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