Mac: Fix performance issues with remote CoreAnimation
[chromium-blink-merge.git] / content / renderer / render_frame_impl.cc
blob64c5c761366d0308cce9498218eaa719155b2e04
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_handle_reference.h"
27 #include "content/child/service_worker/service_worker_network_provider.h"
28 #include "content/child/service_worker/service_worker_provider_context.h"
29 #include "content/child/service_worker/web_service_worker_provider_impl.h"
30 #include "content/child/web_url_loader_impl.h"
31 #include "content/child/web_url_request_util.h"
32 #include "content/child/webmessageportchannel_impl.h"
33 #include "content/child/websocket_bridge.h"
34 #include "content/child/weburlresponse_extradata_impl.h"
35 #include "content/common/clipboard_messages.h"
36 #include "content/common/frame_messages.h"
37 #include "content/common/input_messages.h"
38 #include "content/common/service_worker/service_worker_types.h"
39 #include "content/common/swapped_out_messages.h"
40 #include "content/common/view_messages.h"
41 #include "content/public/common/bindings_policy.h"
42 #include "content/public/common/content_constants.h"
43 #include "content/public/common/content_switches.h"
44 #include "content/public/common/context_menu_params.h"
45 #include "content/public/common/page_state.h"
46 #include "content/public/common/resource_response.h"
47 #include "content/public/common/url_constants.h"
48 #include "content/public/common/url_utils.h"
49 #include "content/public/renderer/browser_plugin_delegate.h"
50 #include "content/public/renderer/content_renderer_client.h"
51 #include "content/public/renderer/context_menu_client.h"
52 #include "content/public/renderer/document_state.h"
53 #include "content/public/renderer/navigation_state.h"
54 #include "content/public/renderer/render_frame_observer.h"
55 #include "content/public/renderer/renderer_ppapi_host.h"
56 #include "content/renderer/accessibility/renderer_accessibility.h"
57 #include "content/renderer/browser_plugin/browser_plugin.h"
58 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
59 #include "content/renderer/child_frame_compositing_helper.h"
60 #include "content/renderer/context_menu_params_builder.h"
61 #include "content/renderer/devtools/devtools_agent.h"
62 #include "content/renderer/dom_automation_controller.h"
63 #include "content/renderer/dom_utils.h"
64 #include "content/renderer/external_popup_menu.h"
65 #include "content/renderer/geolocation_dispatcher.h"
66 #include "content/renderer/history_controller.h"
67 #include "content/renderer/history_serialization.h"
68 #include "content/renderer/image_loading_helper.h"
69 #include "content/renderer/ime_event_guard.h"
70 #include "content/renderer/internal_document_state_data.h"
71 #include "content/renderer/manifest/manifest_manager.h"
72 #include "content/renderer/media/audio_renderer_mixer_manager.h"
73 #include "content/renderer/media/crypto/render_cdm_factory.h"
74 #include "content/renderer/media/media_stream_dispatcher.h"
75 #include "content/renderer/media/media_stream_renderer_factory.h"
76 #include "content/renderer/media/midi_dispatcher.h"
77 #include "content/renderer/media/render_media_log.h"
78 #include "content/renderer/media/user_media_client_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/npapi/plugin_channel_host.h"
83 #include "content/renderer/push_messaging_dispatcher.h"
84 #include "content/renderer/render_frame_proxy.h"
85 #include "content/renderer/render_process.h"
86 #include "content/renderer/render_thread_impl.h"
87 #include "content/renderer/render_view_impl.h"
88 #include "content/renderer/render_widget_fullscreen_pepper.h"
89 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
90 #include "content/renderer/renderer_webcolorchooser_impl.h"
91 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
92 #include "content/renderer/shared_worker_repository.h"
93 #include "content/renderer/v8_value_converter_impl.h"
94 #include "content/renderer/websharedworker_proxy.h"
95 #include "gin/modules/module_registry.h"
96 #include "media/base/audio_renderer_mixer_input.h"
97 #include "media/base/renderer.h"
98 #include "media/blink/encrypted_media_player_support.h"
99 #include "media/blink/webcontentdecryptionmodule_impl.h"
100 #include "media/blink/webmediaplayer_impl.h"
101 #include "media/blink/webmediaplayer_params.h"
102 #include "media/filters/gpu_video_accelerator_factories.h"
103 #include "mojo/edk/js/core.h"
104 #include "mojo/edk/js/support.h"
105 #include "net/base/data_url.h"
106 #include "net/base/net_errors.h"
107 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
108 #include "net/http/http_util.h"
109 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
110 #include "third_party/WebKit/public/platform/WebString.h"
111 #include "third_party/WebKit/public/platform/WebURL.h"
112 #include "third_party/WebKit/public/platform/WebURLError.h"
113 #include "third_party/WebKit/public/platform/WebURLResponse.h"
114 #include "third_party/WebKit/public/platform/WebVector.h"
115 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
116 #include "third_party/WebKit/public/web/WebDocument.h"
117 #include "third_party/WebKit/public/web/WebGlyphCache.h"
118 #include "third_party/WebKit/public/web/WebLocalFrame.h"
119 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
120 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
121 #include "third_party/WebKit/public/web/WebPlugin.h"
122 #include "third_party/WebKit/public/web/WebPluginParams.h"
123 #include "third_party/WebKit/public/web/WebPluginPlaceholder.h"
124 #include "third_party/WebKit/public/web/WebRange.h"
125 #include "third_party/WebKit/public/web/WebScriptSource.h"
126 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
127 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
128 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
129 #include "third_party/WebKit/public/web/WebSurroundingText.h"
130 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
131 #include "third_party/WebKit/public/web/WebView.h"
133 #if defined(ENABLE_PLUGINS)
134 #include "content/renderer/npapi/webplugin_impl.h"
135 #include "content/renderer/pepper/pepper_browser_connection.h"
136 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
137 #include "content/renderer/pepper/pepper_webplugin_impl.h"
138 #include "content/renderer/pepper/plugin_module.h"
139 #include "content/renderer/pepper/plugin_power_saver_helper.h"
140 #endif
142 #if defined(ENABLE_WEBRTC)
143 #include "content/renderer/media/rtc_peer_connection_handler.h"
144 #endif
146 #if defined(OS_ANDROID)
147 #include <cpu-features.h>
149 #include "content/common/gpu/client/context_provider_command_buffer.h"
150 #include "content/renderer/android/synchronous_compositor_factory.h"
151 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
152 #include "content/renderer/media/android/renderer_media_player_manager.h"
153 #include "content/renderer/media/android/stream_texture_factory_impl.h"
154 #include "content/renderer/media/android/webmediaplayer_android.h"
155 #endif
157 #if defined(ENABLE_PEPPER_CDMS)
158 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
159 #elif defined(ENABLE_BROWSER_CDMS)
160 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
161 #endif
163 using blink::WebContextMenuData;
164 using blink::WebData;
165 using blink::WebDataSource;
166 using blink::WebDocument;
167 using blink::WebElement;
168 using blink::WebExternalPopupMenu;
169 using blink::WebExternalPopupMenuClient;
170 using blink::WebFrame;
171 using blink::WebHistoryItem;
172 using blink::WebHTTPBody;
173 using blink::WebLocalFrame;
174 using blink::WebMediaPlayer;
175 using blink::WebMediaPlayerClient;
176 using blink::WebNavigationPolicy;
177 using blink::WebNavigationType;
178 using blink::WebNode;
179 using blink::WebPluginParams;
180 using blink::WebPopupMenuInfo;
181 using blink::WebRange;
182 using blink::WebReferrerPolicy;
183 using blink::WebScriptSource;
184 using blink::WebSearchableFormData;
185 using blink::WebSecurityOrigin;
186 using blink::WebSecurityPolicy;
187 using blink::WebServiceWorkerProvider;
188 using blink::WebStorageQuotaCallbacks;
189 using blink::WebString;
190 using blink::WebURL;
191 using blink::WebURLError;
192 using blink::WebURLRequest;
193 using blink::WebURLResponse;
194 using blink::WebUserGestureIndicator;
195 using blink::WebVector;
196 using blink::WebView;
197 using base::Time;
198 using base::TimeDelta;
200 namespace content {
202 namespace {
204 const char kDefaultAcceptHeader[] =
205 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
206 "*;q=0.8";
207 const char kAcceptHeader[] = "Accept";
209 const size_t kExtraCharsBeforeAndAfterSelection = 100;
211 typedef std::map<int, RenderFrameImpl*> RoutingIDFrameMap;
212 static base::LazyInstance<RoutingIDFrameMap> g_routing_id_frame_map =
213 LAZY_INSTANCE_INITIALIZER;
215 typedef std::map<blink::WebFrame*, RenderFrameImpl*> FrameMap;
216 base::LazyInstance<FrameMap> g_frame_map = LAZY_INSTANCE_INITIALIZER;
218 int64 ExtractPostId(const WebHistoryItem& item) {
219 if (item.isNull())
220 return -1;
222 if (item.httpBody().isNull())
223 return -1;
225 return item.httpBody().identifier();
228 WebURLResponseExtraDataImpl* GetExtraDataFromResponse(
229 const WebURLResponse& response) {
230 return static_cast<WebURLResponseExtraDataImpl*>(response.extraData());
233 void GetRedirectChain(WebDataSource* ds, std::vector<GURL>* result) {
234 // Replace any occurrences of swappedout:// with about:blank.
235 const WebURL& blank_url = GURL(url::kAboutBlankURL);
236 WebVector<WebURL> urls;
237 ds->redirectChain(urls);
238 result->reserve(urls.size());
239 for (size_t i = 0; i < urls.size(); ++i) {
240 if (urls[i] != GURL(kSwappedOutURL))
241 result->push_back(urls[i]);
242 else
243 result->push_back(blank_url);
247 // Returns the original request url. If there is no redirect, the original
248 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
249 // frame was loaded by loadData, the original url will be ds->unreachableURL()
250 static GURL GetOriginalRequestURL(WebDataSource* ds) {
251 // WebDataSource has unreachable URL means that the frame is loaded through
252 // blink::WebFrame::loadData(), and the base URL will be in the redirect
253 // chain. However, we never visited the baseURL. So in this case, we should
254 // use the unreachable URL as the original URL.
255 if (ds->hasUnreachableURL())
256 return ds->unreachableURL();
258 std::vector<GURL> redirects;
259 GetRedirectChain(ds, &redirects);
260 if (!redirects.empty())
261 return redirects.at(0);
263 return ds->originalRequest().url();
266 NOINLINE static void CrashIntentionally() {
267 // NOTE(shess): Crash directly rather than using NOTREACHED() so
268 // that the signature is easier to triage in crash reports.
269 volatile int* zero = NULL;
270 *zero = 0;
273 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
274 NOINLINE static void MaybeTriggerAsanError(const GURL& url) {
275 // NOTE(rogerm): We intentionally perform an invalid heap access here in
276 // order to trigger an Address Sanitizer (ASAN) error report.
277 const char kCrashDomain[] = "crash";
278 const char kHeapOverflow[] = "/heap-overflow";
279 const char kHeapUnderflow[] = "/heap-underflow";
280 const char kUseAfterFree[] = "/use-after-free";
281 #if defined(SYZYASAN)
282 const char kCorruptHeapBlock[] = "/corrupt-heap-block";
283 const char kCorruptHeap[] = "/corrupt-heap";
284 #endif
286 if (!url.DomainIs(kCrashDomain, sizeof(kCrashDomain) - 1))
287 return;
289 if (!url.has_path())
290 return;
292 std::string crash_type(url.path());
293 if (crash_type == kHeapOverflow) {
294 base::debug::AsanHeapOverflow();
295 } else if (crash_type == kHeapUnderflow ) {
296 base::debug::AsanHeapUnderflow();
297 } else if (crash_type == kUseAfterFree) {
298 base::debug::AsanHeapUseAfterFree();
299 #if defined(SYZYASAN)
300 } else if (crash_type == kCorruptHeapBlock) {
301 base::debug::AsanCorruptHeapBlock();
302 } else if (crash_type == kCorruptHeap) {
303 base::debug::AsanCorruptHeap();
304 #endif
307 #endif // ADDRESS_SANITIZER || SYZYASAN
309 static void MaybeHandleDebugURL(const GURL& url) {
310 if (!url.SchemeIs(kChromeUIScheme))
311 return;
312 if (url == GURL(kChromeUICrashURL)) {
313 CrashIntentionally();
314 } else if (url == GURL(kChromeUIDumpURL)) {
315 // This URL will only correctly create a crash dump file if content is
316 // hosted in a process that has correctly called
317 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
318 // of base::debug::DumpWithoutCrashing for more details.
319 base::debug::DumpWithoutCrashing();
320 } else if (url == GURL(kChromeUIKillURL)) {
321 base::KillProcess(base::GetCurrentProcessHandle(), 1, false);
322 } else if (url == GURL(kChromeUIHangURL)) {
323 for (;;) {
324 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
326 } else if (url == GURL(kChromeUIShorthangURL)) {
327 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
330 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
331 MaybeTriggerAsanError(url);
332 #endif // ADDRESS_SANITIZER || SYZYASAN
335 // Returns false unless this is a top-level navigation.
336 static bool IsTopLevelNavigation(WebFrame* frame) {
337 return frame->parent() == NULL;
340 // Returns false unless this is a top-level navigation that crosses origins.
341 static bool IsNonLocalTopLevelNavigation(const GURL& url,
342 WebFrame* frame,
343 WebNavigationType type,
344 bool is_form_post) {
345 if (!IsTopLevelNavigation(frame))
346 return false;
348 // Navigations initiated within Webkit are not sent out to the external host
349 // in the following cases.
350 // 1. The url scheme is not http/https
351 // 2. The origin of the url and the opener is the same in which case the
352 // opener relationship is maintained.
353 // 3. Reloads/form submits/back forward navigations
354 if (!url.SchemeIs(url::kHttpScheme) && !url.SchemeIs(url::kHttpsScheme))
355 return false;
357 if (type != blink::WebNavigationTypeReload &&
358 type != blink::WebNavigationTypeBackForward && !is_form_post) {
359 // The opener relationship between the new window and the parent allows the
360 // new window to script the parent and vice versa. This is not allowed if
361 // the origins of the two domains are different. This can be treated as a
362 // top level navigation and routed back to the host.
363 blink::WebFrame* opener = frame->opener();
364 if (!opener)
365 return true;
367 if (url.GetOrigin() != GURL(opener->document().url()).GetOrigin())
368 return true;
370 return false;
373 WebURLRequest CreateURLRequestForNavigation(
374 const CommonNavigationParams& common_params,
375 const RequestNavigationParams& request_params,
376 scoped_ptr<StreamOverrideParameters> stream_override,
377 bool is_view_source_mode_enabled) {
378 WebURLRequest request(common_params.url);
379 if (is_view_source_mode_enabled)
380 request.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad);
382 if (common_params.referrer.url.is_valid()) {
383 WebString web_referrer = WebSecurityPolicy::generateReferrerHeader(
384 common_params.referrer.policy,
385 common_params.url,
386 WebString::fromUTF8(common_params.referrer.url.spec()));
387 if (!web_referrer.isEmpty())
388 request.setHTTPReferrer(web_referrer, common_params.referrer.policy);
391 if (!request_params.extra_headers.empty()) {
392 for (net::HttpUtil::HeadersIterator i(request_params.extra_headers.begin(),
393 request_params.extra_headers.end(),
394 "\n");
395 i.GetNext();) {
396 request.addHTTPHeaderField(WebString::fromUTF8(i.name()),
397 WebString::fromUTF8(i.values()));
401 if (request_params.is_post) {
402 request.setHTTPMethod(WebString::fromUTF8("POST"));
404 // Set post data.
405 WebHTTPBody http_body;
406 http_body.initialize();
407 const char* data = NULL;
408 if (request_params.browser_initiated_post_data.size()) {
409 data = reinterpret_cast<const char*>(
410 &request_params.browser_initiated_post_data.front());
412 http_body.appendData(
413 WebData(data, request_params.browser_initiated_post_data.size()));
414 request.setHTTPBody(http_body);
417 RequestExtraData* extra_data = new RequestExtraData();
418 extra_data->set_stream_override(stream_override.Pass());
419 request.setExtraData(extra_data);
420 return request;
423 void UpdateFrameNavigationTiming(WebFrame* frame,
424 base::TimeTicks browser_navigation_start,
425 base::TimeTicks renderer_navigation_start) {
426 // The browser provides the navigation_start time to bootstrap the
427 // Navigation Timing information for the browser-initiated navigations. In
428 // case of cross-process navigations, this carries over the time of
429 // finishing the onbeforeunload handler of the previous page.
430 DCHECK(!browser_navigation_start.is_null());
431 if (frame->provisionalDataSource()) {
432 // |browser_navigation_start| is likely before this process existed, so we
433 // can't use InterProcessTimeTicksConverter. We need at least to ensure
434 // that the browser-side navigation start we set is not later than the one
435 // on the renderer side.
436 base::TimeTicks navigation_start = std::min(
437 browser_navigation_start, renderer_navigation_start);
438 double navigation_start_seconds =
439 (navigation_start - base::TimeTicks()).InSecondsF();
440 frame->provisionalDataSource()->setNavigationStartTime(
441 navigation_start_seconds);
442 // TODO(clamy): We need to provide additional timing values for the
443 // Navigation Timing API to work with browser-side navigations.
447 // PlzNavigate
448 FrameHostMsg_BeginNavigation_Params MakeBeginNavigationParams(
449 blink::WebURLRequest* request) {
450 FrameHostMsg_BeginNavigation_Params params;
451 params.method = request->httpMethod().latin1();
452 params.headers = GetWebURLRequestHeaders(*request);
453 params.load_flags = GetLoadFlagsForWebURLRequest(*request);
454 // TODO(clamy): fill the http body.
455 params.has_user_gesture = request->hasUserGesture();
456 return params;
459 // PlzNavigate
460 CommonNavigationParams MakeCommonNavigationParams(
461 blink::WebURLRequest* request) {
462 const RequestExtraData kEmptyData;
463 const RequestExtraData* extra_data =
464 static_cast<RequestExtraData*>(request->extraData());
465 if (!extra_data)
466 extra_data = &kEmptyData;
467 CommonNavigationParams params;
468 params.url = request->url();
469 params.referrer = Referrer(
470 GURL(request->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
471 request->referrerPolicy());
472 params.transition = extra_data->transition_type();
473 return params;
476 } // namespace
478 static RenderFrameImpl* (*g_create_render_frame_impl)(RenderViewImpl*, int32) =
479 NULL;
481 // static
482 RenderFrameImpl* RenderFrameImpl::Create(RenderViewImpl* render_view,
483 int32 routing_id) {
484 DCHECK(routing_id != MSG_ROUTING_NONE);
486 if (g_create_render_frame_impl)
487 return g_create_render_frame_impl(render_view, routing_id);
488 else
489 return new RenderFrameImpl(render_view, routing_id);
492 // static
493 RenderFrameImpl* RenderFrameImpl::FromRoutingID(int32 routing_id) {
494 RoutingIDFrameMap::iterator iter =
495 g_routing_id_frame_map.Get().find(routing_id);
496 if (iter != g_routing_id_frame_map.Get().end())
497 return iter->second;
498 return NULL;
501 // static
502 void RenderFrameImpl::CreateFrame(int routing_id,
503 int parent_routing_id,
504 int proxy_routing_id) {
505 // TODO(nasko): For now, this message is only sent for subframes, as the
506 // top level frame is created when the RenderView is created through the
507 // ViewMsg_New IPC.
508 CHECK_NE(MSG_ROUTING_NONE, parent_routing_id);
510 blink::WebLocalFrame* web_frame;
511 RenderFrameImpl* render_frame;
512 if (proxy_routing_id == MSG_ROUTING_NONE) {
513 RenderFrameProxy* parent_proxy =
514 RenderFrameProxy::FromRoutingID(parent_routing_id);
515 // If the browser is sending a valid parent routing id, it should already
516 // be created and registered.
517 CHECK(parent_proxy);
518 blink::WebRemoteFrame* parent_web_frame = parent_proxy->web_frame();
520 // Create the RenderFrame and WebLocalFrame, linking the two.
521 render_frame =
522 RenderFrameImpl::Create(parent_proxy->render_view(), routing_id);
523 web_frame = parent_web_frame->createLocalChild("", render_frame);
524 } else {
525 RenderFrameProxy* proxy =
526 RenderFrameProxy::FromRoutingID(proxy_routing_id);
527 CHECK(proxy);
528 render_frame = RenderFrameImpl::Create(proxy->render_view(), routing_id);
529 web_frame = blink::WebLocalFrame::create(render_frame);
530 render_frame->proxy_routing_id_ = proxy_routing_id;
531 web_frame->initializeToReplaceRemoteFrame(proxy->web_frame());
533 render_frame->SetWebFrame(web_frame);
534 render_frame->Initialize();
537 // static
538 RenderFrame* RenderFrame::FromWebFrame(blink::WebFrame* web_frame) {
539 return RenderFrameImpl::FromWebFrame(web_frame);
542 // static
543 RenderFrameImpl* RenderFrameImpl::FromWebFrame(blink::WebFrame* web_frame) {
544 FrameMap::iterator iter = g_frame_map.Get().find(web_frame);
545 if (iter != g_frame_map.Get().end())
546 return iter->second;
547 return NULL;
550 // static
551 void RenderFrameImpl::InstallCreateHook(
552 RenderFrameImpl* (*create_render_frame_impl)(RenderViewImpl*, int32)) {
553 CHECK(!g_create_render_frame_impl);
554 g_create_render_frame_impl = create_render_frame_impl;
557 // RenderFrameImpl ----------------------------------------------------------
558 RenderFrameImpl::RenderFrameImpl(RenderViewImpl* render_view, int routing_id)
559 : frame_(NULL),
560 render_view_(render_view->AsWeakPtr()),
561 routing_id_(routing_id),
562 is_swapped_out_(false),
563 render_frame_proxy_(NULL),
564 is_detaching_(false),
565 proxy_routing_id_(MSG_ROUTING_NONE),
566 #if defined(ENABLE_PLUGINS)
567 plugin_power_saver_helper_(NULL),
568 #endif
569 cookie_jar_(this),
570 selection_text_offset_(0),
571 selection_range_(gfx::Range::InvalidRange()),
572 handling_select_range_(false),
573 notification_permission_dispatcher_(NULL),
574 web_user_media_client_(NULL),
575 midi_dispatcher_(NULL),
576 #if defined(OS_ANDROID)
577 media_player_manager_(NULL),
578 #endif
579 #if defined(ENABLE_BROWSER_CDMS)
580 cdm_manager_(NULL),
581 #endif
582 #if defined(VIDEO_HOLE)
583 contains_media_player_(false),
584 #endif
585 geolocation_dispatcher_(NULL),
586 push_messaging_dispatcher_(NULL),
587 screen_orientation_dispatcher_(NULL),
588 manifest_manager_(NULL),
589 accessibility_mode_(AccessibilityModeOff),
590 renderer_accessibility_(NULL),
591 weak_factory_(this) {
592 std::pair<RoutingIDFrameMap::iterator, bool> result =
593 g_routing_id_frame_map.Get().insert(std::make_pair(routing_id_, this));
594 CHECK(result.second) << "Inserting a duplicate item.";
596 RenderThread::Get()->AddRoute(routing_id_, this);
598 render_view_->RegisterRenderFrame(this);
600 // Everything below subclasses RenderFrameObserver and is automatically
601 // deleted when the RenderFrame gets deleted.
602 #if defined(OS_ANDROID)
603 new GinJavaBridgeDispatcher(this);
604 #endif
606 #if defined(ENABLE_PLUGINS)
607 plugin_power_saver_helper_ = new PluginPowerSaverHelper(this);
608 #endif
610 manifest_manager_ = new ManifestManager(this);
613 RenderFrameImpl::~RenderFrameImpl() {
614 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, RenderFrameGone());
615 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, OnDestruct());
617 #if defined(VIDEO_HOLE)
618 if (contains_media_player_)
619 render_view_->UnregisterVideoHoleFrame(this);
620 #endif
622 if (render_frame_proxy_)
623 delete render_frame_proxy_;
625 render_view_->UnregisterRenderFrame(this);
626 g_routing_id_frame_map.Get().erase(routing_id_);
627 RenderThread::Get()->RemoveRoute(routing_id_);
630 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame* web_frame) {
631 DCHECK(!frame_);
633 std::pair<FrameMap::iterator, bool> result = g_frame_map.Get().insert(
634 std::make_pair(web_frame, this));
635 CHECK(result.second) << "Inserting a duplicate item.";
637 frame_ = web_frame;
640 void RenderFrameImpl::Initialize() {
641 #if defined(ENABLE_PLUGINS)
642 new PepperBrowserConnection(this);
643 #endif
644 new SharedWorkerRepository(this);
646 if (!frame_->parent())
647 new ImageLoadingHelper(this);
649 // We delay calling this until we have the WebFrame so that any observer or
650 // embedder can call GetWebFrame on any RenderFrame.
651 GetContentClient()->renderer()->RenderFrameCreated(this);
654 RenderWidget* RenderFrameImpl::GetRenderWidget() {
655 return render_view_.get();
658 #if defined(ENABLE_PLUGINS)
659 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost* host) {
660 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
661 DidCreatePepperPlugin(host));
662 if (host->GetPluginName() == kFlashPluginName) {
663 RenderThread::Get()->RecordAction(
664 base::UserMetricsAction("FrameLoadWithFlash"));
668 void RenderFrameImpl::PepperDidChangeCursor(
669 PepperPluginInstanceImpl* instance,
670 const blink::WebCursorInfo& cursor) {
671 // Update the cursor appearance immediately if the requesting plugin is the
672 // one which receives the last mouse event. Otherwise, the new cursor won't be
673 // picked up until the plugin gets the next input event. That is bad if, e.g.,
674 // the plugin would like to set an invisible cursor when there isn't any user
675 // input for a while.
676 if (instance == render_view_->pepper_last_mouse_event_target())
677 GetRenderWidget()->didChangeCursor(cursor);
680 void RenderFrameImpl::PepperDidReceiveMouseEvent(
681 PepperPluginInstanceImpl* instance) {
682 render_view_->set_pepper_last_mouse_event_target(instance);
685 void RenderFrameImpl::PepperTextInputTypeChanged(
686 PepperPluginInstanceImpl* instance) {
687 if (instance != render_view_->focused_pepper_plugin())
688 return;
690 GetRenderWidget()->UpdateTextInputType();
691 if (renderer_accessibility())
692 renderer_accessibility()->FocusedNodeChanged(WebNode());
695 void RenderFrameImpl::PepperCaretPositionChanged(
696 PepperPluginInstanceImpl* instance) {
697 if (instance != render_view_->focused_pepper_plugin())
698 return;
699 GetRenderWidget()->UpdateSelectionBounds();
702 void RenderFrameImpl::PepperCancelComposition(
703 PepperPluginInstanceImpl* instance) {
704 if (instance != render_view_->focused_pepper_plugin())
705 return;
706 Send(new InputHostMsg_ImeCancelComposition(render_view_->GetRoutingID()));;
707 #if defined(OS_MACOSX) || defined(USE_AURA)
708 GetRenderWidget()->UpdateCompositionInfo(true);
709 #endif
712 void RenderFrameImpl::PepperSelectionChanged(
713 PepperPluginInstanceImpl* instance) {
714 if (instance != render_view_->focused_pepper_plugin())
715 return;
716 SyncSelectionIfRequired();
719 RenderWidgetFullscreenPepper* RenderFrameImpl::CreatePepperFullscreenContainer(
720 PepperPluginInstanceImpl* plugin) {
721 GURL active_url;
722 if (render_view_->webview() && render_view_->webview()->mainFrame())
723 active_url = GURL(render_view_->webview()->mainFrame()->document().url());
724 RenderWidgetFullscreenPepper* widget = RenderWidgetFullscreenPepper::Create(
725 GetRenderWidget()->routing_id(), plugin, active_url,
726 GetRenderWidget()->screenInfo());
727 widget->show(blink::WebNavigationPolicyIgnore);
728 return widget;
731 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
732 if (!render_view_->focused_pepper_plugin())
733 return false;
734 return render_view_->focused_pepper_plugin()->
735 IsPluginAcceptingCompositionEvents();
738 void RenderFrameImpl::PluginCrashed(const base::FilePath& plugin_path,
739 base::ProcessId plugin_pid) {
740 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
741 // routing_id_ as a result.
742 Send(new FrameHostMsg_PluginCrashed(routing_id_, plugin_path, plugin_pid));
745 void RenderFrameImpl::SimulateImeSetComposition(
746 const base::string16& text,
747 const std::vector<blink::WebCompositionUnderline>& underlines,
748 int selection_start,
749 int selection_end) {
750 render_view_->OnImeSetComposition(
751 text, underlines, selection_start, selection_end);
754 void RenderFrameImpl::SimulateImeConfirmComposition(
755 const base::string16& text,
756 const gfx::Range& replacement_range) {
757 render_view_->OnImeConfirmComposition(text, replacement_range, false);
760 void RenderFrameImpl::OnImeSetComposition(
761 const base::string16& text,
762 const std::vector<blink::WebCompositionUnderline>& underlines,
763 int selection_start,
764 int selection_end) {
765 // When a PPAPI plugin has focus, we bypass WebKit.
766 if (!IsPepperAcceptingCompositionEvents()) {
767 pepper_composition_text_ = text;
768 } else {
769 // TODO(kinaba) currently all composition events are sent directly to
770 // plugins. Use DOM event mechanism after WebKit is made aware about
771 // plugins that support composition.
772 // The code below mimics the behavior of WebCore::Editor::setComposition.
774 // Empty -> nonempty: composition started.
775 if (pepper_composition_text_.empty() && !text.empty()) {
776 render_view_->focused_pepper_plugin()->HandleCompositionStart(
777 base::string16());
779 // Nonempty -> empty: composition canceled.
780 if (!pepper_composition_text_.empty() && text.empty()) {
781 render_view_->focused_pepper_plugin()->HandleCompositionEnd(
782 base::string16());
784 pepper_composition_text_ = text;
785 // Nonempty: composition is ongoing.
786 if (!pepper_composition_text_.empty()) {
787 render_view_->focused_pepper_plugin()->HandleCompositionUpdate(
788 pepper_composition_text_, underlines, selection_start,
789 selection_end);
794 void RenderFrameImpl::OnImeConfirmComposition(
795 const base::string16& text,
796 const gfx::Range& replacement_range,
797 bool keep_selection) {
798 // When a PPAPI plugin has focus, we bypass WebKit.
799 // Here, text.empty() has a special meaning. It means to commit the last
800 // update of composition text (see
801 // RenderWidgetHost::ImeConfirmComposition()).
802 const base::string16& last_text = text.empty() ? pepper_composition_text_
803 : text;
805 // last_text is empty only when both text and pepper_composition_text_ is.
806 // Ignore it.
807 if (last_text.empty())
808 return;
810 if (!IsPepperAcceptingCompositionEvents()) {
811 base::i18n::UTF16CharIterator iterator(&last_text);
812 int32 i = 0;
813 while (iterator.Advance()) {
814 blink::WebKeyboardEvent char_event;
815 char_event.type = blink::WebInputEvent::Char;
816 char_event.timeStampSeconds = base::Time::Now().ToDoubleT();
817 char_event.modifiers = 0;
818 char_event.windowsKeyCode = last_text[i];
819 char_event.nativeKeyCode = last_text[i];
821 const int32 char_start = i;
822 for (; i < iterator.array_pos(); ++i) {
823 char_event.text[i - char_start] = last_text[i];
824 char_event.unmodifiedText[i - char_start] = last_text[i];
827 if (GetRenderWidget()->webwidget())
828 GetRenderWidget()->webwidget()->handleInputEvent(char_event);
830 } else {
831 // Mimics the order of events sent by WebKit.
832 // See WebCore::Editor::setComposition() for the corresponding code.
833 render_view_->focused_pepper_plugin()->HandleCompositionEnd(last_text);
834 render_view_->focused_pepper_plugin()->HandleTextInput(last_text);
836 pepper_composition_text_.clear();
839 PluginPowerSaverHelper* RenderFrameImpl::plugin_power_saver_helper() {
840 DCHECK(plugin_power_saver_helper_);
841 return plugin_power_saver_helper_;
843 #endif // defined(ENABLE_PLUGINS)
845 MediaStreamDispatcher* RenderFrameImpl::GetMediaStreamDispatcher() {
846 if (!web_user_media_client_)
847 InitializeUserMediaClient();
848 return web_user_media_client_ ?
849 web_user_media_client_->media_stream_dispatcher() : NULL;
852 bool RenderFrameImpl::Send(IPC::Message* message) {
853 if (is_detaching_) {
854 delete message;
855 return false;
857 if (is_swapped_out_) {
858 if (!SwappedOutMessages::CanSendWhileSwappedOut(message)) {
859 delete message;
860 return false;
864 return RenderThread::Get()->Send(message);
867 #if defined(OS_MACOSX) || defined(OS_ANDROID)
868 void RenderFrameImpl::DidHideExternalPopupMenu() {
869 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
870 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
871 external_popup_menu_.reset();
873 #endif
875 bool RenderFrameImpl::OnMessageReceived(const IPC::Message& msg) {
876 // TODO(kenrb): document() should not be null, but as a transitional step
877 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
878 // to this method. This happens for a top-level remote frame, where a
879 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
880 // around and is still able to receive messages.
881 if (!frame_->document().isNull())
882 GetContentClient()->SetActiveURL(frame_->document().url());
884 ObserverListBase<RenderFrameObserver>::Iterator it(observers_);
885 RenderFrameObserver* observer;
886 while ((observer = it.GetNext()) != NULL) {
887 if (observer->OnMessageReceived(msg))
888 return true;
891 bool handled = true;
892 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl, msg)
893 IPC_MESSAGE_HANDLER(FrameMsg_Navigate, OnNavigate)
894 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload, OnBeforeUnload)
895 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut, OnSwapOut)
896 IPC_MESSAGE_HANDLER(FrameMsg_Stop, OnStop)
897 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed, OnContextMenuClosed)
898 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction,
899 OnCustomContextMenuAction)
900 IPC_MESSAGE_HANDLER(InputMsg_Undo, OnUndo)
901 IPC_MESSAGE_HANDLER(InputMsg_Redo, OnRedo)
902 IPC_MESSAGE_HANDLER(InputMsg_Cut, OnCut)
903 IPC_MESSAGE_HANDLER(InputMsg_Copy, OnCopy)
904 IPC_MESSAGE_HANDLER(InputMsg_Paste, OnPaste)
905 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle, OnPasteAndMatchStyle)
906 IPC_MESSAGE_HANDLER(InputMsg_Delete, OnDelete)
907 IPC_MESSAGE_HANDLER(InputMsg_SelectAll, OnSelectAll)
908 IPC_MESSAGE_HANDLER(InputMsg_SelectRange, OnSelectRange)
909 IPC_MESSAGE_HANDLER(InputMsg_Unselect, OnUnselect)
910 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent,
911 OnMoveRangeSelectionExtent)
912 IPC_MESSAGE_HANDLER(InputMsg_Replace, OnReplace)
913 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling, OnReplaceMisspelling)
914 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete,
915 OnExtendSelectionAndDelete)
916 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText,
917 OnSetCompositionFromExistingText)
918 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest, OnCSSInsertRequest)
919 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest,
920 OnJavaScriptExecuteRequest)
921 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests,
922 OnJavaScriptExecuteRequestForTests)
923 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets,
924 OnSetEditableSelectionOffsets)
925 IPC_MESSAGE_HANDLER(FrameMsg_SetupTransitionView, OnSetupTransitionView)
926 IPC_MESSAGE_HANDLER(FrameMsg_BeginExitTransition, OnBeginExitTransition)
927 IPC_MESSAGE_HANDLER(FrameMsg_HideTransitionElements,
928 OnHideTransitionElements)
929 IPC_MESSAGE_HANDLER(FrameMsg_ShowTransitionElements,
930 OnShowTransitionElements)
931 IPC_MESSAGE_HANDLER(FrameMsg_Reload, OnReload)
932 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest,
933 OnTextSurroundingSelectionRequest)
934 IPC_MESSAGE_HANDLER(FrameMsg_AddStyleSheetByURL,
935 OnAddStyleSheetByURL)
936 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode,
937 OnSetAccessibilityMode)
938 IPC_MESSAGE_HANDLER(FrameMsg_DisownOpener, OnDisownOpener)
939 IPC_MESSAGE_HANDLER(FrameMsg_RequestNavigation, OnRequestNavigation)
940 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation, OnCommitNavigation)
941 #if defined(OS_ANDROID)
942 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems, OnSelectPopupMenuItems)
943 #elif defined(OS_MACOSX)
944 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem, OnSelectPopupMenuItem)
945 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard, OnCopyToFindPboard)
946 #endif
947 IPC_END_MESSAGE_MAP()
949 return handled;
952 void RenderFrameImpl::OnNavigate(const FrameMsg_Navigate_Params& params) {
953 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate",
954 "id", routing_id_,
955 "url", params.common_params.url.possibly_invalid_spec());
956 bool is_reload =
957 RenderViewImpl::IsReload(params.common_params.navigation_type);
958 WebURLRequest::CachePolicy cache_policy =
959 WebURLRequest::UseProtocolCachePolicy;
960 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
961 params.common_params.url, params.common_params.navigation_type,
962 params.commit_params.page_state, true, params.pending_history_list_offset,
963 params.page_id, &is_reload, &cache_policy)) {
964 return;
967 int pending_history_list_offset = params.pending_history_list_offset;
968 int current_history_list_offset = params.current_history_list_offset;
969 int current_history_list_length = params.current_history_list_length;
970 if (params.should_clear_history_list) {
971 CHECK_EQ(pending_history_list_offset, -1);
972 CHECK_EQ(current_history_list_offset, -1);
973 CHECK_EQ(current_history_list_length, 0);
975 render_view_->history_list_offset_ = current_history_list_offset;
976 render_view_->history_list_length_ = current_history_list_length;
977 if (render_view_->history_list_length_ >= 0) {
978 render_view_->history_page_ids_.resize(
979 render_view_->history_list_length_, -1);
981 if (pending_history_list_offset >= 0 &&
982 pending_history_list_offset < render_view_->history_list_length_) {
983 render_view_->history_page_ids_[pending_history_list_offset] =
984 params.page_id;
987 GetContentClient()->SetActiveURL(params.common_params.url);
989 WebFrame* frame = frame_;
990 if (!params.frame_to_navigate.empty()) {
991 // TODO(nasko): Move this lookup to the browser process.
992 frame = render_view_->webview()->findFrameByName(
993 WebString::fromUTF8(params.frame_to_navigate));
994 CHECK(frame) << "Invalid frame name passed: " << params.frame_to_navigate;
997 if (is_reload && !render_view_->history_controller()->GetCurrentEntry()) {
998 // We cannot reload if we do not have any history state. This happens, for
999 // example, when recovering from a crash.
1000 is_reload = false;
1001 cache_policy = WebURLRequest::ReloadIgnoringCacheData;
1004 render_view_->pending_navigation_params_.reset(
1005 new FrameMsg_Navigate_Params(params));
1007 // If we are reloading, then WebKit will use the history state of the current
1008 // page, so we should just ignore any given history state. Otherwise, if we
1009 // have history state, then we need to navigate to it, which corresponds to a
1010 // back/forward navigation event.
1011 if (is_reload) {
1012 bool reload_original_url =
1013 (params.common_params.navigation_type ==
1014 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
1015 bool ignore_cache = (params.common_params.navigation_type ==
1016 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE);
1018 if (reload_original_url)
1019 frame->reloadWithOverrideURL(params.common_params.url, true);
1020 else
1021 frame->reload(ignore_cache);
1022 } else if (params.commit_params.page_state.IsValid()) {
1023 // We must know the page ID of the page we are navigating back to.
1024 DCHECK_NE(params.page_id, -1);
1025 scoped_ptr<HistoryEntry> entry =
1026 PageStateToHistoryEntry(params.commit_params.page_state);
1027 if (entry) {
1028 // Ensure we didn't save the swapped out URL in UpdateState, since the
1029 // browser should never be telling us to navigate to swappedout://.
1030 CHECK(entry->root().urlString() != WebString::fromUTF8(kSwappedOutURL));
1031 render_view_->history_controller()->GoToEntry(entry.Pass(), cache_policy);
1033 } else if (!params.base_url_for_data_url.is_empty()) {
1034 // A loadData request with a specified base URL.
1035 std::string mime_type, charset, data;
1036 if (net::DataURL::Parse(
1037 params.common_params.url, &mime_type, &charset, &data)) {
1038 frame->loadData(
1039 WebData(data.c_str(), data.length()),
1040 WebString::fromUTF8(mime_type),
1041 WebString::fromUTF8(charset),
1042 params.base_url_for_data_url,
1043 params.history_url_for_data_url,
1044 false);
1045 } else {
1046 CHECK(false) << "Invalid URL passed: "
1047 << params.common_params.url.possibly_invalid_spec();
1049 } else {
1050 // Navigate to the given URL.
1051 WebURLRequest request =
1052 CreateURLRequestForNavigation(params.common_params,
1053 params.request_params,
1054 scoped_ptr<StreamOverrideParameters>(),
1055 frame->isViewSourceModeEnabled());
1057 // A session history navigation should have been accompanied by state.
1058 CHECK_EQ(params.page_id, -1);
1060 // Record this before starting the load, we need a lower bound of this time
1061 // to sanitize the navigationStart override set below.
1062 base::TimeTicks renderer_navigation_start = base::TimeTicks::Now();
1063 frame->loadRequest(request);
1065 UpdateFrameNavigationTiming(
1066 frame, params.commit_params.browser_navigation_start,
1067 renderer_navigation_start);
1070 // In case LoadRequest failed before DidCreateDataSource was called.
1071 render_view_->pending_navigation_params_.reset();
1074 void RenderFrameImpl::NavigateToSwappedOutURL() {
1075 // We use loadRequest instead of loadHTMLString because the former commits
1076 // synchronously. Otherwise a new navigation can interrupt the navigation
1077 // to kSwappedOutURL. If that happens to be to the page we had been
1078 // showing, then WebKit will never send a commit and we'll be left spinning.
1079 // Set the is_swapped_out_ bit to true, so IPC filtering is in effect and
1080 // the navigation to swappedout:// is not announced to the browser side.
1081 is_swapped_out_ = true;
1082 GURL swappedOutURL(kSwappedOutURL);
1083 WebURLRequest request(swappedOutURL);
1084 frame_->loadRequest(request);
1087 void RenderFrameImpl::BindServiceRegistry(
1088 mojo::ScopedMessagePipeHandle service_provider_handle) {
1089 service_registry_.BindRemoteServiceProvider(service_provider_handle.Pass());
1092 ManifestManager* RenderFrameImpl::manifest_manager() {
1093 return manifest_manager_;
1096 void RenderFrameImpl::OnBeforeUnload() {
1097 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1098 "id", routing_id_);
1099 // TODO(creis): Right now, this is only called on the main frame. Make the
1100 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1101 // it.
1102 CHECK(!frame_->parent());
1104 base::TimeTicks before_unload_start_time = base::TimeTicks::Now();
1105 bool proceed = frame_->dispatchBeforeUnloadEvent();
1106 base::TimeTicks before_unload_end_time = base::TimeTicks::Now();
1107 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_, proceed,
1108 before_unload_start_time,
1109 before_unload_end_time));
1112 void RenderFrameImpl::OnSwapOut(int proxy_routing_id) {
1113 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_);
1114 RenderFrameProxy* proxy = NULL;
1115 bool is_site_per_process =
1116 CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess);
1117 bool is_main_frame = !frame_->parent();
1119 // Only run unload if we're not swapped out yet, but send the ack either way.
1120 if (!is_swapped_out_) {
1121 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1122 // a different process. This involves running the unload handler and
1123 // clearing the page. We also allow this process to exit if there are no
1124 // other active RenderFrames in it.
1126 // Send an UpdateState message before we get swapped out.
1127 render_view_->SyncNavigationState();
1129 // If we need a proxy to replace this, create it now so its routing id is
1130 // registered for receiving IPC messages.
1131 if (proxy_routing_id != MSG_ROUTING_NONE) {
1132 proxy = RenderFrameProxy::CreateProxyToReplaceFrame(this,
1133 proxy_routing_id);
1136 // Synchronously run the unload handler before sending the ACK.
1137 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1138 // unload on subframes as well.
1139 if (is_main_frame)
1140 frame_->dispatchUnloadEvent();
1142 // Swap out and stop sending any IPC messages that are not ACKs.
1143 if (is_main_frame)
1144 render_view_->SetSwappedOut(true);
1145 is_swapped_out_ = true;
1147 // Now that we're swapped out and filtering IPC messages, stop loading to
1148 // ensure that no other in-progress navigation continues. We do this here
1149 // to avoid sending a DidStopLoading message to the browser process.
1150 // TODO(creis): Should we be stopping all frames here and using
1151 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1152 // frame?
1153 OnStop();
1155 // Transfer settings such as initial drawing parameters to the remote frame,
1156 // if one is created, that will replace this frame.
1157 if (!is_main_frame && proxy)
1158 proxy->web_frame()->initializeFromFrame(frame_);
1160 // Replace the page with a blank dummy URL. The unload handler will not be
1161 // run a second time, thanks to a check in FrameLoader::stopLoading.
1162 // TODO(creis): Need to add a better way to do this that avoids running the
1163 // beforeunload handler. For now, we just run it a second time silently.
1164 if (!is_site_per_process || is_main_frame)
1165 NavigateToSwappedOutURL();
1167 // Let WebKit know that this view is hidden so it can drop resources and
1168 // stop compositing.
1169 // TODO(creis): Support this for subframes as well.
1170 if (is_main_frame) {
1171 render_view_->webview()->setVisibilityState(
1172 blink::WebPageVisibilityStateHidden, false);
1176 // It is now safe to show modal dialogs again.
1177 // TODO(creis): Deal with modal dialogs from subframes.
1178 if (is_main_frame)
1179 render_view_->suppress_dialogs_until_swap_out_ = false;
1181 Send(new FrameHostMsg_SwapOut_ACK(routing_id_));
1183 // Now that all of the cleanup is complete and the browser side is notified,
1184 // start using the RenderFrameProxy, if one is created.
1185 if (proxy) {
1186 if (!is_main_frame) {
1187 frame_->swap(proxy->web_frame());
1188 if (is_site_per_process) {
1189 // TODO(nasko): delete the frame here, since we've replaced it with a
1190 // proxy.
1192 } else {
1193 set_render_frame_proxy(proxy);
1197 // Safe to exit if no one else is using the process.
1198 if (is_main_frame)
1199 render_view_->WasSwappedOut();
1202 void RenderFrameImpl::OnContextMenuClosed(
1203 const CustomContextMenuContext& custom_context) {
1204 if (custom_context.request_id) {
1205 // External request, should be in our map.
1206 ContextMenuClient* client =
1207 pending_context_menus_.Lookup(custom_context.request_id);
1208 if (client) {
1209 client->OnMenuClosed(custom_context.request_id);
1210 pending_context_menus_.Remove(custom_context.request_id);
1212 } else {
1213 if (custom_context.link_followed.is_valid()) {
1214 frame_->sendPings(
1215 DomUtils::ExtractParentAnchorNode(context_menu_node_),
1216 custom_context.link_followed);
1218 // Internal request, forward to WebKit.
1219 context_menu_node_.reset();
1223 void RenderFrameImpl::OnCustomContextMenuAction(
1224 const CustomContextMenuContext& custom_context,
1225 unsigned action) {
1226 if (custom_context.request_id) {
1227 // External context menu request, look in our map.
1228 ContextMenuClient* client =
1229 pending_context_menus_.Lookup(custom_context.request_id);
1230 if (client)
1231 client->OnMenuAction(custom_context.request_id, action);
1232 } else {
1233 // Internal request, forward to WebKit.
1234 render_view_->webview()->performCustomContextMenuAction(action);
1238 void RenderFrameImpl::OnUndo() {
1239 frame_->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1242 void RenderFrameImpl::OnRedo() {
1243 frame_->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1246 void RenderFrameImpl::OnCut() {
1247 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1248 frame_->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1251 void RenderFrameImpl::OnCopy() {
1252 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1253 WebNode current_node = context_menu_node_.isNull() ?
1254 GetFocusedElement() : context_menu_node_;
1255 frame_->executeCommand(WebString::fromUTF8("Copy"), current_node);
1258 void RenderFrameImpl::OnPaste() {
1259 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1260 frame_->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1263 void RenderFrameImpl::OnPasteAndMatchStyle() {
1264 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1265 frame_->executeCommand(
1266 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1269 #if defined(OS_MACOSX)
1270 void RenderFrameImpl::OnCopyToFindPboard() {
1271 // Since the find pasteboard supports only plain text, this can be simpler
1272 // than the |OnCopy()| case.
1273 if (frame_->hasSelection()) {
1274 base::string16 selection = frame_->selectionAsText();
1275 RenderThread::Get()->Send(
1276 new ClipboardHostMsg_FindPboardWriteStringAsync(selection));
1279 #endif
1281 void RenderFrameImpl::OnDelete() {
1282 frame_->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1285 void RenderFrameImpl::OnSelectAll() {
1286 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1287 frame_->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1290 void RenderFrameImpl::OnSelectRange(const gfx::Point& base,
1291 const gfx::Point& extent) {
1292 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1293 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1295 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1296 frame_->selectRange(base, extent);
1299 void RenderFrameImpl::OnUnselect() {
1300 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1301 frame_->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1304 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point& point) {
1305 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1306 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1307 GetRenderWidget()->routing_id()));
1309 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1310 frame_->moveRangeSelectionExtent(point);
1313 void RenderFrameImpl::OnReplace(const base::string16& text) {
1314 if (!frame_->hasSelection())
1315 frame_->selectWordAroundCaret();
1317 frame_->replaceSelection(text);
1320 void RenderFrameImpl::OnReplaceMisspelling(const base::string16& text) {
1321 if (!frame_->hasSelection())
1322 return;
1324 frame_->replaceMisspelledRange(text);
1327 void RenderFrameImpl::OnCSSInsertRequest(const std::string& css) {
1328 frame_->document().insertStyleSheet(WebString::fromUTF8(css));
1331 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1332 const base::string16& jscript,
1333 int id,
1334 bool notify_result) {
1335 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1336 TRACE_EVENT_SCOPE_THREAD);
1338 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
1339 v8::Handle<v8::Value> result =
1340 frame_->executeScriptAndReturnValue(WebScriptSource(jscript));
1342 HandleJavascriptExecutionResult(jscript, id, notify_result, result);
1345 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1346 const base::string16& jscript,
1347 int id,
1348 bool notify_result) {
1349 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1350 TRACE_EVENT_SCOPE_THREAD);
1352 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
1353 v8::Handle<v8::Value> result =
1354 frame_->executeScriptAndReturnValueForTests(WebScriptSource(jscript));
1356 HandleJavascriptExecutionResult(jscript, id, notify_result, result);
1359 void RenderFrameImpl::HandleJavascriptExecutionResult(
1360 const base::string16& jscript,
1361 int id,
1362 bool notify_result,
1363 v8::Handle<v8::Value> result) {
1364 if (notify_result) {
1365 base::ListValue list;
1366 if (!result.IsEmpty()) {
1367 v8::Local<v8::Context> context = frame_->mainWorldScriptContext();
1368 v8::Context::Scope context_scope(context);
1369 V8ValueConverterImpl converter;
1370 converter.SetDateAllowed(true);
1371 converter.SetRegExpAllowed(true);
1372 base::Value* result_value = converter.FromV8Value(result, context);
1373 list.Set(0, result_value ? result_value : base::Value::CreateNullValue());
1374 } else {
1375 list.Set(0, base::Value::CreateNullValue());
1377 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_, id, list));
1381 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start, int end) {
1382 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1383 if (!GetRenderWidget()->ShouldHandleImeEvent())
1384 return;
1385 ImeEventGuard guard(GetRenderWidget());
1386 frame_->setEditableSelectionOffsets(start, end);
1389 void RenderFrameImpl::OnSetCompositionFromExistingText(
1390 int start, int end,
1391 const std::vector<blink::WebCompositionUnderline>& underlines) {
1392 if (!GetRenderWidget()->ShouldHandleImeEvent())
1393 return;
1394 ImeEventGuard guard(GetRenderWidget());
1395 frame_->setCompositionFromExistingText(start, end, underlines);
1398 void RenderFrameImpl::OnExtendSelectionAndDelete(int before, int after) {
1399 if (!GetRenderWidget()->ShouldHandleImeEvent())
1400 return;
1401 ImeEventGuard guard(GetRenderWidget());
1402 frame_->extendSelectionAndDelete(before, after);
1405 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode) {
1406 if (accessibility_mode_ == new_mode)
1407 return;
1408 accessibility_mode_ = new_mode;
1409 if (renderer_accessibility_) {
1410 // Note: this isn't called automatically by the destructor because
1411 // there'd be no point in calling it in frame teardown, only if there's
1412 // an accessibility mode change but the frame is persisting.
1413 renderer_accessibility_->DisableAccessibility();
1415 delete renderer_accessibility_;
1416 renderer_accessibility_ = NULL;
1418 if (accessibility_mode_ == AccessibilityModeOff)
1419 return;
1421 if (accessibility_mode_ & AccessibilityModeFlagFullTree)
1422 renderer_accessibility_ = new RendererAccessibility(this);
1425 void RenderFrameImpl::OnDisownOpener() {
1426 // TODO(creis): We should only see this for main frames for now. To support
1427 // disowning the opener on subframes, we will need to move WebContentsImpl's
1428 // opener_ to FrameTreeNode.
1429 CHECK(!frame_->parent());
1431 if (frame_->opener())
1432 frame_->setOpener(NULL);
1435 #if defined(OS_ANDROID)
1436 void RenderFrameImpl::OnSelectPopupMenuItems(
1437 bool canceled,
1438 const std::vector<int>& selected_indices) {
1439 // It is possible to receive more than one of these calls if the user presses
1440 // a select faster than it takes for the show-select-popup IPC message to make
1441 // it to the browser UI thread. Ignore the extra-messages.
1442 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1443 if (!external_popup_menu_)
1444 return;
1446 external_popup_menu_->DidSelectItems(canceled, selected_indices);
1447 external_popup_menu_.reset();
1449 #endif
1451 #if defined(OS_MACOSX)
1452 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index) {
1453 if (external_popup_menu_ == NULL)
1454 return;
1455 external_popup_menu_->DidSelectItem(selected_index);
1456 external_popup_menu_.reset();
1458 #endif
1460 void RenderFrameImpl::OnReload(bool ignore_cache) {
1461 frame_->reload(ignore_cache);
1464 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length) {
1465 blink::WebSurroundingText surroundingText;
1466 surroundingText.initialize(frame_->selectionRange(), max_length);
1468 if (surroundingText.isNull()) {
1469 // |surroundingText| might not be correctly initialized, for example if
1470 // |frame_->selectionRange().isNull()|, in other words, if there was no
1471 // selection.
1472 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1473 routing_id_, base::string16(), 0, 0));
1474 return;
1477 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1478 routing_id_,
1479 surroundingText.textContent(),
1480 surroundingText.startOffsetInTextContent(),
1481 surroundingText.endOffsetInTextContent()));
1484 void RenderFrameImpl::OnAddStyleSheetByURL(const std::string& url) {
1485 frame_->addStyleSheetByURL(WebString::fromUTF8(url));
1488 void RenderFrameImpl::OnSetupTransitionView(const std::string& markup) {
1489 frame_->document().setIsTransitionDocument();
1490 frame_->navigateToSandboxedMarkup(WebData(markup.data(), markup.length()));
1493 void RenderFrameImpl::OnBeginExitTransition(const std::string& css_selector,
1494 bool exit_to_native_app) {
1495 frame_->document().setIsTransitionDocument();
1496 frame_->document().beginExitTransition(WebString::fromUTF8(css_selector),
1497 exit_to_native_app);
1500 void RenderFrameImpl::OnHideTransitionElements(
1501 const std::string& css_selector) {
1502 frame_->document().setIsTransitionDocument();
1503 frame_->document().hideTransitionElements(WebString::fromUTF8(css_selector));
1506 void RenderFrameImpl::OnShowTransitionElements(
1507 const std::string& css_selector) {
1508 frame_->document().setIsTransitionDocument();
1509 frame_->document().showTransitionElements(WebString::fromUTF8(css_selector));
1512 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type,
1513 const base::string16& message,
1514 const base::string16& default_value,
1515 const GURL& frame_url,
1516 base::string16* result) {
1517 // Don't allow further dialogs if we are waiting to swap out, since the
1518 // PageGroupLoadDeferrer in our stack prevents it.
1519 if (render_view()->suppress_dialogs_until_swap_out_)
1520 return false;
1522 bool success = false;
1523 base::string16 result_temp;
1524 if (!result)
1525 result = &result_temp;
1527 render_view()->SendAndRunNestedMessageLoop(
1528 new FrameHostMsg_RunJavaScriptMessage(
1529 routing_id_, message, default_value, frame_url, type, &success,
1530 result));
1531 return success;
1534 void RenderFrameImpl::LoadNavigationErrorPage(
1535 const WebURLRequest& failed_request,
1536 const WebURLError& error,
1537 bool replace) {
1538 std::string error_html;
1539 GetContentClient()->renderer()->GetNavigationErrorStrings(
1540 render_view(), frame_, failed_request, error, &error_html, NULL);
1542 frame_->loadHTMLString(error_html,
1543 GURL(kUnreachableWebDataURL),
1544 error.unreachableURL,
1545 replace);
1548 void RenderFrameImpl::DidCommitCompositorFrame() {
1549 FOR_EACH_OBSERVER(
1550 RenderFrameObserver, observers_, DidCommitCompositorFrame());
1553 RenderView* RenderFrameImpl::GetRenderView() {
1554 return render_view_.get();
1557 int RenderFrameImpl::GetRoutingID() {
1558 return routing_id_;
1561 blink::WebLocalFrame* RenderFrameImpl::GetWebFrame() {
1562 DCHECK(frame_);
1563 return frame_;
1566 WebPreferences& RenderFrameImpl::GetWebkitPreferences() {
1567 return render_view_->GetWebkitPreferences();
1570 int RenderFrameImpl::ShowContextMenu(ContextMenuClient* client,
1571 const ContextMenuParams& params) {
1572 DCHECK(client); // A null client means "internal" when we issue callbacks.
1573 ContextMenuParams our_params(params);
1574 our_params.custom_context.request_id = pending_context_menus_.Add(client);
1575 Send(new FrameHostMsg_ContextMenu(routing_id_, our_params));
1576 return our_params.custom_context.request_id;
1579 void RenderFrameImpl::CancelContextMenu(int request_id) {
1580 DCHECK(pending_context_menus_.Lookup(request_id));
1581 pending_context_menus_.Remove(request_id);
1584 blink::WebNode RenderFrameImpl::GetContextMenuNode() const {
1585 return context_menu_node_;
1588 blink::WebPlugin* RenderFrameImpl::CreatePlugin(
1589 blink::WebFrame* frame,
1590 const WebPluginInfo& info,
1591 const blink::WebPluginParams& params,
1592 CreatePluginGesture gesture) {
1593 DCHECK_EQ(frame_, frame);
1594 #if defined(ENABLE_PLUGINS)
1595 if (gesture == CREATE_PLUGIN_GESTURE_HAS_USER_GESTURE) {
1596 plugin_power_saver_helper_->WhitelistContentOrigin(
1597 GURL(params.url).GetOrigin());
1600 bool pepper_plugin_was_registered = false;
1601 scoped_refptr<PluginModule> pepper_module(PluginModule::Create(
1602 this, info, &pepper_plugin_was_registered));
1603 if (pepper_plugin_was_registered) {
1604 if (pepper_module.get()) {
1605 return new PepperWebPluginImpl(pepper_module.get(), params, this);
1608 #if defined(OS_CHROMEOS)
1609 LOG(WARNING) << "Pepper module/plugin creation failed.";
1610 return NULL;
1611 #else
1612 // TODO(jam): change to take RenderFrame.
1613 return new WebPluginImpl(frame, params, info.path, render_view_, this);
1614 #endif
1615 #else
1616 return NULL;
1617 #endif
1620 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame* frame,
1621 const blink::WebURLRequest& request,
1622 blink::WebNavigationPolicy policy) {
1623 DCHECK(!frame_ || frame_ == frame);
1624 loadURLExternally(frame, request, policy, WebString());
1627 void RenderFrameImpl::ExecuteJavaScript(const base::string16& javascript) {
1628 OnJavaScriptExecuteRequest(javascript, 0, false);
1631 ServiceRegistry* RenderFrameImpl::GetServiceRegistry() {
1632 return &service_registry_;
1635 bool RenderFrameImpl::IsFTPDirectoryListing() {
1636 WebURLResponseExtraDataImpl* extra_data =
1637 GetExtraDataFromResponse(frame_->dataSource()->response());
1638 return extra_data ? extra_data->is_ftp_directory_listing() : false;
1641 void RenderFrameImpl::AttachGuest(int element_instance_id) {
1642 render_view_->GetBrowserPluginManager()->Attach(element_instance_id);
1645 void RenderFrameImpl::SetSelectedText(const base::string16& selection_text,
1646 size_t offset,
1647 const gfx::Range& range) {
1648 // Use the routing id of Render Widget Host.
1649 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1650 selection_text,
1651 offset,
1652 range));
1655 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1656 v8::Isolate* isolate,
1657 v8::Handle<v8::Context> context) {
1658 gin::ModuleRegistry* registry = gin::ModuleRegistry::From(context);
1659 if (registry->available_modules().count(mojo::js::Core::kModuleName))
1660 return;
1662 v8::HandleScope handle_scope(isolate);
1663 registry->AddBuiltinModule(
1664 isolate, mojo::js::Core::kModuleName, mojo::js::Core::GetModule(isolate));
1665 registry->AddBuiltinModule(isolate,
1666 mojo::js::Support::kModuleName,
1667 mojo::js::Support::GetModule(isolate));
1668 registry->AddBuiltinModule(
1669 isolate,
1670 ServiceRegistryJsWrapper::kModuleName,
1671 ServiceRegistryJsWrapper::Create(isolate, &service_registry_).ToV8());
1674 // blink::WebFrameClient implementation ----------------------------------------
1676 blink::WebPluginPlaceholder* RenderFrameImpl::createPluginPlaceholder(
1677 blink::WebLocalFrame* frame,
1678 const blink::WebPluginParams& params) {
1679 DCHECK_EQ(frame_, frame);
1680 return GetContentClient()
1681 ->renderer()
1682 ->CreatePluginPlaceholder(this, frame, params)
1683 .release();
1686 blink::WebPlugin* RenderFrameImpl::createPlugin(
1687 blink::WebLocalFrame* frame,
1688 const blink::WebPluginParams& params) {
1689 DCHECK_EQ(frame_, frame);
1690 blink::WebPlugin* plugin = NULL;
1691 if (GetContentClient()->renderer()->OverrideCreatePlugin(
1692 this, frame, params, &plugin)) {
1693 return plugin;
1696 if (base::UTF16ToUTF8(params.mimeType) == kBrowserPluginMimeType) {
1697 scoped_ptr<BrowserPluginDelegate> browser_plugin_delegate(
1698 GetContentClient()->renderer()->CreateBrowserPluginDelegate(this,
1699 kBrowserPluginMimeType, GURL(params.url)));
1700 return render_view_->GetBrowserPluginManager()->CreateBrowserPlugin(
1701 render_view_.get(), frame, browser_plugin_delegate.Pass());
1704 #if defined(ENABLE_PLUGINS)
1705 WebPluginInfo info;
1706 std::string mime_type;
1707 bool found = false;
1708 Send(new FrameHostMsg_GetPluginInfo(
1709 routing_id_, params.url, frame->top()->document().url(),
1710 params.mimeType.utf8(), &found, &info, &mime_type));
1711 if (!found)
1712 return NULL;
1714 if (info.type == WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN) {
1715 scoped_ptr<BrowserPluginDelegate> browser_plugin_delegate(
1716 GetContentClient()->renderer()->CreateBrowserPluginDelegate(
1717 this, mime_type, GURL(params.url)));
1718 return render_view_->GetBrowserPluginManager()->CreateBrowserPlugin(
1719 render_view_.get(), frame, browser_plugin_delegate.Pass());
1723 WebPluginParams params_to_use = params;
1724 params_to_use.mimeType = WebString::fromUTF8(mime_type);
1725 return CreatePlugin(frame, info, params_to_use,
1726 CREATE_PLUGIN_GESTURE_NO_USER_GESTURE);
1727 #else
1728 return NULL;
1729 #endif // defined(ENABLE_PLUGINS)
1732 blink::WebMediaPlayer* RenderFrameImpl::createMediaPlayer(
1733 blink::WebLocalFrame* frame,
1734 const blink::WebURL& url,
1735 blink::WebMediaPlayerClient* client) {
1736 return createMediaPlayer(frame, url, client, NULL);
1739 blink::WebMediaPlayer* RenderFrameImpl::createMediaPlayer(
1740 blink::WebLocalFrame* frame,
1741 const blink::WebURL& url,
1742 blink::WebMediaPlayerClient* client,
1743 blink::WebContentDecryptionModule* initial_cdm) {
1744 #if defined(VIDEO_HOLE)
1745 if (!contains_media_player_) {
1746 render_view_->RegisterVideoHoleFrame(this);
1747 contains_media_player_ = true;
1749 #endif // defined(VIDEO_HOLE)
1751 blink::WebMediaStream web_stream(
1752 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url));
1753 if (!web_stream.isNull())
1754 return CreateWebMediaPlayerForMediaStream(url, client);
1756 #if defined(OS_ANDROID)
1757 return CreateAndroidWebMediaPlayer(url, client, initial_cdm);
1758 #else
1759 RenderThreadImpl* render_thread = RenderThreadImpl::current();
1760 media::WebMediaPlayerParams params(
1761 base::Bind(&ContentRendererClient::DeferMediaLoad,
1762 base::Unretained(GetContentClient()->renderer()),
1763 static_cast<RenderFrame*>(this)),
1764 render_thread->GetAudioRendererMixerManager()->CreateInput(
1765 render_view_->routing_id_, routing_id_),
1766 *render_thread->GetAudioHardwareConfig(),
1767 new RenderMediaLog(),
1768 render_thread->GetGpuFactories(),
1769 render_thread->GetMediaThreadTaskRunner(),
1770 render_thread->compositor_message_loop_proxy(),
1771 initial_cdm);
1773 #if defined(ENABLE_PEPPER_CDMS)
1774 scoped_ptr<media::CdmFactory> cdm_factory(
1775 new RenderCdmFactory(base::Bind(&PepperCdmWrapperImpl::Create, frame)));
1776 #else
1777 scoped_ptr<media::CdmFactory> cdm_factory(new RenderCdmFactory());
1778 #endif
1780 scoped_ptr<media::Renderer> media_renderer =
1781 GetContentClient()->renderer()->CreateMediaRenderer(
1782 this, render_thread->GetMediaThreadTaskRunner());
1784 return new media::WebMediaPlayerImpl(
1785 frame, client, weak_factory_.GetWeakPtr(), media_renderer.Pass(),
1786 cdm_factory.Pass(), params);
1787 #endif // defined(OS_ANDROID)
1790 blink::WebContentDecryptionModule*
1791 RenderFrameImpl::createContentDecryptionModule(
1792 blink::WebLocalFrame* frame,
1793 const blink::WebSecurityOrigin& security_origin,
1794 const blink::WebString& key_system) {
1795 DCHECK(!frame_ || frame_ == frame);
1797 #if defined(ENABLE_PEPPER_CDMS)
1798 RenderCdmFactory cdm_factory(
1799 base::Bind(&PepperCdmWrapperImpl::Create, frame));
1800 #elif defined(ENABLE_BROWSER_CDMS)
1801 RenderCdmFactory cdm_factory(GetCdmManager());
1802 #else
1803 RenderCdmFactory cdm_factory;
1804 #endif
1806 return media::WebContentDecryptionModuleImpl::Create(
1807 &cdm_factory, security_origin, key_system);
1810 blink::WebApplicationCacheHost* RenderFrameImpl::createApplicationCacheHost(
1811 blink::WebLocalFrame* frame,
1812 blink::WebApplicationCacheHostClient* client) {
1813 if (!frame || !frame->view())
1814 return NULL;
1815 DCHECK(!frame_ || frame_ == frame);
1816 return new RendererWebApplicationCacheHostImpl(
1817 RenderViewImpl::FromWebView(frame->view()), client,
1818 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
1821 blink::WebWorkerPermissionClientProxy*
1822 RenderFrameImpl::createWorkerPermissionClientProxy(
1823 blink::WebLocalFrame* frame) {
1824 if (!frame || !frame->view())
1825 return NULL;
1826 DCHECK(!frame_ || frame_ == frame);
1827 return GetContentClient()->renderer()->CreateWorkerPermissionClientProxy(
1828 this, frame);
1831 WebExternalPopupMenu* RenderFrameImpl::createExternalPopupMenu(
1832 const WebPopupMenuInfo& popup_menu_info,
1833 WebExternalPopupMenuClient* popup_menu_client) {
1834 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1835 // An IPC message is sent to the browser to build and display the actual
1836 // popup. The user could have time to click a different select by the time
1837 // the popup is shown. In that case external_popup_menu_ is non NULL.
1838 // By returning NULL in that case, we instruct Blink to cancel that new
1839 // popup. So from the user perspective, only the first one will show, and
1840 // will have to close the first one before another one can be shown.
1841 if (external_popup_menu_)
1842 return NULL;
1843 external_popup_menu_.reset(
1844 new ExternalPopupMenu(this, popup_menu_info, popup_menu_client));
1845 if (render_view_->screen_metrics_emulator_) {
1846 render_view_->SetExternalPopupOriginAdjustmentsForEmulation(
1847 external_popup_menu_.get(),
1848 render_view_->screen_metrics_emulator_.get());
1850 return external_popup_menu_.get();
1851 #else
1852 return NULL;
1853 #endif
1856 blink::WebCookieJar* RenderFrameImpl::cookieJar(blink::WebLocalFrame* frame) {
1857 DCHECK(!frame_ || frame_ == frame);
1858 return &cookie_jar_;
1861 blink::WebServiceWorkerProvider* RenderFrameImpl::createServiceWorkerProvider(
1862 blink::WebLocalFrame* frame) {
1863 DCHECK(!frame_ || frame_ == frame);
1864 // At this point we should have non-null data source.
1865 DCHECK(frame->dataSource());
1866 if (!ChildThread::current())
1867 return NULL; // May be null in some tests.
1868 ServiceWorkerNetworkProvider* provider =
1869 ServiceWorkerNetworkProvider::FromDocumentState(
1870 DocumentState::FromDataSource(frame->dataSource()));
1871 return new WebServiceWorkerProviderImpl(
1872 ChildThread::current()->thread_safe_sender(),
1873 provider ? provider->context() : NULL);
1876 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame* frame) {
1877 DCHECK(!frame_ || frame_ == frame);
1878 // Notify the browser process that it is no longer safe to show the pending
1879 // URL of the main frame, since a URL spoof is now possible.
1880 if (!frame->parent() && render_view_->page_id_ == -1)
1881 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_));
1884 blink::WebFrame* RenderFrameImpl::createChildFrame(
1885 blink::WebLocalFrame* parent,
1886 const blink::WebString& name) {
1887 // Synchronously notify the browser of a child frame creation to get the
1888 // routing_id for the RenderFrame.
1889 int child_routing_id = MSG_ROUTING_NONE;
1890 Send(new FrameHostMsg_CreateChildFrame(routing_id_,
1891 base::UTF16ToUTF8(name),
1892 &child_routing_id));
1893 // Allocation of routing id failed, so we can't create a child frame. This can
1894 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
1895 // out state.
1896 if (child_routing_id == MSG_ROUTING_NONE) {
1897 #if !defined(OS_LINUX)
1898 // DumpWithoutCrashing() crashes on Linux in renderer processes when
1899 // breakpad and sandboxing are enabled: crbug.com/349600
1900 base::debug::Alias(parent);
1901 base::debug::Alias(&routing_id_);
1902 bool render_view_is_swapped_out = GetRenderWidget()->is_swapped_out();
1903 base::debug::Alias(&render_view_is_swapped_out);
1904 bool render_view_is_closing = GetRenderWidget()->closing();
1905 base::debug::Alias(&render_view_is_closing);
1906 base::debug::Alias(&is_swapped_out_);
1907 base::debug::DumpWithoutCrashing();
1908 #endif
1909 return NULL;
1912 // Create the RenderFrame and WebLocalFrame, linking the two.
1913 RenderFrameImpl* child_render_frame = RenderFrameImpl::Create(
1914 render_view_.get(), child_routing_id);
1915 blink::WebLocalFrame* web_frame = WebLocalFrame::create(child_render_frame);
1916 child_render_frame->SetWebFrame(web_frame);
1918 // Add the frame to the frame tree and initialize it.
1919 parent->appendChild(web_frame);
1920 child_render_frame->Initialize();
1922 return web_frame;
1925 void RenderFrameImpl::didDisownOpener(blink::WebLocalFrame* frame) {
1926 DCHECK(!frame_ || frame_ == frame);
1927 // We only need to notify the browser if the active, top-level frame clears
1928 // its opener. We can ignore cases where a swapped out frame clears its
1929 // opener after hearing about it from the browser, and the browser does not
1930 // (yet) care about subframe openers.
1931 if (is_swapped_out_ || frame->parent())
1932 return;
1934 // Notify WebContents and all its swapped out RenderViews.
1935 Send(new FrameHostMsg_DidDisownOpener(routing_id_));
1938 void RenderFrameImpl::frameDetached(blink::WebFrame* frame) {
1939 // NOTE: This function is called on the frame that is being detached and not
1940 // the parent frame. This is different from createChildFrame() which is
1941 // called on the parent frame.
1942 CHECK(!is_detaching_);
1943 DCHECK(!frame_ || frame_ == frame);
1945 bool is_subframe = !!frame->parent();
1947 Send(new FrameHostMsg_Detach(routing_id_));
1949 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
1950 // sent before setting |is_detaching_| to true. In contrast, Observers
1951 // should only be notified afterwards so they cannot call back into here and
1952 // have IPCs fired off.
1953 is_detaching_ = true;
1955 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
1956 FrameDetached(frame));
1958 // We need to clean up subframes by removing them from the map and deleting
1959 // the RenderFrameImpl. In contrast, the main frame is owned by its
1960 // containing RenderViewHost (so that they have the same lifetime), so only
1961 // removal from the map is needed and no deletion.
1962 FrameMap::iterator it = g_frame_map.Get().find(frame);
1963 CHECK(it != g_frame_map.Get().end());
1964 CHECK_EQ(it->second, this);
1965 g_frame_map.Get().erase(it);
1967 if (is_subframe)
1968 frame->parent()->removeChild(frame);
1970 // |frame| is invalid after here.
1971 frame->close();
1973 if (is_subframe) {
1974 delete this;
1975 // Object is invalid after this point.
1979 void RenderFrameImpl::frameFocused() {
1980 Send(new FrameHostMsg_FrameFocused(routing_id_));
1983 void RenderFrameImpl::willClose(blink::WebFrame* frame) {
1984 DCHECK(!frame_ || frame_ == frame);
1986 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FrameWillClose());
1987 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
1988 FrameWillClose(frame));
1991 void RenderFrameImpl::didChangeName(blink::WebLocalFrame* frame,
1992 const blink::WebString& name) {
1993 DCHECK(!frame_ || frame_ == frame);
1994 if (!render_view_->renderer_preferences_.report_frame_name_changes)
1995 return;
1997 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeName(name));
2000 void RenderFrameImpl::didMatchCSS(
2001 blink::WebLocalFrame* frame,
2002 const blink::WebVector<blink::WebString>& newly_matching_selectors,
2003 const blink::WebVector<blink::WebString>& stopped_matching_selectors) {
2004 DCHECK(!frame_ || frame_ == frame);
2006 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2007 DidMatchCSS(frame,
2008 newly_matching_selectors,
2009 stopped_matching_selectors));
2012 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2013 const blink::WebString& source) {
2014 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2015 source);
2018 void RenderFrameImpl::didAddMessageToConsole(
2019 const blink::WebConsoleMessage& message,
2020 const blink::WebString& source_name,
2021 unsigned source_line,
2022 const blink::WebString& stack_trace) {
2023 logging::LogSeverity log_severity = logging::LOG_VERBOSE;
2024 switch (message.level) {
2025 case blink::WebConsoleMessage::LevelDebug:
2026 log_severity = logging::LOG_VERBOSE;
2027 break;
2028 case blink::WebConsoleMessage::LevelLog:
2029 case blink::WebConsoleMessage::LevelInfo:
2030 log_severity = logging::LOG_INFO;
2031 break;
2032 case blink::WebConsoleMessage::LevelWarning:
2033 log_severity = logging::LOG_WARNING;
2034 break;
2035 case blink::WebConsoleMessage::LevelError:
2036 log_severity = logging::LOG_ERROR;
2037 break;
2038 default:
2039 NOTREACHED();
2042 if (shouldReportDetailedMessageForSource(source_name)) {
2043 FOR_EACH_OBSERVER(
2044 RenderFrameObserver, observers_,
2045 DetailedConsoleMessageAdded(message.text,
2046 source_name,
2047 stack_trace,
2048 source_line,
2049 static_cast<int32>(log_severity)));
2052 Send(new FrameHostMsg_AddMessageToConsole(routing_id_,
2053 static_cast<int32>(log_severity),
2054 message.text,
2055 static_cast<int32>(source_line),
2056 source_name));
2059 void RenderFrameImpl::loadURLExternally(
2060 blink::WebLocalFrame* frame,
2061 const blink::WebURLRequest& request,
2062 blink::WebNavigationPolicy policy,
2063 const blink::WebString& suggested_name) {
2064 DCHECK(!frame_ || frame_ == frame);
2065 Referrer referrer(RenderViewImpl::GetReferrerFromRequest(frame, request));
2066 if (policy == blink::WebNavigationPolicyDownload) {
2067 render_view_->Send(new ViewHostMsg_DownloadUrl(render_view_->GetRoutingID(),
2068 request.url(), referrer,
2069 suggested_name));
2070 } else {
2071 OpenURL(frame, request.url(), referrer, policy);
2075 blink::WebNavigationPolicy RenderFrameImpl::decidePolicyForNavigation(
2076 const NavigationPolicyInfo& info) {
2077 DCHECK(!frame_ || frame_ == info.frame);
2078 return DecidePolicyForNavigation(this, info);
2081 blink::WebHistoryItem RenderFrameImpl::historyItemForNewChildFrame(
2082 blink::WebFrame* frame) {
2083 DCHECK(!frame_ || frame_ == frame);
2084 return render_view_->history_controller()->GetItemForNewChildFrame(this);
2087 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame* frame,
2088 const blink::WebFormElement& form) {
2089 DCHECK(!frame_ || frame_ == frame);
2091 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2092 WillSendSubmitEvent(frame, form));
2095 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame* frame,
2096 const blink::WebFormElement& form) {
2097 DCHECK(!frame_ || frame_ == frame);
2098 DocumentState* document_state =
2099 DocumentState::FromDataSource(frame->provisionalDataSource());
2100 NavigationState* navigation_state = document_state->navigation_state();
2101 InternalDocumentStateData* internal_data =
2102 InternalDocumentStateData::FromDocumentState(document_state);
2104 if (ui::PageTransitionCoreTypeIs(navigation_state->transition_type(),
2105 ui::PAGE_TRANSITION_LINK)) {
2106 navigation_state->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT);
2109 // Save these to be processed when the ensuing navigation is committed.
2110 WebSearchableFormData web_searchable_form_data(form);
2111 internal_data->set_searchable_form_url(web_searchable_form_data.url());
2112 internal_data->set_searchable_form_encoding(
2113 web_searchable_form_data.encoding().utf8());
2115 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2116 WillSubmitForm(frame, form));
2119 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame* frame,
2120 blink::WebDataSource* datasource) {
2121 DCHECK(!frame_ || frame_ == frame);
2123 // TODO(nasko): Move implementation here. Needed state:
2124 // * pending_navigation_params_
2125 // * webview
2126 // Needed methods:
2127 // * PopulateDocumentStateFromPending
2128 // * CreateNavigationStateFromPending
2129 render_view_->didCreateDataSource(frame, datasource);
2131 // Create the serviceworker's per-document network observing object.
2132 scoped_ptr<ServiceWorkerNetworkProvider>
2133 network_provider(new ServiceWorkerNetworkProvider());
2134 ServiceWorkerNetworkProvider::AttachToDocumentState(
2135 DocumentState::FromDataSource(datasource),
2136 network_provider.Pass());
2139 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame* frame,
2140 bool is_transition_navigation) {
2141 DCHECK(!frame_ || frame_ == frame);
2142 WebDataSource* ds = frame->provisionalDataSource();
2144 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2145 // callback is invoked.
2146 if (!ds)
2147 return;
2149 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2150 "id", routing_id_, "url", ds->request().url().string().utf8());
2151 DocumentState* document_state = DocumentState::FromDataSource(ds);
2153 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2154 CHECK((ds->request().url() != GURL(kSwappedOutURL)) ||
2155 is_swapped_out_) <<
2156 "Heard swappedout:// when not swapped out.";
2158 // Update the request time if WebKit has better knowledge of it.
2159 if (document_state->request_time().is_null()) {
2160 double event_time = ds->triggeringEventTime();
2161 if (event_time != 0.0)
2162 document_state->set_request_time(Time::FromDoubleT(event_time));
2165 // Start time is only set after request time.
2166 document_state->set_start_load_time(Time::Now());
2168 bool is_top_most = !frame->parent();
2169 if (is_top_most) {
2170 render_view_->set_navigation_gesture(
2171 WebUserGestureIndicator::isProcessingUserGesture() ?
2172 NavigationGestureUser : NavigationGestureAuto);
2173 } else if (ds->replacesCurrentHistoryItem()) {
2174 // Subframe navigations that don't add session history items must be
2175 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2176 // handle loading of error pages.
2177 document_state->navigation_state()->set_transition_type(
2178 ui::PAGE_TRANSITION_AUTO_SUBFRAME);
2181 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2182 DidStartProvisionalLoad(frame));
2183 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidStartProvisionalLoad());
2185 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2186 routing_id_, ds->request().url(), is_transition_navigation));
2189 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2190 blink::WebLocalFrame* frame) {
2191 DCHECK(!frame_ || frame_ == frame);
2192 render_view_->history_controller()->RemoveChildrenForRedirect(this);
2195 void RenderFrameImpl::didFailProvisionalLoad(blink::WebLocalFrame* frame,
2196 const blink::WebURLError& error) {
2197 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2198 "id", routing_id_);
2199 DCHECK(!frame_ || frame_ == frame);
2200 WebDataSource* ds = frame->provisionalDataSource();
2201 DCHECK(ds);
2203 const WebURLRequest& failed_request = ds->request();
2205 // Notify the browser that we failed a provisional load with an error.
2207 // Note: It is important this notification occur before DidStopLoading so the
2208 // SSL manager can react to the provisional load failure before being
2209 // notified the load stopped.
2211 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2212 DidFailProvisionalLoad(frame, error));
2213 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
2214 DidFailProvisionalLoad(error));
2216 bool show_repost_interstitial =
2217 (error.reason == net::ERR_CACHE_MISS &&
2218 EqualsASCII(failed_request.httpMethod(), "POST"));
2220 FrameHostMsg_DidFailProvisionalLoadWithError_Params params;
2221 params.error_code = error.reason;
2222 GetContentClient()->renderer()->GetNavigationErrorStrings(
2223 render_view_.get(),
2224 frame,
2225 failed_request,
2226 error,
2227 NULL,
2228 &params.error_description);
2229 params.url = error.unreachableURL;
2230 params.showing_repost_interstitial = show_repost_interstitial;
2231 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(
2232 routing_id_, params));
2234 // Don't display an error page if this is simply a cancelled load. Aside
2235 // from being dumb, WebCore doesn't expect it and it will cause a crash.
2236 if (error.reason == net::ERR_ABORTED)
2237 return;
2239 // Don't display "client blocked" error page if browser has asked us not to.
2240 if (error.reason == net::ERR_BLOCKED_BY_CLIENT &&
2241 render_view_->renderer_preferences_.disable_client_blocked_error_page) {
2242 return;
2245 // Allow the embedder to suppress an error page.
2246 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(this,
2247 error.unreachableURL)) {
2248 return;
2251 if (RenderThreadImpl::current() &&
2252 RenderThreadImpl::current()->layout_test_mode()) {
2253 return;
2256 // Make sure we never show errors in view source mode.
2257 frame->enableViewSourceMode(false);
2259 DocumentState* document_state = DocumentState::FromDataSource(ds);
2260 NavigationState* navigation_state = document_state->navigation_state();
2262 // If this is a failed back/forward/reload navigation, then we need to do a
2263 // 'replace' load. This is necessary to avoid messing up session history.
2264 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2265 // as session history is concerned.
2267 // AUTO_SUBFRAME loads should always be treated as loads that do not advance
2268 // the page id.
2270 // TODO(davidben): This should also take the failed navigation's replacement
2271 // state into account, if a location.replace() failed.
2272 bool replace =
2273 navigation_state->pending_page_id() != -1 ||
2274 ui::PageTransitionCoreTypeIs(navigation_state->transition_type(),
2275 ui::PAGE_TRANSITION_AUTO_SUBFRAME);
2277 // If we failed on a browser initiated request, then make sure that our error
2278 // page load is regarded as the same browser initiated request.
2279 if (!navigation_state->is_content_initiated()) {
2280 render_view_->pending_navigation_params_.reset(
2281 new FrameMsg_Navigate_Params);
2282 render_view_->pending_navigation_params_->page_id =
2283 navigation_state->pending_page_id();
2284 render_view_->pending_navigation_params_->pending_history_list_offset =
2285 navigation_state->pending_history_list_offset();
2286 render_view_->pending_navigation_params_->should_clear_history_list =
2287 navigation_state->history_list_was_cleared();
2288 render_view_->pending_navigation_params_->common_params.transition =
2289 navigation_state->transition_type();
2290 render_view_->pending_navigation_params_->request_time =
2291 document_state->request_time();
2292 render_view_->pending_navigation_params_->should_replace_current_entry =
2293 replace;
2296 // Load an error page.
2297 LoadNavigationErrorPage(failed_request, error, replace);
2300 void RenderFrameImpl::didCommitProvisionalLoad(
2301 blink::WebLocalFrame* frame,
2302 const blink::WebHistoryItem& item,
2303 blink::WebHistoryCommitType commit_type) {
2304 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2305 "id", routing_id_,
2306 "url", GetLoadingUrl().possibly_invalid_spec());
2307 DCHECK(!frame_ || frame_ == frame);
2308 DocumentState* document_state =
2309 DocumentState::FromDataSource(frame->dataSource());
2310 NavigationState* navigation_state = document_state->navigation_state();
2312 if (proxy_routing_id_ != MSG_ROUTING_NONE) {
2313 RenderFrameProxy* proxy =
2314 RenderFrameProxy::FromRoutingID(proxy_routing_id_);
2315 CHECK(proxy);
2316 proxy->web_frame()->swap(frame_);
2317 proxy_routing_id_ = MSG_ROUTING_NONE;
2320 // When we perform a new navigation, we need to update the last committed
2321 // session history entry with state for the page we are leaving. Do this
2322 // before updating the HistoryController state.
2323 render_view_->UpdateSessionHistory(frame);
2325 render_view_->history_controller()->UpdateForCommit(this, item, commit_type,
2326 navigation_state->was_within_same_page());
2328 InternalDocumentStateData* internal_data =
2329 InternalDocumentStateData::FromDocumentState(document_state);
2331 if (document_state->commit_load_time().is_null())
2332 document_state->set_commit_load_time(Time::Now());
2334 if (internal_data->must_reset_scroll_and_scale_state()) {
2335 render_view_->webview()->resetScrollAndScaleState();
2336 internal_data->set_must_reset_scroll_and_scale_state(false);
2338 internal_data->set_use_error_page(false);
2340 bool is_new_navigation = commit_type == blink::WebStandardCommit;
2341 if (is_new_navigation) {
2342 // We bump our Page ID to correspond with the new session history entry.
2343 render_view_->page_id_ = render_view_->next_page_id_++;
2345 // Don't update history_page_ids_ (etc) for kSwappedOutURL, since
2346 // we don't want to forget the entry that was there, and since we will
2347 // never come back to kSwappedOutURL. Note that we have to call
2348 // UpdateSessionHistory and update page_id_ even in this case, so that
2349 // the current entry gets a state update and so that we don't send a
2350 // state update to the wrong entry when we swap back in.
2351 if (GetLoadingUrl() != GURL(kSwappedOutURL)) {
2352 // Advance our offset in session history, applying the length limit.
2353 // There is now no forward history.
2354 render_view_->history_list_offset_++;
2355 if (render_view_->history_list_offset_ >= kMaxSessionHistoryEntries)
2356 render_view_->history_list_offset_ = kMaxSessionHistoryEntries - 1;
2357 render_view_->history_list_length_ =
2358 render_view_->history_list_offset_ + 1;
2359 render_view_->history_page_ids_.resize(
2360 render_view_->history_list_length_, -1);
2361 render_view_->history_page_ids_[render_view_->history_list_offset_] =
2362 render_view_->page_id_;
2364 } else {
2365 // Inspect the navigation_state on this frame to see if the navigation
2366 // corresponds to a session history navigation... Note: |frame| may or
2367 // may not be the toplevel frame, but for the case of capturing session
2368 // history, the first committed frame suffices. We keep track of whether
2369 // we've seen this commit before so that only capture session history once
2370 // per navigation.
2372 // Note that we need to check if the page ID changed. In the case of a
2373 // reload, the page ID doesn't change, and UpdateSessionHistory gets the
2374 // previous URL and the current page ID, which would be wrong.
2375 if (navigation_state->pending_page_id() != -1 &&
2376 navigation_state->pending_page_id() != render_view_->page_id_ &&
2377 !navigation_state->request_committed()) {
2378 // This is a successful session history navigation!
2379 render_view_->page_id_ = navigation_state->pending_page_id();
2381 render_view_->history_list_offset_ =
2382 navigation_state->pending_history_list_offset();
2384 // If the history list is valid, our list of page IDs should be correct.
2385 DCHECK(render_view_->history_list_length_ <= 0 ||
2386 render_view_->history_list_offset_ < 0 ||
2387 render_view_->history_list_offset_ >=
2388 render_view_->history_list_length_ ||
2389 render_view_->history_page_ids_[render_view_->history_list_offset_]
2390 == render_view_->page_id_);
2394 bool sent = Send(
2395 new FrameHostMsg_DidAssignPageId(routing_id_, render_view_->page_id_));
2396 CHECK(sent); // http://crbug.com/407376
2398 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers_,
2399 DidCommitProvisionalLoad(frame, is_new_navigation));
2400 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
2401 DidCommitProvisionalLoad(is_new_navigation));
2403 if (!frame->parent()) { // Only for top frames.
2404 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
2405 if (render_thread_impl) { // Can be NULL in tests.
2406 render_thread_impl->histogram_customizer()->
2407 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2408 RenderViewImpl::GetRenderViewCount());
2412 // Remember that we've already processed this request, so we don't update
2413 // the session history again. We do this regardless of whether this is
2414 // a session history navigation, because if we attempted a session history
2415 // navigation without valid HistoryItem state, WebCore will think it is a
2416 // new navigation.
2417 navigation_state->set_request_committed(true);
2419 SendDidCommitProvisionalLoad(frame);
2421 // Check whether we have new encoding name.
2422 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2425 void RenderFrameImpl::didCreateNewDocument(blink::WebLocalFrame* frame) {
2426 DCHECK(!frame_ || frame_ == frame);
2428 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2429 DidCreateNewDocument(frame));
2432 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame* frame) {
2433 DCHECK(!frame_ || frame_ == frame);
2434 // TODO(nasko): Move implementation here. Needed state:
2435 // * enabled_bindings_
2436 // * dom_automation_controller_
2437 // * stats_collection_controller_
2439 render_view_->didClearWindowObject(frame);
2441 if (render_view_->GetEnabledBindings() & BINDINGS_POLICY_DOM_AUTOMATION)
2442 DomAutomationController::Install(this, frame);
2444 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidClearWindowObject());
2447 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame* frame) {
2448 DCHECK(!frame_ || frame_ == frame);
2450 // Notify the browser about non-blank documents loading in the top frame.
2451 GURL url = frame->document().url();
2452 if (url.is_valid() && url.spec() != url::kAboutBlankURL) {
2453 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2454 // frame->tree()->top().
2455 blink::WebFrame* main_frame = render_view_->webview()->mainFrame();
2456 if (frame == main_frame) {
2457 // For now, don't remember plugin zoom values. We don't want to mix them
2458 // with normal web content (i.e. a fixed layout plugin would usually want
2459 // them different).
2460 render_view_->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2461 render_view_->GetRoutingID(),
2462 main_frame->document().isPluginDocument()));
2466 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2467 DidCreateDocumentElement(frame));
2470 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame* frame,
2471 const blink::WebString& title,
2472 blink::WebTextDirection direction) {
2473 DCHECK(!frame_ || frame_ == frame);
2474 // Ignore all but top level navigations.
2475 if (!frame->parent()) {
2476 base::string16 title16 = title;
2477 base::debug::TraceLog::GetInstance()->UpdateProcessLabel(
2478 routing_id_, base::UTF16ToUTF8(title16));
2480 base::string16 shortened_title = title16.substr(0, kMaxTitleChars);
2481 Send(new FrameHostMsg_UpdateTitle(routing_id_,
2482 shortened_title, direction));
2485 // Also check whether we have new encoding name.
2486 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2489 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame* frame,
2490 blink::WebIconURL::Type icon_type) {
2491 DCHECK(!frame_ || frame_ == frame);
2492 // TODO(nasko): Investigate wheather implementation should move here.
2493 render_view_->didChangeIcon(frame, icon_type);
2496 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame* frame) {
2497 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2498 "id", routing_id_);
2499 DCHECK(!frame_ || frame_ == frame);
2500 WebDataSource* ds = frame->dataSource();
2501 DocumentState* document_state = DocumentState::FromDataSource(ds);
2502 document_state->set_finish_document_load_time(Time::Now());
2504 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_));
2506 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2507 DidFinishDocumentLoad(frame));
2508 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidFinishDocumentLoad());
2510 // Check whether we have new encoding name.
2511 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2514 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame* frame) {
2515 DCHECK(!frame_ || frame_ == frame);
2516 if (!frame->parent())
2517 Send(new FrameHostMsg_DocumentOnLoadCompleted(routing_id_));
2520 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame* frame,
2521 const blink::WebURLError& error) {
2522 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2523 "id", routing_id_);
2524 DCHECK(!frame_ || frame_ == frame);
2525 // TODO(nasko): Move implementation here. No state needed.
2526 WebDataSource* ds = frame->dataSource();
2527 DCHECK(ds);
2529 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2530 DidFailLoad(frame, error));
2532 const WebURLRequest& failed_request = ds->request();
2533 base::string16 error_description;
2534 GetContentClient()->renderer()->GetNavigationErrorStrings(
2535 render_view_.get(),
2536 frame,
2537 failed_request,
2538 error,
2539 NULL,
2540 &error_description);
2541 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_,
2542 failed_request.url(),
2543 error.reason,
2544 error_description));
2547 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame* frame) {
2548 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2549 "id", routing_id_);
2550 DCHECK(!frame_ || frame_ == frame);
2551 WebDataSource* ds = frame->dataSource();
2552 DocumentState* document_state = DocumentState::FromDataSource(ds);
2553 if (document_state->finish_load_time().is_null()) {
2554 if (!frame->parent()) {
2555 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2556 TRACE_EVENT_SCOPE_PROCESS);
2558 document_state->set_finish_load_time(Time::Now());
2561 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2562 DidFinishLoad(frame));
2563 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidFinishLoad());
2565 // Don't send this message while the frame is swapped out.
2566 if (is_swapped_out())
2567 return;
2569 Send(new FrameHostMsg_DidFinishLoad(routing_id_,
2570 ds->request().url()));
2573 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame* frame,
2574 const blink::WebHistoryItem& item,
2575 blink::WebHistoryCommitType commit_type) {
2576 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
2577 "id", routing_id_);
2578 DCHECK(!frame_ || frame_ == frame);
2579 // If this was a reference fragment navigation that we initiated, then we
2580 // could end up having a non-null pending navigation params. We just need to
2581 // update the ExtraData on the datasource so that others who read the
2582 // ExtraData will get the new NavigationState. Similarly, if we did not
2583 // initiate this navigation, then we need to take care to reset any pre-
2584 // existing navigation state to a content-initiated navigation state.
2585 // DidCreateDataSource conveniently takes care of this for us.
2586 didCreateDataSource(frame, frame->dataSource());
2588 DocumentState* document_state =
2589 DocumentState::FromDataSource(frame->dataSource());
2590 NavigationState* new_state = document_state->navigation_state();
2591 new_state->set_was_within_same_page(true);
2593 didCommitProvisionalLoad(frame, item, commit_type);
2596 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame* frame) {
2597 DCHECK(!frame_ || frame_ == frame);
2598 // TODO(nasko): Move implementation here. Needed methods:
2599 // * StartNavStateSyncTimerIfNecessary
2600 render_view_->didUpdateCurrentHistoryItem(frame);
2603 void RenderFrameImpl::addNavigationTransitionData(
2604 const blink::WebTransitionElementData& data) {
2605 FrameHostMsg_AddNavigationTransitionData_Params params;
2606 params.render_frame_id = routing_id_;
2607 params.allowed_destination_host_pattern =
2608 data.scope.utf8();
2609 params.selector = data.selector.utf8();
2610 params.markup = data.markup.utf8();
2611 params.elements.resize(data.elements.size());
2612 for (size_t i = 0; i < data.elements.size(); i++) {
2613 params.elements[i].id = data.elements[i].id.utf8();
2614 params.elements[i].rect = gfx::Rect(data.elements[i].rect);
2617 Send(new FrameHostMsg_AddNavigationTransitionData(params));
2620 void RenderFrameImpl::didChangeThemeColor() {
2621 if (frame_->parent())
2622 return;
2624 Send(new FrameHostMsg_DidChangeThemeColor(
2625 routing_id_, frame_->document().themeColor()));
2628 void RenderFrameImpl::requestNotificationPermission(
2629 const blink::WebSecurityOrigin& origin,
2630 blink::WebNotificationPermissionCallback* callback) {
2631 if (!notification_permission_dispatcher_) {
2632 notification_permission_dispatcher_ =
2633 new NotificationPermissionDispatcher(this);
2636 notification_permission_dispatcher_->RequestPermission(origin, callback);
2639 void RenderFrameImpl::didChangeSelection(bool is_empty_selection) {
2640 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_)
2641 return;
2643 if (is_empty_selection)
2644 selection_text_.clear();
2646 // UpdateTextInputType should be called before SyncSelectionIfRequired.
2647 // UpdateTextInputType may send TextInputTypeChanged to notify the focus
2648 // was changed, and SyncSelectionIfRequired may send SelectionChanged
2649 // to notify the selection was changed. Focus change should be notified
2650 // before selection change.
2651 GetRenderWidget()->UpdateTextInputType();
2652 SyncSelectionIfRequired();
2653 #if defined(OS_ANDROID)
2654 GetRenderWidget()->UpdateTextInputState(RenderWidget::NO_SHOW_IME,
2655 RenderWidget::FROM_NON_IME);
2656 #endif
2659 blink::WebColorChooser* RenderFrameImpl::createColorChooser(
2660 blink::WebColorChooserClient* client,
2661 const blink::WebColor& initial_color,
2662 const blink::WebVector<blink::WebColorSuggestion>& suggestions) {
2663 RendererWebColorChooserImpl* color_chooser =
2664 new RendererWebColorChooserImpl(this, client);
2665 std::vector<ColorSuggestion> color_suggestions;
2666 for (size_t i = 0; i < suggestions.size(); i++) {
2667 color_suggestions.push_back(ColorSuggestion(suggestions[i]));
2669 color_chooser->Open(static_cast<SkColor>(initial_color), color_suggestions);
2670 return color_chooser;
2673 void RenderFrameImpl::runModalAlertDialog(const blink::WebString& message) {
2674 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT,
2675 message,
2676 base::string16(),
2677 frame_->document().url(),
2678 NULL);
2681 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString& message) {
2682 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM,
2683 message,
2684 base::string16(),
2685 frame_->document().url(),
2686 NULL);
2689 bool RenderFrameImpl::runModalPromptDialog(
2690 const blink::WebString& message,
2691 const blink::WebString& default_value,
2692 blink::WebString* actual_value) {
2693 base::string16 result;
2694 bool ok = RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT,
2695 message,
2696 default_value,
2697 frame_->document().url(),
2698 &result);
2699 if (ok)
2700 actual_value->assign(result);
2701 return ok;
2704 bool RenderFrameImpl::runModalBeforeUnloadDialog(
2705 bool is_reload,
2706 const blink::WebString& message) {
2707 // If we are swapping out, we have already run the beforeunload handler.
2708 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
2709 // at all, to avoid running it twice.
2710 if (is_swapped_out_)
2711 return true;
2713 // Don't allow further dialogs if we are waiting to swap out, since the
2714 // PageGroupLoadDeferrer in our stack prevents it.
2715 if (render_view()->suppress_dialogs_until_swap_out_)
2716 return false;
2718 bool success = false;
2719 // This is an ignored return value, but is included so we can accept the same
2720 // response as RunJavaScriptMessage.
2721 base::string16 ignored_result;
2722 render_view()->SendAndRunNestedMessageLoop(
2723 new FrameHostMsg_RunBeforeUnloadConfirm(
2724 routing_id_, frame_->document().url(), message, is_reload,
2725 &success, &ignored_result));
2726 return success;
2729 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData& data) {
2730 ContextMenuParams params = ContextMenuParamsBuilder::Build(data);
2731 params.source_type = GetRenderWidget()->context_menu_source_type();
2732 GetRenderWidget()->OnShowHostContextMenu(&params);
2733 if (GetRenderWidget()->has_host_context_menu_location()) {
2734 params.x = GetRenderWidget()->host_context_menu_location().x();
2735 params.y = GetRenderWidget()->host_context_menu_location().y();
2738 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
2739 // it. We replace it with an empty GURL so the appropriate items are disabled
2740 // in the context menu.
2741 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
2742 // data encoded images. We should have a way to save them.
2743 if (params.src_url.spec().size() > GetMaxURLChars())
2744 params.src_url = GURL();
2745 context_menu_node_ = data.node;
2747 #if defined(OS_ANDROID)
2748 gfx::Rect start_rect;
2749 gfx::Rect end_rect;
2750 GetRenderWidget()->GetSelectionBounds(&start_rect, &end_rect);
2751 params.selection_start = gfx::Point(start_rect.x(), start_rect.bottom());
2752 params.selection_end = gfx::Point(end_rect.right(), end_rect.bottom());
2753 #endif
2755 Send(new FrameHostMsg_ContextMenu(routing_id_, params));
2758 void RenderFrameImpl::clearContextMenu() {
2759 context_menu_node_.reset();
2762 void RenderFrameImpl::willSendRequest(
2763 blink::WebLocalFrame* frame,
2764 unsigned identifier,
2765 blink::WebURLRequest& request,
2766 const blink::WebURLResponse& redirect_response) {
2767 DCHECK(!frame_ || frame_ == frame);
2768 // The request my be empty during tests.
2769 if (request.url().isEmpty())
2770 return;
2772 // Set the first party for cookies url if it has not been set yet (new
2773 // requests). For redirects, it is updated by WebURLLoaderImpl.
2774 if (request.firstPartyForCookies().isEmpty()) {
2775 if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel) {
2776 request.setFirstPartyForCookies(request.url());
2777 } else {
2778 // TODO(nasko): When the top-level frame is remote, there is no document.
2779 // This is broken and should be fixed to propagate the first party.
2780 WebFrame* top = frame->top();
2781 if (top->isWebLocalFrame()) {
2782 request.setFirstPartyForCookies(
2783 frame->top()->document().firstPartyForCookies());
2788 WebFrame* top_frame = frame->top();
2789 // TODO(nasko): Hack around asking about top-frame data source. This means
2790 // for out-of-process iframes we are treating the current frame as the
2791 // top-level frame, which is wrong.
2792 if (!top_frame || top_frame->isWebRemoteFrame())
2793 top_frame = frame;
2794 WebDataSource* provisional_data_source = top_frame->provisionalDataSource();
2795 WebDataSource* top_data_source = top_frame->dataSource();
2796 WebDataSource* data_source =
2797 provisional_data_source ? provisional_data_source : top_data_source;
2799 DocumentState* document_state = DocumentState::FromDataSource(data_source);
2800 DCHECK(document_state);
2801 InternalDocumentStateData* internal_data =
2802 InternalDocumentStateData::FromDocumentState(document_state);
2803 NavigationState* navigation_state = document_state->navigation_state();
2804 ui::PageTransition transition_type = navigation_state->transition_type();
2805 WebDataSource* frame_ds = frame->provisionalDataSource();
2806 if (frame_ds && frame_ds->isClientRedirect()) {
2807 transition_type = ui::PageTransitionFromInt(
2808 transition_type | ui::PAGE_TRANSITION_CLIENT_REDIRECT);
2811 GURL request_url(request.url());
2812 GURL new_url;
2813 if (GetContentClient()->renderer()->WillSendRequest(
2814 frame,
2815 transition_type,
2816 request_url,
2817 request.firstPartyForCookies(),
2818 &new_url)) {
2819 request.setURL(WebURL(new_url));
2822 if (internal_data->is_cache_policy_override_set())
2823 request.setCachePolicy(internal_data->cache_policy_override());
2825 // The request's extra data may indicate that we should set a custom user
2826 // agent. This needs to be done here, after WebKit is through with setting the
2827 // user agent on its own. Similarly, it may indicate that we should set an
2828 // X-Requested-With header. This must be done here to avoid breaking CORS
2829 // checks.
2830 // PlzNavigate: there may also be a stream url associated with the request.
2831 WebString custom_user_agent;
2832 WebString requested_with;
2833 scoped_ptr<StreamOverrideParameters> stream_override;
2834 if (request.extraData()) {
2835 RequestExtraData* old_extra_data =
2836 static_cast<RequestExtraData*>(request.extraData());
2838 custom_user_agent = old_extra_data->custom_user_agent();
2839 if (!custom_user_agent.isNull()) {
2840 if (custom_user_agent.isEmpty())
2841 request.clearHTTPHeaderField("User-Agent");
2842 else
2843 request.setHTTPHeaderField("User-Agent", custom_user_agent);
2846 requested_with = old_extra_data->requested_with();
2847 if (!requested_with.isNull()) {
2848 if (requested_with.isEmpty())
2849 request.clearHTTPHeaderField("X-Requested-With");
2850 else
2851 request.setHTTPHeaderField("X-Requested-With", requested_with);
2853 stream_override = old_extra_data->TakeStreamOverrideOwnership();
2856 // Add the default accept header for frame request if it has not been set
2857 // already.
2858 if ((request.frameType() == blink::WebURLRequest::FrameTypeTopLevel ||
2859 request.frameType() == blink::WebURLRequest::FrameTypeNested) &&
2860 request.httpHeaderField(WebString::fromUTF8(kAcceptHeader)).isEmpty()) {
2861 request.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader),
2862 WebString::fromUTF8(kDefaultAcceptHeader));
2865 // Add an empty HTTP origin header for non GET methods if none is currently
2866 // present.
2867 request.addHTTPOriginIfNeeded(WebString());
2869 // Attach |should_replace_current_entry| state to requests so that, should
2870 // this navigation later require a request transfer, all state is preserved
2871 // when it is re-created in the new process.
2872 bool should_replace_current_entry = false;
2873 if (navigation_state->is_content_initiated()) {
2874 should_replace_current_entry = data_source->replacesCurrentHistoryItem();
2875 } else {
2876 // If the navigation is browser-initiated, the NavigationState contains the
2877 // correct value instead of the WebDataSource.
2879 // TODO(davidben): Avoid this awkward duplication of state. See comment on
2880 // NavigationState::should_replace_current_entry().
2881 should_replace_current_entry =
2882 navigation_state->should_replace_current_entry();
2885 int provider_id = kInvalidServiceWorkerProviderId;
2886 if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel ||
2887 request.frameType() == blink::WebURLRequest::FrameTypeNested) {
2888 // |provisionalDataSource| may be null in some content::ResourceFetcher
2889 // use cases, we don't hook those requests.
2890 if (frame->provisionalDataSource()) {
2891 ServiceWorkerNetworkProvider* provider =
2892 ServiceWorkerNetworkProvider::FromDocumentState(
2893 DocumentState::FromDataSource(frame->provisionalDataSource()));
2894 provider_id = provider->provider_id();
2896 } else if (frame->dataSource()) {
2897 ServiceWorkerNetworkProvider* provider =
2898 ServiceWorkerNetworkProvider::FromDocumentState(
2899 DocumentState::FromDataSource(frame->dataSource()));
2900 provider_id = provider->provider_id();
2903 WebFrame* parent = frame->parent();
2904 int parent_routing_id = MSG_ROUTING_NONE;
2905 if (!parent) {
2906 parent_routing_id = -1;
2907 } else if (parent->isWebLocalFrame()) {
2908 parent_routing_id = FromWebFrame(parent)->GetRoutingID();
2909 } else {
2910 parent_routing_id = RenderFrameProxy::FromWebFrame(parent)->routing_id();
2913 RequestExtraData* extra_data = new RequestExtraData();
2914 extra_data->set_visibility_state(render_view_->visibilityState());
2915 extra_data->set_custom_user_agent(custom_user_agent);
2916 extra_data->set_requested_with(requested_with);
2917 extra_data->set_render_frame_id(routing_id_);
2918 extra_data->set_is_main_frame(frame == top_frame);
2919 extra_data->set_frame_origin(
2920 GURL(frame->document().securityOrigin().toString()));
2921 extra_data->set_parent_is_main_frame(frame->parent() == top_frame);
2922 extra_data->set_parent_render_frame_id(parent_routing_id);
2923 extra_data->set_allow_download(navigation_state->allow_download());
2924 extra_data->set_transition_type(transition_type);
2925 extra_data->set_should_replace_current_entry(should_replace_current_entry);
2926 extra_data->set_transferred_request_child_id(
2927 navigation_state->transferred_request_child_id());
2928 extra_data->set_transferred_request_request_id(
2929 navigation_state->transferred_request_request_id());
2930 extra_data->set_service_worker_provider_id(provider_id);
2931 extra_data->set_stream_override(stream_override.Pass());
2932 request.setExtraData(extra_data);
2934 DocumentState* top_document_state =
2935 DocumentState::FromDataSource(top_data_source);
2936 if (top_document_state) {
2937 // TODO(gavinp): separate out prefetching and prerender field trials
2938 // if the rel=prerender rel type is sticking around.
2939 if (request.requestContext() == WebURLRequest::RequestContextPrefetch)
2940 top_document_state->set_was_prefetcher(true);
2943 // This is an instance where we embed a copy of the routing id
2944 // into the data portion of the message. This can cause problems if we
2945 // don't register this id on the browser side, since the download manager
2946 // expects to find a RenderViewHost based off the id.
2947 request.setRequestorID(render_view_->GetRoutingID());
2948 request.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
2950 if (!navigation_state->extra_headers().empty()) {
2951 for (net::HttpUtil::HeadersIterator i(
2952 navigation_state->extra_headers().begin(),
2953 navigation_state->extra_headers().end(), "\n");
2954 i.GetNext(); ) {
2955 if (LowerCaseEqualsASCII(i.name(), "referer")) {
2956 WebString referrer = WebSecurityPolicy::generateReferrerHeader(
2957 blink::WebReferrerPolicyDefault,
2958 request.url(),
2959 WebString::fromUTF8(i.values()));
2960 request.setHTTPReferrer(referrer, blink::WebReferrerPolicyDefault);
2961 } else {
2962 request.setHTTPHeaderField(WebString::fromUTF8(i.name()),
2963 WebString::fromUTF8(i.values()));
2968 if (!render_view_->renderer_preferences_.enable_referrers)
2969 request.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault);
2972 void RenderFrameImpl::didReceiveResponse(
2973 blink::WebLocalFrame* frame,
2974 unsigned identifier,
2975 const blink::WebURLResponse& response) {
2976 DCHECK(!frame_ || frame_ == frame);
2977 // Only do this for responses that correspond to a provisional data source
2978 // of the top-most frame. If we have a provisional data source, then we
2979 // can't have any sub-resources yet, so we know that this response must
2980 // correspond to a frame load.
2981 if (!frame->provisionalDataSource() || frame->parent())
2982 return;
2984 // If we are in view source mode, then just let the user see the source of
2985 // the server's error page.
2986 if (frame->isViewSourceModeEnabled())
2987 return;
2989 DocumentState* document_state =
2990 DocumentState::FromDataSource(frame->provisionalDataSource());
2991 int http_status_code = response.httpStatusCode();
2993 // Record page load flags.
2994 WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response);
2995 if (extra_data) {
2996 document_state->set_was_fetched_via_spdy(
2997 extra_data->was_fetched_via_spdy());
2998 document_state->set_was_npn_negotiated(
2999 extra_data->was_npn_negotiated());
3000 document_state->set_npn_negotiated_protocol(
3001 extra_data->npn_negotiated_protocol());
3002 document_state->set_was_alternate_protocol_available(
3003 extra_data->was_alternate_protocol_available());
3004 document_state->set_connection_info(
3005 extra_data->connection_info());
3006 document_state->set_was_fetched_via_proxy(
3007 extra_data->was_fetched_via_proxy());
3008 document_state->set_proxy_server(
3009 extra_data->proxy_server());
3011 InternalDocumentStateData* internal_data =
3012 InternalDocumentStateData::FromDocumentState(document_state);
3013 internal_data->set_http_status_code(http_status_code);
3014 // Whether or not the http status code actually corresponds to an error is
3015 // only checked when the page is done loading, if |use_error_page| is
3016 // still true.
3017 internal_data->set_use_error_page(true);
3020 void RenderFrameImpl::didFinishResourceLoad(blink::WebLocalFrame* frame,
3021 unsigned identifier) {
3022 DCHECK(!frame_ || frame_ == frame);
3023 InternalDocumentStateData* internal_data =
3024 InternalDocumentStateData::FromDataSource(frame->dataSource());
3025 if (!internal_data->use_error_page())
3026 return;
3028 // Do not show error page when DevTools is attached.
3029 if (render_view_->devtools_agent_->IsAttached())
3030 return;
3032 // Display error page, if appropriate.
3033 std::string error_domain = "http";
3034 int http_status_code = internal_data->http_status_code();
3035 if (GetContentClient()->renderer()->HasErrorPage(
3036 http_status_code, &error_domain)) {
3037 WebURLError error;
3038 error.unreachableURL = frame->document().url();
3039 error.domain = WebString::fromUTF8(error_domain);
3040 error.reason = http_status_code;
3041 LoadNavigationErrorPage(frame->dataSource()->request(), error, true);
3045 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3046 blink::WebLocalFrame* frame,
3047 const blink::WebURLRequest& request,
3048 const blink::WebURLResponse& response) {
3049 DCHECK(!frame_ || frame_ == frame);
3050 // The recipients of this message have no use for data: URLs: they don't
3051 // affect the page's insecure content list and are not in the disk cache. To
3052 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3053 // filter them out here.
3054 GURL url(request.url());
3055 if (url.SchemeIs(url::kDataScheme))
3056 return;
3058 // Let the browser know we loaded a resource from the memory cache. This
3059 // message is needed to display the correct SSL indicators.
3060 render_view_->Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(
3061 render_view_->GetRoutingID(),
3062 url,
3063 response.securityInfo(),
3064 request.httpMethod().utf8(),
3065 response.mimeType().utf8(),
3066 WebURLRequestToResourceType(request)));
3069 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame* frame) {
3070 DCHECK(!frame_ || frame_ == frame);
3071 render_view_->Send(new ViewHostMsg_DidDisplayInsecureContent(
3072 render_view_->GetRoutingID()));
3075 void RenderFrameImpl::didRunInsecureContent(
3076 blink::WebLocalFrame* frame,
3077 const blink::WebSecurityOrigin& origin,
3078 const blink::WebURL& target) {
3079 DCHECK(!frame_ || frame_ == frame);
3080 render_view_->Send(new ViewHostMsg_DidRunInsecureContent(
3081 render_view_->GetRoutingID(),
3082 origin.toString().utf8(),
3083 target));
3086 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame* frame) {
3087 DCHECK(!frame_ || frame_ == frame);
3088 #if defined(ENABLE_PLUGINS)
3089 if (frame != render_view_->webview()->mainFrame())
3090 return;
3091 PluginChannelHost::Broadcast(
3092 new PluginHostMsg_DidAbortLoading(render_view_->GetRoutingID()));
3093 #endif
3096 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame* frame,
3097 v8::Handle<v8::Context> context,
3098 int extension_group,
3099 int world_id) {
3100 DCHECK(!frame_ || frame_ == frame);
3101 GetContentClient()->renderer()->DidCreateScriptContext(
3102 frame, context, extension_group, world_id);
3105 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame* frame,
3106 v8::Handle<v8::Context> context,
3107 int world_id) {
3108 DCHECK(!frame_ || frame_ == frame);
3110 FOR_EACH_OBSERVER(RenderFrameObserver,
3111 observers_,
3112 WillReleaseScriptContext(context, world_id));
3115 void RenderFrameImpl::didFirstVisuallyNonEmptyLayout(
3116 blink::WebLocalFrame* frame) {
3117 DCHECK(!frame_ || frame_ == frame);
3118 if (frame->parent())
3119 return;
3121 InternalDocumentStateData* data =
3122 InternalDocumentStateData::FromDataSource(frame->dataSource());
3123 data->set_did_first_visually_non_empty_layout(true);
3125 #if defined(OS_ANDROID)
3126 GetRenderWidget()->DidChangeBodyBackgroundColor(
3127 render_view_->webwidget_->backgroundColor());
3128 #endif
3130 GetRenderWidget()->QueueMessage(
3131 new FrameHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_),
3132 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE);
3135 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame* frame) {
3136 DCHECK(!frame_ || frame_ == frame);
3137 // TODO(nasko): Move implementation here. Needed methods:
3138 // * StartNavStateSyncTimerIfNecessary
3139 render_view_->didChangeScrollOffset(frame);
3142 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame* frame) {
3143 DCHECK(!frame_ || frame_ == frame);
3144 if (!frame->parent()) {
3145 render_view_->Send(new ViewHostMsg_WillInsertBody(
3146 render_view_->GetRoutingID()));
3150 void RenderFrameImpl::reportFindInPageMatchCount(int request_id,
3151 int count,
3152 bool final_update) {
3153 int active_match_ordinal = -1; // -1 = don't update active match ordinal
3154 if (!count)
3155 active_match_ordinal = 0;
3157 render_view_->Send(new ViewHostMsg_Find_Reply(
3158 render_view_->GetRoutingID(), request_id, count,
3159 gfx::Rect(), active_match_ordinal, final_update));
3162 void RenderFrameImpl::reportFindInPageSelection(
3163 int request_id,
3164 int active_match_ordinal,
3165 const blink::WebRect& selection_rect) {
3166 render_view_->Send(new ViewHostMsg_Find_Reply(
3167 render_view_->GetRoutingID(), request_id, -1, selection_rect,
3168 active_match_ordinal, false));
3171 void RenderFrameImpl::requestStorageQuota(
3172 blink::WebLocalFrame* frame,
3173 blink::WebStorageQuotaType type,
3174 unsigned long long requested_size,
3175 blink::WebStorageQuotaCallbacks callbacks) {
3176 DCHECK(!frame_ || frame_ == frame);
3177 WebSecurityOrigin origin = frame->document().securityOrigin();
3178 if (origin.isUnique()) {
3179 // Unique origins cannot store persistent state.
3180 callbacks.didFail(blink::WebStorageQuotaErrorAbort);
3181 return;
3183 ChildThread::current()->quota_dispatcher()->RequestStorageQuota(
3184 render_view_->GetRoutingID(),
3185 GURL(origin.toString()),
3186 static_cast<storage::StorageType>(type),
3187 requested_size,
3188 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks));
3191 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle* handle) {
3192 WebSocketBridge* impl = static_cast<WebSocketBridge*>(handle);
3193 impl->set_render_frame_id(routing_id_);
3196 blink::WebGeolocationClient* RenderFrameImpl::geolocationClient() {
3197 if (!geolocation_dispatcher_)
3198 geolocation_dispatcher_ = new GeolocationDispatcher(this);
3199 return geolocation_dispatcher_;
3202 blink::WebPushClient* RenderFrameImpl::pushClient() {
3203 if (!push_messaging_dispatcher_)
3204 push_messaging_dispatcher_ = new PushMessagingDispatcher(this);
3205 return push_messaging_dispatcher_;
3208 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3209 blink::WebLocalFrame* frame,
3210 blink::WebRTCPeerConnectionHandler* handler) {
3211 DCHECK(!frame_ || frame_ == frame);
3212 #if defined(ENABLE_WEBRTC)
3213 static_cast<RTCPeerConnectionHandler*>(handler)->associateWithFrame(frame);
3214 #endif
3217 blink::WebUserMediaClient* RenderFrameImpl::userMediaClient() {
3218 if (!web_user_media_client_)
3219 InitializeUserMediaClient();
3220 return web_user_media_client_;
3223 blink::WebMIDIClient* RenderFrameImpl::webMIDIClient() {
3224 if (!midi_dispatcher_)
3225 midi_dispatcher_ = new MidiDispatcher(this);
3226 return midi_dispatcher_;
3229 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3230 blink::WebLocalFrame* source_frame,
3231 blink::WebFrame* target_frame,
3232 blink::WebSecurityOrigin target_origin,
3233 blink::WebDOMMessageEvent event) {
3234 DCHECK(!frame_ || frame_ == target_frame);
3236 if (!is_swapped_out_)
3237 return false;
3239 ViewMsg_PostMessage_Params params;
3240 params.is_data_raw_string = false;
3241 params.data = event.data().toString();
3242 params.source_origin = event.origin();
3243 if (!target_origin.isNull())
3244 params.target_origin = target_origin.toString();
3246 blink::WebMessagePortChannelArray channels = event.releaseChannels();
3247 if (!channels.isEmpty()) {
3248 std::vector<int> message_port_ids(channels.size());
3249 // Extract the port IDs from the channel array.
3250 for (size_t i = 0; i < channels.size(); ++i) {
3251 WebMessagePortChannelImpl* webchannel =
3252 static_cast<WebMessagePortChannelImpl*>(channels[i]);
3253 message_port_ids[i] = webchannel->message_port_id();
3254 webchannel->QueueMessages();
3255 DCHECK_NE(message_port_ids[i], MSG_ROUTING_NONE);
3257 params.message_port_ids = message_port_ids;
3260 // Include the routing ID for the source frame (if one exists), which the
3261 // browser process will translate into the routing ID for the equivalent
3262 // frame in the target process.
3263 params.source_routing_id = MSG_ROUTING_NONE;
3264 if (source_frame) {
3265 RenderViewImpl* source_view =
3266 RenderViewImpl::FromWebView(source_frame->view());
3267 if (source_view)
3268 params.source_routing_id = source_view->routing_id();
3271 Send(new ViewHostMsg_RouteMessageEvent(render_view_->routing_id_, params));
3272 return true;
3275 blink::WebString RenderFrameImpl::userAgentOverride(blink::WebLocalFrame* frame,
3276 const blink::WebURL& url) {
3277 DCHECK(!frame_ || frame_ == frame);
3278 std::string user_agent_override_for_url =
3279 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url));
3280 if (!user_agent_override_for_url.empty())
3281 return WebString::fromUTF8(user_agent_override_for_url);
3283 if (!render_view_->webview() || !render_view_->webview()->mainFrame() ||
3284 render_view_->renderer_preferences_.user_agent_override.empty()) {
3285 return blink::WebString();
3288 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3289 // associated with it, so the checks below are not valid. Temporarily
3290 // return early and fix properly as part of https://crbug.com/426555.
3291 if (render_view_->webview()->mainFrame()->isWebRemoteFrame())
3292 return blink::WebString();
3294 // If we're in the middle of committing a load, the data source we need
3295 // will still be provisional.
3296 WebFrame* main_frame = render_view_->webview()->mainFrame();
3297 WebDataSource* data_source = NULL;
3298 if (main_frame->provisionalDataSource())
3299 data_source = main_frame->provisionalDataSource();
3300 else
3301 data_source = main_frame->dataSource();
3303 InternalDocumentStateData* internal_data = data_source ?
3304 InternalDocumentStateData::FromDataSource(data_source) : NULL;
3305 if (internal_data && internal_data->is_overriding_user_agent())
3306 return WebString::fromUTF8(
3307 render_view_->renderer_preferences_.user_agent_override);
3308 return blink::WebString();
3311 blink::WebString RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame* frame) {
3312 DCHECK(!frame_ || frame_ == frame);
3313 if (render_view_->renderer_preferences_.enable_do_not_track)
3314 return WebString::fromUTF8("1");
3315 return WebString();
3318 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame* frame,
3319 bool default_value) {
3320 DCHECK(!frame_ || frame_ == frame);
3321 if (!default_value)
3322 return false;
3324 bool blocked = true;
3325 render_view_->Send(new ViewHostMsg_Are3DAPIsBlocked(
3326 render_view_->GetRoutingID(),
3327 GURL(frame->top()->document().securityOrigin().toString()),
3328 THREE_D_API_TYPE_WEBGL,
3329 &blocked));
3330 return !blocked;
3333 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame* frame,
3334 int arb_robustness_status_code) {
3335 DCHECK(!frame_ || frame_ == frame);
3336 render_view_->Send(new ViewHostMsg_DidLose3DContext(
3337 GURL(frame->top()->document().securityOrigin().toString()),
3338 THREE_D_API_TYPE_WEBGL,
3339 arb_robustness_status_code));
3342 blink::WebScreenOrientationClient*
3343 RenderFrameImpl::webScreenOrientationClient() {
3344 if (!screen_orientation_dispatcher_)
3345 screen_orientation_dispatcher_ = new ScreenOrientationDispatcher(this);
3346 return screen_orientation_dispatcher_;
3349 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource& data_source) {
3350 ServiceWorkerNetworkProvider* provider =
3351 ServiceWorkerNetworkProvider::FromDocumentState(
3352 DocumentState::FromDataSource(&data_source));
3353 return provider->context()->controller_handle_id() !=
3354 kInvalidServiceWorkerHandleId;
3357 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource& data_source) {
3358 ServiceWorkerNetworkProvider* provider =
3359 ServiceWorkerNetworkProvider::FromDocumentState(
3360 DocumentState::FromDataSource(&data_source));
3362 if (provider->context()->controller())
3363 return provider->context()->controller()->version_id();
3364 return kInvalidServiceWorkerVersionId;
3367 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject& obj,
3368 blink::WebAXEvent event) {
3369 HandleWebAccessibilityEvent(obj, event);
3372 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3373 int identifier,
3374 int match_index,
3375 const blink::WebAXObject& start_object,
3376 int start_offset,
3377 const blink::WebAXObject& end_object,
3378 int end_offset) {
3379 if (renderer_accessibility_) {
3380 renderer_accessibility_->HandleAccessibilityFindInPageResult(
3381 identifier, match_index, start_object, start_offset,
3382 end_object, end_offset);
3386 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame* frame)
3388 DCHECK(!frame_ || frame_ == frame);
3390 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeManifest());
3393 void RenderFrameImpl::DidPlay(blink::WebMediaPlayer* player) {
3394 Send(new FrameHostMsg_MediaPlayingNotification(
3395 routing_id_, reinterpret_cast<int64>(player), player->hasVideo(),
3396 player->hasAudio(), player->isRemote()));
3399 void RenderFrameImpl::DidPause(blink::WebMediaPlayer* player) {
3400 Send(new FrameHostMsg_MediaPausedNotification(
3401 routing_id_, reinterpret_cast<int64>(player)));
3404 void RenderFrameImpl::PlayerGone(blink::WebMediaPlayer* player) {
3405 DidPause(player);
3408 void RenderFrameImpl::AddObserver(RenderFrameObserver* observer) {
3409 observers_.AddObserver(observer);
3412 void RenderFrameImpl::RemoveObserver(RenderFrameObserver* observer) {
3413 observer->RenderFrameGone();
3414 observers_.RemoveObserver(observer);
3417 void RenderFrameImpl::OnStop() {
3418 DCHECK(frame_);
3419 frame_->stopLoading();
3420 if (!frame_->parent())
3421 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers_, OnStop());
3423 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, OnStop());
3426 void RenderFrameImpl::WasHidden() {
3427 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WasHidden());
3430 void RenderFrameImpl::WasShown() {
3431 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WasShown());
3434 bool RenderFrameImpl::IsHidden() {
3435 return GetRenderWidget()->is_hidden();
3438 // Tell the embedding application that the URL of the active page has changed.
3439 void RenderFrameImpl::SendDidCommitProvisionalLoad(blink::WebFrame* frame) {
3440 DCHECK(!frame_ || frame_ == frame);
3441 WebDataSource* ds = frame->dataSource();
3442 DCHECK(ds);
3444 const WebURLRequest& request = ds->request();
3445 const WebURLResponse& response = ds->response();
3447 DocumentState* document_state = DocumentState::FromDataSource(ds);
3448 NavigationState* navigation_state = document_state->navigation_state();
3449 InternalDocumentStateData* internal_data =
3450 InternalDocumentStateData::FromDocumentState(document_state);
3452 FrameHostMsg_DidCommitProvisionalLoad_Params params;
3453 params.http_status_code = response.httpStatusCode();
3454 params.url_is_unreachable = ds->hasUnreachableURL();
3455 params.is_post = false;
3456 params.post_id = -1;
3457 params.page_id = render_view_->page_id_;
3458 // We need to track the RenderViewHost routing_id because of downstream
3459 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3460 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3461 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3462 // based on the ID stored in the resource requests. Once those dependencies
3463 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3464 // client to be based on the routing_id of the RenderFrameHost.
3465 params.render_view_routing_id = render_view_->routing_id();
3466 params.socket_address.set_host(response.remoteIPAddress().utf8());
3467 params.socket_address.set_port(response.remotePort());
3468 WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response);
3469 if (extra_data)
3470 params.was_fetched_via_proxy = extra_data->was_fetched_via_proxy();
3471 params.was_within_same_page = navigation_state->was_within_same_page();
3472 params.security_info = response.securityInfo();
3474 // Set the URL to be displayed in the browser UI to the user.
3475 params.url = GetLoadingUrl();
3476 DCHECK(!is_swapped_out_ || params.url == GURL(kSwappedOutURL));
3478 if (frame->document().baseURL() != params.url)
3479 params.base_url = frame->document().baseURL();
3481 GetRedirectChain(ds, &params.redirects);
3482 params.should_update_history = !ds->hasUnreachableURL() &&
3483 !response.isMultipartPayload() && (response.httpStatusCode() != 404);
3485 params.searchable_form_url = internal_data->searchable_form_url();
3486 params.searchable_form_encoding = internal_data->searchable_form_encoding();
3488 params.gesture = render_view_->navigation_gesture_;
3489 render_view_->navigation_gesture_ = NavigationGestureUnknown;
3491 // Make navigation state a part of the DidCommitProvisionalLoad message so
3492 // that commited entry has it at all times.
3493 HistoryEntry* entry = render_view_->history_controller()->GetCurrentEntry();
3494 if (entry)
3495 params.page_state = HistoryEntryToPageState(entry);
3496 else
3497 params.page_state = PageState::CreateFromURL(request.url());
3499 if (!frame->parent()) {
3500 // Top-level navigation.
3502 // Reset the zoom limits in case a plugin had changed them previously. This
3503 // will also call us back which will cause us to send a message to
3504 // update WebContentsImpl.
3505 render_view_->webview()->zoomLimitsChanged(
3506 ZoomFactorToZoomLevel(kMinimumZoomFactor),
3507 ZoomFactorToZoomLevel(kMaximumZoomFactor));
3509 // Set zoom level, but don't do it for full-page plugin since they don't use
3510 // the same zoom settings.
3511 HostZoomLevels::iterator host_zoom =
3512 render_view_->host_zoom_levels_.find(GURL(request.url()));
3513 if (render_view_->webview()->mainFrame()->document().isPluginDocument()) {
3514 // Reset the zoom levels for plugins.
3515 render_view_->webview()->setZoomLevel(0);
3516 } else {
3517 // If the zoom level is not found, then do nothing. In-page navigation
3518 // relies on not changing the zoom level in this case.
3519 if (host_zoom != render_view_->host_zoom_levels_.end())
3520 render_view_->webview()->setZoomLevel(host_zoom->second);
3523 if (host_zoom != render_view_->host_zoom_levels_.end()) {
3524 // This zoom level was merely recorded transiently for this load. We can
3525 // erase it now. If at some point we reload this page, the browser will
3526 // send us a new, up-to-date zoom level.
3527 render_view_->host_zoom_levels_.erase(host_zoom);
3530 // Update contents MIME type for main frame.
3531 params.contents_mime_type = ds->response().mimeType().utf8();
3533 params.transition = navigation_state->transition_type();
3534 if (!ui::PageTransitionIsMainFrame(params.transition)) {
3535 // If the main frame does a load, it should not be reported as a subframe
3536 // navigation. This can occur in the following case:
3537 // 1. You're on a site with frames.
3538 // 2. You do a subframe navigation. This is stored with transition type
3539 // MANUAL_SUBFRAME.
3540 // 3. You navigate to some non-frame site, say, google.com.
3541 // 4. You navigate back to the page from step 2. Since it was initially
3542 // MANUAL_SUBFRAME, it will be that same transition type here.
3543 // We don't want that, because any navigation that changes the toplevel
3544 // frame should be tracked as a toplevel navigation (this allows us to
3545 // update the URL bar, etc).
3546 params.transition = ui::PAGE_TRANSITION_LINK;
3549 // If the page contained a client redirect (meta refresh, document.loc...),
3550 // set the referrer and transition appropriately.
3551 if (ds->isClientRedirect()) {
3552 params.referrer =
3553 Referrer(params.redirects[0], ds->request().referrerPolicy());
3554 params.transition = ui::PageTransitionFromInt(
3555 params.transition | ui::PAGE_TRANSITION_CLIENT_REDIRECT);
3556 } else {
3557 params.referrer = RenderViewImpl::GetReferrerFromRequest(
3558 frame, ds->request());
3561 base::string16 method = request.httpMethod();
3562 if (EqualsASCII(method, "POST")) {
3563 params.is_post = true;
3564 params.post_id = ExtractPostId(entry->root());
3567 // Send the user agent override back.
3568 params.is_overriding_user_agent = internal_data->is_overriding_user_agent();
3570 // Track the URL of the original request. We use the first entry of the
3571 // redirect chain if it exists because the chain may have started in another
3572 // process.
3573 params.original_request_url = GetOriginalRequestURL(ds);
3575 params.history_list_was_cleared =
3576 navigation_state->history_list_was_cleared();
3578 // Save some histogram data so we can compute the average memory used per
3579 // page load of the glyphs.
3580 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
3581 blink::WebGlyphCache::pageCount());
3583 // This message needs to be sent before any of allowScripts(),
3584 // allowImages(), allowPlugins() is called for the new page, so that when
3585 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
3586 // after the FrameHostMsg_DidCommitProvisionalLoad message.
3587 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params));
3588 } else {
3589 // Subframe navigation: the type depends on whether this navigation
3590 // generated a new session history entry. When they do generate a session
3591 // history entry, it means the user initiated the navigation and we should
3592 // mark it as such. This test checks if this is the first time
3593 // SendDidCommitProvisionalLoad has been called since WillNavigateToURL was
3594 // called to initiate the load.
3595 if (render_view_->page_id_ > render_view_->last_page_id_sent_to_browser_)
3596 params.transition = ui::PAGE_TRANSITION_MANUAL_SUBFRAME;
3597 else
3598 params.transition = ui::PAGE_TRANSITION_AUTO_SUBFRAME;
3600 DCHECK(!navigation_state->history_list_was_cleared());
3601 params.history_list_was_cleared = false;
3603 // Don't send this message while the subframe is swapped out.
3604 if (!is_swapped_out())
3605 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params));
3608 render_view_->last_page_id_sent_to_browser_ =
3609 std::max(render_view_->last_page_id_sent_to_browser_,
3610 render_view_->page_id_);
3612 // If we end up reusing this WebRequest (for example, due to a #ref click),
3613 // we don't want the transition type to persist. Just clear it.
3614 navigation_state->set_transition_type(ui::PAGE_TRANSITION_LINK);
3617 WebElement RenderFrameImpl::GetFocusedElement() {
3618 WebDocument doc = frame_->document();
3619 if (!doc.isNull())
3620 return doc.focusedElement();
3622 return WebElement();
3625 void RenderFrameImpl::didStartLoading(bool to_different_document) {
3626 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
3627 "id", routing_id_);
3628 render_view_->FrameDidStartLoading(frame_);
3629 Send(new FrameHostMsg_DidStartLoading(routing_id_, to_different_document));
3632 void RenderFrameImpl::didStopLoading() {
3633 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
3634 "id", routing_id_);
3635 render_view_->FrameDidStopLoading(frame_);
3636 Send(new FrameHostMsg_DidStopLoading(routing_id_));
3639 void RenderFrameImpl::didChangeLoadProgress(double load_progress) {
3640 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_, load_progress));
3643 void RenderFrameImpl::HandleWebAccessibilityEvent(
3644 const blink::WebAXObject& obj, blink::WebAXEvent event) {
3645 if (renderer_accessibility_)
3646 renderer_accessibility_->HandleWebAccessibilityEvent(obj, event);
3649 void RenderFrameImpl::FocusedNodeChanged(const WebNode& node) {
3650 if (renderer_accessibility_)
3651 renderer_accessibility_->FocusedNodeChanged(node);
3654 // PlzNavigate
3655 void RenderFrameImpl::OnRequestNavigation(
3656 const CommonNavigationParams& common_params,
3657 const RequestNavigationParams& request_params) {
3658 CHECK(CommandLine::ForCurrentProcess()->HasSwitch(
3659 switches::kEnableBrowserSideNavigation));
3660 WebURLRequest request =
3661 CreateURLRequestForNavigation(common_params,
3662 request_params,
3663 scoped_ptr<StreamOverrideParameters>(),
3664 frame_->isViewSourceModeEnabled());
3665 BeginNavigation(&request);
3668 // PlzNavigate
3669 void RenderFrameImpl::OnCommitNavigation(
3670 const ResourceResponseHead& response,
3671 const GURL& stream_url,
3672 const CommonNavigationParams& common_params,
3673 const CommitNavigationParams& commit_params) {
3674 CHECK(CommandLine::ForCurrentProcess()->HasSwitch(
3675 switches::kEnableBrowserSideNavigation));
3676 bool is_reload = false;
3677 WebURLRequest::CachePolicy cache_policy =
3678 WebURLRequest::UseProtocolCachePolicy;
3679 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
3680 common_params.url, common_params.navigation_type,
3681 commit_params.page_state, false, -1, -1, &is_reload, &cache_policy)) {
3682 return;
3685 GetContentClient()->SetActiveURL(common_params.url);
3687 // Create a WebURLRequest that blink can use to get access to the body of the
3688 // response through a stream in the browser. Blink will then commit the
3689 // navigation.
3690 // TODO(clamy): Have the navigation commit directly, without going through
3691 // loading a WebURLRequest.
3692 scoped_ptr<StreamOverrideParameters> stream_override(
3693 new StreamOverrideParameters());
3694 stream_override->stream_url = stream_url;
3695 stream_override->response = response;
3696 WebURLRequest request =
3697 CreateURLRequestForNavigation(common_params,
3698 RequestNavigationParams(),
3699 stream_override.Pass(),
3700 frame_->isViewSourceModeEnabled());
3702 // Make sure that blink loader will not try to use browser side navigation for
3703 // this request (since it already went to the browser).
3704 request.setCheckForBrowserSideNavigation(false);
3706 // Record this before starting the load. A lower bound of this time is needed
3707 // to sanitize the navigationStart override set below.
3708 base::TimeTicks renderer_navigation_start = base::TimeTicks::Now();
3709 frame_->loadRequest(request);
3710 UpdateFrameNavigationTiming(
3711 frame_, commit_params.browser_navigation_start,
3712 renderer_navigation_start);
3715 WebNavigationPolicy RenderFrameImpl::DecidePolicyForNavigation(
3716 RenderFrame* render_frame,
3717 const NavigationPolicyInfo& info) {
3718 #ifdef OS_ANDROID
3719 // The handlenavigation API is deprecated and will be removed once
3720 // crbug.com/325351 is resolved.
3721 if (info.urlRequest.url() != GURL(kSwappedOutURL) &&
3722 GetContentClient()->renderer()->HandleNavigation(
3723 render_frame,
3724 static_cast<DocumentState*>(info.extraData),
3725 render_view_->opener_id_,
3726 info.frame,
3727 info.urlRequest,
3728 info.navigationType,
3729 info.defaultPolicy,
3730 info.isRedirect)) {
3731 return blink::WebNavigationPolicyIgnore;
3733 #endif
3735 Referrer referrer(RenderViewImpl::GetReferrerFromRequest(info.frame,
3736 info.urlRequest));
3737 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
3739 bool is_subframe = !!info.frame->parent();
3741 if (command_line.HasSwitch(switches::kSitePerProcess) && is_subframe) {
3742 // There's no reason to ignore navigations on subframes, since the swap out
3743 // logic no longer applies.
3744 } else {
3745 if (is_swapped_out_) {
3746 if (info.urlRequest.url() != GURL(kSwappedOutURL)) {
3747 // Targeted links may try to navigate a swapped out frame. Allow the
3748 // browser process to navigate the tab instead. Note that it is also
3749 // possible for non-targeted navigations (from this view) to arrive
3750 // here just after we are swapped out. It's ok to send them to the
3751 // browser, as long as they're for the top level frame.
3752 // TODO(creis): Ensure this supports targeted form submissions when
3753 // fixing http://crbug.com/101395.
3754 if (info.frame->parent() == NULL) {
3755 OpenURL(info.frame, info.urlRequest.url(), referrer,
3756 info.defaultPolicy);
3757 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
3760 // We should otherwise ignore in-process iframe navigations, if they
3761 // arrive just after we are swapped out.
3762 return blink::WebNavigationPolicyIgnore;
3765 // Allow kSwappedOutURL to complete.
3766 return info.defaultPolicy;
3770 // Webkit is asking whether to navigate to a new URL.
3771 // This is fine normally, except if we're showing UI from one security
3772 // context and they're trying to navigate to a different context.
3773 const GURL& url = info.urlRequest.url();
3775 // A content initiated navigation may have originated from a link-click,
3776 // script, drag-n-drop operation, etc.
3777 bool is_content_initiated = static_cast<DocumentState*>(info.extraData)->
3778 navigation_state()->is_content_initiated();
3780 // Experimental:
3781 // If --enable-strict-site-isolation is enabled, send all top-level
3782 // navigations to the browser to let it swap processes when crossing site
3783 // boundaries. This is currently expected to break some script calls and
3784 // navigations, such as form submissions.
3785 bool force_swap_due_to_flag =
3786 command_line.HasSwitch(switches::kEnableStrictSiteIsolation);
3787 if (force_swap_due_to_flag &&
3788 !info.frame->parent() && (is_content_initiated || info.isRedirect)) {
3789 WebString origin_str = info.frame->document().securityOrigin().toString();
3790 GURL frame_url(origin_str.utf8().data());
3791 // TODO(cevans): revisit whether this site check is still necessary once
3792 // crbug.com/101395 is fixed.
3793 bool same_domain_or_host =
3794 net::registry_controlled_domains::SameDomainOrHost(
3795 frame_url,
3796 url,
3797 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
3798 // Only keep same-site (domain + scheme) and data URLs in the same process.
3799 bool is_same_site =
3800 (same_domain_or_host && frame_url.scheme() == url.scheme()) ||
3801 url.SchemeIs(url::kDataScheme);
3802 if (!is_same_site) {
3803 OpenURL(info.frame, url, referrer, info.defaultPolicy);
3804 return blink::WebNavigationPolicyIgnore;
3808 // If the browser is interested, then give it a chance to look at the request.
3809 if (is_content_initiated) {
3810 bool is_form_post =
3811 ((info.navigationType == blink::WebNavigationTypeFormSubmitted) ||
3812 (info.navigationType == blink::WebNavigationTypeFormResubmitted)) &&
3813 EqualsASCII(info.urlRequest.httpMethod(), "POST");
3814 bool browser_handles_request =
3815 render_view_->renderer_preferences_
3816 .browser_handles_non_local_top_level_requests
3817 && IsNonLocalTopLevelNavigation(url, info.frame, info.navigationType,
3818 is_form_post);
3819 if (!browser_handles_request) {
3820 browser_handles_request = IsTopLevelNavigation(info.frame) &&
3821 render_view_->renderer_preferences_
3822 .browser_handles_all_top_level_requests;
3825 if (browser_handles_request) {
3826 OpenURL(info.frame, url, referrer, info.defaultPolicy);
3827 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
3831 // Use the frame's original request's URL rather than the document's URL for
3832 // subsequent checks. For a popup, the document's URL may become the opener
3833 // window's URL if the opener has called document.write().
3834 // See http://crbug.com/93517.
3835 GURL old_url(info.frame->dataSource()->request().url());
3837 // Detect when we're crossing a permission-based boundary (e.g. into or out of
3838 // an extension or app origin, leaving a WebUI page, etc). We only care about
3839 // top-level navigations (not iframes). But we sometimes navigate to
3840 // about:blank to clear a tab, and we want to still allow that.
3842 // Note: this is known to break POST submissions when crossing process
3843 // boundaries until http://crbug.com/101395 is fixed. This is better for
3844 // security than loading a WebUI, extension or app page in the wrong process.
3845 // POST requests don't work because this mechanism does not preserve form
3846 // POST data. We will need to send the request's httpBody data up to the
3847 // browser process, and issue a special POST navigation in WebKit (via
3848 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
3849 // for examples of how to send the httpBody data.
3850 if (!info.frame->parent() && is_content_initiated &&
3851 !url.SchemeIs(url::kAboutScheme)) {
3852 bool send_referrer = false;
3854 // All navigations to or from WebUI URLs or within WebUI-enabled
3855 // RenderProcesses must be handled by the browser process so that the
3856 // correct bindings and data sources can be registered.
3857 // Similarly, navigations to view-source URLs or within ViewSource mode
3858 // must be handled by the browser process (except for reloads - those are
3859 // safe to leave within the renderer).
3860 // Lastly, access to file:// URLs from non-file:// URL pages must be
3861 // handled by the browser so that ordinary renderer processes don't get
3862 // blessed with file permissions.
3863 int cumulative_bindings = RenderProcess::current()->GetEnabledBindings();
3864 bool is_initial_navigation = render_view_->page_id_ == -1;
3865 bool should_fork = HasWebUIScheme(url) || HasWebUIScheme(old_url) ||
3866 (cumulative_bindings & BINDINGS_POLICY_WEB_UI) ||
3867 url.SchemeIs(kViewSourceScheme) ||
3868 (info.frame->isViewSourceModeEnabled() &&
3869 info.navigationType != blink::WebNavigationTypeReload);
3871 if (!should_fork && url.SchemeIs(url::kFileScheme)) {
3872 // Fork non-file to file opens. Check the opener URL if this is the
3873 // initial navigation in a newly opened window.
3874 GURL source_url(old_url);
3875 if (is_initial_navigation && source_url.is_empty() &&
3876 info.frame->opener())
3877 source_url = info.frame->opener()->top()->document().url();
3878 DCHECK(!source_url.is_empty());
3879 should_fork = !source_url.SchemeIs(url::kFileScheme);
3882 if (!should_fork) {
3883 // Give the embedder a chance.
3884 should_fork = GetContentClient()->renderer()->ShouldFork(
3885 info.frame, url, info.urlRequest.httpMethod().utf8(),
3886 is_initial_navigation, info.isRedirect, &send_referrer);
3889 if (should_fork) {
3890 OpenURL(info.frame, url, send_referrer ? referrer : Referrer(),
3891 info.defaultPolicy);
3892 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
3896 // Detect when a page is "forking" a new tab that can be safely rendered in
3897 // its own process. This is done by sites like Gmail that try to open links
3898 // in new windows without script connections back to the original page. We
3899 // treat such cases as browser navigations (in which we will create a new
3900 // renderer for a cross-site navigation), rather than WebKit navigations.
3902 // We use the following heuristic to decide whether to fork a new page in its
3903 // own process:
3904 // The parent page must open a new tab to about:blank, set the new tab's
3905 // window.opener to null, and then redirect the tab to a cross-site URL using
3906 // JavaScript.
3908 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
3909 // (see below).
3910 bool is_fork =
3911 // Must start from a tab showing about:blank, which is later redirected.
3912 old_url == GURL(url::kAboutBlankURL) &&
3913 // Must be the first real navigation of the tab.
3914 render_view_->historyBackListCount() < 1 &&
3915 render_view_->historyForwardListCount() < 1 &&
3916 // The parent page must have set the child's window.opener to null before
3917 // redirecting to the desired URL.
3918 info.frame->opener() == NULL &&
3919 // Must be a top-level frame.
3920 info.frame->parent() == NULL &&
3921 // Must not have issued the request from this page.
3922 is_content_initiated &&
3923 // Must be targeted at the current tab.
3924 info.defaultPolicy == blink::WebNavigationPolicyCurrentTab &&
3925 // Must be a JavaScript navigation, which appears as "other".
3926 info.navigationType == blink::WebNavigationTypeOther;
3928 if (is_fork) {
3929 // Open the URL via the browser, not via WebKit.
3930 OpenURL(info.frame, url, Referrer(), info.defaultPolicy);
3931 return blink::WebNavigationPolicyIgnore;
3934 // PlzNavigate: send the request to the browser if needed.
3935 if (CommandLine::ForCurrentProcess()->HasSwitch(
3936 switches::kEnableBrowserSideNavigation) &&
3937 info.urlRequest.checkForBrowserSideNavigation()) {
3938 BeginNavigation(&info.urlRequest);
3939 return blink::WebNavigationPolicyIgnore;
3942 return info.defaultPolicy;
3945 void RenderFrameImpl::OpenURL(WebFrame* frame,
3946 const GURL& url,
3947 const Referrer& referrer,
3948 WebNavigationPolicy policy) {
3949 DCHECK_EQ(frame_, frame);
3951 FrameHostMsg_OpenURL_Params params;
3952 params.url = url;
3953 params.referrer = referrer;
3954 params.disposition = RenderViewImpl::NavigationPolicyToDisposition(policy);
3955 WebDataSource* ds = frame->provisionalDataSource();
3956 if (ds) {
3957 DocumentState* document_state = DocumentState::FromDataSource(ds);
3958 NavigationState* navigation_state = document_state->navigation_state();
3959 if (navigation_state->is_content_initiated()) {
3960 params.should_replace_current_entry = ds->replacesCurrentHistoryItem();
3961 } else {
3962 // This is necessary to preserve the should_replace_current_entry value on
3963 // cross-process redirects, in the event it was set by a previous process.
3965 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3966 // NavigationState::should_replace_current_entry().
3967 params.should_replace_current_entry =
3968 navigation_state->should_replace_current_entry();
3970 } else {
3971 params.should_replace_current_entry = false;
3973 params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
3974 if (GetContentClient()->renderer()->AllowPopup())
3975 params.user_gesture = true;
3977 if (policy == blink::WebNavigationPolicyNewBackgroundTab ||
3978 policy == blink::WebNavigationPolicyNewForegroundTab ||
3979 policy == blink::WebNavigationPolicyNewWindow ||
3980 policy == blink::WebNavigationPolicyNewPopup) {
3981 WebUserGestureIndicator::consumeUserGesture();
3984 Send(new FrameHostMsg_OpenURL(routing_id_, params));
3987 void RenderFrameImpl::UpdateEncoding(WebFrame* frame,
3988 const std::string& encoding_name) {
3989 // Only update main frame's encoding_name.
3990 if (!frame->parent())
3991 Send(new FrameHostMsg_UpdateEncoding(routing_id_, encoding_name));
3994 void RenderFrameImpl::SyncSelectionIfRequired() {
3995 base::string16 text;
3996 size_t offset;
3997 gfx::Range range;
3998 #if defined(ENABLE_PLUGINS)
3999 if (render_view_->focused_pepper_plugin_) {
4000 render_view_->focused_pepper_plugin_->GetSurroundingText(&text, &range);
4001 offset = 0; // Pepper API does not support offset reporting.
4002 // TODO(kinaba): cut as needed.
4003 } else
4004 #endif
4006 size_t location, length;
4007 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4008 &location, &length)) {
4009 return;
4012 range = gfx::Range(location, location + length);
4014 if (GetRenderWidget()->webwidget()->textInputInfo().type !=
4015 blink::WebTextInputTypeNone) {
4016 // If current focused element is editable, we will send 100 more chars
4017 // before and after selection. It is for input method surrounding text
4018 // feature.
4019 if (location > kExtraCharsBeforeAndAfterSelection)
4020 offset = location - kExtraCharsBeforeAndAfterSelection;
4021 else
4022 offset = 0;
4023 length = location + length - offset + kExtraCharsBeforeAndAfterSelection;
4024 WebRange webrange = WebRange::fromDocumentRange(frame_, offset, length);
4025 if (!webrange.isNull())
4026 text = WebRange::fromDocumentRange(
4027 frame_, offset, length).toPlainText();
4028 } else {
4029 offset = location;
4030 text = frame_->selectionAsText();
4031 // http://crbug.com/101435
4032 // In some case, frame->selectionAsText() returned text's length is not
4033 // equal to the length returned from webwidget()->caretOrSelectionRange().
4034 // So we have to set the range according to text.length().
4035 range.set_end(range.start() + text.length());
4039 // Sometimes we get repeated didChangeSelection calls from webkit when
4040 // the selection hasn't actually changed. We don't want to report these
4041 // because it will cause us to continually claim the X clipboard.
4042 if (selection_text_offset_ != offset ||
4043 selection_range_ != range ||
4044 selection_text_ != text) {
4045 selection_text_ = text;
4046 selection_text_offset_ = offset;
4047 selection_range_ = range;
4048 SetSelectedText(text, offset, range);
4050 GetRenderWidget()->UpdateSelectionBounds();
4053 void RenderFrameImpl::InitializeUserMediaClient() {
4054 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4055 return;
4057 #if defined(OS_ANDROID)
4058 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableWebRTC))
4059 return;
4060 #endif
4062 #if defined(ENABLE_WEBRTC)
4063 DCHECK(!web_user_media_client_);
4064 web_user_media_client_ = new UserMediaClientImpl(
4065 this,
4066 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4067 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4068 #endif
4071 WebMediaPlayer* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4072 const blink::WebURL& url,
4073 WebMediaPlayerClient* client) {
4074 #if defined(ENABLE_WEBRTC)
4075 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4076 bool found_neon =
4077 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0;
4078 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon);
4079 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4080 return new WebMediaPlayerMS(frame_, client, weak_factory_.GetWeakPtr(),
4081 new RenderMediaLog(),
4082 CreateRendererFactory());
4083 #else
4084 return NULL;
4085 #endif // defined(ENABLE_WEBRTC)
4088 scoped_ptr<MediaStreamRendererFactory>
4089 RenderFrameImpl::CreateRendererFactory() {
4090 #if defined(ENABLE_WEBRTC)
4091 return scoped_ptr<MediaStreamRendererFactory>(
4092 new MediaStreamRendererFactory());
4093 #else
4094 return scoped_ptr<MediaStreamRendererFactory>(
4095 static_cast<MediaStreamRendererFactory*>(NULL));
4096 #endif
4099 bool RenderFrameImpl::PrepareRenderViewForNavigation(
4100 const GURL& url,
4101 FrameMsg_Navigate_Type::Value navigate_type,
4102 const PageState& state,
4103 bool check_history,
4104 int pending_history_list_offset,
4105 int32 page_id,
4106 bool* is_reload,
4107 WebURLRequest::CachePolicy* cache_policy) {
4108 MaybeHandleDebugURL(url);
4109 if (!render_view_->webview())
4110 return false;
4112 FOR_EACH_OBSERVER(
4113 RenderViewObserver, render_view_->observers_, Navigate(url));
4115 // If this is a stale back/forward (due to a recent navigation the browser
4116 // didn't know about), ignore it.
4117 if (check_history && render_view_->IsBackForwardToStaleEntry(
4118 state, pending_history_list_offset, page_id, *is_reload))
4119 return false;
4121 if (!is_swapped_out_ || frame_->parent())
4122 return true;
4124 // This is a swapped out main frame, so swap the renderer back in.
4125 // We marked the view as hidden when swapping the view out, so be sure to
4126 // reset the visibility state before navigating to the new URL.
4127 render_view_->webview()->setVisibilityState(
4128 render_view_->visibilityState(), false);
4130 // If this is an attempt to reload while we are swapped out, we should not
4131 // reload swappedout://, but the previous page, which is stored in
4132 // params.state. Setting is_reload to false will treat this like a back
4133 // navigation to accomplish that.
4134 *is_reload = false;
4135 *cache_policy = WebURLRequest::ReloadIgnoringCacheData;
4137 // We refresh timezone when a view is swapped in since timezone
4138 // can get out of sync when the system timezone is updated while
4139 // the view is swapped out.
4140 RenderThreadImpl::NotifyTimezoneChange();
4142 render_view_->SetSwappedOut(false);
4143 is_swapped_out_ = false;
4144 return true;
4147 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest* request) {
4148 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4149 switches::kEnableBrowserSideNavigation));
4150 DCHECK(request);
4151 // TODO(clamy): Execute the beforeunload event.
4153 // Note: At this stage, the goal is to apply all the modifications the
4154 // renderer wants to make to the request, and then send it to the browser, so
4155 // that the actual network request can be started. Ideally, all such
4156 // modifications should take place in willSendRequest, and in the
4157 // implementation of willSendRequest for the various InspectorAgents
4158 // (devtools).
4160 // TODO(clamy): Apply devtools override.
4161 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4162 // else in blink.
4163 willSendRequest(frame_, 0, *request, blink::WebURLResponse());
4165 // TODO(clamy): Same-document navigations should not be sent back to the
4166 // browser.
4167 // TODO(clamy): Data urls should not be sent back to the browser either.
4168 Send(new FrameHostMsg_BeginNavigation(routing_id_,
4169 MakeBeginNavigationParams(request),
4170 MakeCommonNavigationParams(request)));
4173 GURL RenderFrameImpl::GetLoadingUrl() const {
4174 WebDataSource* ds = frame_->dataSource();
4175 if (ds->hasUnreachableURL())
4176 return ds->unreachableURL();
4178 const WebURLRequest& request = ds->request();
4179 return request.url();
4182 #if defined(OS_ANDROID)
4184 WebMediaPlayer* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4185 const blink::WebURL& url,
4186 WebMediaPlayerClient* client,
4187 blink::WebContentDecryptionModule* initial_cdm) {
4188 GpuChannelHost* gpu_channel_host =
4189 RenderThreadImpl::current()->EstablishGpuChannelSync(
4190 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE);
4191 if (!gpu_channel_host) {
4192 LOG(ERROR) << "Failed to establish GPU channel for media player";
4193 return NULL;
4196 scoped_refptr<StreamTextureFactory> stream_texture_factory;
4197 if (SynchronousCompositorFactory* factory =
4198 SynchronousCompositorFactory::GetInstance()) {
4199 stream_texture_factory = factory->CreateStreamTextureFactory(routing_id_);
4200 } else {
4201 scoped_refptr<webkit::gpu::ContextProviderWebContext> context_provider =
4202 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4204 if (!context_provider.get()) {
4205 LOG(ERROR) << "Failed to get context3d for media player";
4206 return NULL;
4209 stream_texture_factory = StreamTextureFactoryImpl::Create(
4210 context_provider, gpu_channel_host, routing_id_);
4213 return new WebMediaPlayerAndroid(
4214 frame_,
4215 client,
4216 weak_factory_.GetWeakPtr(),
4217 GetMediaPlayerManager(),
4218 GetCdmManager(),
4219 initial_cdm,
4220 stream_texture_factory,
4221 RenderThreadImpl::current()->GetMediaThreadTaskRunner(),
4222 new RenderMediaLog());
4225 RendererMediaPlayerManager* RenderFrameImpl::GetMediaPlayerManager() {
4226 if (!media_player_manager_)
4227 media_player_manager_ = new RendererMediaPlayerManager(this);
4228 return media_player_manager_;
4231 #endif // defined(OS_ANDROID)
4233 #if defined(ENABLE_BROWSER_CDMS)
4234 RendererCdmManager* RenderFrameImpl::GetCdmManager() {
4235 if (!cdm_manager_)
4236 cdm_manager_ = new RendererCdmManager(this);
4237 return cdm_manager_;
4239 #endif // defined(ENABLE_BROWSER_CDMS)
4241 } // namespace content