Disable accessibility when VoiceOver is turned off.
[chromium-blink-merge.git] / content / renderer / render_frame_impl.cc
blob769db2eb2891de2ac7c173a7a85801c6a1c71537
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/renderer/render_frame_impl.h"
7 #include <map>
8 #include <string>
10 #include "base/auto_reset.h"
11 #include "base/command_line.h"
12 #include "base/debug/alias.h"
13 #include "base/debug/asan_invalid_access.h"
14 #include "base/debug/dump_without_crashing.h"
15 #include "base/i18n/char_iterator.h"
16 #include "base/metrics/histogram.h"
17 #include "base/process/kill.h"
18 #include "base/process/process.h"
19 #include "base/strings/string16.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/time/time.h"
22 #include "content/child/appcache/appcache_dispatcher.h"
23 #include "content/child/plugin_messages.h"
24 #include "content/child/quota_dispatcher.h"
25 #include "content/child/request_extra_data.h"
26 #include "content/child/service_worker/service_worker_network_provider.h"
27 #include "content/child/service_worker/service_worker_provider_context.h"
28 #include "content/child/service_worker/web_service_worker_provider_impl.h"
29 #include "content/child/web_socket_stream_handle_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/socket_stream_handle_data.h"
40 #include "content/common/swapped_out_messages.h"
41 #include "content/common/view_messages.h"
42 #include "content/public/common/bindings_policy.h"
43 #include "content/public/common/content_constants.h"
44 #include "content/public/common/content_switches.h"
45 #include "content/public/common/context_menu_params.h"
46 #include "content/public/common/page_state.h"
47 #include "content/public/common/resource_response.h"
48 #include "content/public/common/url_constants.h"
49 #include "content/public/common/url_utils.h"
50 #include "content/public/renderer/browser_plugin_delegate.h"
51 #include "content/public/renderer/content_renderer_client.h"
52 #include "content/public/renderer/context_menu_client.h"
53 #include "content/public/renderer/document_state.h"
54 #include "content/public/renderer/navigation_state.h"
55 #include "content/public/renderer/render_frame_observer.h"
56 #include "content/renderer/accessibility/renderer_accessibility_complete.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/encrypted_media_player_support_impl.h"
74 #include "content/renderer/media/crypto/render_cdm_factory.h"
75 #include "content/renderer/media/media_stream_dispatcher.h"
76 #include "content/renderer/media/media_stream_renderer_factory.h"
77 #include "content/renderer/media/midi_dispatcher.h"
78 #include "content/renderer/media/render_media_log.h"
79 #include "content/renderer/media/user_media_client_impl.h"
80 #include "content/renderer/media/webcontentdecryptionmodule_impl.h"
81 #include "content/renderer/media/webmediaplayer_ms.h"
82 #include "content/renderer/mojo/service_registry_js_wrapper.h"
83 #include "content/renderer/notification_permission_dispatcher.h"
84 #include "content/renderer/notification_provider.h"
85 #include "content/renderer/npapi/plugin_channel_host.h"
86 #include "content/renderer/push_messaging_dispatcher.h"
87 #include "content/renderer/render_frame_proxy.h"
88 #include "content/renderer/render_process.h"
89 #include "content/renderer/render_thread_impl.h"
90 #include "content/renderer/render_view_impl.h"
91 #include "content/renderer/render_widget_fullscreen_pepper.h"
92 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
93 #include "content/renderer/renderer_webcolorchooser_impl.h"
94 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
95 #include "content/renderer/shared_worker_repository.h"
96 #include "content/renderer/v8_value_converter_impl.h"
97 #include "content/renderer/websharedworker_proxy.h"
98 #include "gin/modules/module_registry.h"
99 #include "media/base/audio_renderer_mixer_input.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/bindings/js/core.h"
104 #include "mojo/bindings/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/WebRange.h"
124 #include "third_party/WebKit/public/web/WebScriptSource.h"
125 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
126 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
127 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
128 #include "third_party/WebKit/public/web/WebSurroundingText.h"
129 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
130 #include "third_party/WebKit/public/web/WebView.h"
132 #if defined(ENABLE_PLUGINS)
133 #include "content/renderer/npapi/webplugin_impl.h"
134 #include "content/renderer/pepper/pepper_browser_connection.h"
135 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
136 #include "content/renderer/pepper/pepper_webplugin_impl.h"
137 #include "content/renderer/pepper/plugin_module.h"
138 #endif
140 #if defined(ENABLE_WEBRTC)
141 #include "content/renderer/media/rtc_peer_connection_handler.h"
142 #endif
144 #if defined(OS_ANDROID)
145 #include <cpu-features.h>
147 #include "content/common/gpu/client/context_provider_command_buffer.h"
148 #include "content/renderer/android/synchronous_compositor_factory.h"
149 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
150 #include "content/renderer/media/android/renderer_media_player_manager.h"
151 #include "content/renderer/media/android/stream_texture_factory_impl.h"
152 #include "content/renderer/media/android/webmediaplayer_android.h"
153 #endif
155 #if defined(ENABLE_PEPPER_CDMS)
156 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
157 #elif defined(ENABLE_BROWSER_CDMS)
158 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
159 #endif
161 using blink::WebContextMenuData;
162 using blink::WebData;
163 using blink::WebDataSource;
164 using blink::WebDocument;
165 using blink::WebElement;
166 using blink::WebExternalPopupMenu;
167 using blink::WebExternalPopupMenuClient;
168 using blink::WebFrame;
169 using blink::WebHistoryItem;
170 using blink::WebHTTPBody;
171 using blink::WebLocalFrame;
172 using blink::WebMediaPlayer;
173 using blink::WebMediaPlayerClient;
174 using blink::WebNavigationPolicy;
175 using blink::WebNavigationType;
176 using blink::WebNode;
177 using blink::WebPluginParams;
178 using blink::WebPopupMenuInfo;
179 using blink::WebRange;
180 using blink::WebReferrerPolicy;
181 using blink::WebScriptSource;
182 using blink::WebSearchableFormData;
183 using blink::WebSecurityOrigin;
184 using blink::WebSecurityPolicy;
185 using blink::WebServiceWorkerProvider;
186 using blink::WebStorageQuotaCallbacks;
187 using blink::WebString;
188 using blink::WebURL;
189 using blink::WebURLError;
190 using blink::WebURLRequest;
191 using blink::WebURLResponse;
192 using blink::WebUserGestureIndicator;
193 using blink::WebVector;
194 using blink::WebView;
195 using base::Time;
196 using base::TimeDelta;
198 namespace content {
200 namespace {
202 const char kDefaultAcceptHeader[] =
203 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
204 "*;q=0.8";
205 const char kAcceptHeader[] = "Accept";
207 const size_t kExtraCharsBeforeAndAfterSelection = 100;
209 typedef std::map<int, RenderFrameImpl*> RoutingIDFrameMap;
210 static base::LazyInstance<RoutingIDFrameMap> g_routing_id_frame_map =
211 LAZY_INSTANCE_INITIALIZER;
213 typedef std::map<blink::WebFrame*, RenderFrameImpl*> FrameMap;
214 base::LazyInstance<FrameMap> g_frame_map = LAZY_INSTANCE_INITIALIZER;
216 int64 ExtractPostId(const WebHistoryItem& item) {
217 if (item.isNull())
218 return -1;
220 if (item.httpBody().isNull())
221 return -1;
223 return item.httpBody().identifier();
226 WebURLResponseExtraDataImpl* GetExtraDataFromResponse(
227 const WebURLResponse& response) {
228 return static_cast<WebURLResponseExtraDataImpl*>(response.extraData());
231 void GetRedirectChain(WebDataSource* ds, std::vector<GURL>* result) {
232 // Replace any occurrences of swappedout:// with about:blank.
233 const WebURL& blank_url = GURL(url::kAboutBlankURL);
234 WebVector<WebURL> urls;
235 ds->redirectChain(urls);
236 result->reserve(urls.size());
237 for (size_t i = 0; i < urls.size(); ++i) {
238 if (urls[i] != GURL(kSwappedOutURL))
239 result->push_back(urls[i]);
240 else
241 result->push_back(blank_url);
245 // Returns the original request url. If there is no redirect, the original
246 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
247 // frame was loaded by loadData, the original url will be ds->unreachableURL()
248 static GURL GetOriginalRequestURL(WebDataSource* ds) {
249 // WebDataSource has unreachable URL means that the frame is loaded through
250 // blink::WebFrame::loadData(), and the base URL will be in the redirect
251 // chain. However, we never visited the baseURL. So in this case, we should
252 // use the unreachable URL as the original URL.
253 if (ds->hasUnreachableURL())
254 return ds->unreachableURL();
256 std::vector<GURL> redirects;
257 GetRedirectChain(ds, &redirects);
258 if (!redirects.empty())
259 return redirects.at(0);
261 return ds->originalRequest().url();
264 NOINLINE static void CrashIntentionally() {
265 // NOTE(shess): Crash directly rather than using NOTREACHED() so
266 // that the signature is easier to triage in crash reports.
267 volatile int* zero = NULL;
268 *zero = 0;
271 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
272 NOINLINE static void MaybeTriggerAsanError(const GURL& url) {
273 // NOTE(rogerm): We intentionally perform an invalid heap access here in
274 // order to trigger an Address Sanitizer (ASAN) error report.
275 const char kCrashDomain[] = "crash";
276 const char kHeapOverflow[] = "/heap-overflow";
277 const char kHeapUnderflow[] = "/heap-underflow";
278 const char kUseAfterFree[] = "/use-after-free";
279 #if defined(SYZYASAN)
280 const char kCorruptHeapBlock[] = "/corrupt-heap-block";
281 const char kCorruptHeap[] = "/corrupt-heap";
282 #endif
284 if (!url.DomainIs(kCrashDomain, sizeof(kCrashDomain) - 1))
285 return;
287 if (!url.has_path())
288 return;
290 std::string crash_type(url.path());
291 if (crash_type == kHeapOverflow) {
292 base::debug::AsanHeapOverflow();
293 } else if (crash_type == kHeapUnderflow ) {
294 base::debug::AsanHeapUnderflow();
295 } else if (crash_type == kUseAfterFree) {
296 base::debug::AsanHeapUseAfterFree();
297 #if defined(SYZYASAN)
298 } else if (crash_type == kCorruptHeapBlock) {
299 base::debug::AsanCorruptHeapBlock();
300 } else if (crash_type == kCorruptHeap) {
301 base::debug::AsanCorruptHeap();
302 #endif
305 #endif // ADDRESS_SANITIZER || SYZYASAN
307 static void MaybeHandleDebugURL(const GURL& url) {
308 if (!url.SchemeIs(kChromeUIScheme))
309 return;
310 if (url == GURL(kChromeUICrashURL)) {
311 CrashIntentionally();
312 } else if (url == GURL(kChromeUIDumpURL)) {
313 // This URL will only correctly create a crash dump file if content is
314 // hosted in a process that has correctly called
315 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
316 // of base::debug::DumpWithoutCrashing for more details.
317 base::debug::DumpWithoutCrashing();
318 } else if (url == GURL(kChromeUIKillURL)) {
319 base::KillProcess(base::GetCurrentProcessHandle(), 1, false);
320 } else if (url == GURL(kChromeUIHangURL)) {
321 for (;;) {
322 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
324 } else if (url == GURL(kChromeUIShorthangURL)) {
325 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
328 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
329 MaybeTriggerAsanError(url);
330 #endif // ADDRESS_SANITIZER || SYZYASAN
333 // Returns false unless this is a top-level navigation.
334 static bool IsTopLevelNavigation(WebFrame* frame) {
335 return frame->parent() == NULL;
338 // Returns false unless this is a top-level navigation that crosses origins.
339 static bool IsNonLocalTopLevelNavigation(const GURL& url,
340 WebFrame* frame,
341 WebNavigationType type,
342 bool is_form_post) {
343 if (!IsTopLevelNavigation(frame))
344 return false;
346 // Navigations initiated within Webkit are not sent out to the external host
347 // in the following cases.
348 // 1. The url scheme is not http/https
349 // 2. The origin of the url and the opener is the same in which case the
350 // opener relationship is maintained.
351 // 3. Reloads/form submits/back forward navigations
352 if (!url.SchemeIs(url::kHttpScheme) && !url.SchemeIs(url::kHttpsScheme))
353 return false;
355 if (type != blink::WebNavigationTypeReload &&
356 type != blink::WebNavigationTypeBackForward && !is_form_post) {
357 // The opener relationship between the new window and the parent allows the
358 // new window to script the parent and vice versa. This is not allowed if
359 // the origins of the two domains are different. This can be treated as a
360 // top level navigation and routed back to the host.
361 blink::WebFrame* opener = frame->opener();
362 if (!opener)
363 return true;
365 if (url.GetOrigin() != GURL(opener->document().url()).GetOrigin())
366 return true;
368 return false;
371 WebURLRequest CreateURLRequestForNavigation(
372 const CommonNavigationParams& common_params,
373 const RequestNavigationParams& request_params,
374 scoped_ptr<StreamOverrideParameters> stream_override,
375 bool is_view_source_mode_enabled) {
376 WebURLRequest request(common_params.url);
377 if (is_view_source_mode_enabled)
378 request.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad);
380 if (common_params.referrer.url.is_valid()) {
381 WebString web_referrer = WebSecurityPolicy::generateReferrerHeader(
382 common_params.referrer.policy,
383 common_params.url,
384 WebString::fromUTF8(common_params.referrer.url.spec()));
385 if (!web_referrer.isEmpty())
386 request.setHTTPReferrer(web_referrer, common_params.referrer.policy);
389 if (!request_params.extra_headers.empty()) {
390 for (net::HttpUtil::HeadersIterator i(request_params.extra_headers.begin(),
391 request_params.extra_headers.end(),
392 "\n");
393 i.GetNext();) {
394 request.addHTTPHeaderField(WebString::fromUTF8(i.name()),
395 WebString::fromUTF8(i.values()));
399 if (request_params.is_post) {
400 request.setHTTPMethod(WebString::fromUTF8("POST"));
402 // Set post data.
403 WebHTTPBody http_body;
404 http_body.initialize();
405 const char* data = NULL;
406 if (request_params.browser_initiated_post_data.size()) {
407 data = reinterpret_cast<const char*>(
408 &request_params.browser_initiated_post_data.front());
410 http_body.appendData(
411 WebData(data, request_params.browser_initiated_post_data.size()));
412 request.setHTTPBody(http_body);
415 RequestExtraData* extra_data = new RequestExtraData();
416 extra_data->set_stream_override(stream_override.Pass());
417 request.setExtraData(extra_data);
418 return request;
421 void UpdateFrameNavigationTiming(WebFrame* frame,
422 base::TimeTicks browser_navigation_start,
423 base::TimeTicks renderer_navigation_start) {
424 // The browser provides the navigation_start time to bootstrap the
425 // Navigation Timing information for the browser-initiated navigations. In
426 // case of cross-process navigations, this carries over the time of
427 // finishing the onbeforeunload handler of the previous page.
428 DCHECK(!browser_navigation_start.is_null());
429 if (frame->provisionalDataSource()) {
430 // |browser_navigation_start| is likely before this process existed, so we
431 // can't use InterProcessTimeTicksConverter. We need at least to ensure
432 // that the browser-side navigation start we set is not later than the one
433 // on the renderer side.
434 base::TimeTicks navigation_start = std::min(
435 browser_navigation_start, renderer_navigation_start);
436 double navigation_start_seconds =
437 (navigation_start - base::TimeTicks()).InSecondsF();
438 frame->provisionalDataSource()->setNavigationStartTime(
439 navigation_start_seconds);
440 // TODO(clamy): We need to provide additional timing values for the
441 // Navigation Timing API to work with browser-side navigations.
445 // PlzNavigate
446 FrameHostMsg_BeginNavigation_Params MakeBeginNavigationParams(
447 const blink::WebURLRequest& request) {
448 FrameHostMsg_BeginNavigation_Params params;
449 params.method = request.httpMethod().latin1();
450 params.headers = GetWebURLRequestHeaders(request);
451 params.load_flags = GetLoadFlagsForWebURLRequest(request);
452 // TODO(clamy): fill the http body.
453 params.has_user_gesture = request.hasUserGesture();
454 return params;
457 // PlzNavigate
458 CommonNavigationParams MakeCommonNavigationParams(
459 const blink::WebURLRequest& request) {
460 const RequestExtraData kEmptyData;
461 const RequestExtraData* extra_data =
462 static_cast<RequestExtraData*>(request.extraData());
463 if (!extra_data)
464 extra_data = &kEmptyData;
465 CommonNavigationParams params;
466 params.url = request.url();
467 params.referrer = Referrer(
468 GURL(request.httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
469 request.referrerPolicy());
470 params.transition = extra_data->transition_type();
471 return params;
474 } // namespace
476 static RenderFrameImpl* (*g_create_render_frame_impl)(RenderViewImpl*, int32) =
477 NULL;
479 // static
480 RenderFrameImpl* RenderFrameImpl::Create(RenderViewImpl* render_view,
481 int32 routing_id) {
482 DCHECK(routing_id != MSG_ROUTING_NONE);
484 if (g_create_render_frame_impl)
485 return g_create_render_frame_impl(render_view, routing_id);
486 else
487 return new RenderFrameImpl(render_view, routing_id);
490 // static
491 RenderFrameImpl* RenderFrameImpl::FromRoutingID(int32 routing_id) {
492 RoutingIDFrameMap::iterator iter =
493 g_routing_id_frame_map.Get().find(routing_id);
494 if (iter != g_routing_id_frame_map.Get().end())
495 return iter->second;
496 return NULL;
499 // static
500 void RenderFrameImpl::CreateFrame(int routing_id, int parent_routing_id) {
501 // TODO(nasko): For now, this message is only sent for subframes, as the
502 // top level frame is created when the RenderView is created through the
503 // ViewMsg_New IPC.
504 CHECK_NE(MSG_ROUTING_NONE, parent_routing_id);
506 RenderFrameProxy* proxy = RenderFrameProxy::FromRoutingID(parent_routing_id);
508 // If the browser is sending a valid parent routing id, it should already be
509 // created and registered.
510 CHECK(proxy);
511 blink::WebRemoteFrame* parent_web_frame = proxy->web_frame();
513 // Create the RenderFrame and WebLocalFrame, linking the two.
514 RenderFrameImpl* render_frame =
515 RenderFrameImpl::Create(proxy->render_view(), routing_id);
516 blink::WebLocalFrame* web_frame =
517 parent_web_frame->createLocalChild("", render_frame);
518 render_frame->SetWebFrame(web_frame);
519 render_frame->Initialize();
522 // static
523 RenderFrame* RenderFrame::FromWebFrame(blink::WebFrame* web_frame) {
524 return RenderFrameImpl::FromWebFrame(web_frame);
527 // static
528 RenderFrameImpl* RenderFrameImpl::FromWebFrame(blink::WebFrame* web_frame) {
529 FrameMap::iterator iter = g_frame_map.Get().find(web_frame);
530 if (iter != g_frame_map.Get().end())
531 return iter->second;
532 return NULL;
535 // static
536 void RenderFrameImpl::InstallCreateHook(
537 RenderFrameImpl* (*create_render_frame_impl)(RenderViewImpl*, int32)) {
538 CHECK(!g_create_render_frame_impl);
539 g_create_render_frame_impl = create_render_frame_impl;
542 // RenderFrameImpl ----------------------------------------------------------
543 RenderFrameImpl::RenderFrameImpl(RenderViewImpl* render_view, int routing_id)
544 : frame_(NULL),
545 render_view_(render_view->AsWeakPtr()),
546 routing_id_(routing_id),
547 is_swapped_out_(false),
548 render_frame_proxy_(NULL),
549 is_detaching_(false),
550 cookie_jar_(this),
551 selection_text_offset_(0),
552 selection_range_(gfx::Range::InvalidRange()),
553 handling_select_range_(false),
554 notification_permission_dispatcher_(NULL),
555 notification_provider_(NULL),
556 web_user_media_client_(NULL),
557 midi_dispatcher_(NULL),
558 #if defined(OS_ANDROID)
559 media_player_manager_(NULL),
560 #endif
561 #if defined(ENABLE_BROWSER_CDMS)
562 cdm_manager_(NULL),
563 #endif
564 #if defined(VIDEO_HOLE)
565 contains_media_player_(false),
566 #endif
567 geolocation_dispatcher_(NULL),
568 push_messaging_dispatcher_(NULL),
569 screen_orientation_dispatcher_(NULL),
570 manifest_manager_(NULL),
571 accessibility_mode_(AccessibilityModeOff),
572 renderer_accessibility_(NULL),
573 weak_factory_(this) {
574 std::pair<RoutingIDFrameMap::iterator, bool> result =
575 g_routing_id_frame_map.Get().insert(std::make_pair(routing_id_, this));
576 CHECK(result.second) << "Inserting a duplicate item.";
578 RenderThread::Get()->AddRoute(routing_id_, this);
580 render_view_->RegisterRenderFrame(this);
582 #if defined(OS_ANDROID)
583 new GinJavaBridgeDispatcher(this);
584 #endif
586 #if defined(ENABLE_NOTIFICATIONS)
587 notification_provider_ = new NotificationProvider(this);
588 #endif
590 manifest_manager_ = new ManifestManager(this);
593 RenderFrameImpl::~RenderFrameImpl() {
594 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, RenderFrameGone());
595 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, OnDestruct());
597 #if defined(VIDEO_HOLE)
598 if (contains_media_player_)
599 render_view_->UnregisterVideoHoleFrame(this);
600 #endif
602 if (render_frame_proxy_)
603 delete render_frame_proxy_;
605 render_view_->UnregisterRenderFrame(this);
606 g_routing_id_frame_map.Get().erase(routing_id_);
607 RenderThread::Get()->RemoveRoute(routing_id_);
610 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame* web_frame) {
611 DCHECK(!frame_);
613 std::pair<FrameMap::iterator, bool> result = g_frame_map.Get().insert(
614 std::make_pair(web_frame, this));
615 CHECK(result.second) << "Inserting a duplicate item.";
617 frame_ = web_frame;
620 void RenderFrameImpl::Initialize() {
621 #if defined(ENABLE_PLUGINS)
622 new PepperBrowserConnection(this);
623 #endif
624 new SharedWorkerRepository(this);
626 if (!frame_->parent())
627 new ImageLoadingHelper(this);
629 // We delay calling this until we have the WebFrame so that any observer or
630 // embedder can call GetWebFrame on any RenderFrame.
631 GetContentClient()->renderer()->RenderFrameCreated(this);
634 RenderWidget* RenderFrameImpl::GetRenderWidget() {
635 return render_view_.get();
638 #if defined(ENABLE_PLUGINS)
639 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost* host) {
640 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
641 DidCreatePepperPlugin(host));
644 void RenderFrameImpl::PepperDidChangeCursor(
645 PepperPluginInstanceImpl* instance,
646 const blink::WebCursorInfo& cursor) {
647 // Update the cursor appearance immediately if the requesting plugin is the
648 // one which receives the last mouse event. Otherwise, the new cursor won't be
649 // picked up until the plugin gets the next input event. That is bad if, e.g.,
650 // the plugin would like to set an invisible cursor when there isn't any user
651 // input for a while.
652 if (instance == render_view_->pepper_last_mouse_event_target())
653 GetRenderWidget()->didChangeCursor(cursor);
656 void RenderFrameImpl::PepperDidReceiveMouseEvent(
657 PepperPluginInstanceImpl* instance) {
658 render_view_->set_pepper_last_mouse_event_target(instance);
661 void RenderFrameImpl::PepperTextInputTypeChanged(
662 PepperPluginInstanceImpl* instance) {
663 if (instance != render_view_->focused_pepper_plugin())
664 return;
666 GetRenderWidget()->UpdateTextInputType();
667 if (renderer_accessibility())
668 renderer_accessibility()->FocusedNodeChanged(WebNode());
671 void RenderFrameImpl::PepperCaretPositionChanged(
672 PepperPluginInstanceImpl* instance) {
673 if (instance != render_view_->focused_pepper_plugin())
674 return;
675 GetRenderWidget()->UpdateSelectionBounds();
678 void RenderFrameImpl::PepperCancelComposition(
679 PepperPluginInstanceImpl* instance) {
680 if (instance != render_view_->focused_pepper_plugin())
681 return;
682 Send(new InputHostMsg_ImeCancelComposition(render_view_->GetRoutingID()));;
683 #if defined(OS_MACOSX) || defined(USE_AURA)
684 GetRenderWidget()->UpdateCompositionInfo(true);
685 #endif
688 void RenderFrameImpl::PepperSelectionChanged(
689 PepperPluginInstanceImpl* instance) {
690 if (instance != render_view_->focused_pepper_plugin())
691 return;
692 SyncSelectionIfRequired();
695 RenderWidgetFullscreenPepper* RenderFrameImpl::CreatePepperFullscreenContainer(
696 PepperPluginInstanceImpl* plugin) {
697 GURL active_url;
698 if (render_view_->webview() && render_view_->webview()->mainFrame())
699 active_url = GURL(render_view_->webview()->mainFrame()->document().url());
700 RenderWidgetFullscreenPepper* widget = RenderWidgetFullscreenPepper::Create(
701 GetRenderWidget()->routing_id(), plugin, active_url,
702 GetRenderWidget()->screenInfo());
703 widget->show(blink::WebNavigationPolicyIgnore);
704 return widget;
707 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
708 if (!render_view_->focused_pepper_plugin())
709 return false;
710 return render_view_->focused_pepper_plugin()->
711 IsPluginAcceptingCompositionEvents();
714 void RenderFrameImpl::PluginCrashed(const base::FilePath& plugin_path,
715 base::ProcessId plugin_pid) {
716 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
717 // routing_id_ as a result.
718 Send(new FrameHostMsg_PluginCrashed(routing_id_, plugin_path, plugin_pid));
721 void RenderFrameImpl::SimulateImeSetComposition(
722 const base::string16& text,
723 const std::vector<blink::WebCompositionUnderline>& underlines,
724 int selection_start,
725 int selection_end) {
726 render_view_->OnImeSetComposition(
727 text, underlines, selection_start, selection_end);
730 void RenderFrameImpl::SimulateImeConfirmComposition(
731 const base::string16& text,
732 const gfx::Range& replacement_range) {
733 render_view_->OnImeConfirmComposition(text, replacement_range, false);
737 void RenderFrameImpl::OnImeSetComposition(
738 const base::string16& text,
739 const std::vector<blink::WebCompositionUnderline>& underlines,
740 int selection_start,
741 int selection_end) {
742 // When a PPAPI plugin has focus, we bypass WebKit.
743 if (!IsPepperAcceptingCompositionEvents()) {
744 pepper_composition_text_ = text;
745 } else {
746 // TODO(kinaba) currently all composition events are sent directly to
747 // plugins. Use DOM event mechanism after WebKit is made aware about
748 // plugins that support composition.
749 // The code below mimics the behavior of WebCore::Editor::setComposition.
751 // Empty -> nonempty: composition started.
752 if (pepper_composition_text_.empty() && !text.empty()) {
753 render_view_->focused_pepper_plugin()->HandleCompositionStart(
754 base::string16());
756 // Nonempty -> empty: composition canceled.
757 if (!pepper_composition_text_.empty() && text.empty()) {
758 render_view_->focused_pepper_plugin()->HandleCompositionEnd(
759 base::string16());
761 pepper_composition_text_ = text;
762 // Nonempty: composition is ongoing.
763 if (!pepper_composition_text_.empty()) {
764 render_view_->focused_pepper_plugin()->HandleCompositionUpdate(
765 pepper_composition_text_, underlines, selection_start,
766 selection_end);
771 void RenderFrameImpl::OnImeConfirmComposition(
772 const base::string16& text,
773 const gfx::Range& replacement_range,
774 bool keep_selection) {
775 // When a PPAPI plugin has focus, we bypass WebKit.
776 // Here, text.empty() has a special meaning. It means to commit the last
777 // update of composition text (see
778 // RenderWidgetHost::ImeConfirmComposition()).
779 const base::string16& last_text = text.empty() ? pepper_composition_text_
780 : text;
782 // last_text is empty only when both text and pepper_composition_text_ is.
783 // Ignore it.
784 if (last_text.empty())
785 return;
787 if (!IsPepperAcceptingCompositionEvents()) {
788 base::i18n::UTF16CharIterator iterator(&last_text);
789 int32 i = 0;
790 while (iterator.Advance()) {
791 blink::WebKeyboardEvent char_event;
792 char_event.type = blink::WebInputEvent::Char;
793 char_event.timeStampSeconds = base::Time::Now().ToDoubleT();
794 char_event.modifiers = 0;
795 char_event.windowsKeyCode = last_text[i];
796 char_event.nativeKeyCode = last_text[i];
798 const int32 char_start = i;
799 for (; i < iterator.array_pos(); ++i) {
800 char_event.text[i - char_start] = last_text[i];
801 char_event.unmodifiedText[i - char_start] = last_text[i];
804 if (GetRenderWidget()->webwidget())
805 GetRenderWidget()->webwidget()->handleInputEvent(char_event);
807 } else {
808 // Mimics the order of events sent by WebKit.
809 // See WebCore::Editor::setComposition() for the corresponding code.
810 render_view_->focused_pepper_plugin()->HandleCompositionEnd(last_text);
811 render_view_->focused_pepper_plugin()->HandleTextInput(last_text);
813 pepper_composition_text_.clear();
816 #endif // ENABLE_PLUGINS
818 MediaStreamDispatcher* RenderFrameImpl::GetMediaStreamDispatcher() {
819 if (!web_user_media_client_)
820 InitializeUserMediaClient();
821 return web_user_media_client_ ?
822 web_user_media_client_->media_stream_dispatcher() : NULL;
825 bool RenderFrameImpl::Send(IPC::Message* message) {
826 if (is_detaching_) {
827 delete message;
828 return false;
830 if (frame_->parent() == NULL &&
831 (is_swapped_out_ || render_view_->is_swapped_out())) {
832 if (!SwappedOutMessages::CanSendWhileSwappedOut(message)) {
833 delete message;
834 return false;
837 // In most cases, send IPCs through the proxy when swapped out. In some
838 // calls the associated RenderViewImpl routing id is used to send
839 // messages, so don't use the proxy.
840 if (render_frame_proxy_ && message->routing_id() == routing_id_)
841 return render_frame_proxy_->Send(message);
844 return RenderThread::Get()->Send(message);
847 #if defined(OS_MACOSX) || defined(OS_ANDROID)
848 void RenderFrameImpl::DidHideExternalPopupMenu() {
849 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
850 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
851 external_popup_menu_.reset();
853 #endif
855 bool RenderFrameImpl::OnMessageReceived(const IPC::Message& msg) {
856 // TODO(kenrb): document() should not be null, but as a transitional step
857 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
858 // to this method. This happens for a top-level remote frame, where a
859 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
860 // around and is still able to receive messages.
861 if (!frame_->document().isNull())
862 GetContentClient()->SetActiveURL(frame_->document().url());
864 ObserverListBase<RenderFrameObserver>::Iterator it(observers_);
865 RenderFrameObserver* observer;
866 while ((observer = it.GetNext()) != NULL) {
867 if (observer->OnMessageReceived(msg))
868 return true;
871 bool handled = true;
872 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl, msg)
873 IPC_MESSAGE_HANDLER(FrameMsg_Navigate, OnNavigate)
874 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload, OnBeforeUnload)
875 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut, OnSwapOut)
876 IPC_MESSAGE_HANDLER(FrameMsg_Stop, OnStop)
877 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed, OnContextMenuClosed)
878 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction,
879 OnCustomContextMenuAction)
880 IPC_MESSAGE_HANDLER(InputMsg_Undo, OnUndo)
881 IPC_MESSAGE_HANDLER(InputMsg_Redo, OnRedo)
882 IPC_MESSAGE_HANDLER(InputMsg_Cut, OnCut)
883 IPC_MESSAGE_HANDLER(InputMsg_Copy, OnCopy)
884 IPC_MESSAGE_HANDLER(InputMsg_Paste, OnPaste)
885 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle, OnPasteAndMatchStyle)
886 IPC_MESSAGE_HANDLER(InputMsg_Delete, OnDelete)
887 IPC_MESSAGE_HANDLER(InputMsg_SelectAll, OnSelectAll)
888 IPC_MESSAGE_HANDLER(InputMsg_SelectRange, OnSelectRange)
889 IPC_MESSAGE_HANDLER(InputMsg_Unselect, OnUnselect)
890 IPC_MESSAGE_HANDLER(InputMsg_Replace, OnReplace)
891 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling, OnReplaceMisspelling)
892 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete,
893 OnExtendSelectionAndDelete)
894 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText,
895 OnSetCompositionFromExistingText)
896 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest, OnCSSInsertRequest)
897 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest,
898 OnJavaScriptExecuteRequest)
899 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests,
900 OnJavaScriptExecuteRequestForTests)
901 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets,
902 OnSetEditableSelectionOffsets)
903 IPC_MESSAGE_HANDLER(FrameMsg_SetupTransitionView, OnSetupTransitionView)
904 IPC_MESSAGE_HANDLER(FrameMsg_BeginExitTransition, OnBeginExitTransition)
905 IPC_MESSAGE_HANDLER(FrameMsg_Reload, OnReload)
906 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest,
907 OnTextSurroundingSelectionRequest)
908 IPC_MESSAGE_HANDLER(FrameMsg_AddStyleSheetByURL,
909 OnAddStyleSheetByURL)
910 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode,
911 OnSetAccessibilityMode)
912 IPC_MESSAGE_HANDLER(FrameMsg_DisownOpener, OnDisownOpener)
913 IPC_MESSAGE_HANDLER(FrameMsg_RequestNavigation, OnRequestNavigation)
914 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation, OnCommitNavigation)
915 #if defined(OS_ANDROID)
916 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems, OnSelectPopupMenuItems)
917 #elif defined(OS_MACOSX)
918 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem, OnSelectPopupMenuItem)
919 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard, OnCopyToFindPboard)
920 #endif
921 IPC_END_MESSAGE_MAP()
923 return handled;
926 void RenderFrameImpl::OnNavigate(const FrameMsg_Navigate_Params& params) {
927 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate",
928 "id", routing_id_,
929 "url", params.common_params.url.possibly_invalid_spec());
930 bool is_reload =
931 RenderViewImpl::IsReload(params.common_params.navigation_type);
932 WebURLRequest::CachePolicy cache_policy =
933 WebURLRequest::UseProtocolCachePolicy;
934 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
935 params.common_params.url, params.common_params.navigation_type,
936 params.commit_params.page_state, true, params.pending_history_list_offset,
937 params.page_id, &is_reload, &cache_policy)) {
938 return;
941 int pending_history_list_offset = params.pending_history_list_offset;
942 int current_history_list_offset = params.current_history_list_offset;
943 int current_history_list_length = params.current_history_list_length;
944 if (params.should_clear_history_list) {
945 CHECK_EQ(pending_history_list_offset, -1);
946 CHECK_EQ(current_history_list_offset, -1);
947 CHECK_EQ(current_history_list_length, 0);
949 render_view_->history_list_offset_ = current_history_list_offset;
950 render_view_->history_list_length_ = current_history_list_length;
951 if (render_view_->history_list_length_ >= 0) {
952 render_view_->history_page_ids_.resize(
953 render_view_->history_list_length_, -1);
955 if (pending_history_list_offset >= 0 &&
956 pending_history_list_offset < render_view_->history_list_length_) {
957 render_view_->history_page_ids_[pending_history_list_offset] =
958 params.page_id;
961 GetContentClient()->SetActiveURL(params.common_params.url);
963 WebFrame* frame = frame_;
964 if (!params.frame_to_navigate.empty()) {
965 // TODO(nasko): Move this lookup to the browser process.
966 frame = render_view_->webview()->findFrameByName(
967 WebString::fromUTF8(params.frame_to_navigate));
968 CHECK(frame) << "Invalid frame name passed: " << params.frame_to_navigate;
971 if (is_reload && !render_view_->history_controller()->GetCurrentEntry()) {
972 // We cannot reload if we do not have any history state. This happens, for
973 // example, when recovering from a crash.
974 is_reload = false;
975 cache_policy = WebURLRequest::ReloadIgnoringCacheData;
978 render_view_->pending_navigation_params_.reset(
979 new FrameMsg_Navigate_Params(params));
981 // If we are reloading, then WebKit will use the history state of the current
982 // page, so we should just ignore any given history state. Otherwise, if we
983 // have history state, then we need to navigate to it, which corresponds to a
984 // back/forward navigation event.
985 if (is_reload) {
986 bool reload_original_url =
987 (params.common_params.navigation_type ==
988 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
989 bool ignore_cache = (params.common_params.navigation_type ==
990 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE);
992 if (reload_original_url)
993 frame->reloadWithOverrideURL(params.common_params.url, true);
994 else
995 frame->reload(ignore_cache);
996 } else if (params.commit_params.page_state.IsValid()) {
997 // We must know the page ID of the page we are navigating back to.
998 DCHECK_NE(params.page_id, -1);
999 scoped_ptr<HistoryEntry> entry =
1000 PageStateToHistoryEntry(params.commit_params.page_state);
1001 if (entry) {
1002 // Ensure we didn't save the swapped out URL in UpdateState, since the
1003 // browser should never be telling us to navigate to swappedout://.
1004 CHECK(entry->root().urlString() != WebString::fromUTF8(kSwappedOutURL));
1005 render_view_->history_controller()->GoToEntry(entry.Pass(), cache_policy);
1007 } else if (!params.base_url_for_data_url.is_empty()) {
1008 // A loadData request with a specified base URL.
1009 std::string mime_type, charset, data;
1010 if (net::DataURL::Parse(
1011 params.common_params.url, &mime_type, &charset, &data)) {
1012 frame->loadData(
1013 WebData(data.c_str(), data.length()),
1014 WebString::fromUTF8(mime_type),
1015 WebString::fromUTF8(charset),
1016 params.base_url_for_data_url,
1017 params.history_url_for_data_url,
1018 false);
1019 } else {
1020 CHECK(false) << "Invalid URL passed: "
1021 << params.common_params.url.possibly_invalid_spec();
1023 } else {
1024 // Navigate to the given URL.
1025 WebURLRequest request =
1026 CreateURLRequestForNavigation(params.common_params,
1027 params.request_params,
1028 scoped_ptr<StreamOverrideParameters>(),
1029 frame->isViewSourceModeEnabled());
1031 // A session history navigation should have been accompanied by state.
1032 CHECK_EQ(params.page_id, -1);
1034 // Record this before starting the load, we need a lower bound of this time
1035 // to sanitize the navigationStart override set below.
1036 base::TimeTicks renderer_navigation_start = base::TimeTicks::Now();
1037 frame->loadRequest(request);
1039 UpdateFrameNavigationTiming(
1040 frame, params.commit_params.browser_navigation_start,
1041 renderer_navigation_start);
1044 // In case LoadRequest failed before DidCreateDataSource was called.
1045 render_view_->pending_navigation_params_.reset();
1048 void RenderFrameImpl::BindServiceRegistry(
1049 mojo::ScopedMessagePipeHandle service_provider_handle) {
1050 service_registry_.BindRemoteServiceProvider(service_provider_handle.Pass());
1053 ManifestManager* RenderFrameImpl::manifest_manager() {
1054 return manifest_manager_;
1057 void RenderFrameImpl::OnBeforeUnload() {
1058 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1059 "id", routing_id_);
1060 // TODO(creis): Right now, this is only called on the main frame. Make the
1061 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1062 // it.
1063 CHECK(!frame_->parent());
1065 base::TimeTicks before_unload_start_time = base::TimeTicks::Now();
1066 bool proceed = frame_->dispatchBeforeUnloadEvent();
1067 base::TimeTicks before_unload_end_time = base::TimeTicks::Now();
1068 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_, proceed,
1069 before_unload_start_time,
1070 before_unload_end_time));
1073 void RenderFrameImpl::OnSwapOut(int proxy_routing_id) {
1074 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_);
1075 RenderFrameProxy* proxy = NULL;
1076 bool is_site_per_process =
1077 CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess);
1078 bool is_main_frame = !frame_->parent();
1080 // Only run unload if we're not swapped out yet, but send the ack either way.
1081 if (!is_swapped_out_ || !render_view_->is_swapped_out_) {
1082 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1083 // a different process. This involves running the unload handler and
1084 // clearing the page. We also allow this process to exit if there are no
1085 // other active RenderFrames in it.
1087 // Send an UpdateState message before we get swapped out.
1088 render_view_->SyncNavigationState();
1090 // If we need a proxy to replace this, create it now so its routing id is
1091 // registered for receiving IPC messages.
1092 if (proxy_routing_id != MSG_ROUTING_NONE) {
1093 proxy = RenderFrameProxy::CreateProxyToReplaceFrame(this,
1094 proxy_routing_id);
1097 // Synchronously run the unload handler before sending the ACK.
1098 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1099 // unload on subframes as well.
1100 if (is_main_frame)
1101 frame_->dispatchUnloadEvent();
1103 // Swap out and stop sending any IPC messages that are not ACKs.
1104 // TODO(nasko): Do we need RenderFrameImpl::is_swapped_out_ anymore?
1105 if (is_main_frame)
1106 render_view_->SetSwappedOut(true);
1107 is_swapped_out_ = true;
1109 // Now that we're swapped out and filtering IPC messages, stop loading to
1110 // ensure that no other in-progress navigation continues. We do this here
1111 // to avoid sending a DidStopLoading message to the browser process.
1112 // TODO(creis): Should we be stopping all frames here and using
1113 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1114 // frame?
1115 OnStop();
1117 // Transfer settings such as initial drawing parameters to the remote frame,
1118 // if one is created, that will replace this frame.
1119 if (!is_main_frame && proxy)
1120 proxy->web_frame()->initializeFromFrame(frame_);
1122 // Replace the page with a blank dummy URL. The unload handler will not be
1123 // run a second time, thanks to a check in FrameLoader::stopLoading.
1124 // TODO(creis): Need to add a better way to do this that avoids running the
1125 // beforeunload handler. For now, we just run it a second time silently.
1126 if (!is_site_per_process || is_main_frame)
1127 render_view_->NavigateToSwappedOutURL(frame_);
1129 // Let WebKit know that this view is hidden so it can drop resources and
1130 // stop compositing.
1131 // TODO(creis): Support this for subframes as well.
1132 if (is_main_frame) {
1133 render_view_->webview()->setVisibilityState(
1134 blink::WebPageVisibilityStateHidden, false);
1138 // It is now safe to show modal dialogs again.
1139 // TODO(creis): Deal with modal dialogs from subframes.
1140 if (is_main_frame)
1141 render_view_->suppress_dialogs_until_swap_out_ = false;
1143 Send(new FrameHostMsg_SwapOut_ACK(routing_id_));
1145 // Now that all of the cleanup is complete and the browser side is notified,
1146 // start using the RenderFrameProxy, if one is created.
1147 if (proxy) {
1148 if (!is_main_frame) {
1149 frame_->swap(proxy->web_frame());
1150 if (is_site_per_process) {
1151 // TODO(nasko): delete the frame here, since we've replaced it with a
1152 // proxy.
1154 } else {
1155 set_render_frame_proxy(proxy);
1159 // Safe to exit if no one else is using the process.
1160 if (is_main_frame)
1161 render_view_->WasSwappedOut();
1164 void RenderFrameImpl::OnContextMenuClosed(
1165 const CustomContextMenuContext& custom_context) {
1166 if (custom_context.request_id) {
1167 // External request, should be in our map.
1168 ContextMenuClient* client =
1169 pending_context_menus_.Lookup(custom_context.request_id);
1170 if (client) {
1171 client->OnMenuClosed(custom_context.request_id);
1172 pending_context_menus_.Remove(custom_context.request_id);
1174 } else {
1175 if (custom_context.link_followed.is_valid()) {
1176 frame_->sendPings(
1177 DomUtils::ExtractParentAnchorNode(context_menu_node_),
1178 custom_context.link_followed);
1180 // Internal request, forward to WebKit.
1181 context_menu_node_.reset();
1185 void RenderFrameImpl::OnCustomContextMenuAction(
1186 const CustomContextMenuContext& custom_context,
1187 unsigned action) {
1188 if (custom_context.request_id) {
1189 // External context menu request, look in our map.
1190 ContextMenuClient* client =
1191 pending_context_menus_.Lookup(custom_context.request_id);
1192 if (client)
1193 client->OnMenuAction(custom_context.request_id, action);
1194 } else {
1195 // Internal request, forward to WebKit.
1196 render_view_->webview()->performCustomContextMenuAction(action);
1200 void RenderFrameImpl::OnUndo() {
1201 frame_->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1204 void RenderFrameImpl::OnRedo() {
1205 frame_->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1208 void RenderFrameImpl::OnCut() {
1209 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1210 frame_->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1213 void RenderFrameImpl::OnCopy() {
1214 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1215 WebNode current_node = context_menu_node_.isNull() ?
1216 GetFocusedElement() : context_menu_node_;
1217 frame_->executeCommand(WebString::fromUTF8("Copy"), current_node);
1220 void RenderFrameImpl::OnPaste() {
1221 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1222 frame_->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1225 void RenderFrameImpl::OnPasteAndMatchStyle() {
1226 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1227 frame_->executeCommand(
1228 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1231 #if defined(OS_MACOSX)
1232 void RenderFrameImpl::OnCopyToFindPboard() {
1233 // Since the find pasteboard supports only plain text, this can be simpler
1234 // than the |OnCopy()| case.
1235 if (frame_->hasSelection()) {
1236 base::string16 selection = frame_->selectionAsText();
1237 RenderThread::Get()->Send(
1238 new ClipboardHostMsg_FindPboardWriteStringAsync(selection));
1241 #endif
1243 void RenderFrameImpl::OnDelete() {
1244 frame_->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1247 void RenderFrameImpl::OnSelectAll() {
1248 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1249 frame_->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1252 void RenderFrameImpl::OnSelectRange(const gfx::Point& start,
1253 const gfx::Point& end) {
1254 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1255 Send(new ViewHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1257 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1258 frame_->selectRange(start, end);
1261 void RenderFrameImpl::OnUnselect() {
1262 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1263 frame_->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1266 void RenderFrameImpl::OnReplace(const base::string16& text) {
1267 if (!frame_->hasSelection())
1268 frame_->selectWordAroundCaret();
1270 frame_->replaceSelection(text);
1273 void RenderFrameImpl::OnReplaceMisspelling(const base::string16& text) {
1274 if (!frame_->hasSelection())
1275 return;
1277 frame_->replaceMisspelledRange(text);
1280 void RenderFrameImpl::OnCSSInsertRequest(const std::string& css) {
1281 frame_->document().insertStyleSheet(WebString::fromUTF8(css));
1284 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1285 const base::string16& jscript,
1286 int id,
1287 bool notify_result) {
1288 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1289 TRACE_EVENT_SCOPE_THREAD);
1291 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
1292 v8::Handle<v8::Value> result =
1293 frame_->executeScriptAndReturnValue(WebScriptSource(jscript));
1295 HandleJavascriptExecutionResult(jscript, id, notify_result, result);
1298 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1299 const base::string16& jscript,
1300 int id,
1301 bool notify_result) {
1302 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1303 TRACE_EVENT_SCOPE_THREAD);
1305 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
1306 v8::Handle<v8::Value> result =
1307 frame_->executeScriptAndReturnValueForTests(WebScriptSource(jscript));
1309 HandleJavascriptExecutionResult(jscript, id, notify_result, result);
1312 void RenderFrameImpl::HandleJavascriptExecutionResult(
1313 const base::string16& jscript,
1314 int id,
1315 bool notify_result,
1316 v8::Handle<v8::Value> result) {
1317 if (notify_result) {
1318 base::ListValue list;
1319 if (!result.IsEmpty()) {
1320 v8::Local<v8::Context> context = frame_->mainWorldScriptContext();
1321 v8::Context::Scope context_scope(context);
1322 V8ValueConverterImpl converter;
1323 converter.SetDateAllowed(true);
1324 converter.SetRegExpAllowed(true);
1325 base::Value* result_value = converter.FromV8Value(result, context);
1326 list.Set(0, result_value ? result_value : base::Value::CreateNullValue());
1327 } else {
1328 list.Set(0, base::Value::CreateNullValue());
1330 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_, id, list));
1334 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start, int end) {
1335 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1336 if (!GetRenderWidget()->ShouldHandleImeEvent())
1337 return;
1338 ImeEventGuard guard(GetRenderWidget());
1339 frame_->setEditableSelectionOffsets(start, end);
1342 void RenderFrameImpl::OnSetCompositionFromExistingText(
1343 int start, int end,
1344 const std::vector<blink::WebCompositionUnderline>& underlines) {
1345 if (!GetRenderWidget()->ShouldHandleImeEvent())
1346 return;
1347 ImeEventGuard guard(GetRenderWidget());
1348 frame_->setCompositionFromExistingText(start, end, underlines);
1351 void RenderFrameImpl::OnExtendSelectionAndDelete(int before, int after) {
1352 if (!GetRenderWidget()->ShouldHandleImeEvent())
1353 return;
1354 ImeEventGuard guard(GetRenderWidget());
1355 frame_->extendSelectionAndDelete(before, after);
1358 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode) {
1359 if (accessibility_mode_ == new_mode)
1360 return;
1361 accessibility_mode_ = new_mode;
1362 if (renderer_accessibility_) {
1363 // Note: this isn't called automatically by the destructor because
1364 // there'd be no point in calling it in frame teardown, only if there's
1365 // an accessibility mode change but the frame is persisting.
1366 renderer_accessibility_->DisableAccessibility();
1368 delete renderer_accessibility_;
1369 renderer_accessibility_ = NULL;
1371 if (accessibility_mode_ == AccessibilityModeOff)
1372 return;
1374 if (accessibility_mode_ & AccessibilityModeFlagFullTree)
1375 renderer_accessibility_ = new RendererAccessibilityComplete(this);
1378 void RenderFrameImpl::OnDisownOpener() {
1379 // TODO(creis): We should only see this for main frames for now. To support
1380 // disowning the opener on subframes, we will need to move WebContentsImpl's
1381 // opener_ to FrameTreeNode.
1382 CHECK(!frame_->parent());
1384 if (frame_->opener())
1385 frame_->setOpener(NULL);
1388 #if defined(OS_ANDROID)
1389 void RenderFrameImpl::OnSelectPopupMenuItems(
1390 bool canceled,
1391 const std::vector<int>& selected_indices) {
1392 // It is possible to receive more than one of these calls if the user presses
1393 // a select faster than it takes for the show-select-popup IPC message to make
1394 // it to the browser UI thread. Ignore the extra-messages.
1395 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1396 if (!external_popup_menu_)
1397 return;
1399 external_popup_menu_->DidSelectItems(canceled, selected_indices);
1400 external_popup_menu_.reset();
1402 #endif
1404 #if defined(OS_MACOSX)
1405 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index) {
1406 if (external_popup_menu_ == NULL)
1407 return;
1408 external_popup_menu_->DidSelectItem(selected_index);
1409 external_popup_menu_.reset();
1411 #endif
1413 void RenderFrameImpl::OnReload(bool ignore_cache) {
1414 frame_->reload(ignore_cache);
1417 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length) {
1418 blink::WebSurroundingText surroundingText;
1419 surroundingText.initialize(frame_->selectionRange(), max_length);
1421 if (surroundingText.isNull()) {
1422 // |surroundingText| might not be correctly initialized, for example if
1423 // |frame_->selectionRange().isNull()|, in other words, if there was no
1424 // selection.
1425 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1426 routing_id_, base::string16(), 0, 0));
1427 return;
1430 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1431 routing_id_,
1432 surroundingText.textContent(),
1433 surroundingText.startOffsetInTextContent(),
1434 surroundingText.endOffsetInTextContent()));
1437 void RenderFrameImpl::OnAddStyleSheetByURL(const std::string& url) {
1438 frame_->addStyleSheetByURL(WebString::fromUTF8(url));
1441 void RenderFrameImpl::OnSetupTransitionView(const std::string& markup) {
1442 frame_->document().setIsTransitionDocument();
1443 frame_->navigateToSandboxedMarkup(WebData(markup.data(), markup.length()));
1446 void RenderFrameImpl::OnBeginExitTransition(const std::string& css_selector) {
1447 frame_->document().setIsTransitionDocument();
1448 frame_->document().beginExitTransition(WebString::fromUTF8(css_selector));
1451 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type,
1452 const base::string16& message,
1453 const base::string16& default_value,
1454 const GURL& frame_url,
1455 base::string16* result) {
1456 // Don't allow further dialogs if we are waiting to swap out, since the
1457 // PageGroupLoadDeferrer in our stack prevents it.
1458 if (render_view()->suppress_dialogs_until_swap_out_)
1459 return false;
1461 bool success = false;
1462 base::string16 result_temp;
1463 if (!result)
1464 result = &result_temp;
1466 render_view()->SendAndRunNestedMessageLoop(
1467 new FrameHostMsg_RunJavaScriptMessage(
1468 routing_id_, message, default_value, frame_url, type, &success,
1469 result));
1470 return success;
1473 void RenderFrameImpl::LoadNavigationErrorPage(
1474 const WebURLRequest& failed_request,
1475 const WebURLError& error,
1476 bool replace) {
1477 std::string error_html;
1478 GetContentClient()->renderer()->GetNavigationErrorStrings(
1479 render_view(), frame_, failed_request, error, &error_html, NULL);
1481 frame_->loadHTMLString(error_html,
1482 GURL(kUnreachableWebDataURL),
1483 error.unreachableURL,
1484 replace);
1487 void RenderFrameImpl::DidCommitCompositorFrame() {
1488 FOR_EACH_OBSERVER(
1489 RenderFrameObserver, observers_, DidCommitCompositorFrame());
1492 RenderView* RenderFrameImpl::GetRenderView() {
1493 return render_view_.get();
1496 int RenderFrameImpl::GetRoutingID() {
1497 return routing_id_;
1500 blink::WebLocalFrame* RenderFrameImpl::GetWebFrame() {
1501 DCHECK(frame_);
1502 return frame_;
1505 WebPreferences& RenderFrameImpl::GetWebkitPreferences() {
1506 return render_view_->GetWebkitPreferences();
1509 int RenderFrameImpl::ShowContextMenu(ContextMenuClient* client,
1510 const ContextMenuParams& params) {
1511 DCHECK(client); // A null client means "internal" when we issue callbacks.
1512 ContextMenuParams our_params(params);
1513 our_params.custom_context.request_id = pending_context_menus_.Add(client);
1514 Send(new FrameHostMsg_ContextMenu(routing_id_, our_params));
1515 return our_params.custom_context.request_id;
1518 void RenderFrameImpl::CancelContextMenu(int request_id) {
1519 DCHECK(pending_context_menus_.Lookup(request_id));
1520 pending_context_menus_.Remove(request_id);
1523 blink::WebNode RenderFrameImpl::GetContextMenuNode() const {
1524 return context_menu_node_;
1527 blink::WebPlugin* RenderFrameImpl::CreatePlugin(
1528 blink::WebFrame* frame,
1529 const WebPluginInfo& info,
1530 const blink::WebPluginParams& params) {
1531 DCHECK_EQ(frame_, frame);
1532 #if defined(ENABLE_PLUGINS)
1533 bool pepper_plugin_was_registered = false;
1534 scoped_refptr<PluginModule> pepper_module(PluginModule::Create(
1535 this, info, &pepper_plugin_was_registered));
1536 if (pepper_plugin_was_registered) {
1537 if (pepper_module.get()) {
1538 return new PepperWebPluginImpl(pepper_module.get(), params, this);
1541 #if defined(OS_CHROMEOS)
1542 LOG(WARNING) << "Pepper module/plugin creation failed.";
1543 return NULL;
1544 #else
1545 // TODO(jam): change to take RenderFrame.
1546 return new WebPluginImpl(frame, params, info.path, render_view_, this);
1547 #endif
1548 #else
1549 return NULL;
1550 #endif
1553 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame* frame,
1554 const blink::WebURLRequest& request,
1555 blink::WebNavigationPolicy policy) {
1556 DCHECK(!frame_ || frame_ == frame);
1557 loadURLExternally(frame, request, policy, WebString());
1560 void RenderFrameImpl::ExecuteJavaScript(const base::string16& javascript) {
1561 OnJavaScriptExecuteRequest(javascript, 0, false);
1564 ServiceRegistry* RenderFrameImpl::GetServiceRegistry() {
1565 return &service_registry_;
1568 bool RenderFrameImpl::IsFTPDirectoryListing() {
1569 WebURLResponseExtraDataImpl* extra_data =
1570 GetExtraDataFromResponse(frame_->dataSource()->response());
1571 return extra_data ? extra_data->is_ftp_directory_listing() : false;
1574 void RenderFrameImpl::AttachGuest(int element_instance_id) {
1575 render_view_->GetBrowserPluginManager()->Attach(element_instance_id);
1578 void RenderFrameImpl::SetSelectedText(const base::string16& selection_text,
1579 size_t offset,
1580 const gfx::Range& range) {
1581 // Use the routing id of Render Widget Host.
1582 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1583 selection_text,
1584 offset,
1585 range));
1588 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1589 v8::Isolate* isolate,
1590 v8::Handle<v8::Context> context) {
1591 gin::ModuleRegistry* registry = gin::ModuleRegistry::From(context);
1592 if (registry->available_modules().count(mojo::js::Core::kModuleName))
1593 return;
1595 v8::HandleScope handle_scope(isolate);
1596 registry->AddBuiltinModule(
1597 isolate, mojo::js::Core::kModuleName, mojo::js::Core::GetModule(isolate));
1598 registry->AddBuiltinModule(isolate,
1599 mojo::js::Support::kModuleName,
1600 mojo::js::Support::GetModule(isolate));
1601 registry->AddBuiltinModule(
1602 isolate,
1603 ServiceRegistryJsWrapper::kModuleName,
1604 ServiceRegistryJsWrapper::Create(isolate, &service_registry_).ToV8());
1607 // blink::WebFrameClient implementation ----------------------------------------
1609 blink::WebPlugin* RenderFrameImpl::createPlugin(
1610 blink::WebLocalFrame* frame,
1611 const blink::WebPluginParams& params) {
1612 DCHECK_EQ(frame_, frame);
1613 blink::WebPlugin* plugin = NULL;
1614 if (GetContentClient()->renderer()->OverrideCreatePlugin(
1615 this, frame, params, &plugin)) {
1616 return plugin;
1619 if (base::UTF16ToUTF8(params.mimeType) == kBrowserPluginMimeType) {
1620 scoped_ptr<BrowserPluginDelegate> browser_plugin_delegate(
1621 GetContentClient()->renderer()->CreateBrowserPluginDelegate(
1622 this, std::string()));
1623 return render_view_->GetBrowserPluginManager()->CreateBrowserPlugin(
1624 render_view_.get(), frame, browser_plugin_delegate.Pass());
1627 #if defined(ENABLE_PLUGINS)
1628 WebPluginInfo info;
1629 std::string mime_type;
1630 bool found = false;
1631 Send(new FrameHostMsg_GetPluginInfo(
1632 routing_id_, params.url, frame->top()->document().url(),
1633 params.mimeType.utf8(), &found, &info, &mime_type));
1634 if (!found)
1635 return NULL;
1637 if (info.type == content::WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN) {
1638 scoped_ptr<BrowserPluginDelegate> browser_plugin_delegate(
1639 GetContentClient()->renderer()->CreateBrowserPluginDelegate(
1640 this, base::UTF16ToUTF8(params.mimeType)));
1641 return render_view_->GetBrowserPluginManager()->CreateBrowserPlugin(
1642 render_view_.get(), frame, browser_plugin_delegate.Pass());
1646 WebPluginParams params_to_use = params;
1647 params_to_use.mimeType = WebString::fromUTF8(mime_type);
1648 return CreatePlugin(frame, info, params_to_use);
1649 #else
1650 return NULL;
1651 #endif // defined(ENABLE_PLUGINS)
1654 blink::WebMediaPlayer* RenderFrameImpl::createMediaPlayer(
1655 blink::WebLocalFrame* frame,
1656 const blink::WebURL& url,
1657 blink::WebMediaPlayerClient* client) {
1658 return createMediaPlayer(frame, url, client, NULL);
1661 blink::WebMediaPlayer* RenderFrameImpl::createMediaPlayer(
1662 blink::WebLocalFrame* frame,
1663 const blink::WebURL& url,
1664 blink::WebMediaPlayerClient* client,
1665 blink::WebContentDecryptionModule* initial_cdm) {
1666 #if defined(VIDEO_HOLE)
1667 if (!contains_media_player_) {
1668 render_view_->RegisterVideoHoleFrame(this);
1669 contains_media_player_ = true;
1671 #endif // defined(VIDEO_HOLE)
1673 blink::WebMediaStream web_stream(
1674 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url));
1675 if (!web_stream.isNull())
1676 return CreateWebMediaPlayerForMediaStream(url, client);
1678 #if defined(OS_ANDROID)
1679 return CreateAndroidWebMediaPlayer(url, client, initial_cdm);
1680 #else
1681 RenderThreadImpl* render_thread = RenderThreadImpl::current();
1682 media::WebMediaPlayerParams params(
1683 base::Bind(&ContentRendererClient::DeferMediaLoad,
1684 base::Unretained(GetContentClient()->renderer()),
1685 static_cast<RenderFrame*>(this)),
1686 render_thread->GetAudioRendererMixerManager()->CreateInput(
1687 render_view_->routing_id_, routing_id_),
1688 *render_thread->GetAudioHardwareConfig(),
1689 new RenderMediaLog(),
1690 render_thread->GetGpuFactories(),
1691 render_thread->GetMediaThreadTaskRunner(),
1692 render_thread->compositor_message_loop_proxy(),
1693 base::Bind(&EncryptedMediaPlayerSupportImpl::Create),
1694 initial_cdm);
1695 return new media::WebMediaPlayerImpl(frame,
1696 client,
1697 weak_factory_.GetWeakPtr(),
1698 params);
1699 #endif // defined(OS_ANDROID)
1702 blink::WebContentDecryptionModule*
1703 RenderFrameImpl::createContentDecryptionModule(
1704 blink::WebLocalFrame* frame,
1705 const blink::WebSecurityOrigin& security_origin,
1706 const blink::WebString& key_system) {
1707 DCHECK(!frame_ || frame_ == frame);
1709 #if defined(ENABLE_PEPPER_CDMS)
1710 RenderCdmFactory cdm_factory(
1711 base::Bind(&PepperCdmWrapperImpl::Create, frame));
1712 #elif defined(ENABLE_BROWSER_CDMS)
1713 RenderCdmFactory cdm_factory(GetCdmManager());
1714 #else
1715 RenderCdmFactory cdm_factory;
1716 #endif
1718 return WebContentDecryptionModuleImpl::Create(&cdm_factory, security_origin,
1719 key_system);
1722 blink::WebApplicationCacheHost* RenderFrameImpl::createApplicationCacheHost(
1723 blink::WebLocalFrame* frame,
1724 blink::WebApplicationCacheHostClient* client) {
1725 if (!frame || !frame->view())
1726 return NULL;
1727 DCHECK(!frame_ || frame_ == frame);
1728 return new RendererWebApplicationCacheHostImpl(
1729 RenderViewImpl::FromWebView(frame->view()), client,
1730 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
1733 blink::WebWorkerPermissionClientProxy*
1734 RenderFrameImpl::createWorkerPermissionClientProxy(
1735 blink::WebLocalFrame* frame) {
1736 if (!frame || !frame->view())
1737 return NULL;
1738 DCHECK(!frame_ || frame_ == frame);
1739 return GetContentClient()->renderer()->CreateWorkerPermissionClientProxy(
1740 this, frame);
1743 WebExternalPopupMenu* RenderFrameImpl::createExternalPopupMenu(
1744 const WebPopupMenuInfo& popup_menu_info,
1745 WebExternalPopupMenuClient* popup_menu_client) {
1746 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1747 // An IPC message is sent to the browser to build and display the actual
1748 // popup. The user could have time to click a different select by the time
1749 // the popup is shown. In that case external_popup_menu_ is non NULL.
1750 // By returning NULL in that case, we instruct Blink to cancel that new
1751 // popup. So from the user perspective, only the first one will show, and
1752 // will have to close the first one before another one can be shown.
1753 if (external_popup_menu_)
1754 return NULL;
1755 external_popup_menu_.reset(
1756 new ExternalPopupMenu(this, popup_menu_info, popup_menu_client));
1757 if (render_view_->screen_metrics_emulator_) {
1758 render_view_->SetExternalPopupOriginAdjustmentsForEmulation(
1759 external_popup_menu_.get(),
1760 render_view_->screen_metrics_emulator_.get());
1762 return external_popup_menu_.get();
1763 #else
1764 return NULL;
1765 #endif
1768 blink::WebCookieJar* RenderFrameImpl::cookieJar(blink::WebLocalFrame* frame) {
1769 DCHECK(!frame_ || frame_ == frame);
1770 return &cookie_jar_;
1773 blink::WebServiceWorkerProvider* RenderFrameImpl::createServiceWorkerProvider(
1774 blink::WebLocalFrame* frame) {
1775 DCHECK(!frame_ || frame_ == frame);
1776 // At this point we should have non-null data source.
1777 DCHECK(frame->dataSource());
1778 if (!ChildThread::current())
1779 return NULL; // May be null in some tests.
1780 ServiceWorkerNetworkProvider* provider =
1781 ServiceWorkerNetworkProvider::FromDocumentState(
1782 DocumentState::FromDataSource(frame->dataSource()));
1783 return new WebServiceWorkerProviderImpl(
1784 ChildThread::current()->thread_safe_sender(),
1785 provider ? provider->context() : NULL);
1788 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame* frame) {
1789 DCHECK(!frame_ || frame_ == frame);
1790 // Notify the browser process that it is no longer safe to show the pending
1791 // URL of the main frame, since a URL spoof is now possible.
1792 if (!frame->parent() && render_view_->page_id_ == -1)
1793 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_));
1796 blink::WebFrame* RenderFrameImpl::createChildFrame(
1797 blink::WebLocalFrame* parent,
1798 const blink::WebString& name) {
1799 // Synchronously notify the browser of a child frame creation to get the
1800 // routing_id for the RenderFrame.
1801 int child_routing_id = MSG_ROUTING_NONE;
1802 Send(new FrameHostMsg_CreateChildFrame(routing_id_,
1803 base::UTF16ToUTF8(name),
1804 &child_routing_id));
1805 // Allocation of routing id failed, so we can't create a child frame. This can
1806 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
1807 // out state.
1808 if (child_routing_id == MSG_ROUTING_NONE) {
1809 #if !defined(OS_LINUX)
1810 // DumpWithoutCrashing() crashes on Linux in renderer processes when
1811 // breakpad and sandboxing are enabled: crbug.com/349600
1812 base::debug::Alias(parent);
1813 base::debug::Alias(&routing_id_);
1814 bool render_view_is_swapped_out = GetRenderWidget()->is_swapped_out();
1815 base::debug::Alias(&render_view_is_swapped_out);
1816 bool render_view_is_closing = GetRenderWidget()->closing();
1817 base::debug::Alias(&render_view_is_closing);
1818 base::debug::Alias(&is_swapped_out_);
1819 base::debug::DumpWithoutCrashing();
1820 #endif
1821 return NULL;
1824 // Create the RenderFrame and WebLocalFrame, linking the two.
1825 RenderFrameImpl* child_render_frame = RenderFrameImpl::Create(
1826 render_view_.get(), child_routing_id);
1827 blink::WebLocalFrame* web_frame = WebLocalFrame::create(child_render_frame);
1828 child_render_frame->SetWebFrame(web_frame);
1830 // Add the frame to the frame tree and initialize it.
1831 parent->appendChild(web_frame);
1832 child_render_frame->Initialize();
1834 return web_frame;
1837 void RenderFrameImpl::didDisownOpener(blink::WebLocalFrame* frame) {
1838 DCHECK(!frame_ || frame_ == frame);
1839 // We only need to notify the browser if the active, top-level frame clears
1840 // its opener. We can ignore cases where a swapped out frame clears its
1841 // opener after hearing about it from the browser, and the browser does not
1842 // (yet) care about subframe openers.
1843 if (render_view_->is_swapped_out_ || frame->parent())
1844 return;
1846 // Notify WebContents and all its swapped out RenderViews.
1847 Send(new FrameHostMsg_DidDisownOpener(routing_id_));
1850 void RenderFrameImpl::frameDetached(blink::WebFrame* frame) {
1851 // NOTE: This function is called on the frame that is being detached and not
1852 // the parent frame. This is different from createChildFrame() which is
1853 // called on the parent frame.
1854 CHECK(!is_detaching_);
1855 DCHECK(!frame_ || frame_ == frame);
1857 bool is_subframe = !!frame->parent();
1859 Send(new FrameHostMsg_Detach(routing_id_));
1861 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
1862 // sent before setting |is_detaching_| to true. In contrast, Observers
1863 // should only be notified afterwards so they cannot call back into here and
1864 // have IPCs fired off.
1865 is_detaching_ = true;
1867 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
1868 FrameDetached(frame));
1870 // We need to clean up subframes by removing them from the map and deleting
1871 // the RenderFrameImpl. In contrast, the main frame is owned by its
1872 // containing RenderViewHost (so that they have the same lifetime), so only
1873 // removal from the map is needed and no deletion.
1874 FrameMap::iterator it = g_frame_map.Get().find(frame);
1875 CHECK(it != g_frame_map.Get().end());
1876 CHECK_EQ(it->second, this);
1877 g_frame_map.Get().erase(it);
1879 if (is_subframe)
1880 frame->parent()->removeChild(frame);
1882 // |frame| is invalid after here.
1883 frame->close();
1885 if (is_subframe) {
1886 delete this;
1887 // Object is invalid after this point.
1891 void RenderFrameImpl::frameFocused() {
1892 Send(new FrameHostMsg_FrameFocused(routing_id_));
1895 void RenderFrameImpl::willClose(blink::WebFrame* frame) {
1896 DCHECK(!frame_ || frame_ == frame);
1898 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FrameWillClose());
1899 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
1900 FrameWillClose(frame));
1903 void RenderFrameImpl::didChangeName(blink::WebLocalFrame* frame,
1904 const blink::WebString& name) {
1905 DCHECK(!frame_ || frame_ == frame);
1906 if (!render_view_->renderer_preferences_.report_frame_name_changes)
1907 return;
1909 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeName(name));
1912 void RenderFrameImpl::didMatchCSS(
1913 blink::WebLocalFrame* frame,
1914 const blink::WebVector<blink::WebString>& newly_matching_selectors,
1915 const blink::WebVector<blink::WebString>& stopped_matching_selectors) {
1916 DCHECK(!frame_ || frame_ == frame);
1918 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
1919 DidMatchCSS(frame,
1920 newly_matching_selectors,
1921 stopped_matching_selectors));
1924 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
1925 const blink::WebString& source) {
1926 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
1927 source);
1930 void RenderFrameImpl::didAddMessageToConsole(
1931 const blink::WebConsoleMessage& message,
1932 const blink::WebString& source_name,
1933 unsigned source_line,
1934 const blink::WebString& stack_trace) {
1935 logging::LogSeverity log_severity = logging::LOG_VERBOSE;
1936 switch (message.level) {
1937 case blink::WebConsoleMessage::LevelDebug:
1938 log_severity = logging::LOG_VERBOSE;
1939 break;
1940 case blink::WebConsoleMessage::LevelLog:
1941 case blink::WebConsoleMessage::LevelInfo:
1942 log_severity = logging::LOG_INFO;
1943 break;
1944 case blink::WebConsoleMessage::LevelWarning:
1945 log_severity = logging::LOG_WARNING;
1946 break;
1947 case blink::WebConsoleMessage::LevelError:
1948 log_severity = logging::LOG_ERROR;
1949 break;
1950 default:
1951 NOTREACHED();
1954 if (shouldReportDetailedMessageForSource(source_name)) {
1955 FOR_EACH_OBSERVER(
1956 RenderFrameObserver, observers_,
1957 DetailedConsoleMessageAdded(message.text,
1958 source_name,
1959 stack_trace,
1960 source_line,
1961 static_cast<int32>(log_severity)));
1964 Send(new FrameHostMsg_AddMessageToConsole(routing_id_,
1965 static_cast<int32>(log_severity),
1966 message.text,
1967 static_cast<int32>(source_line),
1968 source_name));
1971 void RenderFrameImpl::loadURLExternally(
1972 blink::WebLocalFrame* frame,
1973 const blink::WebURLRequest& request,
1974 blink::WebNavigationPolicy policy,
1975 const blink::WebString& suggested_name) {
1976 DCHECK(!frame_ || frame_ == frame);
1977 Referrer referrer(RenderViewImpl::GetReferrerFromRequest(frame, request));
1978 if (policy == blink::WebNavigationPolicyDownload) {
1979 render_view_->Send(new ViewHostMsg_DownloadUrl(render_view_->GetRoutingID(),
1980 request.url(), referrer,
1981 suggested_name));
1982 } else {
1983 OpenURL(frame, request.url(), referrer, policy);
1987 blink::WebNavigationPolicy RenderFrameImpl::decidePolicyForNavigation(
1988 const NavigationPolicyInfo& info) {
1989 DCHECK(!frame_ || frame_ == info.frame);
1990 return DecidePolicyForNavigation(this, info);
1993 blink::WebHistoryItem RenderFrameImpl::historyItemForNewChildFrame(
1994 blink::WebFrame* frame) {
1995 DCHECK(!frame_ || frame_ == frame);
1996 return render_view_->history_controller()->GetItemForNewChildFrame(this);
1999 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame* frame,
2000 const blink::WebFormElement& form) {
2001 DCHECK(!frame_ || frame_ == frame);
2003 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2004 WillSendSubmitEvent(frame, form));
2007 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame* frame,
2008 const blink::WebFormElement& form) {
2009 DCHECK(!frame_ || frame_ == frame);
2010 DocumentState* document_state =
2011 DocumentState::FromDataSource(frame->provisionalDataSource());
2012 NavigationState* navigation_state = document_state->navigation_state();
2013 InternalDocumentStateData* internal_data =
2014 InternalDocumentStateData::FromDocumentState(document_state);
2016 if (ui::PageTransitionCoreTypeIs(navigation_state->transition_type(),
2017 ui::PAGE_TRANSITION_LINK)) {
2018 navigation_state->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT);
2021 // Save these to be processed when the ensuing navigation is committed.
2022 WebSearchableFormData web_searchable_form_data(form);
2023 internal_data->set_searchable_form_url(web_searchable_form_data.url());
2024 internal_data->set_searchable_form_encoding(
2025 web_searchable_form_data.encoding().utf8());
2027 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2028 WillSubmitForm(frame, form));
2031 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame* frame,
2032 blink::WebDataSource* datasource) {
2033 DCHECK(!frame_ || frame_ == frame);
2035 // TODO(nasko): Move implementation here. Needed state:
2036 // * pending_navigation_params_
2037 // * webview
2038 // Needed methods:
2039 // * PopulateDocumentStateFromPending
2040 // * CreateNavigationStateFromPending
2041 render_view_->didCreateDataSource(frame, datasource);
2043 // Create the serviceworker's per-document network observing object.
2044 scoped_ptr<ServiceWorkerNetworkProvider>
2045 network_provider(new ServiceWorkerNetworkProvider());
2046 ServiceWorkerNetworkProvider::AttachToDocumentState(
2047 DocumentState::FromDataSource(datasource),
2048 network_provider.Pass());
2051 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame* frame,
2052 bool is_transition_navigation) {
2053 DCHECK(!frame_ || frame_ == frame);
2054 WebDataSource* ds = frame->provisionalDataSource();
2056 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2057 // callback is invoked.
2058 if (!ds)
2059 return;
2061 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2062 "id", routing_id_, "url", ds->request().url().string().utf8());
2063 DocumentState* document_state = DocumentState::FromDataSource(ds);
2065 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2066 CHECK((ds->request().url() != GURL(kSwappedOutURL)) ||
2067 is_swapped_out_ ||
2068 render_view_->is_swapped_out()) <<
2069 "Heard swappedout:// when not swapped out.";
2071 // Update the request time if WebKit has better knowledge of it.
2072 if (document_state->request_time().is_null()) {
2073 double event_time = ds->triggeringEventTime();
2074 if (event_time != 0.0)
2075 document_state->set_request_time(Time::FromDoubleT(event_time));
2078 // Start time is only set after request time.
2079 document_state->set_start_load_time(Time::Now());
2081 bool is_top_most = !frame->parent();
2082 if (is_top_most) {
2083 render_view_->set_navigation_gesture(
2084 WebUserGestureIndicator::isProcessingUserGesture() ?
2085 NavigationGestureUser : NavigationGestureAuto);
2086 } else if (ds->replacesCurrentHistoryItem()) {
2087 // Subframe navigations that don't add session history items must be
2088 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2089 // handle loading of error pages.
2090 document_state->navigation_state()->set_transition_type(
2091 ui::PAGE_TRANSITION_AUTO_SUBFRAME);
2094 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2095 DidStartProvisionalLoad(frame));
2096 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidStartProvisionalLoad());
2098 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2099 routing_id_, ds->request().url(), is_transition_navigation));
2102 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2103 blink::WebLocalFrame* frame) {
2104 DCHECK(!frame_ || frame_ == frame);
2105 render_view_->history_controller()->RemoveChildrenForRedirect(this);
2108 void RenderFrameImpl::didFailProvisionalLoad(blink::WebLocalFrame* frame,
2109 const blink::WebURLError& error) {
2110 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2111 "id", routing_id_);
2112 DCHECK(!frame_ || frame_ == frame);
2113 WebDataSource* ds = frame->provisionalDataSource();
2114 DCHECK(ds);
2116 const WebURLRequest& failed_request = ds->request();
2118 // Notify the browser that we failed a provisional load with an error.
2120 // Note: It is important this notification occur before DidStopLoading so the
2121 // SSL manager can react to the provisional load failure before being
2122 // notified the load stopped.
2124 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2125 DidFailProvisionalLoad(frame, error));
2126 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
2127 DidFailProvisionalLoad(error));
2129 bool show_repost_interstitial =
2130 (error.reason == net::ERR_CACHE_MISS &&
2131 EqualsASCII(failed_request.httpMethod(), "POST"));
2133 FrameHostMsg_DidFailProvisionalLoadWithError_Params params;
2134 params.error_code = error.reason;
2135 GetContentClient()->renderer()->GetNavigationErrorStrings(
2136 render_view_.get(),
2137 frame,
2138 failed_request,
2139 error,
2140 NULL,
2141 &params.error_description);
2142 params.url = error.unreachableURL;
2143 params.showing_repost_interstitial = show_repost_interstitial;
2144 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(
2145 routing_id_, params));
2147 // Don't display an error page if this is simply a cancelled load. Aside
2148 // from being dumb, WebCore doesn't expect it and it will cause a crash.
2149 if (error.reason == net::ERR_ABORTED)
2150 return;
2152 // Don't display "client blocked" error page if browser has asked us not to.
2153 if (error.reason == net::ERR_BLOCKED_BY_CLIENT &&
2154 render_view_->renderer_preferences_.disable_client_blocked_error_page) {
2155 return;
2158 // Allow the embedder to suppress an error page.
2159 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(this,
2160 error.unreachableURL)) {
2161 return;
2164 if (RenderThreadImpl::current() &&
2165 RenderThreadImpl::current()->layout_test_mode()) {
2166 return;
2169 // Make sure we never show errors in view source mode.
2170 frame->enableViewSourceMode(false);
2172 DocumentState* document_state = DocumentState::FromDataSource(ds);
2173 NavigationState* navigation_state = document_state->navigation_state();
2175 // If this is a failed back/forward/reload navigation, then we need to do a
2176 // 'replace' load. This is necessary to avoid messing up session history.
2177 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2178 // as session history is concerned.
2180 // AUTO_SUBFRAME loads should always be treated as loads that do not advance
2181 // the page id.
2183 // TODO(davidben): This should also take the failed navigation's replacement
2184 // state into account, if a location.replace() failed.
2185 bool replace =
2186 navigation_state->pending_page_id() != -1 ||
2187 ui::PageTransitionCoreTypeIs(navigation_state->transition_type(),
2188 ui::PAGE_TRANSITION_AUTO_SUBFRAME);
2190 // If we failed on a browser initiated request, then make sure that our error
2191 // page load is regarded as the same browser initiated request.
2192 if (!navigation_state->is_content_initiated()) {
2193 render_view_->pending_navigation_params_.reset(
2194 new FrameMsg_Navigate_Params);
2195 render_view_->pending_navigation_params_->page_id =
2196 navigation_state->pending_page_id();
2197 render_view_->pending_navigation_params_->pending_history_list_offset =
2198 navigation_state->pending_history_list_offset();
2199 render_view_->pending_navigation_params_->should_clear_history_list =
2200 navigation_state->history_list_was_cleared();
2201 render_view_->pending_navigation_params_->common_params.transition =
2202 navigation_state->transition_type();
2203 render_view_->pending_navigation_params_->request_time =
2204 document_state->request_time();
2205 render_view_->pending_navigation_params_->should_replace_current_entry =
2206 replace;
2209 // Load an error page.
2210 LoadNavigationErrorPage(failed_request, error, replace);
2213 void RenderFrameImpl::didCommitProvisionalLoad(
2214 blink::WebLocalFrame* frame,
2215 const blink::WebHistoryItem& item,
2216 blink::WebHistoryCommitType commit_type) {
2217 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2218 "id", routing_id_,
2219 "url", GetLoadingUrl().possibly_invalid_spec());
2220 DCHECK(!frame_ || frame_ == frame);
2221 DocumentState* document_state =
2222 DocumentState::FromDataSource(frame->dataSource());
2223 NavigationState* navigation_state = document_state->navigation_state();
2225 // When we perform a new navigation, we need to update the last committed
2226 // session history entry with state for the page we are leaving. Do this
2227 // before updating the HistoryController state.
2228 render_view_->UpdateSessionHistory(frame);
2230 render_view_->history_controller()->UpdateForCommit(this, item, commit_type,
2231 navigation_state->was_within_same_page());
2233 InternalDocumentStateData* internal_data =
2234 InternalDocumentStateData::FromDocumentState(document_state);
2236 if (document_state->commit_load_time().is_null())
2237 document_state->set_commit_load_time(Time::Now());
2239 if (internal_data->must_reset_scroll_and_scale_state()) {
2240 render_view_->webview()->resetScrollAndScaleState();
2241 internal_data->set_must_reset_scroll_and_scale_state(false);
2243 internal_data->set_use_error_page(false);
2245 bool is_new_navigation = commit_type == blink::WebStandardCommit;
2246 if (is_new_navigation) {
2247 // We bump our Page ID to correspond with the new session history entry.
2248 render_view_->page_id_ = render_view_->next_page_id_++;
2250 // Don't update history_page_ids_ (etc) for kSwappedOutURL, since
2251 // we don't want to forget the entry that was there, and since we will
2252 // never come back to kSwappedOutURL. Note that we have to call
2253 // UpdateSessionHistory and update page_id_ even in this case, so that
2254 // the current entry gets a state update and so that we don't send a
2255 // state update to the wrong entry when we swap back in.
2256 if (GetLoadingUrl() != GURL(kSwappedOutURL)) {
2257 // Advance our offset in session history, applying the length limit.
2258 // There is now no forward history.
2259 render_view_->history_list_offset_++;
2260 if (render_view_->history_list_offset_ >= kMaxSessionHistoryEntries)
2261 render_view_->history_list_offset_ = kMaxSessionHistoryEntries - 1;
2262 render_view_->history_list_length_ =
2263 render_view_->history_list_offset_ + 1;
2264 render_view_->history_page_ids_.resize(
2265 render_view_->history_list_length_, -1);
2266 render_view_->history_page_ids_[render_view_->history_list_offset_] =
2267 render_view_->page_id_;
2269 } else {
2270 // Inspect the navigation_state on this frame to see if the navigation
2271 // corresponds to a session history navigation... Note: |frame| may or
2272 // may not be the toplevel frame, but for the case of capturing session
2273 // history, the first committed frame suffices. We keep track of whether
2274 // we've seen this commit before so that only capture session history once
2275 // per navigation.
2277 // Note that we need to check if the page ID changed. In the case of a
2278 // reload, the page ID doesn't change, and UpdateSessionHistory gets the
2279 // previous URL and the current page ID, which would be wrong.
2280 if (navigation_state->pending_page_id() != -1 &&
2281 navigation_state->pending_page_id() != render_view_->page_id_ &&
2282 !navigation_state->request_committed()) {
2283 // This is a successful session history navigation!
2284 render_view_->page_id_ = navigation_state->pending_page_id();
2286 render_view_->history_list_offset_ =
2287 navigation_state->pending_history_list_offset();
2289 // If the history list is valid, our list of page IDs should be correct.
2290 DCHECK(render_view_->history_list_length_ <= 0 ||
2291 render_view_->history_list_offset_ < 0 ||
2292 render_view_->history_list_offset_ >=
2293 render_view_->history_list_length_ ||
2294 render_view_->history_page_ids_[render_view_->history_list_offset_]
2295 == render_view_->page_id_);
2299 bool sent = Send(
2300 new FrameHostMsg_DidAssignPageId(routing_id_, render_view_->page_id_));
2301 CHECK(sent); // http://crbug.com/407376
2303 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers_,
2304 DidCommitProvisionalLoad(frame, is_new_navigation));
2305 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
2306 DidCommitProvisionalLoad(is_new_navigation));
2308 if (!frame->parent()) { // Only for top frames.
2309 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
2310 if (render_thread_impl) { // Can be NULL in tests.
2311 render_thread_impl->histogram_customizer()->
2312 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2313 RenderViewImpl::GetRenderViewCount());
2317 // Remember that we've already processed this request, so we don't update
2318 // the session history again. We do this regardless of whether this is
2319 // a session history navigation, because if we attempted a session history
2320 // navigation without valid HistoryItem state, WebCore will think it is a
2321 // new navigation.
2322 navigation_state->set_request_committed(true);
2324 SendDidCommitProvisionalLoad(frame);
2326 // Check whether we have new encoding name.
2327 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2330 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame* frame) {
2331 DCHECK(!frame_ || frame_ == frame);
2332 // TODO(nasko): Move implementation here. Needed state:
2333 // * enabled_bindings_
2334 // * dom_automation_controller_
2335 // * stats_collection_controller_
2337 render_view_->didClearWindowObject(frame);
2339 if (render_view_->GetEnabledBindings() & BINDINGS_POLICY_DOM_AUTOMATION)
2340 DomAutomationController::Install(this, frame);
2342 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidClearWindowObject());
2345 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame* frame) {
2346 DCHECK(!frame_ || frame_ == frame);
2348 // Notify the browser about non-blank documents loading in the top frame.
2349 GURL url = frame->document().url();
2350 if (url.is_valid() && url.spec() != url::kAboutBlankURL) {
2351 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2352 // frame->tree()->top().
2353 blink::WebFrame* main_frame = render_view_->webview()->mainFrame();
2354 if (frame == main_frame) {
2355 // For now, don't remember plugin zoom values. We don't want to mix them
2356 // with normal web content (i.e. a fixed layout plugin would usually want
2357 // them different).
2358 render_view_->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2359 render_view_->GetRoutingID(),
2360 main_frame->document().isPluginDocument()));
2364 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2365 DidCreateDocumentElement(frame));
2368 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame* frame,
2369 const blink::WebString& title,
2370 blink::WebTextDirection direction) {
2371 DCHECK(!frame_ || frame_ == frame);
2372 // Ignore all but top level navigations.
2373 if (!frame->parent()) {
2374 base::string16 title16 = title;
2375 base::debug::TraceLog::GetInstance()->UpdateProcessLabel(
2376 routing_id_, base::UTF16ToUTF8(title16));
2378 base::string16 shortened_title = title16.substr(0, kMaxTitleChars);
2379 Send(new FrameHostMsg_UpdateTitle(routing_id_,
2380 render_view_->page_id_,
2381 shortened_title, direction));
2384 // Also check whether we have new encoding name.
2385 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2388 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame* frame,
2389 blink::WebIconURL::Type icon_type) {
2390 DCHECK(!frame_ || frame_ == frame);
2391 // TODO(nasko): Investigate wheather implementation should move here.
2392 render_view_->didChangeIcon(frame, icon_type);
2395 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame* frame) {
2396 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2397 "id", routing_id_);
2398 DCHECK(!frame_ || frame_ == frame);
2399 WebDataSource* ds = frame->dataSource();
2400 DocumentState* document_state = DocumentState::FromDataSource(ds);
2401 document_state->set_finish_document_load_time(Time::Now());
2403 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_));
2405 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2406 DidFinishDocumentLoad(frame));
2407 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidFinishDocumentLoad());
2409 // Check whether we have new encoding name.
2410 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2413 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame* frame) {
2414 DCHECK(!frame_ || frame_ == frame);
2415 if (!frame->parent())
2416 Send(new FrameHostMsg_DocumentOnLoadCompleted(routing_id_));
2419 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame* frame,
2420 const blink::WebURLError& error) {
2421 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2422 "id", routing_id_);
2423 DCHECK(!frame_ || frame_ == frame);
2424 // TODO(nasko): Move implementation here. No state needed.
2425 WebDataSource* ds = frame->dataSource();
2426 DCHECK(ds);
2428 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2429 DidFailLoad(frame, error));
2431 const WebURLRequest& failed_request = ds->request();
2432 base::string16 error_description;
2433 GetContentClient()->renderer()->GetNavigationErrorStrings(
2434 render_view_.get(),
2435 frame,
2436 failed_request,
2437 error,
2438 NULL,
2439 &error_description);
2440 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_,
2441 failed_request.url(),
2442 error.reason,
2443 error_description));
2446 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame* frame) {
2447 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2448 "id", routing_id_);
2449 DCHECK(!frame_ || frame_ == frame);
2450 WebDataSource* ds = frame->dataSource();
2451 DocumentState* document_state = DocumentState::FromDataSource(ds);
2452 if (document_state->finish_load_time().is_null()) {
2453 if (!frame->parent()) {
2454 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2455 TRACE_EVENT_SCOPE_PROCESS);
2457 document_state->set_finish_load_time(Time::Now());
2460 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2461 DidFinishLoad(frame));
2462 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidFinishLoad());
2464 // Don't send this message while the frame is swapped out.
2465 if (is_swapped_out())
2466 return;
2468 Send(new FrameHostMsg_DidFinishLoad(routing_id_,
2469 ds->request().url()));
2472 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame* frame,
2473 const blink::WebHistoryItem& item,
2474 blink::WebHistoryCommitType commit_type) {
2475 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
2476 "id", routing_id_);
2477 DCHECK(!frame_ || frame_ == frame);
2478 // If this was a reference fragment navigation that we initiated, then we
2479 // could end up having a non-null pending navigation params. We just need to
2480 // update the ExtraData on the datasource so that others who read the
2481 // ExtraData will get the new NavigationState. Similarly, if we did not
2482 // initiate this navigation, then we need to take care to reset any pre-
2483 // existing navigation state to a content-initiated navigation state.
2484 // DidCreateDataSource conveniently takes care of this for us.
2485 didCreateDataSource(frame, frame->dataSource());
2487 DocumentState* document_state =
2488 DocumentState::FromDataSource(frame->dataSource());
2489 NavigationState* new_state = document_state->navigation_state();
2490 new_state->set_was_within_same_page(true);
2492 didCommitProvisionalLoad(frame, item, commit_type);
2495 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame* frame) {
2496 DCHECK(!frame_ || frame_ == frame);
2497 // TODO(nasko): Move implementation here. Needed methods:
2498 // * StartNavStateSyncTimerIfNecessary
2499 render_view_->didUpdateCurrentHistoryItem(frame);
2502 // TODO(zhenw): This will be removed once the blink side implementation is done.
2503 void RenderFrameImpl::addNavigationTransitionData(
2504 const blink::WebString& allowed_destination_host_pattern,
2505 const blink::WebString& selector,
2506 const blink::WebString& markup) {
2507 FrameHostMsg_AddNavigationTransitionData_Params params;
2508 params.render_frame_id = routing_id_;
2509 params.allowed_destination_host_pattern =
2510 allowed_destination_host_pattern.utf8();
2511 params.selector = selector.utf8();
2512 params.markup = markup.utf8();
2514 Send(new FrameHostMsg_AddNavigationTransitionData(params));
2517 void RenderFrameImpl::addNavigationTransitionData(
2518 const blink::WebString& allowed_destination_host_pattern,
2519 const blink::WebString& selector,
2520 const blink::WebString& markup,
2521 const blink::WebVector<blink::WebString>& web_names,
2522 const blink::WebVector<blink::WebRect>& web_rects) {
2523 FrameHostMsg_AddNavigationTransitionData_Params params;
2524 params.render_frame_id = routing_id_;
2525 params.allowed_destination_host_pattern =
2526 allowed_destination_host_pattern.utf8();
2527 params.selector = selector.utf8();
2528 params.markup = markup.utf8();
2529 for (size_t i = 0; i < web_names.size(); i++) {
2530 params.names.push_back(web_names[i].utf8());
2532 for (size_t i = 0; i < web_rects.size(); i++) {
2533 params.rects.push_back(gfx::Rect(web_rects[i]));
2536 Send(new FrameHostMsg_AddNavigationTransitionData(params));
2539 void RenderFrameImpl::didChangeThemeColor() {
2540 if (frame_->parent())
2541 return;
2543 Send(new FrameHostMsg_DidChangeThemeColor(
2544 routing_id_, frame_->document().themeColor()));
2547 void RenderFrameImpl::requestNotificationPermission(
2548 const blink::WebSecurityOrigin& origin,
2549 blink::WebNotificationPermissionCallback* callback) {
2550 if (!notification_permission_dispatcher_) {
2551 notification_permission_dispatcher_ =
2552 new NotificationPermissionDispatcher(this);
2555 notification_permission_dispatcher_->RequestPermission(origin, callback);
2558 blink::WebNotificationPresenter* RenderFrameImpl::notificationPresenter() {
2559 return notification_provider_;
2562 void RenderFrameImpl::didChangeSelection(bool is_empty_selection) {
2563 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_)
2564 return;
2566 if (is_empty_selection)
2567 selection_text_.clear();
2569 // UpdateTextInputType should be called before SyncSelectionIfRequired.
2570 // UpdateTextInputType may send TextInputTypeChanged to notify the focus
2571 // was changed, and SyncSelectionIfRequired may send SelectionChanged
2572 // to notify the selection was changed. Focus change should be notified
2573 // before selection change.
2574 GetRenderWidget()->UpdateTextInputType();
2575 SyncSelectionIfRequired();
2576 #if defined(OS_ANDROID)
2577 GetRenderWidget()->UpdateTextInputState(RenderWidget::NO_SHOW_IME,
2578 RenderWidget::FROM_NON_IME);
2579 #endif
2582 blink::WebColorChooser* RenderFrameImpl::createColorChooser(
2583 blink::WebColorChooserClient* client,
2584 const blink::WebColor& initial_color,
2585 const blink::WebVector<blink::WebColorSuggestion>& suggestions) {
2586 RendererWebColorChooserImpl* color_chooser =
2587 new RendererWebColorChooserImpl(this, client);
2588 std::vector<content::ColorSuggestion> color_suggestions;
2589 for (size_t i = 0; i < suggestions.size(); i++) {
2590 color_suggestions.push_back(content::ColorSuggestion(suggestions[i]));
2592 color_chooser->Open(static_cast<SkColor>(initial_color), color_suggestions);
2593 return color_chooser;
2596 void RenderFrameImpl::runModalAlertDialog(const blink::WebString& message) {
2597 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT,
2598 message,
2599 base::string16(),
2600 frame_->document().url(),
2601 NULL);
2604 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString& message) {
2605 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM,
2606 message,
2607 base::string16(),
2608 frame_->document().url(),
2609 NULL);
2612 bool RenderFrameImpl::runModalPromptDialog(
2613 const blink::WebString& message,
2614 const blink::WebString& default_value,
2615 blink::WebString* actual_value) {
2616 base::string16 result;
2617 bool ok = RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT,
2618 message,
2619 default_value,
2620 frame_->document().url(),
2621 &result);
2622 if (ok)
2623 actual_value->assign(result);
2624 return ok;
2627 bool RenderFrameImpl::runModalBeforeUnloadDialog(
2628 bool is_reload,
2629 const blink::WebString& message) {
2630 // If we are swapping out, we have already run the beforeunload handler.
2631 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
2632 // at all, to avoid running it twice.
2633 if (render_view()->is_swapped_out_)
2634 return true;
2636 // Don't allow further dialogs if we are waiting to swap out, since the
2637 // PageGroupLoadDeferrer in our stack prevents it.
2638 if (render_view()->suppress_dialogs_until_swap_out_)
2639 return false;
2641 bool success = false;
2642 // This is an ignored return value, but is included so we can accept the same
2643 // response as RunJavaScriptMessage.
2644 base::string16 ignored_result;
2645 render_view()->SendAndRunNestedMessageLoop(
2646 new FrameHostMsg_RunBeforeUnloadConfirm(
2647 routing_id_, frame_->document().url(), message, is_reload,
2648 &success, &ignored_result));
2649 return success;
2652 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData& data) {
2653 ContextMenuParams params = ContextMenuParamsBuilder::Build(data);
2654 params.source_type = GetRenderWidget()->context_menu_source_type();
2655 GetRenderWidget()->OnShowHostContextMenu(&params);
2656 if (GetRenderWidget()->has_host_context_menu_location()) {
2657 params.x = GetRenderWidget()->host_context_menu_location().x();
2658 params.y = GetRenderWidget()->host_context_menu_location().y();
2661 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
2662 // it. We replace it with an empty GURL so the appropriate items are disabled
2663 // in the context menu.
2664 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
2665 // data encoded images. We should have a way to save them.
2666 if (params.src_url.spec().size() > GetMaxURLChars())
2667 params.src_url = GURL();
2668 context_menu_node_ = data.node;
2670 #if defined(OS_ANDROID)
2671 gfx::Rect start_rect;
2672 gfx::Rect end_rect;
2673 GetRenderWidget()->GetSelectionBounds(&start_rect, &end_rect);
2674 params.selection_start = gfx::Point(start_rect.x(), start_rect.bottom());
2675 params.selection_end = gfx::Point(end_rect.right(), end_rect.bottom());
2676 #endif
2678 Send(new FrameHostMsg_ContextMenu(routing_id_, params));
2681 void RenderFrameImpl::clearContextMenu() {
2682 context_menu_node_.reset();
2685 void RenderFrameImpl::willSendRequest(
2686 blink::WebLocalFrame* frame,
2687 unsigned identifier,
2688 blink::WebURLRequest& request,
2689 const blink::WebURLResponse& redirect_response) {
2690 DCHECK(!frame_ || frame_ == frame);
2691 // The request my be empty during tests.
2692 if (request.url().isEmpty())
2693 return;
2695 // Set the first party for cookies url if it has not been set yet (new
2696 // requests). For redirects, it is updated by WebURLLoaderImpl.
2697 if (request.firstPartyForCookies().isEmpty()) {
2698 if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel) {
2699 request.setFirstPartyForCookies(request.url());
2700 } else {
2701 // TODO(nasko): When the top-level frame is remote, there is no document.
2702 // This is broken and should be fixed to propagate the first party.
2703 WebFrame* top = frame->top();
2704 if (top->isWebLocalFrame()) {
2705 request.setFirstPartyForCookies(
2706 frame->top()->document().firstPartyForCookies());
2711 WebFrame* top_frame = frame->top();
2712 // TODO(nasko): Hack around asking about top-frame data source. This means
2713 // for out-of-process iframes we are treating the current frame as the
2714 // top-level frame, which is wrong.
2715 if (!top_frame || top_frame->isWebRemoteFrame())
2716 top_frame = frame;
2717 WebDataSource* provisional_data_source = top_frame->provisionalDataSource();
2718 WebDataSource* top_data_source = top_frame->dataSource();
2719 WebDataSource* data_source =
2720 provisional_data_source ? provisional_data_source : top_data_source;
2722 ui::PageTransition transition_type = ui::PAGE_TRANSITION_LINK;
2723 DocumentState* document_state = DocumentState::FromDataSource(data_source);
2724 DCHECK(document_state);
2725 InternalDocumentStateData* internal_data =
2726 InternalDocumentStateData::FromDocumentState(document_state);
2727 NavigationState* navigation_state = document_state->navigation_state();
2728 transition_type = navigation_state->transition_type();
2730 GURL request_url(request.url());
2731 GURL new_url;
2732 if (GetContentClient()->renderer()->WillSendRequest(
2733 frame,
2734 transition_type,
2735 request_url,
2736 request.firstPartyForCookies(),
2737 &new_url)) {
2738 request.setURL(WebURL(new_url));
2741 if (internal_data->is_cache_policy_override_set())
2742 request.setCachePolicy(internal_data->cache_policy_override());
2744 // The request's extra data may indicate that we should set a custom user
2745 // agent. This needs to be done here, after WebKit is through with setting the
2746 // user agent on its own. Similarly, it may indicate that we should set an
2747 // X-Requested-With header. This must be done here to avoid breaking CORS
2748 // checks.
2749 // PlzNavigate: there may also be a stream url associated with the request.
2750 WebString custom_user_agent;
2751 WebString requested_with;
2752 scoped_ptr<StreamOverrideParameters> stream_override;
2753 if (request.extraData()) {
2754 RequestExtraData* old_extra_data =
2755 static_cast<RequestExtraData*>(request.extraData());
2757 custom_user_agent = old_extra_data->custom_user_agent();
2758 if (!custom_user_agent.isNull()) {
2759 if (custom_user_agent.isEmpty())
2760 request.clearHTTPHeaderField("User-Agent");
2761 else
2762 request.setHTTPHeaderField("User-Agent", custom_user_agent);
2765 requested_with = old_extra_data->requested_with();
2766 if (!requested_with.isNull()) {
2767 if (requested_with.isEmpty())
2768 request.clearHTTPHeaderField("X-Requested-With");
2769 else
2770 request.setHTTPHeaderField("X-Requested-With", requested_with);
2772 stream_override = old_extra_data->TakeStreamOverrideOwnership();
2775 // Add the default accept header for frame request if it has not been set
2776 // already.
2777 if ((request.frameType() == blink::WebURLRequest::FrameTypeTopLevel ||
2778 request.frameType() == blink::WebURLRequest::FrameTypeNested) &&
2779 request.httpHeaderField(WebString::fromUTF8(kAcceptHeader)).isEmpty()) {
2780 request.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader),
2781 WebString::fromUTF8(kDefaultAcceptHeader));
2784 // Add an empty HTTP origin header for non GET methods if none is currently
2785 // present.
2786 request.addHTTPOriginIfNeeded(WebString());
2788 // Attach |should_replace_current_entry| state to requests so that, should
2789 // this navigation later require a request transfer, all state is preserved
2790 // when it is re-created in the new process.
2791 bool should_replace_current_entry = false;
2792 if (navigation_state->is_content_initiated()) {
2793 should_replace_current_entry = data_source->replacesCurrentHistoryItem();
2794 } else {
2795 // If the navigation is browser-initiated, the NavigationState contains the
2796 // correct value instead of the WebDataSource.
2798 // TODO(davidben): Avoid this awkward duplication of state. See comment on
2799 // NavigationState::should_replace_current_entry().
2800 should_replace_current_entry =
2801 navigation_state->should_replace_current_entry();
2804 int provider_id = kInvalidServiceWorkerProviderId;
2805 if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel ||
2806 request.frameType() == blink::WebURLRequest::FrameTypeNested) {
2807 // |provisionalDataSource| may be null in some content::ResourceFetcher
2808 // use cases, we don't hook those requests.
2809 if (frame->provisionalDataSource()) {
2810 ServiceWorkerNetworkProvider* provider =
2811 ServiceWorkerNetworkProvider::FromDocumentState(
2812 DocumentState::FromDataSource(frame->provisionalDataSource()));
2813 provider_id = provider->provider_id();
2815 } else if (frame->dataSource()) {
2816 ServiceWorkerNetworkProvider* provider =
2817 ServiceWorkerNetworkProvider::FromDocumentState(
2818 DocumentState::FromDataSource(frame->dataSource()));
2819 provider_id = provider->provider_id();
2822 WebFrame* parent = frame->parent();
2823 int parent_routing_id = MSG_ROUTING_NONE;
2824 if (!parent) {
2825 parent_routing_id = -1;
2826 } else if (parent->isWebLocalFrame()) {
2827 parent_routing_id = FromWebFrame(parent)->GetRoutingID();
2828 } else {
2829 parent_routing_id = RenderFrameProxy::FromWebFrame(parent)->routing_id();
2832 RequestExtraData* extra_data = new RequestExtraData();
2833 extra_data->set_visibility_state(render_view_->visibilityState());
2834 extra_data->set_custom_user_agent(custom_user_agent);
2835 extra_data->set_requested_with(requested_with);
2836 extra_data->set_render_frame_id(routing_id_);
2837 extra_data->set_is_main_frame(frame == top_frame);
2838 extra_data->set_frame_origin(
2839 GURL(frame->document().securityOrigin().toString()));
2840 extra_data->set_parent_is_main_frame(frame->parent() == top_frame);
2841 extra_data->set_parent_render_frame_id(parent_routing_id);
2842 extra_data->set_allow_download(navigation_state->allow_download());
2843 extra_data->set_transition_type(transition_type);
2844 extra_data->set_should_replace_current_entry(should_replace_current_entry);
2845 extra_data->set_transferred_request_child_id(
2846 navigation_state->transferred_request_child_id());
2847 extra_data->set_transferred_request_request_id(
2848 navigation_state->transferred_request_request_id());
2849 extra_data->set_service_worker_provider_id(provider_id);
2850 extra_data->set_stream_override(stream_override.Pass());
2851 request.setExtraData(extra_data);
2853 DocumentState* top_document_state =
2854 DocumentState::FromDataSource(top_data_source);
2855 if (top_document_state) {
2856 // TODO(gavinp): separate out prefetching and prerender field trials
2857 // if the rel=prerender rel type is sticking around.
2858 if (request.requestContext() == WebURLRequest::RequestContextPrefetch)
2859 top_document_state->set_was_prefetcher(true);
2862 // This is an instance where we embed a copy of the routing id
2863 // into the data portion of the message. This can cause problems if we
2864 // don't register this id on the browser side, since the download manager
2865 // expects to find a RenderViewHost based off the id.
2866 request.setRequestorID(render_view_->GetRoutingID());
2867 request.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
2869 if (!navigation_state->extra_headers().empty()) {
2870 for (net::HttpUtil::HeadersIterator i(
2871 navigation_state->extra_headers().begin(),
2872 navigation_state->extra_headers().end(), "\n");
2873 i.GetNext(); ) {
2874 if (LowerCaseEqualsASCII(i.name(), "referer")) {
2875 WebString referrer = WebSecurityPolicy::generateReferrerHeader(
2876 blink::WebReferrerPolicyDefault,
2877 request.url(),
2878 WebString::fromUTF8(i.values()));
2879 request.setHTTPReferrer(referrer, blink::WebReferrerPolicyDefault);
2880 } else {
2881 request.setHTTPHeaderField(WebString::fromUTF8(i.name()),
2882 WebString::fromUTF8(i.values()));
2887 if (!render_view_->renderer_preferences_.enable_referrers)
2888 request.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault);
2891 void RenderFrameImpl::didReceiveResponse(
2892 blink::WebLocalFrame* frame,
2893 unsigned identifier,
2894 const blink::WebURLResponse& response) {
2895 DCHECK(!frame_ || frame_ == frame);
2896 // Only do this for responses that correspond to a provisional data source
2897 // of the top-most frame. If we have a provisional data source, then we
2898 // can't have any sub-resources yet, so we know that this response must
2899 // correspond to a frame load.
2900 if (!frame->provisionalDataSource() || frame->parent())
2901 return;
2903 // If we are in view source mode, then just let the user see the source of
2904 // the server's error page.
2905 if (frame->isViewSourceModeEnabled())
2906 return;
2908 DocumentState* document_state =
2909 DocumentState::FromDataSource(frame->provisionalDataSource());
2910 int http_status_code = response.httpStatusCode();
2912 // Record page load flags.
2913 WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response);
2914 if (extra_data) {
2915 document_state->set_was_fetched_via_spdy(
2916 extra_data->was_fetched_via_spdy());
2917 document_state->set_was_npn_negotiated(
2918 extra_data->was_npn_negotiated());
2919 document_state->set_npn_negotiated_protocol(
2920 extra_data->npn_negotiated_protocol());
2921 document_state->set_was_alternate_protocol_available(
2922 extra_data->was_alternate_protocol_available());
2923 document_state->set_connection_info(
2924 extra_data->connection_info());
2925 document_state->set_was_fetched_via_proxy(
2926 extra_data->was_fetched_via_proxy());
2928 InternalDocumentStateData* internal_data =
2929 InternalDocumentStateData::FromDocumentState(document_state);
2930 internal_data->set_http_status_code(http_status_code);
2931 // Whether or not the http status code actually corresponds to an error is
2932 // only checked when the page is done loading, if |use_error_page| is
2933 // still true.
2934 internal_data->set_use_error_page(true);
2937 void RenderFrameImpl::didFinishResourceLoad(blink::WebLocalFrame* frame,
2938 unsigned identifier) {
2939 DCHECK(!frame_ || frame_ == frame);
2940 InternalDocumentStateData* internal_data =
2941 InternalDocumentStateData::FromDataSource(frame->dataSource());
2942 if (!internal_data->use_error_page())
2943 return;
2945 // Do not show error page when DevTools is attached.
2946 if (render_view_->devtools_agent_->IsAttached())
2947 return;
2949 // Display error page, if appropriate.
2950 std::string error_domain = "http";
2951 int http_status_code = internal_data->http_status_code();
2952 if (GetContentClient()->renderer()->HasErrorPage(
2953 http_status_code, &error_domain)) {
2954 WebURLError error;
2955 error.unreachableURL = frame->document().url();
2956 error.domain = WebString::fromUTF8(error_domain);
2957 error.reason = http_status_code;
2958 LoadNavigationErrorPage(frame->dataSource()->request(), error, true);
2962 void RenderFrameImpl::didLoadResourceFromMemoryCache(
2963 blink::WebLocalFrame* frame,
2964 const blink::WebURLRequest& request,
2965 const blink::WebURLResponse& response) {
2966 DCHECK(!frame_ || frame_ == frame);
2967 // The recipients of this message have no use for data: URLs: they don't
2968 // affect the page's insecure content list and are not in the disk cache. To
2969 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
2970 // filter them out here.
2971 GURL url(request.url());
2972 if (url.SchemeIs(url::kDataScheme))
2973 return;
2975 // Let the browser know we loaded a resource from the memory cache. This
2976 // message is needed to display the correct SSL indicators.
2977 render_view_->Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(
2978 render_view_->GetRoutingID(),
2979 url,
2980 response.securityInfo(),
2981 request.httpMethod().utf8(),
2982 response.mimeType().utf8(),
2983 WebURLRequestToResourceType(request)));
2986 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame* frame) {
2987 DCHECK(!frame_ || frame_ == frame);
2988 render_view_->Send(new ViewHostMsg_DidDisplayInsecureContent(
2989 render_view_->GetRoutingID()));
2992 void RenderFrameImpl::didRunInsecureContent(
2993 blink::WebLocalFrame* frame,
2994 const blink::WebSecurityOrigin& origin,
2995 const blink::WebURL& target) {
2996 DCHECK(!frame_ || frame_ == frame);
2997 render_view_->Send(new ViewHostMsg_DidRunInsecureContent(
2998 render_view_->GetRoutingID(),
2999 origin.toString().utf8(),
3000 target));
3003 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame* frame) {
3004 DCHECK(!frame_ || frame_ == frame);
3005 #if defined(ENABLE_PLUGINS)
3006 if (frame != render_view_->webview()->mainFrame())
3007 return;
3008 PluginChannelHost::Broadcast(
3009 new PluginHostMsg_DidAbortLoading(render_view_->GetRoutingID()));
3010 #endif
3013 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame* frame,
3014 v8::Handle<v8::Context> context,
3015 int extension_group,
3016 int world_id) {
3017 DCHECK(!frame_ || frame_ == frame);
3018 GetContentClient()->renderer()->DidCreateScriptContext(
3019 frame, context, extension_group, world_id);
3022 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame* frame,
3023 v8::Handle<v8::Context> context,
3024 int world_id) {
3025 DCHECK(!frame_ || frame_ == frame);
3027 FOR_EACH_OBSERVER(RenderFrameObserver,
3028 observers_,
3029 WillReleaseScriptContext(context, world_id));
3032 void RenderFrameImpl::didFirstVisuallyNonEmptyLayout(
3033 blink::WebLocalFrame* frame) {
3034 DCHECK(!frame_ || frame_ == frame);
3035 if (frame->parent())
3036 return;
3038 InternalDocumentStateData* data =
3039 InternalDocumentStateData::FromDataSource(frame->dataSource());
3040 data->set_did_first_visually_non_empty_layout(true);
3042 #if defined(OS_ANDROID)
3043 GetRenderWidget()->DidChangeBodyBackgroundColor(
3044 render_view_->webwidget_->backgroundColor());
3045 #endif
3047 GetRenderWidget()->QueueMessage(
3048 new FrameHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_),
3049 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE);
3052 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame* frame) {
3053 DCHECK(!frame_ || frame_ == frame);
3054 // TODO(nasko): Move implementation here. Needed methods:
3055 // * StartNavStateSyncTimerIfNecessary
3056 render_view_->didChangeScrollOffset(frame);
3059 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame* frame) {
3060 DCHECK(!frame_ || frame_ == frame);
3061 if (!frame->parent()) {
3062 render_view_->Send(new ViewHostMsg_WillInsertBody(
3063 render_view_->GetRoutingID()));
3067 void RenderFrameImpl::reportFindInPageMatchCount(int request_id,
3068 int count,
3069 bool final_update) {
3070 int active_match_ordinal = -1; // -1 = don't update active match ordinal
3071 if (!count)
3072 active_match_ordinal = 0;
3074 render_view_->Send(new ViewHostMsg_Find_Reply(
3075 render_view_->GetRoutingID(), request_id, count,
3076 gfx::Rect(), active_match_ordinal, final_update));
3079 void RenderFrameImpl::reportFindInPageSelection(
3080 int request_id,
3081 int active_match_ordinal,
3082 const blink::WebRect& selection_rect) {
3083 render_view_->Send(new ViewHostMsg_Find_Reply(
3084 render_view_->GetRoutingID(), request_id, -1, selection_rect,
3085 active_match_ordinal, false));
3088 void RenderFrameImpl::requestStorageQuota(
3089 blink::WebLocalFrame* frame,
3090 blink::WebStorageQuotaType type,
3091 unsigned long long requested_size,
3092 blink::WebStorageQuotaCallbacks callbacks) {
3093 DCHECK(!frame_ || frame_ == frame);
3094 WebSecurityOrigin origin = frame->document().securityOrigin();
3095 if (origin.isUnique()) {
3096 // Unique origins cannot store persistent state.
3097 callbacks.didFail(blink::WebStorageQuotaErrorAbort);
3098 return;
3100 ChildThread::current()->quota_dispatcher()->RequestStorageQuota(
3101 render_view_->GetRoutingID(),
3102 GURL(origin.toString()),
3103 static_cast<storage::StorageType>(type),
3104 requested_size,
3105 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks));
3108 void RenderFrameImpl::willOpenSocketStream(
3109 blink::WebSocketStreamHandle* handle) {
3110 WebSocketStreamHandleImpl* impl =
3111 static_cast<WebSocketStreamHandleImpl*>(handle);
3112 impl->SetUserData(handle, new SocketStreamHandleData(routing_id_));
3115 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle* handle) {
3116 WebSocketBridge* impl = static_cast<WebSocketBridge*>(handle);
3117 impl->set_render_frame_id(routing_id_);
3120 blink::WebGeolocationClient* RenderFrameImpl::geolocationClient() {
3121 if (!geolocation_dispatcher_)
3122 geolocation_dispatcher_ = new GeolocationDispatcher(this);
3123 return geolocation_dispatcher_;
3126 blink::WebPushClient* RenderFrameImpl::pushClient() {
3127 if (!push_messaging_dispatcher_)
3128 push_messaging_dispatcher_ = new PushMessagingDispatcher(this);
3129 return push_messaging_dispatcher_;
3132 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3133 blink::WebLocalFrame* frame,
3134 blink::WebRTCPeerConnectionHandler* handler) {
3135 DCHECK(!frame_ || frame_ == frame);
3136 #if defined(ENABLE_WEBRTC)
3137 static_cast<RTCPeerConnectionHandler*>(handler)->associateWithFrame(frame);
3138 #endif
3141 blink::WebUserMediaClient* RenderFrameImpl::userMediaClient() {
3142 if (!web_user_media_client_)
3143 InitializeUserMediaClient();
3144 return web_user_media_client_;
3147 blink::WebMIDIClient* RenderFrameImpl::webMIDIClient() {
3148 if (!midi_dispatcher_)
3149 midi_dispatcher_ = new MidiDispatcher(this);
3150 return midi_dispatcher_;
3153 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3154 blink::WebLocalFrame* source_frame,
3155 blink::WebFrame* target_frame,
3156 blink::WebSecurityOrigin target_origin,
3157 blink::WebDOMMessageEvent event) {
3158 DCHECK(!frame_ || frame_ == target_frame);
3160 if (!render_view_->is_swapped_out_)
3161 return false;
3163 ViewMsg_PostMessage_Params params;
3164 params.is_data_raw_string = false;
3165 params.data = event.data().toString();
3166 params.source_origin = event.origin();
3167 if (!target_origin.isNull())
3168 params.target_origin = target_origin.toString();
3170 blink::WebMessagePortChannelArray channels = event.releaseChannels();
3171 if (!channels.isEmpty()) {
3172 std::vector<int> message_port_ids(channels.size());
3173 // Extract the port IDs from the channel array.
3174 for (size_t i = 0; i < channels.size(); ++i) {
3175 WebMessagePortChannelImpl* webchannel =
3176 static_cast<WebMessagePortChannelImpl*>(channels[i]);
3177 message_port_ids[i] = webchannel->message_port_id();
3178 webchannel->QueueMessages();
3179 DCHECK_NE(message_port_ids[i], MSG_ROUTING_NONE);
3181 params.message_port_ids = message_port_ids;
3184 // Include the routing ID for the source frame (if one exists), which the
3185 // browser process will translate into the routing ID for the equivalent
3186 // frame in the target process.
3187 params.source_routing_id = MSG_ROUTING_NONE;
3188 if (source_frame) {
3189 RenderViewImpl* source_view =
3190 RenderViewImpl::FromWebView(source_frame->view());
3191 if (source_view)
3192 params.source_routing_id = source_view->routing_id();
3195 Send(new ViewHostMsg_RouteMessageEvent(render_view_->routing_id_, params));
3196 return true;
3199 blink::WebString RenderFrameImpl::userAgentOverride(blink::WebLocalFrame* frame,
3200 const blink::WebURL& url) {
3201 DCHECK(!frame_ || frame_ == frame);
3202 std::string user_agent_override_for_url =
3203 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url));
3204 if (!user_agent_override_for_url.empty())
3205 return WebString::fromUTF8(user_agent_override_for_url);
3207 if (!render_view_->webview() || !render_view_->webview()->mainFrame() ||
3208 render_view_->renderer_preferences_.user_agent_override.empty()) {
3209 return blink::WebString();
3212 // If we're in the middle of committing a load, the data source we need
3213 // will still be provisional.
3214 WebFrame* main_frame = render_view_->webview()->mainFrame();
3215 WebDataSource* data_source = NULL;
3216 if (main_frame->provisionalDataSource())
3217 data_source = main_frame->provisionalDataSource();
3218 else
3219 data_source = main_frame->dataSource();
3221 InternalDocumentStateData* internal_data = data_source ?
3222 InternalDocumentStateData::FromDataSource(data_source) : NULL;
3223 if (internal_data && internal_data->is_overriding_user_agent())
3224 return WebString::fromUTF8(
3225 render_view_->renderer_preferences_.user_agent_override);
3226 return blink::WebString();
3229 blink::WebString RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame* frame) {
3230 DCHECK(!frame_ || frame_ == frame);
3231 if (render_view_->renderer_preferences_.enable_do_not_track)
3232 return WebString::fromUTF8("1");
3233 return WebString();
3236 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame* frame,
3237 bool default_value) {
3238 DCHECK(!frame_ || frame_ == frame);
3239 if (!default_value)
3240 return false;
3242 bool blocked = true;
3243 render_view_->Send(new ViewHostMsg_Are3DAPIsBlocked(
3244 render_view_->GetRoutingID(),
3245 GURL(frame->top()->document().securityOrigin().toString()),
3246 THREE_D_API_TYPE_WEBGL,
3247 &blocked));
3248 return !blocked;
3251 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame* frame,
3252 int arb_robustness_status_code) {
3253 DCHECK(!frame_ || frame_ == frame);
3254 render_view_->Send(new ViewHostMsg_DidLose3DContext(
3255 GURL(frame->top()->document().securityOrigin().toString()),
3256 THREE_D_API_TYPE_WEBGL,
3257 arb_robustness_status_code));
3260 blink::WebScreenOrientationClient*
3261 RenderFrameImpl::webScreenOrientationClient() {
3262 if (!screen_orientation_dispatcher_)
3263 screen_orientation_dispatcher_ = new ScreenOrientationDispatcher(this);
3264 return screen_orientation_dispatcher_;
3267 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource& data_source) {
3268 ServiceWorkerNetworkProvider* provider =
3269 ServiceWorkerNetworkProvider::FromDocumentState(
3270 DocumentState::FromDataSource(&data_source));
3271 return provider->context()->controller_handle_id() !=
3272 kInvalidServiceWorkerHandleId;
3275 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject& obj,
3276 blink::WebAXEvent event) {
3277 HandleWebAccessibilityEvent(obj, event);
3280 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame* frame)
3282 DCHECK(!frame_ || frame_ == frame);
3284 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeManifest());
3287 void RenderFrameImpl::DidPlay(blink::WebMediaPlayer* player) {
3288 Send(new FrameHostMsg_MediaPlayingNotification(
3289 routing_id_, reinterpret_cast<int64>(player), player->hasVideo(),
3290 player->hasAudio(), player->isRemote()));
3293 void RenderFrameImpl::DidPause(blink::WebMediaPlayer* player) {
3294 Send(new FrameHostMsg_MediaPausedNotification(
3295 routing_id_, reinterpret_cast<int64>(player)));
3298 void RenderFrameImpl::PlayerGone(blink::WebMediaPlayer* player) {
3299 DidPause(player);
3302 void RenderFrameImpl::AddObserver(RenderFrameObserver* observer) {
3303 observers_.AddObserver(observer);
3306 void RenderFrameImpl::RemoveObserver(RenderFrameObserver* observer) {
3307 observer->RenderFrameGone();
3308 observers_.RemoveObserver(observer);
3311 void RenderFrameImpl::OnStop() {
3312 DCHECK(frame_);
3313 frame_->stopLoading();
3314 if (!frame_->parent())
3315 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers_, OnStop());
3317 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, OnStop());
3320 void RenderFrameImpl::WasHidden() {
3321 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WasHidden());
3324 void RenderFrameImpl::WasShown() {
3325 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WasShown());
3328 bool RenderFrameImpl::IsHidden() {
3329 return GetRenderWidget()->is_hidden();
3332 // Tell the embedding application that the URL of the active page has changed.
3333 void RenderFrameImpl::SendDidCommitProvisionalLoad(blink::WebFrame* frame) {
3334 DCHECK(!frame_ || frame_ == frame);
3335 WebDataSource* ds = frame->dataSource();
3336 DCHECK(ds);
3338 const WebURLRequest& request = ds->request();
3339 const WebURLResponse& response = ds->response();
3341 DocumentState* document_state = DocumentState::FromDataSource(ds);
3342 NavigationState* navigation_state = document_state->navigation_state();
3343 InternalDocumentStateData* internal_data =
3344 InternalDocumentStateData::FromDocumentState(document_state);
3346 FrameHostMsg_DidCommitProvisionalLoad_Params params;
3347 params.http_status_code = response.httpStatusCode();
3348 params.url_is_unreachable = ds->hasUnreachableURL();
3349 params.is_post = false;
3350 params.post_id = -1;
3351 params.page_id = render_view_->page_id_;
3352 // We need to track the RenderViewHost routing_id because of downstream
3353 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3354 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3355 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3356 // based on the ID stored in the resource requests. Once those dependencies
3357 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3358 // client to be based on the routing_id of the RenderFrameHost.
3359 params.render_view_routing_id = render_view_->routing_id();
3360 params.socket_address.set_host(response.remoteIPAddress().utf8());
3361 params.socket_address.set_port(response.remotePort());
3362 WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response);
3363 if (extra_data)
3364 params.was_fetched_via_proxy = extra_data->was_fetched_via_proxy();
3365 params.was_within_same_page = navigation_state->was_within_same_page();
3366 params.security_info = response.securityInfo();
3368 // Set the URL to be displayed in the browser UI to the user.
3369 params.url = GetLoadingUrl();
3370 DCHECK(!is_swapped_out_ || params.url == GURL(kSwappedOutURL));
3372 if (frame->document().baseURL() != params.url)
3373 params.base_url = frame->document().baseURL();
3375 GetRedirectChain(ds, &params.redirects);
3376 params.should_update_history = !ds->hasUnreachableURL() &&
3377 !response.isMultipartPayload() && (response.httpStatusCode() != 404);
3379 params.searchable_form_url = internal_data->searchable_form_url();
3380 params.searchable_form_encoding = internal_data->searchable_form_encoding();
3382 params.gesture = render_view_->navigation_gesture_;
3383 render_view_->navigation_gesture_ = NavigationGestureUnknown;
3385 // Make navigation state a part of the DidCommitProvisionalLoad message so
3386 // that commited entry has it at all times.
3387 HistoryEntry* entry = render_view_->history_controller()->GetCurrentEntry();
3388 if (entry)
3389 params.page_state = HistoryEntryToPageState(entry);
3390 else
3391 params.page_state = PageState::CreateFromURL(request.url());
3393 if (!frame->parent()) {
3394 // Top-level navigation.
3396 // Reset the zoom limits in case a plugin had changed them previously. This
3397 // will also call us back which will cause us to send a message to
3398 // update WebContentsImpl.
3399 render_view_->webview()->zoomLimitsChanged(
3400 ZoomFactorToZoomLevel(kMinimumZoomFactor),
3401 ZoomFactorToZoomLevel(kMaximumZoomFactor));
3403 // Set zoom level, but don't do it for full-page plugin since they don't use
3404 // the same zoom settings.
3405 HostZoomLevels::iterator host_zoom =
3406 render_view_->host_zoom_levels_.find(GURL(request.url()));
3407 if (render_view_->webview()->mainFrame()->document().isPluginDocument()) {
3408 // Reset the zoom levels for plugins.
3409 render_view_->webview()->setZoomLevel(0);
3410 } else {
3411 if (host_zoom != render_view_->host_zoom_levels_.end()) {
3412 render_view_->webview()->setZoomLevel(host_zoom->second);
3413 } else {
3414 // If the url was not found, we need to reset in case we are re-using
3415 // an existing RenderViewImpl, e.g. to show a network error page.
3416 render_view_->webview()->setZoomLevel(0);
3420 if (host_zoom != render_view_->host_zoom_levels_.end()) {
3421 // This zoom level was merely recorded transiently for this load. We can
3422 // erase it now. If at some point we reload this page, the browser will
3423 // send us a new, up-to-date zoom level.
3424 render_view_->host_zoom_levels_.erase(host_zoom);
3427 // Update contents MIME type for main frame.
3428 params.contents_mime_type = ds->response().mimeType().utf8();
3430 params.transition = navigation_state->transition_type();
3431 if (!ui::PageTransitionIsMainFrame(params.transition)) {
3432 // If the main frame does a load, it should not be reported as a subframe
3433 // navigation. This can occur in the following case:
3434 // 1. You're on a site with frames.
3435 // 2. You do a subframe navigation. This is stored with transition type
3436 // MANUAL_SUBFRAME.
3437 // 3. You navigate to some non-frame site, say, google.com.
3438 // 4. You navigate back to the page from step 2. Since it was initially
3439 // MANUAL_SUBFRAME, it will be that same transition type here.
3440 // We don't want that, because any navigation that changes the toplevel
3441 // frame should be tracked as a toplevel navigation (this allows us to
3442 // update the URL bar, etc).
3443 params.transition = ui::PAGE_TRANSITION_LINK;
3446 // If the page contained a client redirect (meta refresh, document.loc...),
3447 // set the referrer and transition appropriately.
3448 if (ds->isClientRedirect()) {
3449 params.referrer =
3450 Referrer(params.redirects[0], ds->request().referrerPolicy());
3451 params.transition = ui::PageTransitionFromInt(
3452 params.transition | ui::PAGE_TRANSITION_CLIENT_REDIRECT);
3453 } else {
3454 params.referrer = RenderViewImpl::GetReferrerFromRequest(
3455 frame, ds->request());
3458 base::string16 method = request.httpMethod();
3459 if (EqualsASCII(method, "POST")) {
3460 params.is_post = true;
3461 params.post_id = ExtractPostId(entry->root());
3464 // Send the user agent override back.
3465 params.is_overriding_user_agent = internal_data->is_overriding_user_agent();
3467 // Track the URL of the original request. We use the first entry of the
3468 // redirect chain if it exists because the chain may have started in another
3469 // process.
3470 params.original_request_url = GetOriginalRequestURL(ds);
3472 params.history_list_was_cleared =
3473 navigation_state->history_list_was_cleared();
3475 // Save some histogram data so we can compute the average memory used per
3476 // page load of the glyphs.
3477 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
3478 blink::WebGlyphCache::pageCount());
3480 // This message needs to be sent before any of allowScripts(),
3481 // allowImages(), allowPlugins() is called for the new page, so that when
3482 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
3483 // after the FrameHostMsg_DidCommitProvisionalLoad message.
3484 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params));
3485 } else {
3486 // Subframe navigation: the type depends on whether this navigation
3487 // generated a new session history entry. When they do generate a session
3488 // history entry, it means the user initiated the navigation and we should
3489 // mark it as such. This test checks if this is the first time
3490 // SendDidCommitProvisionalLoad has been called since WillNavigateToURL was
3491 // called to initiate the load.
3492 if (render_view_->page_id_ > render_view_->last_page_id_sent_to_browser_)
3493 params.transition = ui::PAGE_TRANSITION_MANUAL_SUBFRAME;
3494 else
3495 params.transition = ui::PAGE_TRANSITION_AUTO_SUBFRAME;
3497 DCHECK(!navigation_state->history_list_was_cleared());
3498 params.history_list_was_cleared = false;
3500 // Don't send this message while the subframe is swapped out.
3501 if (!is_swapped_out())
3502 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params));
3505 render_view_->last_page_id_sent_to_browser_ =
3506 std::max(render_view_->last_page_id_sent_to_browser_,
3507 render_view_->page_id_);
3509 // If we end up reusing this WebRequest (for example, due to a #ref click),
3510 // we don't want the transition type to persist. Just clear it.
3511 navigation_state->set_transition_type(ui::PAGE_TRANSITION_LINK);
3514 WebElement RenderFrameImpl::GetFocusedElement() {
3515 WebDocument doc = frame_->document();
3516 if (!doc.isNull())
3517 return doc.focusedElement();
3519 return WebElement();
3522 void RenderFrameImpl::didStartLoading(bool to_different_document) {
3523 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
3524 "id", routing_id_);
3525 render_view_->FrameDidStartLoading(frame_);
3526 Send(new FrameHostMsg_DidStartLoading(routing_id_, to_different_document));
3529 void RenderFrameImpl::didStopLoading() {
3530 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
3531 "id", routing_id_);
3532 render_view_->FrameDidStopLoading(frame_);
3533 Send(new FrameHostMsg_DidStopLoading(routing_id_));
3536 void RenderFrameImpl::didChangeLoadProgress(double load_progress) {
3537 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_, load_progress));
3540 void RenderFrameImpl::HandleWebAccessibilityEvent(
3541 const blink::WebAXObject& obj, blink::WebAXEvent event) {
3542 if (renderer_accessibility_)
3543 renderer_accessibility_->HandleWebAccessibilityEvent(obj, event);
3546 void RenderFrameImpl::FocusedNodeChanged(const WebNode& node) {
3547 if (renderer_accessibility_)
3548 renderer_accessibility_->FocusedNodeChanged(node);
3551 // PlzNavigate
3552 void RenderFrameImpl::OnRequestNavigation(
3553 const CommonNavigationParams& common_params,
3554 const RequestNavigationParams& request_params) {
3555 CHECK(CommandLine::ForCurrentProcess()->HasSwitch(
3556 switches::kEnableBrowserSideNavigation));
3558 // TODO(clamy): Execute the beforeunload event.
3560 WebURLRequest request =
3561 CreateURLRequestForNavigation(common_params,
3562 request_params,
3563 scoped_ptr<StreamOverrideParameters>(),
3564 frame_->isViewSourceModeEnabled());
3566 // Note: At this stage, the goal is to apply all the modifications the
3567 // renderer wants to make to the request, and then send it to the browser, so
3568 // that the actual network request can be started. Ideally, all such
3569 // modifications should take place in willSendRequest, and in the
3570 // implementation of willSendRequest for the various InspectorAgents
3571 // (devtools).
3573 // TODO(clamy): Apply devtools override.
3574 // TODO(clamy): Make sure that navigation requests are not modified somewhere
3575 // else in blink.
3576 willSendRequest(frame_, 0, request, blink::WebURLResponse());
3578 // TODO(clamy): Same-document navigations should not be sent back to the
3579 // browser.
3580 Send(new FrameHostMsg_BeginNavigation(routing_id_,
3581 MakeBeginNavigationParams(request),
3582 MakeCommonNavigationParams(request)));
3585 // PlzNavigate
3586 void RenderFrameImpl::OnCommitNavigation(
3587 const ResourceResponseHead& response,
3588 const GURL& stream_url,
3589 const CommonNavigationParams& common_params,
3590 const CommitNavigationParams& commit_params) {
3591 CHECK(CommandLine::ForCurrentProcess()->HasSwitch(
3592 switches::kEnableBrowserSideNavigation));
3593 bool is_reload = false;
3594 WebURLRequest::CachePolicy cache_policy =
3595 WebURLRequest::UseProtocolCachePolicy;
3596 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
3597 common_params.url, common_params.navigation_type,
3598 commit_params.page_state, false, -1, -1, &is_reload, &cache_policy)) {
3599 return;
3602 GetContentClient()->SetActiveURL(common_params.url);
3604 // Create a WebURLRequest that blink can use to get access to the body of the
3605 // response through a stream in the browser. Blink will then commit the
3606 // navigation.
3607 // TODO(clamy): Have the navigation commit directly, without going through
3608 // loading a WebURLRequest.
3609 scoped_ptr<StreamOverrideParameters> stream_override(
3610 new StreamOverrideParameters());
3611 stream_override->stream_url = stream_url;
3612 stream_override->response = response;
3613 WebURLRequest request =
3614 CreateURLRequestForNavigation(common_params,
3615 RequestNavigationParams(),
3616 stream_override.Pass(),
3617 frame_->isViewSourceModeEnabled());
3619 // Record this before starting the load. A lower bound of this time is needed
3620 // to sanitize the navigationStart override set below.
3621 base::TimeTicks renderer_navigation_start = base::TimeTicks::Now();
3622 frame_->loadRequest(request);
3623 UpdateFrameNavigationTiming(
3624 frame_, commit_params.browser_navigation_start,
3625 renderer_navigation_start);
3628 WebNavigationPolicy RenderFrameImpl::DecidePolicyForNavigation(
3629 RenderFrame* render_frame,
3630 const NavigationPolicyInfo& info) {
3631 #ifdef OS_ANDROID
3632 // The handlenavigation API is deprecated and will be removed once
3633 // crbug.com/325351 is resolved.
3634 if (info.urlRequest.url() != GURL(kSwappedOutURL) &&
3635 GetContentClient()->renderer()->HandleNavigation(
3636 render_frame,
3637 static_cast<DocumentState*>(info.extraData),
3638 render_view_->opener_id_,
3639 info.frame,
3640 info.urlRequest,
3641 info.navigationType,
3642 info.defaultPolicy,
3643 info.isRedirect)) {
3644 return blink::WebNavigationPolicyIgnore;
3646 #endif
3648 Referrer referrer(RenderViewImpl::GetReferrerFromRequest(info.frame,
3649 info.urlRequest));
3650 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
3652 bool is_subframe = !!info.frame->parent();
3654 if (command_line.HasSwitch(switches::kSitePerProcess) && is_subframe) {
3655 // There's no reason to ignore navigations on subframes, since the swap out
3656 // logic no longer applies.
3657 } else {
3658 if (is_swapped_out_ || render_view_->is_swapped_out()) {
3659 if (info.urlRequest.url() != GURL(kSwappedOutURL)) {
3660 // Targeted links may try to navigate a swapped out frame. Allow the
3661 // browser process to navigate the tab instead. Note that it is also
3662 // possible for non-targeted navigations (from this view) to arrive
3663 // here just after we are swapped out. It's ok to send them to the
3664 // browser, as long as they're for the top level frame.
3665 // TODO(creis): Ensure this supports targeted form submissions when
3666 // fixing http://crbug.com/101395.
3667 if (info.frame->parent() == NULL) {
3668 OpenURL(info.frame, info.urlRequest.url(), referrer,
3669 info.defaultPolicy);
3670 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
3673 // We should otherwise ignore in-process iframe navigations, if they
3674 // arrive just after we are swapped out.
3675 return blink::WebNavigationPolicyIgnore;
3678 // Allow kSwappedOutURL to complete.
3679 return info.defaultPolicy;
3683 // Webkit is asking whether to navigate to a new URL.
3684 // This is fine normally, except if we're showing UI from one security
3685 // context and they're trying to navigate to a different context.
3686 const GURL& url = info.urlRequest.url();
3688 // A content initiated navigation may have originated from a link-click,
3689 // script, drag-n-drop operation, etc.
3690 bool is_content_initiated = static_cast<DocumentState*>(info.extraData)->
3691 navigation_state()->is_content_initiated();
3693 // Experimental:
3694 // If --enable-strict-site-isolation is enabled, send all top-level
3695 // navigations to the browser to let it swap processes when crossing site
3696 // boundaries. This is currently expected to break some script calls and
3697 // navigations, such as form submissions.
3698 bool force_swap_due_to_flag =
3699 command_line.HasSwitch(switches::kEnableStrictSiteIsolation);
3700 if (force_swap_due_to_flag &&
3701 !info.frame->parent() && (is_content_initiated || info.isRedirect)) {
3702 WebString origin_str = info.frame->document().securityOrigin().toString();
3703 GURL frame_url(origin_str.utf8().data());
3704 // TODO(cevans): revisit whether this site check is still necessary once
3705 // crbug.com/101395 is fixed.
3706 bool same_domain_or_host =
3707 net::registry_controlled_domains::SameDomainOrHost(
3708 frame_url,
3709 url,
3710 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
3711 // Only keep same-site (domain + scheme) and data URLs in the same process.
3712 bool is_same_site =
3713 (same_domain_or_host && frame_url.scheme() == url.scheme()) ||
3714 url.SchemeIs(url::kDataScheme);
3715 if (!is_same_site) {
3716 OpenURL(info.frame, url, referrer, info.defaultPolicy);
3717 return blink::WebNavigationPolicyIgnore;
3721 // If the browser is interested, then give it a chance to look at the request.
3722 if (is_content_initiated) {
3723 bool is_form_post =
3724 ((info.navigationType == blink::WebNavigationTypeFormSubmitted) ||
3725 (info.navigationType == blink::WebNavigationTypeFormResubmitted)) &&
3726 EqualsASCII(info.urlRequest.httpMethod(), "POST");
3727 bool browser_handles_request =
3728 render_view_->renderer_preferences_
3729 .browser_handles_non_local_top_level_requests
3730 && IsNonLocalTopLevelNavigation(url, info.frame, info.navigationType,
3731 is_form_post);
3732 if (!browser_handles_request) {
3733 browser_handles_request = IsTopLevelNavigation(info.frame) &&
3734 render_view_->renderer_preferences_
3735 .browser_handles_all_top_level_requests;
3738 if (browser_handles_request) {
3739 OpenURL(info.frame, url, referrer, info.defaultPolicy);
3740 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
3744 // Use the frame's original request's URL rather than the document's URL for
3745 // subsequent checks. For a popup, the document's URL may become the opener
3746 // window's URL if the opener has called document.write().
3747 // See http://crbug.com/93517.
3748 GURL old_url(info.frame->dataSource()->request().url());
3750 // Detect when we're crossing a permission-based boundary (e.g. into or out of
3751 // an extension or app origin, leaving a WebUI page, etc). We only care about
3752 // top-level navigations (not iframes). But we sometimes navigate to
3753 // about:blank to clear a tab, and we want to still allow that.
3755 // Note: this is known to break POST submissions when crossing process
3756 // boundaries until http://crbug.com/101395 is fixed. This is better for
3757 // security than loading a WebUI, extension or app page in the wrong process.
3758 // POST requests don't work because this mechanism does not preserve form
3759 // POST data. We will need to send the request's httpBody data up to the
3760 // browser process, and issue a special POST navigation in WebKit (via
3761 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
3762 // for examples of how to send the httpBody data.
3763 if (!info.frame->parent() && is_content_initiated &&
3764 !url.SchemeIs(url::kAboutScheme)) {
3765 bool send_referrer = false;
3767 // All navigations to or from WebUI URLs or within WebUI-enabled
3768 // RenderProcesses must be handled by the browser process so that the
3769 // correct bindings and data sources can be registered.
3770 // Similarly, navigations to view-source URLs or within ViewSource mode
3771 // must be handled by the browser process (except for reloads - those are
3772 // safe to leave within the renderer).
3773 // Lastly, access to file:// URLs from non-file:// URL pages must be
3774 // handled by the browser so that ordinary renderer processes don't get
3775 // blessed with file permissions.
3776 int cumulative_bindings = RenderProcess::current()->GetEnabledBindings();
3777 bool is_initial_navigation = render_view_->page_id_ == -1;
3778 bool should_fork = HasWebUIScheme(url) || HasWebUIScheme(old_url) ||
3779 (cumulative_bindings & BINDINGS_POLICY_WEB_UI) ||
3780 url.SchemeIs(kViewSourceScheme) ||
3781 (info.frame->isViewSourceModeEnabled() &&
3782 info.navigationType != blink::WebNavigationTypeReload);
3784 if (!should_fork && url.SchemeIs(url::kFileScheme)) {
3785 // Fork non-file to file opens. Check the opener URL if this is the
3786 // initial navigation in a newly opened window.
3787 GURL source_url(old_url);
3788 if (is_initial_navigation && source_url.is_empty() &&
3789 info.frame->opener())
3790 source_url = info.frame->opener()->top()->document().url();
3791 DCHECK(!source_url.is_empty());
3792 should_fork = !source_url.SchemeIs(url::kFileScheme);
3795 if (!should_fork) {
3796 // Give the embedder a chance.
3797 should_fork = GetContentClient()->renderer()->ShouldFork(
3798 info.frame, url, info.urlRequest.httpMethod().utf8(),
3799 is_initial_navigation, info.isRedirect, &send_referrer);
3802 if (should_fork) {
3803 OpenURL(info.frame, url, send_referrer ? referrer : Referrer(),
3804 info.defaultPolicy);
3805 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
3809 // Detect when a page is "forking" a new tab that can be safely rendered in
3810 // its own process. This is done by sites like Gmail that try to open links
3811 // in new windows without script connections back to the original page. We
3812 // treat such cases as browser navigations (in which we will create a new
3813 // renderer for a cross-site navigation), rather than WebKit navigations.
3815 // We use the following heuristic to decide whether to fork a new page in its
3816 // own process:
3817 // The parent page must open a new tab to about:blank, set the new tab's
3818 // window.opener to null, and then redirect the tab to a cross-site URL using
3819 // JavaScript.
3821 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
3822 // (see below).
3823 bool is_fork =
3824 // Must start from a tab showing about:blank, which is later redirected.
3825 old_url == GURL(url::kAboutBlankURL) &&
3826 // Must be the first real navigation of the tab.
3827 render_view_->historyBackListCount() < 1 &&
3828 render_view_->historyForwardListCount() < 1 &&
3829 // The parent page must have set the child's window.opener to null before
3830 // redirecting to the desired URL.
3831 info.frame->opener() == NULL &&
3832 // Must be a top-level frame.
3833 info.frame->parent() == NULL &&
3834 // Must not have issued the request from this page.
3835 is_content_initiated &&
3836 // Must be targeted at the current tab.
3837 info.defaultPolicy == blink::WebNavigationPolicyCurrentTab &&
3838 // Must be a JavaScript navigation, which appears as "other".
3839 info.navigationType == blink::WebNavigationTypeOther;
3841 if (is_fork) {
3842 // Open the URL via the browser, not via WebKit.
3843 OpenURL(info.frame, url, Referrer(), info.defaultPolicy);
3844 return blink::WebNavigationPolicyIgnore;
3847 return info.defaultPolicy;
3850 void RenderFrameImpl::OpenURL(WebFrame* frame,
3851 const GURL& url,
3852 const Referrer& referrer,
3853 WebNavigationPolicy policy) {
3854 DCHECK_EQ(frame_, frame);
3856 FrameHostMsg_OpenURL_Params params;
3857 params.url = url;
3858 params.referrer = referrer;
3859 params.disposition = RenderViewImpl::NavigationPolicyToDisposition(policy);
3860 WebDataSource* ds = frame->provisionalDataSource();
3861 if (ds) {
3862 DocumentState* document_state = DocumentState::FromDataSource(ds);
3863 NavigationState* navigation_state = document_state->navigation_state();
3864 if (navigation_state->is_content_initiated()) {
3865 params.should_replace_current_entry = ds->replacesCurrentHistoryItem();
3866 } else {
3867 // This is necessary to preserve the should_replace_current_entry value on
3868 // cross-process redirects, in the event it was set by a previous process.
3870 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3871 // NavigationState::should_replace_current_entry().
3872 params.should_replace_current_entry =
3873 navigation_state->should_replace_current_entry();
3875 } else {
3876 params.should_replace_current_entry = false;
3878 params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
3879 if (GetContentClient()->renderer()->AllowPopup())
3880 params.user_gesture = true;
3882 if (policy == blink::WebNavigationPolicyNewBackgroundTab ||
3883 policy == blink::WebNavigationPolicyNewForegroundTab ||
3884 policy == blink::WebNavigationPolicyNewWindow ||
3885 policy == blink::WebNavigationPolicyNewPopup) {
3886 WebUserGestureIndicator::consumeUserGesture();
3889 Send(new FrameHostMsg_OpenURL(routing_id_, params));
3892 void RenderFrameImpl::UpdateEncoding(WebFrame* frame,
3893 const std::string& encoding_name) {
3894 // Only update main frame's encoding_name.
3895 if (!frame->parent())
3896 Send(new FrameHostMsg_UpdateEncoding(routing_id_, encoding_name));
3899 void RenderFrameImpl::SyncSelectionIfRequired() {
3900 base::string16 text;
3901 size_t offset;
3902 gfx::Range range;
3903 #if defined(ENABLE_PLUGINS)
3904 if (render_view_->focused_pepper_plugin_) {
3905 render_view_->focused_pepper_plugin_->GetSurroundingText(&text, &range);
3906 offset = 0; // Pepper API does not support offset reporting.
3907 // TODO(kinaba): cut as needed.
3908 } else
3909 #endif
3911 size_t location, length;
3912 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
3913 &location, &length)) {
3914 return;
3917 range = gfx::Range(location, location + length);
3919 if (GetRenderWidget()->webwidget()->textInputInfo().type !=
3920 blink::WebTextInputTypeNone) {
3921 // If current focused element is editable, we will send 100 more chars
3922 // before and after selection. It is for input method surrounding text
3923 // feature.
3924 if (location > kExtraCharsBeforeAndAfterSelection)
3925 offset = location - kExtraCharsBeforeAndAfterSelection;
3926 else
3927 offset = 0;
3928 length = location + length - offset + kExtraCharsBeforeAndAfterSelection;
3929 WebRange webrange = WebRange::fromDocumentRange(frame_, offset, length);
3930 if (!webrange.isNull())
3931 text = WebRange::fromDocumentRange(
3932 frame_, offset, length).toPlainText();
3933 } else {
3934 offset = location;
3935 text = frame_->selectionAsText();
3936 // http://crbug.com/101435
3937 // In some case, frame->selectionAsText() returned text's length is not
3938 // equal to the length returned from webwidget()->caretOrSelectionRange().
3939 // So we have to set the range according to text.length().
3940 range.set_end(range.start() + text.length());
3944 // Sometimes we get repeated didChangeSelection calls from webkit when
3945 // the selection hasn't actually changed. We don't want to report these
3946 // because it will cause us to continually claim the X clipboard.
3947 if (selection_text_offset_ != offset ||
3948 selection_range_ != range ||
3949 selection_text_ != text) {
3950 selection_text_ = text;
3951 selection_text_offset_ = offset;
3952 selection_range_ = range;
3953 SetSelectedText(text, offset, range);
3955 GetRenderWidget()->UpdateSelectionBounds();
3958 void RenderFrameImpl::InitializeUserMediaClient() {
3959 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
3960 return;
3962 #if defined(OS_ANDROID)
3963 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableWebRTC))
3964 return;
3965 #endif
3967 #if defined(ENABLE_WEBRTC)
3968 DCHECK(!web_user_media_client_);
3969 web_user_media_client_ = new UserMediaClientImpl(
3970 this,
3971 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
3972 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
3973 #endif
3976 WebMediaPlayer* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
3977 const blink::WebURL& url,
3978 WebMediaPlayerClient* client) {
3979 #if defined(ENABLE_WEBRTC)
3980 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
3981 bool found_neon =
3982 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0;
3983 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon);
3984 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
3985 return new WebMediaPlayerMS(frame_, client, weak_factory_.GetWeakPtr(),
3986 new RenderMediaLog(),
3987 CreateRendererFactory());
3988 #else
3989 return NULL;
3990 #endif // defined(ENABLE_WEBRTC)
3993 scoped_ptr<MediaStreamRendererFactory>
3994 RenderFrameImpl::CreateRendererFactory() {
3995 #if defined(ENABLE_WEBRTC)
3996 return scoped_ptr<MediaStreamRendererFactory>(
3997 new MediaStreamRendererFactory());
3998 #else
3999 return scoped_ptr<MediaStreamRendererFactory>(
4000 static_cast<MediaStreamRendererFactory*>(NULL));
4001 #endif
4004 bool RenderFrameImpl::PrepareRenderViewForNavigation(
4005 const GURL& url,
4006 FrameMsg_Navigate_Type::Value navigate_type,
4007 const PageState& state,
4008 bool check_history,
4009 int pending_history_list_offset,
4010 int32 page_id,
4011 bool* is_reload,
4012 WebURLRequest::CachePolicy* cache_policy) {
4013 MaybeHandleDebugURL(url);
4014 if (!render_view_->webview())
4015 return false;
4017 FOR_EACH_OBSERVER(
4018 RenderViewObserver, render_view_->observers_, Navigate(url));
4020 // If this is a stale back/forward (due to a recent navigation the browser
4021 // didn't know about), ignore it.
4022 if (check_history && render_view_->IsBackForwardToStaleEntry(
4023 state, pending_history_list_offset, page_id, *is_reload))
4024 return false;
4026 if (!render_view_->is_swapped_out_ ||
4027 GetWebFrame() != render_view_->webview()->mainFrame())
4028 return true;
4030 // This is a swapped out main frame, so swap the renderer back in.
4031 // We marked the view as hidden when swapping the view out, so be sure to
4032 // reset the visibility state before navigating to the new URL.
4033 render_view_->webview()->setVisibilityState(
4034 render_view_->visibilityState(), false);
4036 // If this is an attempt to reload while we are swapped out, we should not
4037 // reload swappedout://, but the previous page, which is stored in
4038 // params.state. Setting is_reload to false will treat this like a back
4039 // navigation to accomplish that.
4040 *is_reload = false;
4041 *cache_policy = WebURLRequest::ReloadIgnoringCacheData;
4043 // We refresh timezone when a view is swapped in since timezone
4044 // can get out of sync when the system timezone is updated while
4045 // the view is swapped out.
4046 RenderThreadImpl::NotifyTimezoneChange();
4048 render_view_->SetSwappedOut(false);
4049 is_swapped_out_ = false;
4050 return true;
4053 GURL RenderFrameImpl::GetLoadingUrl() const {
4054 WebDataSource* ds = frame_->dataSource();
4055 if (ds->hasUnreachableURL())
4056 return ds->unreachableURL();
4058 const WebURLRequest& request = ds->request();
4059 return request.url();
4062 #if defined(OS_ANDROID)
4064 WebMediaPlayer* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4065 const blink::WebURL& url,
4066 WebMediaPlayerClient* client,
4067 blink::WebContentDecryptionModule* initial_cdm) {
4068 GpuChannelHost* gpu_channel_host =
4069 RenderThreadImpl::current()->EstablishGpuChannelSync(
4070 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE);
4071 if (!gpu_channel_host) {
4072 LOG(ERROR) << "Failed to establish GPU channel for media player";
4073 return NULL;
4076 scoped_refptr<StreamTextureFactory> stream_texture_factory;
4077 if (SynchronousCompositorFactory* factory =
4078 SynchronousCompositorFactory::GetInstance()) {
4079 stream_texture_factory = factory->CreateStreamTextureFactory(routing_id_);
4080 } else {
4081 scoped_refptr<webkit::gpu::ContextProviderWebContext> context_provider =
4082 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4084 if (!context_provider.get()) {
4085 LOG(ERROR) << "Failed to get context3d for media player";
4086 return NULL;
4089 stream_texture_factory = StreamTextureFactoryImpl::Create(
4090 context_provider, gpu_channel_host, routing_id_);
4093 return new WebMediaPlayerAndroid(
4094 frame_,
4095 client,
4096 weak_factory_.GetWeakPtr(),
4097 GetMediaPlayerManager(),
4098 GetCdmManager(),
4099 initial_cdm,
4100 stream_texture_factory,
4101 RenderThreadImpl::current()->GetMediaThreadTaskRunner(),
4102 new RenderMediaLog());
4105 RendererMediaPlayerManager* RenderFrameImpl::GetMediaPlayerManager() {
4106 if (!media_player_manager_)
4107 media_player_manager_ = new RendererMediaPlayerManager(this);
4108 return media_player_manager_;
4111 #endif // defined(OS_ANDROID)
4113 #if defined(ENABLE_BROWSER_CDMS)
4114 RendererCdmManager* RenderFrameImpl::GetCdmManager() {
4115 if (!cdm_manager_)
4116 cdm_manager_ = new RendererCdmManager(this);
4117 return cdm_manager_;
4119 #endif // defined(ENABLE_BROWSER_CDMS)
4121 } // namespace content