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