ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / content / renderer / render_frame_impl.cc
blobbceb2b53026e8dfe8c7f785b3ca06dd8e869a7eb
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 "cc/base/switches.h"
23 #include "content/child/appcache/appcache_dispatcher.h"
24 #include "content/child/plugin_messages.h"
25 #include "content/child/quota_dispatcher.h"
26 #include "content/child/request_extra_data.h"
27 #include "content/child/service_worker/service_worker_handle_reference.h"
28 #include "content/child/service_worker/service_worker_network_provider.h"
29 #include "content/child/service_worker/service_worker_provider_context.h"
30 #include "content/child/service_worker/web_service_worker_provider_impl.h"
31 #include "content/child/v8_value_converter_impl.h"
32 #include "content/child/web_url_loader_impl.h"
33 #include "content/child/web_url_request_util.h"
34 #include "content/child/webmessageportchannel_impl.h"
35 #include "content/child/websocket_bridge.h"
36 #include "content/child/weburlresponse_extradata_impl.h"
37 #include "content/common/clipboard_messages.h"
38 #include "content/common/frame_messages.h"
39 #include "content/common/frame_replication_state.h"
40 #include "content/common/input_messages.h"
41 #include "content/common/service_worker/service_worker_types.h"
42 #include "content/common/swapped_out_messages.h"
43 #include "content/common/view_messages.h"
44 #include "content/public/common/bindings_policy.h"
45 #include "content/public/common/content_constants.h"
46 #include "content/public/common/content_switches.h"
47 #include "content/public/common/context_menu_params.h"
48 #include "content/public/common/page_state.h"
49 #include "content/public/common/resource_response.h"
50 #include "content/public/common/url_constants.h"
51 #include "content/public/common/url_utils.h"
52 #include "content/public/renderer/browser_plugin_delegate.h"
53 #include "content/public/renderer/content_renderer_client.h"
54 #include "content/public/renderer/context_menu_client.h"
55 #include "content/public/renderer/document_state.h"
56 #include "content/public/renderer/navigation_state.h"
57 #include "content/public/renderer/render_frame_observer.h"
58 #include "content/public/renderer/renderer_ppapi_host.h"
59 #include "content/renderer/accessibility/renderer_accessibility.h"
60 #include "content/renderer/browser_plugin/browser_plugin.h"
61 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
62 #include "content/renderer/child_frame_compositing_helper.h"
63 #include "content/renderer/context_menu_params_builder.h"
64 #include "content/renderer/devtools/devtools_agent.h"
65 #include "content/renderer/dom_automation_controller.h"
66 #include "content/renderer/dom_utils.h"
67 #include "content/renderer/external_popup_menu.h"
68 #include "content/renderer/geolocation_dispatcher.h"
69 #include "content/renderer/gpu/gpu_benchmarking_extension.h"
70 #include "content/renderer/history_controller.h"
71 #include "content/renderer/history_serialization.h"
72 #include "content/renderer/image_loading_helper.h"
73 #include "content/renderer/ime_event_guard.h"
74 #include "content/renderer/internal_document_state_data.h"
75 #include "content/renderer/manifest/manifest_manager.h"
76 #include "content/renderer/media/audio_renderer_mixer_manager.h"
77 #include "content/renderer/media/crypto/render_cdm_factory.h"
78 #include "content/renderer/media/media_permission_dispatcher.h"
79 #include "content/renderer/media/media_stream_dispatcher.h"
80 #include "content/renderer/media/media_stream_renderer_factory.h"
81 #include "content/renderer/media/midi_dispatcher.h"
82 #include "content/renderer/media/render_media_log.h"
83 #include "content/renderer/media/user_media_client_impl.h"
84 #include "content/renderer/media/webmediaplayer_ms.h"
85 #include "content/renderer/memory_benchmarking_extension.h"
86 #include "content/renderer/mojo/service_registry_js_wrapper.h"
87 #include "content/renderer/notification_permission_dispatcher.h"
88 #include "content/renderer/npapi/plugin_channel_host.h"
89 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
90 #include "content/renderer/presentation/presentation_dispatcher.h"
91 #include "content/renderer/push_messaging/push_messaging_dispatcher.h"
92 #include "content/renderer/render_frame_proxy.h"
93 #include "content/renderer/render_process.h"
94 #include "content/renderer/render_thread_impl.h"
95 #include "content/renderer/render_view_impl.h"
96 #include "content/renderer/render_widget_fullscreen_pepper.h"
97 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
98 #include "content/renderer/renderer_webcolorchooser_impl.h"
99 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
100 #include "content/renderer/shared_worker_repository.h"
101 #include "content/renderer/skia_benchmarking_extension.h"
102 #include "content/renderer/stats_collection_controller.h"
103 #include "content/renderer/web_ui_extension.h"
104 #include "content/renderer/websharedworker_proxy.h"
105 #include "gin/modules/module_registry.h"
106 #include "media/base/audio_renderer_mixer_input.h"
107 #include "media/base/media_log.h"
108 #include "media/blink/webencryptedmediaclient_impl.h"
109 #include "media/blink/webmediaplayer_impl.h"
110 #include "media/blink/webmediaplayer_params.h"
111 #include "media/renderers/gpu_video_accelerator_factories.h"
112 #include "net/base/data_url.h"
113 #include "net/base/net_errors.h"
114 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
115 #include "net/http/http_util.h"
116 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
117 #include "third_party/WebKit/public/platform/WebString.h"
118 #include "third_party/WebKit/public/platform/WebURL.h"
119 #include "third_party/WebKit/public/platform/WebURLError.h"
120 #include "third_party/WebKit/public/platform/WebURLResponse.h"
121 #include "third_party/WebKit/public/platform/WebVector.h"
122 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
123 #include "third_party/WebKit/public/web/WebDocument.h"
124 #include "third_party/WebKit/public/web/WebFrameWidget.h"
125 #include "third_party/WebKit/public/web/WebGlyphCache.h"
126 #include "third_party/WebKit/public/web/WebLocalFrame.h"
127 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
128 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
129 #include "third_party/WebKit/public/web/WebPlugin.h"
130 #include "third_party/WebKit/public/web/WebPluginParams.h"
131 #include "third_party/WebKit/public/web/WebPluginPlaceholder.h"
132 #include "third_party/WebKit/public/web/WebRange.h"
133 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
134 #include "third_party/WebKit/public/web/WebScriptSource.h"
135 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
136 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
137 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
138 #include "third_party/WebKit/public/web/WebSurroundingText.h"
139 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
140 #include "third_party/WebKit/public/web/WebView.h"
141 #include "third_party/mojo/src/mojo/edk/js/core.h"
142 #include "third_party/mojo/src/mojo/edk/js/support.h"
144 #if defined(ENABLE_PLUGINS)
145 #include "content/renderer/npapi/webplugin_impl.h"
146 #include "content/renderer/pepper/pepper_browser_connection.h"
147 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
148 #include "content/renderer/pepper/pepper_webplugin_impl.h"
149 #include "content/renderer/pepper/plugin_module.h"
150 #endif
152 #if defined(ENABLE_WEBRTC)
153 #include "content/renderer/media/rtc_peer_connection_handler.h"
154 #endif
156 #if defined(OS_ANDROID)
157 #include <cpu-features.h>
159 #include "content/common/gpu/client/context_provider_command_buffer.h"
160 #include "content/renderer/android/synchronous_compositor_factory.h"
161 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
162 #include "content/renderer/media/android/renderer_media_player_manager.h"
163 #include "content/renderer/media/android/stream_texture_factory_impl.h"
164 #include "content/renderer/media/android/webmediaplayer_android.h"
165 #else
166 #include "cc/blink/context_provider_web_context.h"
167 #endif
169 #if defined(ENABLE_PEPPER_CDMS)
170 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
171 #elif defined(ENABLE_BROWSER_CDMS)
172 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
173 #endif
175 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
176 #include "content/renderer/media/media_renderer_service_provider.h"
177 #include "media/mojo/services/mojo_renderer_factory.h"
178 #else
179 #include "media/renderers/default_renderer_factory.h"
180 #endif
182 using blink::WebContextMenuData;
183 using blink::WebData;
184 using blink::WebDataSource;
185 using blink::WebDocument;
186 using blink::WebElement;
187 using blink::WebExternalPopupMenu;
188 using blink::WebExternalPopupMenuClient;
189 using blink::WebFrame;
190 using blink::WebHistoryItem;
191 using blink::WebHTTPBody;
192 using blink::WebLocalFrame;
193 using blink::WebMediaPlayer;
194 using blink::WebMediaPlayerClient;
195 using blink::WebNavigationPolicy;
196 using blink::WebNavigationType;
197 using blink::WebNode;
198 using blink::WebPluginParams;
199 using blink::WebPopupMenuInfo;
200 using blink::WebRange;
201 using blink::WebReferrerPolicy;
202 using blink::WebScriptSource;
203 using blink::WebSearchableFormData;
204 using blink::WebSecurityOrigin;
205 using blink::WebSecurityPolicy;
206 using blink::WebServiceWorkerProvider;
207 using blink::WebStorageQuotaCallbacks;
208 using blink::WebString;
209 using blink::WebURL;
210 using blink::WebURLError;
211 using blink::WebURLRequest;
212 using blink::WebURLResponse;
213 using blink::WebUserGestureIndicator;
214 using blink::WebVector;
215 using blink::WebView;
216 using base::Time;
217 using base::TimeDelta;
219 namespace content {
221 namespace {
223 const char kDefaultAcceptHeader[] =
224 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
225 "*;q=0.8";
226 const char kAcceptHeader[] = "Accept";
228 const size_t kExtraCharsBeforeAndAfterSelection = 100;
230 typedef std::map<int, RenderFrameImpl*> RoutingIDFrameMap;
231 static base::LazyInstance<RoutingIDFrameMap> g_routing_id_frame_map =
232 LAZY_INSTANCE_INITIALIZER;
234 typedef std::map<blink::WebFrame*, RenderFrameImpl*> FrameMap;
235 base::LazyInstance<FrameMap> g_frame_map = LAZY_INSTANCE_INITIALIZER;
237 int64 ExtractPostId(HistoryEntry* entry) {
238 if (!entry)
239 return -1;
241 const WebHistoryItem& item = entry->root();
242 if (item.isNull() || item.httpBody().isNull())
243 return -1;
245 return item.httpBody().identifier();
248 WebURLResponseExtraDataImpl* GetExtraDataFromResponse(
249 const WebURLResponse& response) {
250 return static_cast<WebURLResponseExtraDataImpl*>(response.extraData());
253 void GetRedirectChain(WebDataSource* ds, std::vector<GURL>* result) {
254 // Replace any occurrences of swappedout:// with about:blank.
255 const WebURL& blank_url = GURL(url::kAboutBlankURL);
256 WebVector<WebURL> urls;
257 ds->redirectChain(urls);
258 result->reserve(urls.size());
259 for (size_t i = 0; i < urls.size(); ++i) {
260 if (urls[i] != GURL(kSwappedOutURL))
261 result->push_back(urls[i]);
262 else
263 result->push_back(blank_url);
267 // Returns the original request url. If there is no redirect, the original
268 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
269 // frame was loaded by loadData, the original url will be ds->unreachableURL()
270 GURL GetOriginalRequestURL(WebDataSource* ds) {
271 // WebDataSource has unreachable URL means that the frame is loaded through
272 // blink::WebFrame::loadData(), and the base URL will be in the redirect
273 // chain. However, we never visited the baseURL. So in this case, we should
274 // use the unreachable URL as the original URL.
275 if (ds->hasUnreachableURL())
276 return ds->unreachableURL();
278 std::vector<GURL> redirects;
279 GetRedirectChain(ds, &redirects);
280 if (!redirects.empty())
281 return redirects.at(0);
283 return ds->originalRequest().url();
286 NOINLINE void CrashIntentionally() {
287 // NOTE(shess): Crash directly rather than using NOTREACHED() so
288 // that the signature is easier to triage in crash reports.
289 volatile int* zero = NULL;
290 *zero = 0;
293 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
294 NOINLINE void MaybeTriggerAsanError(const GURL& url) {
295 // NOTE(rogerm): We intentionally perform an invalid heap access here in
296 // order to trigger an Address Sanitizer (ASAN) error report.
297 const char kCrashDomain[] = "crash";
298 const char kHeapOverflow[] = "/heap-overflow";
299 const char kHeapUnderflow[] = "/heap-underflow";
300 const char kUseAfterFree[] = "/use-after-free";
301 #if defined(SYZYASAN)
302 const char kCorruptHeapBlock[] = "/corrupt-heap-block";
303 const char kCorruptHeap[] = "/corrupt-heap";
304 #endif
306 if (!url.DomainIs(kCrashDomain, sizeof(kCrashDomain) - 1))
307 return;
309 if (!url.has_path())
310 return;
312 std::string crash_type(url.path());
313 if (crash_type == kHeapOverflow) {
314 base::debug::AsanHeapOverflow();
315 } else if (crash_type == kHeapUnderflow ) {
316 base::debug::AsanHeapUnderflow();
317 } else if (crash_type == kUseAfterFree) {
318 base::debug::AsanHeapUseAfterFree();
319 #if defined(SYZYASAN)
320 } else if (crash_type == kCorruptHeapBlock) {
321 base::debug::AsanCorruptHeapBlock();
322 } else if (crash_type == kCorruptHeap) {
323 base::debug::AsanCorruptHeap();
324 #endif
327 #endif // ADDRESS_SANITIZER || SYZYASAN
329 void MaybeHandleDebugURL(const GURL& url) {
330 if (!url.SchemeIs(kChromeUIScheme))
331 return;
332 if (url == GURL(kChromeUICrashURL)) {
333 CrashIntentionally();
334 } else if (url == GURL(kChromeUIDumpURL)) {
335 // This URL will only correctly create a crash dump file if content is
336 // hosted in a process that has correctly called
337 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
338 // of base::debug::DumpWithoutCrashing for more details.
339 base::debug::DumpWithoutCrashing();
340 } else if (url == GURL(kChromeUIKillURL)) {
341 base::KillProcess(base::GetCurrentProcessHandle(), 1, false);
342 } else if (url == GURL(kChromeUIHangURL)) {
343 for (;;) {
344 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
346 } else if (url == GURL(kChromeUIShorthangURL)) {
347 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
350 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
351 MaybeTriggerAsanError(url);
352 #endif // ADDRESS_SANITIZER || SYZYASAN
355 // Returns false unless this is a top-level navigation.
356 bool IsTopLevelNavigation(WebFrame* frame) {
357 return frame->parent() == NULL;
360 // Returns false unless this is a top-level navigation that crosses origins.
361 bool IsNonLocalTopLevelNavigation(const GURL& url,
362 WebFrame* frame,
363 WebNavigationType type,
364 bool is_form_post) {
365 if (!IsTopLevelNavigation(frame))
366 return false;
368 // Navigations initiated within Webkit are not sent out to the external host
369 // in the following cases.
370 // 1. The url scheme is not http/https
371 // 2. The origin of the url and the opener is the same in which case the
372 // opener relationship is maintained.
373 // 3. Reloads/form submits/back forward navigations
374 if (!url.SchemeIs(url::kHttpScheme) && !url.SchemeIs(url::kHttpsScheme))
375 return false;
377 if (type != blink::WebNavigationTypeReload &&
378 type != blink::WebNavigationTypeBackForward && !is_form_post) {
379 // The opener relationship between the new window and the parent allows the
380 // new window to script the parent and vice versa. This is not allowed if
381 // the origins of the two domains are different. This can be treated as a
382 // top level navigation and routed back to the host.
383 blink::WebFrame* opener = frame->opener();
384 if (!opener)
385 return true;
387 if (url.GetOrigin() != GURL(opener->document().url()).GetOrigin())
388 return true;
390 return false;
393 WebURLRequest CreateURLRequestForNavigation(
394 const CommonNavigationParams& common_params,
395 scoped_ptr<StreamOverrideParameters> stream_override,
396 bool is_view_source_mode_enabled) {
397 WebURLRequest request(common_params.url);
398 if (is_view_source_mode_enabled)
399 request.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad);
401 if (common_params.referrer.url.is_valid()) {
402 WebString web_referrer = WebSecurityPolicy::generateReferrerHeader(
403 common_params.referrer.policy,
404 common_params.url,
405 WebString::fromUTF8(common_params.referrer.url.spec()));
406 if (!web_referrer.isEmpty())
407 request.setHTTPReferrer(web_referrer, common_params.referrer.policy);
410 RequestExtraData* extra_data = new RequestExtraData();
411 extra_data->set_stream_override(stream_override.Pass());
412 request.setExtraData(extra_data);
414 // Set the ui timestamp for this navigation. Currently the timestamp here is
415 // only non empty when the navigation was triggered by an Android intent. The
416 // timestamp is converted to a double version supported by blink. It will be
417 // passed back to the browser in the DidCommitProvisionalLoad and the
418 // DocumentLoadComplete IPCs.
419 base::TimeDelta ui_timestamp = common_params.ui_timestamp - base::TimeTicks();
420 request.setUiStartTime(ui_timestamp.InSecondsF());
421 request.setInputPerfMetricReportPolicy(
422 static_cast<WebURLRequest::InputToLoadPerfMetricReportPolicy>(
423 common_params.report_type));
424 return request;
427 void UpdateFrameNavigationTiming(WebFrame* frame,
428 base::TimeTicks browser_navigation_start,
429 base::TimeTicks renderer_navigation_start) {
430 // The browser provides the navigation_start time to bootstrap the
431 // Navigation Timing information for the browser-initiated navigations. In
432 // case of cross-process navigations, this carries over the time of
433 // finishing the onbeforeunload handler of the previous page.
434 DCHECK(!browser_navigation_start.is_null());
435 if (frame->provisionalDataSource()) {
436 // |browser_navigation_start| is likely before this process existed, so we
437 // can't use InterProcessTimeTicksConverter. We need at least to ensure
438 // that the browser-side navigation start we set is not later than the one
439 // on the renderer side.
440 base::TimeTicks navigation_start = std::min(
441 browser_navigation_start, renderer_navigation_start);
442 double navigation_start_seconds =
443 (navigation_start - base::TimeTicks()).InSecondsF();
444 frame->provisionalDataSource()->setNavigationStartTime(
445 navigation_start_seconds);
446 // TODO(clamy): We need to provide additional timing values for the
447 // Navigation Timing API to work with browser-side navigations.
451 // PlzNavigate
452 CommonNavigationParams MakeCommonNavigationParams(
453 blink::WebURLRequest* request) {
454 const RequestExtraData kEmptyData;
455 const RequestExtraData* extra_data =
456 static_cast<RequestExtraData*>(request->extraData());
457 if (!extra_data)
458 extra_data = &kEmptyData;
459 CommonNavigationParams params;
460 params.url = request->url();
461 params.referrer = Referrer(
462 GURL(request->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
463 request->referrerPolicy());
464 params.transition = extra_data->transition_type();
466 // Set the ui timestamp for this navigation. Currently the timestamp here is
467 // only non empty when the navigation was triggered by an Android intent, or
468 // by the user clicking on a link. The timestamp is converted from a double
469 // version supported by blink. It will be passed back to the renderer in the
470 // CommitNavigation IPC, and then back to the browser again in the
471 // DidCommitProvisionalLoad and the DocumentLoadComplete IPCs.
472 params.ui_timestamp =
473 base::TimeTicks() + base::TimeDelta::FromSecondsD(request->uiStartTime());
474 params.report_type = static_cast<FrameMsg_UILoadMetricsReportType::Value>(
475 request->inputPerfMetricReportPolicy());
476 return params;
479 #if !defined(OS_ANDROID)
480 media::Context3D GetSharedMainThreadContext3D() {
481 cc::ContextProvider* provider =
482 RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
483 if (!provider)
484 return media::Context3D();
485 return media::Context3D(provider->ContextGL(), provider->GrContext());
487 #endif
489 RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl =
490 nullptr;
492 #define STATIC_ASSERT_MATCHING_ENUMS(content_name, blink_name) \
493 static_assert( \
494 static_cast<int>(content_name) == static_cast<int>(blink_name), \
495 "enum values must match")
497 // Check that blink::WebSandboxFlags is kept in sync with
498 // content::SandboxFlags.
499 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::NONE,
500 blink::WebSandboxFlags::None);
501 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::NAVIGATION,
502 blink::WebSandboxFlags::Navigation);
503 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::PLUGINS,
504 blink::WebSandboxFlags::Plugins);
505 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ORIGIN,
506 blink::WebSandboxFlags::Origin);
507 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::FORMS,
508 blink::WebSandboxFlags::Forms);
509 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::SCRIPTS,
510 blink::WebSandboxFlags::Scripts);
511 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::TOP_NAVIGATION,
512 blink::WebSandboxFlags::TopNavigation);
513 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::POPUPS,
514 blink::WebSandboxFlags::Popups);
515 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::AUTOMATIC_FEATURES,
516 blink::WebSandboxFlags::AutomaticFeatures);
517 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::POINTER_LOCK,
518 blink::WebSandboxFlags::PointerLock);
519 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::DOCUMENT_DOMAIN,
520 blink::WebSandboxFlags::DocumentDomain);
521 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ORIENTATION_LOCK,
522 blink::WebSandboxFlags::OrientationLock);
523 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ALL,
524 blink::WebSandboxFlags::All);
526 } // namespace
528 // static
529 RenderFrameImpl* RenderFrameImpl::Create(RenderViewImpl* render_view,
530 int32 routing_id) {
531 DCHECK(routing_id != MSG_ROUTING_NONE);
533 if (g_create_render_frame_impl)
534 return g_create_render_frame_impl(render_view, routing_id);
535 else
536 return new RenderFrameImpl(render_view, routing_id);
539 // static
540 RenderFrameImpl* RenderFrameImpl::FromRoutingID(int32 routing_id) {
541 RoutingIDFrameMap::iterator iter =
542 g_routing_id_frame_map.Get().find(routing_id);
543 if (iter != g_routing_id_frame_map.Get().end())
544 return iter->second;
545 return NULL;
548 // static
549 void RenderFrameImpl::CreateFrame(
550 int routing_id,
551 int parent_routing_id,
552 int proxy_routing_id,
553 const FrameReplicationState& replicated_state,
554 CompositorDependencies* compositor_deps,
555 const FrameMsg_NewFrame_WidgetParams& widget_params) {
556 // TODO(nasko): For now, this message is only sent for subframes, as the
557 // top level frame is created when the RenderView is created through the
558 // ViewMsg_New IPC.
559 CHECK_NE(MSG_ROUTING_NONE, parent_routing_id);
561 blink::WebLocalFrame* web_frame;
562 RenderFrameImpl* render_frame;
563 if (proxy_routing_id == MSG_ROUTING_NONE) {
564 RenderFrameProxy* parent_proxy =
565 RenderFrameProxy::FromRoutingID(parent_routing_id);
566 // If the browser is sending a valid parent routing id, it should already
567 // be created and registered.
568 CHECK(parent_proxy);
569 blink::WebRemoteFrame* parent_web_frame = parent_proxy->web_frame();
571 // Create the RenderFrame and WebLocalFrame, linking the two.
572 render_frame =
573 RenderFrameImpl::Create(parent_proxy->render_view(), routing_id);
574 web_frame = parent_web_frame->createLocalChild(
575 WebString::fromUTF8(replicated_state.name),
576 ContentToWebSandboxFlags(replicated_state.sandbox_flags), render_frame);
577 } else {
578 RenderFrameProxy* proxy =
579 RenderFrameProxy::FromRoutingID(proxy_routing_id);
580 CHECK(proxy);
581 render_frame = RenderFrameImpl::Create(proxy->render_view(), routing_id);
582 web_frame = blink::WebLocalFrame::create(render_frame);
583 render_frame->proxy_routing_id_ = proxy_routing_id;
584 web_frame->initializeToReplaceRemoteFrame(proxy->web_frame());
586 render_frame->SetWebFrame(web_frame);
588 if (widget_params.routing_id != MSG_ROUTING_NONE) {
589 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
590 switches::kSitePerProcess));
591 render_frame->render_widget_ = RenderWidget::CreateForFrame(
592 widget_params.routing_id, widget_params.surface_id,
593 widget_params.hidden, render_frame->render_view_->screen_info(),
594 compositor_deps, web_frame);
595 // TODO(kenrb): Observing shouldn't be necessary when we sort out
596 // WasShown and WasHidden, separating page-level visibility from
597 // frame-level visibility.
598 render_frame->render_widget_->RegisterRenderFrame(render_frame);
601 render_frame->Initialize();
604 // static
605 RenderFrame* RenderFrame::FromWebFrame(blink::WebFrame* web_frame) {
606 return RenderFrameImpl::FromWebFrame(web_frame);
609 // static
610 RenderFrameImpl* RenderFrameImpl::FromWebFrame(blink::WebFrame* web_frame) {
611 FrameMap::iterator iter = g_frame_map.Get().find(web_frame);
612 if (iter != g_frame_map.Get().end())
613 return iter->second;
614 return NULL;
617 // static
618 void RenderFrameImpl::InstallCreateHook(
619 CreateRenderFrameImplFunction create_render_frame_impl) {
620 CHECK(!g_create_render_frame_impl);
621 g_create_render_frame_impl = create_render_frame_impl;
624 // static
625 content::SandboxFlags RenderFrameImpl::WebToContentSandboxFlags(
626 blink::WebSandboxFlags flags) {
627 return static_cast<content::SandboxFlags>(flags);
630 // static
631 blink::WebSandboxFlags RenderFrameImpl::ContentToWebSandboxFlags(
632 content::SandboxFlags flags) {
633 return static_cast<blink::WebSandboxFlags>(flags);
636 // RenderFrameImpl ----------------------------------------------------------
637 RenderFrameImpl::RenderFrameImpl(RenderViewImpl* render_view, int routing_id)
638 : frame_(NULL),
639 render_view_(render_view->AsWeakPtr()),
640 routing_id_(routing_id),
641 is_swapped_out_(false),
642 render_frame_proxy_(NULL),
643 is_detaching_(false),
644 proxy_routing_id_(MSG_ROUTING_NONE),
645 #if defined(ENABLE_PLUGINS)
646 plugin_power_saver_helper_(NULL),
647 #endif
648 cookie_jar_(this),
649 selection_text_offset_(0),
650 selection_range_(gfx::Range::InvalidRange()),
651 handling_select_range_(false),
652 notification_permission_dispatcher_(NULL),
653 web_user_media_client_(NULL),
654 media_permission_dispatcher_(NULL),
655 midi_dispatcher_(NULL),
656 #if defined(OS_ANDROID)
657 media_player_manager_(NULL),
658 #endif
659 #if defined(ENABLE_BROWSER_CDMS)
660 cdm_manager_(NULL),
661 #endif
662 #if defined(VIDEO_HOLE)
663 contains_media_player_(false),
664 #endif
665 geolocation_dispatcher_(NULL),
666 push_messaging_dispatcher_(NULL),
667 presentation_dispatcher_(NULL),
668 screen_orientation_dispatcher_(NULL),
669 manifest_manager_(NULL),
670 accessibility_mode_(AccessibilityModeOff),
671 renderer_accessibility_(NULL),
672 weak_factory_(this) {
673 std::pair<RoutingIDFrameMap::iterator, bool> result =
674 g_routing_id_frame_map.Get().insert(std::make_pair(routing_id_, this));
675 CHECK(result.second) << "Inserting a duplicate item.";
677 RenderThread::Get()->AddRoute(routing_id_, this);
679 render_view_->RegisterRenderFrame(this);
681 // Everything below subclasses RenderFrameObserver and is automatically
682 // deleted when the RenderFrame gets deleted.
683 #if defined(OS_ANDROID)
684 new GinJavaBridgeDispatcher(this);
685 #endif
687 #if defined(ENABLE_PLUGINS)
688 plugin_power_saver_helper_ = new PluginPowerSaverHelper(this);
689 #endif
691 manifest_manager_ = new ManifestManager(this);
694 RenderFrameImpl::~RenderFrameImpl() {
695 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, RenderFrameGone());
696 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, OnDestruct());
698 #if defined(VIDEO_HOLE)
699 if (contains_media_player_)
700 render_view_->UnregisterVideoHoleFrame(this);
701 #endif
703 if (render_frame_proxy_)
704 delete render_frame_proxy_;
706 render_view_->UnregisterRenderFrame(this);
707 g_routing_id_frame_map.Get().erase(routing_id_);
708 RenderThread::Get()->RemoveRoute(routing_id_);
711 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame* web_frame) {
712 DCHECK(!frame_);
714 std::pair<FrameMap::iterator, bool> result = g_frame_map.Get().insert(
715 std::make_pair(web_frame, this));
716 CHECK(result.second) << "Inserting a duplicate item.";
718 frame_ = web_frame;
721 void RenderFrameImpl::Initialize() {
722 #if defined(ENABLE_PLUGINS)
723 new PepperBrowserConnection(this);
724 #endif
725 new SharedWorkerRepository(this);
727 if (!frame_->parent())
728 new ImageLoadingHelper(this);
730 // We delay calling this until we have the WebFrame so that any observer or
731 // embedder can call GetWebFrame on any RenderFrame.
732 GetContentClient()->renderer()->RenderFrameCreated(this);
735 RenderWidget* RenderFrameImpl::GetRenderWidget() {
736 return render_view_.get();
739 #if defined(ENABLE_PLUGINS)
740 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost* host) {
741 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
742 DidCreatePepperPlugin(host));
743 if (host->GetPluginName() == kFlashPluginName) {
744 RenderThread::Get()->RecordAction(
745 base::UserMetricsAction("FrameLoadWithFlash"));
749 void RenderFrameImpl::PepperDidChangeCursor(
750 PepperPluginInstanceImpl* instance,
751 const blink::WebCursorInfo& cursor) {
752 // Update the cursor appearance immediately if the requesting plugin is the
753 // one which receives the last mouse event. Otherwise, the new cursor won't be
754 // picked up until the plugin gets the next input event. That is bad if, e.g.,
755 // the plugin would like to set an invisible cursor when there isn't any user
756 // input for a while.
757 if (instance == render_view_->pepper_last_mouse_event_target())
758 GetRenderWidget()->didChangeCursor(cursor);
761 void RenderFrameImpl::PepperDidReceiveMouseEvent(
762 PepperPluginInstanceImpl* instance) {
763 render_view_->set_pepper_last_mouse_event_target(instance);
766 void RenderFrameImpl::PepperTextInputTypeChanged(
767 PepperPluginInstanceImpl* instance) {
768 if (instance != render_view_->focused_pepper_plugin())
769 return;
771 GetRenderWidget()->UpdateTextInputType();
773 FocusedNodeChangedForAccessibility(WebNode());
776 void RenderFrameImpl::PepperCaretPositionChanged(
777 PepperPluginInstanceImpl* instance) {
778 if (instance != render_view_->focused_pepper_plugin())
779 return;
780 GetRenderWidget()->UpdateSelectionBounds();
783 void RenderFrameImpl::PepperCancelComposition(
784 PepperPluginInstanceImpl* instance) {
785 if (instance != render_view_->focused_pepper_plugin())
786 return;
787 Send(new InputHostMsg_ImeCancelComposition(render_view_->GetRoutingID()));;
788 #if defined(OS_MACOSX) || defined(USE_AURA)
789 GetRenderWidget()->UpdateCompositionInfo(true);
790 #endif
793 void RenderFrameImpl::PepperSelectionChanged(
794 PepperPluginInstanceImpl* instance) {
795 if (instance != render_view_->focused_pepper_plugin())
796 return;
797 SyncSelectionIfRequired();
800 RenderWidgetFullscreenPepper* RenderFrameImpl::CreatePepperFullscreenContainer(
801 PepperPluginInstanceImpl* plugin) {
802 GURL active_url;
803 if (render_view_->webview() && render_view_->webview()->mainFrame())
804 active_url = GURL(render_view_->webview()->mainFrame()->document().url());
805 RenderWidgetFullscreenPepper* widget = RenderWidgetFullscreenPepper::Create(
806 GetRenderWidget()->routing_id(), GetRenderWidget()->compositor_deps(),
807 plugin, active_url, GetRenderWidget()->screenInfo());
808 widget->show(blink::WebNavigationPolicyIgnore);
809 return widget;
812 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
813 if (!render_view_->focused_pepper_plugin())
814 return false;
815 return render_view_->focused_pepper_plugin()->
816 IsPluginAcceptingCompositionEvents();
819 void RenderFrameImpl::PluginCrashed(const base::FilePath& plugin_path,
820 base::ProcessId plugin_pid) {
821 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
822 // routing_id_ as a result.
823 Send(new FrameHostMsg_PluginCrashed(routing_id_, plugin_path, plugin_pid));
826 void RenderFrameImpl::SimulateImeSetComposition(
827 const base::string16& text,
828 const std::vector<blink::WebCompositionUnderline>& underlines,
829 int selection_start,
830 int selection_end) {
831 render_view_->OnImeSetComposition(
832 text, underlines, selection_start, selection_end);
835 void RenderFrameImpl::SimulateImeConfirmComposition(
836 const base::string16& text,
837 const gfx::Range& replacement_range) {
838 render_view_->OnImeConfirmComposition(text, replacement_range, false);
841 void RenderFrameImpl::OnImeSetComposition(
842 const base::string16& text,
843 const std::vector<blink::WebCompositionUnderline>& underlines,
844 int selection_start,
845 int selection_end) {
846 // When a PPAPI plugin has focus, we bypass WebKit.
847 if (!IsPepperAcceptingCompositionEvents()) {
848 pepper_composition_text_ = text;
849 } else {
850 // TODO(kinaba) currently all composition events are sent directly to
851 // plugins. Use DOM event mechanism after WebKit is made aware about
852 // plugins that support composition.
853 // The code below mimics the behavior of WebCore::Editor::setComposition.
855 // Empty -> nonempty: composition started.
856 if (pepper_composition_text_.empty() && !text.empty()) {
857 render_view_->focused_pepper_plugin()->HandleCompositionStart(
858 base::string16());
860 // Nonempty -> empty: composition canceled.
861 if (!pepper_composition_text_.empty() && text.empty()) {
862 render_view_->focused_pepper_plugin()->HandleCompositionEnd(
863 base::string16());
865 pepper_composition_text_ = text;
866 // Nonempty: composition is ongoing.
867 if (!pepper_composition_text_.empty()) {
868 render_view_->focused_pepper_plugin()->HandleCompositionUpdate(
869 pepper_composition_text_, underlines, selection_start,
870 selection_end);
875 void RenderFrameImpl::OnImeConfirmComposition(
876 const base::string16& text,
877 const gfx::Range& replacement_range,
878 bool keep_selection) {
879 // When a PPAPI plugin has focus, we bypass WebKit.
880 // Here, text.empty() has a special meaning. It means to commit the last
881 // update of composition text (see
882 // RenderWidgetHost::ImeConfirmComposition()).
883 const base::string16& last_text = text.empty() ? pepper_composition_text_
884 : text;
886 // last_text is empty only when both text and pepper_composition_text_ is.
887 // Ignore it.
888 if (last_text.empty())
889 return;
891 if (!IsPepperAcceptingCompositionEvents()) {
892 base::i18n::UTF16CharIterator iterator(&last_text);
893 int32 i = 0;
894 while (iterator.Advance()) {
895 blink::WebKeyboardEvent char_event;
896 char_event.type = blink::WebInputEvent::Char;
897 char_event.timeStampSeconds = base::Time::Now().ToDoubleT();
898 char_event.modifiers = 0;
899 char_event.windowsKeyCode = last_text[i];
900 char_event.nativeKeyCode = last_text[i];
902 const int32 char_start = i;
903 for (; i < iterator.array_pos(); ++i) {
904 char_event.text[i - char_start] = last_text[i];
905 char_event.unmodifiedText[i - char_start] = last_text[i];
908 if (GetRenderWidget()->webwidget())
909 GetRenderWidget()->webwidget()->handleInputEvent(char_event);
911 } else {
912 // Mimics the order of events sent by WebKit.
913 // See WebCore::Editor::setComposition() for the corresponding code.
914 render_view_->focused_pepper_plugin()->HandleCompositionEnd(last_text);
915 render_view_->focused_pepper_plugin()->HandleTextInput(last_text);
917 pepper_composition_text_.clear();
919 #endif // defined(ENABLE_PLUGINS)
921 MediaStreamDispatcher* RenderFrameImpl::GetMediaStreamDispatcher() {
922 if (!web_user_media_client_)
923 InitializeUserMediaClient();
924 return web_user_media_client_ ?
925 web_user_media_client_->media_stream_dispatcher() : NULL;
928 bool RenderFrameImpl::Send(IPC::Message* message) {
929 if (is_detaching_) {
930 delete message;
931 return false;
933 if (is_swapped_out_) {
934 if (!SwappedOutMessages::CanSendWhileSwappedOut(message)) {
935 delete message;
936 return false;
940 return RenderThread::Get()->Send(message);
943 #if defined(OS_MACOSX) || defined(OS_ANDROID)
944 void RenderFrameImpl::DidHideExternalPopupMenu() {
945 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
946 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
947 external_popup_menu_.reset();
949 #endif
951 bool RenderFrameImpl::OnMessageReceived(const IPC::Message& msg) {
952 // TODO(kenrb): document() should not be null, but as a transitional step
953 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
954 // to this method. This happens for a top-level remote frame, where a
955 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
956 // around and is still able to receive messages.
957 if (!frame_->document().isNull())
958 GetContentClient()->SetActiveURL(frame_->document().url());
960 ObserverListBase<RenderFrameObserver>::Iterator it(observers_);
961 RenderFrameObserver* observer;
962 while ((observer = it.GetNext()) != NULL) {
963 if (observer->OnMessageReceived(msg))
964 return true;
967 bool handled = true;
968 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl, msg)
969 IPC_MESSAGE_HANDLER(FrameMsg_Navigate, OnNavigate)
970 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload, OnBeforeUnload)
971 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut, OnSwapOut)
972 IPC_MESSAGE_HANDLER(FrameMsg_Stop, OnStop)
973 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed, OnContextMenuClosed)
974 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction,
975 OnCustomContextMenuAction)
976 IPC_MESSAGE_HANDLER(InputMsg_Undo, OnUndo)
977 IPC_MESSAGE_HANDLER(InputMsg_Redo, OnRedo)
978 IPC_MESSAGE_HANDLER(InputMsg_Cut, OnCut)
979 IPC_MESSAGE_HANDLER(InputMsg_Copy, OnCopy)
980 IPC_MESSAGE_HANDLER(InputMsg_Paste, OnPaste)
981 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle, OnPasteAndMatchStyle)
982 IPC_MESSAGE_HANDLER(InputMsg_Delete, OnDelete)
983 IPC_MESSAGE_HANDLER(InputMsg_SelectAll, OnSelectAll)
984 IPC_MESSAGE_HANDLER(InputMsg_SelectRange, OnSelectRange)
985 IPC_MESSAGE_HANDLER(InputMsg_Unselect, OnUnselect)
986 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent,
987 OnMoveRangeSelectionExtent)
988 IPC_MESSAGE_HANDLER(InputMsg_Replace, OnReplace)
989 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling, OnReplaceMisspelling)
990 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete,
991 OnExtendSelectionAndDelete)
992 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText,
993 OnSetCompositionFromExistingText)
994 IPC_MESSAGE_HANDLER(InputMsg_ExecuteNoValueEditCommand,
995 OnExecuteNoValueEditCommand)
996 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest, OnCSSInsertRequest)
997 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest,
998 OnJavaScriptExecuteRequest)
999 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests,
1000 OnJavaScriptExecuteRequestForTests)
1001 IPC_MESSAGE_HANDLER(FrameMsg_VisualStateRequest,
1002 OnVisualStateRequest)
1003 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets,
1004 OnSetEditableSelectionOffsets)
1005 IPC_MESSAGE_HANDLER(FrameMsg_SetupTransitionView, OnSetupTransitionView)
1006 IPC_MESSAGE_HANDLER(FrameMsg_BeginExitTransition, OnBeginExitTransition)
1007 IPC_MESSAGE_HANDLER(FrameMsg_RevertExitTransition, OnRevertExitTransition)
1008 IPC_MESSAGE_HANDLER(FrameMsg_HideTransitionElements,
1009 OnHideTransitionElements)
1010 IPC_MESSAGE_HANDLER(FrameMsg_ShowTransitionElements,
1011 OnShowTransitionElements)
1012 IPC_MESSAGE_HANDLER(FrameMsg_Reload, OnReload)
1013 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest,
1014 OnTextSurroundingSelectionRequest)
1015 IPC_MESSAGE_HANDLER(FrameMsg_AddStyleSheetByURL,
1016 OnAddStyleSheetByURL)
1017 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode,
1018 OnSetAccessibilityMode)
1019 IPC_MESSAGE_HANDLER(FrameMsg_DisownOpener, OnDisownOpener)
1020 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation, OnCommitNavigation)
1021 #if defined(OS_ANDROID)
1022 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems, OnSelectPopupMenuItems)
1023 #elif defined(OS_MACOSX)
1024 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem, OnSelectPopupMenuItem)
1025 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard, OnCopyToFindPboard)
1026 #endif
1027 IPC_END_MESSAGE_MAP()
1029 return handled;
1032 void RenderFrameImpl::OnNavigate(const FrameMsg_Navigate_Params& params) {
1033 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate",
1034 "id", routing_id_,
1035 "url", params.common_params.url.possibly_invalid_spec());
1037 bool is_reload =
1038 RenderViewImpl::IsReload(params.common_params.navigation_type);
1039 bool is_history_navigation = params.commit_params.page_state.IsValid();
1040 WebURLRequest::CachePolicy cache_policy =
1041 WebURLRequest::UseProtocolCachePolicy;
1042 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
1043 params.common_params.url, true, is_history_navigation,
1044 params.current_history_list_offset, &is_reload, &cache_policy)) {
1045 Send(new FrameHostMsg_DidDropNavigation(routing_id_));
1046 return;
1049 render_view_->history_list_offset_ = params.current_history_list_offset;
1050 render_view_->history_list_length_ = params.current_history_list_length;
1051 if (params.should_clear_history_list) {
1052 CHECK_EQ(-1, render_view_->history_list_offset_);
1053 CHECK_EQ(0, render_view_->history_list_length_);
1056 GetContentClient()->SetActiveURL(params.common_params.url);
1058 WebFrame* frame = frame_;
1059 if (!params.frame_to_navigate.empty()) {
1060 // TODO(nasko): Move this lookup to the browser process.
1061 frame = render_view_->webview()->findFrameByName(
1062 WebString::fromUTF8(params.frame_to_navigate));
1063 CHECK(frame) << "Invalid frame name passed: " << params.frame_to_navigate;
1066 if (is_reload && !render_view_->history_controller()->GetCurrentEntry()) {
1067 // We cannot reload if we do not have any history state. This happens, for
1068 // example, when recovering from a crash.
1069 is_reload = false;
1070 cache_policy = WebURLRequest::ReloadIgnoringCacheData;
1073 render_view_->pending_navigation_params_.reset(
1074 new FrameMsg_Navigate_Params(params));
1076 // If we are reloading, then WebKit will use the history state of the current
1077 // page, so we should just ignore any given history state. Otherwise, if we
1078 // have history state, then we need to navigate to it, which corresponds to a
1079 // back/forward navigation event.
1080 if (is_reload) {
1081 bool reload_original_url =
1082 (params.common_params.navigation_type ==
1083 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
1084 bool ignore_cache = (params.common_params.navigation_type ==
1085 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE);
1087 if (reload_original_url)
1088 frame->reloadWithOverrideURL(params.common_params.url, true);
1089 else
1090 frame->reload(ignore_cache);
1091 } else if (is_history_navigation) {
1092 // We must know the page ID of the page we are navigating back to.
1093 DCHECK_NE(params.page_id, -1);
1094 scoped_ptr<HistoryEntry> entry =
1095 PageStateToHistoryEntry(params.commit_params.page_state);
1096 if (entry) {
1097 // Ensure we didn't save the swapped out URL in UpdateState, since the
1098 // browser should never be telling us to navigate to swappedout://.
1099 CHECK(entry->root().urlString() != WebString::fromUTF8(kSwappedOutURL));
1100 render_view_->history_controller()->GoToEntry(entry.Pass(), cache_policy);
1102 } else if (!params.common_params.base_url_for_data_url.is_empty()) {
1103 LoadDataURL(params.common_params, frame);
1104 } else {
1105 // Navigate to the given URL.
1106 WebURLRequest request =
1107 CreateURLRequestForNavigation(params.common_params,
1108 scoped_ptr<StreamOverrideParameters>(),
1109 frame->isViewSourceModeEnabled());
1111 if (!params.extra_headers.empty()) {
1112 for (net::HttpUtil::HeadersIterator i(params.extra_headers.begin(),
1113 params.extra_headers.end(),
1114 "\n");
1115 i.GetNext();) {
1116 request.addHTTPHeaderField(WebString::fromUTF8(i.name()),
1117 WebString::fromUTF8(i.values()));
1121 if (params.is_post) {
1122 request.setHTTPMethod(WebString::fromUTF8("POST"));
1124 // Set post data.
1125 WebHTTPBody http_body;
1126 http_body.initialize();
1127 const char* data = NULL;
1128 if (params.browser_initiated_post_data.size()) {
1129 data = reinterpret_cast<const char*>(
1130 &params.browser_initiated_post_data.front());
1132 http_body.appendData(
1133 WebData(data, params.browser_initiated_post_data.size()));
1134 request.setHTTPBody(http_body);
1137 // A session history navigation should have been accompanied by state.
1138 CHECK_EQ(params.page_id, -1);
1140 // Record this before starting the load, we need a lower bound of this time
1141 // to sanitize the navigationStart override set below.
1142 base::TimeTicks renderer_navigation_start = base::TimeTicks::Now();
1143 frame->loadRequest(request);
1145 UpdateFrameNavigationTiming(
1146 frame, params.commit_params.browser_navigation_start,
1147 renderer_navigation_start);
1150 // In case LoadRequest failed before DidCreateDataSource was called.
1151 render_view_->pending_navigation_params_.reset();
1154 void RenderFrameImpl::NavigateToSwappedOutURL() {
1155 // We use loadRequest instead of loadHTMLString because the former commits
1156 // synchronously. Otherwise a new navigation can interrupt the navigation
1157 // to kSwappedOutURL. If that happens to be to the page we had been
1158 // showing, then WebKit will never send a commit and we'll be left spinning.
1159 // Set the is_swapped_out_ bit to true, so IPC filtering is in effect and
1160 // the navigation to swappedout:// is not announced to the browser side.
1161 is_swapped_out_ = true;
1162 GURL swappedOutURL(kSwappedOutURL);
1163 WebURLRequest request(swappedOutURL);
1164 frame_->loadRequest(request);
1167 void RenderFrameImpl::BindServiceRegistry(
1168 mojo::InterfaceRequest<mojo::ServiceProvider> services,
1169 mojo::ServiceProviderPtr exposed_services) {
1170 service_registry_.Bind(services.Pass());
1171 service_registry_.BindRemoteServiceProvider(exposed_services.Pass());
1174 ManifestManager* RenderFrameImpl::manifest_manager() {
1175 return manifest_manager_;
1178 void RenderFrameImpl::OnBeforeUnload() {
1179 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1180 "id", routing_id_);
1181 // TODO(creis): Right now, this is only called on the main frame. Make the
1182 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1183 // it.
1184 CHECK(!frame_->parent());
1186 base::TimeTicks before_unload_start_time = base::TimeTicks::Now();
1187 bool proceed = frame_->dispatchBeforeUnloadEvent();
1188 base::TimeTicks before_unload_end_time = base::TimeTicks::Now();
1189 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_, proceed,
1190 before_unload_start_time,
1191 before_unload_end_time));
1194 void RenderFrameImpl::OnSwapOut(
1195 int proxy_routing_id,
1196 bool is_loading,
1197 const FrameReplicationState& replicated_frame_state) {
1198 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_);
1199 RenderFrameProxy* proxy = NULL;
1200 bool is_site_per_process = base::CommandLine::ForCurrentProcess()->HasSwitch(
1201 switches::kSitePerProcess);
1202 bool is_main_frame = !frame_->parent();
1204 // Only run unload if we're not swapped out yet, but send the ack either way.
1205 if (!is_swapped_out_) {
1206 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1207 // a different process. This involves running the unload handler and
1208 // clearing the page. We also allow this process to exit if there are no
1209 // other active RenderFrames in it.
1211 // Send an UpdateState message before we get swapped out.
1212 render_view_->SyncNavigationState();
1214 // If we need a proxy to replace this, create it now so its routing id is
1215 // registered for receiving IPC messages.
1216 if (proxy_routing_id != MSG_ROUTING_NONE) {
1217 proxy = RenderFrameProxy::CreateProxyToReplaceFrame(this,
1218 proxy_routing_id);
1221 // Synchronously run the unload handler before sending the ACK.
1222 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1223 // unload on subframes as well.
1224 if (is_main_frame)
1225 frame_->dispatchUnloadEvent();
1227 // Swap out and stop sending any IPC messages that are not ACKs.
1228 if (is_main_frame)
1229 render_view_->SetSwappedOut(true);
1230 is_swapped_out_ = true;
1232 // Now that we're swapped out and filtering IPC messages, stop loading to
1233 // ensure that no other in-progress navigation continues. We do this here
1234 // to avoid sending a DidStopLoading message to the browser process.
1235 // TODO(creis): Should we be stopping all frames here and using
1236 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1237 // frame?
1238 OnStop();
1240 // Transfer settings such as initial drawing parameters to the remote frame,
1241 // if one is created, that will replace this frame.
1242 if (!is_main_frame && proxy)
1243 proxy->web_frame()->initializeFromFrame(frame_);
1245 // Replace the page with a blank dummy URL. The unload handler will not be
1246 // run a second time, thanks to a check in FrameLoader::stopLoading.
1247 // TODO(creis): Need to add a better way to do this that avoids running the
1248 // beforeunload handler. For now, we just run it a second time silently.
1249 if (!is_site_per_process || is_main_frame)
1250 NavigateToSwappedOutURL();
1252 // Let WebKit know that this view is hidden so it can drop resources and
1253 // stop compositing.
1254 // TODO(creis): Support this for subframes as well.
1255 if (is_main_frame) {
1256 render_view_->webview()->setVisibilityState(
1257 blink::WebPageVisibilityStateHidden, false);
1261 // It is now safe to show modal dialogs again.
1262 // TODO(creis): Deal with modal dialogs from subframes.
1263 if (is_main_frame)
1264 render_view_->suppress_dialogs_until_swap_out_ = false;
1266 Send(new FrameHostMsg_SwapOut_ACK(routing_id_));
1268 // Now that all of the cleanup is complete and the browser side is notified,
1269 // start using the RenderFrameProxy, if one is created.
1270 if (proxy) {
1271 if (!is_main_frame) {
1272 frame_->swap(proxy->web_frame());
1274 if (is_loading)
1275 proxy->OnDidStartLoading();
1277 if (is_site_per_process) {
1278 // TODO(nasko): delete the frame here, since we've replaced it with a
1279 // proxy.
1281 } else {
1282 set_render_frame_proxy(proxy);
1286 // In --site-per-process, initialize the WebRemoteFrame with the replication
1287 // state passed by the process that is now rendering the frame.
1288 // TODO(alexmos): We cannot yet do this for swapped-out main frames, because
1289 // in that case we leave the LocalFrame as the main frame visible to Blink
1290 // and don't call swap() above. Because swap() is what creates a RemoteFrame
1291 // in proxy->web_frame(), the RemoteFrame will not exist for main frames.
1292 // When we do an unconditional swap for all frames, we can remove
1293 // !is_main_frame below.
1294 if (is_site_per_process && proxy && !is_main_frame)
1295 proxy->SetReplicatedState(replicated_frame_state);
1297 // Safe to exit if no one else is using the process.
1298 if (is_main_frame)
1299 render_view_->WasSwappedOut();
1302 void RenderFrameImpl::OnContextMenuClosed(
1303 const CustomContextMenuContext& custom_context) {
1304 if (custom_context.request_id) {
1305 // External request, should be in our map.
1306 ContextMenuClient* client =
1307 pending_context_menus_.Lookup(custom_context.request_id);
1308 if (client) {
1309 client->OnMenuClosed(custom_context.request_id);
1310 pending_context_menus_.Remove(custom_context.request_id);
1312 } else {
1313 if (custom_context.link_followed.is_valid()) {
1314 frame_->sendPings(
1315 DomUtils::ExtractParentAnchorNode(context_menu_node_),
1316 custom_context.link_followed);
1318 // Internal request, forward to WebKit.
1319 context_menu_node_.reset();
1323 void RenderFrameImpl::OnCustomContextMenuAction(
1324 const CustomContextMenuContext& custom_context,
1325 unsigned action) {
1326 if (custom_context.request_id) {
1327 // External context menu request, look in our map.
1328 ContextMenuClient* client =
1329 pending_context_menus_.Lookup(custom_context.request_id);
1330 if (client)
1331 client->OnMenuAction(custom_context.request_id, action);
1332 } else {
1333 // Internal request, forward to WebKit.
1334 render_view_->webview()->performCustomContextMenuAction(action);
1338 void RenderFrameImpl::OnUndo() {
1339 frame_->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1342 void RenderFrameImpl::OnRedo() {
1343 frame_->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1346 void RenderFrameImpl::OnCut() {
1347 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1348 frame_->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1351 void RenderFrameImpl::OnCopy() {
1352 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1353 WebNode current_node = context_menu_node_.isNull() ?
1354 GetFocusedElement() : context_menu_node_;
1355 frame_->executeCommand(WebString::fromUTF8("Copy"), current_node);
1358 void RenderFrameImpl::OnPaste() {
1359 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1360 frame_->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1363 void RenderFrameImpl::OnPasteAndMatchStyle() {
1364 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1365 frame_->executeCommand(
1366 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1369 #if defined(OS_MACOSX)
1370 void RenderFrameImpl::OnCopyToFindPboard() {
1371 // Since the find pasteboard supports only plain text, this can be simpler
1372 // than the |OnCopy()| case.
1373 if (frame_->hasSelection()) {
1374 base::string16 selection = frame_->selectionAsText();
1375 RenderThread::Get()->Send(
1376 new ClipboardHostMsg_FindPboardWriteStringAsync(selection));
1379 #endif
1381 void RenderFrameImpl::OnDelete() {
1382 frame_->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1385 void RenderFrameImpl::OnSelectAll() {
1386 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1387 frame_->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1390 void RenderFrameImpl::OnSelectRange(const gfx::Point& base,
1391 const gfx::Point& extent) {
1392 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1393 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1395 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1396 frame_->selectRange(base, extent);
1399 void RenderFrameImpl::OnUnselect() {
1400 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1401 frame_->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1404 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point& point) {
1405 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1406 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1407 GetRenderWidget()->routing_id()));
1409 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1410 frame_->moveRangeSelectionExtent(point);
1413 void RenderFrameImpl::OnReplace(const base::string16& text) {
1414 if (!frame_->hasSelection())
1415 frame_->selectWordAroundCaret();
1417 frame_->replaceSelection(text);
1420 void RenderFrameImpl::OnReplaceMisspelling(const base::string16& text) {
1421 if (!frame_->hasSelection())
1422 return;
1424 frame_->replaceMisspelledRange(text);
1427 void RenderFrameImpl::OnCSSInsertRequest(const std::string& css) {
1428 frame_->document().insertStyleSheet(WebString::fromUTF8(css));
1431 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1432 const base::string16& jscript,
1433 int id,
1434 bool notify_result) {
1435 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1436 TRACE_EVENT_SCOPE_THREAD);
1438 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
1439 v8::Handle<v8::Value> result =
1440 frame_->executeScriptAndReturnValue(WebScriptSource(jscript));
1442 HandleJavascriptExecutionResult(jscript, id, notify_result, result);
1445 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1446 const base::string16& jscript,
1447 int id,
1448 bool notify_result) {
1449 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1450 TRACE_EVENT_SCOPE_THREAD);
1452 // A bunch of tests expect to run code in the context of a user gesture, which
1453 // can grant additional privileges (e.g. the ability to create popups).
1454 blink::WebScopedUserGesture gesture;
1455 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
1456 v8::Handle<v8::Value> result =
1457 frame_->executeScriptAndReturnValue(WebScriptSource(jscript));
1459 HandleJavascriptExecutionResult(jscript, id, notify_result, result);
1462 void RenderFrameImpl::HandleJavascriptExecutionResult(
1463 const base::string16& jscript,
1464 int id,
1465 bool notify_result,
1466 v8::Handle<v8::Value> result) {
1467 if (notify_result) {
1468 base::ListValue list;
1469 if (!result.IsEmpty()) {
1470 v8::Local<v8::Context> context = frame_->mainWorldScriptContext();
1471 v8::Context::Scope context_scope(context);
1472 V8ValueConverterImpl converter;
1473 converter.SetDateAllowed(true);
1474 converter.SetRegExpAllowed(true);
1475 base::Value* result_value = converter.FromV8Value(result, context);
1476 list.Set(0, result_value ? result_value : base::Value::CreateNullValue());
1477 } else {
1478 list.Set(0, base::Value::CreateNullValue());
1480 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_, id, list));
1484 void RenderFrameImpl::OnVisualStateRequest(uint64 id) {
1485 GetRenderWidget()->QueueMessage(
1486 new FrameHostMsg_VisualStateResponse(routing_id_, id),
1487 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE);
1490 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start, int end) {
1491 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1492 if (!GetRenderWidget()->ShouldHandleImeEvent())
1493 return;
1494 ImeEventGuard guard(GetRenderWidget());
1495 frame_->setEditableSelectionOffsets(start, end);
1498 void RenderFrameImpl::OnSetCompositionFromExistingText(
1499 int start, int end,
1500 const std::vector<blink::WebCompositionUnderline>& underlines) {
1501 if (!GetRenderWidget()->ShouldHandleImeEvent())
1502 return;
1503 ImeEventGuard guard(GetRenderWidget());
1504 frame_->setCompositionFromExistingText(start, end, underlines);
1507 void RenderFrameImpl::OnExecuteNoValueEditCommand(const std::string& name) {
1508 frame_->executeCommand(WebString::fromUTF8(name), GetFocusedElement());
1511 void RenderFrameImpl::OnExtendSelectionAndDelete(int before, int after) {
1512 if (!GetRenderWidget()->ShouldHandleImeEvent())
1513 return;
1514 ImeEventGuard guard(GetRenderWidget());
1515 frame_->extendSelectionAndDelete(before, after);
1518 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode) {
1519 if (accessibility_mode_ == new_mode)
1520 return;
1521 accessibility_mode_ = new_mode;
1522 if (renderer_accessibility_) {
1523 // Note: this isn't called automatically by the destructor because
1524 // there'd be no point in calling it in frame teardown, only if there's
1525 // an accessibility mode change but the frame is persisting.
1526 renderer_accessibility_->DisableAccessibility();
1528 delete renderer_accessibility_;
1529 renderer_accessibility_ = NULL;
1531 if (accessibility_mode_ == AccessibilityModeOff)
1532 return;
1534 if (accessibility_mode_ & AccessibilityModeFlagFullTree)
1535 renderer_accessibility_ = new RendererAccessibility(this);
1538 void RenderFrameImpl::OnDisownOpener() {
1539 // TODO(creis): We should only see this for main frames for now. To support
1540 // disowning the opener on subframes, we will need to move WebContentsImpl's
1541 // opener_ to FrameTreeNode.
1542 CHECK(!frame_->parent());
1544 if (frame_->opener())
1545 frame_->setOpener(NULL);
1548 #if defined(OS_ANDROID)
1549 void RenderFrameImpl::OnSelectPopupMenuItems(
1550 bool canceled,
1551 const std::vector<int>& selected_indices) {
1552 // It is possible to receive more than one of these calls if the user presses
1553 // a select faster than it takes for the show-select-popup IPC message to make
1554 // it to the browser UI thread. Ignore the extra-messages.
1555 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1556 if (!external_popup_menu_)
1557 return;
1559 external_popup_menu_->DidSelectItems(canceled, selected_indices);
1560 external_popup_menu_.reset();
1562 #endif
1564 #if defined(OS_MACOSX)
1565 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index) {
1566 if (external_popup_menu_ == NULL)
1567 return;
1568 external_popup_menu_->DidSelectItem(selected_index);
1569 external_popup_menu_.reset();
1571 #endif
1573 void RenderFrameImpl::OnReload(bool ignore_cache) {
1574 frame_->reload(ignore_cache);
1577 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length) {
1578 blink::WebSurroundingText surroundingText;
1579 surroundingText.initialize(frame_->selectionRange(), max_length);
1581 if (surroundingText.isNull()) {
1582 // |surroundingText| might not be correctly initialized, for example if
1583 // |frame_->selectionRange().isNull()|, in other words, if there was no
1584 // selection.
1585 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1586 routing_id_, base::string16(), 0, 0));
1587 return;
1590 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1591 routing_id_,
1592 surroundingText.textContent(),
1593 surroundingText.startOffsetInTextContent(),
1594 surroundingText.endOffsetInTextContent()));
1597 void RenderFrameImpl::OnAddStyleSheetByURL(const std::string& url) {
1598 frame_->addStyleSheetByURL(WebString::fromUTF8(url));
1601 void RenderFrameImpl::OnSetupTransitionView(const std::string& markup) {
1602 frame_->document().setIsTransitionDocument(true);
1603 frame_->navigateToSandboxedMarkup(WebData(markup.data(), markup.length()));
1606 void RenderFrameImpl::OnBeginExitTransition(const std::string& css_selector,
1607 bool exit_to_native_app) {
1608 frame_->document().setIsTransitionDocument(true);
1609 frame_->document().beginExitTransition(WebString::fromUTF8(css_selector),
1610 exit_to_native_app);
1613 void RenderFrameImpl::OnRevertExitTransition() {
1614 frame_->document().setIsTransitionDocument(false);
1615 frame_->document().revertExitTransition();
1618 void RenderFrameImpl::OnHideTransitionElements(
1619 const std::string& css_selector) {
1620 frame_->document().hideTransitionElements(WebString::fromUTF8(css_selector));
1623 void RenderFrameImpl::OnShowTransitionElements(
1624 const std::string& css_selector) {
1625 frame_->document().showTransitionElements(WebString::fromUTF8(css_selector));
1628 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type,
1629 const base::string16& message,
1630 const base::string16& default_value,
1631 const GURL& frame_url,
1632 base::string16* result) {
1633 // Don't allow further dialogs if we are waiting to swap out, since the
1634 // PageGroupLoadDeferrer in our stack prevents it.
1635 if (render_view()->suppress_dialogs_until_swap_out_)
1636 return false;
1638 bool success = false;
1639 base::string16 result_temp;
1640 if (!result)
1641 result = &result_temp;
1643 render_view()->SendAndRunNestedMessageLoop(
1644 new FrameHostMsg_RunJavaScriptMessage(
1645 routing_id_, message, default_value, frame_url, type, &success,
1646 result));
1647 return success;
1650 void RenderFrameImpl::LoadNavigationErrorPage(
1651 const WebURLRequest& failed_request,
1652 const WebURLError& error,
1653 bool replace) {
1654 std::string error_html;
1655 GetContentClient()->renderer()->GetNavigationErrorStrings(
1656 render_view(), frame_, failed_request, error, &error_html, NULL);
1658 frame_->loadHTMLString(error_html,
1659 GURL(kUnreachableWebDataURL),
1660 error.unreachableURL,
1661 replace);
1664 void RenderFrameImpl::DidCommitCompositorFrame() {
1665 if (BrowserPluginManager::Get())
1666 BrowserPluginManager::Get()->DidCommitCompositorFrame(GetRoutingID());
1667 FOR_EACH_OBSERVER(
1668 RenderFrameObserver, observers_, DidCommitCompositorFrame());
1671 RenderView* RenderFrameImpl::GetRenderView() {
1672 return render_view_.get();
1675 int RenderFrameImpl::GetRoutingID() {
1676 return routing_id_;
1679 blink::WebLocalFrame* RenderFrameImpl::GetWebFrame() {
1680 DCHECK(frame_);
1681 return frame_;
1684 WebElement RenderFrameImpl::GetFocusedElement() const {
1685 WebDocument doc = frame_->document();
1686 if (!doc.isNull())
1687 return doc.focusedElement();
1689 return WebElement();
1692 WebPreferences& RenderFrameImpl::GetWebkitPreferences() {
1693 return render_view_->GetWebkitPreferences();
1696 int RenderFrameImpl::ShowContextMenu(ContextMenuClient* client,
1697 const ContextMenuParams& params) {
1698 DCHECK(client); // A null client means "internal" when we issue callbacks.
1699 ContextMenuParams our_params(params);
1700 our_params.custom_context.request_id = pending_context_menus_.Add(client);
1701 Send(new FrameHostMsg_ContextMenu(routing_id_, our_params));
1702 return our_params.custom_context.request_id;
1705 void RenderFrameImpl::CancelContextMenu(int request_id) {
1706 DCHECK(pending_context_menus_.Lookup(request_id));
1707 pending_context_menus_.Remove(request_id);
1710 blink::WebNode RenderFrameImpl::GetContextMenuNode() const {
1711 return context_menu_node_;
1714 blink::WebPlugin* RenderFrameImpl::CreatePlugin(
1715 blink::WebFrame* frame,
1716 const WebPluginInfo& info,
1717 const blink::WebPluginParams& params,
1718 scoped_ptr<content::PluginInstanceThrottler> throttler) {
1719 DCHECK_EQ(frame_, frame);
1720 #if defined(ENABLE_PLUGINS)
1721 if (info.type == WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN) {
1722 scoped_ptr<BrowserPluginDelegate> browser_plugin_delegate(
1723 GetContentClient()->renderer()->CreateBrowserPluginDelegate(
1724 this, params.mimeType.utf8(), GURL(params.url)));
1725 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1726 this, browser_plugin_delegate.Pass());
1729 bool pepper_plugin_was_registered = false;
1730 scoped_refptr<PluginModule> pepper_module(PluginModule::Create(
1731 this, info, &pepper_plugin_was_registered));
1732 if (pepper_plugin_was_registered) {
1733 if (pepper_module.get()) {
1734 return new PepperWebPluginImpl(
1735 pepper_module.get(), params, this,
1736 make_scoped_ptr(
1737 static_cast<PluginInstanceThrottlerImpl*>(throttler.release())));
1740 #if defined(OS_CHROMEOS)
1741 LOG(WARNING) << "Pepper module/plugin creation failed.";
1742 return NULL;
1743 #else
1744 // TODO(jam): change to take RenderFrame.
1745 return new WebPluginImpl(frame, params, info.path, render_view_, this);
1746 #endif
1747 #else
1748 return NULL;
1749 #endif
1752 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame* frame,
1753 const blink::WebURLRequest& request,
1754 blink::WebNavigationPolicy policy) {
1755 DCHECK(!frame_ || frame_ == frame);
1756 loadURLExternally(frame, request, policy, WebString());
1759 void RenderFrameImpl::ExecuteJavaScript(const base::string16& javascript) {
1760 OnJavaScriptExecuteRequest(javascript, 0, false);
1763 ServiceRegistry* RenderFrameImpl::GetServiceRegistry() {
1764 return &service_registry_;
1767 #if defined(ENABLE_PLUGINS)
1768 void RenderFrameImpl::RegisterPeripheralPlugin(
1769 const GURL& content_origin,
1770 const base::Closure& unthrottle_callback) {
1771 return plugin_power_saver_helper_->RegisterPeripheralPlugin(
1772 content_origin, unthrottle_callback);
1774 #endif // defined(ENABLE_PLUGINS)
1776 bool RenderFrameImpl::IsFTPDirectoryListing() {
1777 WebURLResponseExtraDataImpl* extra_data =
1778 GetExtraDataFromResponse(frame_->dataSource()->response());
1779 return extra_data ? extra_data->is_ftp_directory_listing() : false;
1782 void RenderFrameImpl::AttachGuest(int element_instance_id) {
1783 BrowserPluginManager::Get()->Attach(element_instance_id);
1786 void RenderFrameImpl::DetachGuest(int element_instance_id) {
1787 BrowserPluginManager::Get()->Detach(element_instance_id);
1790 void RenderFrameImpl::SetSelectedText(const base::string16& selection_text,
1791 size_t offset,
1792 const gfx::Range& range) {
1793 // Use the routing id of Render Widget Host.
1794 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1795 selection_text,
1796 offset,
1797 range));
1800 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1801 v8::Isolate* isolate,
1802 v8::Handle<v8::Context> context) {
1803 gin::ModuleRegistry* registry = gin::ModuleRegistry::From(context);
1804 if (registry->available_modules().count(mojo::js::Core::kModuleName))
1805 return;
1807 v8::HandleScope handle_scope(isolate);
1808 registry->AddBuiltinModule(
1809 isolate, mojo::js::Core::kModuleName, mojo::js::Core::GetModule(isolate));
1810 registry->AddBuiltinModule(isolate,
1811 mojo::js::Support::kModuleName,
1812 mojo::js::Support::GetModule(isolate));
1813 registry->AddBuiltinModule(
1814 isolate,
1815 ServiceRegistryJsWrapper::kModuleName,
1816 ServiceRegistryJsWrapper::Create(isolate, &service_registry_).ToV8());
1819 // blink::WebFrameClient implementation ----------------------------------------
1821 blink::WebPluginPlaceholder* RenderFrameImpl::createPluginPlaceholder(
1822 blink::WebLocalFrame* frame,
1823 const blink::WebPluginParams& params) {
1824 DCHECK_EQ(frame_, frame);
1825 return GetContentClient()
1826 ->renderer()
1827 ->CreatePluginPlaceholder(this, frame, params)
1828 .release();
1831 blink::WebPlugin* RenderFrameImpl::createPlugin(
1832 blink::WebLocalFrame* frame,
1833 const blink::WebPluginParams& params) {
1834 DCHECK_EQ(frame_, frame);
1835 blink::WebPlugin* plugin = NULL;
1836 if (GetContentClient()->renderer()->OverrideCreatePlugin(
1837 this, frame, params, &plugin)) {
1838 return plugin;
1841 if (base::UTF16ToUTF8(params.mimeType) == kBrowserPluginMimeType) {
1842 scoped_ptr<BrowserPluginDelegate> browser_plugin_delegate(
1843 GetContentClient()->renderer()->CreateBrowserPluginDelegate(this,
1844 kBrowserPluginMimeType, GURL(params.url)));
1845 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1846 this, browser_plugin_delegate.Pass());
1849 #if defined(ENABLE_PLUGINS)
1850 WebPluginInfo info;
1851 std::string mime_type;
1852 bool found = false;
1853 Send(new FrameHostMsg_GetPluginInfo(
1854 routing_id_, params.url, frame->top()->document().url(),
1855 params.mimeType.utf8(), &found, &info, &mime_type));
1856 if (!found)
1857 return NULL;
1859 WebPluginParams params_to_use = params;
1860 params_to_use.mimeType = WebString::fromUTF8(mime_type);
1861 return CreatePlugin(frame, info, params_to_use, nullptr /* throttler */);
1862 #else
1863 return NULL;
1864 #endif // defined(ENABLE_PLUGINS)
1867 blink::WebMediaPlayer* RenderFrameImpl::createMediaPlayer(
1868 blink::WebLocalFrame* frame,
1869 const blink::WebURL& url,
1870 blink::WebMediaPlayerClient* client) {
1871 return createMediaPlayer(frame, url, client, nullptr);
1874 blink::WebMediaPlayer* RenderFrameImpl::createMediaPlayer(
1875 blink::WebLocalFrame* frame,
1876 const blink::WebURL& url,
1877 blink::WebMediaPlayerClient* client,
1878 blink::WebContentDecryptionModule* initial_cdm) {
1879 #if defined(VIDEO_HOLE)
1880 if (!contains_media_player_) {
1881 render_view_->RegisterVideoHoleFrame(this);
1882 contains_media_player_ = true;
1884 #endif // defined(VIDEO_HOLE)
1886 blink::WebMediaStream web_stream(
1887 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url));
1888 if (!web_stream.isNull())
1889 return CreateWebMediaPlayerForMediaStream(url, client);
1891 if (!media_permission_dispatcher_)
1892 media_permission_dispatcher_ = new MediaPermissionDispatcher(this);
1894 #if defined(OS_ANDROID)
1895 return CreateAndroidWebMediaPlayer(url, client, media_permission_dispatcher_,
1896 initial_cdm);
1897 #else
1898 scoped_refptr<media::MediaLog> media_log(new RenderMediaLog());
1901 RenderThreadImpl* render_thread = RenderThreadImpl::current();
1902 media::WebMediaPlayerParams params(
1903 base::Bind(&ContentRendererClient::DeferMediaLoad,
1904 base::Unretained(GetContentClient()->renderer()),
1905 static_cast<RenderFrame*>(this)),
1906 render_thread->GetAudioRendererMixerManager()->CreateInput(
1907 render_view_->routing_id_, routing_id_),
1908 media_log, render_thread->GetMediaThreadTaskRunner(),
1909 render_thread->compositor_message_loop_proxy(),
1910 base::Bind(&GetSharedMainThreadContext3D), media_permission_dispatcher_,
1911 initial_cdm);
1913 #if defined(ENABLE_PEPPER_CDMS)
1914 scoped_ptr<media::CdmFactory> cdm_factory(
1915 new RenderCdmFactory(base::Bind(&PepperCdmWrapperImpl::Create, frame)));
1916 #elif defined(ENABLE_BROWSER_CDMS)
1917 scoped_ptr<media::CdmFactory> cdm_factory(
1918 new RenderCdmFactory(GetCdmManager()));
1919 #else
1920 scoped_ptr<media::CdmFactory> cdm_factory(new RenderCdmFactory());
1921 #endif
1923 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
1924 scoped_ptr<media::RendererFactory> media_renderer_factory(
1925 new media::MojoRendererFactory(make_scoped_ptr(
1926 new MediaRendererServiceProvider(GetServiceRegistry()))));
1927 #else
1928 scoped_ptr<media::RendererFactory> media_renderer_factory =
1929 GetContentClient()->renderer()->CreateMediaRendererFactory(this,
1930 media_log);
1932 if (!media_renderer_factory.get()) {
1933 media_renderer_factory.reset(new media::DefaultRendererFactory(
1934 media_log, render_thread->GetGpuFactories(),
1935 *render_thread->GetAudioHardwareConfig()));
1937 #endif // defined(ENABLE_MEDIA_MOJO_RENDERER)
1939 return new media::WebMediaPlayerImpl(
1940 frame, client, weak_factory_.GetWeakPtr(), media_renderer_factory.Pass(),
1941 cdm_factory.Pass(), params);
1942 #endif // defined(OS_ANDROID)
1945 blink::WebApplicationCacheHost* RenderFrameImpl::createApplicationCacheHost(
1946 blink::WebLocalFrame* frame,
1947 blink::WebApplicationCacheHostClient* client) {
1948 if (!frame || !frame->view())
1949 return NULL;
1950 DCHECK(!frame_ || frame_ == frame);
1951 return new RendererWebApplicationCacheHostImpl(
1952 RenderViewImpl::FromWebView(frame->view()), client,
1953 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
1956 blink::WebWorkerPermissionClientProxy*
1957 RenderFrameImpl::createWorkerPermissionClientProxy(
1958 blink::WebLocalFrame* frame) {
1959 if (!frame || !frame->view())
1960 return NULL;
1961 DCHECK(!frame_ || frame_ == frame);
1962 return GetContentClient()->renderer()->CreateWorkerPermissionClientProxy(
1963 this, frame);
1966 WebExternalPopupMenu* RenderFrameImpl::createExternalPopupMenu(
1967 const WebPopupMenuInfo& popup_menu_info,
1968 WebExternalPopupMenuClient* popup_menu_client) {
1969 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1970 // An IPC message is sent to the browser to build and display the actual
1971 // popup. The user could have time to click a different select by the time
1972 // the popup is shown. In that case external_popup_menu_ is non NULL.
1973 // By returning NULL in that case, we instruct Blink to cancel that new
1974 // popup. So from the user perspective, only the first one will show, and
1975 // will have to close the first one before another one can be shown.
1976 if (external_popup_menu_)
1977 return NULL;
1978 external_popup_menu_.reset(
1979 new ExternalPopupMenu(this, popup_menu_info, popup_menu_client));
1980 if (render_view_->screen_metrics_emulator_) {
1981 render_view_->SetExternalPopupOriginAdjustmentsForEmulation(
1982 external_popup_menu_.get(),
1983 render_view_->screen_metrics_emulator_.get());
1985 return external_popup_menu_.get();
1986 #else
1987 return NULL;
1988 #endif
1991 blink::WebCookieJar* RenderFrameImpl::cookieJar(blink::WebLocalFrame* frame) {
1992 DCHECK(!frame_ || frame_ == frame);
1993 return &cookie_jar_;
1996 blink::WebServiceWorkerProvider* RenderFrameImpl::createServiceWorkerProvider(
1997 blink::WebLocalFrame* frame) {
1998 DCHECK(!frame_ || frame_ == frame);
1999 // At this point we should have non-null data source.
2000 DCHECK(frame->dataSource());
2001 if (!ChildThreadImpl::current())
2002 return NULL; // May be null in some tests.
2003 ServiceWorkerNetworkProvider* provider =
2004 ServiceWorkerNetworkProvider::FromDocumentState(
2005 DocumentState::FromDataSource(frame->dataSource()));
2006 return new WebServiceWorkerProviderImpl(
2007 ChildThreadImpl::current()->thread_safe_sender(),
2008 provider ? provider->context() : NULL);
2011 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame* frame) {
2012 DCHECK(!frame_ || frame_ == frame);
2013 // If the request hasn't yet committed, notify the browser process that it is
2014 // no longer safe to show the pending URL of the main frame, since a URL spoof
2015 // is now possible. (If the request has committed, the browser already knows.)
2016 if (!frame->parent()) {
2017 DocumentState* document_state =
2018 DocumentState::FromDataSource(frame->dataSource());
2019 NavigationState* navigation_state = document_state->navigation_state();
2021 if (!navigation_state->request_committed()) {
2022 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_));
2027 blink::WebFrame* RenderFrameImpl::createChildFrame(
2028 blink::WebLocalFrame* parent,
2029 const blink::WebString& name,
2030 blink::WebSandboxFlags sandbox_flags) {
2031 // Synchronously notify the browser of a child frame creation to get the
2032 // routing_id for the RenderFrame.
2033 int child_routing_id = MSG_ROUTING_NONE;
2034 Send(new FrameHostMsg_CreateChildFrame(
2035 routing_id_, base::UTF16ToUTF8(name),
2036 WebToContentSandboxFlags(sandbox_flags), &child_routing_id));
2038 // Allocation of routing id failed, so we can't create a child frame. This can
2039 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
2040 // out state or synchronous IPC message above has failed.
2041 if (child_routing_id == MSG_ROUTING_NONE) {
2042 NOTREACHED() << "Failed to allocate routing id for child frame.";
2043 return nullptr;
2046 // Create the RenderFrame and WebLocalFrame, linking the two.
2047 RenderFrameImpl* child_render_frame = RenderFrameImpl::Create(
2048 render_view_.get(), child_routing_id);
2049 blink::WebLocalFrame* web_frame = WebLocalFrame::create(child_render_frame);
2050 child_render_frame->SetWebFrame(web_frame);
2052 // Add the frame to the frame tree and initialize it.
2053 parent->appendChild(web_frame);
2054 child_render_frame->Initialize();
2056 return web_frame;
2059 void RenderFrameImpl::didDisownOpener(blink::WebLocalFrame* frame) {
2060 DCHECK(!frame_ || frame_ == frame);
2061 // We only need to notify the browser if the active, top-level frame clears
2062 // its opener. We can ignore cases where a swapped out frame clears its
2063 // opener after hearing about it from the browser, and the browser does not
2064 // (yet) care about subframe openers.
2065 if (is_swapped_out_ || frame->parent())
2066 return;
2068 // Notify WebContents and all its swapped out RenderViews.
2069 Send(new FrameHostMsg_DidDisownOpener(routing_id_));
2072 void RenderFrameImpl::frameDetached(blink::WebFrame* frame) {
2073 // NOTE: This function is called on the frame that is being detached and not
2074 // the parent frame. This is different from createChildFrame() which is
2075 // called on the parent frame.
2076 CHECK(!is_detaching_);
2077 DCHECK(!frame_ || frame_ == frame);
2079 bool is_subframe = !!frame->parent();
2081 Send(new FrameHostMsg_Detach(routing_id_));
2083 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
2084 // sent before setting |is_detaching_| to true. In contrast, Observers
2085 // should only be notified afterwards so they cannot call back into here and
2086 // have IPCs fired off.
2087 is_detaching_ = true;
2089 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FrameDetached());
2090 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2091 FrameDetached(frame));
2093 // We need to clean up subframes by removing them from the map and deleting
2094 // the RenderFrameImpl. In contrast, the main frame is owned by its
2095 // containing RenderViewHost (so that they have the same lifetime), so only
2096 // removal from the map is needed and no deletion.
2097 FrameMap::iterator it = g_frame_map.Get().find(frame);
2098 CHECK(it != g_frame_map.Get().end());
2099 CHECK_EQ(it->second, this);
2100 g_frame_map.Get().erase(it);
2102 if (is_subframe)
2103 frame->parent()->removeChild(frame);
2105 // |frame| is invalid after here.
2106 frame->close();
2108 if (is_subframe) {
2109 delete this;
2110 // Object is invalid after this point.
2114 void RenderFrameImpl::frameFocused() {
2115 Send(new FrameHostMsg_FrameFocused(routing_id_));
2118 void RenderFrameImpl::willClose(blink::WebFrame* frame) {
2119 DCHECK(!frame_ || frame_ == frame);
2121 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FrameWillClose());
2122 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2123 FrameWillClose(frame));
2126 void RenderFrameImpl::didChangeName(blink::WebLocalFrame* frame,
2127 const blink::WebString& name) {
2128 DCHECK(!frame_ || frame_ == frame);
2129 if (!render_view_->renderer_preferences_.report_frame_name_changes)
2130 return;
2132 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeName(name));
2135 void RenderFrameImpl::didMatchCSS(
2136 blink::WebLocalFrame* frame,
2137 const blink::WebVector<blink::WebString>& newly_matching_selectors,
2138 const blink::WebVector<blink::WebString>& stopped_matching_selectors) {
2139 DCHECK(!frame_ || frame_ == frame);
2141 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2142 DidMatchCSS(frame,
2143 newly_matching_selectors,
2144 stopped_matching_selectors));
2147 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2148 const blink::WebString& source) {
2149 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2150 source);
2153 void RenderFrameImpl::didAddMessageToConsole(
2154 const blink::WebConsoleMessage& message,
2155 const blink::WebString& source_name,
2156 unsigned source_line,
2157 const blink::WebString& stack_trace) {
2158 logging::LogSeverity log_severity = logging::LOG_VERBOSE;
2159 switch (message.level) {
2160 case blink::WebConsoleMessage::LevelDebug:
2161 log_severity = logging::LOG_VERBOSE;
2162 break;
2163 case blink::WebConsoleMessage::LevelLog:
2164 case blink::WebConsoleMessage::LevelInfo:
2165 log_severity = logging::LOG_INFO;
2166 break;
2167 case blink::WebConsoleMessage::LevelWarning:
2168 log_severity = logging::LOG_WARNING;
2169 break;
2170 case blink::WebConsoleMessage::LevelError:
2171 log_severity = logging::LOG_ERROR;
2172 break;
2173 default:
2174 NOTREACHED();
2177 if (shouldReportDetailedMessageForSource(source_name)) {
2178 FOR_EACH_OBSERVER(
2179 RenderFrameObserver, observers_,
2180 DetailedConsoleMessageAdded(message.text,
2181 source_name,
2182 stack_trace,
2183 source_line,
2184 static_cast<int32>(log_severity)));
2187 Send(new FrameHostMsg_AddMessageToConsole(routing_id_,
2188 static_cast<int32>(log_severity),
2189 message.text,
2190 static_cast<int32>(source_line),
2191 source_name));
2194 void RenderFrameImpl::loadURLExternally(
2195 blink::WebLocalFrame* frame,
2196 const blink::WebURLRequest& request,
2197 blink::WebNavigationPolicy policy,
2198 const blink::WebString& suggested_name) {
2199 DCHECK(!frame_ || frame_ == frame);
2200 Referrer referrer(RenderViewImpl::GetReferrerFromRequest(frame, request));
2201 if (policy == blink::WebNavigationPolicyDownload) {
2202 render_view_->Send(new ViewHostMsg_DownloadUrl(render_view_->GetRoutingID(),
2203 request.url(), referrer,
2204 suggested_name));
2205 } else {
2206 OpenURL(frame, request.url(), referrer, policy);
2210 blink::WebNavigationPolicy RenderFrameImpl::decidePolicyForNavigation(
2211 const NavigationPolicyInfo& info) {
2212 DCHECK(!frame_ || frame_ == info.frame);
2213 return DecidePolicyForNavigation(this, info);
2216 blink::WebHistoryItem RenderFrameImpl::historyItemForNewChildFrame(
2217 blink::WebFrame* frame) {
2218 DCHECK(!frame_ || frame_ == frame);
2219 return render_view_->history_controller()->GetItemForNewChildFrame(this);
2222 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame* frame,
2223 const blink::WebFormElement& form) {
2224 DCHECK(!frame_ || frame_ == frame);
2226 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WillSendSubmitEvent(form));
2229 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame* frame,
2230 const blink::WebFormElement& form) {
2231 DCHECK(!frame_ || frame_ == frame);
2232 DocumentState* document_state =
2233 DocumentState::FromDataSource(frame->provisionalDataSource());
2234 NavigationState* navigation_state = document_state->navigation_state();
2235 InternalDocumentStateData* internal_data =
2236 InternalDocumentStateData::FromDocumentState(document_state);
2238 if (ui::PageTransitionCoreTypeIs(navigation_state->transition_type(),
2239 ui::PAGE_TRANSITION_LINK)) {
2240 navigation_state->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT);
2243 // Save these to be processed when the ensuing navigation is committed.
2244 WebSearchableFormData web_searchable_form_data(form);
2245 internal_data->set_searchable_form_url(web_searchable_form_data.url());
2246 internal_data->set_searchable_form_encoding(
2247 web_searchable_form_data.encoding().utf8());
2249 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WillSubmitForm(form));
2252 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame* frame,
2253 blink::WebDataSource* datasource) {
2254 DCHECK(!frame_ || frame_ == frame);
2256 // TODO(nasko): Move implementation here. Needed state:
2257 // * pending_navigation_params_
2258 // * webview
2259 // Needed methods:
2260 // * PopulateDocumentStateFromPending
2261 // * CreateNavigationStateFromPending
2262 render_view_->didCreateDataSource(frame, datasource);
2264 // Create the serviceworker's per-document network observing object if it
2265 // does not exist (When navigation happens within a page, the provider already
2266 // exists).
2267 if (!ServiceWorkerNetworkProvider::FromDocumentState(
2268 DocumentState::FromDataSource(datasource))) {
2269 scoped_ptr<ServiceWorkerNetworkProvider>
2270 network_provider(new ServiceWorkerNetworkProvider(
2271 routing_id_, SERVICE_WORKER_PROVIDER_FOR_CONTROLLEE));
2272 ServiceWorkerNetworkProvider::AttachToDocumentState(
2273 DocumentState::FromDataSource(datasource),
2274 network_provider.Pass());
2278 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame* frame,
2279 bool is_transition_navigation,
2280 double triggering_event_time) {
2281 DCHECK(!frame_ || frame_ == frame);
2282 WebDataSource* ds = frame->provisionalDataSource();
2284 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2285 // callback is invoked.
2286 if (!ds)
2287 return;
2289 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2290 "id", routing_id_, "url", ds->request().url().string().utf8());
2291 DocumentState* document_state = DocumentState::FromDataSource(ds);
2293 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2294 CHECK((ds->request().url() != GURL(kSwappedOutURL)) ||
2295 is_swapped_out_) <<
2296 "Heard swappedout:// when not swapped out.";
2298 // Update the request time if WebKit has better knowledge of it.
2299 if (document_state->request_time().is_null() &&
2300 triggering_event_time != 0.0) {
2301 document_state->set_request_time(Time::FromDoubleT(triggering_event_time));
2304 // Start time is only set after request time.
2305 document_state->set_start_load_time(Time::Now());
2307 bool is_top_most = !frame->parent();
2308 if (is_top_most) {
2309 render_view_->set_navigation_gesture(
2310 WebUserGestureIndicator::isProcessingUserGesture() ?
2311 NavigationGestureUser : NavigationGestureAuto);
2312 } else if (ds->replacesCurrentHistoryItem()) {
2313 // Subframe navigations that don't add session history items must be
2314 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2315 // handle loading of error pages.
2316 document_state->navigation_state()->set_transition_type(
2317 ui::PAGE_TRANSITION_AUTO_SUBFRAME);
2320 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2321 DidStartProvisionalLoad(frame));
2322 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidStartProvisionalLoad());
2324 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2325 routing_id_, ds->request().url(), is_transition_navigation));
2328 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2329 blink::WebLocalFrame* frame) {
2330 DCHECK(!frame_ || frame_ == frame);
2331 render_view_->history_controller()->RemoveChildrenForRedirect(this);
2334 void RenderFrameImpl::didFailProvisionalLoad(blink::WebLocalFrame* frame,
2335 const blink::WebURLError& error) {
2336 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2337 "id", routing_id_);
2338 DCHECK(!frame_ || frame_ == frame);
2339 WebDataSource* ds = frame->provisionalDataSource();
2340 DCHECK(ds);
2342 const WebURLRequest& failed_request = ds->request();
2344 // Notify the browser that we failed a provisional load with an error.
2346 // Note: It is important this notification occur before DidStopLoading so the
2347 // SSL manager can react to the provisional load failure before being
2348 // notified the load stopped.
2350 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2351 DidFailProvisionalLoad(frame, error));
2352 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
2353 DidFailProvisionalLoad(error));
2355 bool show_repost_interstitial =
2356 (error.reason == net::ERR_CACHE_MISS &&
2357 EqualsASCII(failed_request.httpMethod(), "POST"));
2359 FrameHostMsg_DidFailProvisionalLoadWithError_Params params;
2360 params.error_code = error.reason;
2361 GetContentClient()->renderer()->GetNavigationErrorStrings(
2362 render_view_.get(),
2363 frame,
2364 failed_request,
2365 error,
2366 NULL,
2367 &params.error_description);
2368 params.url = error.unreachableURL;
2369 params.showing_repost_interstitial = show_repost_interstitial;
2370 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(
2371 routing_id_, params));
2373 // Don't display an error page if this is simply a cancelled load. Aside
2374 // from being dumb, WebCore doesn't expect it and it will cause a crash.
2375 if (error.reason == net::ERR_ABORTED)
2376 return;
2378 // Don't display "client blocked" error page if browser has asked us not to.
2379 if (error.reason == net::ERR_BLOCKED_BY_CLIENT &&
2380 render_view_->renderer_preferences_.disable_client_blocked_error_page) {
2381 return;
2384 // Allow the embedder to suppress an error page.
2385 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(this,
2386 error.unreachableURL)) {
2387 return;
2390 if (RenderThreadImpl::current() &&
2391 RenderThreadImpl::current()->layout_test_mode()) {
2392 return;
2395 // Make sure we never show errors in view source mode.
2396 frame->enableViewSourceMode(false);
2398 DocumentState* document_state = DocumentState::FromDataSource(ds);
2399 NavigationState* navigation_state = document_state->navigation_state();
2401 // If this is a failed back/forward/reload navigation, then we need to do a
2402 // 'replace' load. This is necessary to avoid messing up session history.
2403 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2404 // as session history is concerned.
2406 // AUTO_SUBFRAME loads should always be treated as loads that do not advance
2407 // the page id.
2409 // TODO(davidben): This should also take the failed navigation's replacement
2410 // state into account, if a location.replace() failed.
2411 bool replace =
2412 navigation_state->pending_page_id() != -1 ||
2413 ui::PageTransitionCoreTypeIs(navigation_state->transition_type(),
2414 ui::PAGE_TRANSITION_AUTO_SUBFRAME);
2416 // If we failed on a browser initiated request, then make sure that our error
2417 // page load is regarded as the same browser initiated request.
2418 if (!navigation_state->is_content_initiated()) {
2419 render_view_->pending_navigation_params_.reset(
2420 new FrameMsg_Navigate_Params);
2421 render_view_->pending_navigation_params_->page_id =
2422 navigation_state->pending_page_id();
2423 render_view_->pending_navigation_params_->pending_history_list_offset =
2424 navigation_state->pending_history_list_offset();
2425 render_view_->pending_navigation_params_->should_clear_history_list =
2426 navigation_state->history_list_was_cleared();
2427 render_view_->pending_navigation_params_->common_params.transition =
2428 navigation_state->transition_type();
2429 render_view_->pending_navigation_params_->request_time =
2430 document_state->request_time();
2431 render_view_->pending_navigation_params_->should_replace_current_entry =
2432 replace;
2435 // Load an error page.
2436 LoadNavigationErrorPage(failed_request, error, replace);
2439 void RenderFrameImpl::didCommitProvisionalLoad(
2440 blink::WebLocalFrame* frame,
2441 const blink::WebHistoryItem& item,
2442 blink::WebHistoryCommitType commit_type) {
2443 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2444 "id", routing_id_,
2445 "url", GetLoadingUrl().possibly_invalid_spec());
2446 DCHECK(!frame_ || frame_ == frame);
2447 DocumentState* document_state =
2448 DocumentState::FromDataSource(frame->dataSource());
2449 NavigationState* navigation_state = document_state->navigation_state();
2451 if (proxy_routing_id_ != MSG_ROUTING_NONE) {
2452 RenderFrameProxy* proxy =
2453 RenderFrameProxy::FromRoutingID(proxy_routing_id_);
2454 CHECK(proxy);
2455 proxy->web_frame()->swap(frame_);
2456 proxy_routing_id_ = MSG_ROUTING_NONE;
2459 // When we perform a new navigation, we need to update the last committed
2460 // session history entry with state for the page we are leaving. Do this
2461 // before updating the HistoryController state.
2462 render_view_->UpdateSessionHistory(frame);
2464 render_view_->history_controller()->UpdateForCommit(this, item, commit_type,
2465 navigation_state->was_within_same_page());
2467 InternalDocumentStateData* internal_data =
2468 InternalDocumentStateData::FromDocumentState(document_state);
2470 if (document_state->commit_load_time().is_null())
2471 document_state->set_commit_load_time(Time::Now());
2473 if (internal_data->must_reset_scroll_and_scale_state()) {
2474 render_view_->webview()->resetScrollAndScaleState();
2475 internal_data->set_must_reset_scroll_and_scale_state(false);
2477 internal_data->set_use_error_page(false);
2479 bool is_new_navigation = commit_type == blink::WebStandardCommit;
2480 if (is_new_navigation) {
2481 // We bump our Page ID to correspond with the new session history entry.
2482 render_view_->page_id_ = render_view_->next_page_id_++;
2484 // Don't update history list values for kSwappedOutURL, since
2485 // we don't want to forget the entry that was there, and since we will
2486 // never come back to kSwappedOutURL. Note that we have to call
2487 // UpdateSessionHistory and update page_id_ even in this case, so that
2488 // the current entry gets a state update and so that we don't send a
2489 // state update to the wrong entry when we swap back in.
2490 DCHECK_IMPLIES(navigation_state->should_replace_current_entry(),
2491 render_view_->history_list_length_ > 0);
2492 if (GetLoadingUrl() != GURL(kSwappedOutURL) &&
2493 !navigation_state->should_replace_current_entry()) {
2494 // Advance our offset in session history, applying the length limit.
2495 // There is now no forward history.
2496 render_view_->history_list_offset_++;
2497 if (render_view_->history_list_offset_ >= kMaxSessionHistoryEntries)
2498 render_view_->history_list_offset_ = kMaxSessionHistoryEntries - 1;
2499 render_view_->history_list_length_ =
2500 render_view_->history_list_offset_ + 1;
2502 } else {
2503 // Inspect the navigation_state on this frame to see if the navigation
2504 // corresponds to a session history navigation... Note: |frame| may or
2505 // may not be the toplevel frame, but for the case of capturing session
2506 // history, the first committed frame suffices. We keep track of whether
2507 // we've seen this commit before so that only capture session history once
2508 // per navigation.
2510 // Note that we need to check if the page ID changed. In the case of a
2511 // reload, the page ID doesn't change, and UpdateSessionHistory gets the
2512 // previous URL and the current page ID, which would be wrong.
2513 if (navigation_state->pending_page_id() != -1 &&
2514 navigation_state->pending_page_id() != render_view_->page_id_ &&
2515 !navigation_state->request_committed()) {
2516 // This is a successful session history navigation!
2517 render_view_->page_id_ = navigation_state->pending_page_id();
2519 render_view_->history_list_offset_ =
2520 navigation_state->pending_history_list_offset();
2524 bool sent = Send(
2525 new FrameHostMsg_DidAssignPageId(routing_id_, render_view_->page_id_));
2526 CHECK(sent); // http://crbug.com/407376
2528 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers_,
2529 DidCommitProvisionalLoad(frame, is_new_navigation));
2530 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
2531 DidCommitProvisionalLoad(
2532 is_new_navigation,
2533 navigation_state->was_within_same_page()));
2535 if (!frame->parent()) { // Only for top frames.
2536 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
2537 if (render_thread_impl) { // Can be NULL in tests.
2538 render_thread_impl->histogram_customizer()->
2539 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2540 RenderViewImpl::GetRenderViewCount());
2544 // Remember that we've already processed this request, so we don't update
2545 // the session history again. We do this regardless of whether this is
2546 // a session history navigation, because if we attempted a session history
2547 // navigation without valid HistoryItem state, WebCore will think it is a
2548 // new navigation.
2549 navigation_state->set_request_committed(true);
2551 SendDidCommitProvisionalLoad(frame, commit_type);
2553 // Check whether we have new encoding name.
2554 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2557 void RenderFrameImpl::didCreateNewDocument(blink::WebLocalFrame* frame) {
2558 DCHECK(!frame_ || frame_ == frame);
2560 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2561 DidCreateNewDocument(frame));
2564 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame* frame) {
2565 DCHECK(!frame_ || frame_ == frame);
2567 int enabled_bindings = render_view_->GetEnabledBindings();
2569 if (enabled_bindings & BINDINGS_POLICY_WEB_UI)
2570 WebUIExtension::Install(frame);
2572 if (enabled_bindings & BINDINGS_POLICY_DOM_AUTOMATION)
2573 DomAutomationController::Install(this, frame);
2575 if (enabled_bindings & BINDINGS_POLICY_STATS_COLLECTION)
2576 StatsCollectionController::Install(frame);
2578 const base::CommandLine& command_line =
2579 *base::CommandLine::ForCurrentProcess();
2581 if (command_line.HasSwitch(cc::switches::kEnableGpuBenchmarking))
2582 GpuBenchmarking::Install(frame);
2584 if (command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
2585 MemoryBenchmarkingExtension::Install(frame);
2587 if (command_line.HasSwitch(switches::kEnableSkiaBenchmarking))
2588 SkiaBenchmarking::Install(frame);
2590 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2591 DidClearWindowObject(frame));
2592 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidClearWindowObject());
2595 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame* frame) {
2596 DCHECK(!frame_ || frame_ == frame);
2598 // Notify the browser about non-blank documents loading in the top frame.
2599 GURL url = frame->document().url();
2600 if (url.is_valid() && url.spec() != url::kAboutBlankURL) {
2601 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2602 // frame->tree()->top().
2603 blink::WebFrame* main_frame = render_view_->webview()->mainFrame();
2604 if (frame == main_frame) {
2605 // For now, don't remember plugin zoom values. We don't want to mix them
2606 // with normal web content (i.e. a fixed layout plugin would usually want
2607 // them different).
2608 render_view_->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2609 render_view_->GetRoutingID(),
2610 main_frame->document().isPluginDocument()));
2614 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2615 DidCreateDocumentElement(frame));
2618 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame* frame,
2619 const blink::WebString& title,
2620 blink::WebTextDirection direction) {
2621 DCHECK(!frame_ || frame_ == frame);
2622 // Ignore all but top level navigations.
2623 if (!frame->parent()) {
2624 base::string16 title16 = title;
2625 base::trace_event::TraceLog::GetInstance()->UpdateProcessLabel(
2626 routing_id_, base::UTF16ToUTF8(title16));
2628 base::string16 shortened_title = title16.substr(0, kMaxTitleChars);
2629 Send(new FrameHostMsg_UpdateTitle(routing_id_,
2630 shortened_title, direction));
2633 // Also check whether we have new encoding name.
2634 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2637 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame* frame,
2638 blink::WebIconURL::Type icon_type) {
2639 DCHECK(!frame_ || frame_ == frame);
2640 // TODO(nasko): Investigate wheather implementation should move here.
2641 render_view_->didChangeIcon(frame, icon_type);
2644 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame* frame) {
2645 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2646 "id", routing_id_);
2647 DCHECK(!frame_ || frame_ == frame);
2648 WebDataSource* ds = frame->dataSource();
2649 DocumentState* document_state = DocumentState::FromDataSource(ds);
2650 document_state->set_finish_document_load_time(Time::Now());
2652 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_));
2654 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2655 DidFinishDocumentLoad(frame));
2656 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidFinishDocumentLoad());
2658 // Check whether we have new encoding name.
2659 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2662 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame* frame) {
2663 DCHECK(!frame_ || frame_ == frame);
2664 if (!frame->parent()) {
2665 FrameMsg_UILoadMetricsReportType::Value report_type =
2666 static_cast<FrameMsg_UILoadMetricsReportType::Value>(
2667 frame->dataSource()->request().inputPerfMetricReportPolicy());
2668 base::TimeTicks ui_timestamp = base::TimeTicks() +
2669 base::TimeDelta::FromSecondsD(
2670 frame->dataSource()->request().uiStartTime());
2672 Send(new FrameHostMsg_DocumentOnLoadCompleted(
2673 routing_id_, report_type, ui_timestamp));
2677 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame* frame,
2678 const blink::WebURLError& error) {
2679 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2680 "id", routing_id_);
2681 DCHECK(!frame_ || frame_ == frame);
2682 // TODO(nasko): Move implementation here. No state needed.
2683 WebDataSource* ds = frame->dataSource();
2684 DCHECK(ds);
2686 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2687 DidFailLoad(frame, error));
2689 const WebURLRequest& failed_request = ds->request();
2690 base::string16 error_description;
2691 GetContentClient()->renderer()->GetNavigationErrorStrings(
2692 render_view_.get(),
2693 frame,
2694 failed_request,
2695 error,
2696 NULL,
2697 &error_description);
2698 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_,
2699 failed_request.url(),
2700 error.reason,
2701 error_description));
2704 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame* frame) {
2705 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2706 "id", routing_id_);
2707 DCHECK(!frame_ || frame_ == frame);
2708 WebDataSource* ds = frame->dataSource();
2709 DocumentState* document_state = DocumentState::FromDataSource(ds);
2710 if (document_state->finish_load_time().is_null()) {
2711 if (!frame->parent()) {
2712 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2713 TRACE_EVENT_SCOPE_PROCESS);
2715 document_state->set_finish_load_time(Time::Now());
2718 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2719 DidFinishLoad(frame));
2720 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidFinishLoad());
2722 // Don't send this message while the frame is swapped out.
2723 if (is_swapped_out())
2724 return;
2726 Send(new FrameHostMsg_DidFinishLoad(routing_id_,
2727 ds->request().url()));
2730 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame* frame,
2731 const blink::WebHistoryItem& item,
2732 blink::WebHistoryCommitType commit_type) {
2733 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
2734 "id", routing_id_);
2735 DCHECK(!frame_ || frame_ == frame);
2736 // If this was a reference fragment navigation that we initiated, then we
2737 // could end up having a non-null pending navigation params. We just need to
2738 // update the ExtraData on the datasource so that others who read the
2739 // ExtraData will get the new NavigationState. Similarly, if we did not
2740 // initiate this navigation, then we need to take care to reset any pre-
2741 // existing navigation state to a content-initiated navigation state.
2742 // DidCreateDataSource conveniently takes care of this for us.
2743 didCreateDataSource(frame, frame->dataSource());
2745 DocumentState* document_state =
2746 DocumentState::FromDataSource(frame->dataSource());
2747 NavigationState* new_state = document_state->navigation_state();
2748 new_state->set_was_within_same_page(true);
2750 didCommitProvisionalLoad(frame, item, commit_type);
2753 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame* frame) {
2754 DCHECK(!frame_ || frame_ == frame);
2755 // TODO(nasko): Move implementation here. Needed methods:
2756 // * StartNavStateSyncTimerIfNecessary
2757 render_view_->didUpdateCurrentHistoryItem(frame);
2760 void RenderFrameImpl::addNavigationTransitionData(
2761 const blink::WebTransitionElementData& data) {
2762 FrameHostMsg_AddNavigationTransitionData_Params params;
2763 params.render_frame_id = routing_id_;
2764 params.allowed_destination_host_pattern =
2765 data.scope.utf8();
2766 params.selector = data.selector.utf8();
2767 params.markup = data.markup.utf8();
2768 params.elements.resize(data.elements.size());
2769 for (size_t i = 0; i < data.elements.size(); i++) {
2770 params.elements[i].id = data.elements[i].id.utf8();
2771 params.elements[i].rect = gfx::Rect(data.elements[i].rect);
2774 Send(new FrameHostMsg_AddNavigationTransitionData(params));
2777 void RenderFrameImpl::didChangeThemeColor() {
2778 if (frame_->parent())
2779 return;
2781 Send(new FrameHostMsg_DidChangeThemeColor(
2782 routing_id_, frame_->document().themeColor()));
2785 void RenderFrameImpl::dispatchLoad() {
2786 Send(new FrameHostMsg_DispatchLoad(routing_id_));
2789 void RenderFrameImpl::requestNotificationPermission(
2790 const blink::WebSecurityOrigin& origin,
2791 blink::WebNotificationPermissionCallback* callback) {
2792 if (!notification_permission_dispatcher_) {
2793 notification_permission_dispatcher_ =
2794 new NotificationPermissionDispatcher(this);
2797 notification_permission_dispatcher_->RequestPermission(origin, callback);
2800 void RenderFrameImpl::didChangeSelection(bool is_empty_selection) {
2801 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_)
2802 return;
2804 if (is_empty_selection)
2805 selection_text_.clear();
2807 // UpdateTextInputType should be called before SyncSelectionIfRequired.
2808 // UpdateTextInputType may send TextInputTypeChanged to notify the focus
2809 // was changed, and SyncSelectionIfRequired may send SelectionChanged
2810 // to notify the selection was changed. Focus change should be notified
2811 // before selection change.
2812 GetRenderWidget()->UpdateTextInputType();
2813 SyncSelectionIfRequired();
2814 #if defined(OS_ANDROID)
2815 GetRenderWidget()->UpdateTextInputState(RenderWidget::NO_SHOW_IME,
2816 RenderWidget::FROM_NON_IME);
2817 #endif
2820 blink::WebColorChooser* RenderFrameImpl::createColorChooser(
2821 blink::WebColorChooserClient* client,
2822 const blink::WebColor& initial_color,
2823 const blink::WebVector<blink::WebColorSuggestion>& suggestions) {
2824 RendererWebColorChooserImpl* color_chooser =
2825 new RendererWebColorChooserImpl(this, client);
2826 std::vector<ColorSuggestion> color_suggestions;
2827 for (size_t i = 0; i < suggestions.size(); i++) {
2828 color_suggestions.push_back(ColorSuggestion(suggestions[i]));
2830 color_chooser->Open(static_cast<SkColor>(initial_color), color_suggestions);
2831 return color_chooser;
2834 void RenderFrameImpl::runModalAlertDialog(const blink::WebString& message) {
2835 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT,
2836 message,
2837 base::string16(),
2838 frame_->document().url(),
2839 NULL);
2842 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString& message) {
2843 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM,
2844 message,
2845 base::string16(),
2846 frame_->document().url(),
2847 NULL);
2850 bool RenderFrameImpl::runModalPromptDialog(
2851 const blink::WebString& message,
2852 const blink::WebString& default_value,
2853 blink::WebString* actual_value) {
2854 base::string16 result;
2855 bool ok = RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT,
2856 message,
2857 default_value,
2858 frame_->document().url(),
2859 &result);
2860 if (ok)
2861 actual_value->assign(result);
2862 return ok;
2865 bool RenderFrameImpl::runModalBeforeUnloadDialog(
2866 bool is_reload,
2867 const blink::WebString& message) {
2868 // If we are swapping out, we have already run the beforeunload handler.
2869 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
2870 // at all, to avoid running it twice.
2871 if (is_swapped_out_)
2872 return true;
2874 // Don't allow further dialogs if we are waiting to swap out, since the
2875 // PageGroupLoadDeferrer in our stack prevents it.
2876 if (render_view()->suppress_dialogs_until_swap_out_)
2877 return false;
2879 bool success = false;
2880 // This is an ignored return value, but is included so we can accept the same
2881 // response as RunJavaScriptMessage.
2882 base::string16 ignored_result;
2883 render_view()->SendAndRunNestedMessageLoop(
2884 new FrameHostMsg_RunBeforeUnloadConfirm(
2885 routing_id_, frame_->document().url(), message, is_reload,
2886 &success, &ignored_result));
2887 return success;
2890 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData& data) {
2891 ContextMenuParams params = ContextMenuParamsBuilder::Build(data);
2892 params.source_type = GetRenderWidget()->context_menu_source_type();
2893 GetRenderWidget()->OnShowHostContextMenu(&params);
2894 if (GetRenderWidget()->has_host_context_menu_location()) {
2895 params.x = GetRenderWidget()->host_context_menu_location().x();
2896 params.y = GetRenderWidget()->host_context_menu_location().y();
2899 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
2900 // it. We replace it with an empty GURL so the appropriate items are disabled
2901 // in the context menu.
2902 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
2903 // data encoded images. We should have a way to save them.
2904 if (params.src_url.spec().size() > GetMaxURLChars())
2905 params.src_url = GURL();
2906 context_menu_node_ = data.node;
2908 #if defined(OS_ANDROID)
2909 gfx::Rect start_rect;
2910 gfx::Rect end_rect;
2911 GetRenderWidget()->GetSelectionBounds(&start_rect, &end_rect);
2912 params.selection_start = gfx::Point(start_rect.x(), start_rect.bottom());
2913 params.selection_end = gfx::Point(end_rect.right(), end_rect.bottom());
2914 #endif
2916 Send(new FrameHostMsg_ContextMenu(routing_id_, params));
2919 void RenderFrameImpl::clearContextMenu() {
2920 context_menu_node_.reset();
2923 void RenderFrameImpl::willSendRequest(
2924 blink::WebLocalFrame* frame,
2925 unsigned identifier,
2926 blink::WebURLRequest& request,
2927 const blink::WebURLResponse& redirect_response) {
2928 DCHECK(!frame_ || frame_ == frame);
2929 // The request my be empty during tests.
2930 if (request.url().isEmpty())
2931 return;
2933 // Set the first party for cookies url if it has not been set yet (new
2934 // requests). For redirects, it is updated by WebURLLoaderImpl.
2935 if (request.firstPartyForCookies().isEmpty()) {
2936 if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel) {
2937 request.setFirstPartyForCookies(request.url());
2938 } else {
2939 // TODO(nasko): When the top-level frame is remote, there is no document.
2940 // This is broken and should be fixed to propagate the first party.
2941 WebFrame* top = frame->top();
2942 if (top->isWebLocalFrame()) {
2943 request.setFirstPartyForCookies(
2944 frame->top()->document().firstPartyForCookies());
2949 WebFrame* top_frame = frame->top();
2950 // TODO(nasko): Hack around asking about top-frame data source. This means
2951 // for out-of-process iframes we are treating the current frame as the
2952 // top-level frame, which is wrong.
2953 if (!top_frame || top_frame->isWebRemoteFrame())
2954 top_frame = frame;
2955 WebDataSource* provisional_data_source = top_frame->provisionalDataSource();
2956 WebDataSource* top_data_source = top_frame->dataSource();
2957 WebDataSource* data_source =
2958 provisional_data_source ? provisional_data_source : top_data_source;
2960 DocumentState* document_state = DocumentState::FromDataSource(data_source);
2961 DCHECK(document_state);
2962 InternalDocumentStateData* internal_data =
2963 InternalDocumentStateData::FromDocumentState(document_state);
2964 NavigationState* navigation_state = document_state->navigation_state();
2965 ui::PageTransition transition_type = navigation_state->transition_type();
2966 WebDataSource* frame_ds = frame->provisionalDataSource();
2967 if (frame_ds && frame_ds->isClientRedirect()) {
2968 transition_type = ui::PageTransitionFromInt(
2969 transition_type | ui::PAGE_TRANSITION_CLIENT_REDIRECT);
2972 GURL request_url(request.url());
2973 GURL new_url;
2974 if (GetContentClient()->renderer()->WillSendRequest(
2975 frame,
2976 transition_type,
2977 request_url,
2978 request.firstPartyForCookies(),
2979 &new_url)) {
2980 request.setURL(WebURL(new_url));
2983 if (internal_data->is_cache_policy_override_set())
2984 request.setCachePolicy(internal_data->cache_policy_override());
2986 // The request's extra data may indicate that we should set a custom user
2987 // agent. This needs to be done here, after WebKit is through with setting the
2988 // user agent on its own. Similarly, it may indicate that we should set an
2989 // X-Requested-With header. This must be done here to avoid breaking CORS
2990 // checks.
2991 // PlzNavigate: there may also be a stream url associated with the request.
2992 WebString custom_user_agent;
2993 WebString requested_with;
2994 scoped_ptr<StreamOverrideParameters> stream_override;
2995 if (request.extraData()) {
2996 RequestExtraData* old_extra_data =
2997 static_cast<RequestExtraData*>(request.extraData());
2999 custom_user_agent = old_extra_data->custom_user_agent();
3000 if (!custom_user_agent.isNull()) {
3001 if (custom_user_agent.isEmpty())
3002 request.clearHTTPHeaderField("User-Agent");
3003 else
3004 request.setHTTPHeaderField("User-Agent", custom_user_agent);
3007 requested_with = old_extra_data->requested_with();
3008 if (!requested_with.isNull()) {
3009 if (requested_with.isEmpty())
3010 request.clearHTTPHeaderField("X-Requested-With");
3011 else
3012 request.setHTTPHeaderField("X-Requested-With", requested_with);
3014 stream_override = old_extra_data->TakeStreamOverrideOwnership();
3017 // Add the default accept header for frame request if it has not been set
3018 // already.
3019 if ((request.frameType() == blink::WebURLRequest::FrameTypeTopLevel ||
3020 request.frameType() == blink::WebURLRequest::FrameTypeNested) &&
3021 request.httpHeaderField(WebString::fromUTF8(kAcceptHeader)).isEmpty()) {
3022 request.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader),
3023 WebString::fromUTF8(kDefaultAcceptHeader));
3026 // Add an empty HTTP origin header for non GET methods if none is currently
3027 // present.
3028 request.addHTTPOriginIfNeeded(WebString());
3030 // Attach |should_replace_current_entry| state to requests so that, should
3031 // this navigation later require a request transfer, all state is preserved
3032 // when it is re-created in the new process.
3033 bool should_replace_current_entry = false;
3034 if (navigation_state->is_content_initiated()) {
3035 should_replace_current_entry = data_source->replacesCurrentHistoryItem();
3036 } else {
3037 // If the navigation is browser-initiated, the NavigationState contains the
3038 // correct value instead of the WebDataSource.
3040 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3041 // NavigationState::should_replace_current_entry().
3042 should_replace_current_entry =
3043 navigation_state->should_replace_current_entry();
3046 int provider_id = kInvalidServiceWorkerProviderId;
3047 if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel ||
3048 request.frameType() == blink::WebURLRequest::FrameTypeNested) {
3049 // |provisionalDataSource| may be null in some content::ResourceFetcher
3050 // use cases, we don't hook those requests.
3051 if (frame->provisionalDataSource()) {
3052 ServiceWorkerNetworkProvider* provider =
3053 ServiceWorkerNetworkProvider::FromDocumentState(
3054 DocumentState::FromDataSource(frame->provisionalDataSource()));
3055 provider_id = provider->provider_id();
3057 } else if (frame->dataSource()) {
3058 ServiceWorkerNetworkProvider* provider =
3059 ServiceWorkerNetworkProvider::FromDocumentState(
3060 DocumentState::FromDataSource(frame->dataSource()));
3061 provider_id = provider->provider_id();
3064 WebFrame* parent = frame->parent();
3065 int parent_routing_id = MSG_ROUTING_NONE;
3066 if (!parent) {
3067 parent_routing_id = -1;
3068 } else if (parent->isWebLocalFrame()) {
3069 parent_routing_id = FromWebFrame(parent)->GetRoutingID();
3070 } else {
3071 parent_routing_id = RenderFrameProxy::FromWebFrame(parent)->routing_id();
3074 RequestExtraData* extra_data = new RequestExtraData();
3075 extra_data->set_visibility_state(render_view_->visibilityState());
3076 extra_data->set_custom_user_agent(custom_user_agent);
3077 extra_data->set_requested_with(requested_with);
3078 extra_data->set_render_frame_id(routing_id_);
3079 extra_data->set_is_main_frame(!parent);
3080 extra_data->set_frame_origin(
3081 GURL(frame->document().securityOrigin().toString()));
3082 extra_data->set_parent_is_main_frame(parent && !parent->parent());
3083 extra_data->set_parent_render_frame_id(parent_routing_id);
3084 extra_data->set_allow_download(navigation_state->allow_download());
3085 extra_data->set_transition_type(transition_type);
3086 extra_data->set_should_replace_current_entry(should_replace_current_entry);
3087 extra_data->set_transferred_request_child_id(
3088 navigation_state->transferred_request_child_id());
3089 extra_data->set_transferred_request_request_id(
3090 navigation_state->transferred_request_request_id());
3091 extra_data->set_service_worker_provider_id(provider_id);
3092 extra_data->set_stream_override(stream_override.Pass());
3093 request.setExtraData(extra_data);
3095 DocumentState* top_document_state =
3096 DocumentState::FromDataSource(top_data_source);
3097 if (top_document_state) {
3098 // TODO(gavinp): separate out prefetching and prerender field trials
3099 // if the rel=prerender rel type is sticking around.
3100 if (request.requestContext() == WebURLRequest::RequestContextPrefetch)
3101 top_document_state->set_was_prefetcher(true);
3104 // This is an instance where we embed a copy of the routing id
3105 // into the data portion of the message. This can cause problems if we
3106 // don't register this id on the browser side, since the download manager
3107 // expects to find a RenderViewHost based off the id.
3108 request.setRequestorID(render_view_->GetRoutingID());
3109 request.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
3111 if (!navigation_state->extra_headers().empty()) {
3112 for (net::HttpUtil::HeadersIterator i(
3113 navigation_state->extra_headers().begin(),
3114 navigation_state->extra_headers().end(), "\n");
3115 i.GetNext(); ) {
3116 if (LowerCaseEqualsASCII(i.name(), "referer")) {
3117 WebString referrer = WebSecurityPolicy::generateReferrerHeader(
3118 blink::WebReferrerPolicyDefault,
3119 request.url(),
3120 WebString::fromUTF8(i.values()));
3121 request.setHTTPReferrer(referrer, blink::WebReferrerPolicyDefault);
3122 } else {
3123 request.setHTTPHeaderField(WebString::fromUTF8(i.name()),
3124 WebString::fromUTF8(i.values()));
3129 if (!render_view_->renderer_preferences_.enable_referrers)
3130 request.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault);
3133 void RenderFrameImpl::didReceiveResponse(
3134 blink::WebLocalFrame* frame,
3135 unsigned identifier,
3136 const blink::WebURLResponse& response) {
3137 DCHECK(!frame_ || frame_ == frame);
3138 // Only do this for responses that correspond to a provisional data source
3139 // of the top-most frame. If we have a provisional data source, then we
3140 // can't have any sub-resources yet, so we know that this response must
3141 // correspond to a frame load.
3142 if (!frame->provisionalDataSource() || frame->parent())
3143 return;
3145 // If we are in view source mode, then just let the user see the source of
3146 // the server's error page.
3147 if (frame->isViewSourceModeEnabled())
3148 return;
3150 DocumentState* document_state =
3151 DocumentState::FromDataSource(frame->provisionalDataSource());
3152 int http_status_code = response.httpStatusCode();
3154 // Record page load flags.
3155 WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response);
3156 if (extra_data) {
3157 document_state->set_was_fetched_via_spdy(
3158 extra_data->was_fetched_via_spdy());
3159 document_state->set_was_npn_negotiated(
3160 extra_data->was_npn_negotiated());
3161 document_state->set_npn_negotiated_protocol(
3162 extra_data->npn_negotiated_protocol());
3163 document_state->set_was_alternate_protocol_available(
3164 extra_data->was_alternate_protocol_available());
3165 document_state->set_connection_info(
3166 extra_data->connection_info());
3167 document_state->set_was_fetched_via_proxy(
3168 extra_data->was_fetched_via_proxy());
3169 document_state->set_proxy_server(
3170 extra_data->proxy_server());
3172 InternalDocumentStateData* internal_data =
3173 InternalDocumentStateData::FromDocumentState(document_state);
3174 internal_data->set_http_status_code(http_status_code);
3175 // Whether or not the http status code actually corresponds to an error is
3176 // only checked when the page is done loading, if |use_error_page| is
3177 // still true.
3178 internal_data->set_use_error_page(true);
3181 void RenderFrameImpl::didFinishResourceLoad(blink::WebLocalFrame* frame,
3182 unsigned identifier) {
3183 DCHECK(!frame_ || frame_ == frame);
3184 InternalDocumentStateData* internal_data =
3185 InternalDocumentStateData::FromDataSource(frame->dataSource());
3186 if (!internal_data->use_error_page())
3187 return;
3189 // Do not show error page when DevTools is attached.
3190 if (render_view_->devtools_agent_->IsAttached())
3191 return;
3193 // Display error page, if appropriate.
3194 std::string error_domain = "http";
3195 int http_status_code = internal_data->http_status_code();
3196 if (GetContentClient()->renderer()->HasErrorPage(
3197 http_status_code, &error_domain)) {
3198 WebURLError error;
3199 error.unreachableURL = frame->document().url();
3200 error.domain = WebString::fromUTF8(error_domain);
3201 error.reason = http_status_code;
3202 LoadNavigationErrorPage(frame->dataSource()->request(), error, true);
3206 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3207 blink::WebLocalFrame* frame,
3208 const blink::WebURLRequest& request,
3209 const blink::WebURLResponse& response) {
3210 DCHECK(!frame_ || frame_ == frame);
3211 // The recipients of this message have no use for data: URLs: they don't
3212 // affect the page's insecure content list and are not in the disk cache. To
3213 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3214 // filter them out here.
3215 GURL url(request.url());
3216 if (url.SchemeIs(url::kDataScheme))
3217 return;
3219 // Let the browser know we loaded a resource from the memory cache. This
3220 // message is needed to display the correct SSL indicators.
3221 render_view_->Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(
3222 render_view_->GetRoutingID(),
3223 url,
3224 response.securityInfo(),
3225 request.httpMethod().utf8(),
3226 response.mimeType().utf8(),
3227 WebURLRequestToResourceType(request)));
3230 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame* frame) {
3231 DCHECK(!frame_ || frame_ == frame);
3232 render_view_->Send(new ViewHostMsg_DidDisplayInsecureContent(
3233 render_view_->GetRoutingID()));
3236 void RenderFrameImpl::didRunInsecureContent(
3237 blink::WebLocalFrame* frame,
3238 const blink::WebSecurityOrigin& origin,
3239 const blink::WebURL& target) {
3240 DCHECK(!frame_ || frame_ == frame);
3241 render_view_->Send(new ViewHostMsg_DidRunInsecureContent(
3242 render_view_->GetRoutingID(),
3243 origin.toString().utf8(),
3244 target));
3247 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame* frame) {
3248 DCHECK(!frame_ || frame_ == frame);
3249 #if defined(ENABLE_PLUGINS)
3250 if (frame != render_view_->webview()->mainFrame())
3251 return;
3252 PluginChannelHost::Broadcast(
3253 new PluginHostMsg_DidAbortLoading(render_view_->GetRoutingID()));
3254 #endif
3257 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame* frame,
3258 v8::Handle<v8::Context> context,
3259 int extension_group,
3260 int world_id) {
3261 DCHECK(!frame_ || frame_ == frame);
3262 GetContentClient()->renderer()->DidCreateScriptContext(
3263 frame, context, extension_group, world_id);
3266 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame* frame,
3267 v8::Handle<v8::Context> context,
3268 int world_id) {
3269 DCHECK(!frame_ || frame_ == frame);
3271 FOR_EACH_OBSERVER(RenderFrameObserver,
3272 observers_,
3273 WillReleaseScriptContext(context, world_id));
3276 void RenderFrameImpl::didFirstVisuallyNonEmptyLayout(
3277 blink::WebLocalFrame* frame) {
3278 DCHECK(!frame_ || frame_ == frame);
3279 if (frame->parent())
3280 return;
3282 InternalDocumentStateData* data =
3283 InternalDocumentStateData::FromDataSource(frame->dataSource());
3284 data->set_did_first_visually_non_empty_layout(true);
3286 #if defined(OS_ANDROID)
3287 GetRenderWidget()->DidChangeBodyBackgroundColor(
3288 render_view_->webwidget_->backgroundColor());
3289 #endif
3291 GetRenderWidget()->QueueMessage(
3292 new FrameHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_),
3293 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE);
3296 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame* frame) {
3297 DCHECK(!frame_ || frame_ == frame);
3298 // TODO(nasko): Move implementation here. Needed methods:
3299 // * StartNavStateSyncTimerIfNecessary
3300 render_view_->didChangeScrollOffset(frame);
3302 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeScrollOffset());
3305 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame* frame) {
3306 DCHECK(!frame_ || frame_ == frame);
3307 if (!frame->parent()) {
3308 render_view_->Send(new ViewHostMsg_WillInsertBody(
3309 render_view_->GetRoutingID()));
3313 void RenderFrameImpl::reportFindInPageMatchCount(int request_id,
3314 int count,
3315 bool final_update) {
3316 int active_match_ordinal = -1; // -1 = don't update active match ordinal
3317 if (!count)
3318 active_match_ordinal = 0;
3320 render_view_->Send(new ViewHostMsg_Find_Reply(
3321 render_view_->GetRoutingID(), request_id, count,
3322 gfx::Rect(), active_match_ordinal, final_update));
3325 void RenderFrameImpl::reportFindInPageSelection(
3326 int request_id,
3327 int active_match_ordinal,
3328 const blink::WebRect& selection_rect) {
3329 render_view_->Send(new ViewHostMsg_Find_Reply(
3330 render_view_->GetRoutingID(), request_id, -1, selection_rect,
3331 active_match_ordinal, false));
3334 void RenderFrameImpl::requestStorageQuota(
3335 blink::WebLocalFrame* frame,
3336 blink::WebStorageQuotaType type,
3337 unsigned long long requested_size,
3338 blink::WebStorageQuotaCallbacks callbacks) {
3339 DCHECK(!frame_ || frame_ == frame);
3340 WebSecurityOrigin origin = frame->document().securityOrigin();
3341 if (origin.isUnique()) {
3342 // Unique origins cannot store persistent state.
3343 callbacks.didFail(blink::WebStorageQuotaErrorAbort);
3344 return;
3346 ChildThreadImpl::current()->quota_dispatcher()->RequestStorageQuota(
3347 render_view_->GetRoutingID(),
3348 GURL(origin.toString()),
3349 static_cast<storage::StorageType>(type),
3350 requested_size,
3351 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks));
3354 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle* handle) {
3355 WebSocketBridge* impl = static_cast<WebSocketBridge*>(handle);
3356 impl->set_render_frame_id(routing_id_);
3359 blink::WebGeolocationClient* RenderFrameImpl::geolocationClient() {
3360 if (!geolocation_dispatcher_)
3361 geolocation_dispatcher_ = new GeolocationDispatcher(this);
3362 return geolocation_dispatcher_;
3365 blink::WebPresentationClient* RenderFrameImpl::presentationClient() {
3366 if (!presentation_dispatcher_)
3367 presentation_dispatcher_ = new PresentationDispatcher(this);
3368 return presentation_dispatcher_;
3371 blink::WebPushClient* RenderFrameImpl::pushClient() {
3372 if (!push_messaging_dispatcher_)
3373 push_messaging_dispatcher_ = new PushMessagingDispatcher(this);
3374 return push_messaging_dispatcher_;
3377 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3378 blink::WebLocalFrame* frame,
3379 blink::WebRTCPeerConnectionHandler* handler) {
3380 DCHECK(!frame_ || frame_ == frame);
3381 #if defined(ENABLE_WEBRTC)
3382 static_cast<RTCPeerConnectionHandler*>(handler)->associateWithFrame(frame);
3383 #endif
3386 blink::WebUserMediaClient* RenderFrameImpl::userMediaClient() {
3387 if (!web_user_media_client_)
3388 InitializeUserMediaClient();
3389 return web_user_media_client_;
3392 blink::WebEncryptedMediaClient* RenderFrameImpl::encryptedMediaClient() {
3393 if (!web_encrypted_media_client_) {
3394 #if defined(ENABLE_PEPPER_CDMS)
3395 scoped_ptr<media::CdmFactory> cdm_factory(
3396 new RenderCdmFactory(base::Bind(PepperCdmWrapperImpl::Create, frame_)));
3397 #elif defined(ENABLE_BROWSER_CDMS)
3398 scoped_ptr<media::CdmFactory> cdm_factory(
3399 new RenderCdmFactory(GetCdmManager()));
3400 #else
3401 scoped_ptr<media::CdmFactory> cdm_factory(new RenderCdmFactory());
3402 #endif
3404 if (!media_permission_dispatcher_)
3405 media_permission_dispatcher_ = new MediaPermissionDispatcher(this);
3407 web_encrypted_media_client_.reset(new media::WebEncryptedMediaClientImpl(
3408 cdm_factory.Pass(), media_permission_dispatcher_));
3410 return web_encrypted_media_client_.get();
3413 blink::WebMIDIClient* RenderFrameImpl::webMIDIClient() {
3414 if (!midi_dispatcher_)
3415 midi_dispatcher_ = new MidiDispatcher(this);
3416 return midi_dispatcher_;
3419 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3420 blink::WebLocalFrame* source_frame,
3421 blink::WebFrame* target_frame,
3422 blink::WebSecurityOrigin target_origin,
3423 blink::WebDOMMessageEvent event) {
3424 DCHECK(!frame_ || frame_ == target_frame);
3426 if (!is_swapped_out_)
3427 return false;
3429 ViewMsg_PostMessage_Params params;
3430 params.is_data_raw_string = false;
3431 params.data = event.data().toString();
3432 params.source_origin = event.origin();
3433 if (!target_origin.isNull())
3434 params.target_origin = target_origin.toString();
3436 params.message_ports =
3437 WebMessagePortChannelImpl::ExtractMessagePortIDs(event.releaseChannels());
3439 // Include the routing ID for the source frame (if one exists), which the
3440 // browser process will translate into the routing ID for the equivalent
3441 // frame in the target process.
3442 params.source_routing_id = MSG_ROUTING_NONE;
3443 if (source_frame) {
3444 RenderViewImpl* source_view =
3445 RenderViewImpl::FromWebView(source_frame->view());
3446 if (source_view)
3447 params.source_routing_id = source_view->routing_id();
3450 Send(new ViewHostMsg_RouteMessageEvent(render_view_->routing_id_, params));
3451 return true;
3454 blink::WebString RenderFrameImpl::userAgentOverride(blink::WebLocalFrame* frame,
3455 const blink::WebURL& url) {
3456 DCHECK(!frame_ || frame_ == frame);
3457 std::string user_agent_override_for_url =
3458 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url));
3459 if (!user_agent_override_for_url.empty())
3460 return WebString::fromUTF8(user_agent_override_for_url);
3462 if (!render_view_->webview() || !render_view_->webview()->mainFrame() ||
3463 render_view_->renderer_preferences_.user_agent_override.empty()) {
3464 return blink::WebString();
3467 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3468 // associated with it, so the checks below are not valid. Temporarily
3469 // return early and fix properly as part of https://crbug.com/426555.
3470 if (render_view_->webview()->mainFrame()->isWebRemoteFrame())
3471 return blink::WebString();
3473 // If we're in the middle of committing a load, the data source we need
3474 // will still be provisional.
3475 WebFrame* main_frame = render_view_->webview()->mainFrame();
3476 WebDataSource* data_source = NULL;
3477 if (main_frame->provisionalDataSource())
3478 data_source = main_frame->provisionalDataSource();
3479 else
3480 data_source = main_frame->dataSource();
3482 InternalDocumentStateData* internal_data = data_source ?
3483 InternalDocumentStateData::FromDataSource(data_source) : NULL;
3484 if (internal_data && internal_data->is_overriding_user_agent())
3485 return WebString::fromUTF8(
3486 render_view_->renderer_preferences_.user_agent_override);
3487 return blink::WebString();
3490 blink::WebString RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame* frame) {
3491 DCHECK(!frame_ || frame_ == frame);
3492 if (render_view_->renderer_preferences_.enable_do_not_track)
3493 return WebString::fromUTF8("1");
3494 return WebString();
3497 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame* frame,
3498 bool default_value) {
3499 DCHECK(!frame_ || frame_ == frame);
3500 if (!default_value)
3501 return false;
3503 bool blocked = true;
3504 render_view_->Send(new ViewHostMsg_Are3DAPIsBlocked(
3505 render_view_->GetRoutingID(),
3506 GURL(frame->top()->document().securityOrigin().toString()),
3507 THREE_D_API_TYPE_WEBGL,
3508 &blocked));
3509 return !blocked;
3512 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame* frame,
3513 int arb_robustness_status_code) {
3514 DCHECK(!frame_ || frame_ == frame);
3515 render_view_->Send(new ViewHostMsg_DidLose3DContext(
3516 GURL(frame->top()->document().securityOrigin().toString()),
3517 THREE_D_API_TYPE_WEBGL,
3518 arb_robustness_status_code));
3521 blink::WebScreenOrientationClient*
3522 RenderFrameImpl::webScreenOrientationClient() {
3523 if (!screen_orientation_dispatcher_)
3524 screen_orientation_dispatcher_ = new ScreenOrientationDispatcher(this);
3525 return screen_orientation_dispatcher_;
3528 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource& data_source) {
3529 ServiceWorkerNetworkProvider* provider =
3530 ServiceWorkerNetworkProvider::FromDocumentState(
3531 DocumentState::FromDataSource(&data_source));
3532 return provider->context()->controller_handle_id() !=
3533 kInvalidServiceWorkerHandleId;
3536 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource& data_source) {
3537 ServiceWorkerNetworkProvider* provider =
3538 ServiceWorkerNetworkProvider::FromDocumentState(
3539 DocumentState::FromDataSource(&data_source));
3541 if (provider->context()->controller())
3542 return provider->context()->controller()->version_id();
3543 return kInvalidServiceWorkerVersionId;
3546 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject& obj,
3547 blink::WebAXEvent event) {
3548 HandleWebAccessibilityEvent(obj, event);
3551 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3552 int identifier,
3553 int match_index,
3554 const blink::WebAXObject& start_object,
3555 int start_offset,
3556 const blink::WebAXObject& end_object,
3557 int end_offset) {
3558 if (renderer_accessibility_) {
3559 renderer_accessibility_->HandleAccessibilityFindInPageResult(
3560 identifier, match_index, start_object, start_offset,
3561 end_object, end_offset);
3565 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame* frame) {
3566 DCHECK(!frame_ || frame_ == frame);
3568 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeManifest());
3571 bool RenderFrameImpl::enterFullscreen() {
3572 Send(new FrameHostMsg_ToggleFullscreen(routing_id_, true));
3573 return true;
3576 bool RenderFrameImpl::exitFullscreen() {
3577 Send(new FrameHostMsg_ToggleFullscreen(routing_id_, false));
3578 return true;
3581 void RenderFrameImpl::suddenTerminationDisablerChanged(
3582 bool present,
3583 blink::WebFrameClient::SuddenTerminationDisablerType type) {
3584 switch (type) {
3585 case blink::WebFrameClient::BeforeUnloadHandler:
3586 Send(new FrameHostMsg_BeforeUnloadHandlersPresent(
3587 routing_id_, present));
3588 break;
3589 case blink::WebFrameClient::UnloadHandler:
3590 Send(new FrameHostMsg_UnloadHandlersPresent(
3591 routing_id_, present));
3592 break;
3593 default:
3594 NOTREACHED();
3598 void RenderFrameImpl::DidPlay(blink::WebMediaPlayer* player) {
3599 Send(new FrameHostMsg_MediaPlayingNotification(
3600 routing_id_, reinterpret_cast<int64>(player), player->hasVideo(),
3601 player->hasAudio(), player->isRemote()));
3604 void RenderFrameImpl::DidPause(blink::WebMediaPlayer* player) {
3605 Send(new FrameHostMsg_MediaPausedNotification(
3606 routing_id_, reinterpret_cast<int64>(player)));
3609 void RenderFrameImpl::PlayerGone(blink::WebMediaPlayer* player) {
3610 DidPause(player);
3613 void RenderFrameImpl::AddObserver(RenderFrameObserver* observer) {
3614 observers_.AddObserver(observer);
3617 void RenderFrameImpl::RemoveObserver(RenderFrameObserver* observer) {
3618 observer->RenderFrameGone();
3619 observers_.RemoveObserver(observer);
3622 void RenderFrameImpl::OnStop() {
3623 DCHECK(frame_);
3624 frame_->stopLoading();
3625 if (!frame_->parent())
3626 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers_, OnStop());
3628 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, OnStop());
3631 void RenderFrameImpl::WasHidden() {
3632 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WasHidden());
3635 void RenderFrameImpl::WasShown() {
3636 // TODO(kenrb): Need to figure out how to do this better. Should
3637 // VisibilityState remain a page-level concept or move to frames?
3638 // The semantics of 'Show' might have to change here.
3639 if (render_widget_) {
3640 static_cast<blink::WebFrameWidget*>(render_widget_->webwidget())->
3641 setVisibilityState(blink::WebPageVisibilityStateVisible, false);
3643 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WasShown());
3646 bool RenderFrameImpl::IsHidden() {
3647 return GetRenderWidget()->is_hidden();
3650 // Tell the embedding application that the URL of the active page has changed.
3651 void RenderFrameImpl::SendDidCommitProvisionalLoad(
3652 blink::WebFrame* frame,
3653 blink::WebHistoryCommitType commit_type) {
3654 DCHECK(!frame_ || frame_ == frame);
3655 WebDataSource* ds = frame->dataSource();
3656 DCHECK(ds);
3658 const WebURLRequest& request = ds->request();
3659 const WebURLResponse& response = ds->response();
3661 DocumentState* document_state = DocumentState::FromDataSource(ds);
3662 NavigationState* navigation_state = document_state->navigation_state();
3663 InternalDocumentStateData* internal_data =
3664 InternalDocumentStateData::FromDocumentState(document_state);
3666 FrameHostMsg_DidCommitProvisionalLoad_Params params;
3667 params.http_status_code = response.httpStatusCode();
3668 params.url_is_unreachable = ds->hasUnreachableURL();
3669 params.is_post = false;
3670 params.post_id = -1;
3671 params.page_id = render_view_->page_id_;
3672 // We need to track the RenderViewHost routing_id because of downstream
3673 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3674 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3675 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3676 // based on the ID stored in the resource requests. Once those dependencies
3677 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3678 // client to be based on the routing_id of the RenderFrameHost.
3679 params.render_view_routing_id = render_view_->routing_id();
3680 params.socket_address.set_host(response.remoteIPAddress().utf8());
3681 params.socket_address.set_port(response.remotePort());
3682 WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response);
3683 if (extra_data)
3684 params.was_fetched_via_proxy = extra_data->was_fetched_via_proxy();
3685 params.was_within_same_page = navigation_state->was_within_same_page();
3686 params.security_info = response.securityInfo();
3688 // Set the URL to be displayed in the browser UI to the user.
3689 params.url = GetLoadingUrl();
3690 DCHECK(!is_swapped_out_ || params.url == GURL(kSwappedOutURL));
3692 // Set the origin of the frame. This will be replicated to the corresponding
3693 // RenderFrameProxies in other processes.
3694 // TODO(alexmos): Origins for URLs with non-standard schemes are excluded due
3695 // to https://crbug.com/439608 and will be replicated as unique origins.
3696 if (!is_swapped_out_) {
3697 WebString serialized_origin(frame->document().securityOrigin().toString());
3698 if (GURL(serialized_origin).IsStandard())
3699 params.origin = url::Origin(serialized_origin.utf8());
3702 if (frame->document().baseURL() != params.url)
3703 params.base_url = frame->document().baseURL();
3705 GetRedirectChain(ds, &params.redirects);
3706 params.should_update_history = !ds->hasUnreachableURL() &&
3707 !response.isMultipartPayload() && (response.httpStatusCode() != 404);
3709 params.searchable_form_url = internal_data->searchable_form_url();
3710 params.searchable_form_encoding = internal_data->searchable_form_encoding();
3712 params.gesture = render_view_->navigation_gesture_;
3713 render_view_->navigation_gesture_ = NavigationGestureUnknown;
3715 // Make navigation state a part of the DidCommitProvisionalLoad message so
3716 // that committed entry has it at all times.
3717 HistoryEntry* entry = render_view_->history_controller()->GetCurrentEntry();
3718 if (entry)
3719 params.page_state = HistoryEntryToPageState(entry);
3720 else
3721 params.page_state = PageState::CreateFromURL(request.url());
3723 if (!frame->parent()) {
3724 // Top-level navigation.
3726 // Reset the zoom limits in case a plugin had changed them previously. This
3727 // will also call us back which will cause us to send a message to
3728 // update WebContentsImpl.
3729 render_view_->webview()->zoomLimitsChanged(
3730 ZoomFactorToZoomLevel(kMinimumZoomFactor),
3731 ZoomFactorToZoomLevel(kMaximumZoomFactor));
3733 // Set zoom level, but don't do it for full-page plugin since they don't use
3734 // the same zoom settings.
3735 HostZoomLevels::iterator host_zoom =
3736 render_view_->host_zoom_levels_.find(GURL(request.url()));
3737 if (render_view_->webview()->mainFrame()->document().isPluginDocument()) {
3738 // Reset the zoom levels for plugins.
3739 render_view_->webview()->setZoomLevel(0);
3740 } else {
3741 // If the zoom level is not found, then do nothing. In-page navigation
3742 // relies on not changing the zoom level in this case.
3743 if (host_zoom != render_view_->host_zoom_levels_.end())
3744 render_view_->webview()->setZoomLevel(host_zoom->second);
3747 if (host_zoom != render_view_->host_zoom_levels_.end()) {
3748 // This zoom level was merely recorded transiently for this load. We can
3749 // erase it now. If at some point we reload this page, the browser will
3750 // send us a new, up-to-date zoom level.
3751 render_view_->host_zoom_levels_.erase(host_zoom);
3754 // Update contents MIME type for main frame.
3755 params.contents_mime_type = ds->response().mimeType().utf8();
3757 params.transition = navigation_state->transition_type();
3758 if (!ui::PageTransitionIsMainFrame(params.transition)) {
3759 // If the main frame does a load, it should not be reported as a subframe
3760 // navigation. This can occur in the following case:
3761 // 1. You're on a site with frames.
3762 // 2. You do a subframe navigation. This is stored with transition type
3763 // MANUAL_SUBFRAME.
3764 // 3. You navigate to some non-frame site, say, google.com.
3765 // 4. You navigate back to the page from step 2. Since it was initially
3766 // MANUAL_SUBFRAME, it will be that same transition type here.
3767 // We don't want that, because any navigation that changes the toplevel
3768 // frame should be tracked as a toplevel navigation (this allows us to
3769 // update the URL bar, etc).
3770 params.transition = ui::PAGE_TRANSITION_LINK;
3773 // If the page contained a client redirect (meta refresh, document.loc...),
3774 // set the referrer and transition appropriately.
3775 if (ds->isClientRedirect()) {
3776 params.referrer =
3777 Referrer(params.redirects[0], ds->request().referrerPolicy());
3778 params.transition = ui::PageTransitionFromInt(
3779 params.transition | ui::PAGE_TRANSITION_CLIENT_REDIRECT);
3780 } else {
3781 params.referrer = RenderViewImpl::GetReferrerFromRequest(
3782 frame, ds->request());
3785 base::string16 method = request.httpMethod();
3786 if (EqualsASCII(method, "POST")) {
3787 params.is_post = true;
3788 params.post_id = ExtractPostId(entry);
3791 // Send the user agent override back.
3792 params.is_overriding_user_agent = internal_data->is_overriding_user_agent();
3794 // Track the URL of the original request. We use the first entry of the
3795 // redirect chain if it exists because the chain may have started in another
3796 // process.
3797 params.original_request_url = GetOriginalRequestURL(ds);
3799 params.history_list_was_cleared =
3800 navigation_state->history_list_was_cleared();
3802 params.report_type = static_cast<FrameMsg_UILoadMetricsReportType::Value>(
3803 frame->dataSource()->request().inputPerfMetricReportPolicy());
3804 params.ui_timestamp = base::TimeTicks() + base::TimeDelta::FromSecondsD(
3805 frame->dataSource()->request().uiStartTime());
3807 // Save some histogram data so we can compute the average memory used per
3808 // page load of the glyphs.
3809 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
3810 blink::WebGlyphCache::pageCount());
3812 // This message needs to be sent before any of allowScripts(),
3813 // allowImages(), allowPlugins() is called for the new page, so that when
3814 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
3815 // after the FrameHostMsg_DidCommitProvisionalLoad message.
3816 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params));
3817 } else {
3818 // Subframe navigation: the type depends on whether this navigation
3819 // generated a new session history entry. When they do generate a session
3820 // history entry, it means the user initiated the navigation and we should
3821 // mark it as such.
3822 if (commit_type == blink::WebStandardCommit)
3823 params.transition = ui::PAGE_TRANSITION_MANUAL_SUBFRAME;
3824 else
3825 params.transition = ui::PAGE_TRANSITION_AUTO_SUBFRAME;
3827 DCHECK(!navigation_state->history_list_was_cleared());
3828 params.history_list_was_cleared = false;
3829 params.report_type = FrameMsg_UILoadMetricsReportType::NO_REPORT;
3831 // Don't send this message while the subframe is swapped out.
3832 if (!is_swapped_out())
3833 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params));
3836 // If we end up reusing this WebRequest (for example, due to a #ref click),
3837 // we don't want the transition type to persist. Just clear it.
3838 navigation_state->set_transition_type(ui::PAGE_TRANSITION_LINK);
3841 void RenderFrameImpl::didStartLoading(bool to_different_document) {
3842 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
3843 "id", routing_id_);
3844 render_view_->FrameDidStartLoading(frame_);
3845 Send(new FrameHostMsg_DidStartLoading(routing_id_, to_different_document));
3848 void RenderFrameImpl::didStopLoading() {
3849 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
3850 "id", routing_id_);
3851 render_view_->FrameDidStopLoading(frame_);
3852 Send(new FrameHostMsg_DidStopLoading(routing_id_));
3855 void RenderFrameImpl::didChangeLoadProgress(double load_progress) {
3856 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_, load_progress));
3859 void RenderFrameImpl::HandleWebAccessibilityEvent(
3860 const blink::WebAXObject& obj, blink::WebAXEvent event) {
3861 if (renderer_accessibility_)
3862 renderer_accessibility_->HandleWebAccessibilityEvent(obj, event);
3865 void RenderFrameImpl::FocusedNodeChanged(const WebNode& node) {
3866 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FocusedNodeChanged(node));
3869 void RenderFrameImpl::FocusedNodeChangedForAccessibility(const WebNode& node) {
3870 if (renderer_accessibility())
3871 renderer_accessibility()->AccessibilityFocusedNodeChanged(node);
3874 // PlzNavigate
3875 void RenderFrameImpl::OnCommitNavigation(
3876 const ResourceResponseHead& response,
3877 const GURL& stream_url,
3878 const CommonNavigationParams& common_params,
3879 const CommitNavigationParams& commit_params) {
3880 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
3881 switches::kEnableBrowserSideNavigation));
3882 bool is_reload = false;
3883 bool is_history_navigation = commit_params.page_state.IsValid();
3884 WebURLRequest::CachePolicy cache_policy =
3885 WebURLRequest::UseProtocolCachePolicy;
3886 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
3887 common_params.url, false /* check_for_stale_navigation */,
3888 is_history_navigation, -1 /* current_history_list_offset; TODO(clamy)*/,
3889 &is_reload, &cache_policy)) {
3890 return;
3893 GetContentClient()->SetActiveURL(common_params.url);
3895 if (!common_params.base_url_for_data_url.is_empty() ||
3896 common_params.url.SchemeIs(url::kDataScheme)) {
3897 LoadDataURL(common_params, frame_);
3898 return;
3901 // Create a WebURLRequest that blink can use to get access to the body of the
3902 // response through a stream in the browser. Blink will then commit the
3903 // navigation.
3904 // TODO(clamy): Have the navigation commit directly, without going through
3905 // loading a WebURLRequest.
3906 scoped_ptr<StreamOverrideParameters> stream_override(
3907 new StreamOverrideParameters());
3908 stream_override->stream_url = stream_url;
3909 stream_override->response = response;
3910 WebURLRequest request =
3911 CreateURLRequestForNavigation(common_params,
3912 stream_override.Pass(),
3913 frame_->isViewSourceModeEnabled());
3915 // Make sure that blink loader will not try to use browser side navigation for
3916 // this request (since it already went to the browser).
3917 request.setCheckForBrowserSideNavigation(false);
3919 // Record this before starting the load. A lower bound of this time is needed
3920 // to sanitize the navigationStart override set below.
3921 base::TimeTicks renderer_navigation_start = base::TimeTicks::Now();
3922 frame_->loadRequest(request);
3923 UpdateFrameNavigationTiming(
3924 frame_, commit_params.browser_navigation_start,
3925 renderer_navigation_start);
3928 WebNavigationPolicy RenderFrameImpl::DecidePolicyForNavigation(
3929 RenderFrame* render_frame,
3930 const NavigationPolicyInfo& info) {
3931 #ifdef OS_ANDROID
3932 // The handlenavigation API is deprecated and will be removed once
3933 // crbug.com/325351 is resolved.
3934 if (info.urlRequest.url() != GURL(kSwappedOutURL) &&
3935 GetContentClient()->renderer()->HandleNavigation(
3936 render_frame,
3937 static_cast<DocumentState*>(info.extraData),
3938 render_view_->opener_id_,
3939 info.frame,
3940 info.urlRequest,
3941 info.navigationType,
3942 info.defaultPolicy,
3943 info.isRedirect)) {
3944 return blink::WebNavigationPolicyIgnore;
3946 #endif
3948 Referrer referrer(RenderViewImpl::GetReferrerFromRequest(info.frame,
3949 info.urlRequest));
3950 const base::CommandLine& command_line =
3951 *base::CommandLine::ForCurrentProcess();
3953 bool is_subframe = !!info.frame->parent();
3955 if (command_line.HasSwitch(switches::kSitePerProcess) && is_subframe) {
3956 // There's no reason to ignore navigations on subframes, since the swap out
3957 // logic no longer applies.
3958 } else {
3959 if (is_swapped_out_) {
3960 if (info.urlRequest.url() != GURL(kSwappedOutURL)) {
3961 // Targeted links may try to navigate a swapped out frame. Allow the
3962 // browser process to navigate the tab instead. Note that it is also
3963 // possible for non-targeted navigations (from this view) to arrive
3964 // here just after we are swapped out. It's ok to send them to the
3965 // browser, as long as they're for the top level frame.
3966 // TODO(creis): Ensure this supports targeted form submissions when
3967 // fixing http://crbug.com/101395.
3968 if (info.frame->parent() == NULL) {
3969 OpenURL(info.frame, info.urlRequest.url(), referrer,
3970 info.defaultPolicy);
3971 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
3974 // We should otherwise ignore in-process iframe navigations, if they
3975 // arrive just after we are swapped out.
3976 return blink::WebNavigationPolicyIgnore;
3979 // Allow kSwappedOutURL to complete.
3980 return info.defaultPolicy;
3984 // Webkit is asking whether to navigate to a new URL.
3985 // This is fine normally, except if we're showing UI from one security
3986 // context and they're trying to navigate to a different context.
3987 const GURL& url = info.urlRequest.url();
3989 // A content initiated navigation may have originated from a link-click,
3990 // script, drag-n-drop operation, etc.
3991 bool is_content_initiated = static_cast<DocumentState*>(info.extraData)->
3992 navigation_state()->is_content_initiated();
3994 // Experimental:
3995 // If --enable-strict-site-isolation is enabled, send all top-level
3996 // navigations to the browser to let it swap processes when crossing site
3997 // boundaries. This is currently expected to break some script calls and
3998 // navigations, such as form submissions.
3999 bool force_swap_due_to_flag =
4000 command_line.HasSwitch(switches::kEnableStrictSiteIsolation);
4001 if (force_swap_due_to_flag &&
4002 !info.frame->parent() && (is_content_initiated || info.isRedirect)) {
4003 WebString origin_str = info.frame->document().securityOrigin().toString();
4004 GURL frame_url(origin_str.utf8().data());
4005 // TODO(cevans): revisit whether this site check is still necessary once
4006 // crbug.com/101395 is fixed.
4007 bool same_domain_or_host =
4008 net::registry_controlled_domains::SameDomainOrHost(
4009 frame_url,
4010 url,
4011 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
4012 // Only keep same-site (domain + scheme) and data URLs in the same process.
4013 bool is_same_site =
4014 (same_domain_or_host && frame_url.scheme() == url.scheme()) ||
4015 url.SchemeIs(url::kDataScheme);
4016 if (!is_same_site) {
4017 OpenURL(info.frame, url, referrer, info.defaultPolicy);
4018 return blink::WebNavigationPolicyIgnore;
4022 // If the browser is interested, then give it a chance to look at the request.
4023 if (is_content_initiated) {
4024 bool is_form_post =
4025 ((info.navigationType == blink::WebNavigationTypeFormSubmitted) ||
4026 (info.navigationType == blink::WebNavigationTypeFormResubmitted)) &&
4027 EqualsASCII(info.urlRequest.httpMethod(), "POST");
4028 bool browser_handles_request =
4029 render_view_->renderer_preferences_
4030 .browser_handles_non_local_top_level_requests
4031 && IsNonLocalTopLevelNavigation(url, info.frame, info.navigationType,
4032 is_form_post);
4033 if (!browser_handles_request) {
4034 browser_handles_request = IsTopLevelNavigation(info.frame) &&
4035 render_view_->renderer_preferences_
4036 .browser_handles_all_top_level_requests;
4039 if (browser_handles_request) {
4040 OpenURL(info.frame, url, referrer, info.defaultPolicy);
4041 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
4045 // Use the frame's original request's URL rather than the document's URL for
4046 // subsequent checks. For a popup, the document's URL may become the opener
4047 // window's URL if the opener has called document.write().
4048 // See http://crbug.com/93517.
4049 GURL old_url(info.frame->dataSource()->request().url());
4051 // Detect when we're crossing a permission-based boundary (e.g. into or out of
4052 // an extension or app origin, leaving a WebUI page, etc). We only care about
4053 // top-level navigations (not iframes). But we sometimes navigate to
4054 // about:blank to clear a tab, and we want to still allow that.
4056 // Note: this is known to break POST submissions when crossing process
4057 // boundaries until http://crbug.com/101395 is fixed. This is better for
4058 // security than loading a WebUI, extension or app page in the wrong process.
4059 // POST requests don't work because this mechanism does not preserve form
4060 // POST data. We will need to send the request's httpBody data up to the
4061 // browser process, and issue a special POST navigation in WebKit (via
4062 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
4063 // for examples of how to send the httpBody data.
4064 if (!info.frame->parent() && is_content_initiated &&
4065 !url.SchemeIs(url::kAboutScheme)) {
4066 bool send_referrer = false;
4068 // All navigations to or from WebUI URLs or within WebUI-enabled
4069 // RenderProcesses must be handled by the browser process so that the
4070 // correct bindings and data sources can be registered.
4071 // Similarly, navigations to view-source URLs or within ViewSource mode
4072 // must be handled by the browser process (except for reloads - those are
4073 // safe to leave within the renderer).
4074 // Lastly, access to file:// URLs from non-file:// URL pages must be
4075 // handled by the browser so that ordinary renderer processes don't get
4076 // blessed with file permissions.
4077 int cumulative_bindings = RenderProcess::current()->GetEnabledBindings();
4078 bool is_initial_navigation = render_view_->page_id_ == -1;
4079 bool should_fork = HasWebUIScheme(url) || HasWebUIScheme(old_url) ||
4080 (cumulative_bindings & BINDINGS_POLICY_WEB_UI) ||
4081 url.SchemeIs(kViewSourceScheme) ||
4082 (info.frame->isViewSourceModeEnabled() &&
4083 info.navigationType != blink::WebNavigationTypeReload);
4085 if (!should_fork && url.SchemeIs(url::kFileScheme)) {
4086 // Fork non-file to file opens. Check the opener URL if this is the
4087 // initial navigation in a newly opened window.
4088 GURL source_url(old_url);
4089 if (is_initial_navigation && source_url.is_empty() &&
4090 info.frame->opener())
4091 source_url = info.frame->opener()->top()->document().url();
4092 DCHECK(!source_url.is_empty());
4093 should_fork = !source_url.SchemeIs(url::kFileScheme);
4096 if (!should_fork) {
4097 // Give the embedder a chance.
4098 should_fork = GetContentClient()->renderer()->ShouldFork(
4099 info.frame, url, info.urlRequest.httpMethod().utf8(),
4100 is_initial_navigation, info.isRedirect, &send_referrer);
4103 if (should_fork) {
4104 OpenURL(info.frame, url, send_referrer ? referrer : Referrer(),
4105 info.defaultPolicy);
4106 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
4110 // Detect when a page is "forking" a new tab that can be safely rendered in
4111 // its own process. This is done by sites like Gmail that try to open links
4112 // in new windows without script connections back to the original page. We
4113 // treat such cases as browser navigations (in which we will create a new
4114 // renderer for a cross-site navigation), rather than WebKit navigations.
4116 // We use the following heuristic to decide whether to fork a new page in its
4117 // own process:
4118 // The parent page must open a new tab to about:blank, set the new tab's
4119 // window.opener to null, and then redirect the tab to a cross-site URL using
4120 // JavaScript.
4122 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
4123 // (see below).
4124 bool is_fork =
4125 // Must start from a tab showing about:blank, which is later redirected.
4126 old_url == GURL(url::kAboutBlankURL) &&
4127 // Must be the first real navigation of the tab.
4128 render_view_->historyBackListCount() < 1 &&
4129 render_view_->historyForwardListCount() < 1 &&
4130 // The parent page must have set the child's window.opener to null before
4131 // redirecting to the desired URL.
4132 info.frame->opener() == NULL &&
4133 // Must be a top-level frame.
4134 info.frame->parent() == NULL &&
4135 // Must not have issued the request from this page.
4136 is_content_initiated &&
4137 // Must be targeted at the current tab.
4138 info.defaultPolicy == blink::WebNavigationPolicyCurrentTab &&
4139 // Must be a JavaScript navigation, which appears as "other".
4140 info.navigationType == blink::WebNavigationTypeOther;
4142 if (is_fork) {
4143 // Open the URL via the browser, not via WebKit.
4144 OpenURL(info.frame, url, Referrer(), info.defaultPolicy);
4145 return blink::WebNavigationPolicyIgnore;
4148 // PlzNavigate: send the request to the browser if needed.
4149 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4150 switches::kEnableBrowserSideNavigation) &&
4151 info.urlRequest.checkForBrowserSideNavigation()) {
4152 BeginNavigation(&info.urlRequest);
4153 return blink::WebNavigationPolicyIgnore;
4156 return info.defaultPolicy;
4159 void RenderFrameImpl::OpenURL(WebFrame* frame,
4160 const GURL& url,
4161 const Referrer& referrer,
4162 WebNavigationPolicy policy) {
4163 DCHECK_EQ(frame_, frame);
4165 FrameHostMsg_OpenURL_Params params;
4166 params.url = url;
4167 params.referrer = referrer;
4168 params.disposition = RenderViewImpl::NavigationPolicyToDisposition(policy);
4169 WebDataSource* ds = frame->provisionalDataSource();
4170 if (ds) {
4171 DocumentState* document_state = DocumentState::FromDataSource(ds);
4172 NavigationState* navigation_state = document_state->navigation_state();
4173 if (navigation_state->is_content_initiated()) {
4174 params.should_replace_current_entry =
4175 ds->replacesCurrentHistoryItem() &&
4176 render_view_->history_list_length_;
4177 } else {
4178 // This is necessary to preserve the should_replace_current_entry value on
4179 // cross-process redirects, in the event it was set by a previous process.
4181 // TODO(davidben): Avoid this awkward duplication of state. See comment on
4182 // NavigationState::should_replace_current_entry().
4183 params.should_replace_current_entry =
4184 navigation_state->should_replace_current_entry();
4186 } else {
4187 params.should_replace_current_entry = false;
4189 params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
4190 if (GetContentClient()->renderer()->AllowPopup())
4191 params.user_gesture = true;
4193 if (policy == blink::WebNavigationPolicyNewBackgroundTab ||
4194 policy == blink::WebNavigationPolicyNewForegroundTab ||
4195 policy == blink::WebNavigationPolicyNewWindow ||
4196 policy == blink::WebNavigationPolicyNewPopup) {
4197 WebUserGestureIndicator::consumeUserGesture();
4200 Send(new FrameHostMsg_OpenURL(routing_id_, params));
4203 void RenderFrameImpl::UpdateEncoding(WebFrame* frame,
4204 const std::string& encoding_name) {
4205 // Only update main frame's encoding_name.
4206 if (!frame->parent())
4207 Send(new FrameHostMsg_UpdateEncoding(routing_id_, encoding_name));
4210 void RenderFrameImpl::SyncSelectionIfRequired() {
4211 base::string16 text;
4212 size_t offset;
4213 gfx::Range range;
4214 #if defined(ENABLE_PLUGINS)
4215 if (render_view_->focused_pepper_plugin_) {
4216 render_view_->focused_pepper_plugin_->GetSurroundingText(&text, &range);
4217 offset = 0; // Pepper API does not support offset reporting.
4218 // TODO(kinaba): cut as needed.
4219 } else
4220 #endif
4222 size_t location, length;
4223 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4224 &location, &length)) {
4225 return;
4228 range = gfx::Range(location, location + length);
4230 if (GetRenderWidget()->webwidget()->textInputInfo().type !=
4231 blink::WebTextInputTypeNone) {
4232 // If current focused element is editable, we will send 100 more chars
4233 // before and after selection. It is for input method surrounding text
4234 // feature.
4235 if (location > kExtraCharsBeforeAndAfterSelection)
4236 offset = location - kExtraCharsBeforeAndAfterSelection;
4237 else
4238 offset = 0;
4239 length = location + length - offset + kExtraCharsBeforeAndAfterSelection;
4240 WebRange webrange = WebRange::fromDocumentRange(frame_, offset, length);
4241 if (!webrange.isNull())
4242 text = webrange.toPlainText();
4243 } else {
4244 offset = location;
4245 text = frame_->selectionAsText();
4246 // http://crbug.com/101435
4247 // In some case, frame->selectionAsText() returned text's length is not
4248 // equal to the length returned from webwidget()->caretOrSelectionRange().
4249 // So we have to set the range according to text.length().
4250 range.set_end(range.start() + text.length());
4254 // Sometimes we get repeated didChangeSelection calls from webkit when
4255 // the selection hasn't actually changed. We don't want to report these
4256 // because it will cause us to continually claim the X clipboard.
4257 if (selection_text_offset_ != offset ||
4258 selection_range_ != range ||
4259 selection_text_ != text) {
4260 selection_text_ = text;
4261 selection_text_offset_ = offset;
4262 selection_range_ = range;
4263 SetSelectedText(text, offset, range);
4265 GetRenderWidget()->UpdateSelectionBounds();
4268 void RenderFrameImpl::InitializeUserMediaClient() {
4269 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4270 return;
4272 #if defined(OS_ANDROID)
4273 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4274 switches::kDisableWebRTC))
4275 return;
4276 #endif
4278 #if defined(ENABLE_WEBRTC)
4279 DCHECK(!web_user_media_client_);
4280 web_user_media_client_ = new UserMediaClientImpl(
4281 this,
4282 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4283 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4284 #endif
4287 WebMediaPlayer* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4288 const blink::WebURL& url,
4289 WebMediaPlayerClient* client) {
4290 #if defined(ENABLE_WEBRTC)
4291 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4292 bool found_neon =
4293 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0;
4294 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon);
4295 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4296 return new WebMediaPlayerMS(frame_, client, weak_factory_.GetWeakPtr(),
4297 new RenderMediaLog(),
4298 CreateRendererFactory());
4299 #else
4300 return NULL;
4301 #endif // defined(ENABLE_WEBRTC)
4304 scoped_ptr<MediaStreamRendererFactory>
4305 RenderFrameImpl::CreateRendererFactory() {
4306 #if defined(ENABLE_WEBRTC)
4307 return scoped_ptr<MediaStreamRendererFactory>(
4308 new MediaStreamRendererFactory());
4309 #else
4310 return scoped_ptr<MediaStreamRendererFactory>(
4311 static_cast<MediaStreamRendererFactory*>(NULL));
4312 #endif
4315 bool RenderFrameImpl::PrepareRenderViewForNavigation(
4316 const GURL& url,
4317 bool check_for_stale_navigation,
4318 bool is_history_navigation,
4319 int current_history_list_offset,
4320 bool* is_reload,
4321 WebURLRequest::CachePolicy* cache_policy) {
4322 MaybeHandleDebugURL(url);
4323 if (!render_view_->webview())
4324 return false;
4326 FOR_EACH_OBSERVER(
4327 RenderViewObserver, render_view_->observers_, Navigate(url));
4329 // If this is a stale back/forward (due to a recent navigation the browser
4330 // didn't know about), ignore it. Only check if swapped in because if the
4331 // frame is swapped out, it won't commit before asking the browser.
4332 // TODO(clamy): remove check_for_stale_navigation
4333 if (check_for_stale_navigation &&
4334 !render_view_->is_swapped_out() && is_history_navigation &&
4335 render_view_->history_list_offset_ != current_history_list_offset) {
4336 return false;
4339 if (!is_swapped_out_ || frame_->parent())
4340 return true;
4342 // This is a swapped out main frame, so swap the renderer back in.
4343 // We marked the view as hidden when swapping the view out, so be sure to
4344 // reset the visibility state before navigating to the new URL.
4345 render_view_->webview()->setVisibilityState(
4346 render_view_->visibilityState(), false);
4348 // If this is an attempt to reload while we are swapped out, we should not
4349 // reload swappedout://, but the previous page, which is stored in
4350 // params.state. Setting is_reload to false will treat this like a back
4351 // navigation to accomplish that.
4352 *is_reload = false;
4353 *cache_policy = WebURLRequest::ReloadIgnoringCacheData;
4355 // We refresh timezone when a view is swapped in since timezone
4356 // can get out of sync when the system timezone is updated while
4357 // the view is swapped out.
4358 RenderThreadImpl::NotifyTimezoneChange();
4360 render_view_->SetSwappedOut(false);
4361 is_swapped_out_ = false;
4362 return true;
4365 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest* request) {
4366 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4367 switches::kEnableBrowserSideNavigation));
4368 DCHECK(request);
4369 // TODO(clamy): Execute the beforeunload event.
4371 // Note: At this stage, the goal is to apply all the modifications the
4372 // renderer wants to make to the request, and then send it to the browser, so
4373 // that the actual network request can be started. Ideally, all such
4374 // modifications should take place in willSendRequest, and in the
4375 // implementation of willSendRequest for the various InspectorAgents
4376 // (devtools).
4378 // TODO(clamy): Apply devtools override.
4379 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4380 // else in blink.
4381 willSendRequest(frame_, 0, *request, blink::WebURLResponse());
4383 // TODO(clamy): Same-document navigations should not be sent back to the
4384 // browser.
4385 // TODO(clamy): Data urls should not be sent back to the browser either.
4386 Send(new FrameHostMsg_DidStartLoading(routing_id_, true));
4387 Send(new FrameHostMsg_BeginNavigation(
4388 routing_id_, MakeCommonNavigationParams(request),
4389 BeginNavigationParams(request->httpMethod().latin1(),
4390 GetWebURLRequestHeaders(*request),
4391 GetLoadFlagsForWebURLRequest(*request),
4392 request->hasUserGesture()),
4393 GetRequestBodyForWebURLRequest(*request)));
4396 void RenderFrameImpl::LoadDataURL(const CommonNavigationParams& params,
4397 WebFrame* frame) {
4398 // A loadData request with a specified base URL.
4399 std::string mime_type, charset, data;
4400 if (net::DataURL::Parse(params.url, &mime_type, &charset, &data)) {
4401 const GURL base_url = params.base_url_for_data_url.is_empty() ?
4402 params.url : params.base_url_for_data_url;
4403 frame->loadData(
4404 WebData(data.c_str(), data.length()),
4405 WebString::fromUTF8(mime_type),
4406 WebString::fromUTF8(charset),
4407 base_url,
4408 params.history_url_for_data_url,
4409 false);
4410 } else {
4411 CHECK(false) << "Invalid URL passed: "
4412 << params.url.possibly_invalid_spec();
4416 GURL RenderFrameImpl::GetLoadingUrl() const {
4417 WebDataSource* ds = frame_->dataSource();
4418 if (ds->hasUnreachableURL())
4419 return ds->unreachableURL();
4421 const WebURLRequest& request = ds->request();
4422 return request.url();
4425 #if defined(OS_ANDROID)
4427 WebMediaPlayer* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4428 const blink::WebURL& url,
4429 WebMediaPlayerClient* client,
4430 media::MediaPermission* media_permission,
4431 blink::WebContentDecryptionModule* initial_cdm) {
4432 GpuChannelHost* gpu_channel_host =
4433 RenderThreadImpl::current()->EstablishGpuChannelSync(
4434 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE);
4435 if (!gpu_channel_host) {
4436 LOG(ERROR) << "Failed to establish GPU channel for media player";
4437 return NULL;
4440 scoped_refptr<StreamTextureFactory> stream_texture_factory;
4441 if (SynchronousCompositorFactory* factory =
4442 SynchronousCompositorFactory::GetInstance()) {
4443 stream_texture_factory = factory->CreateStreamTextureFactory(routing_id_);
4444 } else {
4445 scoped_refptr<cc_blink::ContextProviderWebContext> context_provider =
4446 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4448 if (!context_provider.get()) {
4449 LOG(ERROR) << "Failed to get context3d for media player";
4450 return NULL;
4453 stream_texture_factory = StreamTextureFactoryImpl::Create(
4454 context_provider, gpu_channel_host, routing_id_);
4457 return new WebMediaPlayerAndroid(
4458 frame_,
4459 client,
4460 weak_factory_.GetWeakPtr(),
4461 GetMediaPlayerManager(),
4462 GetCdmManager(),
4463 media_permission,
4464 initial_cdm,
4465 stream_texture_factory,
4466 RenderThreadImpl::current()->GetMediaThreadTaskRunner(),
4467 new RenderMediaLog());
4470 RendererMediaPlayerManager* RenderFrameImpl::GetMediaPlayerManager() {
4471 if (!media_player_manager_)
4472 media_player_manager_ = new RendererMediaPlayerManager(this);
4473 return media_player_manager_;
4476 #endif // defined(OS_ANDROID)
4478 #if defined(ENABLE_BROWSER_CDMS)
4479 RendererCdmManager* RenderFrameImpl::GetCdmManager() {
4480 if (!cdm_manager_)
4481 cdm_manager_ = new RendererCdmManager(this);
4482 return cdm_manager_;
4484 #endif // defined(ENABLE_BROWSER_CDMS)
4486 } // namespace content