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