Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / content / renderer / render_view_impl.cc
1 // Copyright (c) 2012 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_view_impl.h"
6
7 #include <algorithm>
8 #include <cmath>
9
10 #include "base/auto_reset.h"
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/command_line.h"
14 #include "base/compiler_specific.h"
15 #include "base/debug/alias.h"
16 #include "base/debug/trace_event.h"
17 #include "base/files/file_path.h"
18 #include "base/i18n/rtl.h"
19 #include "base/json/json_writer.h"
20 #include "base/lazy_instance.h"
21 #include "base/memory/scoped_ptr.h"
22 #include "base/message_loop/message_loop_proxy.h"
23 #include "base/metrics/histogram.h"
24 #include "base/path_service.h"
25 #include "base/process/kill.h"
26 #include "base/process/process.h"
27 #include "base/strings/string_number_conversions.h"
28 #include "base/strings/string_piece.h"
29 #include "base/strings/string_split.h"
30 #include "base/strings/string_util.h"
31 #include "base/strings/sys_string_conversions.h"
32 #include "base/strings/utf_string_conversions.h"
33 #include "base/time/time.h"
34 #include "cc/base/switches.h"
35 #include "content/child/appcache/appcache_dispatcher.h"
36 #include "content/child/appcache/web_application_cache_host_impl.h"
37 #include "content/child/child_thread.h"
38 #include "content/child/npapi/webplugin_delegate_impl.h"
39 #include "content/child/request_extra_data.h"
40 #include "content/child/webmessageportchannel_impl.h"
41 #include "content/common/clipboard_messages.h"
42 #include "content/common/database_messages.h"
43 #include "content/common/dom_storage/dom_storage_types.h"
44 #include "content/common/drag_messages.h"
45 #include "content/common/frame_messages.h"
46 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
47 #include "content/common/input_messages.h"
48 #include "content/common/java_bridge_messages.h"
49 #include "content/common/pepper_messages.h"
50 #include "content/common/socket_stream_handle_data.h"
51 #include "content/common/ssl_status_serialization.h"
52 #include "content/common/view_messages.h"
53 #include "content/public/common/bindings_policy.h"
54 #include "content/public/common/content_client.h"
55 #include "content/public/common/content_constants.h"
56 #include "content/public/common/content_switches.h"
57 #include "content/public/common/drop_data.h"
58 #include "content/public/common/favicon_url.h"
59 #include "content/public/common/file_chooser_params.h"
60 #include "content/public/common/page_zoom.h"
61 #include "content/public/common/ssl_status.h"
62 #include "content/public/common/three_d_api_types.h"
63 #include "content/public/common/url_constants.h"
64 #include "content/public/common/url_utils.h"
65 #include "content/public/renderer/content_renderer_client.h"
66 #include "content/public/renderer/document_state.h"
67 #include "content/public/renderer/history_item_serialization.h"
68 #include "content/public/renderer/navigation_state.h"
69 #include "content/public/renderer/render_view_observer.h"
70 #include "content/public/renderer/render_view_visitor.h"
71 #include "content/public/renderer/web_preferences.h"
72 #include "content/renderer/accessibility/renderer_accessibility.h"
73 #include "content/renderer/accessibility/renderer_accessibility_complete.h"
74 #include "content/renderer/accessibility/renderer_accessibility_focus_only.h"
75 #include "content/renderer/browser_plugin/browser_plugin.h"
76 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
77 #include "content/renderer/browser_plugin/browser_plugin_manager_impl.h"
78 #include "content/renderer/devtools/devtools_agent.h"
79 #include "content/renderer/disambiguation_popup_helper.h"
80 #include "content/renderer/dom_automation_controller.h"
81 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
82 #include "content/renderer/drop_data_builder.h"
83 #include "content/renderer/external_popup_menu.h"
84 #include "content/renderer/geolocation_dispatcher.h"
85 #include "content/renderer/gpu/render_widget_compositor.h"
86 #include "content/renderer/idle_user_detector.h"
87 #include "content/renderer/image_loading_helper.h"
88 #include "content/renderer/ime_event_guard.h"
89 #include "content/renderer/input/input_handler_manager.h"
90 #include "content/renderer/input_tag_speech_dispatcher.h"
91 #include "content/renderer/internal_document_state_data.h"
92 #include "content/renderer/java/java_bridge_dispatcher.h"
93 #include "content/renderer/load_progress_tracker.h"
94 #include "content/renderer/media/audio_device_factory.h"
95 #include "content/renderer/media/audio_renderer_mixer_manager.h"
96 #include "content/renderer/media/media_stream_dependency_factory.h"
97 #include "content/renderer/media/media_stream_dispatcher.h"
98 #include "content/renderer/media/media_stream_impl.h"
99 #include "content/renderer/media/midi_dispatcher.h"
100 #include "content/renderer/media/render_media_log.h"
101 #include "content/renderer/media/video_capture_impl_manager.h"
102 #include "content/renderer/media/webmediaplayer_impl.h"
103 #include "content/renderer/media/webmediaplayer_ms.h"
104 #include "content/renderer/media/webmediaplayer_params.h"
105 #include "content/renderer/memory_benchmarking_extension.h"
106 #include "content/renderer/mhtml_generator.h"
107 #include "content/renderer/notification_provider.h"
108 #include "content/renderer/render_frame_impl.h"
109 #include "content/renderer/render_process.h"
110 #include "content/renderer/render_thread_impl.h"
111 #include "content/renderer/render_view_impl_params.h"
112 #include "content/renderer/render_view_mouse_lock_dispatcher.h"
113 #include "content/renderer/render_widget_fullscreen_pepper.h"
114 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
115 #include "content/renderer/renderer_webcolorchooser_impl.h"
116 #include "content/renderer/resizing_mode_selector.h"
117 #include "content/renderer/savable_resources.h"
118 #include "content/renderer/skia_benchmarking_extension.h"
119 #include "content/renderer/speech_recognition_dispatcher.h"
120 #include "content/renderer/stats_collection_controller.h"
121 #include "content/renderer/stats_collection_observer.h"
122 #include "content/renderer/text_input_client_observer.h"
123 #include "content/renderer/v8_value_converter_impl.h"
124 #include "content/renderer/web_ui_extension.h"
125 #include "content/renderer/web_ui_extension_data.h"
126 #include "content/renderer/websharedworker_proxy.h"
127 #include "media/audio/audio_output_device.h"
128 #include "media/base/audio_renderer_mixer_input.h"
129 #include "media/base/filter_collection.h"
130 #include "media/base/media_switches.h"
131 #include "media/filters/audio_renderer_impl.h"
132 #include "media/filters/gpu_video_accelerator_factories.h"
133 #include "net/base/data_url.h"
134 #include "net/base/escape.h"
135 #include "net/base/net_errors.h"
136 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
137 #include "net/http/http_util.h"
138 #include "third_party/WebKit/public/platform/WebCString.h"
139 #include "third_party/WebKit/public/platform/WebDragData.h"
140 #include "third_party/WebKit/public/platform/WebHTTPBody.h"
141 #include "third_party/WebKit/public/platform/WebImage.h"
142 #include "third_party/WebKit/public/platform/WebMessagePortChannel.h"
143 #include "third_party/WebKit/public/platform/WebPoint.h"
144 #include "third_party/WebKit/public/platform/WebRect.h"
145 #include "third_party/WebKit/public/platform/WebSize.h"
146 #include "third_party/WebKit/public/platform/WebSocketStreamHandle.h"
147 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
148 #include "third_party/WebKit/public/platform/WebString.h"
149 #include "third_party/WebKit/public/platform/WebURL.h"
150 #include "third_party/WebKit/public/platform/WebURLError.h"
151 #include "third_party/WebKit/public/platform/WebURLRequest.h"
152 #include "third_party/WebKit/public/platform/WebURLResponse.h"
153 #include "third_party/WebKit/public/platform/WebVector.h"
154 #include "third_party/WebKit/public/web/WebAXObject.h"
155 #include "third_party/WebKit/public/web/WebColorName.h"
156 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
157 #include "third_party/WebKit/public/web/WebDOMEvent.h"
158 #include "third_party/WebKit/public/web/WebDOMMessageEvent.h"
159 #include "third_party/WebKit/public/web/WebDataSource.h"
160 #include "third_party/WebKit/public/web/WebDateTimeChooserCompletion.h"
161 #include "third_party/WebKit/public/web/WebDateTimeChooserParams.h"
162 #include "third_party/WebKit/public/web/WebDevToolsAgent.h"
163 #include "third_party/WebKit/public/web/WebDocument.h"
164 #include "third_party/WebKit/public/web/WebElement.h"
165 #include "third_party/WebKit/public/web/WebFileChooserParams.h"
166 #include "third_party/WebKit/public/web/WebFindOptions.h"
167 #include "third_party/WebKit/public/web/WebFormControlElement.h"
168 #include "third_party/WebKit/public/web/WebFormElement.h"
169 #include "third_party/WebKit/public/web/WebFrame.h"
170 #include "third_party/WebKit/public/web/WebGlyphCache.h"
171 #include "third_party/WebKit/public/web/WebHelperPlugin.h"
172 #include "third_party/WebKit/public/web/WebHistoryItem.h"
173 #include "third_party/WebKit/public/web/WebInputElement.h"
174 #include "third_party/WebKit/public/web/WebInputEvent.h"
175 #include "third_party/WebKit/public/web/WebMediaPlayerAction.h"
176 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
177 #include "third_party/WebKit/public/web/WebNodeList.h"
178 #include "third_party/WebKit/public/web/WebPageSerializer.h"
179 #include "third_party/WebKit/public/web/WebPlugin.h"
180 #include "third_party/WebKit/public/web/WebPluginAction.h"
181 #include "third_party/WebKit/public/web/WebPluginContainer.h"
182 #include "third_party/WebKit/public/web/WebPluginDocument.h"
183 #include "third_party/WebKit/public/web/WebRange.h"
184 #include "third_party/WebKit/public/web/WebScriptSource.h"
185 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
186 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
187 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
188 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
189 #include "third_party/WebKit/public/web/WebSettings.h"
190 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
191 #include "third_party/WebKit/public/web/WebUserMediaClient.h"
192 #include "third_party/WebKit/public/web/WebView.h"
193 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
194 #include "third_party/WebKit/public/web/default/WebRenderTheme.h"
195 #include "ui/base/ui_base_switches_util.h"
196 #include "ui/events/latency_info.h"
197 #include "ui/gfx/native_widget_types.h"
198 #include "ui/gfx/point.h"
199 #include "ui/gfx/rect.h"
200 #include "ui/gfx/rect_conversions.h"
201 #include "ui/gfx/size_conversions.h"
202 #include "ui/shell_dialogs/selected_file_info.h"
203 #include "v8/include/v8.h"
204 #include "webkit/child/weburlresponse_extradata_impl.h"
205
206 #if defined(OS_ANDROID)
207 #include <cpu-features.h>
208
209 #include "content/common/android/device_telephony_info.h"
210 #include "content/common/gpu/client/context_provider_command_buffer.h"
211 #include "content/renderer/android/address_detector.h"
212 #include "content/renderer/android/content_detector.h"
213 #include "content/renderer/android/email_detector.h"
214 #include "content/renderer/android/phone_number_detector.h"
215 #include "content/renderer/android/synchronous_compositor_factory.h"
216 #include "content/renderer/media/android/renderer_media_player_manager.h"
217 #include "content/renderer/media/android/stream_texture_factory_android_impl.h"
218 #include "content/renderer/media/android/webmediaplayer_android.h"
219 #include "skia/ext/platform_canvas.h"
220 #include "third_party/WebKit/public/platform/WebFloatPoint.h"
221 #include "third_party/WebKit/public/platform/WebFloatRect.h"
222 #include "third_party/WebKit/public/web/WebHitTestResult.h"
223 #include "ui/gfx/rect_f.h"
224
225 #elif defined(OS_WIN)
226 // TODO(port): these files are currently Windows only because they concern:
227 //   * theming
228 #include "ui/native_theme/native_theme_win.h"
229 #elif defined(USE_X11)
230 #include "ui/native_theme/native_theme.h"
231 #elif defined(OS_MACOSX)
232 #include "skia/ext/skia_utils_mac.h"
233 #endif
234
235 #if defined(ENABLE_PLUGINS)
236 #include "content/renderer/npapi/webplugin_delegate_proxy.h"
237 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
238 #include "content/renderer/pepper/pepper_plugin_registry.h"
239 #endif
240
241 #if defined(ENABLE_WEBRTC)
242 #include "content/renderer/media/rtc_peer_connection_handler.h"
243 #endif
244
245 using blink::WebAXObject;
246 using blink::WebApplicationCacheHost;
247 using blink::WebApplicationCacheHostClient;
248 using blink::WebCString;
249 using blink::WebColor;
250 using blink::WebColorName;
251 using blink::WebConsoleMessage;
252 using blink::WebData;
253 using blink::WebDataSource;
254 using blink::WebDocument;
255 using blink::WebDOMEvent;
256 using blink::WebDOMMessageEvent;
257 using blink::WebDragData;
258 using blink::WebDragOperation;
259 using blink::WebDragOperationsMask;
260 using blink::WebElement;
261 using blink::WebExternalPopupMenu;
262 using blink::WebExternalPopupMenuClient;
263 using blink::WebFileChooserCompletion;
264 using blink::WebFindOptions;
265 using blink::WebFormControlElement;
266 using blink::WebFormElement;
267 using blink::WebFrame;
268 using blink::WebGestureEvent;
269 using blink::WebHistoryItem;
270 using blink::WebHTTPBody;
271 using blink::WebIconURL;
272 using blink::WebImage;
273 using blink::WebInputElement;
274 using blink::WebInputEvent;
275 using blink::WebMediaPlayer;
276 using blink::WebMediaPlayerAction;
277 using blink::WebMediaPlayerClient;
278 using blink::WebMouseEvent;
279 using blink::WebNavigationPolicy;
280 using blink::WebNavigationType;
281 using blink::WebNode;
282 using blink::WebPageSerializer;
283 using blink::WebPageSerializerClient;
284 using blink::WebPeerConnection00Handler;
285 using blink::WebPeerConnection00HandlerClient;
286 using blink::WebPeerConnectionHandler;
287 using blink::WebPeerConnectionHandlerClient;
288 using blink::WebPluginAction;
289 using blink::WebPluginContainer;
290 using blink::WebPluginDocument;
291 using blink::WebPoint;
292 using blink::WebPopupMenuInfo;
293 using blink::WebRange;
294 using blink::WebRect;
295 using blink::WebReferrerPolicy;
296 using blink::WebScriptSource;
297 using blink::WebSearchableFormData;
298 using blink::WebSecurityOrigin;
299 using blink::WebSecurityPolicy;
300 using blink::WebSerializedScriptValue;
301 using blink::WebSettings;
302 using blink::WebSize;
303 using blink::WebSocketStreamHandle;
304 using blink::WebStorageNamespace;
305 using blink::WebStorageQuotaCallbacks;
306 using blink::WebStorageQuotaError;
307 using blink::WebStorageQuotaType;
308 using blink::WebString;
309 using blink::WebTextAffinity;
310 using blink::WebTextDirection;
311 using blink::WebTouchEvent;
312 using blink::WebURL;
313 using blink::WebURLError;
314 using blink::WebURLRequest;
315 using blink::WebURLResponse;
316 using blink::WebUserGestureIndicator;
317 using blink::WebVector;
318 using blink::WebView;
319 using blink::WebWidget;
320 using blink::WebWindowFeatures;
321 using base::Time;
322 using base::TimeDelta;
323 using webkit_glue::WebURLResponseExtraDataImpl;
324
325 #if defined(OS_ANDROID)
326 using blink::WebContentDetectionResult;
327 using blink::WebFloatPoint;
328 using blink::WebFloatRect;
329 using blink::WebHitTestResult;
330 #endif
331
332 namespace content {
333
334 //-----------------------------------------------------------------------------
335
336 typedef std::map<blink::WebView*, RenderViewImpl*> ViewMap;
337 static base::LazyInstance<ViewMap> g_view_map = LAZY_INSTANCE_INITIALIZER;
338 typedef std::map<int32, RenderViewImpl*> RoutingIDViewMap;
339 static base::LazyInstance<RoutingIDViewMap> g_routing_id_view_map =
340     LAZY_INSTANCE_INITIALIZER;
341
342 // Time, in seconds, we delay before sending content state changes (such as form
343 // state and scroll position) to the browser. We delay sending changes to avoid
344 // spamming the browser.
345 // To avoid having tab/session restore require sending a message to get the
346 // current content state during tab closing we use a shorter timeout for the
347 // foreground renderer. This means there is a small window of time from which
348 // content state is modified and not sent to session restore, but this is
349 // better than having to wake up all renderers during shutdown.
350 const int kDelaySecondsForContentStateSyncHidden = 5;
351 const int kDelaySecondsForContentStateSync = 1;
352
353 const size_t kExtraCharsBeforeAndAfterSelection = 100;
354
355 const float kScalingIncrementForGesture = 0.01f;
356
357 #if defined(OS_ANDROID)
358 // Delay between tapping in content and launching the associated android intent.
359 // Used to allow users see what has been recognized as content.
360 const size_t kContentIntentDelayMilliseconds = 700;
361 #endif
362
363 static RenderViewImpl* (*g_create_render_view_impl)(RenderViewImplParams*) =
364     NULL;
365
366 // static
367 bool RenderViewImpl::IsReload(const FrameMsg_Navigate_Params& params) {
368   return
369       params.navigation_type == FrameMsg_Navigate_Type::RELOAD ||
370       params.navigation_type == FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE ||
371       params.navigation_type ==
372           FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL;
373 }
374
375 // static
376 Referrer RenderViewImpl::GetReferrerFromRequest(
377     WebFrame* frame,
378     const WebURLRequest& request) {
379   return Referrer(GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
380                   request.referrerPolicy());
381 }
382
383 // Returns false unless this is a top-level navigation.
384 static bool IsTopLevelNavigation(WebFrame* frame) {
385   return frame->parent() == NULL;
386 }
387
388 // Returns false unless this is a top-level navigation that crosses origins.
389 static bool IsNonLocalTopLevelNavigation(const GURL& url,
390                                          WebFrame* frame,
391                                          WebNavigationType type,
392                                          bool is_form_post) {
393   if (!IsTopLevelNavigation(frame))
394     return false;
395
396   // Navigations initiated within Webkit are not sent out to the external host
397   // in the following cases.
398   // 1. The url scheme is not http/https
399   // 2. The origin of the url and the opener is the same in which case the
400   //    opener relationship is maintained.
401   // 3. Reloads/form submits/back forward navigations
402   if (!url.SchemeIs(kHttpScheme) && !url.SchemeIs(kHttpsScheme))
403     return false;
404
405   if (type != blink::WebNavigationTypeReload &&
406       type != blink::WebNavigationTypeBackForward && !is_form_post) {
407     // The opener relationship between the new window and the parent allows the
408     // new window to script the parent and vice versa. This is not allowed if
409     // the origins of the two domains are different. This can be treated as a
410     // top level navigation and routed back to the host.
411     blink::WebFrame* opener = frame->opener();
412     if (!opener)
413       return true;
414
415     if (url.GetOrigin() != GURL(opener->document().url()).GetOrigin())
416       return true;
417   }
418   return false;
419 }
420
421 // static
422 void RenderViewImpl::NotifyTimezoneChange(blink::WebFrame* frame) {
423   v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
424   v8::Context::Scope context_scope(frame->mainWorldScriptContext());
425   v8::Date::DateTimeConfigurationChangeNotification(v8::Isolate::GetCurrent());
426   blink::WebFrame* child = frame->firstChild();
427   for (; child; child = child->nextSibling())
428     NotifyTimezoneChange(child);
429 }
430
431 static WindowOpenDisposition NavigationPolicyToDisposition(
432     WebNavigationPolicy policy) {
433   switch (policy) {
434     case blink::WebNavigationPolicyIgnore:
435       return IGNORE_ACTION;
436     case blink::WebNavigationPolicyDownload:
437       return SAVE_TO_DISK;
438     case blink::WebNavigationPolicyCurrentTab:
439       return CURRENT_TAB;
440     case blink::WebNavigationPolicyNewBackgroundTab:
441       return NEW_BACKGROUND_TAB;
442     case blink::WebNavigationPolicyNewForegroundTab:
443       return NEW_FOREGROUND_TAB;
444     case blink::WebNavigationPolicyNewWindow:
445       return NEW_WINDOW;
446     case blink::WebNavigationPolicyNewPopup:
447       return NEW_POPUP;
448   default:
449     NOTREACHED() << "Unexpected WebNavigationPolicy";
450     return IGNORE_ACTION;
451   }
452 }
453
454 // Returns true if the device scale is high enough that losing subpixel
455 // antialiasing won't have a noticeable effect on text quality.
456 static bool DeviceScaleEnsuresTextQuality(float device_scale_factor) {
457 #if defined(OS_ANDROID)
458   // On Android, we never have subpixel antialiasing.
459   return true;
460 #else
461   return device_scale_factor > 1.5f;
462 #endif
463
464 }
465
466 static bool ShouldUseFixedPositionCompositing(float device_scale_factor) {
467   // Compositing for fixed-position elements is dependent on
468   // device_scale_factor if no flag is set. http://crbug.com/172738
469   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
470
471   if (command_line.HasSwitch(switches::kDisableCompositingForFixedPosition))
472     return false;
473
474   if (command_line.HasSwitch(switches::kEnableCompositingForFixedPosition))
475     return true;
476
477   return DeviceScaleEnsuresTextQuality(device_scale_factor);
478 }
479
480 static bool ShouldUseAcceleratedCompositingForOverflowScroll(
481     float device_scale_factor) {
482   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
483
484   if (command_line.HasSwitch(switches::kDisableAcceleratedOverflowScroll))
485     return false;
486
487   if (command_line.HasSwitch(switches::kEnableAcceleratedOverflowScroll))
488     return true;
489
490   return DeviceScaleEnsuresTextQuality(device_scale_factor);
491 }
492
493 static bool ShouldUseAcceleratedCompositingForScrollableFrames(
494     float device_scale_factor) {
495   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
496
497   if (command_line.HasSwitch(switches::kDisableAcceleratedScrollableFrames))
498     return false;
499
500   if (command_line.HasSwitch(switches::kEnableAcceleratedScrollableFrames))
501     return true;
502
503   if (!cc::switches::IsLCDTextEnabled())
504     return true;
505
506   return DeviceScaleEnsuresTextQuality(device_scale_factor);
507 }
508
509 static bool ShouldUseCompositedScrollingForFrames(
510     float device_scale_factor) {
511   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
512
513   if (command_line.HasSwitch(switches::kDisableCompositedScrollingForFrames))
514     return false;
515
516   if (command_line.HasSwitch(switches::kEnableCompositedScrollingForFrames))
517     return true;
518
519   if (!cc::switches::IsLCDTextEnabled())
520     return true;
521
522   return DeviceScaleEnsuresTextQuality(device_scale_factor);
523 }
524
525 static bool ShouldUseUniversalAcceleratedCompositingForOverflowScroll() {
526   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
527
528   if (command_line.HasSwitch(
529           switches::kDisableUniversalAcceleratedOverflowScroll))
530     return false;
531
532   if (command_line.HasSwitch(
533           switches::kEnableUniversalAcceleratedOverflowScroll))
534     return true;
535
536   return false;
537 }
538
539 static bool ShouldUseTransitionCompositing(float device_scale_factor) {
540   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
541
542   if (command_line.HasSwitch(switches::kDisableCompositingForTransition))
543     return false;
544
545   if (command_line.HasSwitch(switches::kEnableCompositingForTransition))
546     return true;
547
548   // TODO(ajuma): Re-enable this by default for high-DPI once the problem
549   // of excessive layer promotion caused by overlap has been addressed.
550   // http://crbug.com/178119.
551   return false;
552 }
553
554 static bool ShouldUseAcceleratedFixedRootBackground(float device_scale_factor) {
555   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
556
557   if (command_line.HasSwitch(switches::kDisableAcceleratedFixedRootBackground))
558     return false;
559
560   if (command_line.HasSwitch(switches::kEnableAcceleratedFixedRootBackground))
561     return true;
562
563   return DeviceScaleEnsuresTextQuality(device_scale_factor);
564 }
565
566 static FaviconURL::IconType ToFaviconType(blink::WebIconURL::Type type) {
567   switch (type) {
568     case blink::WebIconURL::TypeFavicon:
569       return FaviconURL::FAVICON;
570     case blink::WebIconURL::TypeTouch:
571       return FaviconURL::TOUCH_ICON;
572     case blink::WebIconURL::TypeTouchPrecomposed:
573       return FaviconURL::TOUCH_PRECOMPOSED_ICON;
574     case blink::WebIconURL::TypeInvalid:
575       return FaviconURL::INVALID_ICON;
576   }
577   return FaviconURL::INVALID_ICON;
578 }
579
580 ///////////////////////////////////////////////////////////////////////////////
581
582 struct RenderViewImpl::PendingFileChooser {
583   PendingFileChooser(const FileChooserParams& p, WebFileChooserCompletion* c)
584       : params(p),
585         completion(c) {
586   }
587   FileChooserParams params;
588   WebFileChooserCompletion* completion;  // MAY BE NULL to skip callback.
589 };
590
591 namespace {
592
593 class WebWidgetLockTarget : public MouseLockDispatcher::LockTarget {
594  public:
595   explicit WebWidgetLockTarget(blink::WebWidget* webwidget)
596       : webwidget_(webwidget) {}
597
598   virtual void OnLockMouseACK(bool succeeded) OVERRIDE {
599     if (succeeded)
600       webwidget_->didAcquirePointerLock();
601     else
602       webwidget_->didNotAcquirePointerLock();
603   }
604
605   virtual void OnMouseLockLost() OVERRIDE {
606     webwidget_->didLosePointerLock();
607   }
608
609   virtual bool HandleMouseLockedInputEvent(
610       const blink::WebMouseEvent &event) OVERRIDE {
611     // The WebWidget handles mouse lock in WebKit's handleInputEvent().
612     return false;
613   }
614
615  private:
616   blink::WebWidget* webwidget_;
617 };
618
619 bool TouchEnabled() {
620 // Based on the definition of chrome::kEnableTouchIcon.
621 #if defined(OS_ANDROID)
622   return true;
623 #else
624   return false;
625 #endif
626 }
627
628 WebDragData DropDataToWebDragData(const DropData& drop_data) {
629   std::vector<WebDragData::Item> item_list;
630
631   // These fields are currently unused when dragging into WebKit.
632   DCHECK(drop_data.download_metadata.empty());
633   DCHECK(drop_data.file_contents.empty());
634   DCHECK(drop_data.file_description_filename.empty());
635
636   if (!drop_data.text.is_null()) {
637     WebDragData::Item item;
638     item.storageType = WebDragData::Item::StorageTypeString;
639     item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeText);
640     item.stringData = drop_data.text.string();
641     item_list.push_back(item);
642   }
643
644   // TODO(dcheng): Do we need to distinguish between null and empty URLs? Is it
645   // meaningful to write an empty URL to the clipboard?
646   if (!drop_data.url.is_empty()) {
647     WebDragData::Item item;
648     item.storageType = WebDragData::Item::StorageTypeString;
649     item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeURIList);
650     item.stringData = WebString::fromUTF8(drop_data.url.spec());
651     item.title = drop_data.url_title;
652     item_list.push_back(item);
653   }
654
655   if (!drop_data.html.is_null()) {
656     WebDragData::Item item;
657     item.storageType = WebDragData::Item::StorageTypeString;
658     item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeHTML);
659     item.stringData = drop_data.html.string();
660     item.baseURL = drop_data.html_base_url;
661     item_list.push_back(item);
662   }
663
664   for (std::vector<DropData::FileInfo>::const_iterator it =
665            drop_data.filenames.begin();
666        it != drop_data.filenames.end();
667        ++it) {
668     WebDragData::Item item;
669     item.storageType = WebDragData::Item::StorageTypeFilename;
670     item.filenameData = it->path;
671     item.displayNameData = it->display_name;
672     item_list.push_back(item);
673   }
674
675   for (std::map<base::string16, base::string16>::const_iterator it =
676            drop_data.custom_data.begin();
677        it != drop_data.custom_data.end();
678        ++it) {
679     WebDragData::Item item;
680     item.storageType = WebDragData::Item::StorageTypeString;
681     item.stringType = it->first;
682     item.stringData = it->second;
683     item_list.push_back(item);
684   }
685
686   WebDragData result;
687   result.initialize();
688   result.setItems(item_list);
689   result.setFilesystemId(drop_data.filesystem_id);
690   return result;
691 }
692
693 }  // namespace
694
695 RenderViewImpl::RenderViewImpl(RenderViewImplParams* params)
696     : RenderWidget(blink::WebPopupTypeNone,
697                    params->screen_info,
698                    params->swapped_out,
699                    params->hidden),
700       webkit_preferences_(params->webkit_prefs),
701       send_content_state_immediately_(false),
702       enabled_bindings_(0),
703       send_preferred_size_changes_(false),
704       is_loading_(false),
705       navigation_gesture_(NavigationGestureUnknown),
706       opened_by_user_gesture_(true),
707       opener_suppressed_(false),
708       suppress_dialogs_until_swap_out_(false),
709       page_id_(-1),
710       last_page_id_sent_to_browser_(-1),
711       next_page_id_(params->next_page_id),
712       history_list_offset_(-1),
713       history_list_length_(0),
714       target_url_status_(TARGET_NONE),
715       selection_text_offset_(0),
716       selection_range_(gfx::Range::InvalidRange()),
717 #if defined(OS_ANDROID)
718       top_controls_constraints_(cc::BOTH),
719 #endif
720       cached_is_main_frame_pinned_to_left_(false),
721       cached_is_main_frame_pinned_to_right_(false),
722       cached_has_main_frame_horizontal_scrollbar_(false),
723       cached_has_main_frame_vertical_scrollbar_(false),
724       notification_provider_(NULL),
725       geolocation_dispatcher_(NULL),
726       input_tag_speech_dispatcher_(NULL),
727       speech_recognition_dispatcher_(NULL),
728       media_stream_dispatcher_(NULL),
729       browser_plugin_manager_(NULL),
730       media_stream_client_(NULL),
731       web_user_media_client_(NULL),
732       midi_dispatcher_(NULL),
733       devtools_agent_(NULL),
734       accessibility_mode_(AccessibilityModeOff),
735       renderer_accessibility_(NULL),
736       mouse_lock_dispatcher_(NULL),
737 #if defined(OS_ANDROID)
738       body_background_color_(SK_ColorWHITE),
739       expected_content_intent_id_(0),
740       media_player_manager_(NULL),
741 #endif
742 #if defined(OS_WIN)
743       focused_plugin_id_(-1),
744 #endif
745 #if defined(ENABLE_PLUGINS)
746       focused_pepper_plugin_(NULL),
747       pepper_last_mouse_event_target_(NULL),
748 #endif
749       enumeration_completion_id_(0),
750       load_progress_tracker_(new LoadProgressTracker(this)),
751       session_storage_namespace_id_(params->session_storage_namespace_id),
752       handling_select_range_(false),
753       next_snapshot_id_(0),
754       allow_partial_swap_(params->allow_partial_swap) {
755 }
756
757 void RenderViewImpl::Initialize(RenderViewImplParams* params) {
758   routing_id_ = params->routing_id;
759   surface_id_ = params->surface_id;
760   if (params->opener_id != MSG_ROUTING_NONE && params->is_renderer_created)
761     opener_id_ = params->opener_id;
762
763   // Ensure we start with a valid next_page_id_ from the browser.
764   DCHECK_GE(next_page_id_, 0);
765
766 #if defined(ENABLE_NOTIFICATIONS)
767   notification_provider_ = new NotificationProvider(this);
768 #else
769   notification_provider_ = NULL;
770 #endif
771
772   webwidget_ = WebView::create(this);
773   webwidget_mouse_lock_target_.reset(new WebWidgetLockTarget(webwidget_));
774
775   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
776
777   if (command_line.HasSwitch(switches::kStatsCollectionController))
778     stats_collection_observer_.reset(new StatsCollectionObserver(this));
779
780 #if defined(OS_ANDROID)
781   content::DeviceTelephonyInfo device_info;
782
783   const std::string region_code =
784       command_line.HasSwitch(switches::kNetworkCountryIso)
785           ? command_line.GetSwitchValueASCII(switches::kNetworkCountryIso)
786           : device_info.GetNetworkCountryIso();
787   content_detectors_.push_back(linked_ptr<ContentDetector>(
788       new AddressDetector()));
789   content_detectors_.push_back(linked_ptr<ContentDetector>(
790       new PhoneNumberDetector(region_code)));
791   content_detectors_.push_back(linked_ptr<ContentDetector>(
792       new EmailDetector()));
793 #endif
794
795   RenderThread::Get()->AddRoute(routing_id_, this);
796   // Take a reference on behalf of the RenderThread.  This will be balanced
797   // when we receive ViewMsg_ClosePage.
798   AddRef();
799   if (RenderThreadImpl::current()) {
800     RenderThreadImpl::current()->WidgetCreated();
801     if (is_hidden_)
802       RenderThreadImpl::current()->WidgetHidden();
803   }
804
805   // If this is a popup, we must wait for the CreatingNew_ACK message before
806   // completing initialization.  Otherwise, we can finish it now.
807   if (opener_id_ == MSG_ROUTING_NONE) {
808     did_show_ = true;
809     CompleteInit();
810   }
811
812   g_view_map.Get().insert(std::make_pair(webview(), this));
813   g_routing_id_view_map.Get().insert(std::make_pair(routing_id_, this));
814   webview()->setDeviceScaleFactor(device_scale_factor_);
815   webview()->settings()->setAcceleratedCompositingForFixedPositionEnabled(
816       ShouldUseFixedPositionCompositing(device_scale_factor_));
817   webview()->settings()->setAcceleratedCompositingForOverflowScrollEnabled(
818       ShouldUseAcceleratedCompositingForOverflowScroll(device_scale_factor_));
819   webview()->settings()->setCompositorDrivenAcceleratedScrollingEnabled(
820       ShouldUseUniversalAcceleratedCompositingForOverflowScroll());
821   webview()->settings()->setAcceleratedCompositingForTransitionEnabled(
822       ShouldUseTransitionCompositing(device_scale_factor_));
823   webview()->settings()->setAcceleratedCompositingForFixedRootBackgroundEnabled(
824       ShouldUseAcceleratedFixedRootBackground(device_scale_factor_));
825   webview()->settings()->setAcceleratedCompositingForScrollableFramesEnabled(
826       ShouldUseAcceleratedCompositingForScrollableFrames(device_scale_factor_));
827   webview()->settings()->setCompositedScrollingForFramesEnabled(
828       ShouldUseCompositedScrollingForFrames(device_scale_factor_));
829
830   ApplyWebPreferences(webkit_preferences_, webview());
831
832   main_render_frame_.reset(
833       RenderFrameImpl::Create(this, params->main_frame_routing_id));
834   // The main frame WebFrame object is closed by
835   // RenderFrameImpl::frameDetached().
836   webview()->setMainFrame(WebFrame::create(main_render_frame_.get()));
837   main_render_frame_->SetWebFrame(webview()->mainFrame());
838
839   if (switches::IsTouchDragDropEnabled())
840     webview()->settings()->setTouchDragDropEnabled(true);
841
842   if (switches::IsTouchEditingEnabled())
843     webview()->settings()->setTouchEditingEnabled(true);
844
845   if (!params->frame_name.empty())
846     webview()->mainFrame()->setName(params->frame_name);
847
848   OnSetRendererPrefs(params->renderer_prefs);
849
850 #if defined(ENABLE_WEBRTC)
851   if (!media_stream_dispatcher_)
852     media_stream_dispatcher_ = new MediaStreamDispatcher(this);
853 #endif
854
855   new MHTMLGenerator(this);
856 #if defined(OS_MACOSX)
857   new TextInputClientObserver(this);
858 #endif  // defined(OS_MACOSX)
859
860 #if defined(OS_ANDROID)
861   media_player_manager_ = new RendererMediaPlayerManager(this);
862   new JavaBridgeDispatcher(this);
863 #endif
864
865   // The next group of objects all implement RenderViewObserver, so are deleted
866   // along with the RenderView automatically.
867   devtools_agent_ = new DevToolsAgent(this);
868   if (RenderWidgetCompositor* rwc = compositor()) {
869     webview()->devToolsAgent()->setLayerTreeId(rwc->GetLayerTreeId());
870   }
871   mouse_lock_dispatcher_ = new RenderViewMouseLockDispatcher(this);
872   new ImageLoadingHelper(this);
873
874   // Create renderer_accessibility_ if needed.
875   OnSetAccessibilityMode(params->accessibility_mode);
876
877   new IdleUserDetector(this);
878
879   if (command_line.HasSwitch(switches::kDomAutomationController))
880     enabled_bindings_ |= BINDINGS_POLICY_DOM_AUTOMATION;
881   if (command_line.HasSwitch(switches::kStatsCollectionController))
882     enabled_bindings_ |= BINDINGS_POLICY_STATS_COLLECTION;
883
884   ProcessViewLayoutFlags(command_line);
885
886   GetContentClient()->renderer()->RenderViewCreated(this);
887
888   // If we have an opener_id but we weren't created by a renderer, then
889   // it's the browser asking us to set our opener to another RenderView.
890   if (params->opener_id != MSG_ROUTING_NONE && !params->is_renderer_created) {
891     RenderViewImpl* opener_view = FromRoutingID(params->opener_id);
892     if (opener_view)
893       webview()->mainFrame()->setOpener(opener_view->webview()->mainFrame());
894   }
895
896   // If we are initially swapped out, navigate to kSwappedOutURL.
897   // This ensures we are in a unique origin that others cannot script.
898   if (is_swapped_out_)
899     NavigateToSwappedOutURL(webview()->mainFrame());
900 }
901
902 RenderViewImpl::~RenderViewImpl() {
903   history_page_ids_.clear();
904
905   base::debug::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_);
906
907   // If file chooser is still waiting for answer, dispatch empty answer.
908   while (!file_chooser_completions_.empty()) {
909     if (file_chooser_completions_.front()->completion) {
910       file_chooser_completions_.front()->completion->didChooseFile(
911           WebVector<WebString>());
912     }
913     file_chooser_completions_.pop_front();
914   }
915
916 #if defined(OS_ANDROID)
917   // The date/time picker client is both a scoped_ptr member of this class and
918   // a RenderViewObserver. Reset it to prevent double deletion.
919   date_time_picker_client_.reset();
920 #endif
921
922 #ifndef NDEBUG
923   // Make sure we are no longer referenced by the ViewMap or RoutingIDViewMap.
924   ViewMap* views = g_view_map.Pointer();
925   for (ViewMap::iterator it = views->begin(); it != views->end(); ++it)
926     DCHECK_NE(this, it->second) << "Failed to call Close?";
927   RoutingIDViewMap* routing_id_views = g_routing_id_view_map.Pointer();
928   for (RoutingIDViewMap::iterator it = routing_id_views->begin();
929        it != routing_id_views->end(); ++it)
930     DCHECK_NE(this, it->second) << "Failed to call Close?";
931 #endif
932
933   FOR_EACH_OBSERVER(RenderViewObserver, observers_, RenderViewGone());
934   FOR_EACH_OBSERVER(RenderViewObserver, observers_, OnDestruct());
935 }
936
937 /*static*/
938 RenderViewImpl* RenderViewImpl::FromWebView(WebView* webview) {
939   ViewMap* views = g_view_map.Pointer();
940   ViewMap::iterator it = views->find(webview);
941   return it == views->end() ? NULL : it->second;
942 }
943
944 /*static*/
945 RenderView* RenderView::FromWebView(blink::WebView* webview) {
946   return RenderViewImpl::FromWebView(webview);
947 }
948
949 /*static*/
950 RenderViewImpl* RenderViewImpl::FromRoutingID(int32 routing_id) {
951   RoutingIDViewMap* views = g_routing_id_view_map.Pointer();
952   RoutingIDViewMap::iterator it = views->find(routing_id);
953   return it == views->end() ? NULL : it->second;
954 }
955
956 /*static*/
957 RenderView* RenderView::FromRoutingID(int routing_id) {
958   return RenderViewImpl::FromRoutingID(routing_id);
959 }
960
961 /*static*/
962 void RenderView::ForEach(RenderViewVisitor* visitor) {
963   ViewMap* views = g_view_map.Pointer();
964   for (ViewMap::iterator it = views->begin(); it != views->end(); ++it) {
965     if (!visitor->Visit(it->second))
966       return;
967   }
968 }
969
970 /*static*/
971 RenderViewImpl* RenderViewImpl::Create(
972     int32 opener_id,
973     const RendererPreferences& renderer_prefs,
974     const WebPreferences& webkit_prefs,
975     int32 routing_id,
976     int32 main_frame_routing_id,
977     int32 surface_id,
978     int64 session_storage_namespace_id,
979     const base::string16& frame_name,
980     bool is_renderer_created,
981     bool swapped_out,
982     bool hidden,
983     int32 next_page_id,
984     const blink::WebScreenInfo& screen_info,
985     unsigned int accessibility_mode,
986     bool allow_partial_swap) {
987   DCHECK(routing_id != MSG_ROUTING_NONE);
988   RenderViewImplParams params(
989       opener_id,
990       renderer_prefs,
991       webkit_prefs,
992       routing_id,
993       main_frame_routing_id,
994       surface_id,
995       session_storage_namespace_id,
996       frame_name,
997       is_renderer_created,
998       swapped_out,
999       hidden,
1000       next_page_id,
1001       screen_info,
1002       accessibility_mode,
1003       allow_partial_swap);
1004   RenderViewImpl* render_view = NULL;
1005   if (g_create_render_view_impl)
1006     render_view = g_create_render_view_impl(&params);
1007   else
1008     render_view = new RenderViewImpl(&params);
1009   render_view->Initialize(&params);
1010   return render_view;
1011 }
1012
1013 // static
1014 void RenderViewImpl::InstallCreateHook(
1015     RenderViewImpl* (*create_render_view_impl)(RenderViewImplParams*)) {
1016   CHECK(!g_create_render_view_impl);
1017   g_create_render_view_impl = create_render_view_impl;
1018 }
1019
1020 void RenderViewImpl::AddObserver(RenderViewObserver* observer) {
1021   observers_.AddObserver(observer);
1022 }
1023
1024 void RenderViewImpl::RemoveObserver(RenderViewObserver* observer) {
1025   observer->RenderViewGone();
1026   observers_.RemoveObserver(observer);
1027 }
1028
1029 blink::WebView* RenderViewImpl::webview() const {
1030   return static_cast<blink::WebView*>(webwidget());
1031 }
1032
1033 #if defined(ENABLE_PLUGINS)
1034 void RenderViewImpl::PepperInstanceCreated(
1035     PepperPluginInstanceImpl* instance) {
1036   active_pepper_instances_.insert(instance);
1037 }
1038
1039 void RenderViewImpl::PepperInstanceDeleted(
1040     PepperPluginInstanceImpl* instance) {
1041   active_pepper_instances_.erase(instance);
1042
1043   if (pepper_last_mouse_event_target_ == instance)
1044     pepper_last_mouse_event_target_ = NULL;
1045   if (focused_pepper_plugin_ == instance)
1046     PepperFocusChanged(instance, false);
1047 }
1048
1049 void RenderViewImpl::PepperFocusChanged(PepperPluginInstanceImpl* instance,
1050                                         bool focused) {
1051   if (focused)
1052     focused_pepper_plugin_ = instance;
1053   else if (focused_pepper_plugin_ == instance)
1054     focused_pepper_plugin_ = NULL;
1055
1056   UpdateTextInputType();
1057   UpdateSelectionBounds();
1058 }
1059
1060 void RenderViewImpl::RegisterPluginDelegate(WebPluginDelegateProxy* delegate) {
1061   plugin_delegates_.insert(delegate);
1062   // If the renderer is visible, set initial visibility and focus state.
1063   if (!is_hidden()) {
1064 #if defined(OS_MACOSX)
1065     delegate->SetContainerVisibility(true);
1066     if (webview() && webview()->isActive())
1067       delegate->SetWindowFocus(true);
1068 #endif
1069   }
1070   // Plugins start assuming the content has focus (so that they work in
1071   // environments where RenderView isn't hosting them), so we always have to
1072   // set the initial state. See webplugin_delegate_impl.h for details.
1073   delegate->SetContentAreaFocus(has_focus());
1074 }
1075
1076 void RenderViewImpl::UnregisterPluginDelegate(
1077     WebPluginDelegateProxy* delegate) {
1078   plugin_delegates_.erase(delegate);
1079 }
1080
1081 #if defined(OS_WIN)
1082 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1083   if (focused)
1084     focused_plugin_id_ = plugin_id;
1085   else
1086     focused_plugin_id_ = -1;
1087 }
1088 #endif
1089
1090 #if defined(OS_MACOSX)
1091 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1092   Send(new ViewHostMsg_PluginFocusChanged(routing_id(), focused, plugin_id));
1093 }
1094
1095 void RenderViewImpl::StartPluginIme() {
1096   IPC::Message* msg = new ViewHostMsg_StartPluginIme(routing_id());
1097   // This message can be sent during event-handling, and needs to be delivered
1098   // within that context.
1099   msg->set_unblock(true);
1100   Send(msg);
1101 }
1102 #endif  // defined(OS_MACOSX)
1103
1104 #endif  // ENABLE_PLUGINS
1105
1106 void RenderViewImpl::TransferActiveWheelFlingAnimation(
1107     const blink::WebActiveWheelFlingParameters& params) {
1108   if (webview())
1109     webview()->transferActiveWheelFlingAnimation(params);
1110 }
1111
1112 bool RenderViewImpl::HasIMETextFocus() {
1113   return GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE;
1114 }
1115
1116 bool RenderViewImpl::OnMessageReceived(const IPC::Message& message) {
1117   WebFrame* main_frame = webview() ? webview()->mainFrame() : NULL;
1118   if (main_frame)
1119     GetContentClient()->SetActiveURL(main_frame->document().url());
1120
1121   ObserverListBase<RenderViewObserver>::Iterator it(observers_);
1122   RenderViewObserver* observer;
1123   while ((observer = it.GetNext()) != NULL)
1124     if (observer->OnMessageReceived(message))
1125       return true;
1126
1127   bool handled = true;
1128   bool msg_is_ok = true;
1129   IPC_BEGIN_MESSAGE_MAP_EX(RenderViewImpl, message, msg_is_ok)
1130     IPC_MESSAGE_HANDLER(InputMsg_Copy, OnCopy)
1131     IPC_MESSAGE_HANDLER(InputMsg_Cut, OnCut)
1132     IPC_MESSAGE_HANDLER(InputMsg_Delete, OnDelete)
1133     IPC_MESSAGE_HANDLER(InputMsg_ExecuteEditCommand, OnExecuteEditCommand)
1134     IPC_MESSAGE_HANDLER(InputMsg_MoveCaret, OnMoveCaret)
1135     IPC_MESSAGE_HANDLER(InputMsg_Paste, OnPaste)
1136     IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle, OnPasteAndMatchStyle)
1137     IPC_MESSAGE_HANDLER(InputMsg_Redo, OnRedo)
1138     IPC_MESSAGE_HANDLER(InputMsg_Replace, OnReplace)
1139     IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling, OnReplaceMisspelling)
1140     IPC_MESSAGE_HANDLER(InputMsg_ScrollFocusedEditableNodeIntoRect,
1141                         OnScrollFocusedEditableNodeIntoRect)
1142     IPC_MESSAGE_HANDLER(InputMsg_SelectAll, OnSelectAll)
1143     IPC_MESSAGE_HANDLER(InputMsg_SelectRange, OnSelectRange)
1144     IPC_MESSAGE_HANDLER(InputMsg_SetEditCommandsForNextKeyEvent,
1145                         OnSetEditCommandsForNextKeyEvent)
1146     IPC_MESSAGE_HANDLER(InputMsg_Undo, OnUndo)
1147     IPC_MESSAGE_HANDLER(InputMsg_Unselect, OnUnselect)
1148     IPC_MESSAGE_HANDLER(FrameMsg_Navigate, OnNavigate)
1149     IPC_MESSAGE_HANDLER(ViewMsg_Stop, OnStop)
1150     IPC_MESSAGE_HANDLER(ViewMsg_ReloadFrame, OnReloadFrame)
1151     IPC_MESSAGE_HANDLER(ViewMsg_SetName, OnSetName)
1152     IPC_MESSAGE_HANDLER(ViewMsg_SetEditableSelectionOffsets,
1153                         OnSetEditableSelectionOffsets)
1154     IPC_MESSAGE_HANDLER(ViewMsg_SetCompositionFromExistingText,
1155                         OnSetCompositionFromExistingText)
1156     IPC_MESSAGE_HANDLER(ViewMsg_ExtendSelectionAndDelete,
1157                         OnExtendSelectionAndDelete)
1158     IPC_MESSAGE_HANDLER(ViewMsg_CopyImageAt, OnCopyImageAt)
1159     IPC_MESSAGE_HANDLER(ViewMsg_Find, OnFind)
1160     IPC_MESSAGE_HANDLER(ViewMsg_StopFinding, OnStopFinding)
1161     IPC_MESSAGE_HANDLER(ViewMsg_Zoom, OnZoom)
1162     IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevel, OnSetZoomLevel)
1163     IPC_MESSAGE_HANDLER(ViewMsg_ZoomFactor, OnZoomFactor)
1164     IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForLoadingURL,
1165                         OnSetZoomLevelForLoadingURL)
1166     IPC_MESSAGE_HANDLER(ViewMsg_SetPageEncoding, OnSetPageEncoding)
1167     IPC_MESSAGE_HANDLER(ViewMsg_ResetPageEncodingToDefault,
1168                         OnResetPageEncodingToDefault)
1169     IPC_MESSAGE_HANDLER(ViewMsg_ScriptEvalRequest, OnScriptEvalRequest)
1170     IPC_MESSAGE_HANDLER(ViewMsg_PostMessageEvent, OnPostMessageEvent)
1171     IPC_MESSAGE_HANDLER(ViewMsg_CSSInsertRequest, OnCSSInsertRequest)
1172     IPC_MESSAGE_HANDLER(DragMsg_TargetDragEnter, OnDragTargetDragEnter)
1173     IPC_MESSAGE_HANDLER(DragMsg_TargetDragOver, OnDragTargetDragOver)
1174     IPC_MESSAGE_HANDLER(DragMsg_TargetDragLeave, OnDragTargetDragLeave)
1175     IPC_MESSAGE_HANDLER(DragMsg_TargetDrop, OnDragTargetDrop)
1176     IPC_MESSAGE_HANDLER(DragMsg_SourceEndedOrMoved, OnDragSourceEndedOrMoved)
1177     IPC_MESSAGE_HANDLER(DragMsg_SourceSystemDragEnded,
1178                         OnDragSourceSystemDragEnded)
1179     IPC_MESSAGE_HANDLER(ViewMsg_AllowBindings, OnAllowBindings)
1180     IPC_MESSAGE_HANDLER(ViewMsg_SetInitialFocus, OnSetInitialFocus)
1181     IPC_MESSAGE_HANDLER(ViewMsg_UpdateTargetURL_ACK, OnUpdateTargetURLAck)
1182     IPC_MESSAGE_HANDLER(ViewMsg_UpdateWebPreferences, OnUpdateWebPreferences)
1183     IPC_MESSAGE_HANDLER(ViewMsg_TimezoneChange, OnUpdateTimezone)
1184     IPC_MESSAGE_HANDLER(ViewMsg_EnumerateDirectoryResponse,
1185                         OnEnumerateDirectoryResponse)
1186     IPC_MESSAGE_HANDLER(ViewMsg_RunFileChooserResponse, OnFileChooserResponse)
1187     IPC_MESSAGE_HANDLER(ViewMsg_ShouldClose, OnShouldClose)
1188     IPC_MESSAGE_HANDLER(ViewMsg_SuppressDialogsUntilSwapOut,
1189                         OnSuppressDialogsUntilSwapOut)
1190     IPC_MESSAGE_HANDLER(ViewMsg_SwapOut, OnSwapOut)
1191     IPC_MESSAGE_HANDLER(ViewMsg_ClosePage, OnClosePage)
1192     IPC_MESSAGE_HANDLER(ViewMsg_ThemeChanged, OnThemeChanged)
1193     IPC_MESSAGE_HANDLER(ViewMsg_MoveOrResizeStarted, OnMoveOrResizeStarted)
1194     IPC_MESSAGE_HANDLER(ViewMsg_ClearFocusedNode, OnClearFocusedNode)
1195     IPC_MESSAGE_HANDLER(ViewMsg_SetBackground, OnSetBackground)
1196     IPC_MESSAGE_HANDLER(ViewMsg_EnablePreferredSizeChangedMode,
1197                         OnEnablePreferredSizeChangedMode)
1198     IPC_MESSAGE_HANDLER(ViewMsg_EnableAutoResize, OnEnableAutoResize)
1199     IPC_MESSAGE_HANDLER(ViewMsg_DisableAutoResize, OnDisableAutoResize)
1200     IPC_MESSAGE_HANDLER(ViewMsg_DisableScrollbarsForSmallWindows,
1201                         OnDisableScrollbarsForSmallWindows)
1202     IPC_MESSAGE_HANDLER(ViewMsg_SetRendererPrefs, OnSetRendererPrefs)
1203     IPC_MESSAGE_HANDLER(ViewMsg_MediaPlayerActionAt, OnMediaPlayerActionAt)
1204     IPC_MESSAGE_HANDLER(ViewMsg_OrientationChangeEvent,
1205                         OnOrientationChangeEvent)
1206     IPC_MESSAGE_HANDLER(ViewMsg_PluginActionAt, OnPluginActionAt)
1207     IPC_MESSAGE_HANDLER(ViewMsg_SetActive, OnSetActive)
1208     IPC_MESSAGE_HANDLER(ViewMsg_GetAllSavableResourceLinksForCurrentPage,
1209                         OnGetAllSavableResourceLinksForCurrentPage)
1210     IPC_MESSAGE_HANDLER(
1211         ViewMsg_GetSerializedHtmlDataForCurrentPageWithLocalLinks,
1212         OnGetSerializedHtmlDataForCurrentPageWithLocalLinks)
1213     IPC_MESSAGE_HANDLER(ViewMsg_ShowContextMenu, OnShowContextMenu)
1214     // TODO(viettrungluu): Move to a separate message filter.
1215     IPC_MESSAGE_HANDLER(ViewMsg_SetHistoryLengthAndPrune,
1216                         OnSetHistoryLengthAndPrune)
1217     IPC_MESSAGE_HANDLER(ViewMsg_EnableViewSourceMode, OnEnableViewSourceMode)
1218     IPC_MESSAGE_HANDLER(ViewMsg_SetAccessibilityMode, OnSetAccessibilityMode)
1219     IPC_MESSAGE_HANDLER(ViewMsg_DisownOpener, OnDisownOpener)
1220     IPC_MESSAGE_HANDLER(ViewMsg_ReleaseDisambiguationPopupDIB,
1221                         OnReleaseDisambiguationPopupDIB)
1222     IPC_MESSAGE_HANDLER(ViewMsg_WindowSnapshotCompleted,
1223                         OnWindowSnapshotCompleted)
1224 #if defined(OS_ANDROID)
1225     IPC_MESSAGE_HANDLER(InputMsg_ActivateNearestFindResult,
1226                         OnActivateNearestFindResult)
1227     IPC_MESSAGE_HANDLER(ViewMsg_FindMatchRects, OnFindMatchRects)
1228     IPC_MESSAGE_HANDLER(ViewMsg_SelectPopupMenuItems, OnSelectPopupMenuItems)
1229     IPC_MESSAGE_HANDLER(ViewMsg_UndoScrollFocusedEditableNodeIntoView,
1230                         OnUndoScrollFocusedEditableNodeIntoRect)
1231     IPC_MESSAGE_HANDLER(ViewMsg_UpdateTopControlsState,
1232                         OnUpdateTopControlsState)
1233     IPC_MESSAGE_HANDLER(ViewMsg_PauseVideo, OnPauseVideo)
1234     IPC_MESSAGE_HANDLER(ViewMsg_ExtractSmartClipData, OnExtractSmartClipData)
1235 #elif defined(OS_MACOSX)
1236     IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard, OnCopyToFindPboard)
1237     IPC_MESSAGE_HANDLER(ViewMsg_PluginImeCompositionCompleted,
1238                         OnPluginImeCompositionCompleted)
1239     IPC_MESSAGE_HANDLER(ViewMsg_SelectPopupMenuItem, OnSelectPopupMenuItem)
1240     IPC_MESSAGE_HANDLER(ViewMsg_SetInLiveResize, OnSetInLiveResize)
1241     IPC_MESSAGE_HANDLER(ViewMsg_SetWindowVisibility, OnSetWindowVisibility)
1242     IPC_MESSAGE_HANDLER(ViewMsg_WindowFrameChanged, OnWindowFrameChanged)
1243 #endif
1244     // Adding a new message? Add platform independent ones first, then put the
1245     // platform specific ones at the end.
1246
1247     // Have the super handle all other messages.
1248     IPC_MESSAGE_UNHANDLED(handled = RenderWidget::OnMessageReceived(message))
1249   IPC_END_MESSAGE_MAP()
1250
1251   if (!msg_is_ok) {
1252     // The message had a handler, but its deserialization failed.
1253     // Kill the renderer to avoid potential spoofing attacks.
1254     CHECK(false) << "Unable to deserialize message in RenderViewImpl.";
1255   }
1256
1257   return handled;
1258 }
1259
1260 void RenderViewImpl::OnNavigate(const FrameMsg_Navigate_Params& params) {
1261   FOR_EACH_OBSERVER(RenderViewObserver, observers_, Navigate(params.url));
1262 }
1263
1264 bool RenderViewImpl::IsBackForwardToStaleEntry(
1265     const FrameMsg_Navigate_Params& params,
1266     bool is_reload) {
1267   // Make sure this isn't a back/forward to an entry we have already cropped
1268   // or replaced from our history, before the browser knew about it.  If so,
1269   // a new navigation has committed in the mean time, and we can ignore this.
1270   bool is_back_forward = !is_reload && params.page_state.IsValid();
1271
1272   // Note: if the history_list_length_ is 0 for a back/forward, we must be
1273   // restoring from a previous session.  We'll update our state in OnNavigate.
1274   if (!is_back_forward || history_list_length_ <= 0)
1275     return false;
1276
1277   DCHECK_EQ(static_cast<int>(history_page_ids_.size()), history_list_length_);
1278
1279   // Check for whether the forward history has been cropped due to a recent
1280   // navigation the browser didn't know about.
1281   if (params.pending_history_list_offset >= history_list_length_)
1282     return true;
1283
1284   // Check for whether this entry has been replaced with a new one.
1285   int expected_page_id =
1286       history_page_ids_[params.pending_history_list_offset];
1287   if (expected_page_id > 0 && params.page_id != expected_page_id) {
1288     if (params.page_id < expected_page_id)
1289       return true;
1290
1291     // Otherwise we've removed an earlier entry and should have shifted all
1292     // entries left.  For now, it's ok to lazily update the list.
1293     // TODO(creis): Notify all live renderers when we remove entries from
1294     // the front of the list, so that we don't hit this case.
1295     history_page_ids_[params.pending_history_list_offset] = params.page_id;
1296   }
1297
1298   return false;
1299 }
1300
1301 // Stop loading the current page.
1302 void RenderViewImpl::OnStop() {
1303   if (webview())
1304     webview()->mainFrame()->stopLoading();
1305   FOR_EACH_OBSERVER(RenderViewObserver, observers_, OnStop());
1306   main_render_frame_->OnStop();
1307 }
1308
1309 // Reload current focused frame.
1310 // E.g. called by right-clicking on the frame and picking "reload this frame".
1311 void RenderViewImpl::OnReloadFrame() {
1312   if (webview() && webview()->focusedFrame()) {
1313     // We always obey the cache (ignore_cache=false) here.
1314     // TODO(evanm): perhaps we could allow shift-clicking the menu item to do
1315     // a cache-ignoring reload of the frame.
1316     webview()->focusedFrame()->reload(false);
1317   }
1318 }
1319
1320 void RenderViewImpl::OnCopyImageAt(int x, int y) {
1321   webview()->copyImageAt(WebPoint(x, y));
1322 }
1323
1324 void RenderViewImpl::OnUpdateTargetURLAck() {
1325   // Check if there is a targeturl waiting to be sent.
1326   if (target_url_status_ == TARGET_PENDING) {
1327     Send(new ViewHostMsg_UpdateTargetURL(routing_id_, page_id_,
1328                                          pending_target_url_));
1329   }
1330
1331   target_url_status_ = TARGET_NONE;
1332 }
1333
1334 void RenderViewImpl::OnCopy() {
1335   if (!webview())
1336     return;
1337
1338   base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1339   WebNode current_node = context_menu_node_.isNull() ?
1340       GetFocusedNode() : context_menu_node_;
1341   webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Copy"),
1342                                             current_node);
1343 }
1344
1345 void RenderViewImpl::OnCut() {
1346   if (!webview())
1347     return;
1348
1349   base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1350   webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Cut"),
1351                                             GetFocusedNode());
1352 }
1353
1354 void RenderViewImpl::OnDelete() {
1355   if (!webview())
1356     return;
1357
1358   webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Delete"),
1359                                             GetFocusedNode());
1360 }
1361
1362 void RenderViewImpl::OnExecuteEditCommand(const std::string& name,
1363     const std::string& value) {
1364   if (!webview() || !webview()->focusedFrame())
1365     return;
1366
1367   webview()->focusedFrame()->executeCommand(
1368       WebString::fromUTF8(name), WebString::fromUTF8(value));
1369 }
1370
1371 void RenderViewImpl::OnMoveCaret(const gfx::Point& point) {
1372   if (!webview())
1373     return;
1374
1375   Send(new ViewHostMsg_MoveCaret_ACK(routing_id_));
1376
1377   webview()->focusedFrame()->moveCaretSelection(point);
1378 }
1379
1380 void RenderViewImpl::OnPaste() {
1381   if (!webview())
1382     return;
1383
1384   base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1385   webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Paste"),
1386                                             GetFocusedNode());
1387 }
1388
1389 void RenderViewImpl::OnPasteAndMatchStyle() {
1390   if (!webview())
1391     return;
1392
1393   base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1394   webview()->focusedFrame()->executeCommand(
1395       WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedNode());
1396 }
1397
1398 void RenderViewImpl::OnRedo() {
1399   if (!webview())
1400     return;
1401
1402   webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Redo"),
1403                                             GetFocusedNode());
1404 }
1405
1406 void RenderViewImpl::OnReplace(const base::string16& text) {
1407   if (!webview())
1408     return;
1409
1410   WebFrame* frame = webview()->focusedFrame();
1411   if (!frame->hasSelection())
1412     frame->selectWordAroundCaret();
1413
1414   frame->replaceSelection(text);
1415 }
1416
1417 void RenderViewImpl::OnReplaceMisspelling(const base::string16& text) {
1418   if (!webview())
1419     return;
1420
1421   WebFrame* frame = webview()->focusedFrame();
1422   if (!frame->hasSelection())
1423     return;
1424
1425   frame->replaceMisspelledRange(text);
1426 }
1427
1428 void RenderViewImpl::OnScrollFocusedEditableNodeIntoRect(
1429     const gfx::Rect& rect) {
1430   blink::WebNode node = GetFocusedNode();
1431   if (!node.isNull()) {
1432     if (IsEditableNode(node)) {
1433       webview()->saveScrollAndScaleState();
1434       webview()->scrollFocusedNodeIntoRect(rect);
1435     }
1436   }
1437 }
1438
1439 void RenderViewImpl::OnSelectAll() {
1440   if (!webview())
1441     return;
1442
1443   base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1444   webview()->focusedFrame()->executeCommand(
1445       WebString::fromUTF8("SelectAll"), GetFocusedNode());
1446 }
1447
1448 void RenderViewImpl::OnSelectRange(const gfx::Point& start,
1449                                    const gfx::Point& end) {
1450   if (!webview())
1451     return;
1452
1453   Send(new ViewHostMsg_SelectRange_ACK(routing_id_));
1454
1455   base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1456   webview()->focusedFrame()->selectRange(start, end);
1457 }
1458
1459 void RenderViewImpl::OnSetEditCommandsForNextKeyEvent(
1460     const EditCommands& edit_commands) {
1461   edit_commands_ = edit_commands;
1462 }
1463
1464 void RenderViewImpl::OnUndo() {
1465   if (!webview())
1466     return;
1467
1468   webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Undo"),
1469                                             GetFocusedNode());
1470 }
1471
1472 void RenderViewImpl::OnUnselect() {
1473   if (!webview())
1474     return;
1475
1476   base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1477   webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Unselect"),
1478                                             GetFocusedNode());
1479 }
1480
1481 #if defined(OS_MACOSX)
1482 void RenderViewImpl::OnCopyToFindPboard() {
1483   if (!webview())
1484     return;
1485
1486   // Since the find pasteboard supports only plain text, this can be simpler
1487   // than the |OnCopy()| case.
1488   WebFrame* frame = webview()->focusedFrame();
1489   if (frame->hasSelection()) {
1490     base::string16 selection = frame->selectionAsText();
1491     RenderThread::Get()->Send(
1492         new ClipboardHostMsg_FindPboardWriteStringAsync(selection));
1493   }
1494 }
1495 #endif
1496
1497 void RenderViewImpl::OnSetName(const std::string& name) {
1498   if (!webview())
1499     return;
1500
1501   webview()->mainFrame()->setName(WebString::fromUTF8(name));
1502 }
1503
1504 void RenderViewImpl::OnSetEditableSelectionOffsets(int start, int end) {
1505   base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1506   if (!ShouldHandleImeEvent())
1507     return;
1508   ImeEventGuard guard(this);
1509   webview()->setEditableSelectionOffsets(start, end);
1510 }
1511
1512 void RenderViewImpl::OnSetCompositionFromExistingText(
1513     int start, int end,
1514     const std::vector<blink::WebCompositionUnderline>& underlines) {
1515   if (!ShouldHandleImeEvent())
1516     return;
1517   ImeEventGuard guard(this);
1518   webview()->setCompositionFromExistingText(start, end, underlines);
1519 }
1520
1521 void RenderViewImpl::OnExtendSelectionAndDelete(int before, int after) {
1522   if (!ShouldHandleImeEvent())
1523     return;
1524   ImeEventGuard guard(this);
1525   webview()->extendSelectionAndDelete(before, after);
1526 }
1527
1528 void RenderViewImpl::OnSetHistoryLengthAndPrune(int history_length,
1529                                                 int32 minimum_page_id) {
1530   DCHECK_GE(history_length, 0);
1531   DCHECK(history_list_offset_ == history_list_length_ - 1);
1532   DCHECK_GE(minimum_page_id, -1);
1533
1534   // Generate the new list.
1535   std::vector<int32> new_history_page_ids(history_length, -1);
1536   for (size_t i = 0; i < history_page_ids_.size(); ++i) {
1537     if (minimum_page_id >= 0 && history_page_ids_[i] < minimum_page_id)
1538       continue;
1539     new_history_page_ids.push_back(history_page_ids_[i]);
1540   }
1541   new_history_page_ids.swap(history_page_ids_);
1542
1543   // Update indexes.
1544   history_list_length_ = history_page_ids_.size();
1545   history_list_offset_ = history_list_length_ - 1;
1546 }
1547
1548
1549 void RenderViewImpl::OnSetInitialFocus(bool reverse) {
1550   if (!webview())
1551     return;
1552   webview()->setInitialFocus(reverse);
1553 }
1554
1555 #if defined(OS_MACOSX)
1556 void RenderViewImpl::OnSetInLiveResize(bool in_live_resize) {
1557   if (!webview())
1558     return;
1559   if (in_live_resize)
1560     webview()->willStartLiveResize();
1561   else
1562     webview()->willEndLiveResize();
1563 }
1564 #endif
1565
1566 #if defined(OS_ANDROID)
1567 void RenderViewImpl::OnUndoScrollFocusedEditableNodeIntoRect() {
1568   const WebNode node = GetFocusedNode();
1569   if (!node.isNull() && IsEditableNode(node))
1570     webview()->restoreScrollAndScaleState();
1571 }
1572
1573 void RenderViewImpl::OnPauseVideo() {
1574   // Inform RendererMediaPlayerManager to release all video player resources.
1575   // If something is in progress the resource will not be freed, it will
1576   // only be freed once the tab is destroyed or if the user navigates away
1577   // via WebMediaPlayerAndroid::Destroy.
1578   media_player_manager_->ReleaseVideoResources();
1579 }
1580 #endif
1581
1582 ///////////////////////////////////////////////////////////////////////////////
1583
1584 // Tell the embedding application that the title of the active page has changed
1585 void RenderViewImpl::UpdateTitle(WebFrame* frame,
1586                                  const base::string16& title,
1587                                  WebTextDirection title_direction) {
1588   // Ignore all but top level navigations.
1589   if (frame->parent())
1590     return;
1591
1592   base::debug::TraceLog::GetInstance()->UpdateProcessLabel(
1593       routing_id_, base::UTF16ToUTF8(title));
1594
1595   base::string16 shortened_title = title.substr(0, kMaxTitleChars);
1596   Send(new ViewHostMsg_UpdateTitle(routing_id_, page_id_, shortened_title,
1597                                    title_direction));
1598 }
1599
1600 void RenderViewImpl::UpdateEncoding(WebFrame* frame,
1601                                     const std::string& encoding_name) {
1602   // Only update main frame's encoding_name.
1603   if (webview()->mainFrame() == frame &&
1604       last_encoding_name_ != encoding_name) {
1605     // Save the encoding name for later comparing.
1606     last_encoding_name_ = encoding_name;
1607
1608     Send(new ViewHostMsg_UpdateEncoding(routing_id_, last_encoding_name_));
1609   }
1610 }
1611
1612 // Sends the last committed session history state to the browser so it will be
1613 // saved before we navigate to a new page. This must be called *before* the
1614 // page ID has been updated so we know what it was.
1615 void RenderViewImpl::UpdateSessionHistory(WebFrame* frame) {
1616   // If we have a valid page ID at this point, then it corresponds to the page
1617   // we are navigating away from.  Otherwise, this is the first navigation, so
1618   // there is no past session history to record.
1619   if (page_id_ == -1)
1620     return;
1621
1622   const WebHistoryItem& item =
1623       webview()->mainFrame()->previousHistoryItem();
1624   SendUpdateState(item);
1625 }
1626
1627 void RenderViewImpl::SendUpdateState(const WebHistoryItem& item) {
1628   if (item.isNull())
1629     return;
1630
1631   // Don't send state updates for kSwappedOutURL.
1632   if (item.urlString() == WebString::fromUTF8(kSwappedOutURL))
1633     return;
1634
1635   Send(new ViewHostMsg_UpdateState(
1636       routing_id_, page_id_, HistoryItemToPageState(item)));
1637 }
1638
1639 void RenderViewImpl::OpenURL(WebFrame* frame,
1640                              const GURL& url,
1641                              const Referrer& referrer,
1642                              WebNavigationPolicy policy) {
1643   ViewHostMsg_OpenURL_Params params;
1644   params.url = url;
1645   params.referrer = referrer;
1646   params.disposition = NavigationPolicyToDisposition(policy);
1647   params.frame_id = frame->identifier();
1648   WebDataSource* ds = frame->provisionalDataSource();
1649   if (ds) {
1650     DocumentState* document_state = DocumentState::FromDataSource(ds);
1651     NavigationState* navigation_state = document_state->navigation_state();
1652     if (navigation_state->is_content_initiated()) {
1653       params.should_replace_current_entry = ds->replacesCurrentHistoryItem();
1654     } else {
1655       // This is necessary to preserve the should_replace_current_entry value on
1656       // cross-process redirects, in the event it was set by a previous process.
1657       //
1658       // TODO(davidben): Avoid this awkward duplication of state. See comment on
1659       // NavigationState::should_replace_current_entry().
1660       params.should_replace_current_entry =
1661           navigation_state->should_replace_current_entry();
1662     }
1663   } else {
1664     params.should_replace_current_entry = false;
1665   }
1666   params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
1667   if (GetContentClient()->renderer()->AllowPopup())
1668     params.user_gesture = true;
1669
1670   if (policy == blink::WebNavigationPolicyNewBackgroundTab ||
1671       policy == blink::WebNavigationPolicyNewForegroundTab ||
1672       policy == blink::WebNavigationPolicyNewWindow ||
1673       policy == blink::WebNavigationPolicyNewPopup) {
1674     WebUserGestureIndicator::consumeUserGesture();
1675   }
1676
1677   Send(new ViewHostMsg_OpenURL(routing_id_, params));
1678 }
1679
1680 // WebViewDelegate ------------------------------------------------------------
1681
1682 void RenderViewImpl::LoadNavigationErrorPage(
1683     WebFrame* frame,
1684     const WebURLRequest& failed_request,
1685     const WebURLError& error,
1686     bool replace) {
1687   std::string error_html;
1688   GetContentClient()->renderer()->GetNavigationErrorStrings(
1689       this, frame, failed_request, error, &error_html, NULL);
1690
1691   frame->loadHTMLString(error_html,
1692                         GURL(kUnreachableWebDataURL),
1693                         error.unreachableURL,
1694                         replace);
1695 }
1696
1697 bool RenderViewImpl::RunJavaScriptMessage(JavaScriptMessageType type,
1698                                           const base::string16& message,
1699                                           const base::string16& default_value,
1700                                           const GURL& frame_url,
1701                                           base::string16* result) {
1702   // Don't allow further dialogs if we are waiting to swap out, since the
1703   // PageGroupLoadDeferrer in our stack prevents it.
1704   if (suppress_dialogs_until_swap_out_)
1705     return false;
1706
1707   bool success = false;
1708   base::string16 result_temp;
1709   if (!result)
1710     result = &result_temp;
1711
1712   SendAndRunNestedMessageLoop(new ViewHostMsg_RunJavaScriptMessage(
1713       routing_id_, message, default_value, frame_url, type, &success, result));
1714   return success;
1715 }
1716
1717 bool RenderViewImpl::SendAndRunNestedMessageLoop(IPC::SyncMessage* message) {
1718   // Before WebKit asks us to show an alert (etc.), it takes care of doing the
1719   // equivalent of WebView::willEnterModalLoop.  In the case of showModalDialog
1720   // it is particularly important that we do not call willEnterModalLoop as
1721   // that would defer resource loads for the dialog itself.
1722   if (RenderThreadImpl::current())  // Will be NULL during unit tests.
1723     RenderThreadImpl::current()->DoNotNotifyWebKitOfModalLoop();
1724
1725   message->EnableMessagePumping();  // Runs a nested message loop.
1726   return Send(message);
1727 }
1728
1729 void RenderViewImpl::GetWindowSnapshot(const WindowSnapshotCallback& callback) {
1730   int id = next_snapshot_id_++;
1731   pending_snapshots_.insert(std::make_pair(id, callback));
1732   ui::LatencyInfo latency_info;
1733   latency_info.AddLatencyNumber(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
1734                                 0,
1735                                 id);
1736   scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1737   if (RenderWidgetCompositor* rwc = compositor()) {
1738     latency_info_swap_promise_monitor =
1739         rwc->CreateLatencyInfoSwapPromiseMonitor(&latency_info).Pass();
1740   } else {
1741     latency_info_.push_back(latency_info);
1742   }
1743   ScheduleCompositeWithForcedRedraw();
1744 }
1745
1746 void RenderViewImpl::OnWindowSnapshotCompleted(const int snapshot_id,
1747     const gfx::Size& size, const std::vector<unsigned char>& png) {
1748
1749   // Any pending snapshots with a lower ID than the one received are considered
1750   // to be implicitly complete, and returned the same snapshot data.
1751   PendingSnapshotMap::iterator it = pending_snapshots_.begin();
1752   while(it != pending_snapshots_.end()) {
1753       if (it->first <= snapshot_id) {
1754         it->second.Run(size, png);
1755         pending_snapshots_.erase(it++);
1756       } else {
1757         ++it;
1758       }
1759   }
1760 }
1761
1762 // blink::WebViewClient ------------------------------------------------------
1763
1764 WebView* RenderViewImpl::createView(
1765     WebFrame* creator,
1766     const WebURLRequest& request,
1767     const WebWindowFeatures& features,
1768     const WebString& frame_name,
1769     WebNavigationPolicy policy,
1770     bool suppress_opener) {
1771   ViewHostMsg_CreateWindow_Params params;
1772   params.opener_id = routing_id_;
1773   params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
1774   if (GetContentClient()->renderer()->AllowPopup())
1775     params.user_gesture = true;
1776   params.window_container_type = WindowFeaturesToContainerType(features);
1777   params.session_storage_namespace_id = session_storage_namespace_id_;
1778   if (frame_name != "_blank")
1779     params.frame_name = frame_name;
1780   params.opener_frame_id = creator->identifier();
1781   params.opener_url = creator->document().url();
1782   params.opener_top_level_frame_url = creator->top()->document().url();
1783   GURL security_url(creator->document().securityOrigin().toString().utf8());
1784   if (!security_url.is_valid())
1785     security_url = GURL();
1786   params.opener_security_origin = security_url;
1787   params.opener_suppressed = suppress_opener;
1788   params.disposition = NavigationPolicyToDisposition(policy);
1789   if (!request.isNull()) {
1790     params.target_url = request.url();
1791     params.referrer = GetReferrerFromRequest(creator, request);
1792   }
1793   params.features = features;
1794
1795   for (size_t i = 0; i < features.additionalFeatures.size(); ++i)
1796     params.additional_features.push_back(features.additionalFeatures[i]);
1797
1798   int32 routing_id = MSG_ROUTING_NONE;
1799   int32 main_frame_routing_id = MSG_ROUTING_NONE;
1800   int32 surface_id = 0;
1801   int64 cloned_session_storage_namespace_id;
1802
1803   RenderThread::Get()->Send(
1804       new ViewHostMsg_CreateWindow(params,
1805                                    &routing_id,
1806                                    &main_frame_routing_id,
1807                                    &surface_id,
1808                                    &cloned_session_storage_namespace_id));
1809   if (routing_id == MSG_ROUTING_NONE)
1810     return NULL;
1811
1812   WebUserGestureIndicator::consumeUserGesture();
1813
1814   WebPreferences transferred_preferences = webkit_preferences_;
1815
1816   // Unless accelerated compositing has been explicitly disabled from the
1817   // command line (e.g. via the blacklist or about:flags) re-enable it for
1818   // new views that get spawned by this view. This gets around the issue that
1819   // background extension pages disable accelerated compositing via web prefs
1820   // but can themselves spawn a visible render view which should be allowed
1821   // use gpu acceleration.
1822   if (!webkit_preferences_.accelerated_compositing_enabled) {
1823     const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1824     if (!command_line.HasSwitch(switches::kDisableAcceleratedCompositing))
1825       transferred_preferences.accelerated_compositing_enabled = true;
1826   }
1827
1828   // The initial hidden state for the RenderViewImpl here has to match what the
1829   // browser will eventually decide for the given disposition. Since we have to
1830   // return from this call synchronously, we just have to make our best guess
1831   // and rely on the browser sending a WasHidden / WasShown message if it
1832   // disagrees.
1833   RenderViewImpl* view = RenderViewImpl::Create(
1834       routing_id_,
1835       renderer_preferences_,
1836       transferred_preferences,
1837       routing_id,
1838       main_frame_routing_id,
1839       surface_id,
1840       cloned_session_storage_namespace_id,
1841       base::string16(),  // WebCore will take care of setting the correct name.
1842       true,  // is_renderer_created
1843       false, // swapped_out
1844       params.disposition == NEW_BACKGROUND_TAB, // hidden
1845       1,     // next_page_id
1846       screen_info_,
1847       accessibility_mode_,
1848       allow_partial_swap_);
1849   view->opened_by_user_gesture_ = params.user_gesture;
1850
1851   // Record whether the creator frame is trying to suppress the opener field.
1852   view->opener_suppressed_ = params.opener_suppressed;
1853
1854   return view->webview();
1855 }
1856
1857 WebWidget* RenderViewImpl::createPopupMenu(blink::WebPopupType popup_type) {
1858   RenderWidget* widget =
1859       RenderWidget::Create(routing_id_, popup_type, screen_info_);
1860   if (screen_metrics_emulator_) {
1861     widget->SetPopupOriginAdjustmentsForEmulation(
1862         screen_metrics_emulator_.get());
1863   }
1864   return widget->webwidget();
1865 }
1866
1867 WebExternalPopupMenu* RenderViewImpl::createExternalPopupMenu(
1868     const WebPopupMenuInfo& popup_menu_info,
1869     WebExternalPopupMenuClient* popup_menu_client) {
1870   // An IPC message is sent to the browser to build and display the actual
1871   // popup.  The user could have time to click a different select by the time
1872   // the popup is shown.  In that case external_popup_menu_ is non NULL.
1873   // By returning NULL in that case, we instruct WebKit to cancel that new
1874   // popup.  So from the user perspective, only the first one will show, and
1875   // will have to close the first one before another one can be shown.
1876   if (external_popup_menu_)
1877     return NULL;
1878   external_popup_menu_.reset(
1879       new ExternalPopupMenu(this, popup_menu_info, popup_menu_client));
1880   if (screen_metrics_emulator_) {
1881     SetExternalPopupOriginAdjustmentsForEmulation(
1882         external_popup_menu_.get(), screen_metrics_emulator_.get());
1883   }
1884   return external_popup_menu_.get();
1885 }
1886
1887 WebStorageNamespace* RenderViewImpl::createSessionStorageNamespace() {
1888   CHECK(session_storage_namespace_id_ != kInvalidSessionStorageNamespaceId);
1889   return new WebStorageNamespaceImpl(session_storage_namespace_id_);
1890 }
1891
1892 bool RenderViewImpl::shouldReportDetailedMessageForSource(
1893     const WebString& source) {
1894   return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
1895       source);
1896 }
1897
1898 void RenderViewImpl::didAddMessageToConsole(
1899     const WebConsoleMessage& message, const WebString& source_name,
1900     unsigned source_line, const WebString& stack_trace) {
1901   logging::LogSeverity log_severity = logging::LOG_VERBOSE;
1902   switch (message.level) {
1903     case WebConsoleMessage::LevelDebug:
1904       log_severity = logging::LOG_VERBOSE;
1905       break;
1906     case WebConsoleMessage::LevelLog:
1907     case WebConsoleMessage::LevelInfo:
1908       log_severity = logging::LOG_INFO;
1909       break;
1910     case WebConsoleMessage::LevelWarning:
1911       log_severity = logging::LOG_WARNING;
1912       break;
1913     case WebConsoleMessage::LevelError:
1914       log_severity = logging::LOG_ERROR;
1915       break;
1916     default:
1917       NOTREACHED();
1918   }
1919
1920   if (shouldReportDetailedMessageForSource(source_name)) {
1921     FOR_EACH_OBSERVER(
1922         RenderViewObserver,
1923         observers_,
1924         DetailedConsoleMessageAdded(message.text,
1925                                     source_name,
1926                                     stack_trace,
1927                                     source_line,
1928                                     static_cast<int32>(log_severity)));
1929   }
1930
1931   Send(new ViewHostMsg_AddMessageToConsole(routing_id_,
1932                                            static_cast<int32>(log_severity),
1933                                            message.text,
1934                                            static_cast<int32>(source_line),
1935                                            source_name));
1936 }
1937
1938 void RenderViewImpl::printPage(WebFrame* frame) {
1939   FOR_EACH_OBSERVER(RenderViewObserver, observers_,
1940                     PrintPage(frame, handling_input_event_));
1941 }
1942
1943 blink::WebNotificationPresenter* RenderViewImpl::notificationPresenter() {
1944   return notification_provider_;
1945 }
1946
1947 bool RenderViewImpl::enumerateChosenDirectory(
1948     const WebString& path,
1949     WebFileChooserCompletion* chooser_completion) {
1950   int id = enumeration_completion_id_++;
1951   enumeration_completions_[id] = chooser_completion;
1952   return Send(new ViewHostMsg_EnumerateDirectory(
1953       routing_id_,
1954       id,
1955       base::FilePath::FromUTF16Unsafe(path)));
1956 }
1957
1958 void RenderViewImpl::initializeHelperPluginWebFrame(
1959     blink::WebHelperPlugin* plugin) {
1960   plugin->initializeFrame(main_render_frame_.get());
1961 }
1962
1963 void RenderViewImpl::didStartLoading(bool to_different_document) {
1964   didStartLoading();
1965 }
1966
1967 void RenderViewImpl::didStartLoading() {
1968   if (is_loading_) {
1969     DVLOG(1) << "didStartLoading called while loading";
1970     return;
1971   }
1972
1973   is_loading_ = true;
1974
1975   // Send the IPC message through the top-level frame.
1976   main_render_frame_->didStartLoading();
1977
1978   FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStartLoading());
1979 }
1980
1981 void RenderViewImpl::didStopLoading() {
1982   if (!is_loading_) {
1983     DVLOG(1) << "DidStopLoading called while not loading";
1984     return;
1985   }
1986
1987   is_loading_ = false;
1988
1989   // NOTE: For now we're doing the safest thing, and sending out notification
1990   // when done loading. This currently isn't an issue as the favicon is only
1991   // displayed when done loading. Ideally we would send notification when
1992   // finished parsing the head, but webkit doesn't support that yet.
1993   // The feed discovery code would also benefit from access to the head.
1994   // NOTE: Sending of the IPC message happens through the top-level frame.
1995   main_render_frame_->didStopLoading();
1996
1997   if (load_progress_tracker_ != NULL)
1998     load_progress_tracker_->DidStopLoading();
1999
2000   DidStopLoadingIcons();
2001
2002   FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStopLoading());
2003 }
2004
2005 void RenderViewImpl::didChangeLoadProgress(WebFrame* frame,
2006                                            double load_progress) {
2007   if (load_progress_tracker_ != NULL)
2008     load_progress_tracker_->DidChangeLoadProgress(frame, load_progress);
2009 }
2010
2011 void RenderViewImpl::didCancelCompositionOnSelectionChange() {
2012   Send(new ViewHostMsg_ImeCancelComposition(routing_id()));
2013 }
2014
2015 void RenderViewImpl::didChangeSelection(bool is_empty_selection) {
2016   if (!handling_input_event_ && !handling_select_range_)
2017     return;
2018
2019   if (is_empty_selection)
2020     selection_text_.clear();
2021
2022   // UpdateTextInputType should be called before SyncSelectionIfRequired.
2023   // UpdateTextInputType may send TextInputTypeChanged to notify the focus
2024   // was changed, and SyncSelectionIfRequired may send SelectionChanged
2025   // to notify the selection was changed.  Focus change should be notified
2026   // before selection change.
2027   UpdateTextInputType();
2028   SyncSelectionIfRequired();
2029 #if defined(OS_ANDROID)
2030   UpdateTextInputState(false, true);
2031 #endif
2032 }
2033
2034 void RenderViewImpl::didExecuteCommand(const WebString& command_name) {
2035   const std::string& name = base::UTF16ToUTF8(command_name);
2036   if (StartsWithASCII(name, "Move", true) ||
2037       StartsWithASCII(name, "Insert", true) ||
2038       StartsWithASCII(name, "Delete", true))
2039     return;
2040   RenderThreadImpl::current()->RecordComputedAction(name);
2041 }
2042
2043 bool RenderViewImpl::handleCurrentKeyboardEvent() {
2044   if (edit_commands_.empty())
2045     return false;
2046
2047   WebFrame* frame = webview()->focusedFrame();
2048   if (!frame)
2049     return false;
2050
2051   EditCommands::iterator it = edit_commands_.begin();
2052   EditCommands::iterator end = edit_commands_.end();
2053
2054   bool did_execute_command = false;
2055   for (; it != end; ++it) {
2056     // In gtk and cocoa, it's possible to bind multiple edit commands to one
2057     // key (but it's the exception). Once one edit command is not executed, it
2058     // seems safest to not execute the rest.
2059     if (!frame->executeCommand(WebString::fromUTF8(it->name),
2060                                WebString::fromUTF8(it->value),
2061                                GetFocusedNode()))
2062       break;
2063     did_execute_command = true;
2064   }
2065
2066   return did_execute_command;
2067 }
2068
2069 blink::WebColorChooser* RenderViewImpl::createColorChooser(
2070     blink::WebColorChooserClient* client,
2071     const blink::WebColor& initial_color,
2072     const blink::WebVector<blink::WebColorSuggestion>& suggestions) {
2073   RendererWebColorChooserImpl* color_chooser =
2074       new RendererWebColorChooserImpl(this, client);
2075   std::vector<content::ColorSuggestion> color_suggestions;
2076   for (size_t i = 0; i < suggestions.size(); i++) {
2077     color_suggestions.push_back(content::ColorSuggestion(suggestions[i]));
2078   }
2079   color_chooser->Open(static_cast<SkColor>(initial_color), color_suggestions);
2080   return color_chooser;
2081 }
2082
2083 bool RenderViewImpl::runFileChooser(
2084     const blink::WebFileChooserParams& params,
2085     WebFileChooserCompletion* chooser_completion) {
2086   // Do not open the file dialog in a hidden RenderView.
2087   if (is_hidden())
2088     return false;
2089   FileChooserParams ipc_params;
2090   if (params.directory)
2091     ipc_params.mode = FileChooserParams::UploadFolder;
2092   else if (params.multiSelect)
2093     ipc_params.mode = FileChooserParams::OpenMultiple;
2094   else if (params.saveAs)
2095     ipc_params.mode = FileChooserParams::Save;
2096   else
2097     ipc_params.mode = FileChooserParams::Open;
2098   ipc_params.title = params.title;
2099   ipc_params.default_file_name =
2100       base::FilePath::FromUTF16Unsafe(params.initialValue);
2101   ipc_params.accept_types.reserve(params.acceptTypes.size());
2102   for (size_t i = 0; i < params.acceptTypes.size(); ++i)
2103     ipc_params.accept_types.push_back(params.acceptTypes[i]);
2104 #if defined(OS_ANDROID)
2105   ipc_params.capture = params.useMediaCapture;
2106 #endif
2107
2108   return ScheduleFileChooser(ipc_params, chooser_completion);
2109 }
2110
2111 void RenderViewImpl::runModalAlertDialog(WebFrame* frame,
2112                                          const WebString& message) {
2113   RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT,
2114                        message,
2115                        base::string16(),
2116                        frame->document().url(),
2117                        NULL);
2118 }
2119
2120 bool RenderViewImpl::runModalConfirmDialog(WebFrame* frame,
2121                                            const WebString& message) {
2122   return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM,
2123                               message,
2124                               base::string16(),
2125                               frame->document().url(),
2126                               NULL);
2127 }
2128
2129 bool RenderViewImpl::runModalPromptDialog(WebFrame* frame,
2130                                           const WebString& message,
2131                                           const WebString& default_value,
2132                                           WebString* actual_value) {
2133   base::string16 result;
2134   bool ok = RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT,
2135                                  message,
2136                                  default_value,
2137                                  frame->document().url(),
2138                                  &result);
2139   if (ok)
2140     actual_value->assign(result);
2141   return ok;
2142 }
2143
2144 bool RenderViewImpl::runModalBeforeUnloadDialog(
2145     WebFrame* frame, const WebString& message) {
2146   bool is_reload = false;
2147   WebDataSource* ds = frame->provisionalDataSource();
2148   if (ds)
2149     is_reload = (ds->navigationType() == blink::WebNavigationTypeReload);
2150   return runModalBeforeUnloadDialog(frame, is_reload, message);
2151 }
2152
2153 bool RenderViewImpl::runModalBeforeUnloadDialog(
2154     WebFrame* frame, bool is_reload, const WebString& message) {
2155   // If we are swapping out, we have already run the beforeunload handler.
2156   // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
2157   // at all, to avoid running it twice.
2158   if (is_swapped_out_)
2159     return true;
2160
2161   // Don't allow further dialogs if we are waiting to swap out, since the
2162   // PageGroupLoadDeferrer in our stack prevents it.
2163   if (suppress_dialogs_until_swap_out_)
2164     return false;
2165
2166   bool success = false;
2167   // This is an ignored return value, but is included so we can accept the same
2168   // response as RunJavaScriptMessage.
2169   base::string16 ignored_result;
2170   SendAndRunNestedMessageLoop(new ViewHostMsg_RunBeforeUnloadConfirm(
2171       routing_id_, frame->document().url(), message, is_reload,
2172       &success, &ignored_result));
2173   return success;
2174 }
2175
2176 void RenderViewImpl::showValidationMessage(
2177     const blink::WebRect& anchor_in_root_view,
2178     const blink::WebString& main_text,
2179     const blink::WebString& sub_text,
2180     blink::WebTextDirection hint) {
2181   base::string16 wrapped_main_text = main_text;
2182   base::string16 wrapped_sub_text = sub_text;
2183   if (hint == blink::WebTextDirectionLeftToRight) {
2184     wrapped_main_text =
2185         base::i18n::GetDisplayStringInLTRDirectionality(wrapped_main_text);
2186     if (!wrapped_sub_text.empty()) {
2187       wrapped_sub_text =
2188           base::i18n::GetDisplayStringInLTRDirectionality(wrapped_sub_text);
2189     }
2190   } else if (hint == blink::WebTextDirectionRightToLeft
2191              && !base::i18n::IsRTL()) {
2192     base::i18n::WrapStringWithRTLFormatting(&wrapped_main_text);
2193     if (!wrapped_sub_text.empty()) {
2194       base::i18n::WrapStringWithRTLFormatting(&wrapped_sub_text);
2195     }
2196   }
2197   Send(new ViewHostMsg_ShowValidationMessage(
2198     routing_id(), anchor_in_root_view, wrapped_main_text, wrapped_sub_text));
2199 }
2200
2201 void RenderViewImpl::hideValidationMessage() {
2202   Send(new ViewHostMsg_HideValidationMessage(routing_id()));
2203 }
2204
2205 void RenderViewImpl::moveValidationMessage(
2206     const blink::WebRect& anchor_in_root_view) {
2207   Send(new ViewHostMsg_MoveValidationMessage(routing_id(),
2208                                              anchor_in_root_view));
2209 }
2210
2211 void RenderViewImpl::showContextMenu(
2212     WebFrame* frame, const blink::WebContextMenuData& data) {
2213   // TODO(jam): move this method to WebFrameClient.
2214   RenderFrameImpl* render_frame = RenderFrameImpl::FromWebFrame(frame);
2215   render_frame->showContextMenu(data);
2216 }
2217
2218 void RenderViewImpl::clearContextMenu() {
2219   context_menu_node_.reset();
2220 }
2221
2222 void RenderViewImpl::setStatusText(const WebString& text) {
2223 }
2224
2225 void RenderViewImpl::UpdateTargetURL(const GURL& url,
2226                                      const GURL& fallback_url) {
2227   GURL latest_url = url.is_empty() ? fallback_url : url;
2228   if (latest_url == target_url_)
2229     return;
2230
2231   // Tell the browser to display a destination link.
2232   if (target_url_status_ == TARGET_INFLIGHT ||
2233       target_url_status_ == TARGET_PENDING) {
2234     // If we have a request in-flight, save the URL to be sent when we
2235     // receive an ACK to the in-flight request. We can happily overwrite
2236     // any existing pending sends.
2237     pending_target_url_ = latest_url;
2238     target_url_status_ = TARGET_PENDING;
2239   } else {
2240     // URLs larger than |MaxURLChars()| cannot be sent through IPC -
2241     // see |ParamTraits<GURL>|.
2242     if (latest_url.possibly_invalid_spec().size() > GetMaxURLChars())
2243       latest_url = GURL();
2244     Send(new ViewHostMsg_UpdateTargetURL(routing_id_, page_id_, latest_url));
2245     target_url_ = latest_url;
2246     target_url_status_ = TARGET_INFLIGHT;
2247   }
2248 }
2249
2250 gfx::RectF RenderViewImpl::ClientRectToPhysicalWindowRect(
2251     const gfx::RectF& rect) const {
2252   gfx::RectF window_rect = rect;
2253   window_rect.Scale(device_scale_factor_ * webview()->pageScaleFactor());
2254   return window_rect;
2255 }
2256
2257 void RenderViewImpl::StartNavStateSyncTimerIfNecessary() {
2258   // No need to update state if no page has committed yet.
2259   if (page_id_ == -1)
2260     return;
2261
2262   int delay;
2263   if (send_content_state_immediately_)
2264     delay = 0;
2265   else if (is_hidden())
2266     delay = kDelaySecondsForContentStateSyncHidden;
2267   else
2268     delay = kDelaySecondsForContentStateSync;
2269
2270   if (nav_state_sync_timer_.IsRunning()) {
2271     // The timer is already running. If the delay of the timer maches the amount
2272     // we want to delay by, then return. Otherwise stop the timer so that it
2273     // gets started with the right delay.
2274     if (nav_state_sync_timer_.GetCurrentDelay().InSeconds() == delay)
2275       return;
2276     nav_state_sync_timer_.Stop();
2277   }
2278
2279   nav_state_sync_timer_.Start(FROM_HERE, TimeDelta::FromSeconds(delay), this,
2280                               &RenderViewImpl::SyncNavigationState);
2281 }
2282
2283 void RenderViewImpl::setMouseOverURL(const WebURL& url) {
2284   mouse_over_url_ = GURL(url);
2285   UpdateTargetURL(mouse_over_url_, focus_url_);
2286 }
2287
2288 void RenderViewImpl::setKeyboardFocusURL(const WebURL& url) {
2289   focus_url_ = GURL(url);
2290   UpdateTargetURL(focus_url_, mouse_over_url_);
2291 }
2292
2293 void RenderViewImpl::startDragging(WebFrame* frame,
2294                                    const WebDragData& data,
2295                                    WebDragOperationsMask mask,
2296                                    const WebImage& image,
2297                                    const WebPoint& webImageOffset) {
2298   DropData drop_data(DropDataBuilder::Build(data));
2299   drop_data.referrer_policy = frame->document().referrerPolicy();
2300   gfx::Vector2d imageOffset(webImageOffset.x, webImageOffset.y);
2301   Send(new DragHostMsg_StartDragging(routing_id_,
2302                                      drop_data,
2303                                      mask,
2304                                      image.getSkBitmap(),
2305                                      imageOffset,
2306                                      possible_drag_event_info_));
2307 }
2308
2309 bool RenderViewImpl::acceptsLoadDrops() {
2310   return renderer_preferences_.can_accept_load_drops;
2311 }
2312
2313 void RenderViewImpl::focusNext() {
2314   Send(new ViewHostMsg_TakeFocus(routing_id_, false));
2315 }
2316
2317 void RenderViewImpl::focusPrevious() {
2318   Send(new ViewHostMsg_TakeFocus(routing_id_, true));
2319 }
2320
2321 void RenderViewImpl::focusedNodeChanged(const WebNode& node) {
2322   Send(new ViewHostMsg_FocusedNodeChanged(routing_id_, IsEditableNode(node)));
2323
2324   FOR_EACH_OBSERVER(RenderViewObserver, observers_, FocusedNodeChanged(node));
2325 }
2326
2327 void RenderViewImpl::numberOfWheelEventHandlersChanged(unsigned num_handlers) {
2328   Send(new ViewHostMsg_DidChangeNumWheelEvents(routing_id_, num_handlers));
2329 }
2330
2331 void RenderViewImpl::didUpdateLayout() {
2332   FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidUpdateLayout());
2333
2334   // We don't always want to set up a timer, only if we've been put in that
2335   // mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
2336   // message.
2337   if (!send_preferred_size_changes_ || !webview())
2338     return;
2339
2340   if (check_preferred_size_timer_.IsRunning())
2341     return;
2342   check_preferred_size_timer_.Start(FROM_HERE,
2343                                     TimeDelta::FromMilliseconds(0), this,
2344                                     &RenderViewImpl::CheckPreferredSize);
2345 }
2346
2347 void RenderViewImpl::navigateBackForwardSoon(int offset) {
2348   Send(new ViewHostMsg_GoToEntryAtOffset(routing_id_, offset));
2349 }
2350
2351 int RenderViewImpl::historyBackListCount() {
2352   return history_list_offset_ < 0 ? 0 : history_list_offset_;
2353 }
2354
2355 int RenderViewImpl::historyForwardListCount() {
2356   return history_list_length_ - historyBackListCount() - 1;
2357 }
2358
2359 void RenderViewImpl::postAccessibilityEvent(
2360     const WebAXObject& obj, blink::WebAXEvent event) {
2361   if (renderer_accessibility_) {
2362     renderer_accessibility_->HandleWebAccessibilityEvent(obj, event);
2363   }
2364 }
2365
2366 void RenderViewImpl::didUpdateInspectorSetting(const WebString& key,
2367                                            const WebString& value) {
2368   Send(new ViewHostMsg_UpdateInspectorSetting(routing_id_,
2369                                               key.utf8(),
2370                                               value.utf8()));
2371 }
2372
2373 // blink::WebWidgetClient ----------------------------------------------------
2374
2375 void RenderViewImpl::didFocus() {
2376   // TODO(jcivelli): when https://bugs.webkit.org/show_bug.cgi?id=33389 is fixed
2377   //                 we won't have to test for user gesture anymore and we can
2378   //                 move that code back to render_widget.cc
2379   if (WebUserGestureIndicator::isProcessingUserGesture() &&
2380       !RenderThreadImpl::current()->layout_test_mode()) {
2381     Send(new ViewHostMsg_Focus(routing_id_));
2382   }
2383 }
2384
2385 void RenderViewImpl::didBlur() {
2386   // TODO(jcivelli): see TODO above in didFocus().
2387   if (WebUserGestureIndicator::isProcessingUserGesture() &&
2388       !RenderThreadImpl::current()->layout_test_mode()) {
2389     Send(new ViewHostMsg_Blur(routing_id_));
2390   }
2391 }
2392
2393 // We are supposed to get a single call to Show for a newly created RenderView
2394 // that was created via RenderViewImpl::CreateWebView.  So, we wait until this
2395 // point to dispatch the ShowView message.
2396 //
2397 // This method provides us with the information about how to display the newly
2398 // created RenderView (i.e., as a blocked popup or as a new tab).
2399 //
2400 void RenderViewImpl::show(WebNavigationPolicy policy) {
2401   if (did_show_) {
2402     // When supports_multiple_windows is disabled, popups are reusing
2403     // the same view. In some scenarios, this makes WebKit to call show() twice.
2404     if (webkit_preferences_.supports_multiple_windows)
2405       NOTREACHED() << "received extraneous Show call";
2406     return;
2407   }
2408   did_show_ = true;
2409
2410   DCHECK(opener_id_ != MSG_ROUTING_NONE);
2411
2412   // Force new windows to a popup if they were not opened with a user gesture.
2413   if (!opened_by_user_gesture_) {
2414     // We exempt background tabs for compat with older versions of Chrome.
2415     // TODO(darin): This seems bogus.  These should have a user gesture, so
2416     // we probably don't need this check.
2417     if (policy != blink::WebNavigationPolicyNewBackgroundTab)
2418       policy = blink::WebNavigationPolicyNewPopup;
2419   }
2420
2421   // NOTE: initial_pos_ may still have its default values at this point, but
2422   // that's okay.  It'll be ignored if disposition is not NEW_POPUP, or the
2423   // browser process will impose a default position otherwise.
2424   Send(new ViewHostMsg_ShowView(opener_id_, routing_id_,
2425       NavigationPolicyToDisposition(policy), initial_pos_,
2426       opened_by_user_gesture_));
2427   SetPendingWindowRect(initial_pos_);
2428 }
2429
2430 void RenderViewImpl::runModal() {
2431   DCHECK(did_show_) << "should already have shown the view";
2432
2433   // Don't allow further dialogs if we are waiting to swap out, since the
2434   // PageGroupLoadDeferrer in our stack prevents it.
2435   if (suppress_dialogs_until_swap_out_)
2436     return;
2437
2438   // We must keep WebKit's shared timer running in this case in order to allow
2439   // showModalDialog to function properly.
2440   //
2441   // TODO(darin): WebKit should really be smarter about suppressing events and
2442   // timers so that we do not need to manage the shared timer in such a heavy
2443   // handed manner.
2444   //
2445   if (RenderThreadImpl::current())  // Will be NULL during unit tests.
2446     RenderThreadImpl::current()->DoNotSuspendWebKitSharedTimer();
2447
2448   SendAndRunNestedMessageLoop(new ViewHostMsg_RunModal(
2449       routing_id_, opener_id_));
2450 }
2451
2452 bool RenderViewImpl::enterFullScreen() {
2453   Send(new ViewHostMsg_ToggleFullscreen(routing_id_, true));
2454   return true;
2455 }
2456
2457 void RenderViewImpl::exitFullScreen() {
2458   Send(new ViewHostMsg_ToggleFullscreen(routing_id_, false));
2459 }
2460
2461 bool RenderViewImpl::requestPointerLock() {
2462   return mouse_lock_dispatcher_->LockMouse(webwidget_mouse_lock_target_.get());
2463 }
2464
2465 void RenderViewImpl::requestPointerUnlock() {
2466   mouse_lock_dispatcher_->UnlockMouse(webwidget_mouse_lock_target_.get());
2467 }
2468
2469 bool RenderViewImpl::isPointerLocked() {
2470   return mouse_lock_dispatcher_->IsMouseLockedTo(
2471       webwidget_mouse_lock_target_.get());
2472 }
2473
2474 void RenderViewImpl::didActivateCompositor(int input_handler_identifier) {
2475 #if !defined(OS_MACOSX)  // many events are unhandled - http://crbug.com/138003
2476   InputHandlerManager* input_handler_manager =
2477       RenderThreadImpl::current()->input_handler_manager();
2478   if (input_handler_manager) {
2479      input_handler_manager->AddInputHandler(
2480         routing_id_,
2481         compositor_->GetInputHandler(),
2482         AsWeakPtr());
2483   }
2484 #endif
2485
2486   RenderWidget::didActivateCompositor(input_handler_identifier);
2487 }
2488
2489 void RenderViewImpl::didHandleGestureEvent(
2490     const WebGestureEvent& event,
2491     bool event_cancelled) {
2492   RenderWidget::didHandleGestureEvent(event, event_cancelled);
2493
2494   if (event.type != blink::WebGestureEvent::GestureTap)
2495     return;
2496
2497   blink::WebTextInputType text_input_type =
2498       GetWebView()->textInputInfo().type;
2499
2500   Send(new ViewHostMsg_FocusedNodeTouched(
2501       routing_id(), text_input_type != blink::WebTextInputTypeNone));
2502 }
2503
2504 void RenderViewImpl::initializeLayerTreeView() {
2505   RenderWidget::initializeLayerTreeView();
2506   RenderWidgetCompositor* rwc = compositor();
2507   if (!rwc || !webview() || !webview()->devToolsAgent())
2508     return;
2509   webview()->devToolsAgent()->setLayerTreeId(rwc->GetLayerTreeId());
2510 }
2511
2512 // blink::WebFrameClient -----------------------------------------------------
2513
2514 WebMediaPlayer* RenderViewImpl::createMediaPlayer(
2515     WebFrame* frame, const blink::WebURL& url, WebMediaPlayerClient* client) {
2516   NOTREACHED();
2517   return NULL;
2518 }
2519
2520 blink::WebMediaPlayer* RenderViewImpl::CreateMediaPlayer(
2521     RenderFrame* render_frame,
2522     blink::WebFrame* frame,
2523     const blink::WebURL& url,
2524     blink::WebMediaPlayerClient* client) {
2525   FOR_EACH_OBSERVER(
2526       RenderViewObserver, observers_, WillCreateMediaPlayer(frame, client));
2527
2528   WebMediaPlayer* player = CreateWebMediaPlayerForMediaStream(frame, url,
2529                                                               client);
2530   if (player)
2531     return player;
2532
2533 #if defined(OS_ANDROID)
2534   return CreateAndroidWebMediaPlayer(frame, url, client);
2535 #else
2536   scoped_refptr<media::AudioRendererSink> sink;
2537   if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableAudio)) {
2538     sink = RenderThreadImpl::current()->GetAudioRendererMixerManager()->
2539         CreateInput(routing_id_, render_frame->GetRoutingID());
2540     DVLOG(1) << "Using AudioRendererMixerManager-provided sink: " << sink.get();
2541   }
2542
2543   WebMediaPlayerParams params(
2544       base::Bind(&ContentRendererClient::DeferMediaLoad,
2545                  base::Unretained(GetContentClient()->renderer()),
2546                  static_cast<RenderFrame*>(render_frame)),
2547       sink);
2548   return new WebMediaPlayerImpl(frame, client, AsWeakPtr(), params);
2549 #endif  // defined(OS_ANDROID)
2550 }
2551
2552 void RenderViewImpl::didAccessInitialDocument(WebFrame* frame) {
2553   // Notify the browser process that it is no longer safe to show the pending
2554   // URL of the main frame, since a URL spoof is now possible.
2555   if (!frame->parent() && page_id_ == -1)
2556     Send(new ViewHostMsg_DidAccessInitialDocument(routing_id_));
2557 }
2558
2559 void RenderViewImpl::didDisownOpener(blink::WebFrame* frame) {
2560   // We only need to notify the browser if the active, top-level frame clears
2561   // its opener.  We can ignore cases where a swapped out frame clears its
2562   // opener after hearing about it from the browser, and the browser does not
2563   // (yet) care about subframe openers.
2564   if (is_swapped_out_ || frame->parent())
2565     return;
2566
2567   // Notify WebContents and all its swapped out RenderViews.
2568   Send(new ViewHostMsg_DidDisownOpener(routing_id_));
2569 }
2570
2571 void RenderViewImpl::frameDetached(WebFrame* frame) {
2572   // NOTE: We may get here for either the main frame or for subframes.  The
2573   // RenderFrameImpl will be deleted immediately after this call for subframes
2574   // but not for the main frame, which is owned by |main_render_frame_|.
2575
2576   FOR_EACH_OBSERVER(RenderViewObserver, observers_, FrameDetached(frame));
2577 }
2578
2579 void RenderViewImpl::willClose(WebFrame* frame) {
2580   FOR_EACH_OBSERVER(RenderViewObserver, observers_, FrameWillClose(frame));
2581 }
2582
2583 void RenderViewImpl::didMatchCSS(
2584     WebFrame* frame,
2585     const WebVector<WebString>& newly_matching_selectors,
2586     const WebVector<WebString>& stopped_matching_selectors) {
2587   FOR_EACH_OBSERVER(
2588       RenderViewObserver, observers_,
2589       DidMatchCSS(frame, newly_matching_selectors, stopped_matching_selectors));
2590 }
2591
2592 void RenderViewImpl::Repaint(const gfx::Size& size) {
2593   OnRepaint(size);
2594 }
2595
2596 void RenderViewImpl::SetEditCommandForNextKeyEvent(const std::string& name,
2597                                                    const std::string& value) {
2598   EditCommands edit_commands;
2599   edit_commands.push_back(EditCommand(name, value));
2600   OnSetEditCommandsForNextKeyEvent(edit_commands);
2601 }
2602
2603 void RenderViewImpl::ClearEditCommands() {
2604   edit_commands_.clear();
2605 }
2606
2607 SSLStatus RenderViewImpl::GetSSLStatusOfFrame(blink::WebFrame* frame) const {
2608   std::string security_info;
2609   if (frame && frame->dataSource())
2610     security_info = frame->dataSource()->response().securityInfo();
2611
2612   SSLStatus ssl_status;
2613   DeserializeSecurityInfo(security_info,
2614                           &ssl_status.cert_id,
2615                           &ssl_status.cert_status,
2616                           &ssl_status.security_bits,
2617                           &ssl_status.connection_status,
2618                           &ssl_status.signed_certificate_timestamp_ids);
2619   return ssl_status;
2620 }
2621
2622 const std::string& RenderViewImpl::GetAcceptLanguages() const {
2623   return renderer_preferences_.accept_languages;
2624 }
2625
2626 WebNavigationPolicy RenderViewImpl::DecidePolicyForNavigation(
2627     RenderFrame* render_frame, WebFrame* frame,
2628     WebDataSource::ExtraData* extraData, const WebURLRequest& request,
2629     WebNavigationType type, WebNavigationPolicy default_policy,
2630     bool is_redirect) {
2631 #ifdef OS_ANDROID
2632   // The handlenavigation API is deprecated and will be removed once
2633   // crbug.com/325351 is resolved.
2634   if (request.url() != GURL(kSwappedOutURL) &&
2635       GetContentClient()->renderer()->HandleNavigation(
2636           render_frame,
2637           static_cast<DocumentState*>(extraData),
2638           opener_id_,
2639           frame,
2640           request,
2641           type,
2642           default_policy,
2643           is_redirect)) {
2644     return blink::WebNavigationPolicyIgnore;
2645   }
2646 #endif
2647
2648   Referrer referrer(GetReferrerFromRequest(frame, request));
2649
2650   if (is_swapped_out_) {
2651     if (request.url() != GURL(kSwappedOutURL)) {
2652       // Targeted links may try to navigate a swapped out frame.  Allow the
2653       // browser process to navigate the tab instead.  Note that it is also
2654       // possible for non-targeted navigations (from this view) to arrive
2655       // here just after we are swapped out.  It's ok to send them to the
2656       // browser, as long as they're for the top level frame.
2657       // TODO(creis): Ensure this supports targeted form submissions when
2658       // fixing http://crbug.com/101395.
2659       if (frame->parent() == NULL) {
2660         OpenURL(frame, request.url(), referrer, default_policy);
2661         return blink::WebNavigationPolicyIgnore;  // Suppress the load here.
2662       }
2663
2664       // We should otherwise ignore in-process iframe navigations, if they
2665       // arrive just after we are swapped out.
2666       return blink::WebNavigationPolicyIgnore;
2667     }
2668
2669     // Allow kSwappedOutURL to complete.
2670     return default_policy;
2671   }
2672
2673   // Webkit is asking whether to navigate to a new URL.
2674   // This is fine normally, except if we're showing UI from one security
2675   // context and they're trying to navigate to a different context.
2676   const GURL& url = request.url();
2677
2678   // A content initiated navigation may have originated from a link-click,
2679   // script, drag-n-drop operation, etc.
2680   bool is_content_initiated = static_cast<DocumentState*>(extraData)->
2681           navigation_state()->is_content_initiated();
2682
2683   // Experimental:
2684   // If --enable-strict-site-isolation or --site-per-process is enabled, send
2685   // all top-level navigations to the browser to let it swap processes when
2686   // crossing site boundaries.  This is currently expected to break some script
2687   // calls and navigations, such as form submissions.
2688   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
2689   bool force_swap_due_to_flag =
2690       command_line.HasSwitch(switches::kEnableStrictSiteIsolation) ||
2691       command_line.HasSwitch(switches::kSitePerProcess);
2692   if (force_swap_due_to_flag &&
2693       !frame->parent() && (is_content_initiated || is_redirect)) {
2694     WebString origin_str = frame->document().securityOrigin().toString();
2695     GURL frame_url(origin_str.utf8().data());
2696     // TODO(cevans): revisit whether this site check is still necessary once
2697     // crbug.com/101395 is fixed.
2698     bool same_domain_or_host =
2699         net::registry_controlled_domains::SameDomainOrHost(
2700             frame_url,
2701             url,
2702             net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
2703     if (!same_domain_or_host || frame_url.scheme() != url.scheme()) {
2704       OpenURL(frame, url, referrer, default_policy);
2705       return blink::WebNavigationPolicyIgnore;
2706     }
2707   }
2708
2709   // If the browser is interested, then give it a chance to look at the request.
2710   if (is_content_initiated) {
2711     bool is_form_post = ((type == blink::WebNavigationTypeFormSubmitted) ||
2712                          (type == blink::WebNavigationTypeFormResubmitted)) &&
2713                         EqualsASCII(request.httpMethod(), "POST");
2714     bool browser_handles_request =
2715         renderer_preferences_.browser_handles_non_local_top_level_requests &&
2716         IsNonLocalTopLevelNavigation(url, frame, type, is_form_post);
2717     if (!browser_handles_request) {
2718       browser_handles_request = IsTopLevelNavigation(frame) &&
2719           renderer_preferences_.browser_handles_all_top_level_requests;
2720     }
2721
2722     if (browser_handles_request) {
2723       // Reset these counters as the RenderView could be reused for the next
2724       // navigation.
2725       page_id_ = -1;
2726       last_page_id_sent_to_browser_ = -1;
2727       OpenURL(frame, url, referrer, default_policy);
2728       return blink::WebNavigationPolicyIgnore;  // Suppress the load here.
2729     }
2730   }
2731
2732   // Use the frame's original request's URL rather than the document's URL for
2733   // subsequent checks.  For a popup, the document's URL may become the opener
2734   // window's URL if the opener has called document.write().
2735   // See http://crbug.com/93517.
2736   GURL old_url(frame->dataSource()->request().url());
2737
2738   // Detect when we're crossing a permission-based boundary (e.g. into or out of
2739   // an extension or app origin, leaving a WebUI page, etc). We only care about
2740   // top-level navigations (not iframes). But we sometimes navigate to
2741   // about:blank to clear a tab, and we want to still allow that.
2742   //
2743   // Note: this is known to break POST submissions when crossing process
2744   // boundaries until http://crbug.com/101395 is fixed.  This is better for
2745   // security than loading a WebUI, extension or app page in the wrong process.
2746   // POST requests don't work because this mechanism does not preserve form
2747   // POST data. We will need to send the request's httpBody data up to the
2748   // browser process, and issue a special POST navigation in WebKit (via
2749   // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
2750   // for examples of how to send the httpBody data.
2751   if (!frame->parent() && is_content_initiated &&
2752       !url.SchemeIs(chrome::kAboutScheme)) {
2753     bool send_referrer = false;
2754
2755     // All navigations to or from WebUI URLs or within WebUI-enabled
2756     // RenderProcesses must be handled by the browser process so that the
2757     // correct bindings and data sources can be registered.
2758     // Similarly, navigations to view-source URLs or within ViewSource mode
2759     // must be handled by the browser process (except for reloads - those are
2760     // safe to leave within the renderer).
2761     // Lastly, access to file:// URLs from non-file:// URL pages must be
2762     // handled by the browser so that ordinary renderer processes don't get
2763     // blessed with file permissions.
2764     int cumulative_bindings = RenderProcess::current()->GetEnabledBindings();
2765     bool is_initial_navigation = page_id_ == -1;
2766     bool should_fork = HasWebUIScheme(url) || HasWebUIScheme(old_url) ||
2767         (cumulative_bindings & BINDINGS_POLICY_WEB_UI) ||
2768         url.SchemeIs(kViewSourceScheme) ||
2769         (frame->isViewSourceModeEnabled() &&
2770             type != blink::WebNavigationTypeReload);
2771
2772     if (!should_fork && url.SchemeIs(kFileScheme)) {
2773       // Fork non-file to file opens.  Check the opener URL if this is the
2774       // initial navigation in a newly opened window.
2775       GURL source_url(old_url);
2776       if (is_initial_navigation && source_url.is_empty() && frame->opener())
2777         source_url = frame->opener()->top()->document().url();
2778       DCHECK(!source_url.is_empty());
2779       should_fork = !source_url.SchemeIs(kFileScheme);
2780     }
2781
2782     if (!should_fork) {
2783       // Give the embedder a chance.
2784       should_fork = GetContentClient()->renderer()->ShouldFork(
2785           frame, url, request.httpMethod().utf8(), is_initial_navigation,
2786           is_redirect, &send_referrer);
2787     }
2788
2789     if (should_fork) {
2790       OpenURL(
2791           frame, url, send_referrer ? referrer : Referrer(), default_policy);
2792       return blink::WebNavigationPolicyIgnore;  // Suppress the load here.
2793     }
2794   }
2795
2796   // Detect when a page is "forking" a new tab that can be safely rendered in
2797   // its own process.  This is done by sites like Gmail that try to open links
2798   // in new windows without script connections back to the original page.  We
2799   // treat such cases as browser navigations (in which we will create a new
2800   // renderer for a cross-site navigation), rather than WebKit navigations.
2801   //
2802   // We use the following heuristic to decide whether to fork a new page in its
2803   // own process:
2804   // The parent page must open a new tab to about:blank, set the new tab's
2805   // window.opener to null, and then redirect the tab to a cross-site URL using
2806   // JavaScript.
2807   //
2808   // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
2809   // (see below).
2810   bool is_fork =
2811       // Must start from a tab showing about:blank, which is later redirected.
2812       old_url == GURL(kAboutBlankURL) &&
2813       // Must be the first real navigation of the tab.
2814       historyBackListCount() < 1 &&
2815       historyForwardListCount() < 1 &&
2816       // The parent page must have set the child's window.opener to null before
2817       // redirecting to the desired URL.
2818       frame->opener() == NULL &&
2819       // Must be a top-level frame.
2820       frame->parent() == NULL &&
2821       // Must not have issued the request from this page.
2822       is_content_initiated &&
2823       // Must be targeted at the current tab.
2824       default_policy == blink::WebNavigationPolicyCurrentTab &&
2825       // Must be a JavaScript navigation, which appears as "other".
2826       type == blink::WebNavigationTypeOther;
2827
2828   if (is_fork) {
2829     // Open the URL via the browser, not via WebKit.
2830     OpenURL(frame, url, Referrer(), default_policy);
2831     return blink::WebNavigationPolicyIgnore;
2832   }
2833
2834   return default_policy;
2835 }
2836
2837 void RenderViewImpl::willSendSubmitEvent(blink::WebFrame* frame,
2838     const blink::WebFormElement& form) {
2839   FOR_EACH_OBSERVER(
2840       RenderViewObserver, observers_, WillSendSubmitEvent(frame, form));
2841 }
2842
2843 void RenderViewImpl::willSubmitForm(WebFrame* frame,
2844                                     const WebFormElement& form) {
2845   FOR_EACH_OBSERVER(
2846       RenderViewObserver, observers_, WillSubmitForm(frame, form));
2847 }
2848
2849 void RenderViewImpl::didCreateDataSource(WebFrame* frame, WebDataSource* ds) {
2850   bool content_initiated = !pending_navigation_params_.get();
2851
2852   // Make sure any previous redirect URLs end up in our new data source.
2853   if (pending_navigation_params_.get()) {
2854     for (std::vector<GURL>::const_iterator i =
2855              pending_navigation_params_->redirects.begin();
2856          i != pending_navigation_params_->redirects.end(); ++i) {
2857       ds->appendRedirect(*i);
2858     }
2859   }
2860
2861   DocumentState* document_state = DocumentState::FromDataSource(ds);
2862   if (!document_state) {
2863     document_state = new DocumentState;
2864     ds->setExtraData(document_state);
2865     if (!content_initiated)
2866       PopulateDocumentStateFromPending(document_state);
2867   }
2868
2869   // Carry over the user agent override flag, if it exists.
2870   if (content_initiated && webview() && webview()->mainFrame() &&
2871       webview()->mainFrame()->dataSource()) {
2872     DocumentState* old_document_state =
2873         DocumentState::FromDataSource(webview()->mainFrame()->dataSource());
2874     if (old_document_state) {
2875       InternalDocumentStateData* internal_data =
2876           InternalDocumentStateData::FromDocumentState(document_state);
2877       InternalDocumentStateData* old_internal_data =
2878           InternalDocumentStateData::FromDocumentState(old_document_state);
2879       internal_data->set_is_overriding_user_agent(
2880           old_internal_data->is_overriding_user_agent());
2881     }
2882   }
2883
2884   // The rest of RenderView assumes that a WebDataSource will always have a
2885   // non-null NavigationState.
2886   if (content_initiated) {
2887     document_state->set_navigation_state(
2888         NavigationState::CreateContentInitiated());
2889   } else {
2890     document_state->set_navigation_state(CreateNavigationStateFromPending());
2891     pending_navigation_params_.reset();
2892   }
2893
2894   // DocumentState::referred_by_prefetcher_ is true if we are
2895   // navigating from a page that used prefetching using a link on that
2896   // page.  We are early enough in the request process here that we
2897   // can still see the DocumentState of the previous page and set
2898   // this value appropriately.
2899   // TODO(gavinp): catch the important case of navigation in a new
2900   // renderer process.
2901   if (webview()) {
2902     if (WebFrame* old_frame = webview()->mainFrame()) {
2903       const WebURLRequest& original_request = ds->originalRequest();
2904       const GURL referrer(
2905           original_request.httpHeaderField(WebString::fromUTF8("Referer")));
2906       if (!referrer.is_empty() &&
2907           DocumentState::FromDataSource(
2908               old_frame->dataSource())->was_prefetcher()) {
2909         for (; old_frame; old_frame = old_frame->traverseNext(false)) {
2910           WebDataSource* old_frame_ds = old_frame->dataSource();
2911           if (old_frame_ds && referrer == GURL(old_frame_ds->request().url())) {
2912             document_state->set_was_referred_by_prefetcher(true);
2913             break;
2914           }
2915         }
2916       }
2917     }
2918   }
2919
2920   if (content_initiated) {
2921     const WebURLRequest& request = ds->request();
2922     switch (request.cachePolicy()) {
2923       case WebURLRequest::UseProtocolCachePolicy:  // normal load.
2924         document_state->set_load_type(DocumentState::LINK_LOAD_NORMAL);
2925         break;
2926       case WebURLRequest::ReloadIgnoringCacheData:  // reload.
2927         document_state->set_load_type(DocumentState::LINK_LOAD_RELOAD);
2928         break;
2929       case WebURLRequest::ReturnCacheDataElseLoad:  // allow stale data.
2930         document_state->set_load_type(
2931             DocumentState::LINK_LOAD_CACHE_STALE_OK);
2932         break;
2933       case WebURLRequest::ReturnCacheDataDontLoad:  // Don't re-post.
2934         document_state->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY);
2935         break;
2936     }
2937   }
2938
2939   FOR_EACH_OBSERVER(
2940       RenderViewObserver, observers_, DidCreateDataSource(frame, ds));
2941 }
2942
2943 void RenderViewImpl::PopulateDocumentStateFromPending(
2944     DocumentState* document_state) {
2945   const FrameMsg_Navigate_Params& params = *pending_navigation_params_.get();
2946   document_state->set_request_time(params.request_time);
2947
2948   InternalDocumentStateData* internal_data =
2949       InternalDocumentStateData::FromDocumentState(document_state);
2950
2951   if (!params.url.SchemeIs(kJavaScriptScheme) &&
2952       params.navigation_type == FrameMsg_Navigate_Type::RESTORE) {
2953     // We're doing a load of a page that was restored from the last session. By
2954     // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
2955     // can result in stale data for pages that are set to expire. We explicitly
2956     // override that by setting the policy here so that as necessary we load
2957     // from the network.
2958     //
2959     // TODO(davidben): Remove this in favor of passing a cache policy to the
2960     // loadHistoryItem call in OnNavigate. That requires not overloading
2961     // UseProtocolCachePolicy to mean both "normal load" and "determine cache
2962     // policy based on load type, etc".
2963     internal_data->set_cache_policy_override(
2964         WebURLRequest::UseProtocolCachePolicy);
2965   }
2966
2967   if (IsReload(params))
2968     document_state->set_load_type(DocumentState::RELOAD);
2969   else if (params.page_state.IsValid())
2970     document_state->set_load_type(DocumentState::HISTORY_LOAD);
2971   else
2972     document_state->set_load_type(DocumentState::NORMAL_LOAD);
2973
2974   internal_data->set_is_overriding_user_agent(params.is_overriding_user_agent);
2975   internal_data->set_must_reset_scroll_and_scale_state(
2976       params.navigation_type ==
2977           FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
2978   document_state->set_can_load_local_resources(params.can_load_local_resources);
2979 }
2980
2981 NavigationState* RenderViewImpl::CreateNavigationStateFromPending() {
2982   const FrameMsg_Navigate_Params& params = *pending_navigation_params_.get();
2983   NavigationState* navigation_state = NULL;
2984
2985   // A navigation resulting from loading a javascript URL should not be treated
2986   // as a browser initiated event.  Instead, we want it to look as if the page
2987   // initiated any load resulting from JS execution.
2988   if (!params.url.SchemeIs(kJavaScriptScheme)) {
2989     navigation_state = NavigationState::CreateBrowserInitiated(
2990         params.page_id,
2991         params.pending_history_list_offset,
2992         params.should_clear_history_list,
2993         params.transition);
2994     navigation_state->set_should_replace_current_entry(
2995         params.should_replace_current_entry);
2996     navigation_state->set_transferred_request_child_id(
2997         params.transferred_request_child_id);
2998     navigation_state->set_transferred_request_request_id(
2999         params.transferred_request_request_id);
3000     navigation_state->set_allow_download(params.allow_download);
3001     navigation_state->set_extra_headers(params.extra_headers);
3002   } else {
3003     navigation_state = NavigationState::CreateContentInitiated();
3004   }
3005   return navigation_state;
3006 }
3007
3008 void RenderViewImpl::ProcessViewLayoutFlags(const CommandLine& command_line) {
3009   bool enable_viewport =
3010       command_line.HasSwitch(switches::kEnableViewport) ||
3011       command_line.HasSwitch(switches::kEnableViewportMeta);
3012
3013   // If viewport tag is enabled, then the WebKit side will take care
3014   // of setting the fixed layout size and page scale limits.
3015   if (enable_viewport)
3016     return;
3017
3018   // When navigating to a new page, reset the page scale factor to be 1.0.
3019   webview()->setInitialPageScaleOverride(1.f);
3020
3021   float maxPageScaleFactor =
3022       command_line.HasSwitch(switches::kEnablePinch) ? 4.f : 1.f ;
3023   webview()->setPageScaleFactorLimits(1, maxPageScaleFactor);
3024 }
3025
3026 // TODO(nasko): Remove this method once WebTestProxy in Blink is fixed.
3027 void RenderViewImpl::didStartProvisionalLoad(WebFrame* frame) {
3028 }
3029
3030 void RenderViewImpl::didFailProvisionalLoad(WebFrame* frame,
3031                                             const WebURLError& error) {
3032   // Notify the browser that we failed a provisional load with an error.
3033   //
3034   // Note: It is important this notification occur before DidStopLoading so the
3035   //       SSL manager can react to the provisional load failure before being
3036   //       notified the load stopped.
3037   //
3038   FOR_EACH_OBSERVER(
3039       RenderViewObserver, observers_, DidFailProvisionalLoad(frame, error));
3040 }
3041
3042 void RenderViewImpl::didCommitProvisionalLoad(WebFrame* frame,
3043                                               bool is_new_navigation) {
3044   FOR_EACH_OBSERVER(RenderViewObserver, observers_,
3045                     DidCommitProvisionalLoad(frame, is_new_navigation));
3046
3047   // TODO(nasko): Transition this code to RenderFrameImpl, since g_view_map is
3048   // not accessible from there.
3049   if (!frame->parent()) {  // Only for top frames.
3050     RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
3051     if (render_thread_impl) {  // Can be NULL in tests.
3052       render_thread_impl->histogram_customizer()->
3053           RenderViewNavigatedToHost(GURL(GetLoadingUrl(frame)).host(),
3054                                     g_view_map.Get().size());
3055     }
3056   }
3057 }
3058
3059 void RenderViewImpl::didClearWindowObject(WebFrame* frame, int world_id) {
3060   FOR_EACH_OBSERVER(RenderViewObserver, observers_,
3061                     DidClearWindowObject(frame, world_id));
3062
3063   // Only install controllers into the main world.
3064   if (world_id)
3065     return;
3066
3067   if (enabled_bindings_& BINDINGS_POLICY_WEB_UI)
3068     WebUIExtension::Install(frame);
3069
3070   if (enabled_bindings_ & BINDINGS_POLICY_DOM_AUTOMATION)
3071     DomAutomationController::Install(this, frame);
3072
3073   if (enabled_bindings_ & BINDINGS_POLICY_STATS_COLLECTION)
3074     StatsCollectionController::Install(frame);
3075
3076   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
3077
3078   if (command_line.HasSwitch(switches::kEnableSkiaBenchmarking))
3079     SkiaBenchmarking::Install(frame);
3080
3081   if (command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
3082     MemoryBenchmarkingExtension::Install(frame);
3083 }
3084
3085 void RenderViewImpl::didCreateDocumentElement(WebFrame* frame) {
3086   FOR_EACH_OBSERVER(RenderViewObserver, observers_,
3087                     DidCreateDocumentElement(frame));
3088 }
3089
3090 void RenderViewImpl::didReceiveTitle(WebFrame* frame, const WebString& title,
3091                                      WebTextDirection direction) {
3092   UpdateTitle(frame, title, direction);
3093
3094   // Also check whether we have new encoding name.
3095   UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
3096 }
3097
3098 void RenderViewImpl::didChangeIcon(WebFrame* frame,
3099                                    WebIconURL::Type icon_type) {
3100   if (frame->parent())
3101     return;
3102
3103   if (!TouchEnabled() && icon_type != WebIconURL::TypeFavicon)
3104     return;
3105
3106   WebVector<WebIconURL> icon_urls = frame->iconURLs(icon_type);
3107   std::vector<FaviconURL> urls;
3108   for (size_t i = 0; i < icon_urls.size(); i++) {
3109     urls.push_back(FaviconURL(icon_urls[i].iconURL(),
3110                               ToFaviconType(icon_urls[i].iconType())));
3111   }
3112   SendUpdateFaviconURL(urls);
3113 }
3114
3115 void RenderViewImpl::didFinishDocumentLoad(WebFrame* frame) {
3116   FOR_EACH_OBSERVER(RenderViewObserver, observers_,
3117                     DidFinishDocumentLoad(frame));
3118 }
3119
3120 void RenderViewImpl::didHandleOnloadEvents(WebFrame* frame) {
3121   if (webview()->mainFrame() == frame) {
3122     Send(new ViewHostMsg_DocumentOnLoadCompletedInMainFrame(routing_id_,
3123                                                             page_id_));
3124   }
3125 }
3126
3127 void RenderViewImpl::didFailLoad(WebFrame* frame, const WebURLError& error) {
3128   FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidFailLoad(frame, error));
3129 }
3130
3131 void RenderViewImpl::didFinishLoad(WebFrame* frame) {
3132   WebDataSource* ds = frame->dataSource();
3133   DocumentState* document_state = DocumentState::FromDataSource(ds);
3134   if (document_state->finish_load_time().is_null()) {
3135     if (!frame->parent()) {
3136       TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
3137                            TRACE_EVENT_SCOPE_PROCESS);
3138     }
3139     document_state->set_finish_load_time(Time::Now());
3140   }
3141
3142   FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidFinishLoad(frame));
3143
3144   // Don't send this message while the subframe is swapped out.
3145   // TODO(creis): This whole method should move to RenderFrame.
3146   RenderFrameImpl* rf = RenderFrameImpl::FromWebFrame(frame);
3147   if (rf && rf->is_swapped_out())
3148     return;
3149
3150   Send(new ViewHostMsg_DidFinishLoad(routing_id_,
3151                                      frame->identifier(),
3152                                      ds->request().url(),
3153                                      !frame->parent()));
3154 }
3155
3156 void RenderViewImpl::didNavigateWithinPage(
3157     WebFrame* frame,
3158     bool is_new_navigation) {
3159   // TODO(nasko): Forward calls to the main RenderFrameImpl until all
3160   // callers of this method on RenderView are removed.
3161   main_render_frame_->didNavigateWithinPage(frame, is_new_navigation);
3162 }
3163
3164 void RenderViewImpl::didUpdateCurrentHistoryItem(WebFrame* frame) {
3165   StartNavStateSyncTimerIfNecessary();
3166 }
3167
3168 void RenderViewImpl::willSendRequest(WebFrame* frame,
3169                                      unsigned identifier,
3170                                      WebURLRequest& request,
3171                                      const WebURLResponse& redirect_response) {
3172   NOTREACHED();
3173 }
3174
3175 void RenderViewImpl::didReceiveResponse(
3176     WebFrame* frame, unsigned identifier, const WebURLResponse& response) {
3177   NOTREACHED();
3178 }
3179
3180 void RenderViewImpl::didFinishResourceLoad(
3181     WebFrame* frame, unsigned identifier) {
3182   InternalDocumentStateData* internal_data =
3183       InternalDocumentStateData::FromDataSource(frame->dataSource());
3184   if (!internal_data->use_error_page())
3185     return;
3186
3187   // Do not show error page when DevTools is attached.
3188   if (devtools_agent_->IsAttached())
3189     return;
3190
3191   // Display error page, if appropriate.
3192   std::string error_domain = "http";
3193   int http_status_code = internal_data->http_status_code();
3194   if (GetContentClient()->renderer()->HasErrorPage(
3195           http_status_code, &error_domain)) {
3196     WebURLError error;
3197     error.unreachableURL = frame->document().url();
3198     error.domain = WebString::fromUTF8(error_domain);
3199     error.reason = http_status_code;
3200     LoadNavigationErrorPage(frame, frame->dataSource()->request(), error, true);
3201   }
3202 }
3203
3204 void RenderViewImpl::didLoadResourceFromMemoryCache(
3205     WebFrame* frame, const WebURLRequest& request,
3206     const WebURLResponse& response) {
3207   NOTREACHED();
3208 }
3209
3210 void RenderViewImpl::didDisplayInsecureContent(WebFrame* frame) {
3211   NOTREACHED();
3212 }
3213
3214 void RenderViewImpl::didRunInsecureContent(
3215     WebFrame* frame, const WebSecurityOrigin& origin, const WebURL& target) {
3216   NOTREACHED();
3217 }
3218
3219 void RenderViewImpl::didExhaustMemoryAvailableForScript(WebFrame* frame) {
3220   NOTREACHED();
3221 }
3222
3223 void RenderViewImpl::didCreateScriptContext(WebFrame* frame,
3224                                             v8::Handle<v8::Context> context,
3225                                             int extension_group,
3226                                             int world_id) {
3227   NOTREACHED();
3228 }
3229
3230 void RenderViewImpl::willReleaseScriptContext(WebFrame* frame,
3231                                               v8::Handle<v8::Context> context,
3232                                               int world_id) {
3233   NOTREACHED();
3234 }
3235
3236 void RenderViewImpl::CheckPreferredSize() {
3237   // We don't always want to send the change messages over IPC, only if we've
3238   // been put in that mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
3239   // message.
3240   if (!send_preferred_size_changes_ || !webview())
3241     return;
3242
3243   gfx::Size size = webview()->contentsPreferredMinimumSize();
3244
3245   // In the presence of zoom, these sizes are still reported as if unzoomed,
3246   // so we need to adjust.
3247   double zoom_factor = ZoomLevelToZoomFactor(webview()->zoomLevel());
3248   size.set_width(static_cast<int>(size.width() * zoom_factor));
3249   size.set_height(static_cast<int>(size.height() * zoom_factor));
3250
3251   if (size == preferred_size_)
3252     return;
3253
3254   preferred_size_ = size;
3255   Send(new ViewHostMsg_DidContentsPreferredSizeChange(routing_id_,
3256                                                       preferred_size_));
3257 }
3258
3259 BrowserPluginManager* RenderViewImpl::GetBrowserPluginManager() {
3260   if (!browser_plugin_manager_.get())
3261     browser_plugin_manager_ = BrowserPluginManager::Create(this);
3262   return browser_plugin_manager_.get();
3263 }
3264
3265 bool RenderViewImpl::InitializeMediaStreamClient() {
3266   if (media_stream_client_)
3267     return true;
3268
3269   if (!RenderThreadImpl::current())  // Will be NULL during unit tests.
3270     return false;
3271
3272 #if defined(OS_ANDROID)
3273   if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableWebRTC))
3274     return false;
3275 #endif
3276
3277 #if defined(ENABLE_WEBRTC)
3278   if (!media_stream_dispatcher_)
3279     media_stream_dispatcher_ = new MediaStreamDispatcher(this);
3280
3281   MediaStreamImpl* media_stream_impl = new MediaStreamImpl(
3282       this,
3283       media_stream_dispatcher_,
3284       RenderThreadImpl::current()->GetMediaStreamDependencyFactory());
3285   media_stream_client_ = media_stream_impl;
3286   web_user_media_client_ = media_stream_impl;
3287   return true;
3288 #else
3289   return false;
3290 #endif
3291 }
3292
3293 void RenderViewImpl::didChangeContentsSize(WebFrame* frame,
3294                                            const WebSize& size) {
3295   if (webview()->mainFrame() != frame)
3296     return;
3297   WebView* frameView = frame->view();
3298   if (!frameView)
3299     return;
3300
3301   bool has_horizontal_scrollbar = frame->hasHorizontalScrollbar();
3302   bool has_vertical_scrollbar = frame->hasVerticalScrollbar();
3303
3304   if (has_horizontal_scrollbar != cached_has_main_frame_horizontal_scrollbar_ ||
3305       has_vertical_scrollbar != cached_has_main_frame_vertical_scrollbar_) {
3306     Send(new ViewHostMsg_DidChangeScrollbarsForMainFrame(
3307           routing_id_, has_horizontal_scrollbar, has_vertical_scrollbar));
3308
3309     cached_has_main_frame_horizontal_scrollbar_ = has_horizontal_scrollbar;
3310     cached_has_main_frame_vertical_scrollbar_ = has_vertical_scrollbar;
3311   }
3312 }
3313
3314 void RenderViewImpl::UpdateScrollState(WebFrame* frame) {
3315   WebSize offset = frame->scrollOffset();
3316   WebSize minimum_offset = frame->minimumScrollOffset();
3317   WebSize maximum_offset = frame->maximumScrollOffset();
3318
3319   bool is_pinned_to_left = offset.width <= minimum_offset.width;
3320   bool is_pinned_to_right = offset.width >= maximum_offset.width;
3321
3322   if (is_pinned_to_left != cached_is_main_frame_pinned_to_left_ ||
3323       is_pinned_to_right != cached_is_main_frame_pinned_to_right_) {
3324     Send(new ViewHostMsg_DidChangeScrollOffsetPinningForMainFrame(
3325           routing_id_, is_pinned_to_left, is_pinned_to_right));
3326
3327     cached_is_main_frame_pinned_to_left_ = is_pinned_to_left;
3328     cached_is_main_frame_pinned_to_right_ = is_pinned_to_right;
3329   }
3330
3331   Send(new ViewHostMsg_DidChangeScrollOffset(routing_id_));
3332 }
3333
3334 void RenderViewImpl::didChangeScrollOffset(WebFrame* frame) {
3335   StartNavStateSyncTimerIfNecessary();
3336
3337   if (webview()->mainFrame() == frame)
3338     UpdateScrollState(frame);
3339
3340   FOR_EACH_OBSERVER(
3341       RenderViewObserver, observers_, DidChangeScrollOffset(frame));
3342 }
3343
3344 void RenderViewImpl::willInsertBody(blink::WebFrame* frame) {
3345   NOTREACHED();
3346 }
3347
3348 void RenderViewImpl::didFirstVisuallyNonEmptyLayout(WebFrame* frame) {
3349   if (frame != webview()->mainFrame())
3350     return;
3351
3352   InternalDocumentStateData* data =
3353       InternalDocumentStateData::FromDataSource(frame->dataSource());
3354   data->set_did_first_visually_non_empty_layout(true);
3355
3356 #if defined(OS_ANDROID)
3357   // Update body background color if necessary.
3358   SkColor bg_color = webwidget_->backgroundColor();
3359
3360   // If not initialized, default to white. Note that 0 is different from black
3361   // as black still has alpha 0xFF.
3362   if (!bg_color)
3363     bg_color = SK_ColorWHITE;
3364
3365   if (bg_color != body_background_color_) {
3366     body_background_color_ = bg_color;
3367     Send(new ViewHostMsg_DidChangeBodyBackgroundColor(
3368         GetRoutingID(), bg_color));
3369   }
3370 #endif
3371 }
3372
3373 void RenderViewImpl::SendFindReply(int request_id,
3374                                    int match_count,
3375                                    int ordinal,
3376                                    const WebRect& selection_rect,
3377                                    bool final_status_update) {
3378   Send(new ViewHostMsg_Find_Reply(routing_id_,
3379                                   request_id,
3380                                   match_count,
3381                                   selection_rect,
3382                                   ordinal,
3383                                   final_status_update));
3384 }
3385
3386 void RenderViewImpl::reportFindInPageMatchCount(int request_id,
3387                                                 int count,
3388                                                 bool final_update) {
3389   NOTREACHED();
3390 }
3391
3392 void RenderViewImpl::reportFindInPageSelection(int request_id,
3393                                                int active_match_ordinal,
3394                                                const WebRect& selection_rect) {
3395   NOTREACHED();
3396 }
3397
3398 void RenderViewImpl::requestStorageQuota(
3399     WebFrame* frame,
3400     WebStorageQuotaType type,
3401     unsigned long long requested_size,
3402     blink::WebStorageQuotaCallbacks callbacks) {
3403   NOTREACHED();
3404 }
3405
3406 bool RenderViewImpl::willCheckAndDispatchMessageEvent(
3407     blink::WebFrame* sourceFrame,
3408     blink::WebFrame* targetFrame,
3409     blink::WebSecurityOrigin target_origin,
3410     blink::WebDOMMessageEvent event) {
3411   if (!is_swapped_out_)
3412     return false;
3413
3414   ViewMsg_PostMessage_Params params;
3415   params.data = event.data().toString();
3416   params.source_origin = event.origin();
3417   if (!target_origin.isNull())
3418     params.target_origin = target_origin.toString();
3419
3420   blink::WebMessagePortChannelArray channels = event.releaseChannels();
3421   if (!channels.isEmpty()) {
3422     std::vector<int> message_port_ids(channels.size());
3423      // Extract the port IDs from the channel array.
3424      for (size_t i = 0; i < channels.size(); ++i) {
3425        WebMessagePortChannelImpl* webchannel =
3426            static_cast<WebMessagePortChannelImpl*>(channels[i]);
3427        message_port_ids[i] = webchannel->message_port_id();
3428        webchannel->QueueMessages();
3429        DCHECK_NE(message_port_ids[i], MSG_ROUTING_NONE);
3430      }
3431      params.message_port_ids = message_port_ids;
3432   }
3433
3434   // Include the routing ID for the source frame (if one exists), which the
3435   // browser process will translate into the routing ID for the equivalent
3436   // frame in the target process.
3437   params.source_routing_id = MSG_ROUTING_NONE;
3438   if (sourceFrame) {
3439     RenderViewImpl* source_view = FromWebView(sourceFrame->view());
3440     if (source_view)
3441       params.source_routing_id = source_view->routing_id();
3442   }
3443
3444   Send(new ViewHostMsg_RouteMessageEvent(routing_id_, params));
3445   return true;
3446 }
3447
3448 void RenderViewImpl::willOpenSocketStream(
3449     WebSocketStreamHandle* handle) {
3450   NOTREACHED();
3451 }
3452
3453 void RenderViewImpl::willStartUsingPeerConnectionHandler(
3454     blink::WebFrame* frame, blink::WebRTCPeerConnectionHandler* handler) {
3455   NOTREACHED();
3456 }
3457
3458 blink::WebString RenderViewImpl::acceptLanguages() {
3459   return WebString::fromUTF8(renderer_preferences_.accept_languages);
3460 }
3461
3462 blink::WebString RenderViewImpl::userAgentOverride(
3463     blink::WebFrame* frame,
3464     const blink::WebURL& url) {
3465   NOTREACHED();
3466   return blink::WebString();
3467 }
3468
3469 WebString RenderViewImpl::doNotTrackValue(WebFrame* frame) {
3470   NOTREACHED();
3471   return blink::WebString();
3472 }
3473
3474 bool RenderViewImpl::allowWebGL(WebFrame* frame, bool default_value) {
3475   NOTREACHED();
3476   return false;
3477 }
3478
3479 void RenderViewImpl::didLoseWebGLContext(
3480     blink::WebFrame* frame,
3481     int arb_robustness_status_code) {
3482   NOTREACHED();
3483 }
3484
3485 // blink::WebPageSerializerClient implementation ------------------------------
3486
3487 void RenderViewImpl::didSerializeDataForFrame(
3488     const WebURL& frame_url,
3489     const WebCString& data,
3490     WebPageSerializerClient::PageSerializationStatus status) {
3491   Send(new ViewHostMsg_SendSerializedHtmlData(
3492     routing_id(),
3493     frame_url,
3494     data.data(),
3495     static_cast<int32>(status)));
3496 }
3497
3498 // RenderView implementation ---------------------------------------------------
3499
3500 bool RenderViewImpl::Send(IPC::Message* message) {
3501   return RenderWidget::Send(message);
3502 }
3503
3504 RenderFrame* RenderViewImpl::GetMainRenderFrame() {
3505   return main_render_frame_.get();
3506 }
3507
3508 int RenderViewImpl::GetRoutingID() const {
3509   return routing_id_;
3510 }
3511
3512 int RenderViewImpl::GetPageId() const {
3513   return page_id_;
3514 }
3515
3516 gfx::Size RenderViewImpl::GetSize() const {
3517   return size();
3518 }
3519
3520 WebPreferences& RenderViewImpl::GetWebkitPreferences() {
3521   return webkit_preferences_;
3522 }
3523
3524 void RenderViewImpl::SetWebkitPreferences(const WebPreferences& preferences) {
3525   OnUpdateWebPreferences(preferences);
3526 }
3527
3528 blink::WebView* RenderViewImpl::GetWebView() {
3529   return webview();
3530 }
3531
3532 blink::WebNode RenderViewImpl::GetFocusedNode() const {
3533   if (!webview())
3534     return WebNode();
3535   WebFrame* focused_frame = webview()->focusedFrame();
3536   if (focused_frame) {
3537     WebDocument doc = focused_frame->document();
3538     if (!doc.isNull())
3539       return doc.focusedNode();
3540   }
3541
3542   return WebNode();
3543 }
3544
3545 blink::WebNode RenderViewImpl::GetContextMenuNode() const {
3546   return context_menu_node_;
3547 }
3548
3549 bool RenderViewImpl::IsEditableNode(const WebNode& node) const {
3550   if (node.isNull())
3551     return false;
3552
3553   if (node.isContentEditable())
3554     return true;
3555
3556   if (node.isElementNode()) {
3557     const WebElement& element = node.toConst<WebElement>();
3558     if (element.isTextFormControlElement())
3559       return true;
3560
3561     // Also return true if it has an ARIA role of 'textbox'.
3562     for (unsigned i = 0; i < element.attributeCount(); ++i) {
3563       if (LowerCaseEqualsASCII(element.attributeLocalName(i), "role")) {
3564         if (LowerCaseEqualsASCII(element.attributeValue(i), "textbox"))
3565           return true;
3566         break;
3567       }
3568     }
3569   }
3570
3571   return false;
3572 }
3573
3574 void RenderViewImpl::EvaluateScript(const base::string16& frame_xpath,
3575                                     const base::string16& jscript,
3576                                     int id,
3577                                     bool notify_result) {
3578   v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
3579   v8::Handle<v8::Value> result;
3580   WebFrame* web_frame = GetChildFrame(frame_xpath);
3581   if (web_frame)
3582     result = web_frame->executeScriptAndReturnValue(WebScriptSource(jscript));
3583   if (notify_result) {
3584     base::ListValue list;
3585     if (!result.IsEmpty() && web_frame) {
3586       v8::Local<v8::Context> context = web_frame->mainWorldScriptContext();
3587       v8::Context::Scope context_scope(context);
3588       V8ValueConverterImpl converter;
3589       converter.SetDateAllowed(true);
3590       converter.SetRegExpAllowed(true);
3591       base::Value* result_value = converter.FromV8Value(result, context);
3592       list.Set(0, result_value ? result_value : base::Value::CreateNullValue());
3593     } else {
3594       list.Set(0, base::Value::CreateNullValue());
3595     }
3596     Send(new ViewHostMsg_ScriptEvalResponse(routing_id_, id, list));
3597   }
3598 }
3599
3600 bool RenderViewImpl::ShouldDisplayScrollbars(int width, int height) const {
3601   return (!send_preferred_size_changes_ ||
3602           (disable_scrollbars_size_limit_.width() <= width ||
3603            disable_scrollbars_size_limit_.height() <= height));
3604 }
3605
3606 int RenderViewImpl::GetEnabledBindings() const {
3607   return enabled_bindings_;
3608 }
3609
3610 bool RenderViewImpl::GetContentStateImmediately() const {
3611   return send_content_state_immediately_;
3612 }
3613
3614 float RenderViewImpl::GetFilteredTimePerFrame() const {
3615   return filtered_time_per_frame();
3616 }
3617
3618 blink::WebPageVisibilityState RenderViewImpl::GetVisibilityState() const {
3619   return visibilityState();
3620 }
3621
3622 void RenderViewImpl::RunModalAlertDialog(blink::WebFrame* frame,
3623                                          const blink::WebString& message) {
3624   return runModalAlertDialog(frame, message);
3625 }
3626
3627 void RenderViewImpl::DidStartLoading() {
3628   didStartLoading();
3629 }
3630
3631 void RenderViewImpl::DidStopLoading() {
3632   didStopLoading();
3633 }
3634
3635 void RenderViewImpl::DidPlay(blink::WebMediaPlayer* player) {
3636   Send(new ViewHostMsg_MediaPlayingNotification(routing_id_,
3637                                                 reinterpret_cast<int64>(player),
3638                                                 player->hasVideo(),
3639                                                 player->hasAudio()));
3640 }
3641
3642 void RenderViewImpl::DidPause(blink::WebMediaPlayer* player) {
3643   Send(new ViewHostMsg_MediaPausedNotification(
3644       routing_id_, reinterpret_cast<int64>(player)));
3645 }
3646
3647 void RenderViewImpl::PlayerGone(blink::WebMediaPlayer* player) {
3648   DidPause(player);
3649 }
3650
3651 void RenderViewImpl::SyncNavigationState() {
3652   if (!webview())
3653     return;
3654
3655   const WebHistoryItem& item = webview()->mainFrame()->currentHistoryItem();
3656   SendUpdateState(item);
3657 }
3658
3659 void RenderViewImpl::SyncSelectionIfRequired() {
3660   WebFrame* frame = webview()->focusedFrame();
3661   if (!frame)
3662     return;
3663
3664   base::string16 text;
3665   size_t offset;
3666   gfx::Range range;
3667 #if defined(ENABLE_PLUGINS)
3668   if (focused_pepper_plugin_) {
3669     focused_pepper_plugin_->GetSurroundingText(&text, &range);
3670     offset = 0;  // Pepper API does not support offset reporting.
3671     // TODO(kinaba): cut as needed.
3672   } else
3673 #endif
3674   {
3675     size_t location, length;
3676     if (!webview()->caretOrSelectionRange(&location, &length))
3677       return;
3678
3679     range = gfx::Range(location, location + length);
3680
3681     if (webview()->textInputInfo().type != blink::WebTextInputTypeNone) {
3682       // If current focused element is editable, we will send 100 more chars
3683       // before and after selection. It is for input method surrounding text
3684       // feature.
3685       if (location > kExtraCharsBeforeAndAfterSelection)
3686         offset = location - kExtraCharsBeforeAndAfterSelection;
3687       else
3688         offset = 0;
3689       length = location + length - offset + kExtraCharsBeforeAndAfterSelection;
3690       WebRange webrange = WebRange::fromDocumentRange(frame, offset, length);
3691       if (!webrange.isNull())
3692         text = WebRange::fromDocumentRange(frame, offset, length).toPlainText();
3693     } else {
3694       offset = location;
3695       text = frame->selectionAsText();
3696       // http://crbug.com/101435
3697       // In some case, frame->selectionAsText() returned text's length is not
3698       // equal to the length returned from webview()->caretOrSelectionRange().
3699       // So we have to set the range according to text.length().
3700       range.set_end(range.start() + text.length());
3701     }
3702   }
3703
3704   // Sometimes we get repeated didChangeSelection calls from webkit when
3705   // the selection hasn't actually changed. We don't want to report these
3706   // because it will cause us to continually claim the X clipboard.
3707   if (selection_text_offset_ != offset ||
3708       selection_range_ != range ||
3709       selection_text_ != text) {
3710     selection_text_ = text;
3711     selection_text_offset_ = offset;
3712     selection_range_ = range;
3713     Send(new ViewHostMsg_SelectionChanged(routing_id_, text, offset, range));
3714   }
3715   UpdateSelectionBounds();
3716 }
3717
3718 GURL RenderViewImpl::GetLoadingUrl(blink::WebFrame* frame) const {
3719   WebDataSource* ds = frame->dataSource();
3720   if (ds->hasUnreachableURL())
3721     return ds->unreachableURL();
3722
3723   const WebURLRequest& request = ds->request();
3724   return request.url();
3725 }
3726
3727 blink::WebPlugin* RenderViewImpl::GetWebPluginFromPluginDocument() {
3728   return webview()->mainFrame()->document().to<WebPluginDocument>().plugin();
3729 }
3730
3731 void RenderViewImpl::OnFind(int request_id,
3732                             const base::string16& search_text,
3733                             const WebFindOptions& options) {
3734   WebFrame* main_frame = webview()->mainFrame();
3735
3736   // Check if the plugin still exists in the document.
3737   if (main_frame->document().isPluginDocument() &&
3738       GetWebPluginFromPluginDocument()) {
3739     if (options.findNext) {
3740       // Just navigate back/forward.
3741       GetWebPluginFromPluginDocument()->selectFindResult(options.forward);
3742     } else {
3743       if (!GetWebPluginFromPluginDocument()->startFind(
3744           search_text, options.matchCase, request_id)) {
3745         // Send "no results".
3746         SendFindReply(request_id, 0, 0, gfx::Rect(), true);
3747       }
3748     }
3749     return;
3750   }
3751
3752   WebFrame* frame_after_main = main_frame->traverseNext(true);
3753   WebFrame* focused_frame = webview()->focusedFrame();
3754   WebFrame* search_frame = focused_frame;  // start searching focused frame.
3755
3756   bool multi_frame = (frame_after_main != main_frame);
3757
3758   // If we have multiple frames, we don't want to wrap the search within the
3759   // frame, so we check here if we only have main_frame in the chain.
3760   bool wrap_within_frame = !multi_frame;
3761
3762   WebRect selection_rect;
3763   bool result = false;
3764
3765   // If something is selected when we start searching it means we cannot just
3766   // increment the current match ordinal; we need to re-generate it.
3767   WebRange current_selection = focused_frame->selectionRange();
3768
3769   do {
3770     result = search_frame->find(
3771         request_id, search_text, options, wrap_within_frame, &selection_rect);
3772
3773     if (!result) {
3774       // don't leave text selected as you move to the next frame.
3775       search_frame->executeCommand(WebString::fromUTF8("Unselect"),
3776                                    GetFocusedNode());
3777
3778       // Find the next frame, but skip the invisible ones.
3779       do {
3780         // What is the next frame to search? (we might be going backwards). Note
3781         // that we specify wrap=true so that search_frame never becomes NULL.
3782         search_frame = options.forward ?
3783             search_frame->traverseNext(true) :
3784             search_frame->traversePrevious(true);
3785       } while (!search_frame->hasVisibleContent() &&
3786                search_frame != focused_frame);
3787
3788       // Make sure selection doesn't affect the search operation in new frame.
3789       search_frame->executeCommand(WebString::fromUTF8("Unselect"),
3790                                    GetFocusedNode());
3791
3792       // If we have multiple frames and we have wrapped back around to the
3793       // focused frame, we need to search it once more allowing wrap within
3794       // the frame, otherwise it will report 'no match' if the focused frame has
3795       // reported matches, but no frames after the focused_frame contain a
3796       // match for the search word(s).
3797       if (multi_frame && search_frame == focused_frame) {
3798         result = search_frame->find(
3799             request_id, search_text, options, true,  // Force wrapping.
3800             &selection_rect);
3801       }
3802     }
3803
3804     webview()->setFocusedFrame(search_frame);
3805   } while (!result && search_frame != focused_frame);
3806
3807   if (options.findNext && current_selection.isNull()) {
3808     // Force the main_frame to report the actual count.
3809     main_frame->increaseMatchCount(0, request_id);
3810   } else {
3811     // If nothing is found, set result to "0 of 0", otherwise, set it to
3812     // "-1 of 1" to indicate that we found at least one item, but we don't know
3813     // yet what is active.
3814     int ordinal = result ? -1 : 0;  // -1 here means, we might know more later.
3815     int match_count = result ? 1 : 0;  // 1 here means possibly more coming.
3816
3817     // If we find no matches then this will be our last status update.
3818     // Otherwise the scoping effort will send more results.
3819     bool final_status_update = !result;
3820
3821     SendFindReply(request_id, match_count, ordinal, selection_rect,
3822                   final_status_update);
3823
3824     // Scoping effort begins, starting with the mainframe.
3825     search_frame = main_frame;
3826
3827     main_frame->resetMatchCount();
3828
3829     do {
3830       // Cancel all old scoping requests before starting a new one.
3831       search_frame->cancelPendingScopingEffort();
3832
3833       // We don't start another scoping effort unless at least one match has
3834       // been found.
3835       if (result) {
3836         // Start new scoping request. If the scoping function determines that it
3837         // needs to scope, it will defer until later.
3838         search_frame->scopeStringMatches(request_id,
3839                                          search_text,
3840                                          options,
3841                                          true);  // reset the tickmarks
3842       }
3843
3844       // Iterate to the next frame. The frame will not necessarily scope, for
3845       // example if it is not visible.
3846       search_frame = search_frame->traverseNext(true);
3847     } while (search_frame != main_frame);
3848   }
3849 }
3850
3851 void RenderViewImpl::OnStopFinding(StopFindAction action) {
3852   WebView* view = webview();
3853   if (!view)
3854     return;
3855
3856   WebDocument doc = view->mainFrame()->document();
3857   if (doc.isPluginDocument() && GetWebPluginFromPluginDocument()) {
3858     GetWebPluginFromPluginDocument()->stopFind();
3859     return;
3860   }
3861
3862   bool clear_selection = action == STOP_FIND_ACTION_CLEAR_SELECTION;
3863   if (clear_selection) {
3864     view->focusedFrame()->executeCommand(WebString::fromUTF8("Unselect"),
3865                                          GetFocusedNode());
3866   }
3867
3868   WebFrame* frame = view->mainFrame();
3869   while (frame) {
3870     frame->stopFinding(clear_selection);
3871     frame = frame->traverseNext(false);
3872   }
3873
3874   if (action == STOP_FIND_ACTION_ACTIVATE_SELECTION) {
3875     WebFrame* focused_frame = view->focusedFrame();
3876     if (focused_frame) {
3877       WebDocument doc = focused_frame->document();
3878       if (!doc.isNull()) {
3879         WebNode node = doc.focusedNode();
3880         if (!node.isNull())
3881           node.simulateClick();
3882       }
3883     }
3884   }
3885 }
3886
3887 #if defined(OS_ANDROID)
3888 void RenderViewImpl::OnActivateNearestFindResult(int request_id,
3889                                                  float x, float y) {
3890   if (!webview())
3891       return;
3892
3893   WebFrame* main_frame = webview()->mainFrame();
3894   WebRect selection_rect;
3895   int ordinal = main_frame->selectNearestFindMatch(WebFloatPoint(x, y),
3896                                                    &selection_rect);
3897   if (ordinal == -1) {
3898     // Something went wrong, so send a no-op reply (force the main_frame to
3899     // report the current match count) in case the host is waiting for a
3900     // response due to rate-limiting).
3901     main_frame->increaseMatchCount(0, request_id);
3902     return;
3903   }
3904
3905   SendFindReply(request_id,
3906                 -1 /* number_of_matches */,
3907                 ordinal,
3908                 selection_rect,
3909                 true /* final_update */);
3910 }
3911
3912 void RenderViewImpl::OnFindMatchRects(int current_version) {
3913   if (!webview())
3914       return;
3915
3916   WebFrame* main_frame = webview()->mainFrame();
3917   std::vector<gfx::RectF> match_rects;
3918
3919   int rects_version = main_frame->findMatchMarkersVersion();
3920   if (current_version != rects_version) {
3921     WebVector<WebFloatRect> web_match_rects;
3922     main_frame->findMatchRects(web_match_rects);
3923     match_rects.reserve(web_match_rects.size());
3924     for (size_t i = 0; i < web_match_rects.size(); ++i)
3925       match_rects.push_back(gfx::RectF(web_match_rects[i]));
3926   }
3927
3928   gfx::RectF active_rect = main_frame->activeFindMatchRect();
3929   Send(new ViewHostMsg_FindMatchRects_Reply(routing_id_,
3930                                                rects_version,
3931                                                match_rects,
3932                                                active_rect));
3933 }
3934 #endif
3935
3936 void RenderViewImpl::OnZoom(PageZoom zoom) {
3937   if (!webview())  // Not sure if this can happen, but no harm in being safe.
3938     return;
3939
3940   webview()->hidePopups();
3941
3942   double old_zoom_level = webview()->zoomLevel();
3943   double zoom_level;
3944   if (zoom == PAGE_ZOOM_RESET) {
3945     zoom_level = 0;
3946   } else if (static_cast<int>(old_zoom_level) == old_zoom_level) {
3947     // Previous zoom level is a whole number, so just increment/decrement.
3948     zoom_level = old_zoom_level + zoom;
3949   } else {
3950     // Either the user hit the zoom factor limit and thus the zoom level is now
3951     // not a whole number, or a plugin changed it to a custom value.  We want
3952     // to go to the next whole number so that the user can always get back to
3953     // 100% with the keyboard/menu.
3954     if ((old_zoom_level > 1 && zoom > 0) ||
3955         (old_zoom_level < 1 && zoom < 0)) {
3956       zoom_level = static_cast<int>(old_zoom_level + zoom);
3957     } else {
3958       // We're going towards 100%, so first go to the next whole number.
3959       zoom_level = static_cast<int>(old_zoom_level);
3960     }
3961   }
3962   webview()->setZoomLevel(zoom_level);
3963   zoomLevelChanged();
3964 }
3965
3966 void RenderViewImpl::OnZoomFactor(PageZoom zoom, int zoom_center_x,
3967                                   int zoom_center_y) {
3968   ZoomFactorHelper(zoom, zoom_center_x, zoom_center_y,
3969                    kScalingIncrementForGesture);
3970 }
3971
3972 void RenderViewImpl::ZoomFactorHelper(PageZoom zoom,
3973                                       int zoom_center_x,
3974                                       int zoom_center_y,
3975                                       float scaling_increment) {
3976   if (!webview())  // Not sure if this can happen, but no harm in being safe.
3977     return;
3978
3979   double old_page_scale_factor = webview()->pageScaleFactor();
3980   double page_scale_factor;
3981   if (zoom == PAGE_ZOOM_RESET) {
3982     page_scale_factor = 1.0;
3983   } else {
3984     page_scale_factor = old_page_scale_factor +
3985         (zoom > 0 ? scaling_increment : -scaling_increment);
3986   }
3987   if (page_scale_factor > 0) {
3988     webview()->setPageScaleFactor(page_scale_factor,
3989                                   WebPoint(zoom_center_x, zoom_center_y));
3990   }
3991 }
3992
3993 void RenderViewImpl::OnSetZoomLevel(double zoom_level) {
3994   webview()->hidePopups();
3995   webview()->setZoomLevel(zoom_level);
3996   zoomLevelChanged();
3997 }
3998
3999 void RenderViewImpl::OnSetZoomLevelForLoadingURL(const GURL& url,
4000                                                  double zoom_level) {
4001 #if !defined(OS_ANDROID)
4002   // On Android, page zoom isn't used, and in case of WebView, text zoom is used
4003   // for legacy WebView text scaling emulation. Thus, the code that resets
4004   // the zoom level from this map will be effectively resetting text zoom level.
4005   host_zoom_levels_[url] = zoom_level;
4006 #endif
4007 }
4008
4009 void RenderViewImpl::OnSetPageEncoding(const std::string& encoding_name) {
4010   webview()->setPageEncoding(WebString::fromUTF8(encoding_name));
4011 }
4012
4013 void RenderViewImpl::OnResetPageEncodingToDefault() {
4014   WebString no_encoding;
4015   webview()->setPageEncoding(no_encoding);
4016 }
4017
4018 WebFrame* RenderViewImpl::GetChildFrame(const base::string16& xpath) const {
4019   if (xpath.empty())
4020     return webview()->mainFrame();
4021
4022   // xpath string can represent a frame deep down the tree (across multiple
4023   // frame DOMs).
4024   // Example, /html/body/table/tbody/tr/td/iframe\n/frameset/frame[0]
4025   // should break into 2 xpaths
4026   // /html/body/table/tbody/tr/td/iframe & /frameset/frame[0]
4027   std::vector<base::string16> xpaths;
4028   base::SplitString(xpath, '\n', &xpaths);
4029
4030   WebFrame* frame = webview()->mainFrame();
4031   for (std::vector<base::string16>::const_iterator i = xpaths.begin();
4032        frame && i != xpaths.end(); ++i) {
4033     frame = frame->findChildByExpression(*i);
4034   }
4035
4036   return frame;
4037 }
4038
4039 void RenderViewImpl::OnScriptEvalRequest(const base::string16& frame_xpath,
4040                                          const base::string16& jscript,
4041                                          int id,
4042                                          bool notify_result) {
4043   TRACE_EVENT_INSTANT0("test_tracing", "OnScriptEvalRequest",
4044                        TRACE_EVENT_SCOPE_THREAD);
4045   EvaluateScript(frame_xpath, jscript, id, notify_result);
4046 }
4047
4048 void RenderViewImpl::OnPostMessageEvent(
4049     const ViewMsg_PostMessage_Params& params) {
4050   // TODO(nasko): Support sending to subframes.
4051   WebFrame* frame = webview()->mainFrame();
4052
4053   // Find the source frame if it exists.
4054   WebFrame* source_frame = NULL;
4055   if (params.source_routing_id != MSG_ROUTING_NONE) {
4056     RenderViewImpl* source_view = FromRoutingID(params.source_routing_id);
4057     if (source_view)
4058       source_frame = source_view->webview()->mainFrame();
4059   }
4060
4061   // If the message contained MessagePorts, create the corresponding endpoints.
4062   DCHECK_EQ(params.message_port_ids.size(), params.new_routing_ids.size());
4063   blink::WebMessagePortChannelArray channels(params.message_port_ids.size());
4064   for (size_t i = 0;
4065        i < params.message_port_ids.size() && i < params.new_routing_ids.size();
4066        ++i) {
4067     channels[i] =
4068         new WebMessagePortChannelImpl(params.new_routing_ids[i],
4069                                       params.message_port_ids[i],
4070                                       base::MessageLoopProxy::current().get());
4071   }
4072
4073   // Create an event with the message.  The final parameter to initMessageEvent
4074   // is the last event ID, which is not used with postMessage.
4075   WebDOMEvent event = frame->document().createEvent("MessageEvent");
4076   WebDOMMessageEvent msg_event = event.to<WebDOMMessageEvent>();
4077   msg_event.initMessageEvent("message",
4078                              // |canBubble| and |cancellable| are always false
4079                              false, false,
4080                              WebSerializedScriptValue::fromString(params.data),
4081                              params.source_origin, source_frame, "", channels);
4082
4083   // We must pass in the target_origin to do the security check on this side,
4084   // since it may have changed since the original postMessage call was made.
4085   WebSecurityOrigin target_origin;
4086   if (!params.target_origin.empty()) {
4087     target_origin =
4088         WebSecurityOrigin::createFromString(WebString(params.target_origin));
4089   }
4090   frame->dispatchMessageEventWithOriginCheck(target_origin, msg_event);
4091 }
4092
4093 void RenderViewImpl::OnCSSInsertRequest(const base::string16& frame_xpath,
4094                                         const std::string& css) {
4095   WebFrame* frame = GetChildFrame(frame_xpath);
4096   if (!frame)
4097     return;
4098
4099   frame->document().insertStyleSheet(WebString::fromUTF8(css));
4100 }
4101
4102 void RenderViewImpl::OnAllowBindings(int enabled_bindings_flags) {
4103   if ((enabled_bindings_flags & BINDINGS_POLICY_WEB_UI) &&
4104       !(enabled_bindings_ & BINDINGS_POLICY_WEB_UI)) {
4105     new WebUIExtensionData(this);
4106   }
4107
4108   enabled_bindings_ |= enabled_bindings_flags;
4109
4110   // Keep track of the total bindings accumulated in this process.
4111   RenderProcess::current()->AddBindings(enabled_bindings_flags);
4112 }
4113
4114 void RenderViewImpl::OnDragTargetDragEnter(const DropData& drop_data,
4115                                            const gfx::Point& client_point,
4116                                            const gfx::Point& screen_point,
4117                                            WebDragOperationsMask ops,
4118                                            int key_modifiers) {
4119   WebDragOperation operation = webview()->dragTargetDragEnter(
4120       DropDataToWebDragData(drop_data),
4121       client_point,
4122       screen_point,
4123       ops,
4124       key_modifiers);
4125
4126   Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
4127 }
4128
4129 void RenderViewImpl::OnDragTargetDragOver(const gfx::Point& client_point,
4130                                           const gfx::Point& screen_point,
4131                                           WebDragOperationsMask ops,
4132                                           int key_modifiers) {
4133   WebDragOperation operation = webview()->dragTargetDragOver(
4134       client_point,
4135       screen_point,
4136       ops,
4137       key_modifiers);
4138
4139   Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
4140 }
4141
4142 void RenderViewImpl::OnDragTargetDragLeave() {
4143   webview()->dragTargetDragLeave();
4144 }
4145
4146 void RenderViewImpl::OnDragTargetDrop(const gfx::Point& client_point,
4147                                       const gfx::Point& screen_point,
4148                                       int key_modifiers) {
4149   webview()->dragTargetDrop(client_point, screen_point, key_modifiers);
4150
4151   Send(new DragHostMsg_TargetDrop_ACK(routing_id_));
4152 }
4153
4154 void RenderViewImpl::OnDragSourceEndedOrMoved(const gfx::Point& client_point,
4155                                               const gfx::Point& screen_point,
4156                                               bool ended,
4157                                               WebDragOperation op) {
4158   if (ended) {
4159     webview()->dragSourceEndedAt(client_point, screen_point, op);
4160   } else {
4161     webview()->dragSourceMovedTo(client_point, screen_point, op);
4162   }
4163 }
4164
4165 void RenderViewImpl::OnDragSourceSystemDragEnded() {
4166   webview()->dragSourceSystemDragEnded();
4167 }
4168
4169 void RenderViewImpl::OnUpdateWebPreferences(const WebPreferences& prefs) {
4170   webkit_preferences_ = prefs;
4171   ApplyWebPreferences(webkit_preferences_, webview());
4172 }
4173
4174 void RenderViewImpl::OnUpdateTimezone() {
4175   if (webview())
4176     NotifyTimezoneChange(webview()->mainFrame());
4177 }
4178
4179 void RenderViewImpl::OnEnumerateDirectoryResponse(
4180     int id,
4181     const std::vector<base::FilePath>& paths) {
4182   if (!enumeration_completions_[id])
4183     return;
4184
4185   WebVector<WebString> ws_file_names(paths.size());
4186   for (size_t i = 0; i < paths.size(); ++i)
4187     ws_file_names[i] = paths[i].AsUTF16Unsafe();
4188
4189   enumeration_completions_[id]->didChooseFile(ws_file_names);
4190   enumeration_completions_.erase(id);
4191 }
4192
4193 void RenderViewImpl::OnFileChooserResponse(
4194     const std::vector<ui::SelectedFileInfo>& files) {
4195   // This could happen if we navigated to a different page before the user
4196   // closed the chooser.
4197   if (file_chooser_completions_.empty())
4198     return;
4199
4200   // Convert Chrome's SelectedFileInfo list to WebKit's.
4201   WebVector<WebFileChooserCompletion::SelectedFileInfo> selected_files(
4202       files.size());
4203   for (size_t i = 0; i < files.size(); ++i) {
4204     WebFileChooserCompletion::SelectedFileInfo selected_file;
4205     selected_file.path = files[i].local_path.AsUTF16Unsafe();
4206     selected_file.displayName =
4207         base::FilePath(files[i].display_name).AsUTF16Unsafe();
4208     selected_files[i] = selected_file;
4209   }
4210
4211   if (file_chooser_completions_.front()->completion)
4212     file_chooser_completions_.front()->completion->didChooseFile(
4213         selected_files);
4214   file_chooser_completions_.pop_front();
4215
4216   // If there are more pending file chooser requests, schedule one now.
4217   if (!file_chooser_completions_.empty()) {
4218     Send(new ViewHostMsg_RunFileChooser(routing_id_,
4219         file_chooser_completions_.front()->params));
4220   }
4221 }
4222
4223 void RenderViewImpl::OnEnableAutoResize(const gfx::Size& min_size,
4224                                         const gfx::Size& max_size) {
4225   DCHECK(disable_scrollbars_size_limit_.IsEmpty());
4226   if (!webview())
4227     return;
4228   auto_resize_mode_ = true;
4229   webview()->enableAutoResizeMode(min_size, max_size);
4230 }
4231
4232 void RenderViewImpl::OnDisableAutoResize(const gfx::Size& new_size) {
4233   DCHECK(disable_scrollbars_size_limit_.IsEmpty());
4234   if (!webview())
4235     return;
4236   auto_resize_mode_ = false;
4237   webview()->disableAutoResizeMode();
4238
4239   if (!new_size.IsEmpty()) {
4240     Resize(new_size,
4241            physical_backing_size_,
4242            overdraw_bottom_height_,
4243            resizer_rect_,
4244            is_fullscreen_,
4245            NO_RESIZE_ACK);
4246   }
4247 }
4248
4249 void RenderViewImpl::OnEnablePreferredSizeChangedMode() {
4250   if (send_preferred_size_changes_)
4251     return;
4252   send_preferred_size_changes_ = true;
4253
4254   // Start off with an initial preferred size notification (in case
4255   // |didUpdateLayout| was already called).
4256   didUpdateLayout();
4257 }
4258
4259 void RenderViewImpl::OnDisableScrollbarsForSmallWindows(
4260     const gfx::Size& disable_scrollbar_size_limit) {
4261   disable_scrollbars_size_limit_ = disable_scrollbar_size_limit;
4262 }
4263
4264 void RenderViewImpl::OnSetRendererPrefs(
4265     const RendererPreferences& renderer_prefs) {
4266   double old_zoom_level = renderer_preferences_.default_zoom_level;
4267   renderer_preferences_ = renderer_prefs;
4268   UpdateFontRenderingFromRendererPrefs();
4269
4270 #if defined(USE_DEFAULT_RENDER_THEME) || defined(TOOLKIT_GTK)
4271   if (renderer_prefs.use_custom_colors) {
4272     WebColorName name = blink::WebColorWebkitFocusRingColor;
4273     blink::setNamedColors(&name, &renderer_prefs.focus_ring_color, 1);
4274     blink::setCaretBlinkInterval(renderer_prefs.caret_blink_interval);
4275 #if defined(TOOLKIT_GTK)
4276     ui::NativeTheme::instance()->SetScrollbarColors(
4277         renderer_prefs.thumb_inactive_color,
4278         renderer_prefs.thumb_active_color,
4279         renderer_prefs.track_color);
4280 #endif  // defined(TOOLKIT_GTK)
4281
4282     if (webview()) {
4283       webview()->setSelectionColors(
4284           renderer_prefs.active_selection_bg_color,
4285           renderer_prefs.active_selection_fg_color,
4286           renderer_prefs.inactive_selection_bg_color,
4287           renderer_prefs.inactive_selection_fg_color);
4288       webview()->themeChanged();
4289     }
4290   }
4291 #endif  // defined(USE_DEFAULT_RENDER_THEME) || defined(TOOLKIT_GTK)
4292
4293   if (RenderThreadImpl::current())  // Will be NULL during unit tests.
4294     RenderThreadImpl::current()->SetFlingCurveParameters(
4295         renderer_prefs.touchpad_fling_profile,
4296         renderer_prefs.touchscreen_fling_profile);
4297
4298   // If the zoom level for this page matches the old zoom default, and this
4299   // is not a plugin, update the zoom level to match the new default.
4300   if (webview() && !webview()->mainFrame()->document().isPluginDocument() &&
4301       !ZoomValuesEqual(old_zoom_level,
4302                        renderer_preferences_.default_zoom_level) &&
4303       ZoomValuesEqual(webview()->zoomLevel(), old_zoom_level)) {
4304     webview()->setZoomLevel(renderer_preferences_.default_zoom_level);
4305     zoomLevelChanged();
4306   }
4307 }
4308
4309 void RenderViewImpl::OnMediaPlayerActionAt(const gfx::Point& location,
4310                                            const WebMediaPlayerAction& action) {
4311   if (webview())
4312     webview()->performMediaPlayerAction(action, location);
4313 }
4314
4315 void RenderViewImpl::OnOrientationChangeEvent(int orientation) {
4316   // Screen has rotated. 0 = default (portrait), 90 = one turn right, and so on.
4317   FOR_EACH_OBSERVER(RenderViewObserver,
4318                     observers_,
4319                     OrientationChangeEvent(orientation));
4320   webview()->mainFrame()->sendOrientationChangeEvent(orientation);
4321 }
4322
4323 void RenderViewImpl::OnPluginActionAt(const gfx::Point& location,
4324                                       const WebPluginAction& action) {
4325   if (webview())
4326     webview()->performPluginAction(action, location);
4327 }
4328
4329 void RenderViewImpl::OnGetAllSavableResourceLinksForCurrentPage(
4330     const GURL& page_url) {
4331   // Prepare list to storage all savable resource links.
4332   std::vector<GURL> resources_list;
4333   std::vector<GURL> referrer_urls_list;
4334   std::vector<blink::WebReferrerPolicy> referrer_policies_list;
4335   std::vector<GURL> frames_list;
4336   SavableResourcesResult result(&resources_list,
4337                                 &referrer_urls_list,
4338                                 &referrer_policies_list,
4339                                 &frames_list);
4340
4341   // webkit/ doesn't know about Referrer.
4342   if (!GetAllSavableResourceLinksForCurrentPage(
4343           webview(),
4344           page_url,
4345           &result,
4346           const_cast<const char**>(GetSavableSchemes()))) {
4347     // If something is wrong when collecting all savable resource links,
4348     // send empty list to embedder(browser) to tell it failed.
4349     referrer_urls_list.clear();
4350     referrer_policies_list.clear();
4351     resources_list.clear();
4352     frames_list.clear();
4353   }
4354
4355   std::vector<Referrer> referrers_list;
4356   CHECK_EQ(referrer_urls_list.size(), referrer_policies_list.size());
4357   for (unsigned i = 0; i < referrer_urls_list.size(); ++i) {
4358     referrers_list.push_back(
4359         Referrer(referrer_urls_list[i], referrer_policies_list[i]));
4360   }
4361
4362   // Send result of all savable resource links to embedder.
4363   Send(new ViewHostMsg_SendCurrentPageAllSavableResourceLinks(routing_id(),
4364                                                               resources_list,
4365                                                               referrers_list,
4366                                                               frames_list));
4367 }
4368
4369 void RenderViewImpl::OnGetSerializedHtmlDataForCurrentPageWithLocalLinks(
4370     const std::vector<GURL>& links,
4371     const std::vector<base::FilePath>& local_paths,
4372     const base::FilePath& local_directory_name) {
4373
4374   // Convert std::vector of GURLs to WebVector<WebURL>
4375   WebVector<WebURL> weburl_links(links);
4376
4377   // Convert std::vector of base::FilePath to WebVector<WebString>
4378   WebVector<WebString> webstring_paths(local_paths.size());
4379   for (size_t i = 0; i < local_paths.size(); i++)
4380     webstring_paths[i] = local_paths[i].AsUTF16Unsafe();
4381
4382   WebPageSerializer::serialize(webview()->mainFrame(), true, this, weburl_links,
4383                                webstring_paths,
4384                                local_directory_name.AsUTF16Unsafe());
4385 }
4386
4387 void RenderViewImpl::OnShouldClose() {
4388   base::TimeTicks before_unload_start_time = base::TimeTicks::Now();
4389   bool should_close = webview()->dispatchBeforeUnloadEvent();
4390   base::TimeTicks before_unload_end_time = base::TimeTicks::Now();
4391   Send(new ViewHostMsg_ShouldClose_ACK(routing_id_, should_close,
4392                                        before_unload_start_time,
4393                                        before_unload_end_time));
4394 }
4395
4396 void RenderViewImpl::OnSuppressDialogsUntilSwapOut() {
4397   // Don't show any more dialogs until we finish OnSwapOut.
4398   suppress_dialogs_until_swap_out_ = true;
4399 }
4400
4401 void RenderViewImpl::OnSwapOut() {
4402   // Only run unload if we're not swapped out yet, but send the ack either way.
4403   if (!is_swapped_out_) {
4404     // Swap this RenderView out so the tab can navigate to a page rendered by a
4405     // different process.  This involves running the unload handler and clearing
4406     // the page.  Once WasSwappedOut is called, we also allow this process to
4407     // exit if there are no other active RenderViews in it.
4408
4409     // Send an UpdateState message before we get swapped out.
4410     SyncNavigationState();
4411
4412     // Synchronously run the unload handler before sending the ACK.
4413     webview()->dispatchUnloadEvent();
4414
4415     // Swap out and stop sending any IPC messages that are not ACKs.
4416     SetSwappedOut(true);
4417
4418     // Now that we're swapped out and filtering IPC messages, stop loading to
4419     // ensure that no other in-progress navigation continues.  We do this here
4420     // to avoid sending a DidStopLoading message to the browser process.
4421     OnStop();
4422
4423     // Replace the page with a blank dummy URL. The unload handler will not be
4424     // run a second time, thanks to a check in FrameLoader::stopLoading.
4425     // TODO(creis): Need to add a better way to do this that avoids running the
4426     // beforeunload handler. For now, we just run it a second time silently.
4427     NavigateToSwappedOutURL(webview()->mainFrame());
4428
4429     // Let WebKit know that this view is hidden so it can drop resources and
4430     // stop compositing.
4431     webview()->setVisibilityState(blink::WebPageVisibilityStateHidden, false);
4432   }
4433
4434   // It is now safe to show modal dialogs again.
4435   suppress_dialogs_until_swap_out_ = false;
4436
4437   Send(new ViewHostMsg_SwapOut_ACK(routing_id_));
4438 }
4439
4440 void RenderViewImpl::NavigateToSwappedOutURL(blink::WebFrame* frame) {
4441   // We use loadRequest instead of loadHTMLString because the former commits
4442   // synchronously.  Otherwise a new navigation can interrupt the navigation
4443   // to kSwappedOutURL. If that happens to be to the page we had been
4444   // showing, then WebKit will never send a commit and we'll be left spinning.
4445   // TODO(creis): Until we move this to RenderFrame, we may call this from a
4446   // swapped out RenderFrame while our own is_swapped_out_ is false.
4447   RenderFrameImpl* rf = RenderFrameImpl::FromWebFrame(frame);
4448   CHECK(is_swapped_out_ || rf->is_swapped_out());
4449   GURL swappedOutURL(kSwappedOutURL);
4450   WebURLRequest request(swappedOutURL);
4451   frame->loadRequest(request);
4452 }
4453
4454 void RenderViewImpl::OnClosePage() {
4455   FOR_EACH_OBSERVER(RenderViewObserver, observers_, ClosePage());
4456   // TODO(creis): We'd rather use webview()->Close() here, but that currently
4457   // sets the WebView's delegate_ to NULL, preventing any JavaScript dialogs
4458   // in the onunload handler from appearing.  For now, we're bypassing that and
4459   // calling the FrameLoader's CloseURL method directly.  This should be
4460   // revisited to avoid having two ways to close a page.  Having a single way
4461   // to close that can run onunload is also useful for fixing
4462   // http://b/issue?id=753080.
4463   webview()->dispatchUnloadEvent();
4464
4465   Send(new ViewHostMsg_ClosePage_ACK(routing_id_));
4466 }
4467
4468 void RenderViewImpl::OnThemeChanged() {
4469 #if defined(USE_AURA)
4470   // Aura doesn't care if we switch themes.
4471 #elif defined(OS_WIN)
4472   ui::NativeThemeWin::instance()->CloseHandles();
4473   if (webview())
4474     webview()->themeChanged();
4475 #else  // defined(OS_WIN)
4476   // TODO(port): we don't support theming on non-Windows platforms yet
4477   NOTIMPLEMENTED();
4478 #endif
4479 }
4480
4481 void RenderViewImpl::OnMoveOrResizeStarted() {
4482   if (webview())
4483     webview()->hidePopups();
4484 }
4485
4486 void RenderViewImpl::OnResize(const ViewMsg_Resize_Params& params) {
4487   if (webview()) {
4488     webview()->hidePopups();
4489     if (send_preferred_size_changes_) {
4490       webview()->mainFrame()->setCanHaveScrollbars(
4491           ShouldDisplayScrollbars(params.new_size.width(),
4492                                   params.new_size.height()));
4493     }
4494     UpdateScrollState(webview()->mainFrame());
4495   }
4496
4497   RenderWidget::OnResize(params);
4498 }
4499
4500 void RenderViewImpl::DidInitiatePaint() {
4501 #if defined(ENABLE_PLUGINS)
4502   // Notify all instances that we painted.  The same caveats apply as for
4503   // ViewFlushedPaint regarding instances closing themselves, so we take
4504   // similar precautions.
4505   PepperPluginSet plugins = active_pepper_instances_;
4506   for (PepperPluginSet::iterator i = plugins.begin(); i != plugins.end(); ++i) {
4507     if (active_pepper_instances_.find(*i) != active_pepper_instances_.end())
4508       (*i)->ViewInitiatedPaint();
4509   }
4510 #endif
4511 }
4512
4513 void RenderViewImpl::DidFlushPaint() {
4514 #if defined(ENABLE_PLUGINS)
4515   // Notify all instances that we flushed. This will call into the plugin, and
4516   // we it may ask to close itself as a result. This will, in turn, modify our
4517   // set, possibly invalidating the iterator. So we iterate on a copy that
4518   // won't change out from under us.
4519   PepperPluginSet plugins = active_pepper_instances_;
4520   for (PepperPluginSet::iterator i = plugins.begin(); i != plugins.end(); ++i) {
4521     // The copy above makes sure our iterator is never invalid if some plugins
4522     // are destroyed. But some plugin may decide to close all of its views in
4523     // response to a paint in one of them, so we need to make sure each one is
4524     // still "current" before using it.
4525     //
4526     // It's possible that a plugin was destroyed, but another one was created
4527     // with the same address. In this case, we'll call ViewFlushedPaint on that
4528     // new plugin. But that's OK for this particular case since we're just
4529     // notifying all of our instances that the view flushed, and the new one is
4530     // one of our instances.
4531     //
4532     // What about the case where a new one is created in a callback at a new
4533     // address and we don't issue the callback? We're still OK since this
4534     // callback is used for flush callbacks and we could not have possibly
4535     // started a new paint for the new plugin while processing a previous paint
4536     // for an existing one.
4537     if (active_pepper_instances_.find(*i) != active_pepper_instances_.end())
4538       (*i)->ViewFlushedPaint();
4539   }
4540 #endif
4541
4542   // If the RenderWidget is closing down then early-exit, otherwise we'll crash.
4543   // See crbug.com/112921.
4544   if (!webview())
4545     return;
4546
4547   WebFrame* main_frame = webview()->mainFrame();
4548
4549   // If we have a provisional frame we are between the start and commit stages
4550   // of loading and we don't want to save stats.
4551   if (!main_frame->provisionalDataSource()) {
4552     WebDataSource* ds = main_frame->dataSource();
4553     DocumentState* document_state = DocumentState::FromDataSource(ds);
4554     InternalDocumentStateData* data =
4555         InternalDocumentStateData::FromDocumentState(document_state);
4556     if (data->did_first_visually_non_empty_layout() &&
4557         !data->did_first_visually_non_empty_paint()) {
4558       data->set_did_first_visually_non_empty_paint(true);
4559       Send(new ViewHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_,
4560                                                          page_id_));
4561     }
4562
4563     // TODO(jar): The following code should all be inside a method, probably in
4564     // NavigatorState.
4565     Time now = Time::Now();
4566     if (document_state->first_paint_time().is_null()) {
4567       document_state->set_first_paint_time(now);
4568     }
4569     if (document_state->first_paint_after_load_time().is_null() &&
4570         !document_state->finish_load_time().is_null()) {
4571       document_state->set_first_paint_after_load_time(now);
4572     }
4573   }
4574 }
4575
4576 PepperPluginInstanceImpl* RenderViewImpl::GetBitmapForOptimizedPluginPaint(
4577     const gfx::Rect& paint_bounds,
4578     TransportDIB** dib,
4579     gfx::Rect* location,
4580     gfx::Rect* clip,
4581     float* scale_factor) {
4582 #if defined(ENABLE_PLUGINS)
4583   for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
4584        i != active_pepper_instances_.end(); ++i) {
4585     PepperPluginInstanceImpl* instance = *i;
4586     // In Flash fullscreen , the plugin contents should be painted onto the
4587     // fullscreen widget instead of the web page.
4588     if (!instance->FlashIsFullscreenOrPending() &&
4589         instance->GetBitmapForOptimizedPluginPaint(paint_bounds, dib, location,
4590                                                    clip, scale_factor))
4591       return *i;
4592   }
4593 #endif
4594   return NULL;
4595 }
4596
4597 gfx::Vector2d RenderViewImpl::GetScrollOffset() {
4598   WebSize scroll_offset = webview()->mainFrame()->scrollOffset();
4599   return gfx::Vector2d(scroll_offset.width, scroll_offset.height);
4600 }
4601
4602 void RenderViewImpl::OnClearFocusedNode() {
4603   if (webview())
4604     webview()->clearFocusedNode();
4605 }
4606
4607 void RenderViewImpl::OnSetBackground(const SkBitmap& background) {
4608   if (webview())
4609     webview()->setIsTransparent(!background.empty());
4610   if (compositor_)
4611     compositor_->setHasTransparentBackground(!background.empty());
4612
4613   SetBackground(background);
4614 }
4615
4616 void RenderViewImpl::OnSetAccessibilityMode(unsigned int new_mode) {
4617   if (accessibility_mode_ == new_mode)
4618     return;
4619   accessibility_mode_ = new_mode;
4620   if (renderer_accessibility_) {
4621     delete renderer_accessibility_;
4622     renderer_accessibility_ = NULL;
4623   }
4624   if (accessibility_mode_ == AccessibilityModeOff)
4625     return;
4626
4627   if (accessibility_mode_ & AccessibilityModeFlagPlatformFullTree)
4628     renderer_accessibility_ = new RendererAccessibilityComplete(this);
4629 #if !defined(OS_ANDROID)
4630   else
4631     renderer_accessibility_ = new RendererAccessibilityFocusOnly(this);
4632 #endif
4633 }
4634
4635 void RenderViewImpl::OnSetActive(bool active) {
4636   if (webview())
4637     webview()->setIsActive(active);
4638
4639 #if defined(ENABLE_PLUGINS) && defined(OS_MACOSX)
4640   std::set<WebPluginDelegateProxy*>::iterator plugin_it;
4641   for (plugin_it = plugin_delegates_.begin();
4642        plugin_it != plugin_delegates_.end(); ++plugin_it) {
4643     (*plugin_it)->SetWindowFocus(active);
4644   }
4645 #endif
4646 }
4647
4648 #if defined(OS_MACOSX)
4649 void RenderViewImpl::OnSetWindowVisibility(bool visible) {
4650 #if defined(ENABLE_PLUGINS)
4651   // Inform plugins that their container has changed visibility.
4652   std::set<WebPluginDelegateProxy*>::iterator plugin_it;
4653   for (plugin_it = plugin_delegates_.begin();
4654        plugin_it != plugin_delegates_.end(); ++plugin_it) {
4655     (*plugin_it)->SetContainerVisibility(visible);
4656   }
4657 #endif
4658 }
4659
4660 void RenderViewImpl::OnWindowFrameChanged(const gfx::Rect& window_frame,
4661                                           const gfx::Rect& view_frame) {
4662 #if defined(ENABLE_PLUGINS)
4663   // Inform plugins that their window's frame has changed.
4664   std::set<WebPluginDelegateProxy*>::iterator plugin_it;
4665   for (plugin_it = plugin_delegates_.begin();
4666        plugin_it != plugin_delegates_.end(); ++plugin_it) {
4667     (*plugin_it)->WindowFrameChanged(window_frame, view_frame);
4668   }
4669 #endif
4670 }
4671
4672 void RenderViewImpl::OnPluginImeCompositionCompleted(const base::string16& text,
4673                                                      int plugin_id) {
4674   // WebPluginDelegateProxy is responsible for figuring out if this event
4675   // applies to it or not, so inform all the delegates.
4676   std::set<WebPluginDelegateProxy*>::iterator plugin_it;
4677   for (plugin_it = plugin_delegates_.begin();
4678        plugin_it != plugin_delegates_.end(); ++plugin_it) {
4679     (*plugin_it)->ImeCompositionCompleted(text, plugin_id);
4680   }
4681 }
4682 #endif  // OS_MACOSX
4683
4684 void RenderViewImpl::Close() {
4685   // We need to grab a pointer to the doomed WebView before we destroy it.
4686   WebView* doomed = webview();
4687   RenderWidget::Close();
4688   g_view_map.Get().erase(doomed);
4689   g_routing_id_view_map.Get().erase(routing_id_);
4690 }
4691
4692 void RenderViewImpl::DidHandleKeyEvent() {
4693   ClearEditCommands();
4694 }
4695
4696 bool RenderViewImpl::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
4697   possible_drag_event_info_.event_source =
4698       ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE;
4699   possible_drag_event_info_.event_location =
4700       gfx::Point(event.globalX, event.globalY);
4701
4702 #if defined(ENABLE_PLUGINS)
4703   // This method is called for every mouse event that the render view receives.
4704   // And then the mouse event is forwarded to WebKit, which dispatches it to the
4705   // event target. Potentially a Pepper plugin will receive the event.
4706   // In order to tell whether a plugin gets the last mouse event and which it
4707   // is, we set |pepper_last_mouse_event_target_| to NULL here. If a plugin gets
4708   // the event, it will notify us via DidReceiveMouseEvent() and set itself as
4709   // |pepper_last_mouse_event_target_|.
4710   pepper_last_mouse_event_target_ = NULL;
4711 #endif
4712
4713   // If the mouse is locked, only the current owner of the mouse lock can
4714   // process mouse events.
4715   return mouse_lock_dispatcher_->WillHandleMouseEvent(event);
4716 }
4717
4718 bool RenderViewImpl::WillHandleGestureEvent(
4719     const blink::WebGestureEvent& event) {
4720   possible_drag_event_info_.event_source =
4721       ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH;
4722   possible_drag_event_info_.event_location =
4723       gfx::Point(event.globalX, event.globalY);
4724   return false;
4725 }
4726
4727 void RenderViewImpl::DidHandleMouseEvent(const WebMouseEvent& event) {
4728   FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidHandleMouseEvent(event));
4729 }
4730
4731 void RenderViewImpl::DidHandleTouchEvent(const WebTouchEvent& event) {
4732   FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidHandleTouchEvent(event));
4733 }
4734
4735 bool RenderViewImpl::HasTouchEventHandlersAt(const gfx::Point& point) const {
4736   if (!webview())
4737     return false;
4738   return webview()->hasTouchEventHandlersAt(point);
4739 }
4740
4741 void RenderViewImpl::OnWasHidden() {
4742   RenderWidget::OnWasHidden();
4743
4744 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
4745   RenderThreadImpl::current()->video_capture_impl_manager()->
4746       SuspendDevices(true);
4747 #endif
4748
4749   if (webview())
4750     webview()->setVisibilityState(visibilityState(), false);
4751
4752 #if defined(ENABLE_PLUGINS)
4753   for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
4754        i != active_pepper_instances_.end(); ++i)
4755     (*i)->PageVisibilityChanged(false);
4756
4757 #if defined(OS_MACOSX)
4758   // Inform NPAPI plugins that their container is no longer visible.
4759   std::set<WebPluginDelegateProxy*>::iterator plugin_it;
4760   for (plugin_it = plugin_delegates_.begin();
4761        plugin_it != plugin_delegates_.end(); ++plugin_it) {
4762     (*plugin_it)->SetContainerVisibility(false);
4763   }
4764 #endif  // OS_MACOSX
4765 #endif // ENABLE_PLUGINS
4766 }
4767
4768 void RenderViewImpl::OnWasShown(bool needs_repainting) {
4769   RenderWidget::OnWasShown(needs_repainting);
4770
4771 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
4772   RenderThreadImpl::current()->video_capture_impl_manager()->
4773       SuspendDevices(false);
4774 #endif
4775
4776   if (webview())
4777     webview()->setVisibilityState(visibilityState(), false);
4778
4779 #if defined(ENABLE_PLUGINS)
4780   for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
4781        i != active_pepper_instances_.end(); ++i)
4782     (*i)->PageVisibilityChanged(true);
4783
4784 #if defined(OS_MACOSX)
4785   // Inform NPAPI plugins that their container is now visible.
4786   std::set<WebPluginDelegateProxy*>::iterator plugin_it;
4787   for (plugin_it = plugin_delegates_.begin();
4788        plugin_it != plugin_delegates_.end(); ++plugin_it) {
4789     (*plugin_it)->SetContainerVisibility(true);
4790   }
4791 #endif  // OS_MACOSX
4792 #endif  // ENABLE_PLUGINS
4793 }
4794
4795 GURL RenderViewImpl::GetURLForGraphicsContext3D() {
4796   DCHECK(webview());
4797   if (webview()->mainFrame())
4798     return GURL(webview()->mainFrame()->document().url());
4799   else
4800     return GURL("chrome://gpu/RenderViewImpl::CreateGraphicsContext3D");
4801 }
4802
4803 bool RenderViewImpl::ForceCompositingModeEnabled() {
4804   return webkit_preferences_.force_compositing_mode;
4805 }
4806
4807 void RenderViewImpl::OnSetFocus(bool enable) {
4808   RenderWidget::OnSetFocus(enable);
4809
4810 #if defined(ENABLE_PLUGINS)
4811   if (webview() && webview()->isActive()) {
4812     // Notify all NPAPI plugins.
4813     std::set<WebPluginDelegateProxy*>::iterator plugin_it;
4814     for (plugin_it = plugin_delegates_.begin();
4815          plugin_it != plugin_delegates_.end(); ++plugin_it) {
4816 #if defined(OS_MACOSX)
4817       // RenderWidget's call to setFocus can cause the underlying webview's
4818       // activation state to change just like a call to setIsActive.
4819       if (enable)
4820         (*plugin_it)->SetWindowFocus(true);
4821 #endif
4822       (*plugin_it)->SetContentAreaFocus(enable);
4823     }
4824   }
4825   // Notify all Pepper plugins.
4826   for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
4827        i != active_pepper_instances_.end(); ++i)
4828     (*i)->SetContentAreaFocus(enable);
4829 #endif
4830   // Notify all BrowserPlugins of the RenderView's focus state.
4831   if (browser_plugin_manager_.get())
4832     browser_plugin_manager_->UpdateFocusState();
4833 }
4834
4835 void RenderViewImpl::OnImeSetComposition(
4836     const base::string16& text,
4837     const std::vector<blink::WebCompositionUnderline>& underlines,
4838     int selection_start,
4839     int selection_end) {
4840 #if defined(ENABLE_PLUGINS)
4841   if (focused_pepper_plugin_) {
4842     focused_pepper_plugin_->render_frame()->OnImeSetComposition(
4843         text, underlines, selection_start, selection_end);
4844     return;
4845   }
4846
4847 #if defined(OS_WIN)
4848   // When a plug-in has focus, we create platform-specific IME data used by
4849   // our IME emulator and send it directly to the focused plug-in, i.e. we
4850   // bypass WebKit. (WebPluginDelegate dispatches this IME data only when its
4851   // instance ID is the same one as the specified ID.)
4852   if (focused_plugin_id_ >= 0) {
4853     std::vector<int> clauses;
4854     std::vector<int> target;
4855     for (size_t i = 0; i < underlines.size(); ++i) {
4856       clauses.push_back(underlines[i].startOffset);
4857       clauses.push_back(underlines[i].endOffset);
4858       if (underlines[i].thick) {
4859         target.clear();
4860         target.push_back(underlines[i].startOffset);
4861         target.push_back(underlines[i].endOffset);
4862       }
4863     }
4864     std::set<WebPluginDelegateProxy*>::iterator it;
4865     for (it = plugin_delegates_.begin(); it != plugin_delegates_.end(); ++it) {
4866       (*it)->ImeCompositionUpdated(text, clauses, target, selection_end,
4867                                    focused_plugin_id_);
4868     }
4869     return;
4870   }
4871 #endif  // OS_WIN
4872 #endif  // ENABLE_PLUGINS
4873   RenderWidget::OnImeSetComposition(text,
4874                                     underlines,
4875                                     selection_start,
4876                                     selection_end);
4877 }
4878
4879 void RenderViewImpl::OnImeConfirmComposition(
4880     const base::string16& text,
4881     const gfx::Range& replacement_range,
4882     bool keep_selection) {
4883 #if defined(ENABLE_PLUGINS)
4884   if (focused_pepper_plugin_) {
4885     focused_pepper_plugin_->render_frame()->OnImeConfirmComposition(
4886         text, replacement_range, keep_selection);
4887     return;
4888   }
4889 #if defined(OS_WIN)
4890   // Same as OnImeSetComposition(), we send the text from IMEs directly to
4891   // plug-ins. When we send IME text directly to plug-ins, we should not send
4892   // it to WebKit to prevent WebKit from controlling IMEs.
4893   // TODO(thakis): Honor |replacement_range| for plugins?
4894   if (focused_plugin_id_ >= 0) {
4895     std::set<WebPluginDelegateProxy*>::iterator it;
4896     for (it = plugin_delegates_.begin();
4897           it != plugin_delegates_.end(); ++it) {
4898       (*it)->ImeCompositionCompleted(text, focused_plugin_id_);
4899     }
4900     return;
4901   }
4902 #endif  // OS_WIN
4903 #endif  // ENABLE_PLUGINS
4904   if (replacement_range.IsValid() && webview()) {
4905     // Select the text in |replacement_range|, it will then be replaced by
4906     // text added by the call to RenderWidget::OnImeConfirmComposition().
4907     if (WebFrame* frame = webview()->focusedFrame()) {
4908       WebRange webrange = WebRange::fromDocumentRange(
4909           frame, replacement_range.start(), replacement_range.length());
4910       if (!webrange.isNull())
4911         frame->selectRange(webrange);
4912     }
4913   }
4914   RenderWidget::OnImeConfirmComposition(text,
4915                                         replacement_range,
4916                                         keep_selection);
4917 }
4918
4919 void RenderViewImpl::SetDeviceScaleFactor(float device_scale_factor) {
4920   RenderWidget::SetDeviceScaleFactor(device_scale_factor);
4921   if (webview()) {
4922     webview()->setDeviceScaleFactor(device_scale_factor);
4923     webview()->settings()->setAcceleratedCompositingForFixedPositionEnabled(
4924         ShouldUseFixedPositionCompositing(device_scale_factor_));
4925   webview()->settings()->setAcceleratedCompositingForOverflowScrollEnabled(
4926       ShouldUseAcceleratedCompositingForOverflowScroll(device_scale_factor_));
4927     webview()->settings()->setAcceleratedCompositingForTransitionEnabled(
4928         ShouldUseTransitionCompositing(device_scale_factor_));
4929     webview()->settings()->
4930         setAcceleratedCompositingForFixedRootBackgroundEnabled(
4931             ShouldUseAcceleratedFixedRootBackground(device_scale_factor_));
4932     webview()->settings()->setAcceleratedCompositingForScrollableFramesEnabled(
4933         ShouldUseAcceleratedCompositingForScrollableFrames(
4934             device_scale_factor_));
4935     webview()->settings()->setCompositedScrollingForFramesEnabled(
4936         ShouldUseCompositedScrollingForFrames(device_scale_factor_));
4937   }
4938   if (auto_resize_mode_)
4939     AutoResizeCompositor();
4940
4941   if (browser_plugin_manager_.get())
4942     browser_plugin_manager_->UpdateDeviceScaleFactor(device_scale_factor_);
4943 }
4944
4945 ui::TextInputType RenderViewImpl::GetTextInputType() {
4946 #if defined(ENABLE_PLUGINS)
4947   if (focused_pepper_plugin_)
4948     return focused_pepper_plugin_->text_input_type();
4949 #endif
4950   return RenderWidget::GetTextInputType();
4951 }
4952
4953 void RenderViewImpl::GetSelectionBounds(gfx::Rect* start, gfx::Rect* end) {
4954 #if defined(ENABLE_PLUGINS)
4955   if (focused_pepper_plugin_) {
4956     // TODO(kinaba) http://crbug.com/101101
4957     // Current Pepper IME API does not handle selection bounds. So we simply
4958     // use the caret position as an empty range for now. It will be updated
4959     // after Pepper API equips features related to surrounding text retrieval.
4960     gfx::Rect caret = focused_pepper_plugin_->GetCaretBounds();
4961     *start = caret;
4962     *end = caret;
4963     return;
4964   }
4965 #endif
4966   RenderWidget::GetSelectionBounds(start, end);
4967 }
4968
4969 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(USE_AURA)
4970 void RenderViewImpl::GetCompositionCharacterBounds(
4971     std::vector<gfx::Rect>* bounds) {
4972   DCHECK(bounds);
4973   bounds->clear();
4974
4975 #if defined(ENABLE_PLUGINS)
4976   if (focused_pepper_plugin_) {
4977     return;
4978   }
4979 #endif
4980
4981   if (!webview())
4982     return;
4983   size_t start_offset = 0;
4984   size_t character_count = 0;
4985   if (!webview()->compositionRange(&start_offset, &character_count))
4986     return;
4987   if (character_count == 0)
4988     return;
4989
4990   blink::WebFrame* frame = webview()->focusedFrame();
4991   if (!frame)
4992     return;
4993
4994   bounds->reserve(character_count);
4995   blink::WebRect webrect;
4996   for (size_t i = 0; i < character_count; ++i) {
4997     if (!frame->firstRectForCharacterRange(start_offset + i, 1, webrect)) {
4998       DLOG(ERROR) << "Could not retrieve character rectangle at " << i;
4999       bounds->clear();
5000       return;
5001     }
5002     bounds->push_back(webrect);
5003   }
5004 }
5005
5006 void RenderViewImpl::GetCompositionRange(gfx::Range* range) {
5007 #if defined(ENABLE_PLUGINS)
5008   if (focused_pepper_plugin_) {
5009     return;
5010   }
5011 #endif
5012   RenderWidget::GetCompositionRange(range);
5013 }
5014 #endif
5015
5016 bool RenderViewImpl::CanComposeInline() {
5017 #if defined(ENABLE_PLUGINS)
5018   if (focused_pepper_plugin_)
5019     return focused_pepper_plugin_->IsPluginAcceptingCompositionEvents();
5020 #endif
5021   return true;
5022 }
5023
5024 void RenderViewImpl::InstrumentWillBeginFrame(int frame_id) {
5025   if (!webview())
5026     return;
5027   if (!webview()->devToolsAgent())
5028     return;
5029   webview()->devToolsAgent()->didBeginFrame(frame_id);
5030 }
5031
5032 void RenderViewImpl::InstrumentDidBeginFrame() {
5033   if (!webview())
5034     return;
5035   if (!webview()->devToolsAgent())
5036     return;
5037   // TODO(jamesr/caseq): Decide if this needs to be renamed.
5038   webview()->devToolsAgent()->didComposite();
5039 }
5040
5041 void RenderViewImpl::InstrumentDidCancelFrame() {
5042   if (!webview())
5043     return;
5044   if (!webview()->devToolsAgent())
5045     return;
5046   webview()->devToolsAgent()->didCancelFrame();
5047 }
5048
5049 void RenderViewImpl::InstrumentWillComposite() {
5050   if (!webview())
5051     return;
5052   if (!webview()->devToolsAgent())
5053     return;
5054   webview()->devToolsAgent()->willComposite();
5055 }
5056
5057 bool RenderViewImpl::AllowPartialSwap() const {
5058   return allow_partial_swap_;
5059 }
5060
5061 void RenderViewImpl::SetScreenMetricsEmulationParameters(
5062     float device_scale_factor,
5063     const gfx::Point& root_layer_offset,
5064     float root_layer_scale) {
5065   if (webview()) {
5066     webview()->setCompositorDeviceScaleFactorOverride(device_scale_factor);
5067     webview()->setRootLayerTransform(
5068         blink::WebSize(root_layer_offset.x(), root_layer_offset.y()),
5069         root_layer_scale);
5070   }
5071 }
5072
5073 bool RenderViewImpl::ScheduleFileChooser(
5074     const FileChooserParams& params,
5075     WebFileChooserCompletion* completion) {
5076   static const size_t kMaximumPendingFileChooseRequests = 4;
5077   if (file_chooser_completions_.size() > kMaximumPendingFileChooseRequests) {
5078     // This sanity check prevents too many file choose requests from getting
5079     // queued which could DoS the user. Getting these is most likely a
5080     // programming error (there are many ways to DoS the user so it's not
5081     // considered a "real" security check), either in JS requesting many file
5082     // choosers to pop up, or in a plugin.
5083     //
5084     // TODO(brettw) we might possibly want to require a user gesture to open
5085     // a file picker, which will address this issue in a better way.
5086     return false;
5087   }
5088
5089   file_chooser_completions_.push_back(linked_ptr<PendingFileChooser>(
5090       new PendingFileChooser(params, completion)));
5091   if (file_chooser_completions_.size() == 1) {
5092     // Actually show the browse dialog when this is the first request.
5093     Send(new ViewHostMsg_RunFileChooser(routing_id_, params));
5094   }
5095   return true;
5096 }
5097
5098 blink::WebGeolocationClient* RenderViewImpl::geolocationClient() {
5099   if (!geolocation_dispatcher_)
5100     geolocation_dispatcher_ = new GeolocationDispatcher(this);
5101   return geolocation_dispatcher_;
5102 }
5103
5104 blink::WebSpeechInputController* RenderViewImpl::speechInputController(
5105     blink::WebSpeechInputListener* listener) {
5106 #if defined(ENABLE_INPUT_SPEECH)
5107   if (!input_tag_speech_dispatcher_)
5108     input_tag_speech_dispatcher_ =
5109         new InputTagSpeechDispatcher(this, listener);
5110 #endif
5111   return input_tag_speech_dispatcher_;
5112 }
5113
5114 blink::WebSpeechRecognizer* RenderViewImpl::speechRecognizer() {
5115   if (!speech_recognition_dispatcher_)
5116     speech_recognition_dispatcher_ = new SpeechRecognitionDispatcher(this);
5117   return speech_recognition_dispatcher_;
5118 }
5119
5120 void RenderViewImpl::zoomLimitsChanged(double minimum_level,
5121                                        double maximum_level) {
5122   // For now, don't remember plugin zoom values.  We don't want to mix them with
5123   // normal web content (i.e. a fixed layout plugin would usually want them
5124   // different).
5125   bool remember = !webview()->mainFrame()->document().isPluginDocument();
5126
5127   int minimum_percent = static_cast<int>(
5128       ZoomLevelToZoomFactor(minimum_level) * 100);
5129   int maximum_percent = static_cast<int>(
5130       ZoomLevelToZoomFactor(maximum_level) * 100);
5131
5132   Send(new ViewHostMsg_UpdateZoomLimits(
5133       routing_id_, minimum_percent, maximum_percent, remember));
5134 }
5135
5136 void RenderViewImpl::zoomLevelChanged() {
5137   bool remember = !webview()->mainFrame()->document().isPluginDocument();
5138   float zoom_level = webview()->zoomLevel();
5139
5140   FOR_EACH_OBSERVER(RenderViewObserver, observers_, ZoomLevelChanged());
5141
5142   // Tell the browser which url got zoomed so it can update the menu and the
5143   // saved values if necessary
5144   Send(new ViewHostMsg_DidZoomURL(
5145       routing_id_, zoom_level, remember,
5146       GURL(webview()->mainFrame()->document().url())));
5147 }
5148
5149 double RenderViewImpl::zoomLevelToZoomFactor(double zoom_level) const {
5150   return ZoomLevelToZoomFactor(zoom_level);
5151 }
5152
5153 double RenderViewImpl::zoomFactorToZoomLevel(double factor) const {
5154   return ZoomFactorToZoomLevel(factor);
5155 }
5156
5157 void RenderViewImpl::registerProtocolHandler(const WebString& scheme,
5158                                              const WebURL& base_url,
5159                                              const WebURL& url,
5160                                              const WebString& title) {
5161   bool user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
5162   GURL base(base_url);
5163   GURL absolute_url = base.Resolve(base::UTF16ToUTF8(url.string()));
5164   if (base.GetOrigin() != absolute_url.GetOrigin()) {
5165     return;
5166   }
5167   Send(new ViewHostMsg_RegisterProtocolHandler(routing_id_,
5168                                                base::UTF16ToUTF8(scheme),
5169                                                absolute_url,
5170                                                title,
5171                                                user_gesture));
5172 }
5173
5174 blink::WebPageVisibilityState RenderViewImpl::visibilityState() const {
5175   blink::WebPageVisibilityState current_state = is_hidden() ?
5176       blink::WebPageVisibilityStateHidden :
5177       blink::WebPageVisibilityStateVisible;
5178   blink::WebPageVisibilityState override_state = current_state;
5179   // TODO(jam): move this method to WebFrameClient.
5180   if (GetContentClient()->renderer()->
5181           ShouldOverridePageVisibilityState(main_render_frame_.get(),
5182                                             &override_state))
5183     return override_state;
5184   return current_state;
5185 }
5186
5187 blink::WebUserMediaClient* RenderViewImpl::userMediaClient() {
5188   // This can happen in tests, in which case it's OK to return NULL.
5189   if (!InitializeMediaStreamClient())
5190     return NULL;
5191
5192   return web_user_media_client_;
5193 }
5194
5195 blink::WebMIDIClient* RenderViewImpl::webMIDIClient() {
5196   if (!midi_dispatcher_)
5197     midi_dispatcher_ = new MidiDispatcher(this);
5198   return midi_dispatcher_;
5199 }
5200
5201 void RenderViewImpl::draggableRegionsChanged() {
5202   FOR_EACH_OBSERVER(
5203       RenderViewObserver,
5204       observers_,
5205       DraggableRegionsChanged(webview()->mainFrame()));
5206 }
5207
5208 WebMediaPlayer* RenderViewImpl::CreateWebMediaPlayerForMediaStream(
5209     WebFrame* frame,
5210     const blink::WebURL& url,
5211     WebMediaPlayerClient* client) {
5212 #if defined(ENABLE_WEBRTC)
5213   if (!InitializeMediaStreamClient()) {
5214     LOG(ERROR) << "Failed to initialize MediaStreamClient";
5215     return NULL;
5216   }
5217   if (media_stream_client_->IsMediaStream(url)) {
5218 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
5219     bool found_neon =
5220         (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0;
5221     UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon);
5222 #endif  // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
5223     return new WebMediaPlayerMS(frame, client, AsWeakPtr(),
5224                                 media_stream_client_, new RenderMediaLog());
5225   }
5226 #endif  // defined(ENABLE_WEBRTC)
5227   return NULL;
5228 }
5229
5230 #if defined(OS_ANDROID)
5231 WebContentDetectionResult RenderViewImpl::detectContentAround(
5232     const WebHitTestResult& touch_hit) {
5233   DCHECK(!touch_hit.isNull());
5234   DCHECK(!touch_hit.node().isNull());
5235   DCHECK(touch_hit.node().isTextNode());
5236
5237   // Process the position with all the registered content detectors until
5238   // a match is found. Priority is provided by their relative order.
5239   for (ContentDetectorList::const_iterator it = content_detectors_.begin();
5240       it != content_detectors_.end(); ++it) {
5241     ContentDetector::Result content = (*it)->FindTappedContent(touch_hit);
5242     if (content.valid) {
5243       return WebContentDetectionResult(content.content_boundaries,
5244           base::UTF8ToUTF16(content.text), content.intent_url);
5245     }
5246   }
5247   return WebContentDetectionResult();
5248 }
5249
5250 void RenderViewImpl::scheduleContentIntent(const WebURL& intent) {
5251   // Introduce a short delay so that the user can notice the content.
5252   base::MessageLoop::current()->PostDelayedTask(
5253       FROM_HERE,
5254       base::Bind(&RenderViewImpl::LaunchAndroidContentIntent,
5255                  AsWeakPtr(),
5256                  intent,
5257                  expected_content_intent_id_),
5258       base::TimeDelta::FromMilliseconds(kContentIntentDelayMilliseconds));
5259 }
5260
5261 void RenderViewImpl::cancelScheduledContentIntents() {
5262   ++expected_content_intent_id_;
5263 }
5264
5265 void RenderViewImpl::LaunchAndroidContentIntent(const GURL& intent,
5266                                                 size_t request_id) {
5267   if (request_id != expected_content_intent_id_)
5268       return;
5269
5270   // Remove the content highlighting if any.
5271   scheduleComposite();
5272
5273   if (!intent.is_empty())
5274     Send(new ViewHostMsg_StartContentIntent(routing_id_, intent));
5275 }
5276
5277 bool RenderViewImpl::openDateTimeChooser(
5278     const blink::WebDateTimeChooserParams& params,
5279     blink::WebDateTimeChooserCompletion* completion) {
5280   // JavaScript may try to open a date time chooser while one is already open.
5281   if (date_time_picker_client_)
5282     return false;
5283   date_time_picker_client_.reset(
5284       new RendererDateTimePicker(this, params, completion));
5285   return date_time_picker_client_->Open();
5286 }
5287
5288 void RenderViewImpl::DismissDateTimeDialog() {
5289   DCHECK(date_time_picker_client_);
5290   date_time_picker_client_.reset(NULL);
5291 }
5292
5293 WebMediaPlayer* RenderViewImpl::CreateAndroidWebMediaPlayer(
5294       WebFrame* frame,
5295       const blink::WebURL& url,
5296       WebMediaPlayerClient* client) {
5297   GpuChannelHost* gpu_channel_host =
5298       RenderThreadImpl::current()->EstablishGpuChannelSync(
5299           CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE);
5300   if (!gpu_channel_host) {
5301     LOG(ERROR) << "Failed to establish GPU channel for media player";
5302     return NULL;
5303   }
5304
5305   scoped_ptr<StreamTextureFactory> stream_texture_factory;
5306   if (UsingSynchronousRendererCompositor()) {
5307     SynchronousCompositorFactory* factory =
5308         SynchronousCompositorFactory::GetInstance();
5309     stream_texture_factory = factory->CreateStreamTextureFactory(routing_id_);
5310   } else {
5311     scoped_refptr<webkit::gpu::ContextProviderWebContext> context_provider =
5312         RenderThreadImpl::current()->SharedMainThreadContextProvider();
5313
5314     if (!context_provider.get()) {
5315       LOG(ERROR) << "Failed to get context3d for media player";
5316       return NULL;
5317     }
5318
5319     stream_texture_factory.reset(new StreamTextureFactoryImpl(
5320         context_provider, gpu_channel_host, routing_id_));
5321   }
5322
5323   return new WebMediaPlayerAndroid(
5324       frame,
5325       client,
5326       AsWeakPtr(),
5327       media_player_manager_,
5328       stream_texture_factory.release(),
5329       RenderThreadImpl::current()->GetMediaThreadMessageLoopProxy(),
5330       new RenderMediaLog());
5331 }
5332
5333 #endif  // defined(OS_ANDROID)
5334
5335 #if defined(OS_MACOSX)
5336 void RenderViewImpl::OnSelectPopupMenuItem(int selected_index) {
5337   if (external_popup_menu_ == NULL) {
5338     // Crash reports from the field indicate that we can be notified with a
5339     // NULL external popup menu (we probably get notified twice).
5340     // If you hit this please file a bug against jcivelli and include the page
5341     // and steps to repro.
5342     NOTREACHED();
5343     return;
5344   }
5345   external_popup_menu_->DidSelectItem(selected_index);
5346   external_popup_menu_.reset();
5347 }
5348 #endif
5349
5350 #if defined(OS_ANDROID)
5351 void RenderViewImpl::OnSelectPopupMenuItems(
5352     bool canceled,
5353     const std::vector<int>& selected_indices) {
5354   // It is possible to receive more than one of these calls if the user presses
5355   // a select faster than it takes for the show-select-popup IPC message to make
5356   // it to the browser UI thread.  Ignore the extra-messages.
5357   // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
5358   if (!external_popup_menu_)
5359     return;
5360
5361   external_popup_menu_->DidSelectItems(canceled, selected_indices);
5362   external_popup_menu_.reset();
5363 }
5364 #endif
5365
5366 void RenderViewImpl::OnShowContextMenu(const gfx::Point& location) {
5367   context_menu_source_type_ = ui::MENU_SOURCE_TOUCH_EDIT_MENU;
5368   touch_editing_context_menu_location_ = location;
5369   if (webview())
5370     webview()->showContextMenu();
5371 }
5372
5373 void RenderViewImpl::OnEnableViewSourceMode() {
5374   if (!webview())
5375     return;
5376   WebFrame* main_frame = webview()->mainFrame();
5377   if (!main_frame)
5378     return;
5379   main_frame->enableViewSourceMode(true);
5380 }
5381
5382 void RenderViewImpl::OnDisownOpener() {
5383   if (!webview())
5384     return;
5385
5386   WebFrame* main_frame = webview()->mainFrame();
5387   if (main_frame && main_frame->opener())
5388     main_frame->setOpener(NULL);
5389 }
5390
5391 #if defined(OS_ANDROID)
5392 bool RenderViewImpl::didTapMultipleTargets(
5393     const blink::WebGestureEvent& event,
5394     const WebVector<WebRect>& target_rects) {
5395   // Never show a disambiguation popup when accessibility is enabled,
5396   // as this interferes with "touch exploration".
5397   bool matchesAccessibilityModeComplete =
5398       (accessibility_mode_ & AccessibilityModeComplete) ==
5399       AccessibilityModeComplete;
5400   if (matchesAccessibilityModeComplete)
5401     return false;
5402
5403   gfx::Rect finger_rect(
5404       event.x - event.data.tap.width / 2, event.y - event.data.tap.height / 2,
5405       event.data.tap.width, event.data.tap.height);
5406   gfx::Rect zoom_rect;
5407   float new_total_scale =
5408       DisambiguationPopupHelper::ComputeZoomAreaAndScaleFactor(
5409           finger_rect, target_rects, GetSize(),
5410           gfx::Rect(webview()->mainFrame()->visibleContentRect()).size(),
5411           device_scale_factor_ * webview()->pageScaleFactor(), &zoom_rect);
5412   if (!new_total_scale)
5413     return false;
5414
5415   bool handled = false;
5416   switch (renderer_preferences_.tap_multiple_targets_strategy) {
5417     case TAP_MULTIPLE_TARGETS_STRATEGY_ZOOM:
5418       handled = webview()->zoomToMultipleTargetsRect(zoom_rect);
5419       break;
5420     case TAP_MULTIPLE_TARGETS_STRATEGY_POPUP: {
5421       gfx::Size canvas_size =
5422           gfx::ToCeiledSize(gfx::ScaleSize(zoom_rect.size(), new_total_scale));
5423       TransportDIB* transport_dib = NULL;
5424       {
5425         scoped_ptr<skia::PlatformCanvas> canvas(
5426             RenderProcess::current()->GetDrawingCanvas(&transport_dib,
5427                                                        gfx::Rect(canvas_size)));
5428         if (!canvas) {
5429           handled = false;
5430           break;
5431         }
5432
5433         // TODO(trchen): Cleanup the device scale factor mess.
5434         // device scale will be applied in WebKit
5435         // --> zoom_rect doesn't include device scale,
5436         //     but WebKit will still draw on zoom_rect * device_scale_factor_
5437         canvas->scale(new_total_scale / device_scale_factor_,
5438                       new_total_scale / device_scale_factor_);
5439         canvas->translate(-zoom_rect.x() * device_scale_factor_,
5440                           -zoom_rect.y() * device_scale_factor_);
5441
5442         webwidget_->paint(
5443             canvas.get(),
5444             zoom_rect,
5445             WebWidget::ForceSoftwareRenderingAndIgnoreGPUResidentContent);
5446       }
5447
5448       gfx::Rect physical_window_zoom_rect = gfx::ToEnclosingRect(
5449           ClientRectToPhysicalWindowRect(gfx::RectF(zoom_rect)));
5450       Send(new ViewHostMsg_ShowDisambiguationPopup(routing_id_,
5451                                                    physical_window_zoom_rect,
5452                                                    canvas_size,
5453                                                    transport_dib->id()));
5454       handled = true;
5455       break;
5456     }
5457     case TAP_MULTIPLE_TARGETS_STRATEGY_NONE:
5458       // No-op.
5459       break;
5460   }
5461
5462   return handled;
5463 }
5464 #endif
5465
5466 unsigned RenderViewImpl::GetLocalSessionHistoryLengthForTesting() const {
5467   return history_list_length_;
5468 }
5469
5470 void RenderViewImpl::SetFocusAndActivateForTesting(bool enable) {
5471   if (enable) {
5472     if (has_focus())
5473       return;
5474     OnSetActive(true);
5475     OnSetFocus(true);
5476   } else {
5477     if (!has_focus())
5478       return;
5479     OnSetFocus(false);
5480     OnSetActive(false);
5481   }
5482 }
5483
5484 void RenderViewImpl::SetDeviceScaleFactorForTesting(float factor) {
5485   ViewMsg_Resize_Params params;
5486   params.screen_info = screen_info_;
5487   params.screen_info.deviceScaleFactor = factor;
5488   params.new_size = size();
5489   params.physical_backing_size =
5490       gfx::ToCeiledSize(gfx::ScaleSize(size(), factor));
5491   params.overdraw_bottom_height = 0.f;
5492   params.resizer_rect = WebRect();
5493   params.is_fullscreen = is_fullscreen();
5494   OnResize(params);
5495 }
5496
5497 void RenderViewImpl::ForceResizeForTesting(const gfx::Size& new_size) {
5498   gfx::Rect new_position(rootWindowRect().x,
5499                          rootWindowRect().y,
5500                          new_size.width(),
5501                          new_size.height());
5502   ResizeSynchronously(new_position);
5503 }
5504
5505 void RenderViewImpl::UseSynchronousResizeModeForTesting(bool enable) {
5506   resizing_mode_selector_->set_is_synchronous_mode(enable);
5507 }
5508
5509 void RenderViewImpl::EnableAutoResizeForTesting(const gfx::Size& min_size,
5510                                                 const gfx::Size& max_size) {
5511   OnEnableAutoResize(min_size, max_size);
5512 }
5513
5514 void RenderViewImpl::DisableAutoResizeForTesting(const gfx::Size& new_size) {
5515   OnDisableAutoResize(new_size);
5516 }
5517
5518 void RenderViewImpl::SetMediaStreamClientForTesting(
5519     MediaStreamClient* media_stream_client) {
5520   DCHECK(!media_stream_client_);
5521   DCHECK(!web_user_media_client_);
5522   media_stream_client_ = media_stream_client;
5523 }
5524
5525 void RenderViewImpl::OnReleaseDisambiguationPopupDIB(
5526     TransportDIB::Handle dib_handle) {
5527   TransportDIB* dib = TransportDIB::CreateWithHandle(dib_handle);
5528   RenderProcess::current()->ReleaseTransportDIB(dib);
5529 }
5530
5531 void RenderViewImpl::DidCommitCompositorFrame() {
5532   RenderWidget::DidCommitCompositorFrame();
5533   FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidCommitCompositorFrame());
5534 }
5535
5536 void RenderViewImpl::SendUpdateFaviconURL(const std::vector<FaviconURL>& urls) {
5537   if (!urls.empty())
5538     Send(new ViewHostMsg_UpdateFaviconURL(routing_id_, page_id_, urls));
5539 }
5540
5541 void RenderViewImpl::DidStopLoadingIcons() {
5542   int icon_types = WebIconURL::TypeFavicon;
5543   if (TouchEnabled())
5544     icon_types |= WebIconURL::TypeTouchPrecomposed | WebIconURL::TypeTouch;
5545
5546   WebVector<WebIconURL> icon_urls =
5547       webview()->mainFrame()->iconURLs(icon_types);
5548
5549   std::vector<FaviconURL> urls;
5550   for (size_t i = 0; i < icon_urls.size(); i++) {
5551     WebURL url = icon_urls[i].iconURL();
5552     if (!url.isEmpty())
5553       urls.push_back(FaviconURL(url,
5554                                 ToFaviconType(icon_urls[i].iconType())));
5555   }
5556   SendUpdateFaviconURL(urls);
5557 }
5558
5559 }  // namespace content