cc: Make picture pile base thread safe.
[chromium-blink-merge.git] / content / renderer / render_frame_impl.cc
blob0ca01ad816c2115d2f4f59d147d63c04bac880dc
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/renderer/render_frame_impl.h"
7 #include <map>
8 #include <string>
10 #include "base/auto_reset.h"
11 #include "base/command_line.h"
12 #include "base/debug/alias.h"
13 #include "base/debug/asan_invalid_access.h"
14 #include "base/debug/dump_without_crashing.h"
15 #include "base/i18n/char_iterator.h"
16 #include "base/metrics/histogram.h"
17 #include "base/process/kill.h"
18 #include "base/process/process.h"
19 #include "base/strings/string16.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/time/time.h"
22 #include "content/child/appcache/appcache_dispatcher.h"
23 #include "content/child/plugin_messages.h"
24 #include "content/child/quota_dispatcher.h"
25 #include "content/child/request_extra_data.h"
26 #include "content/child/service_worker/service_worker_network_provider.h"
27 #include "content/child/service_worker/service_worker_provider_context.h"
28 #include "content/child/service_worker/web_service_worker_provider_impl.h"
29 #include "content/child/web_url_loader_impl.h"
30 #include "content/child/web_url_request_util.h"
31 #include "content/child/webmessageportchannel_impl.h"
32 #include "content/child/websocket_bridge.h"
33 #include "content/child/weburlresponse_extradata_impl.h"
34 #include "content/common/clipboard_messages.h"
35 #include "content/common/frame_messages.h"
36 #include "content/common/input_messages.h"
37 #include "content/common/service_worker/service_worker_types.h"
38 #include "content/common/swapped_out_messages.h"
39 #include "content/common/view_messages.h"
40 #include "content/public/common/bindings_policy.h"
41 #include "content/public/common/content_constants.h"
42 #include "content/public/common/content_switches.h"
43 #include "content/public/common/context_menu_params.h"
44 #include "content/public/common/page_state.h"
45 #include "content/public/common/resource_response.h"
46 #include "content/public/common/url_constants.h"
47 #include "content/public/common/url_utils.h"
48 #include "content/public/renderer/browser_plugin_delegate.h"
49 #include "content/public/renderer/content_renderer_client.h"
50 #include "content/public/renderer/context_menu_client.h"
51 #include "content/public/renderer/document_state.h"
52 #include "content/public/renderer/navigation_state.h"
53 #include "content/public/renderer/render_frame_observer.h"
54 #include "content/renderer/accessibility/renderer_accessibility_complete.h"
55 #include "content/renderer/browser_plugin/browser_plugin.h"
56 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
57 #include "content/renderer/child_frame_compositing_helper.h"
58 #include "content/renderer/context_menu_params_builder.h"
59 #include "content/renderer/devtools/devtools_agent.h"
60 #include "content/renderer/dom_automation_controller.h"
61 #include "content/renderer/dom_utils.h"
62 #include "content/renderer/external_popup_menu.h"
63 #include "content/renderer/geolocation_dispatcher.h"
64 #include "content/renderer/history_controller.h"
65 #include "content/renderer/history_serialization.h"
66 #include "content/renderer/image_loading_helper.h"
67 #include "content/renderer/ime_event_guard.h"
68 #include "content/renderer/internal_document_state_data.h"
69 #include "content/renderer/manifest/manifest_manager.h"
70 #include "content/renderer/media/audio_renderer_mixer_manager.h"
71 #include "content/renderer/media/crypto/encrypted_media_player_support_impl.h"
72 #include "content/renderer/media/crypto/render_cdm_factory.h"
73 #include "content/renderer/media/media_stream_dispatcher.h"
74 #include "content/renderer/media/media_stream_renderer_factory.h"
75 #include "content/renderer/media/midi_dispatcher.h"
76 #include "content/renderer/media/render_media_log.h"
77 #include "content/renderer/media/user_media_client_impl.h"
78 #include "content/renderer/media/webcontentdecryptionmodule_impl.h"
79 #include "content/renderer/media/webmediaplayer_ms.h"
80 #include "content/renderer/mojo/service_registry_js_wrapper.h"
81 #include "content/renderer/notification_permission_dispatcher.h"
82 #include "content/renderer/notification_provider.h"
83 #include "content/renderer/npapi/plugin_channel_host.h"
84 #include "content/renderer/push_messaging_dispatcher.h"
85 #include "content/renderer/render_frame_proxy.h"
86 #include "content/renderer/render_process.h"
87 #include "content/renderer/render_thread_impl.h"
88 #include "content/renderer/render_view_impl.h"
89 #include "content/renderer/render_widget_fullscreen_pepper.h"
90 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
91 #include "content/renderer/renderer_webcolorchooser_impl.h"
92 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
93 #include "content/renderer/shared_worker_repository.h"
94 #include "content/renderer/v8_value_converter_impl.h"
95 #include "content/renderer/websharedworker_proxy.h"
96 #include "gin/modules/module_registry.h"
97 #include "media/base/audio_renderer_mixer_input.h"
98 #include "media/base/renderer.h"
99 #include "media/blink/webmediaplayer_impl.h"
100 #include "media/blink/webmediaplayer_params.h"
101 #include "media/filters/gpu_video_accelerator_factories.h"
102 #include "mojo/bindings/js/core.h"
103 #include "mojo/bindings/js/support.h"
104 #include "net/base/data_url.h"
105 #include "net/base/net_errors.h"
106 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
107 #include "net/http/http_util.h"
108 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
109 #include "third_party/WebKit/public/platform/WebString.h"
110 #include "third_party/WebKit/public/platform/WebURL.h"
111 #include "third_party/WebKit/public/platform/WebURLError.h"
112 #include "third_party/WebKit/public/platform/WebURLResponse.h"
113 #include "third_party/WebKit/public/platform/WebVector.h"
114 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
115 #include "third_party/WebKit/public/web/WebDocument.h"
116 #include "third_party/WebKit/public/web/WebGlyphCache.h"
117 #include "third_party/WebKit/public/web/WebLocalFrame.h"
118 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
119 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
120 #include "third_party/WebKit/public/web/WebPlugin.h"
121 #include "third_party/WebKit/public/web/WebPluginParams.h"
122 #include "third_party/WebKit/public/web/WebRange.h"
123 #include "third_party/WebKit/public/web/WebScriptSource.h"
124 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
125 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
126 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
127 #include "third_party/WebKit/public/web/WebSurroundingText.h"
128 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
129 #include "third_party/WebKit/public/web/WebView.h"
131 #if defined(ENABLE_PLUGINS)
132 #include "content/renderer/npapi/webplugin_impl.h"
133 #include "content/renderer/pepper/pepper_browser_connection.h"
134 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
135 #include "content/renderer/pepper/pepper_webplugin_impl.h"
136 #include "content/renderer/pepper/plugin_module.h"
137 #endif
139 #if defined(ENABLE_WEBRTC)
140 #include "content/renderer/media/rtc_peer_connection_handler.h"
141 #endif
143 #if defined(OS_ANDROID)
144 #include <cpu-features.h>
146 #include "content/common/gpu/client/context_provider_command_buffer.h"
147 #include "content/renderer/android/synchronous_compositor_factory.h"
148 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
149 #include "content/renderer/media/android/renderer_media_player_manager.h"
150 #include "content/renderer/media/android/stream_texture_factory_impl.h"
151 #include "content/renderer/media/android/webmediaplayer_android.h"
152 #endif
154 #if defined(ENABLE_PEPPER_CDMS)
155 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
156 #elif defined(ENABLE_BROWSER_CDMS)
157 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
158 #endif
160 using blink::WebContextMenuData;
161 using blink::WebData;
162 using blink::WebDataSource;
163 using blink::WebDocument;
164 using blink::WebElement;
165 using blink::WebExternalPopupMenu;
166 using blink::WebExternalPopupMenuClient;
167 using blink::WebFrame;
168 using blink::WebHistoryItem;
169 using blink::WebHTTPBody;
170 using blink::WebLocalFrame;
171 using blink::WebMediaPlayer;
172 using blink::WebMediaPlayerClient;
173 using blink::WebNavigationPolicy;
174 using blink::WebNavigationType;
175 using blink::WebNode;
176 using blink::WebPluginParams;
177 using blink::WebPopupMenuInfo;
178 using blink::WebRange;
179 using blink::WebReferrerPolicy;
180 using blink::WebScriptSource;
181 using blink::WebSearchableFormData;
182 using blink::WebSecurityOrigin;
183 using blink::WebSecurityPolicy;
184 using blink::WebServiceWorkerProvider;
185 using blink::WebStorageQuotaCallbacks;
186 using blink::WebString;
187 using blink::WebURL;
188 using blink::WebURLError;
189 using blink::WebURLRequest;
190 using blink::WebURLResponse;
191 using blink::WebUserGestureIndicator;
192 using blink::WebVector;
193 using blink::WebView;
194 using base::Time;
195 using base::TimeDelta;
197 namespace content {
199 namespace {
201 const char kDefaultAcceptHeader[] =
202 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
203 "*;q=0.8";
204 const char kAcceptHeader[] = "Accept";
206 const size_t kExtraCharsBeforeAndAfterSelection = 100;
208 typedef std::map<int, RenderFrameImpl*> RoutingIDFrameMap;
209 static base::LazyInstance<RoutingIDFrameMap> g_routing_id_frame_map =
210 LAZY_INSTANCE_INITIALIZER;
212 typedef std::map<blink::WebFrame*, RenderFrameImpl*> FrameMap;
213 base::LazyInstance<FrameMap> g_frame_map = LAZY_INSTANCE_INITIALIZER;
215 int64 ExtractPostId(const WebHistoryItem& item) {
216 if (item.isNull())
217 return -1;
219 if (item.httpBody().isNull())
220 return -1;
222 return item.httpBody().identifier();
225 WebURLResponseExtraDataImpl* GetExtraDataFromResponse(
226 const WebURLResponse& response) {
227 return static_cast<WebURLResponseExtraDataImpl*>(response.extraData());
230 void GetRedirectChain(WebDataSource* ds, std::vector<GURL>* result) {
231 // Replace any occurrences of swappedout:// with about:blank.
232 const WebURL& blank_url = GURL(url::kAboutBlankURL);
233 WebVector<WebURL> urls;
234 ds->redirectChain(urls);
235 result->reserve(urls.size());
236 for (size_t i = 0; i < urls.size(); ++i) {
237 if (urls[i] != GURL(kSwappedOutURL))
238 result->push_back(urls[i]);
239 else
240 result->push_back(blank_url);
244 // Returns the original request url. If there is no redirect, the original
245 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
246 // frame was loaded by loadData, the original url will be ds->unreachableURL()
247 static GURL GetOriginalRequestURL(WebDataSource* ds) {
248 // WebDataSource has unreachable URL means that the frame is loaded through
249 // blink::WebFrame::loadData(), and the base URL will be in the redirect
250 // chain. However, we never visited the baseURL. So in this case, we should
251 // use the unreachable URL as the original URL.
252 if (ds->hasUnreachableURL())
253 return ds->unreachableURL();
255 std::vector<GURL> redirects;
256 GetRedirectChain(ds, &redirects);
257 if (!redirects.empty())
258 return redirects.at(0);
260 return ds->originalRequest().url();
263 NOINLINE static void CrashIntentionally() {
264 // NOTE(shess): Crash directly rather than using NOTREACHED() so
265 // that the signature is easier to triage in crash reports.
266 volatile int* zero = NULL;
267 *zero = 0;
270 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
271 NOINLINE static void MaybeTriggerAsanError(const GURL& url) {
272 // NOTE(rogerm): We intentionally perform an invalid heap access here in
273 // order to trigger an Address Sanitizer (ASAN) error report.
274 const char kCrashDomain[] = "crash";
275 const char kHeapOverflow[] = "/heap-overflow";
276 const char kHeapUnderflow[] = "/heap-underflow";
277 const char kUseAfterFree[] = "/use-after-free";
278 #if defined(SYZYASAN)
279 const char kCorruptHeapBlock[] = "/corrupt-heap-block";
280 const char kCorruptHeap[] = "/corrupt-heap";
281 #endif
283 if (!url.DomainIs(kCrashDomain, sizeof(kCrashDomain) - 1))
284 return;
286 if (!url.has_path())
287 return;
289 std::string crash_type(url.path());
290 if (crash_type == kHeapOverflow) {
291 base::debug::AsanHeapOverflow();
292 } else if (crash_type == kHeapUnderflow ) {
293 base::debug::AsanHeapUnderflow();
294 } else if (crash_type == kUseAfterFree) {
295 base::debug::AsanHeapUseAfterFree();
296 #if defined(SYZYASAN)
297 } else if (crash_type == kCorruptHeapBlock) {
298 base::debug::AsanCorruptHeapBlock();
299 } else if (crash_type == kCorruptHeap) {
300 base::debug::AsanCorruptHeap();
301 #endif
304 #endif // ADDRESS_SANITIZER || SYZYASAN
306 static void MaybeHandleDebugURL(const GURL& url) {
307 if (!url.SchemeIs(kChromeUIScheme))
308 return;
309 if (url == GURL(kChromeUICrashURL)) {
310 CrashIntentionally();
311 } else if (url == GURL(kChromeUIDumpURL)) {
312 // This URL will only correctly create a crash dump file if content is
313 // hosted in a process that has correctly called
314 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
315 // of base::debug::DumpWithoutCrashing for more details.
316 base::debug::DumpWithoutCrashing();
317 } else if (url == GURL(kChromeUIKillURL)) {
318 base::KillProcess(base::GetCurrentProcessHandle(), 1, false);
319 } else if (url == GURL(kChromeUIHangURL)) {
320 for (;;) {
321 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
323 } else if (url == GURL(kChromeUIShorthangURL)) {
324 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
327 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
328 MaybeTriggerAsanError(url);
329 #endif // ADDRESS_SANITIZER || SYZYASAN
332 // Returns false unless this is a top-level navigation.
333 static bool IsTopLevelNavigation(WebFrame* frame) {
334 return frame->parent() == NULL;
337 // Returns false unless this is a top-level navigation that crosses origins.
338 static bool IsNonLocalTopLevelNavigation(const GURL& url,
339 WebFrame* frame,
340 WebNavigationType type,
341 bool is_form_post) {
342 if (!IsTopLevelNavigation(frame))
343 return false;
345 // Navigations initiated within Webkit are not sent out to the external host
346 // in the following cases.
347 // 1. The url scheme is not http/https
348 // 2. The origin of the url and the opener is the same in which case the
349 // opener relationship is maintained.
350 // 3. Reloads/form submits/back forward navigations
351 if (!url.SchemeIs(url::kHttpScheme) && !url.SchemeIs(url::kHttpsScheme))
352 return false;
354 if (type != blink::WebNavigationTypeReload &&
355 type != blink::WebNavigationTypeBackForward && !is_form_post) {
356 // The opener relationship between the new window and the parent allows the
357 // new window to script the parent and vice versa. This is not allowed if
358 // the origins of the two domains are different. This can be treated as a
359 // top level navigation and routed back to the host.
360 blink::WebFrame* opener = frame->opener();
361 if (!opener)
362 return true;
364 if (url.GetOrigin() != GURL(opener->document().url()).GetOrigin())
365 return true;
367 return false;
370 WebURLRequest CreateURLRequestForNavigation(
371 const CommonNavigationParams& common_params,
372 const RequestNavigationParams& request_params,
373 scoped_ptr<StreamOverrideParameters> stream_override,
374 bool is_view_source_mode_enabled) {
375 WebURLRequest request(common_params.url);
376 if (is_view_source_mode_enabled)
377 request.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad);
379 if (common_params.referrer.url.is_valid()) {
380 WebString web_referrer = WebSecurityPolicy::generateReferrerHeader(
381 common_params.referrer.policy,
382 common_params.url,
383 WebString::fromUTF8(common_params.referrer.url.spec()));
384 if (!web_referrer.isEmpty())
385 request.setHTTPReferrer(web_referrer, common_params.referrer.policy);
388 if (!request_params.extra_headers.empty()) {
389 for (net::HttpUtil::HeadersIterator i(request_params.extra_headers.begin(),
390 request_params.extra_headers.end(),
391 "\n");
392 i.GetNext();) {
393 request.addHTTPHeaderField(WebString::fromUTF8(i.name()),
394 WebString::fromUTF8(i.values()));
398 if (request_params.is_post) {
399 request.setHTTPMethod(WebString::fromUTF8("POST"));
401 // Set post data.
402 WebHTTPBody http_body;
403 http_body.initialize();
404 const char* data = NULL;
405 if (request_params.browser_initiated_post_data.size()) {
406 data = reinterpret_cast<const char*>(
407 &request_params.browser_initiated_post_data.front());
409 http_body.appendData(
410 WebData(data, request_params.browser_initiated_post_data.size()));
411 request.setHTTPBody(http_body);
414 RequestExtraData* extra_data = new RequestExtraData();
415 extra_data->set_stream_override(stream_override.Pass());
416 request.setExtraData(extra_data);
417 return request;
420 void UpdateFrameNavigationTiming(WebFrame* frame,
421 base::TimeTicks browser_navigation_start,
422 base::TimeTicks renderer_navigation_start) {
423 // The browser provides the navigation_start time to bootstrap the
424 // Navigation Timing information for the browser-initiated navigations. In
425 // case of cross-process navigations, this carries over the time of
426 // finishing the onbeforeunload handler of the previous page.
427 DCHECK(!browser_navigation_start.is_null());
428 if (frame->provisionalDataSource()) {
429 // |browser_navigation_start| is likely before this process existed, so we
430 // can't use InterProcessTimeTicksConverter. We need at least to ensure
431 // that the browser-side navigation start we set is not later than the one
432 // on the renderer side.
433 base::TimeTicks navigation_start = std::min(
434 browser_navigation_start, renderer_navigation_start);
435 double navigation_start_seconds =
436 (navigation_start - base::TimeTicks()).InSecondsF();
437 frame->provisionalDataSource()->setNavigationStartTime(
438 navigation_start_seconds);
439 // TODO(clamy): We need to provide additional timing values for the
440 // Navigation Timing API to work with browser-side navigations.
444 // PlzNavigate
445 FrameHostMsg_BeginNavigation_Params MakeBeginNavigationParams(
446 const blink::WebURLRequest& request) {
447 FrameHostMsg_BeginNavigation_Params params;
448 params.method = request.httpMethod().latin1();
449 params.headers = GetWebURLRequestHeaders(request);
450 params.load_flags = GetLoadFlagsForWebURLRequest(request);
451 // TODO(clamy): fill the http body.
452 params.has_user_gesture = request.hasUserGesture();
453 return params;
456 // PlzNavigate
457 CommonNavigationParams MakeCommonNavigationParams(
458 const blink::WebURLRequest& request) {
459 const RequestExtraData kEmptyData;
460 const RequestExtraData* extra_data =
461 static_cast<RequestExtraData*>(request.extraData());
462 if (!extra_data)
463 extra_data = &kEmptyData;
464 CommonNavigationParams params;
465 params.url = request.url();
466 params.referrer = Referrer(
467 GURL(request.httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
468 request.referrerPolicy());
469 params.transition = extra_data->transition_type();
470 return params;
473 } // namespace
475 static RenderFrameImpl* (*g_create_render_frame_impl)(RenderViewImpl*, int32) =
476 NULL;
478 // static
479 RenderFrameImpl* RenderFrameImpl::Create(RenderViewImpl* render_view,
480 int32 routing_id) {
481 DCHECK(routing_id != MSG_ROUTING_NONE);
483 if (g_create_render_frame_impl)
484 return g_create_render_frame_impl(render_view, routing_id);
485 else
486 return new RenderFrameImpl(render_view, routing_id);
489 // static
490 RenderFrameImpl* RenderFrameImpl::FromRoutingID(int32 routing_id) {
491 RoutingIDFrameMap::iterator iter =
492 g_routing_id_frame_map.Get().find(routing_id);
493 if (iter != g_routing_id_frame_map.Get().end())
494 return iter->second;
495 return NULL;
498 // static
499 void RenderFrameImpl::CreateFrame(int routing_id, int parent_routing_id) {
500 // TODO(nasko): For now, this message is only sent for subframes, as the
501 // top level frame is created when the RenderView is created through the
502 // ViewMsg_New IPC.
503 CHECK_NE(MSG_ROUTING_NONE, parent_routing_id);
505 RenderFrameProxy* proxy = RenderFrameProxy::FromRoutingID(parent_routing_id);
507 // If the browser is sending a valid parent routing id, it should already be
508 // created and registered.
509 CHECK(proxy);
510 blink::WebRemoteFrame* parent_web_frame = proxy->web_frame();
512 // Create the RenderFrame and WebLocalFrame, linking the two.
513 RenderFrameImpl* render_frame =
514 RenderFrameImpl::Create(proxy->render_view(), routing_id);
515 blink::WebLocalFrame* web_frame =
516 parent_web_frame->createLocalChild("", render_frame);
517 render_frame->SetWebFrame(web_frame);
518 render_frame->Initialize();
521 // static
522 RenderFrame* RenderFrame::FromWebFrame(blink::WebFrame* web_frame) {
523 return RenderFrameImpl::FromWebFrame(web_frame);
526 // static
527 RenderFrameImpl* RenderFrameImpl::FromWebFrame(blink::WebFrame* web_frame) {
528 FrameMap::iterator iter = g_frame_map.Get().find(web_frame);
529 if (iter != g_frame_map.Get().end())
530 return iter->second;
531 return NULL;
534 // static
535 void RenderFrameImpl::InstallCreateHook(
536 RenderFrameImpl* (*create_render_frame_impl)(RenderViewImpl*, int32)) {
537 CHECK(!g_create_render_frame_impl);
538 g_create_render_frame_impl = create_render_frame_impl;
541 // RenderFrameImpl ----------------------------------------------------------
542 RenderFrameImpl::RenderFrameImpl(RenderViewImpl* render_view, int routing_id)
543 : frame_(NULL),
544 render_view_(render_view->AsWeakPtr()),
545 routing_id_(routing_id),
546 is_swapped_out_(false),
547 render_frame_proxy_(NULL),
548 is_detaching_(false),
549 cookie_jar_(this),
550 selection_text_offset_(0),
551 selection_range_(gfx::Range::InvalidRange()),
552 handling_select_range_(false),
553 notification_permission_dispatcher_(NULL),
554 notification_provider_(NULL),
555 web_user_media_client_(NULL),
556 midi_dispatcher_(NULL),
557 #if defined(OS_ANDROID)
558 media_player_manager_(NULL),
559 #endif
560 #if defined(ENABLE_BROWSER_CDMS)
561 cdm_manager_(NULL),
562 #endif
563 #if defined(VIDEO_HOLE)
564 contains_media_player_(false),
565 #endif
566 geolocation_dispatcher_(NULL),
567 push_messaging_dispatcher_(NULL),
568 screen_orientation_dispatcher_(NULL),
569 manifest_manager_(NULL),
570 accessibility_mode_(AccessibilityModeOff),
571 renderer_accessibility_(NULL),
572 weak_factory_(this) {
573 std::pair<RoutingIDFrameMap::iterator, bool> result =
574 g_routing_id_frame_map.Get().insert(std::make_pair(routing_id_, this));
575 CHECK(result.second) << "Inserting a duplicate item.";
577 RenderThread::Get()->AddRoute(routing_id_, this);
579 render_view_->RegisterRenderFrame(this);
581 #if defined(OS_ANDROID)
582 new GinJavaBridgeDispatcher(this);
583 #endif
585 #if defined(ENABLE_NOTIFICATIONS)
586 notification_provider_ = new NotificationProvider(this);
587 #endif
589 manifest_manager_ = new ManifestManager(this);
592 RenderFrameImpl::~RenderFrameImpl() {
593 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, RenderFrameGone());
594 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, OnDestruct());
596 #if defined(VIDEO_HOLE)
597 if (contains_media_player_)
598 render_view_->UnregisterVideoHoleFrame(this);
599 #endif
601 if (render_frame_proxy_)
602 delete render_frame_proxy_;
604 render_view_->UnregisterRenderFrame(this);
605 g_routing_id_frame_map.Get().erase(routing_id_);
606 RenderThread::Get()->RemoveRoute(routing_id_);
609 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame* web_frame) {
610 DCHECK(!frame_);
612 std::pair<FrameMap::iterator, bool> result = g_frame_map.Get().insert(
613 std::make_pair(web_frame, this));
614 CHECK(result.second) << "Inserting a duplicate item.";
616 frame_ = web_frame;
619 void RenderFrameImpl::Initialize() {
620 #if defined(ENABLE_PLUGINS)
621 new PepperBrowserConnection(this);
622 #endif
623 new SharedWorkerRepository(this);
625 if (!frame_->parent())
626 new ImageLoadingHelper(this);
628 // We delay calling this until we have the WebFrame so that any observer or
629 // embedder can call GetWebFrame on any RenderFrame.
630 GetContentClient()->renderer()->RenderFrameCreated(this);
633 RenderWidget* RenderFrameImpl::GetRenderWidget() {
634 return render_view_.get();
637 #if defined(ENABLE_PLUGINS)
638 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost* host) {
639 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
640 DidCreatePepperPlugin(host));
643 void RenderFrameImpl::PepperDidChangeCursor(
644 PepperPluginInstanceImpl* instance,
645 const blink::WebCursorInfo& cursor) {
646 // Update the cursor appearance immediately if the requesting plugin is the
647 // one which receives the last mouse event. Otherwise, the new cursor won't be
648 // picked up until the plugin gets the next input event. That is bad if, e.g.,
649 // the plugin would like to set an invisible cursor when there isn't any user
650 // input for a while.
651 if (instance == render_view_->pepper_last_mouse_event_target())
652 GetRenderWidget()->didChangeCursor(cursor);
655 void RenderFrameImpl::PepperDidReceiveMouseEvent(
656 PepperPluginInstanceImpl* instance) {
657 render_view_->set_pepper_last_mouse_event_target(instance);
660 void RenderFrameImpl::PepperTextInputTypeChanged(
661 PepperPluginInstanceImpl* instance) {
662 if (instance != render_view_->focused_pepper_plugin())
663 return;
665 GetRenderWidget()->UpdateTextInputType();
666 if (renderer_accessibility())
667 renderer_accessibility()->FocusedNodeChanged(WebNode());
670 void RenderFrameImpl::PepperCaretPositionChanged(
671 PepperPluginInstanceImpl* instance) {
672 if (instance != render_view_->focused_pepper_plugin())
673 return;
674 GetRenderWidget()->UpdateSelectionBounds();
677 void RenderFrameImpl::PepperCancelComposition(
678 PepperPluginInstanceImpl* instance) {
679 if (instance != render_view_->focused_pepper_plugin())
680 return;
681 Send(new InputHostMsg_ImeCancelComposition(render_view_->GetRoutingID()));;
682 #if defined(OS_MACOSX) || defined(USE_AURA)
683 GetRenderWidget()->UpdateCompositionInfo(true);
684 #endif
687 void RenderFrameImpl::PepperSelectionChanged(
688 PepperPluginInstanceImpl* instance) {
689 if (instance != render_view_->focused_pepper_plugin())
690 return;
691 SyncSelectionIfRequired();
694 RenderWidgetFullscreenPepper* RenderFrameImpl::CreatePepperFullscreenContainer(
695 PepperPluginInstanceImpl* plugin) {
696 GURL active_url;
697 if (render_view_->webview() && render_view_->webview()->mainFrame())
698 active_url = GURL(render_view_->webview()->mainFrame()->document().url());
699 RenderWidgetFullscreenPepper* widget = RenderWidgetFullscreenPepper::Create(
700 GetRenderWidget()->routing_id(), plugin, active_url,
701 GetRenderWidget()->screenInfo());
702 widget->show(blink::WebNavigationPolicyIgnore);
703 return widget;
706 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
707 if (!render_view_->focused_pepper_plugin())
708 return false;
709 return render_view_->focused_pepper_plugin()->
710 IsPluginAcceptingCompositionEvents();
713 void RenderFrameImpl::PluginCrashed(const base::FilePath& plugin_path,
714 base::ProcessId plugin_pid) {
715 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
716 // routing_id_ as a result.
717 Send(new FrameHostMsg_PluginCrashed(routing_id_, plugin_path, plugin_pid));
720 void RenderFrameImpl::SimulateImeSetComposition(
721 const base::string16& text,
722 const std::vector<blink::WebCompositionUnderline>& underlines,
723 int selection_start,
724 int selection_end) {
725 render_view_->OnImeSetComposition(
726 text, underlines, selection_start, selection_end);
729 void RenderFrameImpl::SimulateImeConfirmComposition(
730 const base::string16& text,
731 const gfx::Range& replacement_range) {
732 render_view_->OnImeConfirmComposition(text, replacement_range, false);
736 void RenderFrameImpl::OnImeSetComposition(
737 const base::string16& text,
738 const std::vector<blink::WebCompositionUnderline>& underlines,
739 int selection_start,
740 int selection_end) {
741 // When a PPAPI plugin has focus, we bypass WebKit.
742 if (!IsPepperAcceptingCompositionEvents()) {
743 pepper_composition_text_ = text;
744 } else {
745 // TODO(kinaba) currently all composition events are sent directly to
746 // plugins. Use DOM event mechanism after WebKit is made aware about
747 // plugins that support composition.
748 // The code below mimics the behavior of WebCore::Editor::setComposition.
750 // Empty -> nonempty: composition started.
751 if (pepper_composition_text_.empty() && !text.empty()) {
752 render_view_->focused_pepper_plugin()->HandleCompositionStart(
753 base::string16());
755 // Nonempty -> empty: composition canceled.
756 if (!pepper_composition_text_.empty() && text.empty()) {
757 render_view_->focused_pepper_plugin()->HandleCompositionEnd(
758 base::string16());
760 pepper_composition_text_ = text;
761 // Nonempty: composition is ongoing.
762 if (!pepper_composition_text_.empty()) {
763 render_view_->focused_pepper_plugin()->HandleCompositionUpdate(
764 pepper_composition_text_, underlines, selection_start,
765 selection_end);
770 void RenderFrameImpl::OnImeConfirmComposition(
771 const base::string16& text,
772 const gfx::Range& replacement_range,
773 bool keep_selection) {
774 // When a PPAPI plugin has focus, we bypass WebKit.
775 // Here, text.empty() has a special meaning. It means to commit the last
776 // update of composition text (see
777 // RenderWidgetHost::ImeConfirmComposition()).
778 const base::string16& last_text = text.empty() ? pepper_composition_text_
779 : text;
781 // last_text is empty only when both text and pepper_composition_text_ is.
782 // Ignore it.
783 if (last_text.empty())
784 return;
786 if (!IsPepperAcceptingCompositionEvents()) {
787 base::i18n::UTF16CharIterator iterator(&last_text);
788 int32 i = 0;
789 while (iterator.Advance()) {
790 blink::WebKeyboardEvent char_event;
791 char_event.type = blink::WebInputEvent::Char;
792 char_event.timeStampSeconds = base::Time::Now().ToDoubleT();
793 char_event.modifiers = 0;
794 char_event.windowsKeyCode = last_text[i];
795 char_event.nativeKeyCode = last_text[i];
797 const int32 char_start = i;
798 for (; i < iterator.array_pos(); ++i) {
799 char_event.text[i - char_start] = last_text[i];
800 char_event.unmodifiedText[i - char_start] = last_text[i];
803 if (GetRenderWidget()->webwidget())
804 GetRenderWidget()->webwidget()->handleInputEvent(char_event);
806 } else {
807 // Mimics the order of events sent by WebKit.
808 // See WebCore::Editor::setComposition() for the corresponding code.
809 render_view_->focused_pepper_plugin()->HandleCompositionEnd(last_text);
810 render_view_->focused_pepper_plugin()->HandleTextInput(last_text);
812 pepper_composition_text_.clear();
815 #endif // ENABLE_PLUGINS
817 MediaStreamDispatcher* RenderFrameImpl::GetMediaStreamDispatcher() {
818 if (!web_user_media_client_)
819 InitializeUserMediaClient();
820 return web_user_media_client_ ?
821 web_user_media_client_->media_stream_dispatcher() : NULL;
824 bool RenderFrameImpl::Send(IPC::Message* message) {
825 if (is_detaching_) {
826 delete message;
827 return false;
829 if (frame_->parent() == NULL &&
830 (is_swapped_out_ || render_view_->is_swapped_out())) {
831 if (!SwappedOutMessages::CanSendWhileSwappedOut(message)) {
832 delete message;
833 return false;
836 // In most cases, send IPCs through the proxy when swapped out. In some
837 // calls the associated RenderViewImpl routing id is used to send
838 // messages, so don't use the proxy.
839 if (render_frame_proxy_ && message->routing_id() == routing_id_)
840 return render_frame_proxy_->Send(message);
843 return RenderThread::Get()->Send(message);
846 #if defined(OS_MACOSX) || defined(OS_ANDROID)
847 void RenderFrameImpl::DidHideExternalPopupMenu() {
848 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
849 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
850 external_popup_menu_.reset();
852 #endif
854 bool RenderFrameImpl::OnMessageReceived(const IPC::Message& msg) {
855 // TODO(kenrb): document() should not be null, but as a transitional step
856 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
857 // to this method. This happens for a top-level remote frame, where a
858 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
859 // around and is still able to receive messages.
860 if (!frame_->document().isNull())
861 GetContentClient()->SetActiveURL(frame_->document().url());
863 ObserverListBase<RenderFrameObserver>::Iterator it(observers_);
864 RenderFrameObserver* observer;
865 while ((observer = it.GetNext()) != NULL) {
866 if (observer->OnMessageReceived(msg))
867 return true;
870 bool handled = true;
871 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl, msg)
872 IPC_MESSAGE_HANDLER(FrameMsg_Navigate, OnNavigate)
873 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload, OnBeforeUnload)
874 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut, OnSwapOut)
875 IPC_MESSAGE_HANDLER(FrameMsg_Stop, OnStop)
876 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed, OnContextMenuClosed)
877 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction,
878 OnCustomContextMenuAction)
879 IPC_MESSAGE_HANDLER(InputMsg_Undo, OnUndo)
880 IPC_MESSAGE_HANDLER(InputMsg_Redo, OnRedo)
881 IPC_MESSAGE_HANDLER(InputMsg_Cut, OnCut)
882 IPC_MESSAGE_HANDLER(InputMsg_Copy, OnCopy)
883 IPC_MESSAGE_HANDLER(InputMsg_Paste, OnPaste)
884 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle, OnPasteAndMatchStyle)
885 IPC_MESSAGE_HANDLER(InputMsg_Delete, OnDelete)
886 IPC_MESSAGE_HANDLER(InputMsg_SelectAll, OnSelectAll)
887 IPC_MESSAGE_HANDLER(InputMsg_SelectRange, OnSelectRange)
888 IPC_MESSAGE_HANDLER(InputMsg_Unselect, OnUnselect)
889 IPC_MESSAGE_HANDLER(InputMsg_Replace, OnReplace)
890 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling, OnReplaceMisspelling)
891 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete,
892 OnExtendSelectionAndDelete)
893 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText,
894 OnSetCompositionFromExistingText)
895 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest, OnCSSInsertRequest)
896 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest,
897 OnJavaScriptExecuteRequest)
898 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests,
899 OnJavaScriptExecuteRequestForTests)
900 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets,
901 OnSetEditableSelectionOffsets)
902 IPC_MESSAGE_HANDLER(FrameMsg_SetupTransitionView, OnSetupTransitionView)
903 IPC_MESSAGE_HANDLER(FrameMsg_BeginExitTransition, OnBeginExitTransition)
904 IPC_MESSAGE_HANDLER(FrameMsg_Reload, OnReload)
905 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest,
906 OnTextSurroundingSelectionRequest)
907 IPC_MESSAGE_HANDLER(FrameMsg_AddStyleSheetByURL,
908 OnAddStyleSheetByURL)
909 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode,
910 OnSetAccessibilityMode)
911 IPC_MESSAGE_HANDLER(FrameMsg_DisownOpener, OnDisownOpener)
912 IPC_MESSAGE_HANDLER(FrameMsg_RequestNavigation, OnRequestNavigation)
913 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation, OnCommitNavigation)
914 #if defined(OS_ANDROID)
915 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems, OnSelectPopupMenuItems)
916 #elif defined(OS_MACOSX)
917 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem, OnSelectPopupMenuItem)
918 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard, OnCopyToFindPboard)
919 #endif
920 IPC_END_MESSAGE_MAP()
922 return handled;
925 void RenderFrameImpl::OnNavigate(const FrameMsg_Navigate_Params& params) {
926 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate",
927 "id", routing_id_,
928 "url", params.common_params.url.possibly_invalid_spec());
929 bool is_reload =
930 RenderViewImpl::IsReload(params.common_params.navigation_type);
931 WebURLRequest::CachePolicy cache_policy =
932 WebURLRequest::UseProtocolCachePolicy;
933 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
934 params.common_params.url, params.common_params.navigation_type,
935 params.commit_params.page_state, true, params.pending_history_list_offset,
936 params.page_id, &is_reload, &cache_policy)) {
937 return;
940 int pending_history_list_offset = params.pending_history_list_offset;
941 int current_history_list_offset = params.current_history_list_offset;
942 int current_history_list_length = params.current_history_list_length;
943 if (params.should_clear_history_list) {
944 CHECK_EQ(pending_history_list_offset, -1);
945 CHECK_EQ(current_history_list_offset, -1);
946 CHECK_EQ(current_history_list_length, 0);
948 render_view_->history_list_offset_ = current_history_list_offset;
949 render_view_->history_list_length_ = current_history_list_length;
950 if (render_view_->history_list_length_ >= 0) {
951 render_view_->history_page_ids_.resize(
952 render_view_->history_list_length_, -1);
954 if (pending_history_list_offset >= 0 &&
955 pending_history_list_offset < render_view_->history_list_length_) {
956 render_view_->history_page_ids_[pending_history_list_offset] =
957 params.page_id;
960 GetContentClient()->SetActiveURL(params.common_params.url);
962 WebFrame* frame = frame_;
963 if (!params.frame_to_navigate.empty()) {
964 // TODO(nasko): Move this lookup to the browser process.
965 frame = render_view_->webview()->findFrameByName(
966 WebString::fromUTF8(params.frame_to_navigate));
967 CHECK(frame) << "Invalid frame name passed: " << params.frame_to_navigate;
970 if (is_reload && !render_view_->history_controller()->GetCurrentEntry()) {
971 // We cannot reload if we do not have any history state. This happens, for
972 // example, when recovering from a crash.
973 is_reload = false;
974 cache_policy = WebURLRequest::ReloadIgnoringCacheData;
977 render_view_->pending_navigation_params_.reset(
978 new FrameMsg_Navigate_Params(params));
980 // If we are reloading, then WebKit will use the history state of the current
981 // page, so we should just ignore any given history state. Otherwise, if we
982 // have history state, then we need to navigate to it, which corresponds to a
983 // back/forward navigation event.
984 if (is_reload) {
985 bool reload_original_url =
986 (params.common_params.navigation_type ==
987 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
988 bool ignore_cache = (params.common_params.navigation_type ==
989 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE);
991 if (reload_original_url)
992 frame->reloadWithOverrideURL(params.common_params.url, true);
993 else
994 frame->reload(ignore_cache);
995 } else if (params.commit_params.page_state.IsValid()) {
996 // We must know the page ID of the page we are navigating back to.
997 DCHECK_NE(params.page_id, -1);
998 scoped_ptr<HistoryEntry> entry =
999 PageStateToHistoryEntry(params.commit_params.page_state);
1000 if (entry) {
1001 // Ensure we didn't save the swapped out URL in UpdateState, since the
1002 // browser should never be telling us to navigate to swappedout://.
1003 CHECK(entry->root().urlString() != WebString::fromUTF8(kSwappedOutURL));
1004 render_view_->history_controller()->GoToEntry(entry.Pass(), cache_policy);
1006 } else if (!params.base_url_for_data_url.is_empty()) {
1007 // A loadData request with a specified base URL.
1008 std::string mime_type, charset, data;
1009 if (net::DataURL::Parse(
1010 params.common_params.url, &mime_type, &charset, &data)) {
1011 frame->loadData(
1012 WebData(data.c_str(), data.length()),
1013 WebString::fromUTF8(mime_type),
1014 WebString::fromUTF8(charset),
1015 params.base_url_for_data_url,
1016 params.history_url_for_data_url,
1017 false);
1018 } else {
1019 CHECK(false) << "Invalid URL passed: "
1020 << params.common_params.url.possibly_invalid_spec();
1022 } else {
1023 // Navigate to the given URL.
1024 WebURLRequest request =
1025 CreateURLRequestForNavigation(params.common_params,
1026 params.request_params,
1027 scoped_ptr<StreamOverrideParameters>(),
1028 frame->isViewSourceModeEnabled());
1030 // A session history navigation should have been accompanied by state.
1031 CHECK_EQ(params.page_id, -1);
1033 // Record this before starting the load, we need a lower bound of this time
1034 // to sanitize the navigationStart override set below.
1035 base::TimeTicks renderer_navigation_start = base::TimeTicks::Now();
1036 frame->loadRequest(request);
1038 UpdateFrameNavigationTiming(
1039 frame, params.commit_params.browser_navigation_start,
1040 renderer_navigation_start);
1043 // In case LoadRequest failed before DidCreateDataSource was called.
1044 render_view_->pending_navigation_params_.reset();
1047 void RenderFrameImpl::BindServiceRegistry(
1048 mojo::ScopedMessagePipeHandle service_provider_handle) {
1049 service_registry_.BindRemoteServiceProvider(service_provider_handle.Pass());
1052 ManifestManager* RenderFrameImpl::manifest_manager() {
1053 return manifest_manager_;
1056 void RenderFrameImpl::OnBeforeUnload() {
1057 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1058 "id", routing_id_);
1059 // TODO(creis): Right now, this is only called on the main frame. Make the
1060 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1061 // it.
1062 CHECK(!frame_->parent());
1064 base::TimeTicks before_unload_start_time = base::TimeTicks::Now();
1065 bool proceed = frame_->dispatchBeforeUnloadEvent();
1066 base::TimeTicks before_unload_end_time = base::TimeTicks::Now();
1067 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_, proceed,
1068 before_unload_start_time,
1069 before_unload_end_time));
1072 void RenderFrameImpl::OnSwapOut(int proxy_routing_id) {
1073 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_);
1074 RenderFrameProxy* proxy = NULL;
1075 bool is_site_per_process =
1076 CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess);
1077 bool is_main_frame = !frame_->parent();
1079 // Only run unload if we're not swapped out yet, but send the ack either way.
1080 if (!is_swapped_out_ || !render_view_->is_swapped_out_) {
1081 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1082 // a different process. This involves running the unload handler and
1083 // clearing the page. We also allow this process to exit if there are no
1084 // other active RenderFrames in it.
1086 // Send an UpdateState message before we get swapped out.
1087 render_view_->SyncNavigationState();
1089 // If we need a proxy to replace this, create it now so its routing id is
1090 // registered for receiving IPC messages.
1091 if (proxy_routing_id != MSG_ROUTING_NONE) {
1092 proxy = RenderFrameProxy::CreateProxyToReplaceFrame(this,
1093 proxy_routing_id);
1096 // Synchronously run the unload handler before sending the ACK.
1097 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1098 // unload on subframes as well.
1099 if (is_main_frame)
1100 frame_->dispatchUnloadEvent();
1102 // Swap out and stop sending any IPC messages that are not ACKs.
1103 // TODO(nasko): Do we need RenderFrameImpl::is_swapped_out_ anymore?
1104 if (is_main_frame)
1105 render_view_->SetSwappedOut(true);
1106 is_swapped_out_ = true;
1108 // Now that we're swapped out and filtering IPC messages, stop loading to
1109 // ensure that no other in-progress navigation continues. We do this here
1110 // to avoid sending a DidStopLoading message to the browser process.
1111 // TODO(creis): Should we be stopping all frames here and using
1112 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1113 // frame?
1114 OnStop();
1116 // Transfer settings such as initial drawing parameters to the remote frame,
1117 // if one is created, that will replace this frame.
1118 if (!is_main_frame && proxy)
1119 proxy->web_frame()->initializeFromFrame(frame_);
1121 // Replace the page with a blank dummy URL. The unload handler will not be
1122 // run a second time, thanks to a check in FrameLoader::stopLoading.
1123 // TODO(creis): Need to add a better way to do this that avoids running the
1124 // beforeunload handler. For now, we just run it a second time silently.
1125 if (!is_site_per_process || is_main_frame)
1126 render_view_->NavigateToSwappedOutURL(frame_);
1128 // Let WebKit know that this view is hidden so it can drop resources and
1129 // stop compositing.
1130 // TODO(creis): Support this for subframes as well.
1131 if (is_main_frame) {
1132 render_view_->webview()->setVisibilityState(
1133 blink::WebPageVisibilityStateHidden, false);
1137 // It is now safe to show modal dialogs again.
1138 // TODO(creis): Deal with modal dialogs from subframes.
1139 if (is_main_frame)
1140 render_view_->suppress_dialogs_until_swap_out_ = false;
1142 Send(new FrameHostMsg_SwapOut_ACK(routing_id_));
1144 // Now that all of the cleanup is complete and the browser side is notified,
1145 // start using the RenderFrameProxy, if one is created.
1146 if (proxy) {
1147 if (!is_main_frame) {
1148 frame_->swap(proxy->web_frame());
1149 if (is_site_per_process) {
1150 // TODO(nasko): delete the frame here, since we've replaced it with a
1151 // proxy.
1153 } else {
1154 set_render_frame_proxy(proxy);
1158 // Safe to exit if no one else is using the process.
1159 if (is_main_frame)
1160 render_view_->WasSwappedOut();
1163 void RenderFrameImpl::OnContextMenuClosed(
1164 const CustomContextMenuContext& custom_context) {
1165 if (custom_context.request_id) {
1166 // External request, should be in our map.
1167 ContextMenuClient* client =
1168 pending_context_menus_.Lookup(custom_context.request_id);
1169 if (client) {
1170 client->OnMenuClosed(custom_context.request_id);
1171 pending_context_menus_.Remove(custom_context.request_id);
1173 } else {
1174 if (custom_context.link_followed.is_valid()) {
1175 frame_->sendPings(
1176 DomUtils::ExtractParentAnchorNode(context_menu_node_),
1177 custom_context.link_followed);
1179 // Internal request, forward to WebKit.
1180 context_menu_node_.reset();
1184 void RenderFrameImpl::OnCustomContextMenuAction(
1185 const CustomContextMenuContext& custom_context,
1186 unsigned action) {
1187 if (custom_context.request_id) {
1188 // External context menu request, look in our map.
1189 ContextMenuClient* client =
1190 pending_context_menus_.Lookup(custom_context.request_id);
1191 if (client)
1192 client->OnMenuAction(custom_context.request_id, action);
1193 } else {
1194 // Internal request, forward to WebKit.
1195 render_view_->webview()->performCustomContextMenuAction(action);
1199 void RenderFrameImpl::OnUndo() {
1200 frame_->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1203 void RenderFrameImpl::OnRedo() {
1204 frame_->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1207 void RenderFrameImpl::OnCut() {
1208 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1209 frame_->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1212 void RenderFrameImpl::OnCopy() {
1213 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1214 WebNode current_node = context_menu_node_.isNull() ?
1215 GetFocusedElement() : context_menu_node_;
1216 frame_->executeCommand(WebString::fromUTF8("Copy"), current_node);
1219 void RenderFrameImpl::OnPaste() {
1220 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1221 frame_->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1224 void RenderFrameImpl::OnPasteAndMatchStyle() {
1225 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1226 frame_->executeCommand(
1227 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1230 #if defined(OS_MACOSX)
1231 void RenderFrameImpl::OnCopyToFindPboard() {
1232 // Since the find pasteboard supports only plain text, this can be simpler
1233 // than the |OnCopy()| case.
1234 if (frame_->hasSelection()) {
1235 base::string16 selection = frame_->selectionAsText();
1236 RenderThread::Get()->Send(
1237 new ClipboardHostMsg_FindPboardWriteStringAsync(selection));
1240 #endif
1242 void RenderFrameImpl::OnDelete() {
1243 frame_->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1246 void RenderFrameImpl::OnSelectAll() {
1247 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1248 frame_->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1251 void RenderFrameImpl::OnSelectRange(const gfx::Point& start,
1252 const gfx::Point& end) {
1253 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1254 Send(new ViewHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1256 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1257 frame_->selectRange(start, end);
1260 void RenderFrameImpl::OnUnselect() {
1261 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1262 frame_->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1265 void RenderFrameImpl::OnReplace(const base::string16& text) {
1266 if (!frame_->hasSelection())
1267 frame_->selectWordAroundCaret();
1269 frame_->replaceSelection(text);
1272 void RenderFrameImpl::OnReplaceMisspelling(const base::string16& text) {
1273 if (!frame_->hasSelection())
1274 return;
1276 frame_->replaceMisspelledRange(text);
1279 void RenderFrameImpl::OnCSSInsertRequest(const std::string& css) {
1280 frame_->document().insertStyleSheet(WebString::fromUTF8(css));
1283 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1284 const base::string16& jscript,
1285 int id,
1286 bool notify_result) {
1287 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1288 TRACE_EVENT_SCOPE_THREAD);
1290 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
1291 v8::Handle<v8::Value> result =
1292 frame_->executeScriptAndReturnValue(WebScriptSource(jscript));
1294 HandleJavascriptExecutionResult(jscript, id, notify_result, result);
1297 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1298 const base::string16& jscript,
1299 int id,
1300 bool notify_result) {
1301 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1302 TRACE_EVENT_SCOPE_THREAD);
1304 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
1305 v8::Handle<v8::Value> result =
1306 frame_->executeScriptAndReturnValueForTests(WebScriptSource(jscript));
1308 HandleJavascriptExecutionResult(jscript, id, notify_result, result);
1311 void RenderFrameImpl::HandleJavascriptExecutionResult(
1312 const base::string16& jscript,
1313 int id,
1314 bool notify_result,
1315 v8::Handle<v8::Value> result) {
1316 if (notify_result) {
1317 base::ListValue list;
1318 if (!result.IsEmpty()) {
1319 v8::Local<v8::Context> context = frame_->mainWorldScriptContext();
1320 v8::Context::Scope context_scope(context);
1321 V8ValueConverterImpl converter;
1322 converter.SetDateAllowed(true);
1323 converter.SetRegExpAllowed(true);
1324 base::Value* result_value = converter.FromV8Value(result, context);
1325 list.Set(0, result_value ? result_value : base::Value::CreateNullValue());
1326 } else {
1327 list.Set(0, base::Value::CreateNullValue());
1329 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_, id, list));
1333 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start, int end) {
1334 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1335 if (!GetRenderWidget()->ShouldHandleImeEvent())
1336 return;
1337 ImeEventGuard guard(GetRenderWidget());
1338 frame_->setEditableSelectionOffsets(start, end);
1341 void RenderFrameImpl::OnSetCompositionFromExistingText(
1342 int start, int end,
1343 const std::vector<blink::WebCompositionUnderline>& underlines) {
1344 if (!GetRenderWidget()->ShouldHandleImeEvent())
1345 return;
1346 ImeEventGuard guard(GetRenderWidget());
1347 frame_->setCompositionFromExistingText(start, end, underlines);
1350 void RenderFrameImpl::OnExtendSelectionAndDelete(int before, int after) {
1351 if (!GetRenderWidget()->ShouldHandleImeEvent())
1352 return;
1353 ImeEventGuard guard(GetRenderWidget());
1354 frame_->extendSelectionAndDelete(before, after);
1357 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode) {
1358 if (accessibility_mode_ == new_mode)
1359 return;
1360 accessibility_mode_ = new_mode;
1361 if (renderer_accessibility_) {
1362 // Note: this isn't called automatically by the destructor because
1363 // there'd be no point in calling it in frame teardown, only if there's
1364 // an accessibility mode change but the frame is persisting.
1365 renderer_accessibility_->DisableAccessibility();
1367 delete renderer_accessibility_;
1368 renderer_accessibility_ = NULL;
1370 if (accessibility_mode_ == AccessibilityModeOff)
1371 return;
1373 if (accessibility_mode_ & AccessibilityModeFlagFullTree)
1374 renderer_accessibility_ = new RendererAccessibilityComplete(this);
1377 void RenderFrameImpl::OnDisownOpener() {
1378 // TODO(creis): We should only see this for main frames for now. To support
1379 // disowning the opener on subframes, we will need to move WebContentsImpl's
1380 // opener_ to FrameTreeNode.
1381 CHECK(!frame_->parent());
1383 if (frame_->opener())
1384 frame_->setOpener(NULL);
1387 #if defined(OS_ANDROID)
1388 void RenderFrameImpl::OnSelectPopupMenuItems(
1389 bool canceled,
1390 const std::vector<int>& selected_indices) {
1391 // It is possible to receive more than one of these calls if the user presses
1392 // a select faster than it takes for the show-select-popup IPC message to make
1393 // it to the browser UI thread. Ignore the extra-messages.
1394 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1395 if (!external_popup_menu_)
1396 return;
1398 external_popup_menu_->DidSelectItems(canceled, selected_indices);
1399 external_popup_menu_.reset();
1401 #endif
1403 #if defined(OS_MACOSX)
1404 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index) {
1405 if (external_popup_menu_ == NULL)
1406 return;
1407 external_popup_menu_->DidSelectItem(selected_index);
1408 external_popup_menu_.reset();
1410 #endif
1412 void RenderFrameImpl::OnReload(bool ignore_cache) {
1413 frame_->reload(ignore_cache);
1416 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length) {
1417 blink::WebSurroundingText surroundingText;
1418 surroundingText.initialize(frame_->selectionRange(), max_length);
1420 if (surroundingText.isNull()) {
1421 // |surroundingText| might not be correctly initialized, for example if
1422 // |frame_->selectionRange().isNull()|, in other words, if there was no
1423 // selection.
1424 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1425 routing_id_, base::string16(), 0, 0));
1426 return;
1429 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1430 routing_id_,
1431 surroundingText.textContent(),
1432 surroundingText.startOffsetInTextContent(),
1433 surroundingText.endOffsetInTextContent()));
1436 void RenderFrameImpl::OnAddStyleSheetByURL(const std::string& url) {
1437 frame_->addStyleSheetByURL(WebString::fromUTF8(url));
1440 void RenderFrameImpl::OnSetupTransitionView(const std::string& markup) {
1441 frame_->document().setIsTransitionDocument();
1442 frame_->navigateToSandboxedMarkup(WebData(markup.data(), markup.length()));
1445 void RenderFrameImpl::OnBeginExitTransition(const std::string& css_selector) {
1446 frame_->document().setIsTransitionDocument();
1447 frame_->document().beginExitTransition(WebString::fromUTF8(css_selector));
1450 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type,
1451 const base::string16& message,
1452 const base::string16& default_value,
1453 const GURL& frame_url,
1454 base::string16* result) {
1455 // Don't allow further dialogs if we are waiting to swap out, since the
1456 // PageGroupLoadDeferrer in our stack prevents it.
1457 if (render_view()->suppress_dialogs_until_swap_out_)
1458 return false;
1460 bool success = false;
1461 base::string16 result_temp;
1462 if (!result)
1463 result = &result_temp;
1465 render_view()->SendAndRunNestedMessageLoop(
1466 new FrameHostMsg_RunJavaScriptMessage(
1467 routing_id_, message, default_value, frame_url, type, &success,
1468 result));
1469 return success;
1472 void RenderFrameImpl::LoadNavigationErrorPage(
1473 const WebURLRequest& failed_request,
1474 const WebURLError& error,
1475 bool replace) {
1476 std::string error_html;
1477 GetContentClient()->renderer()->GetNavigationErrorStrings(
1478 render_view(), frame_, failed_request, error, &error_html, NULL);
1480 frame_->loadHTMLString(error_html,
1481 GURL(kUnreachableWebDataURL),
1482 error.unreachableURL,
1483 replace);
1486 void RenderFrameImpl::DidCommitCompositorFrame() {
1487 FOR_EACH_OBSERVER(
1488 RenderFrameObserver, observers_, DidCommitCompositorFrame());
1491 RenderView* RenderFrameImpl::GetRenderView() {
1492 return render_view_.get();
1495 int RenderFrameImpl::GetRoutingID() {
1496 return routing_id_;
1499 blink::WebLocalFrame* RenderFrameImpl::GetWebFrame() {
1500 DCHECK(frame_);
1501 return frame_;
1504 WebPreferences& RenderFrameImpl::GetWebkitPreferences() {
1505 return render_view_->GetWebkitPreferences();
1508 int RenderFrameImpl::ShowContextMenu(ContextMenuClient* client,
1509 const ContextMenuParams& params) {
1510 DCHECK(client); // A null client means "internal" when we issue callbacks.
1511 ContextMenuParams our_params(params);
1512 our_params.custom_context.request_id = pending_context_menus_.Add(client);
1513 Send(new FrameHostMsg_ContextMenu(routing_id_, our_params));
1514 return our_params.custom_context.request_id;
1517 void RenderFrameImpl::CancelContextMenu(int request_id) {
1518 DCHECK(pending_context_menus_.Lookup(request_id));
1519 pending_context_menus_.Remove(request_id);
1522 blink::WebNode RenderFrameImpl::GetContextMenuNode() const {
1523 return context_menu_node_;
1526 blink::WebPlugin* RenderFrameImpl::CreatePlugin(
1527 blink::WebFrame* frame,
1528 const WebPluginInfo& info,
1529 const blink::WebPluginParams& params) {
1530 DCHECK_EQ(frame_, frame);
1531 #if defined(ENABLE_PLUGINS)
1532 bool pepper_plugin_was_registered = false;
1533 scoped_refptr<PluginModule> pepper_module(PluginModule::Create(
1534 this, info, &pepper_plugin_was_registered));
1535 if (pepper_plugin_was_registered) {
1536 if (pepper_module.get()) {
1537 return new PepperWebPluginImpl(pepper_module.get(), params, this);
1540 #if defined(OS_CHROMEOS)
1541 LOG(WARNING) << "Pepper module/plugin creation failed.";
1542 return NULL;
1543 #else
1544 // TODO(jam): change to take RenderFrame.
1545 return new WebPluginImpl(frame, params, info.path, render_view_, this);
1546 #endif
1547 #else
1548 return NULL;
1549 #endif
1552 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame* frame,
1553 const blink::WebURLRequest& request,
1554 blink::WebNavigationPolicy policy) {
1555 DCHECK(!frame_ || frame_ == frame);
1556 loadURLExternally(frame, request, policy, WebString());
1559 void RenderFrameImpl::ExecuteJavaScript(const base::string16& javascript) {
1560 OnJavaScriptExecuteRequest(javascript, 0, false);
1563 ServiceRegistry* RenderFrameImpl::GetServiceRegistry() {
1564 return &service_registry_;
1567 bool RenderFrameImpl::IsFTPDirectoryListing() {
1568 WebURLResponseExtraDataImpl* extra_data =
1569 GetExtraDataFromResponse(frame_->dataSource()->response());
1570 return extra_data ? extra_data->is_ftp_directory_listing() : false;
1573 void RenderFrameImpl::AttachGuest(int element_instance_id) {
1574 render_view_->GetBrowserPluginManager()->Attach(element_instance_id);
1577 void RenderFrameImpl::SetSelectedText(const base::string16& selection_text,
1578 size_t offset,
1579 const gfx::Range& range) {
1580 // Use the routing id of Render Widget Host.
1581 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1582 selection_text,
1583 offset,
1584 range));
1587 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1588 v8::Isolate* isolate,
1589 v8::Handle<v8::Context> context) {
1590 gin::ModuleRegistry* registry = gin::ModuleRegistry::From(context);
1591 if (registry->available_modules().count(mojo::js::Core::kModuleName))
1592 return;
1594 v8::HandleScope handle_scope(isolate);
1595 registry->AddBuiltinModule(
1596 isolate, mojo::js::Core::kModuleName, mojo::js::Core::GetModule(isolate));
1597 registry->AddBuiltinModule(isolate,
1598 mojo::js::Support::kModuleName,
1599 mojo::js::Support::GetModule(isolate));
1600 registry->AddBuiltinModule(
1601 isolate,
1602 ServiceRegistryJsWrapper::kModuleName,
1603 ServiceRegistryJsWrapper::Create(isolate, &service_registry_).ToV8());
1606 // blink::WebFrameClient implementation ----------------------------------------
1608 blink::WebPlugin* RenderFrameImpl::createPlugin(
1609 blink::WebLocalFrame* frame,
1610 const blink::WebPluginParams& params) {
1611 DCHECK_EQ(frame_, frame);
1612 blink::WebPlugin* plugin = NULL;
1613 if (GetContentClient()->renderer()->OverrideCreatePlugin(
1614 this, frame, params, &plugin)) {
1615 return plugin;
1618 if (base::UTF16ToUTF8(params.mimeType) == kBrowserPluginMimeType) {
1619 scoped_ptr<BrowserPluginDelegate> browser_plugin_delegate(
1620 GetContentClient()->renderer()->CreateBrowserPluginDelegate(
1621 this, std::string()));
1622 return render_view_->GetBrowserPluginManager()->CreateBrowserPlugin(
1623 render_view_.get(), frame, browser_plugin_delegate.Pass());
1626 #if defined(ENABLE_PLUGINS)
1627 WebPluginInfo info;
1628 std::string mime_type;
1629 bool found = false;
1630 Send(new FrameHostMsg_GetPluginInfo(
1631 routing_id_, params.url, frame->top()->document().url(),
1632 params.mimeType.utf8(), &found, &info, &mime_type));
1633 if (!found)
1634 return NULL;
1636 if (info.type == content::WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN) {
1637 scoped_ptr<BrowserPluginDelegate> browser_plugin_delegate(
1638 GetContentClient()->renderer()->CreateBrowserPluginDelegate(
1639 this, base::UTF16ToUTF8(params.mimeType)));
1640 return render_view_->GetBrowserPluginManager()->CreateBrowserPlugin(
1641 render_view_.get(), frame, browser_plugin_delegate.Pass());
1645 WebPluginParams params_to_use = params;
1646 params_to_use.mimeType = WebString::fromUTF8(mime_type);
1647 return CreatePlugin(frame, info, params_to_use);
1648 #else
1649 return NULL;
1650 #endif // defined(ENABLE_PLUGINS)
1653 blink::WebMediaPlayer* RenderFrameImpl::createMediaPlayer(
1654 blink::WebLocalFrame* frame,
1655 const blink::WebURL& url,
1656 blink::WebMediaPlayerClient* client) {
1657 return createMediaPlayer(frame, url, client, NULL);
1660 blink::WebMediaPlayer* RenderFrameImpl::createMediaPlayer(
1661 blink::WebLocalFrame* frame,
1662 const blink::WebURL& url,
1663 blink::WebMediaPlayerClient* client,
1664 blink::WebContentDecryptionModule* initial_cdm) {
1665 #if defined(VIDEO_HOLE)
1666 if (!contains_media_player_) {
1667 render_view_->RegisterVideoHoleFrame(this);
1668 contains_media_player_ = true;
1670 #endif // defined(VIDEO_HOLE)
1672 blink::WebMediaStream web_stream(
1673 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url));
1674 if (!web_stream.isNull())
1675 return CreateWebMediaPlayerForMediaStream(url, client);
1677 #if defined(OS_ANDROID)
1678 return CreateAndroidWebMediaPlayer(url, client, initial_cdm);
1679 #else
1680 RenderThreadImpl* render_thread = RenderThreadImpl::current();
1681 media::WebMediaPlayerParams params(
1682 base::Bind(&ContentRendererClient::DeferMediaLoad,
1683 base::Unretained(GetContentClient()->renderer()),
1684 static_cast<RenderFrame*>(this)),
1685 render_thread->GetAudioRendererMixerManager()->CreateInput(
1686 render_view_->routing_id_, routing_id_),
1687 *render_thread->GetAudioHardwareConfig(),
1688 new RenderMediaLog(),
1689 render_thread->GetGpuFactories(),
1690 render_thread->GetMediaThreadTaskRunner(),
1691 render_thread->compositor_message_loop_proxy(),
1692 base::Bind(&EncryptedMediaPlayerSupportImpl::Create),
1693 initial_cdm);
1694 return new media::WebMediaPlayerImpl(
1695 frame, client, weak_factory_.GetWeakPtr(), nullptr, params);
1696 #endif // defined(OS_ANDROID)
1699 blink::WebContentDecryptionModule*
1700 RenderFrameImpl::createContentDecryptionModule(
1701 blink::WebLocalFrame* frame,
1702 const blink::WebSecurityOrigin& security_origin,
1703 const blink::WebString& key_system) {
1704 DCHECK(!frame_ || frame_ == frame);
1706 #if defined(ENABLE_PEPPER_CDMS)
1707 RenderCdmFactory cdm_factory(
1708 base::Bind(&PepperCdmWrapperImpl::Create, frame));
1709 #elif defined(ENABLE_BROWSER_CDMS)
1710 RenderCdmFactory cdm_factory(GetCdmManager());
1711 #else
1712 RenderCdmFactory cdm_factory;
1713 #endif
1715 return WebContentDecryptionModuleImpl::Create(&cdm_factory, security_origin,
1716 key_system);
1719 blink::WebApplicationCacheHost* RenderFrameImpl::createApplicationCacheHost(
1720 blink::WebLocalFrame* frame,
1721 blink::WebApplicationCacheHostClient* client) {
1722 if (!frame || !frame->view())
1723 return NULL;
1724 DCHECK(!frame_ || frame_ == frame);
1725 return new RendererWebApplicationCacheHostImpl(
1726 RenderViewImpl::FromWebView(frame->view()), client,
1727 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
1730 blink::WebWorkerPermissionClientProxy*
1731 RenderFrameImpl::createWorkerPermissionClientProxy(
1732 blink::WebLocalFrame* frame) {
1733 if (!frame || !frame->view())
1734 return NULL;
1735 DCHECK(!frame_ || frame_ == frame);
1736 return GetContentClient()->renderer()->CreateWorkerPermissionClientProxy(
1737 this, frame);
1740 WebExternalPopupMenu* RenderFrameImpl::createExternalPopupMenu(
1741 const WebPopupMenuInfo& popup_menu_info,
1742 WebExternalPopupMenuClient* popup_menu_client) {
1743 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1744 // An IPC message is sent to the browser to build and display the actual
1745 // popup. The user could have time to click a different select by the time
1746 // the popup is shown. In that case external_popup_menu_ is non NULL.
1747 // By returning NULL in that case, we instruct Blink to cancel that new
1748 // popup. So from the user perspective, only the first one will show, and
1749 // will have to close the first one before another one can be shown.
1750 if (external_popup_menu_)
1751 return NULL;
1752 external_popup_menu_.reset(
1753 new ExternalPopupMenu(this, popup_menu_info, popup_menu_client));
1754 if (render_view_->screen_metrics_emulator_) {
1755 render_view_->SetExternalPopupOriginAdjustmentsForEmulation(
1756 external_popup_menu_.get(),
1757 render_view_->screen_metrics_emulator_.get());
1759 return external_popup_menu_.get();
1760 #else
1761 return NULL;
1762 #endif
1765 blink::WebCookieJar* RenderFrameImpl::cookieJar(blink::WebLocalFrame* frame) {
1766 DCHECK(!frame_ || frame_ == frame);
1767 return &cookie_jar_;
1770 blink::WebServiceWorkerProvider* RenderFrameImpl::createServiceWorkerProvider(
1771 blink::WebLocalFrame* frame) {
1772 DCHECK(!frame_ || frame_ == frame);
1773 // At this point we should have non-null data source.
1774 DCHECK(frame->dataSource());
1775 if (!ChildThread::current())
1776 return NULL; // May be null in some tests.
1777 ServiceWorkerNetworkProvider* provider =
1778 ServiceWorkerNetworkProvider::FromDocumentState(
1779 DocumentState::FromDataSource(frame->dataSource()));
1780 return new WebServiceWorkerProviderImpl(
1781 ChildThread::current()->thread_safe_sender(),
1782 provider ? provider->context() : NULL);
1785 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame* frame) {
1786 DCHECK(!frame_ || frame_ == frame);
1787 // Notify the browser process that it is no longer safe to show the pending
1788 // URL of the main frame, since a URL spoof is now possible.
1789 if (!frame->parent() && render_view_->page_id_ == -1)
1790 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_));
1793 blink::WebFrame* RenderFrameImpl::createChildFrame(
1794 blink::WebLocalFrame* parent,
1795 const blink::WebString& name) {
1796 // Synchronously notify the browser of a child frame creation to get the
1797 // routing_id for the RenderFrame.
1798 int child_routing_id = MSG_ROUTING_NONE;
1799 Send(new FrameHostMsg_CreateChildFrame(routing_id_,
1800 base::UTF16ToUTF8(name),
1801 &child_routing_id));
1802 // Allocation of routing id failed, so we can't create a child frame. This can
1803 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
1804 // out state.
1805 if (child_routing_id == MSG_ROUTING_NONE) {
1806 #if !defined(OS_LINUX)
1807 // DumpWithoutCrashing() crashes on Linux in renderer processes when
1808 // breakpad and sandboxing are enabled: crbug.com/349600
1809 base::debug::Alias(parent);
1810 base::debug::Alias(&routing_id_);
1811 bool render_view_is_swapped_out = GetRenderWidget()->is_swapped_out();
1812 base::debug::Alias(&render_view_is_swapped_out);
1813 bool render_view_is_closing = GetRenderWidget()->closing();
1814 base::debug::Alias(&render_view_is_closing);
1815 base::debug::Alias(&is_swapped_out_);
1816 base::debug::DumpWithoutCrashing();
1817 #endif
1818 return NULL;
1821 // Create the RenderFrame and WebLocalFrame, linking the two.
1822 RenderFrameImpl* child_render_frame = RenderFrameImpl::Create(
1823 render_view_.get(), child_routing_id);
1824 blink::WebLocalFrame* web_frame = WebLocalFrame::create(child_render_frame);
1825 child_render_frame->SetWebFrame(web_frame);
1827 // Add the frame to the frame tree and initialize it.
1828 parent->appendChild(web_frame);
1829 child_render_frame->Initialize();
1831 return web_frame;
1834 void RenderFrameImpl::didDisownOpener(blink::WebLocalFrame* frame) {
1835 DCHECK(!frame_ || frame_ == frame);
1836 // We only need to notify the browser if the active, top-level frame clears
1837 // its opener. We can ignore cases where a swapped out frame clears its
1838 // opener after hearing about it from the browser, and the browser does not
1839 // (yet) care about subframe openers.
1840 if (render_view_->is_swapped_out_ || frame->parent())
1841 return;
1843 // Notify WebContents and all its swapped out RenderViews.
1844 Send(new FrameHostMsg_DidDisownOpener(routing_id_));
1847 void RenderFrameImpl::frameDetached(blink::WebFrame* frame) {
1848 // NOTE: This function is called on the frame that is being detached and not
1849 // the parent frame. This is different from createChildFrame() which is
1850 // called on the parent frame.
1851 CHECK(!is_detaching_);
1852 DCHECK(!frame_ || frame_ == frame);
1854 bool is_subframe = !!frame->parent();
1856 Send(new FrameHostMsg_Detach(routing_id_));
1858 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
1859 // sent before setting |is_detaching_| to true. In contrast, Observers
1860 // should only be notified afterwards so they cannot call back into here and
1861 // have IPCs fired off.
1862 is_detaching_ = true;
1864 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
1865 FrameDetached(frame));
1867 // We need to clean up subframes by removing them from the map and deleting
1868 // the RenderFrameImpl. In contrast, the main frame is owned by its
1869 // containing RenderViewHost (so that they have the same lifetime), so only
1870 // removal from the map is needed and no deletion.
1871 FrameMap::iterator it = g_frame_map.Get().find(frame);
1872 CHECK(it != g_frame_map.Get().end());
1873 CHECK_EQ(it->second, this);
1874 g_frame_map.Get().erase(it);
1876 if (is_subframe)
1877 frame->parent()->removeChild(frame);
1879 // |frame| is invalid after here.
1880 frame->close();
1882 if (is_subframe) {
1883 delete this;
1884 // Object is invalid after this point.
1888 void RenderFrameImpl::frameFocused() {
1889 Send(new FrameHostMsg_FrameFocused(routing_id_));
1892 void RenderFrameImpl::willClose(blink::WebFrame* frame) {
1893 DCHECK(!frame_ || frame_ == frame);
1895 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FrameWillClose());
1896 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
1897 FrameWillClose(frame));
1900 void RenderFrameImpl::didChangeName(blink::WebLocalFrame* frame,
1901 const blink::WebString& name) {
1902 DCHECK(!frame_ || frame_ == frame);
1903 if (!render_view_->renderer_preferences_.report_frame_name_changes)
1904 return;
1906 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeName(name));
1909 void RenderFrameImpl::didMatchCSS(
1910 blink::WebLocalFrame* frame,
1911 const blink::WebVector<blink::WebString>& newly_matching_selectors,
1912 const blink::WebVector<blink::WebString>& stopped_matching_selectors) {
1913 DCHECK(!frame_ || frame_ == frame);
1915 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
1916 DidMatchCSS(frame,
1917 newly_matching_selectors,
1918 stopped_matching_selectors));
1921 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
1922 const blink::WebString& source) {
1923 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
1924 source);
1927 void RenderFrameImpl::didAddMessageToConsole(
1928 const blink::WebConsoleMessage& message,
1929 const blink::WebString& source_name,
1930 unsigned source_line,
1931 const blink::WebString& stack_trace) {
1932 logging::LogSeverity log_severity = logging::LOG_VERBOSE;
1933 switch (message.level) {
1934 case blink::WebConsoleMessage::LevelDebug:
1935 log_severity = logging::LOG_VERBOSE;
1936 break;
1937 case blink::WebConsoleMessage::LevelLog:
1938 case blink::WebConsoleMessage::LevelInfo:
1939 log_severity = logging::LOG_INFO;
1940 break;
1941 case blink::WebConsoleMessage::LevelWarning:
1942 log_severity = logging::LOG_WARNING;
1943 break;
1944 case blink::WebConsoleMessage::LevelError:
1945 log_severity = logging::LOG_ERROR;
1946 break;
1947 default:
1948 NOTREACHED();
1951 if (shouldReportDetailedMessageForSource(source_name)) {
1952 FOR_EACH_OBSERVER(
1953 RenderFrameObserver, observers_,
1954 DetailedConsoleMessageAdded(message.text,
1955 source_name,
1956 stack_trace,
1957 source_line,
1958 static_cast<int32>(log_severity)));
1961 Send(new FrameHostMsg_AddMessageToConsole(routing_id_,
1962 static_cast<int32>(log_severity),
1963 message.text,
1964 static_cast<int32>(source_line),
1965 source_name));
1968 void RenderFrameImpl::loadURLExternally(
1969 blink::WebLocalFrame* frame,
1970 const blink::WebURLRequest& request,
1971 blink::WebNavigationPolicy policy,
1972 const blink::WebString& suggested_name) {
1973 DCHECK(!frame_ || frame_ == frame);
1974 Referrer referrer(RenderViewImpl::GetReferrerFromRequest(frame, request));
1975 if (policy == blink::WebNavigationPolicyDownload) {
1976 render_view_->Send(new ViewHostMsg_DownloadUrl(render_view_->GetRoutingID(),
1977 request.url(), referrer,
1978 suggested_name));
1979 } else {
1980 OpenURL(frame, request.url(), referrer, policy);
1984 blink::WebNavigationPolicy RenderFrameImpl::decidePolicyForNavigation(
1985 const NavigationPolicyInfo& info) {
1986 DCHECK(!frame_ || frame_ == info.frame);
1987 return DecidePolicyForNavigation(this, info);
1990 blink::WebHistoryItem RenderFrameImpl::historyItemForNewChildFrame(
1991 blink::WebFrame* frame) {
1992 DCHECK(!frame_ || frame_ == frame);
1993 return render_view_->history_controller()->GetItemForNewChildFrame(this);
1996 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame* frame,
1997 const blink::WebFormElement& form) {
1998 DCHECK(!frame_ || frame_ == frame);
2000 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2001 WillSendSubmitEvent(frame, form));
2004 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame* frame,
2005 const blink::WebFormElement& form) {
2006 DCHECK(!frame_ || frame_ == frame);
2007 DocumentState* document_state =
2008 DocumentState::FromDataSource(frame->provisionalDataSource());
2009 NavigationState* navigation_state = document_state->navigation_state();
2010 InternalDocumentStateData* internal_data =
2011 InternalDocumentStateData::FromDocumentState(document_state);
2013 if (ui::PageTransitionCoreTypeIs(navigation_state->transition_type(),
2014 ui::PAGE_TRANSITION_LINK)) {
2015 navigation_state->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT);
2018 // Save these to be processed when the ensuing navigation is committed.
2019 WebSearchableFormData web_searchable_form_data(form);
2020 internal_data->set_searchable_form_url(web_searchable_form_data.url());
2021 internal_data->set_searchable_form_encoding(
2022 web_searchable_form_data.encoding().utf8());
2024 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2025 WillSubmitForm(frame, form));
2028 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame* frame,
2029 blink::WebDataSource* datasource) {
2030 DCHECK(!frame_ || frame_ == frame);
2032 // TODO(nasko): Move implementation here. Needed state:
2033 // * pending_navigation_params_
2034 // * webview
2035 // Needed methods:
2036 // * PopulateDocumentStateFromPending
2037 // * CreateNavigationStateFromPending
2038 render_view_->didCreateDataSource(frame, datasource);
2040 // Create the serviceworker's per-document network observing object.
2041 scoped_ptr<ServiceWorkerNetworkProvider>
2042 network_provider(new ServiceWorkerNetworkProvider());
2043 ServiceWorkerNetworkProvider::AttachToDocumentState(
2044 DocumentState::FromDataSource(datasource),
2045 network_provider.Pass());
2048 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame* frame,
2049 bool is_transition_navigation) {
2050 DCHECK(!frame_ || frame_ == frame);
2051 WebDataSource* ds = frame->provisionalDataSource();
2053 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2054 // callback is invoked.
2055 if (!ds)
2056 return;
2058 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2059 "id", routing_id_, "url", ds->request().url().string().utf8());
2060 DocumentState* document_state = DocumentState::FromDataSource(ds);
2062 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2063 CHECK((ds->request().url() != GURL(kSwappedOutURL)) ||
2064 is_swapped_out_ ||
2065 render_view_->is_swapped_out()) <<
2066 "Heard swappedout:// when not swapped out.";
2068 // Update the request time if WebKit has better knowledge of it.
2069 if (document_state->request_time().is_null()) {
2070 double event_time = ds->triggeringEventTime();
2071 if (event_time != 0.0)
2072 document_state->set_request_time(Time::FromDoubleT(event_time));
2075 // Start time is only set after request time.
2076 document_state->set_start_load_time(Time::Now());
2078 bool is_top_most = !frame->parent();
2079 if (is_top_most) {
2080 render_view_->set_navigation_gesture(
2081 WebUserGestureIndicator::isProcessingUserGesture() ?
2082 NavigationGestureUser : NavigationGestureAuto);
2083 } else if (ds->replacesCurrentHistoryItem()) {
2084 // Subframe navigations that don't add session history items must be
2085 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2086 // handle loading of error pages.
2087 document_state->navigation_state()->set_transition_type(
2088 ui::PAGE_TRANSITION_AUTO_SUBFRAME);
2091 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2092 DidStartProvisionalLoad(frame));
2093 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidStartProvisionalLoad());
2095 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2096 routing_id_, ds->request().url(), is_transition_navigation));
2099 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2100 blink::WebLocalFrame* frame) {
2101 DCHECK(!frame_ || frame_ == frame);
2102 render_view_->history_controller()->RemoveChildrenForRedirect(this);
2105 void RenderFrameImpl::didFailProvisionalLoad(blink::WebLocalFrame* frame,
2106 const blink::WebURLError& error) {
2107 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2108 "id", routing_id_);
2109 DCHECK(!frame_ || frame_ == frame);
2110 WebDataSource* ds = frame->provisionalDataSource();
2111 DCHECK(ds);
2113 const WebURLRequest& failed_request = ds->request();
2115 // Notify the browser that we failed a provisional load with an error.
2117 // Note: It is important this notification occur before DidStopLoading so the
2118 // SSL manager can react to the provisional load failure before being
2119 // notified the load stopped.
2121 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2122 DidFailProvisionalLoad(frame, error));
2123 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
2124 DidFailProvisionalLoad(error));
2126 bool show_repost_interstitial =
2127 (error.reason == net::ERR_CACHE_MISS &&
2128 EqualsASCII(failed_request.httpMethod(), "POST"));
2130 FrameHostMsg_DidFailProvisionalLoadWithError_Params params;
2131 params.error_code = error.reason;
2132 GetContentClient()->renderer()->GetNavigationErrorStrings(
2133 render_view_.get(),
2134 frame,
2135 failed_request,
2136 error,
2137 NULL,
2138 &params.error_description);
2139 params.url = error.unreachableURL;
2140 params.showing_repost_interstitial = show_repost_interstitial;
2141 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(
2142 routing_id_, params));
2144 // Don't display an error page if this is simply a cancelled load. Aside
2145 // from being dumb, WebCore doesn't expect it and it will cause a crash.
2146 if (error.reason == net::ERR_ABORTED)
2147 return;
2149 // Don't display "client blocked" error page if browser has asked us not to.
2150 if (error.reason == net::ERR_BLOCKED_BY_CLIENT &&
2151 render_view_->renderer_preferences_.disable_client_blocked_error_page) {
2152 return;
2155 // Allow the embedder to suppress an error page.
2156 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(this,
2157 error.unreachableURL)) {
2158 return;
2161 if (RenderThreadImpl::current() &&
2162 RenderThreadImpl::current()->layout_test_mode()) {
2163 return;
2166 // Make sure we never show errors in view source mode.
2167 frame->enableViewSourceMode(false);
2169 DocumentState* document_state = DocumentState::FromDataSource(ds);
2170 NavigationState* navigation_state = document_state->navigation_state();
2172 // If this is a failed back/forward/reload navigation, then we need to do a
2173 // 'replace' load. This is necessary to avoid messing up session history.
2174 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2175 // as session history is concerned.
2177 // AUTO_SUBFRAME loads should always be treated as loads that do not advance
2178 // the page id.
2180 // TODO(davidben): This should also take the failed navigation's replacement
2181 // state into account, if a location.replace() failed.
2182 bool replace =
2183 navigation_state->pending_page_id() != -1 ||
2184 ui::PageTransitionCoreTypeIs(navigation_state->transition_type(),
2185 ui::PAGE_TRANSITION_AUTO_SUBFRAME);
2187 // If we failed on a browser initiated request, then make sure that our error
2188 // page load is regarded as the same browser initiated request.
2189 if (!navigation_state->is_content_initiated()) {
2190 render_view_->pending_navigation_params_.reset(
2191 new FrameMsg_Navigate_Params);
2192 render_view_->pending_navigation_params_->page_id =
2193 navigation_state->pending_page_id();
2194 render_view_->pending_navigation_params_->pending_history_list_offset =
2195 navigation_state->pending_history_list_offset();
2196 render_view_->pending_navigation_params_->should_clear_history_list =
2197 navigation_state->history_list_was_cleared();
2198 render_view_->pending_navigation_params_->common_params.transition =
2199 navigation_state->transition_type();
2200 render_view_->pending_navigation_params_->request_time =
2201 document_state->request_time();
2202 render_view_->pending_navigation_params_->should_replace_current_entry =
2203 replace;
2206 // Load an error page.
2207 LoadNavigationErrorPage(failed_request, error, replace);
2210 void RenderFrameImpl::didCommitProvisionalLoad(
2211 blink::WebLocalFrame* frame,
2212 const blink::WebHistoryItem& item,
2213 blink::WebHistoryCommitType commit_type) {
2214 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2215 "id", routing_id_,
2216 "url", GetLoadingUrl().possibly_invalid_spec());
2217 DCHECK(!frame_ || frame_ == frame);
2218 DocumentState* document_state =
2219 DocumentState::FromDataSource(frame->dataSource());
2220 NavigationState* navigation_state = document_state->navigation_state();
2222 // When we perform a new navigation, we need to update the last committed
2223 // session history entry with state for the page we are leaving. Do this
2224 // before updating the HistoryController state.
2225 render_view_->UpdateSessionHistory(frame);
2227 render_view_->history_controller()->UpdateForCommit(this, item, commit_type,
2228 navigation_state->was_within_same_page());
2230 InternalDocumentStateData* internal_data =
2231 InternalDocumentStateData::FromDocumentState(document_state);
2233 if (document_state->commit_load_time().is_null())
2234 document_state->set_commit_load_time(Time::Now());
2236 if (internal_data->must_reset_scroll_and_scale_state()) {
2237 render_view_->webview()->resetScrollAndScaleState();
2238 internal_data->set_must_reset_scroll_and_scale_state(false);
2240 internal_data->set_use_error_page(false);
2242 bool is_new_navigation = commit_type == blink::WebStandardCommit;
2243 if (is_new_navigation) {
2244 // We bump our Page ID to correspond with the new session history entry.
2245 render_view_->page_id_ = render_view_->next_page_id_++;
2247 // Don't update history_page_ids_ (etc) for kSwappedOutURL, since
2248 // we don't want to forget the entry that was there, and since we will
2249 // never come back to kSwappedOutURL. Note that we have to call
2250 // UpdateSessionHistory and update page_id_ even in this case, so that
2251 // the current entry gets a state update and so that we don't send a
2252 // state update to the wrong entry when we swap back in.
2253 if (GetLoadingUrl() != GURL(kSwappedOutURL)) {
2254 // Advance our offset in session history, applying the length limit.
2255 // There is now no forward history.
2256 render_view_->history_list_offset_++;
2257 if (render_view_->history_list_offset_ >= kMaxSessionHistoryEntries)
2258 render_view_->history_list_offset_ = kMaxSessionHistoryEntries - 1;
2259 render_view_->history_list_length_ =
2260 render_view_->history_list_offset_ + 1;
2261 render_view_->history_page_ids_.resize(
2262 render_view_->history_list_length_, -1);
2263 render_view_->history_page_ids_[render_view_->history_list_offset_] =
2264 render_view_->page_id_;
2266 } else {
2267 // Inspect the navigation_state on this frame to see if the navigation
2268 // corresponds to a session history navigation... Note: |frame| may or
2269 // may not be the toplevel frame, but for the case of capturing session
2270 // history, the first committed frame suffices. We keep track of whether
2271 // we've seen this commit before so that only capture session history once
2272 // per navigation.
2274 // Note that we need to check if the page ID changed. In the case of a
2275 // reload, the page ID doesn't change, and UpdateSessionHistory gets the
2276 // previous URL and the current page ID, which would be wrong.
2277 if (navigation_state->pending_page_id() != -1 &&
2278 navigation_state->pending_page_id() != render_view_->page_id_ &&
2279 !navigation_state->request_committed()) {
2280 // This is a successful session history navigation!
2281 render_view_->page_id_ = navigation_state->pending_page_id();
2283 render_view_->history_list_offset_ =
2284 navigation_state->pending_history_list_offset();
2286 // If the history list is valid, our list of page IDs should be correct.
2287 DCHECK(render_view_->history_list_length_ <= 0 ||
2288 render_view_->history_list_offset_ < 0 ||
2289 render_view_->history_list_offset_ >=
2290 render_view_->history_list_length_ ||
2291 render_view_->history_page_ids_[render_view_->history_list_offset_]
2292 == render_view_->page_id_);
2296 bool sent = Send(
2297 new FrameHostMsg_DidAssignPageId(routing_id_, render_view_->page_id_));
2298 CHECK(sent); // http://crbug.com/407376
2300 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers_,
2301 DidCommitProvisionalLoad(frame, is_new_navigation));
2302 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
2303 DidCommitProvisionalLoad(is_new_navigation));
2305 if (!frame->parent()) { // Only for top frames.
2306 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
2307 if (render_thread_impl) { // Can be NULL in tests.
2308 render_thread_impl->histogram_customizer()->
2309 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2310 RenderViewImpl::GetRenderViewCount());
2314 // Remember that we've already processed this request, so we don't update
2315 // the session history again. We do this regardless of whether this is
2316 // a session history navigation, because if we attempted a session history
2317 // navigation without valid HistoryItem state, WebCore will think it is a
2318 // new navigation.
2319 navigation_state->set_request_committed(true);
2321 SendDidCommitProvisionalLoad(frame);
2323 // Check whether we have new encoding name.
2324 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2327 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame* frame) {
2328 DCHECK(!frame_ || frame_ == frame);
2329 // TODO(nasko): Move implementation here. Needed state:
2330 // * enabled_bindings_
2331 // * dom_automation_controller_
2332 // * stats_collection_controller_
2334 render_view_->didClearWindowObject(frame);
2336 if (render_view_->GetEnabledBindings() & BINDINGS_POLICY_DOM_AUTOMATION)
2337 DomAutomationController::Install(this, frame);
2339 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidClearWindowObject());
2342 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame* frame) {
2343 DCHECK(!frame_ || frame_ == frame);
2345 // Notify the browser about non-blank documents loading in the top frame.
2346 GURL url = frame->document().url();
2347 if (url.is_valid() && url.spec() != url::kAboutBlankURL) {
2348 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2349 // frame->tree()->top().
2350 blink::WebFrame* main_frame = render_view_->webview()->mainFrame();
2351 if (frame == main_frame) {
2352 // For now, don't remember plugin zoom values. We don't want to mix them
2353 // with normal web content (i.e. a fixed layout plugin would usually want
2354 // them different).
2355 render_view_->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2356 render_view_->GetRoutingID(),
2357 main_frame->document().isPluginDocument()));
2361 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2362 DidCreateDocumentElement(frame));
2365 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame* frame,
2366 const blink::WebString& title,
2367 blink::WebTextDirection direction) {
2368 DCHECK(!frame_ || frame_ == frame);
2369 // Ignore all but top level navigations.
2370 if (!frame->parent()) {
2371 base::string16 title16 = title;
2372 base::debug::TraceLog::GetInstance()->UpdateProcessLabel(
2373 routing_id_, base::UTF16ToUTF8(title16));
2375 base::string16 shortened_title = title16.substr(0, kMaxTitleChars);
2376 Send(new FrameHostMsg_UpdateTitle(routing_id_,
2377 render_view_->page_id_,
2378 shortened_title, direction));
2381 // Also check whether we have new encoding name.
2382 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2385 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame* frame,
2386 blink::WebIconURL::Type icon_type) {
2387 DCHECK(!frame_ || frame_ == frame);
2388 // TODO(nasko): Investigate wheather implementation should move here.
2389 render_view_->didChangeIcon(frame, icon_type);
2392 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame* frame) {
2393 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2394 "id", routing_id_);
2395 DCHECK(!frame_ || frame_ == frame);
2396 WebDataSource* ds = frame->dataSource();
2397 DocumentState* document_state = DocumentState::FromDataSource(ds);
2398 document_state->set_finish_document_load_time(Time::Now());
2400 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_));
2402 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2403 DidFinishDocumentLoad(frame));
2404 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidFinishDocumentLoad());
2406 // Check whether we have new encoding name.
2407 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2410 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame* frame) {
2411 DCHECK(!frame_ || frame_ == frame);
2412 if (!frame->parent())
2413 Send(new FrameHostMsg_DocumentOnLoadCompleted(routing_id_));
2416 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame* frame,
2417 const blink::WebURLError& error) {
2418 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2419 "id", routing_id_);
2420 DCHECK(!frame_ || frame_ == frame);
2421 // TODO(nasko): Move implementation here. No state needed.
2422 WebDataSource* ds = frame->dataSource();
2423 DCHECK(ds);
2425 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2426 DidFailLoad(frame, error));
2428 const WebURLRequest& failed_request = ds->request();
2429 base::string16 error_description;
2430 GetContentClient()->renderer()->GetNavigationErrorStrings(
2431 render_view_.get(),
2432 frame,
2433 failed_request,
2434 error,
2435 NULL,
2436 &error_description);
2437 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_,
2438 failed_request.url(),
2439 error.reason,
2440 error_description));
2443 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame* frame) {
2444 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2445 "id", routing_id_);
2446 DCHECK(!frame_ || frame_ == frame);
2447 WebDataSource* ds = frame->dataSource();
2448 DocumentState* document_state = DocumentState::FromDataSource(ds);
2449 if (document_state->finish_load_time().is_null()) {
2450 if (!frame->parent()) {
2451 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2452 TRACE_EVENT_SCOPE_PROCESS);
2454 document_state->set_finish_load_time(Time::Now());
2457 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2458 DidFinishLoad(frame));
2459 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidFinishLoad());
2461 // Don't send this message while the frame is swapped out.
2462 if (is_swapped_out())
2463 return;
2465 Send(new FrameHostMsg_DidFinishLoad(routing_id_,
2466 ds->request().url()));
2469 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame* frame,
2470 const blink::WebHistoryItem& item,
2471 blink::WebHistoryCommitType commit_type) {
2472 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
2473 "id", routing_id_);
2474 DCHECK(!frame_ || frame_ == frame);
2475 // If this was a reference fragment navigation that we initiated, then we
2476 // could end up having a non-null pending navigation params. We just need to
2477 // update the ExtraData on the datasource so that others who read the
2478 // ExtraData will get the new NavigationState. Similarly, if we did not
2479 // initiate this navigation, then we need to take care to reset any pre-
2480 // existing navigation state to a content-initiated navigation state.
2481 // DidCreateDataSource conveniently takes care of this for us.
2482 didCreateDataSource(frame, frame->dataSource());
2484 DocumentState* document_state =
2485 DocumentState::FromDataSource(frame->dataSource());
2486 NavigationState* new_state = document_state->navigation_state();
2487 new_state->set_was_within_same_page(true);
2489 didCommitProvisionalLoad(frame, item, commit_type);
2492 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame* frame) {
2493 DCHECK(!frame_ || frame_ == frame);
2494 // TODO(nasko): Move implementation here. Needed methods:
2495 // * StartNavStateSyncTimerIfNecessary
2496 render_view_->didUpdateCurrentHistoryItem(frame);
2499 // TODO(zhenw): This will be removed once the blink side implementation is done.
2500 void RenderFrameImpl::addNavigationTransitionData(
2501 const blink::WebString& allowed_destination_host_pattern,
2502 const blink::WebString& selector,
2503 const blink::WebString& markup) {
2504 FrameHostMsg_AddNavigationTransitionData_Params params;
2505 params.render_frame_id = routing_id_;
2506 params.allowed_destination_host_pattern =
2507 allowed_destination_host_pattern.utf8();
2508 params.selector = selector.utf8();
2509 params.markup = markup.utf8();
2511 Send(new FrameHostMsg_AddNavigationTransitionData(params));
2514 void RenderFrameImpl::addNavigationTransitionData(
2515 const blink::WebString& allowed_destination_host_pattern,
2516 const blink::WebString& selector,
2517 const blink::WebString& markup,
2518 const blink::WebVector<blink::WebString>& web_names,
2519 const blink::WebVector<blink::WebRect>& web_rects) {
2520 FrameHostMsg_AddNavigationTransitionData_Params params;
2521 params.render_frame_id = routing_id_;
2522 params.allowed_destination_host_pattern =
2523 allowed_destination_host_pattern.utf8();
2524 params.selector = selector.utf8();
2525 params.markup = markup.utf8();
2526 for (size_t i = 0; i < web_names.size(); i++) {
2527 params.names.push_back(web_names[i].utf8());
2529 for (size_t i = 0; i < web_rects.size(); i++) {
2530 params.rects.push_back(gfx::Rect(web_rects[i]));
2533 Send(new FrameHostMsg_AddNavigationTransitionData(params));
2536 void RenderFrameImpl::didChangeThemeColor() {
2537 if (frame_->parent())
2538 return;
2540 Send(new FrameHostMsg_DidChangeThemeColor(
2541 routing_id_, frame_->document().themeColor()));
2544 void RenderFrameImpl::requestNotificationPermission(
2545 const blink::WebSecurityOrigin& origin,
2546 blink::WebNotificationPermissionCallback* callback) {
2547 if (!notification_permission_dispatcher_) {
2548 notification_permission_dispatcher_ =
2549 new NotificationPermissionDispatcher(this);
2552 notification_permission_dispatcher_->RequestPermission(origin, callback);
2555 blink::WebNotificationPresenter* RenderFrameImpl::notificationPresenter() {
2556 return notification_provider_;
2559 void RenderFrameImpl::didChangeSelection(bool is_empty_selection) {
2560 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_)
2561 return;
2563 if (is_empty_selection)
2564 selection_text_.clear();
2566 // UpdateTextInputType should be called before SyncSelectionIfRequired.
2567 // UpdateTextInputType may send TextInputTypeChanged to notify the focus
2568 // was changed, and SyncSelectionIfRequired may send SelectionChanged
2569 // to notify the selection was changed. Focus change should be notified
2570 // before selection change.
2571 GetRenderWidget()->UpdateTextInputType();
2572 SyncSelectionIfRequired();
2573 #if defined(OS_ANDROID)
2574 GetRenderWidget()->UpdateTextInputState(RenderWidget::NO_SHOW_IME,
2575 RenderWidget::FROM_NON_IME);
2576 #endif
2579 blink::WebColorChooser* RenderFrameImpl::createColorChooser(
2580 blink::WebColorChooserClient* client,
2581 const blink::WebColor& initial_color,
2582 const blink::WebVector<blink::WebColorSuggestion>& suggestions) {
2583 RendererWebColorChooserImpl* color_chooser =
2584 new RendererWebColorChooserImpl(this, client);
2585 std::vector<content::ColorSuggestion> color_suggestions;
2586 for (size_t i = 0; i < suggestions.size(); i++) {
2587 color_suggestions.push_back(content::ColorSuggestion(suggestions[i]));
2589 color_chooser->Open(static_cast<SkColor>(initial_color), color_suggestions);
2590 return color_chooser;
2593 void RenderFrameImpl::runModalAlertDialog(const blink::WebString& message) {
2594 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT,
2595 message,
2596 base::string16(),
2597 frame_->document().url(),
2598 NULL);
2601 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString& message) {
2602 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM,
2603 message,
2604 base::string16(),
2605 frame_->document().url(),
2606 NULL);
2609 bool RenderFrameImpl::runModalPromptDialog(
2610 const blink::WebString& message,
2611 const blink::WebString& default_value,
2612 blink::WebString* actual_value) {
2613 base::string16 result;
2614 bool ok = RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT,
2615 message,
2616 default_value,
2617 frame_->document().url(),
2618 &result);
2619 if (ok)
2620 actual_value->assign(result);
2621 return ok;
2624 bool RenderFrameImpl::runModalBeforeUnloadDialog(
2625 bool is_reload,
2626 const blink::WebString& message) {
2627 // If we are swapping out, we have already run the beforeunload handler.
2628 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
2629 // at all, to avoid running it twice.
2630 if (render_view()->is_swapped_out_)
2631 return true;
2633 // Don't allow further dialogs if we are waiting to swap out, since the
2634 // PageGroupLoadDeferrer in our stack prevents it.
2635 if (render_view()->suppress_dialogs_until_swap_out_)
2636 return false;
2638 bool success = false;
2639 // This is an ignored return value, but is included so we can accept the same
2640 // response as RunJavaScriptMessage.
2641 base::string16 ignored_result;
2642 render_view()->SendAndRunNestedMessageLoop(
2643 new FrameHostMsg_RunBeforeUnloadConfirm(
2644 routing_id_, frame_->document().url(), message, is_reload,
2645 &success, &ignored_result));
2646 return success;
2649 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData& data) {
2650 ContextMenuParams params = ContextMenuParamsBuilder::Build(data);
2651 params.source_type = GetRenderWidget()->context_menu_source_type();
2652 GetRenderWidget()->OnShowHostContextMenu(&params);
2653 if (GetRenderWidget()->has_host_context_menu_location()) {
2654 params.x = GetRenderWidget()->host_context_menu_location().x();
2655 params.y = GetRenderWidget()->host_context_menu_location().y();
2658 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
2659 // it. We replace it with an empty GURL so the appropriate items are disabled
2660 // in the context menu.
2661 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
2662 // data encoded images. We should have a way to save them.
2663 if (params.src_url.spec().size() > GetMaxURLChars())
2664 params.src_url = GURL();
2665 context_menu_node_ = data.node;
2667 #if defined(OS_ANDROID)
2668 gfx::Rect start_rect;
2669 gfx::Rect end_rect;
2670 GetRenderWidget()->GetSelectionBounds(&start_rect, &end_rect);
2671 params.selection_start = gfx::Point(start_rect.x(), start_rect.bottom());
2672 params.selection_end = gfx::Point(end_rect.right(), end_rect.bottom());
2673 #endif
2675 Send(new FrameHostMsg_ContextMenu(routing_id_, params));
2678 void RenderFrameImpl::clearContextMenu() {
2679 context_menu_node_.reset();
2682 void RenderFrameImpl::willSendRequest(
2683 blink::WebLocalFrame* frame,
2684 unsigned identifier,
2685 blink::WebURLRequest& request,
2686 const blink::WebURLResponse& redirect_response) {
2687 DCHECK(!frame_ || frame_ == frame);
2688 // The request my be empty during tests.
2689 if (request.url().isEmpty())
2690 return;
2692 // Set the first party for cookies url if it has not been set yet (new
2693 // requests). For redirects, it is updated by WebURLLoaderImpl.
2694 if (request.firstPartyForCookies().isEmpty()) {
2695 if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel) {
2696 request.setFirstPartyForCookies(request.url());
2697 } else {
2698 // TODO(nasko): When the top-level frame is remote, there is no document.
2699 // This is broken and should be fixed to propagate the first party.
2700 WebFrame* top = frame->top();
2701 if (top->isWebLocalFrame()) {
2702 request.setFirstPartyForCookies(
2703 frame->top()->document().firstPartyForCookies());
2708 WebFrame* top_frame = frame->top();
2709 // TODO(nasko): Hack around asking about top-frame data source. This means
2710 // for out-of-process iframes we are treating the current frame as the
2711 // top-level frame, which is wrong.
2712 if (!top_frame || top_frame->isWebRemoteFrame())
2713 top_frame = frame;
2714 WebDataSource* provisional_data_source = top_frame->provisionalDataSource();
2715 WebDataSource* top_data_source = top_frame->dataSource();
2716 WebDataSource* data_source =
2717 provisional_data_source ? provisional_data_source : top_data_source;
2719 ui::PageTransition transition_type = ui::PAGE_TRANSITION_LINK;
2720 DocumentState* document_state = DocumentState::FromDataSource(data_source);
2721 DCHECK(document_state);
2722 InternalDocumentStateData* internal_data =
2723 InternalDocumentStateData::FromDocumentState(document_state);
2724 NavigationState* navigation_state = document_state->navigation_state();
2725 transition_type = navigation_state->transition_type();
2727 GURL request_url(request.url());
2728 GURL new_url;
2729 if (GetContentClient()->renderer()->WillSendRequest(
2730 frame,
2731 transition_type,
2732 request_url,
2733 request.firstPartyForCookies(),
2734 &new_url)) {
2735 request.setURL(WebURL(new_url));
2738 if (internal_data->is_cache_policy_override_set())
2739 request.setCachePolicy(internal_data->cache_policy_override());
2741 // The request's extra data may indicate that we should set a custom user
2742 // agent. This needs to be done here, after WebKit is through with setting the
2743 // user agent on its own. Similarly, it may indicate that we should set an
2744 // X-Requested-With header. This must be done here to avoid breaking CORS
2745 // checks.
2746 // PlzNavigate: there may also be a stream url associated with the request.
2747 WebString custom_user_agent;
2748 WebString requested_with;
2749 scoped_ptr<StreamOverrideParameters> stream_override;
2750 if (request.extraData()) {
2751 RequestExtraData* old_extra_data =
2752 static_cast<RequestExtraData*>(request.extraData());
2754 custom_user_agent = old_extra_data->custom_user_agent();
2755 if (!custom_user_agent.isNull()) {
2756 if (custom_user_agent.isEmpty())
2757 request.clearHTTPHeaderField("User-Agent");
2758 else
2759 request.setHTTPHeaderField("User-Agent", custom_user_agent);
2762 requested_with = old_extra_data->requested_with();
2763 if (!requested_with.isNull()) {
2764 if (requested_with.isEmpty())
2765 request.clearHTTPHeaderField("X-Requested-With");
2766 else
2767 request.setHTTPHeaderField("X-Requested-With", requested_with);
2769 stream_override = old_extra_data->TakeStreamOverrideOwnership();
2772 // Add the default accept header for frame request if it has not been set
2773 // already.
2774 if ((request.frameType() == blink::WebURLRequest::FrameTypeTopLevel ||
2775 request.frameType() == blink::WebURLRequest::FrameTypeNested) &&
2776 request.httpHeaderField(WebString::fromUTF8(kAcceptHeader)).isEmpty()) {
2777 request.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader),
2778 WebString::fromUTF8(kDefaultAcceptHeader));
2781 // Add an empty HTTP origin header for non GET methods if none is currently
2782 // present.
2783 request.addHTTPOriginIfNeeded(WebString());
2785 // Attach |should_replace_current_entry| state to requests so that, should
2786 // this navigation later require a request transfer, all state is preserved
2787 // when it is re-created in the new process.
2788 bool should_replace_current_entry = false;
2789 if (navigation_state->is_content_initiated()) {
2790 should_replace_current_entry = data_source->replacesCurrentHistoryItem();
2791 } else {
2792 // If the navigation is browser-initiated, the NavigationState contains the
2793 // correct value instead of the WebDataSource.
2795 // TODO(davidben): Avoid this awkward duplication of state. See comment on
2796 // NavigationState::should_replace_current_entry().
2797 should_replace_current_entry =
2798 navigation_state->should_replace_current_entry();
2801 int provider_id = kInvalidServiceWorkerProviderId;
2802 if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel ||
2803 request.frameType() == blink::WebURLRequest::FrameTypeNested) {
2804 // |provisionalDataSource| may be null in some content::ResourceFetcher
2805 // use cases, we don't hook those requests.
2806 if (frame->provisionalDataSource()) {
2807 ServiceWorkerNetworkProvider* provider =
2808 ServiceWorkerNetworkProvider::FromDocumentState(
2809 DocumentState::FromDataSource(frame->provisionalDataSource()));
2810 provider_id = provider->provider_id();
2812 } else if (frame->dataSource()) {
2813 ServiceWorkerNetworkProvider* provider =
2814 ServiceWorkerNetworkProvider::FromDocumentState(
2815 DocumentState::FromDataSource(frame->dataSource()));
2816 provider_id = provider->provider_id();
2819 WebFrame* parent = frame->parent();
2820 int parent_routing_id = MSG_ROUTING_NONE;
2821 if (!parent) {
2822 parent_routing_id = -1;
2823 } else if (parent->isWebLocalFrame()) {
2824 parent_routing_id = FromWebFrame(parent)->GetRoutingID();
2825 } else {
2826 parent_routing_id = RenderFrameProxy::FromWebFrame(parent)->routing_id();
2829 RequestExtraData* extra_data = new RequestExtraData();
2830 extra_data->set_visibility_state(render_view_->visibilityState());
2831 extra_data->set_custom_user_agent(custom_user_agent);
2832 extra_data->set_requested_with(requested_with);
2833 extra_data->set_render_frame_id(routing_id_);
2834 extra_data->set_is_main_frame(frame == top_frame);
2835 extra_data->set_frame_origin(
2836 GURL(frame->document().securityOrigin().toString()));
2837 extra_data->set_parent_is_main_frame(frame->parent() == top_frame);
2838 extra_data->set_parent_render_frame_id(parent_routing_id);
2839 extra_data->set_allow_download(navigation_state->allow_download());
2840 extra_data->set_transition_type(transition_type);
2841 extra_data->set_should_replace_current_entry(should_replace_current_entry);
2842 extra_data->set_transferred_request_child_id(
2843 navigation_state->transferred_request_child_id());
2844 extra_data->set_transferred_request_request_id(
2845 navigation_state->transferred_request_request_id());
2846 extra_data->set_service_worker_provider_id(provider_id);
2847 extra_data->set_stream_override(stream_override.Pass());
2848 request.setExtraData(extra_data);
2850 DocumentState* top_document_state =
2851 DocumentState::FromDataSource(top_data_source);
2852 if (top_document_state) {
2853 // TODO(gavinp): separate out prefetching and prerender field trials
2854 // if the rel=prerender rel type is sticking around.
2855 if (request.requestContext() == WebURLRequest::RequestContextPrefetch)
2856 top_document_state->set_was_prefetcher(true);
2859 // This is an instance where we embed a copy of the routing id
2860 // into the data portion of the message. This can cause problems if we
2861 // don't register this id on the browser side, since the download manager
2862 // expects to find a RenderViewHost based off the id.
2863 request.setRequestorID(render_view_->GetRoutingID());
2864 request.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
2866 if (!navigation_state->extra_headers().empty()) {
2867 for (net::HttpUtil::HeadersIterator i(
2868 navigation_state->extra_headers().begin(),
2869 navigation_state->extra_headers().end(), "\n");
2870 i.GetNext(); ) {
2871 if (LowerCaseEqualsASCII(i.name(), "referer")) {
2872 WebString referrer = WebSecurityPolicy::generateReferrerHeader(
2873 blink::WebReferrerPolicyDefault,
2874 request.url(),
2875 WebString::fromUTF8(i.values()));
2876 request.setHTTPReferrer(referrer, blink::WebReferrerPolicyDefault);
2877 } else {
2878 request.setHTTPHeaderField(WebString::fromUTF8(i.name()),
2879 WebString::fromUTF8(i.values()));
2884 if (!render_view_->renderer_preferences_.enable_referrers)
2885 request.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault);
2888 void RenderFrameImpl::didReceiveResponse(
2889 blink::WebLocalFrame* frame,
2890 unsigned identifier,
2891 const blink::WebURLResponse& response) {
2892 DCHECK(!frame_ || frame_ == frame);
2893 // Only do this for responses that correspond to a provisional data source
2894 // of the top-most frame. If we have a provisional data source, then we
2895 // can't have any sub-resources yet, so we know that this response must
2896 // correspond to a frame load.
2897 if (!frame->provisionalDataSource() || frame->parent())
2898 return;
2900 // If we are in view source mode, then just let the user see the source of
2901 // the server's error page.
2902 if (frame->isViewSourceModeEnabled())
2903 return;
2905 DocumentState* document_state =
2906 DocumentState::FromDataSource(frame->provisionalDataSource());
2907 int http_status_code = response.httpStatusCode();
2909 // Record page load flags.
2910 WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response);
2911 if (extra_data) {
2912 document_state->set_was_fetched_via_spdy(
2913 extra_data->was_fetched_via_spdy());
2914 document_state->set_was_npn_negotiated(
2915 extra_data->was_npn_negotiated());
2916 document_state->set_npn_negotiated_protocol(
2917 extra_data->npn_negotiated_protocol());
2918 document_state->set_was_alternate_protocol_available(
2919 extra_data->was_alternate_protocol_available());
2920 document_state->set_connection_info(
2921 extra_data->connection_info());
2922 document_state->set_was_fetched_via_proxy(
2923 extra_data->was_fetched_via_proxy());
2925 InternalDocumentStateData* internal_data =
2926 InternalDocumentStateData::FromDocumentState(document_state);
2927 internal_data->set_http_status_code(http_status_code);
2928 // Whether or not the http status code actually corresponds to an error is
2929 // only checked when the page is done loading, if |use_error_page| is
2930 // still true.
2931 internal_data->set_use_error_page(true);
2934 void RenderFrameImpl::didFinishResourceLoad(blink::WebLocalFrame* frame,
2935 unsigned identifier) {
2936 DCHECK(!frame_ || frame_ == frame);
2937 InternalDocumentStateData* internal_data =
2938 InternalDocumentStateData::FromDataSource(frame->dataSource());
2939 if (!internal_data->use_error_page())
2940 return;
2942 // Do not show error page when DevTools is attached.
2943 if (render_view_->devtools_agent_->IsAttached())
2944 return;
2946 // Display error page, if appropriate.
2947 std::string error_domain = "http";
2948 int http_status_code = internal_data->http_status_code();
2949 if (GetContentClient()->renderer()->HasErrorPage(
2950 http_status_code, &error_domain)) {
2951 WebURLError error;
2952 error.unreachableURL = frame->document().url();
2953 error.domain = WebString::fromUTF8(error_domain);
2954 error.reason = http_status_code;
2955 LoadNavigationErrorPage(frame->dataSource()->request(), error, true);
2959 void RenderFrameImpl::didLoadResourceFromMemoryCache(
2960 blink::WebLocalFrame* frame,
2961 const blink::WebURLRequest& request,
2962 const blink::WebURLResponse& response) {
2963 DCHECK(!frame_ || frame_ == frame);
2964 // The recipients of this message have no use for data: URLs: they don't
2965 // affect the page's insecure content list and are not in the disk cache. To
2966 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
2967 // filter them out here.
2968 GURL url(request.url());
2969 if (url.SchemeIs(url::kDataScheme))
2970 return;
2972 // Let the browser know we loaded a resource from the memory cache. This
2973 // message is needed to display the correct SSL indicators.
2974 render_view_->Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(
2975 render_view_->GetRoutingID(),
2976 url,
2977 response.securityInfo(),
2978 request.httpMethod().utf8(),
2979 response.mimeType().utf8(),
2980 WebURLRequestToResourceType(request)));
2983 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame* frame) {
2984 DCHECK(!frame_ || frame_ == frame);
2985 render_view_->Send(new ViewHostMsg_DidDisplayInsecureContent(
2986 render_view_->GetRoutingID()));
2989 void RenderFrameImpl::didRunInsecureContent(
2990 blink::WebLocalFrame* frame,
2991 const blink::WebSecurityOrigin& origin,
2992 const blink::WebURL& target) {
2993 DCHECK(!frame_ || frame_ == frame);
2994 render_view_->Send(new ViewHostMsg_DidRunInsecureContent(
2995 render_view_->GetRoutingID(),
2996 origin.toString().utf8(),
2997 target));
3000 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame* frame) {
3001 DCHECK(!frame_ || frame_ == frame);
3002 #if defined(ENABLE_PLUGINS)
3003 if (frame != render_view_->webview()->mainFrame())
3004 return;
3005 PluginChannelHost::Broadcast(
3006 new PluginHostMsg_DidAbortLoading(render_view_->GetRoutingID()));
3007 #endif
3010 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame* frame,
3011 v8::Handle<v8::Context> context,
3012 int extension_group,
3013 int world_id) {
3014 DCHECK(!frame_ || frame_ == frame);
3015 GetContentClient()->renderer()->DidCreateScriptContext(
3016 frame, context, extension_group, world_id);
3019 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame* frame,
3020 v8::Handle<v8::Context> context,
3021 int world_id) {
3022 DCHECK(!frame_ || frame_ == frame);
3024 FOR_EACH_OBSERVER(RenderFrameObserver,
3025 observers_,
3026 WillReleaseScriptContext(context, world_id));
3029 void RenderFrameImpl::didFirstVisuallyNonEmptyLayout(
3030 blink::WebLocalFrame* frame) {
3031 DCHECK(!frame_ || frame_ == frame);
3032 if (frame->parent())
3033 return;
3035 InternalDocumentStateData* data =
3036 InternalDocumentStateData::FromDataSource(frame->dataSource());
3037 data->set_did_first_visually_non_empty_layout(true);
3039 #if defined(OS_ANDROID)
3040 GetRenderWidget()->DidChangeBodyBackgroundColor(
3041 render_view_->webwidget_->backgroundColor());
3042 #endif
3044 GetRenderWidget()->QueueMessage(
3045 new FrameHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_),
3046 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE);
3049 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame* frame) {
3050 DCHECK(!frame_ || frame_ == frame);
3051 // TODO(nasko): Move implementation here. Needed methods:
3052 // * StartNavStateSyncTimerIfNecessary
3053 render_view_->didChangeScrollOffset(frame);
3056 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame* frame) {
3057 DCHECK(!frame_ || frame_ == frame);
3058 if (!frame->parent()) {
3059 render_view_->Send(new ViewHostMsg_WillInsertBody(
3060 render_view_->GetRoutingID()));
3064 void RenderFrameImpl::reportFindInPageMatchCount(int request_id,
3065 int count,
3066 bool final_update) {
3067 int active_match_ordinal = -1; // -1 = don't update active match ordinal
3068 if (!count)
3069 active_match_ordinal = 0;
3071 render_view_->Send(new ViewHostMsg_Find_Reply(
3072 render_view_->GetRoutingID(), request_id, count,
3073 gfx::Rect(), active_match_ordinal, final_update));
3076 void RenderFrameImpl::reportFindInPageSelection(
3077 int request_id,
3078 int active_match_ordinal,
3079 const blink::WebRect& selection_rect) {
3080 render_view_->Send(new ViewHostMsg_Find_Reply(
3081 render_view_->GetRoutingID(), request_id, -1, selection_rect,
3082 active_match_ordinal, false));
3085 void RenderFrameImpl::requestStorageQuota(
3086 blink::WebLocalFrame* frame,
3087 blink::WebStorageQuotaType type,
3088 unsigned long long requested_size,
3089 blink::WebStorageQuotaCallbacks callbacks) {
3090 DCHECK(!frame_ || frame_ == frame);
3091 WebSecurityOrigin origin = frame->document().securityOrigin();
3092 if (origin.isUnique()) {
3093 // Unique origins cannot store persistent state.
3094 callbacks.didFail(blink::WebStorageQuotaErrorAbort);
3095 return;
3097 ChildThread::current()->quota_dispatcher()->RequestStorageQuota(
3098 render_view_->GetRoutingID(),
3099 GURL(origin.toString()),
3100 static_cast<storage::StorageType>(type),
3101 requested_size,
3102 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks));
3105 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle* handle) {
3106 WebSocketBridge* impl = static_cast<WebSocketBridge*>(handle);
3107 impl->set_render_frame_id(routing_id_);
3110 blink::WebGeolocationClient* RenderFrameImpl::geolocationClient() {
3111 if (!geolocation_dispatcher_)
3112 geolocation_dispatcher_ = new GeolocationDispatcher(this);
3113 return geolocation_dispatcher_;
3116 blink::WebPushClient* RenderFrameImpl::pushClient() {
3117 if (!push_messaging_dispatcher_)
3118 push_messaging_dispatcher_ = new PushMessagingDispatcher(this);
3119 return push_messaging_dispatcher_;
3122 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3123 blink::WebLocalFrame* frame,
3124 blink::WebRTCPeerConnectionHandler* handler) {
3125 DCHECK(!frame_ || frame_ == frame);
3126 #if defined(ENABLE_WEBRTC)
3127 static_cast<RTCPeerConnectionHandler*>(handler)->associateWithFrame(frame);
3128 #endif
3131 blink::WebUserMediaClient* RenderFrameImpl::userMediaClient() {
3132 if (!web_user_media_client_)
3133 InitializeUserMediaClient();
3134 return web_user_media_client_;
3137 blink::WebMIDIClient* RenderFrameImpl::webMIDIClient() {
3138 if (!midi_dispatcher_)
3139 midi_dispatcher_ = new MidiDispatcher(this);
3140 return midi_dispatcher_;
3143 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3144 blink::WebLocalFrame* source_frame,
3145 blink::WebFrame* target_frame,
3146 blink::WebSecurityOrigin target_origin,
3147 blink::WebDOMMessageEvent event) {
3148 DCHECK(!frame_ || frame_ == target_frame);
3150 if (!render_view_->is_swapped_out_)
3151 return false;
3153 ViewMsg_PostMessage_Params params;
3154 params.is_data_raw_string = false;
3155 params.data = event.data().toString();
3156 params.source_origin = event.origin();
3157 if (!target_origin.isNull())
3158 params.target_origin = target_origin.toString();
3160 blink::WebMessagePortChannelArray channels = event.releaseChannels();
3161 if (!channels.isEmpty()) {
3162 std::vector<int> message_port_ids(channels.size());
3163 // Extract the port IDs from the channel array.
3164 for (size_t i = 0; i < channels.size(); ++i) {
3165 WebMessagePortChannelImpl* webchannel =
3166 static_cast<WebMessagePortChannelImpl*>(channels[i]);
3167 message_port_ids[i] = webchannel->message_port_id();
3168 webchannel->QueueMessages();
3169 DCHECK_NE(message_port_ids[i], MSG_ROUTING_NONE);
3171 params.message_port_ids = message_port_ids;
3174 // Include the routing ID for the source frame (if one exists), which the
3175 // browser process will translate into the routing ID for the equivalent
3176 // frame in the target process.
3177 params.source_routing_id = MSG_ROUTING_NONE;
3178 if (source_frame) {
3179 RenderViewImpl* source_view =
3180 RenderViewImpl::FromWebView(source_frame->view());
3181 if (source_view)
3182 params.source_routing_id = source_view->routing_id();
3185 Send(new ViewHostMsg_RouteMessageEvent(render_view_->routing_id_, params));
3186 return true;
3189 blink::WebString RenderFrameImpl::userAgentOverride(blink::WebLocalFrame* frame,
3190 const blink::WebURL& url) {
3191 DCHECK(!frame_ || frame_ == frame);
3192 std::string user_agent_override_for_url =
3193 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url));
3194 if (!user_agent_override_for_url.empty())
3195 return WebString::fromUTF8(user_agent_override_for_url);
3197 if (!render_view_->webview() || !render_view_->webview()->mainFrame() ||
3198 render_view_->renderer_preferences_.user_agent_override.empty()) {
3199 return blink::WebString();
3202 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3203 // associated with it, so the checks below are not valid. Temporarily
3204 // return early and fix properly as part of https://crbug.com/426555.
3205 if (render_view_->webview()->mainFrame()->isWebRemoteFrame())
3206 return blink::WebString();
3208 // If we're in the middle of committing a load, the data source we need
3209 // will still be provisional.
3210 WebFrame* main_frame = render_view_->webview()->mainFrame();
3211 WebDataSource* data_source = NULL;
3212 if (main_frame->provisionalDataSource())
3213 data_source = main_frame->provisionalDataSource();
3214 else
3215 data_source = main_frame->dataSource();
3217 InternalDocumentStateData* internal_data = data_source ?
3218 InternalDocumentStateData::FromDataSource(data_source) : NULL;
3219 if (internal_data && internal_data->is_overriding_user_agent())
3220 return WebString::fromUTF8(
3221 render_view_->renderer_preferences_.user_agent_override);
3222 return blink::WebString();
3225 blink::WebString RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame* frame) {
3226 DCHECK(!frame_ || frame_ == frame);
3227 if (render_view_->renderer_preferences_.enable_do_not_track)
3228 return WebString::fromUTF8("1");
3229 return WebString();
3232 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame* frame,
3233 bool default_value) {
3234 DCHECK(!frame_ || frame_ == frame);
3235 if (!default_value)
3236 return false;
3238 bool blocked = true;
3239 render_view_->Send(new ViewHostMsg_Are3DAPIsBlocked(
3240 render_view_->GetRoutingID(),
3241 GURL(frame->top()->document().securityOrigin().toString()),
3242 THREE_D_API_TYPE_WEBGL,
3243 &blocked));
3244 return !blocked;
3247 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame* frame,
3248 int arb_robustness_status_code) {
3249 DCHECK(!frame_ || frame_ == frame);
3250 render_view_->Send(new ViewHostMsg_DidLose3DContext(
3251 GURL(frame->top()->document().securityOrigin().toString()),
3252 THREE_D_API_TYPE_WEBGL,
3253 arb_robustness_status_code));
3256 blink::WebScreenOrientationClient*
3257 RenderFrameImpl::webScreenOrientationClient() {
3258 if (!screen_orientation_dispatcher_)
3259 screen_orientation_dispatcher_ = new ScreenOrientationDispatcher(this);
3260 return screen_orientation_dispatcher_;
3263 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource& data_source) {
3264 ServiceWorkerNetworkProvider* provider =
3265 ServiceWorkerNetworkProvider::FromDocumentState(
3266 DocumentState::FromDataSource(&data_source));
3267 return provider->context()->controller_handle_id() !=
3268 kInvalidServiceWorkerHandleId;
3271 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject& obj,
3272 blink::WebAXEvent event) {
3273 HandleWebAccessibilityEvent(obj, event);
3276 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame* frame)
3278 DCHECK(!frame_ || frame_ == frame);
3280 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeManifest());
3283 void RenderFrameImpl::DidPlay(blink::WebMediaPlayer* player) {
3284 Send(new FrameHostMsg_MediaPlayingNotification(
3285 routing_id_, reinterpret_cast<int64>(player), player->hasVideo(),
3286 player->hasAudio(), player->isRemote()));
3289 void RenderFrameImpl::DidPause(blink::WebMediaPlayer* player) {
3290 Send(new FrameHostMsg_MediaPausedNotification(
3291 routing_id_, reinterpret_cast<int64>(player)));
3294 void RenderFrameImpl::PlayerGone(blink::WebMediaPlayer* player) {
3295 DidPause(player);
3298 void RenderFrameImpl::AddObserver(RenderFrameObserver* observer) {
3299 observers_.AddObserver(observer);
3302 void RenderFrameImpl::RemoveObserver(RenderFrameObserver* observer) {
3303 observer->RenderFrameGone();
3304 observers_.RemoveObserver(observer);
3307 void RenderFrameImpl::OnStop() {
3308 DCHECK(frame_);
3309 frame_->stopLoading();
3310 if (!frame_->parent())
3311 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers_, OnStop());
3313 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, OnStop());
3316 void RenderFrameImpl::WasHidden() {
3317 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WasHidden());
3320 void RenderFrameImpl::WasShown() {
3321 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WasShown());
3324 bool RenderFrameImpl::IsHidden() {
3325 return GetRenderWidget()->is_hidden();
3328 // Tell the embedding application that the URL of the active page has changed.
3329 void RenderFrameImpl::SendDidCommitProvisionalLoad(blink::WebFrame* frame) {
3330 DCHECK(!frame_ || frame_ == frame);
3331 WebDataSource* ds = frame->dataSource();
3332 DCHECK(ds);
3334 const WebURLRequest& request = ds->request();
3335 const WebURLResponse& response = ds->response();
3337 DocumentState* document_state = DocumentState::FromDataSource(ds);
3338 NavigationState* navigation_state = document_state->navigation_state();
3339 InternalDocumentStateData* internal_data =
3340 InternalDocumentStateData::FromDocumentState(document_state);
3342 FrameHostMsg_DidCommitProvisionalLoad_Params params;
3343 params.http_status_code = response.httpStatusCode();
3344 params.url_is_unreachable = ds->hasUnreachableURL();
3345 params.is_post = false;
3346 params.post_id = -1;
3347 params.page_id = render_view_->page_id_;
3348 // We need to track the RenderViewHost routing_id because of downstream
3349 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3350 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3351 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3352 // based on the ID stored in the resource requests. Once those dependencies
3353 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3354 // client to be based on the routing_id of the RenderFrameHost.
3355 params.render_view_routing_id = render_view_->routing_id();
3356 params.socket_address.set_host(response.remoteIPAddress().utf8());
3357 params.socket_address.set_port(response.remotePort());
3358 WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response);
3359 if (extra_data)
3360 params.was_fetched_via_proxy = extra_data->was_fetched_via_proxy();
3361 params.was_within_same_page = navigation_state->was_within_same_page();
3362 params.security_info = response.securityInfo();
3364 // Set the URL to be displayed in the browser UI to the user.
3365 params.url = GetLoadingUrl();
3366 DCHECK(!is_swapped_out_ || params.url == GURL(kSwappedOutURL));
3368 if (frame->document().baseURL() != params.url)
3369 params.base_url = frame->document().baseURL();
3371 GetRedirectChain(ds, &params.redirects);
3372 params.should_update_history = !ds->hasUnreachableURL() &&
3373 !response.isMultipartPayload() && (response.httpStatusCode() != 404);
3375 params.searchable_form_url = internal_data->searchable_form_url();
3376 params.searchable_form_encoding = internal_data->searchable_form_encoding();
3378 params.gesture = render_view_->navigation_gesture_;
3379 render_view_->navigation_gesture_ = NavigationGestureUnknown;
3381 // Make navigation state a part of the DidCommitProvisionalLoad message so
3382 // that commited entry has it at all times.
3383 HistoryEntry* entry = render_view_->history_controller()->GetCurrentEntry();
3384 if (entry)
3385 params.page_state = HistoryEntryToPageState(entry);
3386 else
3387 params.page_state = PageState::CreateFromURL(request.url());
3389 if (!frame->parent()) {
3390 // Top-level navigation.
3392 // Reset the zoom limits in case a plugin had changed them previously. This
3393 // will also call us back which will cause us to send a message to
3394 // update WebContentsImpl.
3395 render_view_->webview()->zoomLimitsChanged(
3396 ZoomFactorToZoomLevel(kMinimumZoomFactor),
3397 ZoomFactorToZoomLevel(kMaximumZoomFactor));
3399 // Set zoom level, but don't do it for full-page plugin since they don't use
3400 // the same zoom settings.
3401 HostZoomLevels::iterator host_zoom =
3402 render_view_->host_zoom_levels_.find(GURL(request.url()));
3403 if (render_view_->webview()->mainFrame()->document().isPluginDocument()) {
3404 // Reset the zoom levels for plugins.
3405 render_view_->webview()->setZoomLevel(0);
3406 } else {
3407 if (host_zoom != render_view_->host_zoom_levels_.end()) {
3408 render_view_->webview()->setZoomLevel(host_zoom->second);
3409 } else {
3410 // If the url was not found, we need to reset in case we are re-using
3411 // an existing RenderViewImpl, e.g. to show a network error page.
3412 render_view_->webview()->setZoomLevel(0);
3416 if (host_zoom != render_view_->host_zoom_levels_.end()) {
3417 // This zoom level was merely recorded transiently for this load. We can
3418 // erase it now. If at some point we reload this page, the browser will
3419 // send us a new, up-to-date zoom level.
3420 render_view_->host_zoom_levels_.erase(host_zoom);
3423 // Update contents MIME type for main frame.
3424 params.contents_mime_type = ds->response().mimeType().utf8();
3426 params.transition = navigation_state->transition_type();
3427 if (!ui::PageTransitionIsMainFrame(params.transition)) {
3428 // If the main frame does a load, it should not be reported as a subframe
3429 // navigation. This can occur in the following case:
3430 // 1. You're on a site with frames.
3431 // 2. You do a subframe navigation. This is stored with transition type
3432 // MANUAL_SUBFRAME.
3433 // 3. You navigate to some non-frame site, say, google.com.
3434 // 4. You navigate back to the page from step 2. Since it was initially
3435 // MANUAL_SUBFRAME, it will be that same transition type here.
3436 // We don't want that, because any navigation that changes the toplevel
3437 // frame should be tracked as a toplevel navigation (this allows us to
3438 // update the URL bar, etc).
3439 params.transition = ui::PAGE_TRANSITION_LINK;
3442 // If the page contained a client redirect (meta refresh, document.loc...),
3443 // set the referrer and transition appropriately.
3444 if (ds->isClientRedirect()) {
3445 params.referrer =
3446 Referrer(params.redirects[0], ds->request().referrerPolicy());
3447 params.transition = ui::PageTransitionFromInt(
3448 params.transition | ui::PAGE_TRANSITION_CLIENT_REDIRECT);
3449 } else {
3450 params.referrer = RenderViewImpl::GetReferrerFromRequest(
3451 frame, ds->request());
3454 base::string16 method = request.httpMethod();
3455 if (EqualsASCII(method, "POST")) {
3456 params.is_post = true;
3457 params.post_id = ExtractPostId(entry->root());
3460 // Send the user agent override back.
3461 params.is_overriding_user_agent = internal_data->is_overriding_user_agent();
3463 // Track the URL of the original request. We use the first entry of the
3464 // redirect chain if it exists because the chain may have started in another
3465 // process.
3466 params.original_request_url = GetOriginalRequestURL(ds);
3468 params.history_list_was_cleared =
3469 navigation_state->history_list_was_cleared();
3471 // Save some histogram data so we can compute the average memory used per
3472 // page load of the glyphs.
3473 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
3474 blink::WebGlyphCache::pageCount());
3476 // This message needs to be sent before any of allowScripts(),
3477 // allowImages(), allowPlugins() is called for the new page, so that when
3478 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
3479 // after the FrameHostMsg_DidCommitProvisionalLoad message.
3480 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params));
3481 } else {
3482 // Subframe navigation: the type depends on whether this navigation
3483 // generated a new session history entry. When they do generate a session
3484 // history entry, it means the user initiated the navigation and we should
3485 // mark it as such. This test checks if this is the first time
3486 // SendDidCommitProvisionalLoad has been called since WillNavigateToURL was
3487 // called to initiate the load.
3488 if (render_view_->page_id_ > render_view_->last_page_id_sent_to_browser_)
3489 params.transition = ui::PAGE_TRANSITION_MANUAL_SUBFRAME;
3490 else
3491 params.transition = ui::PAGE_TRANSITION_AUTO_SUBFRAME;
3493 DCHECK(!navigation_state->history_list_was_cleared());
3494 params.history_list_was_cleared = false;
3496 // Don't send this message while the subframe is swapped out.
3497 if (!is_swapped_out())
3498 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params));
3501 render_view_->last_page_id_sent_to_browser_ =
3502 std::max(render_view_->last_page_id_sent_to_browser_,
3503 render_view_->page_id_);
3505 // If we end up reusing this WebRequest (for example, due to a #ref click),
3506 // we don't want the transition type to persist. Just clear it.
3507 navigation_state->set_transition_type(ui::PAGE_TRANSITION_LINK);
3510 WebElement RenderFrameImpl::GetFocusedElement() {
3511 WebDocument doc = frame_->document();
3512 if (!doc.isNull())
3513 return doc.focusedElement();
3515 return WebElement();
3518 void RenderFrameImpl::didStartLoading(bool to_different_document) {
3519 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
3520 "id", routing_id_);
3521 render_view_->FrameDidStartLoading(frame_);
3522 Send(new FrameHostMsg_DidStartLoading(routing_id_, to_different_document));
3525 void RenderFrameImpl::didStopLoading() {
3526 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
3527 "id", routing_id_);
3528 render_view_->FrameDidStopLoading(frame_);
3529 Send(new FrameHostMsg_DidStopLoading(routing_id_));
3532 void RenderFrameImpl::didChangeLoadProgress(double load_progress) {
3533 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_, load_progress));
3536 void RenderFrameImpl::HandleWebAccessibilityEvent(
3537 const blink::WebAXObject& obj, blink::WebAXEvent event) {
3538 if (renderer_accessibility_)
3539 renderer_accessibility_->HandleWebAccessibilityEvent(obj, event);
3542 void RenderFrameImpl::FocusedNodeChanged(const WebNode& node) {
3543 if (renderer_accessibility_)
3544 renderer_accessibility_->FocusedNodeChanged(node);
3547 // PlzNavigate
3548 void RenderFrameImpl::OnRequestNavigation(
3549 const CommonNavigationParams& common_params,
3550 const RequestNavigationParams& request_params) {
3551 CHECK(CommandLine::ForCurrentProcess()->HasSwitch(
3552 switches::kEnableBrowserSideNavigation));
3554 // TODO(clamy): Execute the beforeunload event.
3556 WebURLRequest request =
3557 CreateURLRequestForNavigation(common_params,
3558 request_params,
3559 scoped_ptr<StreamOverrideParameters>(),
3560 frame_->isViewSourceModeEnabled());
3562 // Note: At this stage, the goal is to apply all the modifications the
3563 // renderer wants to make to the request, and then send it to the browser, so
3564 // that the actual network request can be started. Ideally, all such
3565 // modifications should take place in willSendRequest, and in the
3566 // implementation of willSendRequest for the various InspectorAgents
3567 // (devtools).
3569 // TODO(clamy): Apply devtools override.
3570 // TODO(clamy): Make sure that navigation requests are not modified somewhere
3571 // else in blink.
3572 willSendRequest(frame_, 0, request, blink::WebURLResponse());
3574 // TODO(clamy): Same-document navigations should not be sent back to the
3575 // browser.
3576 Send(new FrameHostMsg_BeginNavigation(routing_id_,
3577 MakeBeginNavigationParams(request),
3578 MakeCommonNavigationParams(request)));
3581 // PlzNavigate
3582 void RenderFrameImpl::OnCommitNavigation(
3583 const ResourceResponseHead& response,
3584 const GURL& stream_url,
3585 const CommonNavigationParams& common_params,
3586 const CommitNavigationParams& commit_params) {
3587 CHECK(CommandLine::ForCurrentProcess()->HasSwitch(
3588 switches::kEnableBrowserSideNavigation));
3589 bool is_reload = false;
3590 WebURLRequest::CachePolicy cache_policy =
3591 WebURLRequest::UseProtocolCachePolicy;
3592 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
3593 common_params.url, common_params.navigation_type,
3594 commit_params.page_state, false, -1, -1, &is_reload, &cache_policy)) {
3595 return;
3598 GetContentClient()->SetActiveURL(common_params.url);
3600 // Create a WebURLRequest that blink can use to get access to the body of the
3601 // response through a stream in the browser. Blink will then commit the
3602 // navigation.
3603 // TODO(clamy): Have the navigation commit directly, without going through
3604 // loading a WebURLRequest.
3605 scoped_ptr<StreamOverrideParameters> stream_override(
3606 new StreamOverrideParameters());
3607 stream_override->stream_url = stream_url;
3608 stream_override->response = response;
3609 WebURLRequest request =
3610 CreateURLRequestForNavigation(common_params,
3611 RequestNavigationParams(),
3612 stream_override.Pass(),
3613 frame_->isViewSourceModeEnabled());
3615 // Record this before starting the load. A lower bound of this time is needed
3616 // to sanitize the navigationStart override set below.
3617 base::TimeTicks renderer_navigation_start = base::TimeTicks::Now();
3618 frame_->loadRequest(request);
3619 UpdateFrameNavigationTiming(
3620 frame_, commit_params.browser_navigation_start,
3621 renderer_navigation_start);
3624 WebNavigationPolicy RenderFrameImpl::DecidePolicyForNavigation(
3625 RenderFrame* render_frame,
3626 const NavigationPolicyInfo& info) {
3627 #ifdef OS_ANDROID
3628 // The handlenavigation API is deprecated and will be removed once
3629 // crbug.com/325351 is resolved.
3630 if (info.urlRequest.url() != GURL(kSwappedOutURL) &&
3631 GetContentClient()->renderer()->HandleNavigation(
3632 render_frame,
3633 static_cast<DocumentState*>(info.extraData),
3634 render_view_->opener_id_,
3635 info.frame,
3636 info.urlRequest,
3637 info.navigationType,
3638 info.defaultPolicy,
3639 info.isRedirect)) {
3640 return blink::WebNavigationPolicyIgnore;
3642 #endif
3644 Referrer referrer(RenderViewImpl::GetReferrerFromRequest(info.frame,
3645 info.urlRequest));
3646 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
3648 bool is_subframe = !!info.frame->parent();
3650 if (command_line.HasSwitch(switches::kSitePerProcess) && is_subframe) {
3651 // There's no reason to ignore navigations on subframes, since the swap out
3652 // logic no longer applies.
3653 } else {
3654 if (is_swapped_out_ || render_view_->is_swapped_out()) {
3655 if (info.urlRequest.url() != GURL(kSwappedOutURL)) {
3656 // Targeted links may try to navigate a swapped out frame. Allow the
3657 // browser process to navigate the tab instead. Note that it is also
3658 // possible for non-targeted navigations (from this view) to arrive
3659 // here just after we are swapped out. It's ok to send them to the
3660 // browser, as long as they're for the top level frame.
3661 // TODO(creis): Ensure this supports targeted form submissions when
3662 // fixing http://crbug.com/101395.
3663 if (info.frame->parent() == NULL) {
3664 OpenURL(info.frame, info.urlRequest.url(), referrer,
3665 info.defaultPolicy);
3666 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
3669 // We should otherwise ignore in-process iframe navigations, if they
3670 // arrive just after we are swapped out.
3671 return blink::WebNavigationPolicyIgnore;
3674 // Allow kSwappedOutURL to complete.
3675 return info.defaultPolicy;
3679 // Webkit is asking whether to navigate to a new URL.
3680 // This is fine normally, except if we're showing UI from one security
3681 // context and they're trying to navigate to a different context.
3682 const GURL& url = info.urlRequest.url();
3684 // A content initiated navigation may have originated from a link-click,
3685 // script, drag-n-drop operation, etc.
3686 bool is_content_initiated = static_cast<DocumentState*>(info.extraData)->
3687 navigation_state()->is_content_initiated();
3689 // Experimental:
3690 // If --enable-strict-site-isolation is enabled, send all top-level
3691 // navigations to the browser to let it swap processes when crossing site
3692 // boundaries. This is currently expected to break some script calls and
3693 // navigations, such as form submissions.
3694 bool force_swap_due_to_flag =
3695 command_line.HasSwitch(switches::kEnableStrictSiteIsolation);
3696 if (force_swap_due_to_flag &&
3697 !info.frame->parent() && (is_content_initiated || info.isRedirect)) {
3698 WebString origin_str = info.frame->document().securityOrigin().toString();
3699 GURL frame_url(origin_str.utf8().data());
3700 // TODO(cevans): revisit whether this site check is still necessary once
3701 // crbug.com/101395 is fixed.
3702 bool same_domain_or_host =
3703 net::registry_controlled_domains::SameDomainOrHost(
3704 frame_url,
3705 url,
3706 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
3707 // Only keep same-site (domain + scheme) and data URLs in the same process.
3708 bool is_same_site =
3709 (same_domain_or_host && frame_url.scheme() == url.scheme()) ||
3710 url.SchemeIs(url::kDataScheme);
3711 if (!is_same_site) {
3712 OpenURL(info.frame, url, referrer, info.defaultPolicy);
3713 return blink::WebNavigationPolicyIgnore;
3717 // If the browser is interested, then give it a chance to look at the request.
3718 if (is_content_initiated) {
3719 bool is_form_post =
3720 ((info.navigationType == blink::WebNavigationTypeFormSubmitted) ||
3721 (info.navigationType == blink::WebNavigationTypeFormResubmitted)) &&
3722 EqualsASCII(info.urlRequest.httpMethod(), "POST");
3723 bool browser_handles_request =
3724 render_view_->renderer_preferences_
3725 .browser_handles_non_local_top_level_requests
3726 && IsNonLocalTopLevelNavigation(url, info.frame, info.navigationType,
3727 is_form_post);
3728 if (!browser_handles_request) {
3729 browser_handles_request = IsTopLevelNavigation(info.frame) &&
3730 render_view_->renderer_preferences_
3731 .browser_handles_all_top_level_requests;
3734 if (browser_handles_request) {
3735 OpenURL(info.frame, url, referrer, info.defaultPolicy);
3736 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
3740 // Use the frame's original request's URL rather than the document's URL for
3741 // subsequent checks. For a popup, the document's URL may become the opener
3742 // window's URL if the opener has called document.write().
3743 // See http://crbug.com/93517.
3744 GURL old_url(info.frame->dataSource()->request().url());
3746 // Detect when we're crossing a permission-based boundary (e.g. into or out of
3747 // an extension or app origin, leaving a WebUI page, etc). We only care about
3748 // top-level navigations (not iframes). But we sometimes navigate to
3749 // about:blank to clear a tab, and we want to still allow that.
3751 // Note: this is known to break POST submissions when crossing process
3752 // boundaries until http://crbug.com/101395 is fixed. This is better for
3753 // security than loading a WebUI, extension or app page in the wrong process.
3754 // POST requests don't work because this mechanism does not preserve form
3755 // POST data. We will need to send the request's httpBody data up to the
3756 // browser process, and issue a special POST navigation in WebKit (via
3757 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
3758 // for examples of how to send the httpBody data.
3759 if (!info.frame->parent() && is_content_initiated &&
3760 !url.SchemeIs(url::kAboutScheme)) {
3761 bool send_referrer = false;
3763 // All navigations to or from WebUI URLs or within WebUI-enabled
3764 // RenderProcesses must be handled by the browser process so that the
3765 // correct bindings and data sources can be registered.
3766 // Similarly, navigations to view-source URLs or within ViewSource mode
3767 // must be handled by the browser process (except for reloads - those are
3768 // safe to leave within the renderer).
3769 // Lastly, access to file:// URLs from non-file:// URL pages must be
3770 // handled by the browser so that ordinary renderer processes don't get
3771 // blessed with file permissions.
3772 int cumulative_bindings = RenderProcess::current()->GetEnabledBindings();
3773 bool is_initial_navigation = render_view_->page_id_ == -1;
3774 bool should_fork = HasWebUIScheme(url) || HasWebUIScheme(old_url) ||
3775 (cumulative_bindings & BINDINGS_POLICY_WEB_UI) ||
3776 url.SchemeIs(kViewSourceScheme) ||
3777 (info.frame->isViewSourceModeEnabled() &&
3778 info.navigationType != blink::WebNavigationTypeReload);
3780 if (!should_fork && url.SchemeIs(url::kFileScheme)) {
3781 // Fork non-file to file opens. Check the opener URL if this is the
3782 // initial navigation in a newly opened window.
3783 GURL source_url(old_url);
3784 if (is_initial_navigation && source_url.is_empty() &&
3785 info.frame->opener())
3786 source_url = info.frame->opener()->top()->document().url();
3787 DCHECK(!source_url.is_empty());
3788 should_fork = !source_url.SchemeIs(url::kFileScheme);
3791 if (!should_fork) {
3792 // Give the embedder a chance.
3793 should_fork = GetContentClient()->renderer()->ShouldFork(
3794 info.frame, url, info.urlRequest.httpMethod().utf8(),
3795 is_initial_navigation, info.isRedirect, &send_referrer);
3798 if (should_fork) {
3799 OpenURL(info.frame, url, send_referrer ? referrer : Referrer(),
3800 info.defaultPolicy);
3801 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
3805 // Detect when a page is "forking" a new tab that can be safely rendered in
3806 // its own process. This is done by sites like Gmail that try to open links
3807 // in new windows without script connections back to the original page. We
3808 // treat such cases as browser navigations (in which we will create a new
3809 // renderer for a cross-site navigation), rather than WebKit navigations.
3811 // We use the following heuristic to decide whether to fork a new page in its
3812 // own process:
3813 // The parent page must open a new tab to about:blank, set the new tab's
3814 // window.opener to null, and then redirect the tab to a cross-site URL using
3815 // JavaScript.
3817 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
3818 // (see below).
3819 bool is_fork =
3820 // Must start from a tab showing about:blank, which is later redirected.
3821 old_url == GURL(url::kAboutBlankURL) &&
3822 // Must be the first real navigation of the tab.
3823 render_view_->historyBackListCount() < 1 &&
3824 render_view_->historyForwardListCount() < 1 &&
3825 // The parent page must have set the child's window.opener to null before
3826 // redirecting to the desired URL.
3827 info.frame->opener() == NULL &&
3828 // Must be a top-level frame.
3829 info.frame->parent() == NULL &&
3830 // Must not have issued the request from this page.
3831 is_content_initiated &&
3832 // Must be targeted at the current tab.
3833 info.defaultPolicy == blink::WebNavigationPolicyCurrentTab &&
3834 // Must be a JavaScript navigation, which appears as "other".
3835 info.navigationType == blink::WebNavigationTypeOther;
3837 if (is_fork) {
3838 // Open the URL via the browser, not via WebKit.
3839 OpenURL(info.frame, url, Referrer(), info.defaultPolicy);
3840 return blink::WebNavigationPolicyIgnore;
3843 return info.defaultPolicy;
3846 void RenderFrameImpl::OpenURL(WebFrame* frame,
3847 const GURL& url,
3848 const Referrer& referrer,
3849 WebNavigationPolicy policy) {
3850 DCHECK_EQ(frame_, frame);
3852 FrameHostMsg_OpenURL_Params params;
3853 params.url = url;
3854 params.referrer = referrer;
3855 params.disposition = RenderViewImpl::NavigationPolicyToDisposition(policy);
3856 WebDataSource* ds = frame->provisionalDataSource();
3857 if (ds) {
3858 DocumentState* document_state = DocumentState::FromDataSource(ds);
3859 NavigationState* navigation_state = document_state->navigation_state();
3860 if (navigation_state->is_content_initiated()) {
3861 params.should_replace_current_entry = ds->replacesCurrentHistoryItem();
3862 } else {
3863 // This is necessary to preserve the should_replace_current_entry value on
3864 // cross-process redirects, in the event it was set by a previous process.
3866 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3867 // NavigationState::should_replace_current_entry().
3868 params.should_replace_current_entry =
3869 navigation_state->should_replace_current_entry();
3871 } else {
3872 params.should_replace_current_entry = false;
3874 params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
3875 if (GetContentClient()->renderer()->AllowPopup())
3876 params.user_gesture = true;
3878 if (policy == blink::WebNavigationPolicyNewBackgroundTab ||
3879 policy == blink::WebNavigationPolicyNewForegroundTab ||
3880 policy == blink::WebNavigationPolicyNewWindow ||
3881 policy == blink::WebNavigationPolicyNewPopup) {
3882 WebUserGestureIndicator::consumeUserGesture();
3885 Send(new FrameHostMsg_OpenURL(routing_id_, params));
3888 void RenderFrameImpl::UpdateEncoding(WebFrame* frame,
3889 const std::string& encoding_name) {
3890 // Only update main frame's encoding_name.
3891 if (!frame->parent())
3892 Send(new FrameHostMsg_UpdateEncoding(routing_id_, encoding_name));
3895 void RenderFrameImpl::SyncSelectionIfRequired() {
3896 base::string16 text;
3897 size_t offset;
3898 gfx::Range range;
3899 #if defined(ENABLE_PLUGINS)
3900 if (render_view_->focused_pepper_plugin_) {
3901 render_view_->focused_pepper_plugin_->GetSurroundingText(&text, &range);
3902 offset = 0; // Pepper API does not support offset reporting.
3903 // TODO(kinaba): cut as needed.
3904 } else
3905 #endif
3907 size_t location, length;
3908 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
3909 &location, &length)) {
3910 return;
3913 range = gfx::Range(location, location + length);
3915 if (GetRenderWidget()->webwidget()->textInputInfo().type !=
3916 blink::WebTextInputTypeNone) {
3917 // If current focused element is editable, we will send 100 more chars
3918 // before and after selection. It is for input method surrounding text
3919 // feature.
3920 if (location > kExtraCharsBeforeAndAfterSelection)
3921 offset = location - kExtraCharsBeforeAndAfterSelection;
3922 else
3923 offset = 0;
3924 length = location + length - offset + kExtraCharsBeforeAndAfterSelection;
3925 WebRange webrange = WebRange::fromDocumentRange(frame_, offset, length);
3926 if (!webrange.isNull())
3927 text = WebRange::fromDocumentRange(
3928 frame_, offset, length).toPlainText();
3929 } else {
3930 offset = location;
3931 text = frame_->selectionAsText();
3932 // http://crbug.com/101435
3933 // In some case, frame->selectionAsText() returned text's length is not
3934 // equal to the length returned from webwidget()->caretOrSelectionRange().
3935 // So we have to set the range according to text.length().
3936 range.set_end(range.start() + text.length());
3940 // Sometimes we get repeated didChangeSelection calls from webkit when
3941 // the selection hasn't actually changed. We don't want to report these
3942 // because it will cause us to continually claim the X clipboard.
3943 if (selection_text_offset_ != offset ||
3944 selection_range_ != range ||
3945 selection_text_ != text) {
3946 selection_text_ = text;
3947 selection_text_offset_ = offset;
3948 selection_range_ = range;
3949 SetSelectedText(text, offset, range);
3951 GetRenderWidget()->UpdateSelectionBounds();
3954 void RenderFrameImpl::InitializeUserMediaClient() {
3955 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
3956 return;
3958 #if defined(OS_ANDROID)
3959 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableWebRTC))
3960 return;
3961 #endif
3963 #if defined(ENABLE_WEBRTC)
3964 DCHECK(!web_user_media_client_);
3965 web_user_media_client_ = new UserMediaClientImpl(
3966 this,
3967 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
3968 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
3969 #endif
3972 WebMediaPlayer* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
3973 const blink::WebURL& url,
3974 WebMediaPlayerClient* client) {
3975 #if defined(ENABLE_WEBRTC)
3976 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
3977 bool found_neon =
3978 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0;
3979 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon);
3980 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
3981 return new WebMediaPlayerMS(frame_, client, weak_factory_.GetWeakPtr(),
3982 new RenderMediaLog(),
3983 CreateRendererFactory());
3984 #else
3985 return NULL;
3986 #endif // defined(ENABLE_WEBRTC)
3989 scoped_ptr<MediaStreamRendererFactory>
3990 RenderFrameImpl::CreateRendererFactory() {
3991 #if defined(ENABLE_WEBRTC)
3992 return scoped_ptr<MediaStreamRendererFactory>(
3993 new MediaStreamRendererFactory());
3994 #else
3995 return scoped_ptr<MediaStreamRendererFactory>(
3996 static_cast<MediaStreamRendererFactory*>(NULL));
3997 #endif
4000 bool RenderFrameImpl::PrepareRenderViewForNavigation(
4001 const GURL& url,
4002 FrameMsg_Navigate_Type::Value navigate_type,
4003 const PageState& state,
4004 bool check_history,
4005 int pending_history_list_offset,
4006 int32 page_id,
4007 bool* is_reload,
4008 WebURLRequest::CachePolicy* cache_policy) {
4009 MaybeHandleDebugURL(url);
4010 if (!render_view_->webview())
4011 return false;
4013 FOR_EACH_OBSERVER(
4014 RenderViewObserver, render_view_->observers_, Navigate(url));
4016 // If this is a stale back/forward (due to a recent navigation the browser
4017 // didn't know about), ignore it.
4018 if (check_history && render_view_->IsBackForwardToStaleEntry(
4019 state, pending_history_list_offset, page_id, *is_reload))
4020 return false;
4022 if (!render_view_->is_swapped_out_ ||
4023 GetWebFrame() != render_view_->webview()->mainFrame())
4024 return true;
4026 // This is a swapped out main frame, so swap the renderer back in.
4027 // We marked the view as hidden when swapping the view out, so be sure to
4028 // reset the visibility state before navigating to the new URL.
4029 render_view_->webview()->setVisibilityState(
4030 render_view_->visibilityState(), false);
4032 // If this is an attempt to reload while we are swapped out, we should not
4033 // reload swappedout://, but the previous page, which is stored in
4034 // params.state. Setting is_reload to false will treat this like a back
4035 // navigation to accomplish that.
4036 *is_reload = false;
4037 *cache_policy = WebURLRequest::ReloadIgnoringCacheData;
4039 // We refresh timezone when a view is swapped in since timezone
4040 // can get out of sync when the system timezone is updated while
4041 // the view is swapped out.
4042 RenderThreadImpl::NotifyTimezoneChange();
4044 render_view_->SetSwappedOut(false);
4045 is_swapped_out_ = false;
4046 return true;
4049 GURL RenderFrameImpl::GetLoadingUrl() const {
4050 WebDataSource* ds = frame_->dataSource();
4051 if (ds->hasUnreachableURL())
4052 return ds->unreachableURL();
4054 const WebURLRequest& request = ds->request();
4055 return request.url();
4058 #if defined(OS_ANDROID)
4060 WebMediaPlayer* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4061 const blink::WebURL& url,
4062 WebMediaPlayerClient* client,
4063 blink::WebContentDecryptionModule* initial_cdm) {
4064 GpuChannelHost* gpu_channel_host =
4065 RenderThreadImpl::current()->EstablishGpuChannelSync(
4066 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE);
4067 if (!gpu_channel_host) {
4068 LOG(ERROR) << "Failed to establish GPU channel for media player";
4069 return NULL;
4072 scoped_refptr<StreamTextureFactory> stream_texture_factory;
4073 if (SynchronousCompositorFactory* factory =
4074 SynchronousCompositorFactory::GetInstance()) {
4075 stream_texture_factory = factory->CreateStreamTextureFactory(routing_id_);
4076 } else {
4077 scoped_refptr<webkit::gpu::ContextProviderWebContext> context_provider =
4078 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4080 if (!context_provider.get()) {
4081 LOG(ERROR) << "Failed to get context3d for media player";
4082 return NULL;
4085 stream_texture_factory = StreamTextureFactoryImpl::Create(
4086 context_provider, gpu_channel_host, routing_id_);
4089 return new WebMediaPlayerAndroid(
4090 frame_,
4091 client,
4092 weak_factory_.GetWeakPtr(),
4093 GetMediaPlayerManager(),
4094 GetCdmManager(),
4095 initial_cdm,
4096 stream_texture_factory,
4097 RenderThreadImpl::current()->GetMediaThreadTaskRunner(),
4098 new RenderMediaLog());
4101 RendererMediaPlayerManager* RenderFrameImpl::GetMediaPlayerManager() {
4102 if (!media_player_manager_)
4103 media_player_manager_ = new RendererMediaPlayerManager(this);
4104 return media_player_manager_;
4107 #endif // defined(OS_ANDROID)
4109 #if defined(ENABLE_BROWSER_CDMS)
4110 RendererCdmManager* RenderFrameImpl::GetCdmManager() {
4111 if (!cdm_manager_)
4112 cdm_manager_ = new RendererCdmManager(this);
4113 return cdm_manager_;
4115 #endif // defined(ENABLE_BROWSER_CDMS)
4117 } // namespace content