Upstream version 9.37.195.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/field_trial.h"
24 #include "base/metrics/histogram.h"
25 #include "base/path_service.h"
26 #include "base/process/kill.h"
27 #include "base/process/process.h"
28 #include "base/strings/string_number_conversions.h"
29 #include "base/strings/string_piece.h"
30 #include "base/strings/string_split.h"
31 #include "base/strings/string_util.h"
32 #include "base/strings/sys_string_conversions.h"
33 #include "base/strings/utf_string_conversions.h"
34 #include "base/time/time.h"
35 #include "cc/base/switches.h"
36 #include "content/child/appcache/appcache_dispatcher.h"
37 #include "content/child/appcache/web_application_cache_host_impl.h"
38 #include "content/child/child_shared_bitmap_manager.h"
39 #include "content/child/child_thread.h"
40 #include "content/child/npapi/webplugin_delegate_impl.h"
41 #include "content/child/request_extra_data.h"
42 #include "content/child/webmessageportchannel_impl.h"
43 #include "content/common/database_messages.h"
44 #include "content/common/dom_storage/dom_storage_types.h"
45 #include "content/common/drag_messages.h"
46 #include "content/common/frame_messages.h"
47 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
48 #include "content/common/input_messages.h"
49 #include "content/common/pepper_messages.h"
50 #include "content/common/socket_stream_handle_data.h"
51 #include "content/common/ssl_status_serialization.h"
52 #include "content/common/view_messages.h"
53 #include "content/public/common/bindings_policy.h"
54 #include "content/public/common/content_client.h"
55 #include "content/public/common/content_constants.h"
56 #include "content/public/common/content_switches.h"
57 #include "content/public/common/drop_data.h"
58 #include "content/public/common/favicon_url.h"
59 #include "content/public/common/file_chooser_params.h"
60 #include "content/public/common/page_zoom.h"
61 #include "content/public/common/ssl_status.h"
62 #include "content/public/common/three_d_api_types.h"
63 #include "content/public/common/url_constants.h"
64 #include "content/public/common/url_utils.h"
65 #include "content/public/renderer/content_renderer_client.h"
66 #include "content/public/renderer/document_state.h"
67 #include "content/public/renderer/navigation_state.h"
68 #include "content/public/renderer/render_view_observer.h"
69 #include "content/public/renderer/render_view_visitor.h"
70 #include "content/public/renderer/web_preferences.h"
71 #include "content/renderer/accessibility/renderer_accessibility.h"
72 #include "content/renderer/accessibility/renderer_accessibility_complete.h"
73 #include "content/renderer/accessibility/renderer_accessibility_focus_only.h"
74 #include "content/renderer/browser_plugin/browser_plugin.h"
75 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
76 #include "content/renderer/browser_plugin/browser_plugin_manager_impl.h"
77 #include "content/renderer/devtools/devtools_agent.h"
78 #include "content/renderer/disambiguation_popup_helper.h"
79 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
80 #include "content/renderer/drop_data_builder.h"
81 #include "content/renderer/external_popup_menu.h"
82 #include "content/renderer/gpu/render_widget_compositor.h"
83 #include "content/renderer/history_controller.h"
84 #include "content/renderer/history_serialization.h"
85 #include "content/renderer/idle_user_detector.h"
86 #include "content/renderer/ime_event_guard.h"
87 #include "content/renderer/input/input_handler_manager.h"
88 #include "content/renderer/internal_document_state_data.h"
89 #include "content/renderer/media/audio_device_factory.h"
90 #include "content/renderer/media/media_stream_dispatcher.h"
91 #include "content/renderer/media/video_capture_impl_manager.h"
92 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
93 #include "content/renderer/memory_benchmarking_extension.h"
94 #include "content/renderer/mhtml_generator.h"
95 #include "content/renderer/push_messaging_dispatcher.h"
96 #include "content/renderer/render_frame_impl.h"
97 #include "content/renderer/render_frame_proxy.h"
98 #include "content/renderer/render_process.h"
99 #include "content/renderer/render_thread_impl.h"
100 #include "content/renderer/render_view_impl_params.h"
101 #include "content/renderer/render_view_mouse_lock_dispatcher.h"
102 #include "content/renderer/render_widget_fullscreen_pepper.h"
103 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
104 #include "content/renderer/resizing_mode_selector.h"
105 #include "content/renderer/savable_resources.h"
106 #include "content/renderer/skia_benchmarking_extension.h"
107 #include "content/renderer/speech_recognition_dispatcher.h"
108 #include "content/renderer/stats_collection_controller.h"
109 #include "content/renderer/stats_collection_observer.h"
110 #include "content/renderer/text_input_client_observer.h"
111 #include "content/renderer/v8_value_converter_impl.h"
112 #include "content/renderer/web_ui_extension.h"
113 #include "content/renderer/web_ui_extension_data.h"
114 #include "content/renderer/web_ui_mojo.h"
115 #include "content/renderer/websharedworker_proxy.h"
116 #include "media/audio/audio_output_device.h"
117 #include "media/base/filter_collection.h"
118 #include "media/base/media_switches.h"
119 #include "media/filters/audio_renderer_impl.h"
120 #include "media/filters/gpu_video_accelerator_factories.h"
121 #include "net/base/data_url.h"
122 #include "net/base/escape.h"
123 #include "net/base/net_errors.h"
124 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
125 #include "net/http/http_util.h"
126 #include "third_party/WebKit/public/platform/WebCString.h"
127 #include "third_party/WebKit/public/platform/WebDragData.h"
128 #include "third_party/WebKit/public/platform/WebHTTPBody.h"
129 #include "third_party/WebKit/public/platform/WebImage.h"
130 #include "third_party/WebKit/public/platform/WebMessagePortChannel.h"
131 #include "third_party/WebKit/public/platform/WebPoint.h"
132 #include "third_party/WebKit/public/platform/WebRect.h"
133 #include "third_party/WebKit/public/platform/WebSize.h"
134 #include "third_party/WebKit/public/platform/WebSocketStreamHandle.h"
135 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
136 #include "third_party/WebKit/public/platform/WebString.h"
137 #include "third_party/WebKit/public/platform/WebURL.h"
138 #include "third_party/WebKit/public/platform/WebURLError.h"
139 #include "third_party/WebKit/public/platform/WebURLRequest.h"
140 #include "third_party/WebKit/public/platform/WebURLResponse.h"
141 #include "third_party/WebKit/public/platform/WebVector.h"
142 #include "third_party/WebKit/public/web/WebAXObject.h"
143 #include "third_party/WebKit/public/web/WebColorName.h"
144 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
145 #include "third_party/WebKit/public/web/WebDOMEvent.h"
146 #include "third_party/WebKit/public/web/WebDOMMessageEvent.h"
147 #include "third_party/WebKit/public/web/WebDataSource.h"
148 #include "third_party/WebKit/public/web/WebDateTimeChooserCompletion.h"
149 #include "third_party/WebKit/public/web/WebDateTimeChooserParams.h"
150 #include "third_party/WebKit/public/web/WebDevToolsAgent.h"
151 #include "third_party/WebKit/public/web/WebDocument.h"
152 #include "third_party/WebKit/public/web/WebElement.h"
153 #include "third_party/WebKit/public/web/WebFileChooserParams.h"
154 #include "third_party/WebKit/public/web/WebFindOptions.h"
155 #include "third_party/WebKit/public/web/WebFormControlElement.h"
156 #include "third_party/WebKit/public/web/WebFormElement.h"
157 #include "third_party/WebKit/public/web/WebFrame.h"
158 #include "third_party/WebKit/public/web/WebGlyphCache.h"
159 #include "third_party/WebKit/public/web/WebHistoryItem.h"
160 #include "third_party/WebKit/public/web/WebInputElement.h"
161 #include "third_party/WebKit/public/web/WebInputEvent.h"
162 #include "third_party/WebKit/public/web/WebLocalFrame.h"
163 #include "third_party/WebKit/public/web/WebMediaPlayerAction.h"
164 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
165 #include "third_party/WebKit/public/web/WebNodeList.h"
166 #include "third_party/WebKit/public/web/WebPageSerializer.h"
167 #include "third_party/WebKit/public/web/WebPlugin.h"
168 #include "third_party/WebKit/public/web/WebPluginAction.h"
169 #include "third_party/WebKit/public/web/WebPluginContainer.h"
170 #include "third_party/WebKit/public/web/WebPluginDocument.h"
171 #include "third_party/WebKit/public/web/WebRange.h"
172 #include "third_party/WebKit/public/web/WebScriptSource.h"
173 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
174 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
175 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
176 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
177 #include "third_party/WebKit/public/web/WebSettings.h"
178 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
179 #include "third_party/WebKit/public/web/WebView.h"
180 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
181 #include "third_party/WebKit/public/web/default/WebRenderTheme.h"
182 #include "ui/base/clipboard/clipboard.h"
183 #include "ui/base/ui_base_switches_util.h"
184 #include "ui/events/latency_info.h"
185 #include "ui/gfx/native_widget_types.h"
186 #include "ui/gfx/point.h"
187 #include "ui/gfx/rect.h"
188 #include "ui/gfx/rect_conversions.h"
189 #include "ui/gfx/size_conversions.h"
190 #include "ui/shell_dialogs/selected_file_info.h"
191 #include "v8/include/v8.h"
192 #include "webkit/child/weburlresponse_extradata_impl.h"
193
194 #if defined(OS_ANDROID)
195 #include <cpu-features.h>
196
197 #include "content/renderer/android/address_detector.h"
198 #include "content/renderer/android/content_detector.h"
199 #include "content/renderer/android/email_detector.h"
200 #include "content/renderer/android/phone_number_detector.h"
201 #include "net/android/network_library.h"
202 #include "skia/ext/platform_canvas.h"
203 #include "third_party/WebKit/public/platform/WebFloatPoint.h"
204 #include "third_party/WebKit/public/platform/WebFloatRect.h"
205 #include "third_party/WebKit/public/web/WebHitTestResult.h"
206 #include "ui/gfx/rect_f.h"
207
208 #elif defined(OS_WIN)
209 // TODO(port): these files are currently Windows only because they concern:
210 //   * theming
211 #include "ui/native_theme/native_theme_win.h"
212 #elif defined(USE_X11)
213 #include "ui/native_theme/native_theme.h"
214 #elif defined(OS_MACOSX)
215 #include "skia/ext/skia_utils_mac.h"
216 #endif
217
218 #if defined(ENABLE_PLUGINS)
219 #include "content/renderer/npapi/webplugin_delegate_proxy.h"
220 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
221 #include "content/renderer/pepper/pepper_plugin_registry.h"
222 #endif
223
224 #if defined(ENABLE_WEBRTC)
225 #include "content/renderer/media/rtc_peer_connection_handler.h"
226 #endif
227
228 using blink::WebAXObject;
229 using blink::WebApplicationCacheHost;
230 using blink::WebApplicationCacheHostClient;
231 using blink::WebCString;
232 using blink::WebColor;
233 using blink::WebColorName;
234 using blink::WebConsoleMessage;
235 using blink::WebData;
236 using blink::WebDataSource;
237 using blink::WebDocument;
238 using blink::WebDOMEvent;
239 using blink::WebDOMMessageEvent;
240 using blink::WebDragData;
241 using blink::WebDragOperation;
242 using blink::WebDragOperationsMask;
243 using blink::WebElement;
244 using blink::WebExternalPopupMenu;
245 using blink::WebExternalPopupMenuClient;
246 using blink::WebFileChooserCompletion;
247 using blink::WebFindOptions;
248 using blink::WebFormControlElement;
249 using blink::WebFormElement;
250 using blink::WebFrame;
251 using blink::WebGestureEvent;
252 using blink::WebHistoryItem;
253 using blink::WebHTTPBody;
254 using blink::WebIconURL;
255 using blink::WebImage;
256 using blink::WebInputElement;
257 using blink::WebInputEvent;
258 using blink::WebLocalFrame;
259 using blink::WebMediaPlayerAction;
260 using blink::WebMouseEvent;
261 using blink::WebNavigationPolicy;
262 using blink::WebNavigationType;
263 using blink::WebNode;
264 using blink::WebPageSerializer;
265 using blink::WebPageSerializerClient;
266 using blink::WebPeerConnection00Handler;
267 using blink::WebPeerConnection00HandlerClient;
268 using blink::WebPeerConnectionHandler;
269 using blink::WebPeerConnectionHandlerClient;
270 using blink::WebPluginAction;
271 using blink::WebPluginContainer;
272 using blink::WebPluginDocument;
273 using blink::WebPoint;
274 using blink::WebPopupMenuInfo;
275 using blink::WebRange;
276 using blink::WebRect;
277 using blink::WebReferrerPolicy;
278 using blink::WebScriptSource;
279 using blink::WebSearchableFormData;
280 using blink::WebSecurityOrigin;
281 using blink::WebSecurityPolicy;
282 using blink::WebSerializedScriptValue;
283 using blink::WebSettings;
284 using blink::WebSize;
285 using blink::WebSocketStreamHandle;
286 using blink::WebStorageNamespace;
287 using blink::WebStorageQuotaCallbacks;
288 using blink::WebStorageQuotaError;
289 using blink::WebStorageQuotaType;
290 using blink::WebString;
291 using blink::WebTextAffinity;
292 using blink::WebTextDirection;
293 using blink::WebTouchEvent;
294 using blink::WebURL;
295 using blink::WebURLError;
296 using blink::WebURLRequest;
297 using blink::WebURLResponse;
298 using blink::WebUserGestureIndicator;
299 using blink::WebVector;
300 using blink::WebView;
301 using blink::WebWidget;
302 using blink::WebWindowFeatures;
303 using base::Time;
304 using base::TimeDelta;
305 using webkit_glue::WebURLResponseExtraDataImpl;
306
307 #if defined(OS_ANDROID)
308 using blink::WebContentDetectionResult;
309 using blink::WebFloatPoint;
310 using blink::WebFloatRect;
311 using blink::WebHitTestResult;
312 #endif
313
314 namespace content {
315
316 //-----------------------------------------------------------------------------
317
318 typedef std::map<blink::WebView*, RenderViewImpl*> ViewMap;
319 static base::LazyInstance<ViewMap> g_view_map = LAZY_INSTANCE_INITIALIZER;
320 typedef std::map<int32, RenderViewImpl*> RoutingIDViewMap;
321 static base::LazyInstance<RoutingIDViewMap> g_routing_id_view_map =
322     LAZY_INSTANCE_INITIALIZER;
323
324 // Time, in seconds, we delay before sending content state changes (such as form
325 // state and scroll position) to the browser. We delay sending changes to avoid
326 // spamming the browser.
327 // To avoid having tab/session restore require sending a message to get the
328 // current content state during tab closing we use a shorter timeout for the
329 // foreground renderer. This means there is a small window of time from which
330 // content state is modified and not sent to session restore, but this is
331 // better than having to wake up all renderers during shutdown.
332 const int kDelaySecondsForContentStateSyncHidden = 5;
333 const int kDelaySecondsForContentStateSync = 1;
334
335 #if defined(OS_ANDROID)
336 // Delay between tapping in content and launching the associated android intent.
337 // Used to allow users see what has been recognized as content.
338 const size_t kContentIntentDelayMilliseconds = 700;
339 #endif
340
341 static RenderViewImpl* (*g_create_render_view_impl)(RenderViewImplParams*) =
342     NULL;
343
344 // static
345 bool RenderViewImpl::IsReload(const FrameMsg_Navigate_Params& params) {
346   return
347       params.navigation_type == FrameMsg_Navigate_Type::RELOAD ||
348       params.navigation_type == FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE ||
349       params.navigation_type ==
350           FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL;
351 }
352
353 // static
354 Referrer RenderViewImpl::GetReferrerFromRequest(
355     WebFrame* frame,
356     const WebURLRequest& request) {
357   return Referrer(GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
358                   request.referrerPolicy());
359 }
360
361 // static
362 WindowOpenDisposition RenderViewImpl::NavigationPolicyToDisposition(
363     WebNavigationPolicy policy) {
364   switch (policy) {
365     case blink::WebNavigationPolicyIgnore:
366       return IGNORE_ACTION;
367     case blink::WebNavigationPolicyDownload:
368       return SAVE_TO_DISK;
369     case blink::WebNavigationPolicyCurrentTab:
370       return CURRENT_TAB;
371     case blink::WebNavigationPolicyNewBackgroundTab:
372       return NEW_BACKGROUND_TAB;
373     case blink::WebNavigationPolicyNewForegroundTab:
374       return NEW_FOREGROUND_TAB;
375     case blink::WebNavigationPolicyNewWindow:
376       return NEW_WINDOW;
377     case blink::WebNavigationPolicyNewPopup:
378       return NEW_POPUP;
379   default:
380     NOTREACHED() << "Unexpected WebNavigationPolicy";
381     return IGNORE_ACTION;
382   }
383 }
384
385 // Returns true if the device scale is high enough that losing subpixel
386 // antialiasing won't have a noticeable effect on text quality.
387 static bool DeviceScaleEnsuresTextQuality(float device_scale_factor) {
388 #if defined(OS_ANDROID)
389   // On Android, we never have subpixel antialiasing.
390   return true;
391 #else
392   return device_scale_factor > 1.5f;
393 #endif
394
395 }
396
397 static bool ShouldUseFixedPositionCompositing(float device_scale_factor) {
398   // Compositing for fixed-position elements is dependent on
399   // device_scale_factor if no flag is set. http://crbug.com/172738
400   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
401
402   if (command_line.HasSwitch(switches::kDisableCompositingForFixedPosition))
403     return false;
404
405   if (command_line.HasSwitch(switches::kEnableCompositingForFixedPosition))
406     return true;
407
408   return DeviceScaleEnsuresTextQuality(device_scale_factor);
409 }
410
411 static bool ShouldUseAcceleratedCompositingForOverflowScroll(
412     float device_scale_factor) {
413   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
414
415   if (command_line.HasSwitch(switches::kDisableAcceleratedOverflowScroll))
416     return false;
417
418   if (command_line.HasSwitch(switches::kEnableAcceleratedOverflowScroll))
419     return true;
420
421   return DeviceScaleEnsuresTextQuality(device_scale_factor);
422 }
423
424 static bool ShouldUseCompositedScrollingForFrames(
425     float device_scale_factor) {
426   if (RenderThreadImpl::current() &&
427       !RenderThreadImpl::current()->is_lcd_text_enabled())
428     return true;
429
430   return DeviceScaleEnsuresTextQuality(device_scale_factor);
431 }
432
433 static bool ShouldUseTransitionCompositing(float device_scale_factor) {
434   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
435
436   if (command_line.HasSwitch(switches::kDisableCompositingForTransition))
437     return false;
438
439   if (command_line.HasSwitch(switches::kEnableCompositingForTransition))
440     return true;
441
442   // TODO(ajuma): Re-enable this by default for high-DPI once the problem
443   // of excessive layer promotion caused by overlap has been addressed.
444   // http://crbug.com/178119.
445   return false;
446 }
447
448 static bool ShouldUseAcceleratedFixedRootBackground(float device_scale_factor) {
449   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
450
451   if (command_line.HasSwitch(switches::kDisableAcceleratedFixedRootBackground))
452     return false;
453
454   if (command_line.HasSwitch(switches::kEnableAcceleratedFixedRootBackground))
455     return true;
456
457   return DeviceScaleEnsuresTextQuality(device_scale_factor);
458 }
459
460 static bool ShouldUseExpandedHeuristicsForGpuRasterization() {
461   return base::FieldTrialList::FindFullName(
462              "GpuRasterizationExpandedContentWhitelist") == "Enabled";
463 }
464
465 static FaviconURL::IconType ToFaviconType(blink::WebIconURL::Type type) {
466   switch (type) {
467     case blink::WebIconURL::TypeFavicon:
468       return FaviconURL::FAVICON;
469     case blink::WebIconURL::TypeTouch:
470       return FaviconURL::TOUCH_ICON;
471     case blink::WebIconURL::TypeTouchPrecomposed:
472       return FaviconURL::TOUCH_PRECOMPOSED_ICON;
473     case blink::WebIconURL::TypeInvalid:
474       return FaviconURL::INVALID_ICON;
475   }
476   return FaviconURL::INVALID_ICON;
477 }
478
479 static void ConvertToFaviconSizes(
480     const blink::WebVector<blink::WebSize>& web_sizes,
481     std::vector<gfx::Size>* sizes) {
482   DCHECK(sizes->empty());
483   sizes->reserve(web_sizes.size());
484   for (size_t i = 0; i < web_sizes.size(); ++i)
485     sizes->push_back(gfx::Size(web_sizes[i]));
486 }
487
488 ///////////////////////////////////////////////////////////////////////////////
489
490 struct RenderViewImpl::PendingFileChooser {
491   PendingFileChooser(const FileChooserParams& p, WebFileChooserCompletion* c)
492       : params(p),
493         completion(c) {
494   }
495   FileChooserParams params;
496   WebFileChooserCompletion* completion;  // MAY BE NULL to skip callback.
497 };
498
499 namespace {
500
501 class WebWidgetLockTarget : public MouseLockDispatcher::LockTarget {
502  public:
503   explicit WebWidgetLockTarget(blink::WebWidget* webwidget)
504       : webwidget_(webwidget) {}
505
506   virtual void OnLockMouseACK(bool succeeded) OVERRIDE {
507     if (succeeded)
508       webwidget_->didAcquirePointerLock();
509     else
510       webwidget_->didNotAcquirePointerLock();
511   }
512
513   virtual void OnMouseLockLost() OVERRIDE {
514     webwidget_->didLosePointerLock();
515   }
516
517   virtual bool HandleMouseLockedInputEvent(
518       const blink::WebMouseEvent &event) OVERRIDE {
519     // The WebWidget handles mouse lock in WebKit's handleInputEvent().
520     return false;
521   }
522
523  private:
524   blink::WebWidget* webwidget_;
525 };
526
527 bool TouchEnabled() {
528 // Based on the definition of chrome::kEnableTouchIcon.
529 #if defined(OS_ANDROID)
530   return true;
531 #else
532   return false;
533 #endif
534 }
535
536 WebDragData DropDataToWebDragData(const DropData& drop_data) {
537   std::vector<WebDragData::Item> item_list;
538
539   // These fields are currently unused when dragging into WebKit.
540   DCHECK(drop_data.download_metadata.empty());
541   DCHECK(drop_data.file_contents.empty());
542   DCHECK(drop_data.file_description_filename.empty());
543
544   if (!drop_data.text.is_null()) {
545     WebDragData::Item item;
546     item.storageType = WebDragData::Item::StorageTypeString;
547     item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeText);
548     item.stringData = drop_data.text.string();
549     item_list.push_back(item);
550   }
551
552   // TODO(dcheng): Do we need to distinguish between null and empty URLs? Is it
553   // meaningful to write an empty URL to the clipboard?
554   if (!drop_data.url.is_empty()) {
555     WebDragData::Item item;
556     item.storageType = WebDragData::Item::StorageTypeString;
557     item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeURIList);
558     item.stringData = WebString::fromUTF8(drop_data.url.spec());
559     item.title = drop_data.url_title;
560     item_list.push_back(item);
561   }
562
563   if (!drop_data.html.is_null()) {
564     WebDragData::Item item;
565     item.storageType = WebDragData::Item::StorageTypeString;
566     item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeHTML);
567     item.stringData = drop_data.html.string();
568     item.baseURL = drop_data.html_base_url;
569     item_list.push_back(item);
570   }
571
572   for (std::vector<ui::FileInfo>::const_iterator it =
573            drop_data.filenames.begin();
574        it != drop_data.filenames.end();
575        ++it) {
576     WebDragData::Item item;
577     item.storageType = WebDragData::Item::StorageTypeFilename;
578     item.filenameData = it->path.AsUTF16Unsafe();
579     item.displayNameData = it->display_name.AsUTF16Unsafe();
580     item_list.push_back(item);
581   }
582
583   for (std::vector<DropData::FileSystemFileInfo>::const_iterator it =
584            drop_data.file_system_files.begin();
585        it != drop_data.file_system_files.end();
586        ++it) {
587     WebDragData::Item item;
588     item.storageType = WebDragData::Item::StorageTypeFileSystemFile;
589     item.fileSystemURL = it->url;
590     item.fileSystemFileSize = it->size;
591     item_list.push_back(item);
592   }
593
594   for (std::map<base::string16, base::string16>::const_iterator it =
595            drop_data.custom_data.begin();
596        it != drop_data.custom_data.end();
597        ++it) {
598     WebDragData::Item item;
599     item.storageType = WebDragData::Item::StorageTypeString;
600     item.stringType = it->first;
601     item.stringData = it->second;
602     item_list.push_back(item);
603   }
604
605   WebDragData result;
606   result.initialize();
607   result.setItems(item_list);
608   result.setFilesystemId(drop_data.filesystem_id);
609   return result;
610 }
611
612 }  // namespace
613
614 RenderViewImpl::RenderViewImpl(RenderViewImplParams* params)
615     : RenderWidget(blink::WebPopupTypeNone,
616                    params->screen_info,
617                    params->swapped_out,
618                    params->hidden,
619                    params->never_visible),
620       webkit_preferences_(params->webkit_prefs),
621       send_content_state_immediately_(false),
622       enabled_bindings_(0),
623       send_preferred_size_changes_(false),
624       navigation_gesture_(NavigationGestureUnknown),
625       opened_by_user_gesture_(true),
626       opener_suppressed_(false),
627       suppress_dialogs_until_swap_out_(false),
628       page_id_(-1),
629       last_page_id_sent_to_browser_(-1),
630       next_page_id_(params->next_page_id),
631       history_list_offset_(-1),
632       history_list_length_(0),
633       frames_in_progress_(0),
634       target_url_status_(TARGET_NONE),
635       uses_temporary_zoom_level_(false),
636 #if defined(OS_ANDROID)
637       top_controls_constraints_(cc::BOTH),
638 #endif
639       has_scrolled_focused_editable_node_into_rect_(false),
640       push_messaging_dispatcher_(NULL),
641       speech_recognition_dispatcher_(NULL),
642       media_stream_dispatcher_(NULL),
643       browser_plugin_manager_(NULL),
644       devtools_agent_(NULL),
645       accessibility_mode_(AccessibilityModeOff),
646       renderer_accessibility_(NULL),
647       mouse_lock_dispatcher_(NULL),
648 #if defined(OS_ANDROID)
649       expected_content_intent_id_(0),
650 #endif
651 #if defined(OS_WIN)
652       focused_plugin_id_(-1),
653 #endif
654 #if defined(ENABLE_PLUGINS)
655       plugin_find_handler_(NULL),
656       focused_pepper_plugin_(NULL),
657       pepper_last_mouse_event_target_(NULL),
658 #endif
659       enumeration_completion_id_(0),
660       session_storage_namespace_id_(params->session_storage_namespace_id),
661       next_snapshot_id_(0) {
662 }
663
664 void RenderViewImpl::Initialize(RenderViewImplParams* params) {
665   routing_id_ = params->routing_id;
666   surface_id_ = params->surface_id;
667   if (params->opener_id != MSG_ROUTING_NONE && params->is_renderer_created)
668     opener_id_ = params->opener_id;
669
670   // Ensure we start with a valid next_page_id_ from the browser.
671   DCHECK_GE(next_page_id_, 0);
672
673   main_render_frame_.reset(RenderFrameImpl::Create(
674       this, params->main_frame_routing_id));
675   // The main frame WebLocalFrame object is closed by
676   // RenderFrameImpl::frameDetached().
677   WebLocalFrame* web_frame = WebLocalFrame::create(main_render_frame_.get());
678   main_render_frame_->SetWebFrame(web_frame);
679
680   if (params->proxy_routing_id != MSG_ROUTING_NONE) {
681     CHECK(params->swapped_out);
682     RenderFrameProxy* proxy =
683         RenderFrameProxy::CreateFrameProxy(params->proxy_routing_id,
684                                            params->main_frame_routing_id);
685     main_render_frame_->set_render_frame_proxy(proxy);
686   }
687
688   webwidget_ = WebView::create(this);
689   webwidget_mouse_lock_target_.reset(new WebWidgetLockTarget(webwidget_));
690
691   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
692
693   if (command_line.HasSwitch(switches::kStatsCollectionController))
694     stats_collection_observer_.reset(new StatsCollectionObserver(this));
695
696 #if defined(OS_ANDROID)
697   const std::string region_code =
698       command_line.HasSwitch(switches::kNetworkCountryIso)
699           ? command_line.GetSwitchValueASCII(switches::kNetworkCountryIso)
700           : net::android::GetTelephonyNetworkOperator();
701   content_detectors_.push_back(linked_ptr<ContentDetector>(
702       new AddressDetector()));
703   content_detectors_.push_back(linked_ptr<ContentDetector>(
704       new PhoneNumberDetector(region_code)));
705   content_detectors_.push_back(linked_ptr<ContentDetector>(
706       new EmailDetector()));
707 #endif
708
709   RenderThread::Get()->AddRoute(routing_id_, this);
710   // Take a reference on behalf of the RenderThread.  This will be balanced
711   // when we receive ViewMsg_ClosePage.
712   AddRef();
713   if (RenderThreadImpl::current()) {
714     RenderThreadImpl::current()->WidgetCreated();
715     if (is_hidden_)
716       RenderThreadImpl::current()->WidgetHidden();
717   }
718
719   // If this is a popup, we must wait for the CreatingNew_ACK message before
720   // completing initialization.  Otherwise, we can finish it now.
721   if (opener_id_ == MSG_ROUTING_NONE) {
722     did_show_ = true;
723     CompleteInit();
724   }
725
726   g_view_map.Get().insert(std::make_pair(webview(), this));
727   g_routing_id_view_map.Get().insert(std::make_pair(routing_id_, this));
728   webview()->setDeviceScaleFactor(device_scale_factor_);
729   webview()->settings()->setAcceleratedCompositingForFixedPositionEnabled(
730       ShouldUseFixedPositionCompositing(device_scale_factor_));
731   webview()->settings()->setAcceleratedCompositingForOverflowScrollEnabled(
732       ShouldUseAcceleratedCompositingForOverflowScroll(device_scale_factor_));
733   webview()->settings()->setAcceleratedCompositingForTransitionEnabled(
734       ShouldUseTransitionCompositing(device_scale_factor_));
735   webview()->settings()->setAcceleratedCompositingForFixedRootBackgroundEnabled(
736       ShouldUseAcceleratedFixedRootBackground(device_scale_factor_));
737   webview()->settings()->setCompositedScrollingForFramesEnabled(
738       ShouldUseCompositedScrollingForFrames(device_scale_factor_));
739   webview()->settings()->setUseExpandedHeuristicsForGpuRasterization(
740       ShouldUseExpandedHeuristicsForGpuRasterization());
741
742   ApplyWebPreferences(webkit_preferences_, webview());
743
744   webview()->settings()->setAllowConnectingInsecureWebSocket(
745       command_line.HasSwitch(switches::kAllowInsecureWebSocketFromHttpsOrigin));
746
747   webview()->setMainFrame(main_render_frame_->GetWebFrame());
748   main_render_frame_->Initialize();
749
750   if (switches::IsTouchDragDropEnabled())
751     webview()->settings()->setTouchDragDropEnabled(true);
752
753   if (switches::IsTouchEditingEnabled())
754     webview()->settings()->setTouchEditingEnabled(true);
755
756   if (!params->frame_name.empty())
757     webview()->mainFrame()->setName(params->frame_name);
758
759   // TODO(davidben): Move this state from Blink into content.
760   if (params->window_was_created_with_opener)
761     webview()->setOpenedByDOM();
762
763   OnSetRendererPrefs(params->renderer_prefs);
764
765 #if defined(ENABLE_WEBRTC)
766   if (!media_stream_dispatcher_)
767     media_stream_dispatcher_ = new MediaStreamDispatcher(this);
768 #endif
769
770   new MHTMLGenerator(this);
771 #if defined(OS_MACOSX)
772   new TextInputClientObserver(this);
773 #endif  // defined(OS_MACOSX)
774
775   // The next group of objects all implement RenderViewObserver, so are deleted
776   // along with the RenderView automatically.
777   devtools_agent_ = new DevToolsAgent(this);
778   if (RenderWidgetCompositor* rwc = compositor()) {
779     webview()->devToolsAgent()->setLayerTreeId(rwc->GetLayerTreeId());
780   }
781   mouse_lock_dispatcher_ = new RenderViewMouseLockDispatcher(this);
782
783   history_controller_.reset(new HistoryController(this));
784
785   // Create renderer_accessibility_ if needed.
786   OnSetAccessibilityMode(params->accessibility_mode);
787
788   new IdleUserDetector(this);
789
790   if (command_line.HasSwitch(switches::kDomAutomationController))
791     enabled_bindings_ |= BINDINGS_POLICY_DOM_AUTOMATION;
792   if (command_line.HasSwitch(switches::kStatsCollectionController))
793     enabled_bindings_ |= BINDINGS_POLICY_STATS_COLLECTION;
794
795   ProcessViewLayoutFlags(command_line);
796
797   GetContentClient()->renderer()->RenderViewCreated(this);
798
799   // If we have an opener_id but we weren't created by a renderer, then
800   // it's the browser asking us to set our opener to another RenderView.
801   if (params->opener_id != MSG_ROUTING_NONE && !params->is_renderer_created) {
802     RenderViewImpl* opener_view = FromRoutingID(params->opener_id);
803     if (opener_view)
804       webview()->mainFrame()->setOpener(opener_view->webview()->mainFrame());
805   }
806
807   // If we are initially swapped out, navigate to kSwappedOutURL.
808   // This ensures we are in a unique origin that others cannot script.
809   if (is_swapped_out_)
810     NavigateToSwappedOutURL(webview()->mainFrame());
811 }
812
813 RenderViewImpl::~RenderViewImpl() {
814   for (BitmapMap::iterator it = disambiguation_bitmaps_.begin();
815        it != disambiguation_bitmaps_.end();
816        ++it)
817     delete it->second;
818   history_page_ids_.clear();
819
820   base::debug::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_);
821
822   // If file chooser is still waiting for answer, dispatch empty answer.
823   while (!file_chooser_completions_.empty()) {
824     if (file_chooser_completions_.front()->completion) {
825       file_chooser_completions_.front()->completion->didChooseFile(
826           WebVector<WebString>());
827     }
828     file_chooser_completions_.pop_front();
829   }
830
831 #if defined(OS_ANDROID)
832   // The date/time picker client is both a scoped_ptr member of this class and
833   // a RenderViewObserver. Reset it to prevent double deletion.
834   date_time_picker_client_.reset();
835 #endif
836
837 #ifndef NDEBUG
838   // Make sure we are no longer referenced by the ViewMap or RoutingIDViewMap.
839   ViewMap* views = g_view_map.Pointer();
840   for (ViewMap::iterator it = views->begin(); it != views->end(); ++it)
841     DCHECK_NE(this, it->second) << "Failed to call Close?";
842   RoutingIDViewMap* routing_id_views = g_routing_id_view_map.Pointer();
843   for (RoutingIDViewMap::iterator it = routing_id_views->begin();
844        it != routing_id_views->end(); ++it)
845     DCHECK_NE(this, it->second) << "Failed to call Close?";
846 #endif
847
848   FOR_EACH_OBSERVER(RenderViewObserver, observers_, RenderViewGone());
849   FOR_EACH_OBSERVER(RenderViewObserver, observers_, OnDestruct());
850 }
851
852 /*static*/
853 RenderViewImpl* RenderViewImpl::FromWebView(WebView* webview) {
854   ViewMap* views = g_view_map.Pointer();
855   ViewMap::iterator it = views->find(webview);
856   return it == views->end() ? NULL : it->second;
857 }
858
859 /*static*/
860 RenderView* RenderView::FromWebView(blink::WebView* webview) {
861   return RenderViewImpl::FromWebView(webview);
862 }
863
864 /*static*/
865 RenderViewImpl* RenderViewImpl::FromRoutingID(int32 routing_id) {
866   RoutingIDViewMap* views = g_routing_id_view_map.Pointer();
867   RoutingIDViewMap::iterator it = views->find(routing_id);
868   return it == views->end() ? NULL : it->second;
869 }
870
871 /*static*/
872 RenderView* RenderView::FromRoutingID(int routing_id) {
873   return RenderViewImpl::FromRoutingID(routing_id);
874 }
875
876 /* static */
877 size_t RenderViewImpl::GetRenderViewCount() {
878   return g_view_map.Get().size();
879 }
880
881 /*static*/
882 void RenderView::ForEach(RenderViewVisitor* visitor) {
883   ViewMap* views = g_view_map.Pointer();
884   for (ViewMap::iterator it = views->begin(); it != views->end(); ++it) {
885     if (!visitor->Visit(it->second))
886       return;
887   }
888 }
889
890 /*static*/
891 RenderViewImpl* RenderViewImpl::Create(
892     int32 opener_id,
893     bool window_was_created_with_opener,
894     const RendererPreferences& renderer_prefs,
895     const WebPreferences& webkit_prefs,
896     int32 routing_id,
897     int32 main_frame_routing_id,
898     int32 surface_id,
899     int64 session_storage_namespace_id,
900     const base::string16& frame_name,
901     bool is_renderer_created,
902     bool swapped_out,
903     int32 proxy_routing_id,
904     bool hidden,
905     bool never_visible,
906     int32 next_page_id,
907     const blink::WebScreenInfo& screen_info,
908     AccessibilityMode accessibility_mode) {
909   DCHECK(routing_id != MSG_ROUTING_NONE);
910   RenderViewImplParams params(opener_id,
911                               window_was_created_with_opener,
912                               renderer_prefs,
913                               webkit_prefs,
914                               routing_id,
915                               main_frame_routing_id,
916                               surface_id,
917                               session_storage_namespace_id,
918                               frame_name,
919                               is_renderer_created,
920                               swapped_out,
921                               proxy_routing_id,
922                               hidden,
923                               never_visible,
924                               next_page_id,
925                               screen_info,
926                               accessibility_mode);
927   RenderViewImpl* render_view = NULL;
928   if (g_create_render_view_impl)
929     render_view = g_create_render_view_impl(&params);
930   else
931     render_view = new RenderViewImpl(&params);
932
933   render_view->Initialize(&params);
934   return render_view;
935 }
936
937 // static
938 void RenderViewImpl::InstallCreateHook(
939     RenderViewImpl* (*create_render_view_impl)(RenderViewImplParams*)) {
940   CHECK(!g_create_render_view_impl);
941   g_create_render_view_impl = create_render_view_impl;
942 }
943
944 void RenderViewImpl::AddObserver(RenderViewObserver* observer) {
945   observers_.AddObserver(observer);
946 }
947
948 void RenderViewImpl::RemoveObserver(RenderViewObserver* observer) {
949   observer->RenderViewGone();
950   observers_.RemoveObserver(observer);
951 }
952
953 blink::WebView* RenderViewImpl::webview() const {
954   return static_cast<blink::WebView*>(webwidget());
955 }
956
957 #if defined(ENABLE_PLUGINS)
958 void RenderViewImpl::PepperInstanceCreated(
959     PepperPluginInstanceImpl* instance) {
960   active_pepper_instances_.insert(instance);
961 }
962
963 void RenderViewImpl::PepperInstanceDeleted(
964     PepperPluginInstanceImpl* instance) {
965   active_pepper_instances_.erase(instance);
966
967   if (pepper_last_mouse_event_target_ == instance)
968     pepper_last_mouse_event_target_ = NULL;
969   if (focused_pepper_plugin_ == instance)
970     PepperFocusChanged(instance, false);
971 }
972
973 void RenderViewImpl::PepperFocusChanged(PepperPluginInstanceImpl* instance,
974                                         bool focused) {
975   if (focused)
976     focused_pepper_plugin_ = instance;
977   else if (focused_pepper_plugin_ == instance)
978     focused_pepper_plugin_ = NULL;
979
980   UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
981   UpdateSelectionBounds();
982 }
983
984 void RenderViewImpl::RegisterPluginDelegate(WebPluginDelegateProxy* delegate) {
985   plugin_delegates_.insert(delegate);
986   // If the renderer is visible, set initial visibility and focus state.
987   if (!is_hidden()) {
988 #if defined(OS_MACOSX)
989     delegate->SetContainerVisibility(true);
990     if (webview() && webview()->isActive())
991       delegate->SetWindowFocus(true);
992 #endif
993   }
994   // Plugins start assuming the content has focus (so that they work in
995   // environments where RenderView isn't hosting them), so we always have to
996   // set the initial state. See webplugin_delegate_impl.h for details.
997   delegate->SetContentAreaFocus(has_focus());
998 }
999
1000 void RenderViewImpl::UnregisterPluginDelegate(
1001     WebPluginDelegateProxy* delegate) {
1002   plugin_delegates_.erase(delegate);
1003 }
1004
1005 #if defined(OS_WIN)
1006 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1007   if (focused)
1008     focused_plugin_id_ = plugin_id;
1009   else
1010     focused_plugin_id_ = -1;
1011 }
1012 #endif
1013
1014 #if defined(OS_MACOSX)
1015 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1016   Send(new ViewHostMsg_PluginFocusChanged(routing_id(), focused, plugin_id));
1017 }
1018
1019 void RenderViewImpl::StartPluginIme() {
1020   IPC::Message* msg = new ViewHostMsg_StartPluginIme(routing_id());
1021   // This message can be sent during event-handling, and needs to be delivered
1022   // within that context.
1023   msg->set_unblock(true);
1024   Send(msg);
1025 }
1026 #endif  // defined(OS_MACOSX)
1027
1028 #endif  // ENABLE_PLUGINS
1029
1030 void RenderViewImpl::TransferActiveWheelFlingAnimation(
1031     const blink::WebActiveWheelFlingParameters& params) {
1032   if (webview())
1033     webview()->transferActiveWheelFlingAnimation(params);
1034 }
1035
1036 bool RenderViewImpl::HasIMETextFocus() {
1037   return GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE;
1038 }
1039
1040 bool RenderViewImpl::OnMessageReceived(const IPC::Message& message) {
1041   WebFrame* main_frame = webview() ? webview()->mainFrame() : NULL;
1042   if (main_frame)
1043     GetContentClient()->SetActiveURL(main_frame->document().url());
1044
1045   ObserverListBase<RenderViewObserver>::Iterator it(observers_);
1046   RenderViewObserver* observer;
1047   while ((observer = it.GetNext()) != NULL)
1048     if (observer->OnMessageReceived(message))
1049       return true;
1050
1051   bool handled = true;
1052   IPC_BEGIN_MESSAGE_MAP(RenderViewImpl, message)
1053     IPC_MESSAGE_HANDLER(InputMsg_ExecuteEditCommand, OnExecuteEditCommand)
1054     IPC_MESSAGE_HANDLER(InputMsg_MoveCaret, OnMoveCaret)
1055     IPC_MESSAGE_HANDLER(InputMsg_ScrollFocusedEditableNodeIntoRect,
1056                         OnScrollFocusedEditableNodeIntoRect)
1057     IPC_MESSAGE_HANDLER(InputMsg_SetEditCommandsForNextKeyEvent,
1058                         OnSetEditCommandsForNextKeyEvent)
1059     IPC_MESSAGE_HANDLER(ViewMsg_Stop, OnStop)
1060     IPC_MESSAGE_HANDLER(ViewMsg_CopyImageAt, OnCopyImageAt)
1061     IPC_MESSAGE_HANDLER(ViewMsg_SaveImageAt, OnSaveImageAt)
1062     IPC_MESSAGE_HANDLER(ViewMsg_Find, OnFind)
1063     IPC_MESSAGE_HANDLER(ViewMsg_StopFinding, OnStopFinding)
1064     IPC_MESSAGE_HANDLER(ViewMsg_Zoom, OnZoom)
1065     IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForLoadingURL,
1066                         OnSetZoomLevelForLoadingURL)
1067     IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForView,
1068                         OnSetZoomLevelForView)
1069     IPC_MESSAGE_HANDLER(ViewMsg_SetPageEncoding, OnSetPageEncoding)
1070     IPC_MESSAGE_HANDLER(ViewMsg_ResetPageEncodingToDefault,
1071                         OnResetPageEncodingToDefault)
1072     IPC_MESSAGE_HANDLER(ViewMsg_PostMessageEvent, OnPostMessageEvent)
1073     IPC_MESSAGE_HANDLER(DragMsg_TargetDragEnter, OnDragTargetDragEnter)
1074     IPC_MESSAGE_HANDLER(DragMsg_TargetDragOver, OnDragTargetDragOver)
1075     IPC_MESSAGE_HANDLER(DragMsg_TargetDragLeave, OnDragTargetDragLeave)
1076     IPC_MESSAGE_HANDLER(DragMsg_TargetDrop, OnDragTargetDrop)
1077     IPC_MESSAGE_HANDLER(DragMsg_SourceEnded, OnDragSourceEnded)
1078     IPC_MESSAGE_HANDLER(DragMsg_SourceSystemDragEnded,
1079                         OnDragSourceSystemDragEnded)
1080     IPC_MESSAGE_HANDLER(ViewMsg_AllowBindings, OnAllowBindings)
1081     IPC_MESSAGE_HANDLER(ViewMsg_SetInitialFocus, OnSetInitialFocus)
1082     IPC_MESSAGE_HANDLER(ViewMsg_UpdateTargetURL_ACK, OnUpdateTargetURLAck)
1083     IPC_MESSAGE_HANDLER(ViewMsg_UpdateWebPreferences, OnUpdateWebPreferences)
1084     IPC_MESSAGE_HANDLER(ViewMsg_EnumerateDirectoryResponse,
1085                         OnEnumerateDirectoryResponse)
1086     IPC_MESSAGE_HANDLER(ViewMsg_RunFileChooserResponse, OnFileChooserResponse)
1087     IPC_MESSAGE_HANDLER(ViewMsg_SuppressDialogsUntilSwapOut,
1088                         OnSuppressDialogsUntilSwapOut)
1089     IPC_MESSAGE_HANDLER(ViewMsg_ClosePage, OnClosePage)
1090     IPC_MESSAGE_HANDLER(ViewMsg_ThemeChanged, OnThemeChanged)
1091     IPC_MESSAGE_HANDLER(ViewMsg_MoveOrResizeStarted, OnMoveOrResizeStarted)
1092     IPC_MESSAGE_HANDLER(ViewMsg_ClearFocusedElement, OnClearFocusedElement)
1093     IPC_MESSAGE_HANDLER(ViewMsg_SetBackgroundOpaque, OnSetBackgroundOpaque)
1094     IPC_MESSAGE_HANDLER(ViewMsg_EnablePreferredSizeChangedMode,
1095                         OnEnablePreferredSizeChangedMode)
1096     IPC_MESSAGE_HANDLER(ViewMsg_EnableAutoResize, OnEnableAutoResize)
1097     IPC_MESSAGE_HANDLER(ViewMsg_DisableAutoResize, OnDisableAutoResize)
1098     IPC_MESSAGE_HANDLER(ViewMsg_DisableScrollbarsForSmallWindows,
1099                         OnDisableScrollbarsForSmallWindows)
1100     IPC_MESSAGE_HANDLER(ViewMsg_SetRendererPrefs, OnSetRendererPrefs)
1101     IPC_MESSAGE_HANDLER(ViewMsg_MediaPlayerActionAt, OnMediaPlayerActionAt)
1102     IPC_MESSAGE_HANDLER(ViewMsg_PluginActionAt, OnPluginActionAt)
1103     IPC_MESSAGE_HANDLER(ViewMsg_SetActive, OnSetActive)
1104     IPC_MESSAGE_HANDLER(ViewMsg_GetAllSavableResourceLinksForCurrentPage,
1105                         OnGetAllSavableResourceLinksForCurrentPage)
1106     IPC_MESSAGE_HANDLER(
1107         ViewMsg_GetSerializedHtmlDataForCurrentPageWithLocalLinks,
1108         OnGetSerializedHtmlDataForCurrentPageWithLocalLinks)
1109     IPC_MESSAGE_HANDLER(ViewMsg_ShowContextMenu, OnShowContextMenu)
1110     // TODO(viettrungluu): Move to a separate message filter.
1111     IPC_MESSAGE_HANDLER(ViewMsg_SetHistoryLengthAndPrune,
1112                         OnSetHistoryLengthAndPrune)
1113     IPC_MESSAGE_HANDLER(ViewMsg_EnableViewSourceMode, OnEnableViewSourceMode)
1114     IPC_MESSAGE_HANDLER(ViewMsg_SetAccessibilityMode, OnSetAccessibilityMode)
1115     IPC_MESSAGE_HANDLER(ViewMsg_DisownOpener, OnDisownOpener)
1116     IPC_MESSAGE_HANDLER(ViewMsg_ReleaseDisambiguationPopupBitmap,
1117                         OnReleaseDisambiguationPopupBitmap)
1118     IPC_MESSAGE_HANDLER(ViewMsg_WindowSnapshotCompleted,
1119                         OnWindowSnapshotCompleted)
1120     IPC_MESSAGE_HANDLER(ViewMsg_SelectWordAroundCaret, OnSelectWordAroundCaret)
1121 #if defined(OS_ANDROID)
1122     IPC_MESSAGE_HANDLER(InputMsg_ActivateNearestFindResult,
1123                         OnActivateNearestFindResult)
1124     IPC_MESSAGE_HANDLER(ViewMsg_FindMatchRects, OnFindMatchRects)
1125     IPC_MESSAGE_HANDLER(ViewMsg_SelectPopupMenuItems, OnSelectPopupMenuItems)
1126     IPC_MESSAGE_HANDLER(ViewMsg_UpdateTopControlsState,
1127                         OnUpdateTopControlsState)
1128     IPC_MESSAGE_HANDLER(ViewMsg_ExtractSmartClipData, OnExtractSmartClipData)
1129 #elif defined(OS_MACOSX)
1130     IPC_MESSAGE_HANDLER(ViewMsg_PluginImeCompositionCompleted,
1131                         OnPluginImeCompositionCompleted)
1132     IPC_MESSAGE_HANDLER(ViewMsg_SelectPopupMenuItem, OnSelectPopupMenuItem)
1133     IPC_MESSAGE_HANDLER(ViewMsg_SetInLiveResize, OnSetInLiveResize)
1134     IPC_MESSAGE_HANDLER(ViewMsg_SetWindowVisibility, OnSetWindowVisibility)
1135     IPC_MESSAGE_HANDLER(ViewMsg_WindowFrameChanged, OnWindowFrameChanged)
1136 #endif
1137     // Adding a new message? Add platform independent ones first, then put the
1138     // platform specific ones at the end.
1139
1140     // Have the super handle all other messages.
1141     IPC_MESSAGE_UNHANDLED(handled = RenderWidget::OnMessageReceived(message))
1142   IPC_END_MESSAGE_MAP()
1143
1144   return handled;
1145 }
1146
1147 void RenderViewImpl::OnSelectWordAroundCaret() {
1148   if (!webview())
1149     return;
1150
1151   handling_input_event_ = true;
1152   webview()->focusedFrame()->selectWordAroundCaret();
1153   handling_input_event_ = false;
1154 }
1155
1156 bool RenderViewImpl::IsBackForwardToStaleEntry(
1157     const FrameMsg_Navigate_Params& params,
1158     bool is_reload) {
1159   // Make sure this isn't a back/forward to an entry we have already cropped
1160   // or replaced from our history, before the browser knew about it.  If so,
1161   // a new navigation has committed in the mean time, and we can ignore this.
1162   bool is_back_forward = !is_reload && params.page_state.IsValid();
1163
1164   // Note: if the history_list_length_ is 0 for a back/forward, we must be
1165   // restoring from a previous session.  We'll update our state in OnNavigate.
1166   if (!is_back_forward || history_list_length_ <= 0)
1167     return false;
1168
1169   DCHECK_EQ(static_cast<int>(history_page_ids_.size()), history_list_length_);
1170
1171   // Check for whether the forward history has been cropped due to a recent
1172   // navigation the browser didn't know about.
1173   if (params.pending_history_list_offset >= history_list_length_)
1174     return true;
1175
1176   // Check for whether this entry has been replaced with a new one.
1177   int expected_page_id =
1178       history_page_ids_[params.pending_history_list_offset];
1179   if (expected_page_id > 0 && params.page_id != expected_page_id) {
1180     if (params.page_id < expected_page_id)
1181       return true;
1182
1183     // Otherwise we've removed an earlier entry and should have shifted all
1184     // entries left.  For now, it's ok to lazily update the list.
1185     // TODO(creis): Notify all live renderers when we remove entries from
1186     // the front of the list, so that we don't hit this case.
1187     history_page_ids_[params.pending_history_list_offset] = params.page_id;
1188   }
1189
1190   return false;
1191 }
1192
1193 // Stop loading the current page.
1194 void RenderViewImpl::OnStop() {
1195   if (webview())
1196     webview()->mainFrame()->stopLoading();
1197   FOR_EACH_OBSERVER(RenderViewObserver, observers_, OnStop());
1198   main_render_frame_->OnStop();
1199 }
1200
1201 void RenderViewImpl::OnCopyImageAt(int x, int y) {
1202   webview()->copyImageAt(WebPoint(x, y));
1203 }
1204
1205 void RenderViewImpl::OnSaveImageAt(int x, int y) {
1206   webview()->saveImageAt(WebPoint(x, y));
1207 }
1208
1209 void RenderViewImpl::OnUpdateTargetURLAck() {
1210   // Check if there is a targeturl waiting to be sent.
1211   if (target_url_status_ == TARGET_PENDING) {
1212     Send(new ViewHostMsg_UpdateTargetURL(routing_id_, page_id_,
1213                                          pending_target_url_));
1214   }
1215
1216   target_url_status_ = TARGET_NONE;
1217 }
1218
1219 void RenderViewImpl::OnExecuteEditCommand(const std::string& name,
1220     const std::string& value) {
1221   if (!webview() || !webview()->focusedFrame())
1222     return;
1223
1224   webview()->focusedFrame()->executeCommand(
1225       WebString::fromUTF8(name), WebString::fromUTF8(value));
1226 }
1227
1228 void RenderViewImpl::OnMoveCaret(const gfx::Point& point) {
1229   if (!webview())
1230     return;
1231
1232   Send(new ViewHostMsg_MoveCaret_ACK(routing_id_));
1233
1234   webview()->focusedFrame()->moveCaretSelection(point);
1235 }
1236
1237 void RenderViewImpl::OnScrollFocusedEditableNodeIntoRect(
1238     const gfx::Rect& rect) {
1239   if (has_scrolled_focused_editable_node_into_rect_ &&
1240       rect == rect_for_scrolled_focused_editable_node_) {
1241     return;
1242   }
1243
1244   blink::WebElement element = GetFocusedElement();
1245   if (!element.isNull() && IsEditableNode(element)) {
1246     rect_for_scrolled_focused_editable_node_ = rect;
1247     has_scrolled_focused_editable_node_into_rect_ = true;
1248     webview()->scrollFocusedNodeIntoRect(rect);
1249   }
1250 }
1251
1252 void RenderViewImpl::OnSetEditCommandsForNextKeyEvent(
1253     const EditCommands& edit_commands) {
1254   edit_commands_ = edit_commands;
1255 }
1256
1257 void RenderViewImpl::OnSetHistoryLengthAndPrune(int history_length,
1258                                                 int32 minimum_page_id) {
1259   DCHECK_GE(history_length, 0);
1260   DCHECK(history_list_offset_ == history_list_length_ - 1);
1261   DCHECK_GE(minimum_page_id, -1);
1262
1263   // Generate the new list.
1264   std::vector<int32> new_history_page_ids(history_length, -1);
1265   for (size_t i = 0; i < history_page_ids_.size(); ++i) {
1266     if (minimum_page_id >= 0 && history_page_ids_[i] < minimum_page_id)
1267       continue;
1268     new_history_page_ids.push_back(history_page_ids_[i]);
1269   }
1270   new_history_page_ids.swap(history_page_ids_);
1271
1272   // Update indexes.
1273   history_list_length_ = history_page_ids_.size();
1274   history_list_offset_ = history_list_length_ - 1;
1275 }
1276
1277
1278 void RenderViewImpl::OnSetInitialFocus(bool reverse) {
1279   if (!webview())
1280     return;
1281   webview()->setInitialFocus(reverse);
1282 }
1283
1284 #if defined(OS_MACOSX)
1285 void RenderViewImpl::OnSetInLiveResize(bool in_live_resize) {
1286   if (!webview())
1287     return;
1288   if (in_live_resize)
1289     webview()->willStartLiveResize();
1290   else
1291     webview()->willEndLiveResize();
1292 }
1293 #endif
1294
1295 ///////////////////////////////////////////////////////////////////////////////
1296
1297 // Sends the current history state to the browser so it will be saved before we
1298 // navigate to a new page.
1299 void RenderViewImpl::UpdateSessionHistory(WebFrame* frame) {
1300   // If we have a valid page ID at this point, then it corresponds to the page
1301   // we are navigating away from.  Otherwise, this is the first navigation, so
1302   // there is no past session history to record.
1303   if (page_id_ == -1)
1304     return;
1305   SendUpdateState(history_controller_->GetCurrentEntry());
1306 }
1307
1308 void RenderViewImpl::SendUpdateState(HistoryEntry* entry) {
1309   if (!entry)
1310     return;
1311
1312   // Don't send state updates for kSwappedOutURL.
1313   if (entry->root().urlString() == WebString::fromUTF8(kSwappedOutURL))
1314     return;
1315
1316   Send(new ViewHostMsg_UpdateState(
1317       routing_id_, page_id_, HistoryEntryToPageState(entry)));
1318 }
1319
1320 bool RenderViewImpl::SendAndRunNestedMessageLoop(IPC::SyncMessage* message) {
1321   // Before WebKit asks us to show an alert (etc.), it takes care of doing the
1322   // equivalent of WebView::willEnterModalLoop.  In the case of showModalDialog
1323   // it is particularly important that we do not call willEnterModalLoop as
1324   // that would defer resource loads for the dialog itself.
1325   if (RenderThreadImpl::current())  // Will be NULL during unit tests.
1326     RenderThreadImpl::current()->DoNotNotifyWebKitOfModalLoop();
1327
1328   message->EnableMessagePumping();  // Runs a nested message loop.
1329   return Send(message);
1330 }
1331
1332 void RenderViewImpl::GetWindowSnapshot(const WindowSnapshotCallback& callback) {
1333   int id = next_snapshot_id_++;
1334   pending_snapshots_.insert(std::make_pair(id, callback));
1335   ui::LatencyInfo latency_info;
1336   latency_info.AddLatencyNumber(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
1337                                 0,
1338                                 id);
1339   scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1340   if (RenderWidgetCompositor* rwc = compositor()) {
1341     latency_info_swap_promise_monitor =
1342         rwc->CreateLatencyInfoSwapPromiseMonitor(&latency_info).Pass();
1343   }
1344   ScheduleCompositeWithForcedRedraw();
1345 }
1346
1347 void RenderViewImpl::OnWindowSnapshotCompleted(const int snapshot_id,
1348     const gfx::Size& size, const std::vector<unsigned char>& png) {
1349
1350   // Any pending snapshots with a lower ID than the one received are considered
1351   // to be implicitly complete, and returned the same snapshot data.
1352   PendingSnapshotMap::iterator it = pending_snapshots_.begin();
1353   while(it != pending_snapshots_.end()) {
1354       if (it->first <= snapshot_id) {
1355         it->second.Run(size, png);
1356         pending_snapshots_.erase(it++);
1357       } else {
1358         ++it;
1359       }
1360   }
1361 }
1362
1363 // blink::WebViewClient ------------------------------------------------------
1364
1365 WebView* RenderViewImpl::createView(WebLocalFrame* creator,
1366                                     const WebURLRequest& request,
1367                                     const WebWindowFeatures& features,
1368                                     const WebString& frame_name,
1369                                     WebNavigationPolicy policy,
1370                                     bool suppress_opener) {
1371   ViewHostMsg_CreateWindow_Params params;
1372   params.opener_id = routing_id_;
1373   params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
1374   if (GetContentClient()->renderer()->AllowPopup())
1375     params.user_gesture = true;
1376   params.window_container_type = WindowFeaturesToContainerType(features);
1377   params.session_storage_namespace_id = session_storage_namespace_id_;
1378   if (frame_name != "_blank")
1379     params.frame_name = frame_name;
1380   params.opener_render_frame_id =
1381       RenderFrameImpl::FromWebFrame(creator)->GetRoutingID();
1382   params.opener_url = creator->document().url();
1383   params.opener_top_level_frame_url = creator->top()->document().url();
1384   GURL security_url(creator->document().securityOrigin().toString());
1385   if (!security_url.is_valid())
1386     security_url = GURL();
1387   params.opener_security_origin = security_url;
1388   params.opener_suppressed = suppress_opener;
1389   params.disposition = NavigationPolicyToDisposition(policy);
1390   if (!request.isNull()) {
1391     params.target_url = request.url();
1392     params.referrer = GetReferrerFromRequest(creator, request);
1393   }
1394   params.features = features;
1395
1396   for (size_t i = 0; i < features.additionalFeatures.size(); ++i)
1397     params.additional_features.push_back(features.additionalFeatures[i]);
1398
1399   int32 routing_id = MSG_ROUTING_NONE;
1400   int32 main_frame_routing_id = MSG_ROUTING_NONE;
1401   int32 surface_id = 0;
1402   int64 cloned_session_storage_namespace_id;
1403
1404   RenderThread::Get()->Send(
1405       new ViewHostMsg_CreateWindow(params,
1406                                    &routing_id,
1407                                    &main_frame_routing_id,
1408                                    &surface_id,
1409                                    &cloned_session_storage_namespace_id));
1410   if (routing_id == MSG_ROUTING_NONE)
1411     return NULL;
1412
1413   WebUserGestureIndicator::consumeUserGesture();
1414
1415   // While this view may be a background extension page, it can spawn a visible
1416   // render view. So we just assume that the new one is not another background
1417   // page instead of passing on our own value.
1418   // TODO(vangelis): Can we tell if the new view will be a background page?
1419   bool never_visible = false;
1420
1421   // The initial hidden state for the RenderViewImpl here has to match what the
1422   // browser will eventually decide for the given disposition. Since we have to
1423   // return from this call synchronously, we just have to make our best guess
1424   // and rely on the browser sending a WasHidden / WasShown message if it
1425   // disagrees.
1426   RenderViewImpl* view = RenderViewImpl::Create(
1427       routing_id_,
1428       true,  // window_was_created_with_opener
1429       renderer_preferences_,
1430       webkit_preferences_,
1431       routing_id,
1432       main_frame_routing_id,
1433       surface_id,
1434       cloned_session_storage_namespace_id,
1435       base::string16(),  // WebCore will take care of setting the correct name.
1436       true,              // is_renderer_created
1437       false,             // swapped_out
1438       MSG_ROUTING_NONE,  // proxy_routing_id
1439       params.disposition == NEW_BACKGROUND_TAB,  // hidden
1440       never_visible,
1441       1,  // next_page_id
1442       screen_info_,
1443       accessibility_mode_);
1444   view->opened_by_user_gesture_ = params.user_gesture;
1445
1446   // Record whether the creator frame is trying to suppress the opener field.
1447   view->opener_suppressed_ = params.opener_suppressed;
1448
1449   return view->webview();
1450 }
1451
1452 WebWidget* RenderViewImpl::createPopupMenu(blink::WebPopupType popup_type) {
1453   RenderWidget* widget =
1454       RenderWidget::Create(routing_id_, popup_type, screen_info_);
1455   if (!widget)
1456     return NULL;
1457   if (screen_metrics_emulator_) {
1458     widget->SetPopupOriginAdjustmentsForEmulation(
1459         screen_metrics_emulator_.get());
1460   }
1461   return widget->webwidget();
1462 }
1463
1464 WebExternalPopupMenu* RenderViewImpl::createExternalPopupMenu(
1465     const WebPopupMenuInfo& popup_menu_info,
1466     WebExternalPopupMenuClient* popup_menu_client) {
1467 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1468   // An IPC message is sent to the browser to build and display the actual
1469   // popup.  The user could have time to click a different select by the time
1470   // the popup is shown.  In that case external_popup_menu_ is non NULL.
1471   // By returning NULL in that case, we instruct WebKit to cancel that new
1472   // popup.  So from the user perspective, only the first one will show, and
1473   // will have to close the first one before another one can be shown.
1474   if (external_popup_menu_)
1475     return NULL;
1476   external_popup_menu_.reset(
1477       new ExternalPopupMenu(this, popup_menu_info, popup_menu_client));
1478   if (screen_metrics_emulator_) {
1479     SetExternalPopupOriginAdjustmentsForEmulation(
1480         external_popup_menu_.get(), screen_metrics_emulator_.get());
1481   }
1482   return external_popup_menu_.get();
1483 #else
1484   return NULL;
1485 #endif
1486 }
1487
1488 WebStorageNamespace* RenderViewImpl::createSessionStorageNamespace() {
1489   CHECK(session_storage_namespace_id_ != kInvalidSessionStorageNamespaceId);
1490   return new WebStorageNamespaceImpl(session_storage_namespace_id_);
1491 }
1492
1493 void RenderViewImpl::printPage(WebLocalFrame* frame) {
1494   FOR_EACH_OBSERVER(RenderViewObserver, observers_,
1495                     PrintPage(frame, handling_input_event_));
1496 }
1497
1498 bool RenderViewImpl::enumerateChosenDirectory(
1499     const WebString& path,
1500     WebFileChooserCompletion* chooser_completion) {
1501   int id = enumeration_completion_id_++;
1502   enumeration_completions_[id] = chooser_completion;
1503   return Send(new ViewHostMsg_EnumerateDirectory(
1504       routing_id_,
1505       id,
1506       base::FilePath::FromUTF16Unsafe(path)));
1507 }
1508
1509 void RenderViewImpl::FrameDidStartLoading(WebFrame* frame) {
1510   DCHECK_GE(frames_in_progress_, 0);
1511   if (frames_in_progress_ == 0)
1512     FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStartLoading());
1513   frames_in_progress_++;
1514 }
1515
1516 void RenderViewImpl::FrameDidStopLoading(WebFrame* frame) {
1517   // TODO(japhet): This should be a DCHECK, but the pdf plugin sometimes
1518   // calls DidStopLoading() without a matching DidStartLoading().
1519   if (frames_in_progress_ == 0)
1520     return;
1521   frames_in_progress_--;
1522   if (frames_in_progress_ == 0) {
1523     DidStopLoadingIcons();
1524     FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStopLoading());
1525   }
1526 }
1527
1528 void RenderViewImpl::didCancelCompositionOnSelectionChange() {
1529   Send(new ViewHostMsg_ImeCancelComposition(routing_id()));
1530 }
1531
1532 bool RenderViewImpl::handleCurrentKeyboardEvent() {
1533   if (edit_commands_.empty())
1534     return false;
1535
1536   WebFrame* frame = webview()->focusedFrame();
1537   if (!frame)
1538     return false;
1539
1540   EditCommands::iterator it = edit_commands_.begin();
1541   EditCommands::iterator end = edit_commands_.end();
1542
1543   bool did_execute_command = false;
1544   for (; it != end; ++it) {
1545     // In gtk and cocoa, it's possible to bind multiple edit commands to one
1546     // key (but it's the exception). Once one edit command is not executed, it
1547     // seems safest to not execute the rest.
1548     if (!frame->executeCommand(WebString::fromUTF8(it->name),
1549                                WebString::fromUTF8(it->value),
1550                                GetFocusedElement()))
1551       break;
1552     did_execute_command = true;
1553   }
1554
1555   return did_execute_command;
1556 }
1557
1558 bool RenderViewImpl::runFileChooser(
1559     const blink::WebFileChooserParams& params,
1560     WebFileChooserCompletion* chooser_completion) {
1561   // Do not open the file dialog in a hidden RenderView.
1562   if (is_hidden())
1563     return false;
1564   FileChooserParams ipc_params;
1565   if (params.directory)
1566     ipc_params.mode = FileChooserParams::UploadFolder;
1567   else if (params.multiSelect)
1568     ipc_params.mode = FileChooserParams::OpenMultiple;
1569   else if (params.saveAs)
1570     ipc_params.mode = FileChooserParams::Save;
1571   else
1572     ipc_params.mode = FileChooserParams::Open;
1573   ipc_params.title = params.title;
1574   ipc_params.default_file_name =
1575       base::FilePath::FromUTF16Unsafe(params.initialValue);
1576   ipc_params.accept_types.reserve(params.acceptTypes.size());
1577   for (size_t i = 0; i < params.acceptTypes.size(); ++i)
1578     ipc_params.accept_types.push_back(params.acceptTypes[i]);
1579 #if defined(OS_ANDROID)
1580   ipc_params.capture = params.useMediaCapture;
1581 #endif
1582
1583   return ScheduleFileChooser(ipc_params, chooser_completion);
1584 }
1585
1586 void RenderViewImpl::showValidationMessage(
1587     const blink::WebRect& anchor_in_root_view,
1588     const blink::WebString& main_text,
1589     const blink::WebString& sub_text,
1590     blink::WebTextDirection hint) {
1591   base::string16 wrapped_main_text = main_text;
1592   base::string16 wrapped_sub_text = sub_text;
1593   if (hint == blink::WebTextDirectionLeftToRight) {
1594     wrapped_main_text =
1595         base::i18n::GetDisplayStringInLTRDirectionality(wrapped_main_text);
1596     if (!wrapped_sub_text.empty()) {
1597       wrapped_sub_text =
1598           base::i18n::GetDisplayStringInLTRDirectionality(wrapped_sub_text);
1599     }
1600   } else if (hint == blink::WebTextDirectionRightToLeft
1601              && !base::i18n::IsRTL()) {
1602     base::i18n::WrapStringWithRTLFormatting(&wrapped_main_text);
1603     if (!wrapped_sub_text.empty()) {
1604       base::i18n::WrapStringWithRTLFormatting(&wrapped_sub_text);
1605     }
1606   }
1607   Send(new ViewHostMsg_ShowValidationMessage(
1608     routing_id(), anchor_in_root_view, wrapped_main_text, wrapped_sub_text));
1609 }
1610
1611 void RenderViewImpl::hideValidationMessage() {
1612   Send(new ViewHostMsg_HideValidationMessage(routing_id()));
1613 }
1614
1615 void RenderViewImpl::moveValidationMessage(
1616     const blink::WebRect& anchor_in_root_view) {
1617   Send(new ViewHostMsg_MoveValidationMessage(routing_id(),
1618                                              anchor_in_root_view));
1619 }
1620
1621 void RenderViewImpl::setStatusText(const WebString& text) {
1622 }
1623
1624 void RenderViewImpl::UpdateTargetURL(const GURL& url,
1625                                      const GURL& fallback_url) {
1626   GURL latest_url = url.is_empty() ? fallback_url : url;
1627   if (latest_url == target_url_)
1628     return;
1629
1630   // Tell the browser to display a destination link.
1631   if (target_url_status_ == TARGET_INFLIGHT ||
1632       target_url_status_ == TARGET_PENDING) {
1633     // If we have a request in-flight, save the URL to be sent when we
1634     // receive an ACK to the in-flight request. We can happily overwrite
1635     // any existing pending sends.
1636     pending_target_url_ = latest_url;
1637     target_url_status_ = TARGET_PENDING;
1638   } else {
1639     // URLs larger than |MaxURLChars()| cannot be sent through IPC -
1640     // see |ParamTraits<GURL>|.
1641     if (latest_url.possibly_invalid_spec().size() > GetMaxURLChars())
1642       latest_url = GURL();
1643     Send(new ViewHostMsg_UpdateTargetURL(routing_id_, page_id_, latest_url));
1644     target_url_ = latest_url;
1645     target_url_status_ = TARGET_INFLIGHT;
1646   }
1647 }
1648
1649 gfx::RectF RenderViewImpl::ClientRectToPhysicalWindowRect(
1650     const gfx::RectF& rect) const {
1651   gfx::RectF window_rect = rect;
1652   window_rect.Scale(device_scale_factor_ * webview()->pageScaleFactor());
1653   return window_rect;
1654 }
1655
1656 void RenderViewImpl::StartNavStateSyncTimerIfNecessary() {
1657   // No need to update state if no page has committed yet.
1658   if (page_id_ == -1)
1659     return;
1660
1661   int delay;
1662   if (send_content_state_immediately_)
1663     delay = 0;
1664   else if (is_hidden())
1665     delay = kDelaySecondsForContentStateSyncHidden;
1666   else
1667     delay = kDelaySecondsForContentStateSync;
1668
1669   if (nav_state_sync_timer_.IsRunning()) {
1670     // The timer is already running. If the delay of the timer maches the amount
1671     // we want to delay by, then return. Otherwise stop the timer so that it
1672     // gets started with the right delay.
1673     if (nav_state_sync_timer_.GetCurrentDelay().InSeconds() == delay)
1674       return;
1675     nav_state_sync_timer_.Stop();
1676   }
1677
1678   nav_state_sync_timer_.Start(FROM_HERE, TimeDelta::FromSeconds(delay), this,
1679                               &RenderViewImpl::SyncNavigationState);
1680 }
1681
1682 void RenderViewImpl::setMouseOverURL(const WebURL& url) {
1683   mouse_over_url_ = GURL(url);
1684   UpdateTargetURL(mouse_over_url_, focus_url_);
1685 }
1686
1687 void RenderViewImpl::setKeyboardFocusURL(const WebURL& url) {
1688   focus_url_ = GURL(url);
1689   UpdateTargetURL(focus_url_, mouse_over_url_);
1690 }
1691
1692 void RenderViewImpl::startDragging(WebLocalFrame* frame,
1693                                    const WebDragData& data,
1694                                    WebDragOperationsMask mask,
1695                                    const WebImage& image,
1696                                    const WebPoint& webImageOffset) {
1697   DropData drop_data(DropDataBuilder::Build(data));
1698   drop_data.referrer_policy = frame->document().referrerPolicy();
1699   gfx::Vector2d imageOffset(webImageOffset.x, webImageOffset.y);
1700   Send(new DragHostMsg_StartDragging(routing_id_,
1701                                      drop_data,
1702                                      mask,
1703                                      image.getSkBitmap(),
1704                                      imageOffset,
1705                                      possible_drag_event_info_));
1706 }
1707
1708 bool RenderViewImpl::acceptsLoadDrops() {
1709   return renderer_preferences_.can_accept_load_drops;
1710 }
1711
1712 void RenderViewImpl::focusNext() {
1713   Send(new ViewHostMsg_TakeFocus(routing_id_, false));
1714 }
1715
1716 void RenderViewImpl::focusPrevious() {
1717   Send(new ViewHostMsg_TakeFocus(routing_id_, true));
1718 }
1719
1720 void RenderViewImpl::focusedNodeChanged(const WebNode& node) {
1721   has_scrolled_focused_editable_node_into_rect_ = false;
1722
1723   Send(new ViewHostMsg_FocusedNodeChanged(routing_id_, IsEditableNode(node)));
1724
1725   FOR_EACH_OBSERVER(RenderViewObserver, observers_, FocusedNodeChanged(node));
1726 }
1727
1728 void RenderViewImpl::didUpdateLayout() {
1729   FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidUpdateLayout());
1730
1731   // We don't always want to set up a timer, only if we've been put in that
1732   // mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
1733   // message.
1734   if (!send_preferred_size_changes_ || !webview())
1735     return;
1736
1737   if (check_preferred_size_timer_.IsRunning())
1738     return;
1739   check_preferred_size_timer_.Start(FROM_HERE,
1740                                     TimeDelta::FromMilliseconds(0), this,
1741                                     &RenderViewImpl::CheckPreferredSize);
1742 }
1743
1744 void RenderViewImpl::navigateBackForwardSoon(int offset) {
1745   Send(new ViewHostMsg_GoToEntryAtOffset(routing_id_, offset));
1746 }
1747
1748 int RenderViewImpl::historyBackListCount() {
1749   return history_list_offset_ < 0 ? 0 : history_list_offset_;
1750 }
1751
1752 int RenderViewImpl::historyForwardListCount() {
1753   return history_list_length_ - historyBackListCount() - 1;
1754 }
1755
1756 void RenderViewImpl::postAccessibilityEvent(
1757     const WebAXObject& obj, blink::WebAXEvent event) {
1758   if (renderer_accessibility_) {
1759     renderer_accessibility_->HandleWebAccessibilityEvent(obj, event);
1760   }
1761 }
1762
1763 void RenderViewImpl::didUpdateInspectorSetting(const WebString& key,
1764                                            const WebString& value) {
1765   Send(new ViewHostMsg_UpdateInspectorSetting(routing_id_,
1766                                               key.utf8(),
1767                                               value.utf8()));
1768 }
1769
1770 // blink::WebWidgetClient ----------------------------------------------------
1771
1772 void RenderViewImpl::didFocus() {
1773   // TODO(jcivelli): when https://bugs.webkit.org/show_bug.cgi?id=33389 is fixed
1774   //                 we won't have to test for user gesture anymore and we can
1775   //                 move that code back to render_widget.cc
1776   if (WebUserGestureIndicator::isProcessingUserGesture() &&
1777       !RenderThreadImpl::current()->layout_test_mode()) {
1778     Send(new ViewHostMsg_Focus(routing_id_));
1779   }
1780 }
1781
1782 void RenderViewImpl::didBlur() {
1783   // TODO(jcivelli): see TODO above in didFocus().
1784   if (WebUserGestureIndicator::isProcessingUserGesture() &&
1785       !RenderThreadImpl::current()->layout_test_mode()) {
1786     Send(new ViewHostMsg_Blur(routing_id_));
1787   }
1788 }
1789
1790 // We are supposed to get a single call to Show for a newly created RenderView
1791 // that was created via RenderViewImpl::CreateWebView.  So, we wait until this
1792 // point to dispatch the ShowView message.
1793 //
1794 // This method provides us with the information about how to display the newly
1795 // created RenderView (i.e., as a blocked popup or as a new tab).
1796 //
1797 void RenderViewImpl::show(WebNavigationPolicy policy) {
1798   if (did_show_) {
1799     // When supports_multiple_windows is disabled, popups are reusing
1800     // the same view. In some scenarios, this makes WebKit to call show() twice.
1801     if (webkit_preferences_.supports_multiple_windows)
1802       NOTREACHED() << "received extraneous Show call";
1803     return;
1804   }
1805   did_show_ = true;
1806
1807   DCHECK(opener_id_ != MSG_ROUTING_NONE);
1808
1809   // Force new windows to a popup if they were not opened with a user gesture.
1810   if (!opened_by_user_gesture_) {
1811     // We exempt background tabs for compat with older versions of Chrome.
1812     // TODO(darin): This seems bogus.  These should have a user gesture, so
1813     // we probably don't need this check.
1814     if (policy != blink::WebNavigationPolicyNewBackgroundTab)
1815       policy = blink::WebNavigationPolicyNewPopup;
1816   }
1817
1818   // NOTE: initial_pos_ may still have its default values at this point, but
1819   // that's okay.  It'll be ignored if disposition is not NEW_POPUP, or the
1820   // browser process will impose a default position otherwise.
1821   Send(new ViewHostMsg_ShowView(opener_id_, routing_id_,
1822       NavigationPolicyToDisposition(policy), initial_pos_,
1823       opened_by_user_gesture_));
1824   SetPendingWindowRect(initial_pos_);
1825 }
1826
1827 void RenderViewImpl::runModal() {
1828   DCHECK(did_show_) << "should already have shown the view";
1829
1830   // Don't allow further dialogs if we are waiting to swap out, since the
1831   // PageGroupLoadDeferrer in our stack prevents it.
1832   if (suppress_dialogs_until_swap_out_)
1833     return;
1834
1835   // We must keep WebKit's shared timer running in this case in order to allow
1836   // showModalDialog to function properly.
1837   //
1838   // TODO(darin): WebKit should really be smarter about suppressing events and
1839   // timers so that we do not need to manage the shared timer in such a heavy
1840   // handed manner.
1841   //
1842   if (RenderThreadImpl::current())  // Will be NULL during unit tests.
1843     RenderThreadImpl::current()->DoNotSuspendWebKitSharedTimer();
1844
1845   SendAndRunNestedMessageLoop(new ViewHostMsg_RunModal(
1846       routing_id_, opener_id_));
1847 }
1848
1849 bool RenderViewImpl::enterFullScreen() {
1850   Send(new ViewHostMsg_ToggleFullscreen(routing_id_, true));
1851   return true;
1852 }
1853
1854 void RenderViewImpl::exitFullScreen() {
1855   Send(new ViewHostMsg_ToggleFullscreen(routing_id_, false));
1856 }
1857
1858 bool RenderViewImpl::requestPointerLock() {
1859   return mouse_lock_dispatcher_->LockMouse(webwidget_mouse_lock_target_.get());
1860 }
1861
1862 void RenderViewImpl::requestPointerUnlock() {
1863   mouse_lock_dispatcher_->UnlockMouse(webwidget_mouse_lock_target_.get());
1864 }
1865
1866 bool RenderViewImpl::isPointerLocked() {
1867   return mouse_lock_dispatcher_->IsMouseLockedTo(
1868       webwidget_mouse_lock_target_.get());
1869 }
1870
1871 void RenderViewImpl::didHandleGestureEvent(
1872     const WebGestureEvent& event,
1873     bool event_cancelled) {
1874   RenderWidget::didHandleGestureEvent(event, event_cancelled);
1875
1876   if (event.type != blink::WebGestureEvent::GestureTap)
1877     return;
1878
1879   blink::WebTextInputType text_input_type =
1880       GetWebView()->textInputInfo().type;
1881
1882   Send(new ViewHostMsg_FocusedNodeTouched(
1883       routing_id(), text_input_type != blink::WebTextInputTypeNone));
1884 }
1885
1886 void RenderViewImpl::initializeLayerTreeView() {
1887   RenderWidget::initializeLayerTreeView();
1888   RenderWidgetCompositor* rwc = compositor();
1889   if (!rwc)
1890     return;
1891   if (webview() && webview()->devToolsAgent())
1892     webview()->devToolsAgent()->setLayerTreeId(rwc->GetLayerTreeId());
1893
1894 #if !defined(OS_MACOSX)  // many events are unhandled - http://crbug.com/138003
1895   RenderThreadImpl* render_thread = RenderThreadImpl::current();
1896   // render_thread may be NULL in tests.
1897   InputHandlerManager* input_handler_manager =
1898       render_thread ? render_thread->input_handler_manager() : NULL;
1899   if (input_handler_manager) {
1900     input_handler_manager->AddInputHandler(
1901         routing_id_, rwc->GetInputHandler(), AsWeakPtr());
1902   }
1903 #endif
1904 }
1905
1906 // blink::WebFrameClient -----------------------------------------------------
1907
1908 void RenderViewImpl::Repaint(const gfx::Size& size) {
1909   OnRepaint(size);
1910 }
1911
1912 void RenderViewImpl::SetEditCommandForNextKeyEvent(const std::string& name,
1913                                                    const std::string& value) {
1914   EditCommands edit_commands;
1915   edit_commands.push_back(EditCommand(name, value));
1916   OnSetEditCommandsForNextKeyEvent(edit_commands);
1917 }
1918
1919 void RenderViewImpl::ClearEditCommands() {
1920   edit_commands_.clear();
1921 }
1922
1923 SSLStatus RenderViewImpl::GetSSLStatusOfFrame(blink::WebFrame* frame) const {
1924   std::string security_info;
1925   if (frame && frame->dataSource())
1926     security_info = frame->dataSource()->response().securityInfo();
1927
1928   SSLStatus ssl_status;
1929   DeserializeSecurityInfo(security_info,
1930                           &ssl_status.cert_id,
1931                           &ssl_status.cert_status,
1932                           &ssl_status.security_bits,
1933                           &ssl_status.connection_status,
1934                           &ssl_status.signed_certificate_timestamp_ids);
1935   return ssl_status;
1936 }
1937
1938 const std::string& RenderViewImpl::GetAcceptLanguages() const {
1939   return renderer_preferences_.accept_languages;
1940 }
1941
1942 void RenderViewImpl::didCreateDataSource(WebLocalFrame* frame,
1943                                          WebDataSource* ds) {
1944   bool content_initiated = !pending_navigation_params_.get();
1945
1946   // Make sure any previous redirect URLs end up in our new data source.
1947   if (pending_navigation_params_.get()) {
1948     for (std::vector<GURL>::const_iterator i =
1949              pending_navigation_params_->redirects.begin();
1950          i != pending_navigation_params_->redirects.end(); ++i) {
1951       ds->appendRedirect(*i);
1952     }
1953   }
1954
1955   DocumentState* document_state = DocumentState::FromDataSource(ds);
1956   if (!document_state) {
1957     document_state = new DocumentState;
1958     ds->setExtraData(document_state);
1959     if (!content_initiated)
1960       PopulateDocumentStateFromPending(document_state);
1961   }
1962
1963   // Carry over the user agent override flag, if it exists.
1964   if (content_initiated && webview() && webview()->mainFrame() &&
1965       webview()->mainFrame()->dataSource()) {
1966     DocumentState* old_document_state =
1967         DocumentState::FromDataSource(webview()->mainFrame()->dataSource());
1968     if (old_document_state) {
1969       InternalDocumentStateData* internal_data =
1970           InternalDocumentStateData::FromDocumentState(document_state);
1971       InternalDocumentStateData* old_internal_data =
1972           InternalDocumentStateData::FromDocumentState(old_document_state);
1973       internal_data->set_is_overriding_user_agent(
1974           old_internal_data->is_overriding_user_agent());
1975     }
1976   }
1977
1978   // The rest of RenderView assumes that a WebDataSource will always have a
1979   // non-null NavigationState.
1980   if (content_initiated) {
1981     document_state->set_navigation_state(
1982         NavigationState::CreateContentInitiated());
1983   } else {
1984     document_state->set_navigation_state(CreateNavigationStateFromPending());
1985     pending_navigation_params_.reset();
1986   }
1987
1988   // DocumentState::referred_by_prefetcher_ is true if we are
1989   // navigating from a page that used prefetching using a link on that
1990   // page.  We are early enough in the request process here that we
1991   // can still see the DocumentState of the previous page and set
1992   // this value appropriately.
1993   // TODO(gavinp): catch the important case of navigation in a new
1994   // renderer process.
1995   if (webview()) {
1996     if (WebFrame* old_frame = webview()->mainFrame()) {
1997       const WebURLRequest& original_request = ds->originalRequest();
1998       const GURL referrer(
1999           original_request.httpHeaderField(WebString::fromUTF8("Referer")));
2000       if (!referrer.is_empty() &&
2001           DocumentState::FromDataSource(
2002               old_frame->dataSource())->was_prefetcher()) {
2003         for (; old_frame; old_frame = old_frame->traverseNext(false)) {
2004           WebDataSource* old_frame_ds = old_frame->dataSource();
2005           if (old_frame_ds && referrer == GURL(old_frame_ds->request().url())) {
2006             document_state->set_was_referred_by_prefetcher(true);
2007             break;
2008           }
2009         }
2010       }
2011     }
2012   }
2013
2014   if (content_initiated) {
2015     const WebURLRequest& request = ds->request();
2016     switch (request.cachePolicy()) {
2017       case WebURLRequest::UseProtocolCachePolicy:  // normal load.
2018         document_state->set_load_type(DocumentState::LINK_LOAD_NORMAL);
2019         break;
2020       case WebURLRequest::ReloadIgnoringCacheData:  // reload.
2021       case WebURLRequest::ReloadBypassingCache:  // end-to-end reload.
2022         document_state->set_load_type(DocumentState::LINK_LOAD_RELOAD);
2023         break;
2024       case WebURLRequest::ReturnCacheDataElseLoad:  // allow stale data.
2025         document_state->set_load_type(
2026             DocumentState::LINK_LOAD_CACHE_STALE_OK);
2027         break;
2028       case WebURLRequest::ReturnCacheDataDontLoad:  // Don't re-post.
2029         document_state->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY);
2030         break;
2031       default:
2032         NOTREACHED();
2033     }
2034   }
2035
2036   FOR_EACH_OBSERVER(
2037       RenderViewObserver, observers_, DidCreateDataSource(frame, ds));
2038 }
2039
2040 void RenderViewImpl::PopulateDocumentStateFromPending(
2041     DocumentState* document_state) {
2042   const FrameMsg_Navigate_Params& params = *pending_navigation_params_.get();
2043   document_state->set_request_time(params.request_time);
2044
2045   InternalDocumentStateData* internal_data =
2046       InternalDocumentStateData::FromDocumentState(document_state);
2047
2048   if (!params.url.SchemeIs(url::kJavaScriptScheme) &&
2049       params.navigation_type == FrameMsg_Navigate_Type::RESTORE) {
2050     // We're doing a load of a page that was restored from the last session. By
2051     // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
2052     // can result in stale data for pages that are set to expire. We explicitly
2053     // override that by setting the policy here so that as necessary we load
2054     // from the network.
2055     //
2056     // TODO(davidben): Remove this in favor of passing a cache policy to the
2057     // loadHistoryItem call in OnNavigate. That requires not overloading
2058     // UseProtocolCachePolicy to mean both "normal load" and "determine cache
2059     // policy based on load type, etc".
2060     internal_data->set_cache_policy_override(
2061         WebURLRequest::UseProtocolCachePolicy);
2062   }
2063
2064   if (IsReload(params))
2065     document_state->set_load_type(DocumentState::RELOAD);
2066   else if (params.page_state.IsValid())
2067     document_state->set_load_type(DocumentState::HISTORY_LOAD);
2068   else
2069     document_state->set_load_type(DocumentState::NORMAL_LOAD);
2070
2071   internal_data->set_is_overriding_user_agent(params.is_overriding_user_agent);
2072   internal_data->set_must_reset_scroll_and_scale_state(
2073       params.navigation_type ==
2074           FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
2075   document_state->set_can_load_local_resources(params.can_load_local_resources);
2076 }
2077
2078 NavigationState* RenderViewImpl::CreateNavigationStateFromPending() {
2079   const FrameMsg_Navigate_Params& params = *pending_navigation_params_.get();
2080   NavigationState* navigation_state = NULL;
2081
2082   // A navigation resulting from loading a javascript URL should not be treated
2083   // as a browser initiated event.  Instead, we want it to look as if the page
2084   // initiated any load resulting from JS execution.
2085   if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
2086     navigation_state = NavigationState::CreateBrowserInitiated(
2087         params.page_id,
2088         params.pending_history_list_offset,
2089         params.should_clear_history_list,
2090         params.transition);
2091     navigation_state->set_should_replace_current_entry(
2092         params.should_replace_current_entry);
2093     navigation_state->set_transferred_request_child_id(
2094         params.transferred_request_child_id);
2095     navigation_state->set_transferred_request_request_id(
2096         params.transferred_request_request_id);
2097     navigation_state->set_allow_download(params.allow_download);
2098     navigation_state->set_extra_headers(params.extra_headers);
2099   } else {
2100     navigation_state = NavigationState::CreateContentInitiated();
2101   }
2102   return navigation_state;
2103 }
2104
2105 void RenderViewImpl::ProcessViewLayoutFlags(const CommandLine& command_line) {
2106   bool enable_viewport =
2107       command_line.HasSwitch(switches::kEnableViewport) ||
2108       command_line.HasSwitch(switches::kEnableViewportMeta);
2109
2110   // If viewport tag is enabled, then the WebKit side will take care
2111   // of setting the fixed layout size and page scale limits.
2112   if (enable_viewport)
2113     return;
2114
2115   // When navigating to a new page, reset the page scale factor to be 1.0.
2116   webview()->setInitialPageScaleOverride(1.f);
2117
2118   float maxPageScaleFactor =
2119       command_line.HasSwitch(switches::kEnablePinch) ? 4.f : 1.f ;
2120   webview()->setPageScaleFactorLimits(1, maxPageScaleFactor);
2121 }
2122
2123 void RenderViewImpl::didClearWindowObject(WebLocalFrame* frame) {
2124   FOR_EACH_OBSERVER(
2125       RenderViewObserver, observers_, DidClearWindowObject(frame));
2126
2127   if (enabled_bindings_& BINDINGS_POLICY_WEB_UI)
2128     WebUIExtension::Install(frame);
2129
2130   if (enabled_bindings_ & BINDINGS_POLICY_STATS_COLLECTION)
2131     StatsCollectionController::Install(frame);
2132
2133   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
2134
2135   if (command_line.HasSwitch(switches::kEnableSkiaBenchmarking))
2136     SkiaBenchmarking::Install(frame);
2137
2138   if (command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
2139     MemoryBenchmarkingExtension::Install(frame);
2140 }
2141
2142 void RenderViewImpl::didChangeIcon(WebLocalFrame* frame,
2143                                    WebIconURL::Type icon_type) {
2144   if (frame->parent())
2145     return;
2146
2147   if (!TouchEnabled() && icon_type != WebIconURL::TypeFavicon)
2148     return;
2149
2150   WebVector<WebIconURL> icon_urls = frame->iconURLs(icon_type);
2151   std::vector<FaviconURL> urls;
2152   for (size_t i = 0; i < icon_urls.size(); i++) {
2153     std::vector<gfx::Size> sizes;
2154     ConvertToFaviconSizes(icon_urls[i].sizes(), &sizes);
2155     urls.push_back(FaviconURL(
2156         icon_urls[i].iconURL(), ToFaviconType(icon_urls[i].iconType()), sizes));
2157   }
2158   SendUpdateFaviconURL(urls);
2159 }
2160
2161 void RenderViewImpl::didUpdateCurrentHistoryItem(WebLocalFrame* frame) {
2162   StartNavStateSyncTimerIfNecessary();
2163 }
2164
2165 void RenderViewImpl::CheckPreferredSize() {
2166   // We don't always want to send the change messages over IPC, only if we've
2167   // been put in that mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
2168   // message.
2169   if (!send_preferred_size_changes_ || !webview())
2170     return;
2171
2172   gfx::Size size = webview()->contentsPreferredMinimumSize();
2173
2174   // In the presence of zoom, these sizes are still reported as if unzoomed,
2175   // so we need to adjust.
2176   double zoom_factor = ZoomLevelToZoomFactor(webview()->zoomLevel());
2177   size.set_width(static_cast<int>(size.width() * zoom_factor));
2178   size.set_height(static_cast<int>(size.height() * zoom_factor));
2179
2180   if (size == preferred_size_)
2181     return;
2182
2183   preferred_size_ = size;
2184   Send(new ViewHostMsg_DidContentsPreferredSizeChange(routing_id_,
2185                                                       preferred_size_));
2186 }
2187
2188 BrowserPluginManager* RenderViewImpl::GetBrowserPluginManager() {
2189   if (!browser_plugin_manager_.get())
2190     browser_plugin_manager_ = BrowserPluginManager::Create(this);
2191   return browser_plugin_manager_.get();
2192 }
2193
2194 void RenderViewImpl::UpdateScrollState(WebFrame* frame) {
2195   Send(new ViewHostMsg_DidChangeScrollOffset(routing_id_));
2196 }
2197
2198 void RenderViewImpl::didChangeScrollOffset(WebLocalFrame* frame) {
2199   StartNavStateSyncTimerIfNecessary();
2200
2201   if (webview()->mainFrame() == frame)
2202     UpdateScrollState(frame);
2203
2204   FOR_EACH_OBSERVER(
2205       RenderViewObserver, observers_, DidChangeScrollOffset(frame));
2206 }
2207
2208 void RenderViewImpl::SendFindReply(int request_id,
2209                                    int match_count,
2210                                    int ordinal,
2211                                    const WebRect& selection_rect,
2212                                    bool final_status_update) {
2213   Send(new ViewHostMsg_Find_Reply(routing_id_,
2214                                   request_id,
2215                                   match_count,
2216                                   selection_rect,
2217                                   ordinal,
2218                                   final_status_update));
2219 }
2220
2221 blink::WebString RenderViewImpl::acceptLanguages() {
2222   return WebString::fromUTF8(renderer_preferences_.accept_languages);
2223 }
2224
2225 // blink::WebPageSerializerClient implementation ------------------------------
2226
2227 void RenderViewImpl::didSerializeDataForFrame(
2228     const WebURL& frame_url,
2229     const WebCString& data,
2230     WebPageSerializerClient::PageSerializationStatus status) {
2231   Send(new ViewHostMsg_SendSerializedHtmlData(
2232     routing_id(),
2233     frame_url,
2234     data.data(),
2235     static_cast<int32>(status)));
2236 }
2237
2238 // RenderView implementation ---------------------------------------------------
2239
2240 bool RenderViewImpl::Send(IPC::Message* message) {
2241   return RenderWidget::Send(message);
2242 }
2243
2244 RenderFrame* RenderViewImpl::GetMainRenderFrame() {
2245   return main_render_frame_.get();
2246 }
2247
2248 int RenderViewImpl::GetRoutingID() const {
2249   return routing_id_;
2250 }
2251
2252 int RenderViewImpl::GetPageId() const {
2253   return page_id_;
2254 }
2255
2256 gfx::Size RenderViewImpl::GetSize() const {
2257   return size();
2258 }
2259
2260 WebPreferences& RenderViewImpl::GetWebkitPreferences() {
2261   return webkit_preferences_;
2262 }
2263
2264 void RenderViewImpl::SetWebkitPreferences(const WebPreferences& preferences) {
2265   OnUpdateWebPreferences(preferences);
2266 }
2267
2268 blink::WebView* RenderViewImpl::GetWebView() {
2269   return webview();
2270 }
2271
2272 blink::WebElement RenderViewImpl::GetFocusedElement() const {
2273   if (!webview())
2274     return WebElement();
2275   WebFrame* focused_frame = webview()->focusedFrame();
2276   if (focused_frame) {
2277     WebDocument doc = focused_frame->document();
2278     if (!doc.isNull())
2279       return doc.focusedElement();
2280   }
2281
2282   return WebElement();
2283 }
2284
2285 bool RenderViewImpl::IsEditableNode(const WebNode& node) const {
2286   if (node.isNull())
2287     return false;
2288
2289   if (node.isContentEditable())
2290     return true;
2291
2292   if (node.isElementNode()) {
2293     const WebElement& element = node.toConst<WebElement>();
2294     if (element.isTextFormControlElement())
2295       return true;
2296
2297     // Also return true if it has an ARIA role of 'textbox'.
2298     for (unsigned i = 0; i < element.attributeCount(); ++i) {
2299       if (LowerCaseEqualsASCII(element.attributeLocalName(i), "role")) {
2300         if (LowerCaseEqualsASCII(element.attributeValue(i), "textbox"))
2301           return true;
2302         break;
2303       }
2304     }
2305   }
2306
2307   return false;
2308 }
2309
2310 bool RenderViewImpl::ShouldDisplayScrollbars(int width, int height) const {
2311   return (!send_preferred_size_changes_ ||
2312           (disable_scrollbars_size_limit_.width() <= width ||
2313            disable_scrollbars_size_limit_.height() <= height));
2314 }
2315
2316 int RenderViewImpl::GetEnabledBindings() const {
2317   return enabled_bindings_;
2318 }
2319
2320 bool RenderViewImpl::GetContentStateImmediately() const {
2321   return send_content_state_immediately_;
2322 }
2323
2324 blink::WebPageVisibilityState RenderViewImpl::GetVisibilityState() const {
2325   return visibilityState();
2326 }
2327
2328 void RenderViewImpl::DidStartLoading() {
2329   main_render_frame_->didStartLoading(true);
2330 }
2331
2332 void RenderViewImpl::DidStopLoading() {
2333   main_render_frame_->didStopLoading();
2334 }
2335
2336 void RenderViewImpl::SyncNavigationState() {
2337   if (!webview())
2338     return;
2339   SendUpdateState(history_controller_->GetCurrentEntry());
2340 }
2341
2342 blink::WebPlugin* RenderViewImpl::GetWebPluginForFind() {
2343   if (!webview())
2344     return NULL;
2345
2346   WebFrame* main_frame = webview()->mainFrame();
2347   if (main_frame->document().isPluginDocument())
2348     return webview()->mainFrame()->document().to<WebPluginDocument>().plugin();
2349
2350 #if defined(ENABLE_PLUGINS)
2351   if (plugin_find_handler_)
2352     return plugin_find_handler_->container()->plugin();
2353 #endif
2354
2355   return NULL;
2356 }
2357
2358 void RenderViewImpl::OnFind(int request_id,
2359                             const base::string16& search_text,
2360                             const WebFindOptions& options) {
2361   WebFrame* main_frame = webview()->mainFrame();
2362   blink::WebPlugin* plugin = GetWebPluginForFind();
2363   // Check if the plugin still exists in the document.
2364   if (plugin) {
2365     if (options.findNext) {
2366       // Just navigate back/forward.
2367       plugin->selectFindResult(options.forward);
2368     } else {
2369       if (!plugin->startFind(
2370           search_text, options.matchCase, request_id)) {
2371         // Send "no results".
2372         SendFindReply(request_id, 0, 0, gfx::Rect(), true);
2373       }
2374     }
2375     return;
2376   }
2377
2378   WebFrame* frame_after_main = main_frame->traverseNext(true);
2379   WebFrame* focused_frame = webview()->focusedFrame();
2380   WebFrame* search_frame = focused_frame;  // start searching focused frame.
2381
2382   bool multi_frame = (frame_after_main != main_frame);
2383
2384   // If we have multiple frames, we don't want to wrap the search within the
2385   // frame, so we check here if we only have main_frame in the chain.
2386   bool wrap_within_frame = !multi_frame;
2387
2388   WebRect selection_rect;
2389   bool result = false;
2390
2391   // If something is selected when we start searching it means we cannot just
2392   // increment the current match ordinal; we need to re-generate it.
2393   WebRange current_selection = focused_frame->selectionRange();
2394
2395   do {
2396     result = search_frame->find(
2397         request_id, search_text, options, wrap_within_frame, &selection_rect);
2398
2399     if (!result) {
2400       // don't leave text selected as you move to the next frame.
2401       search_frame->executeCommand(WebString::fromUTF8("Unselect"),
2402                                    GetFocusedElement());
2403
2404       // Find the next frame, but skip the invisible ones.
2405       do {
2406         // What is the next frame to search? (we might be going backwards). Note
2407         // that we specify wrap=true so that search_frame never becomes NULL.
2408         search_frame = options.forward ?
2409             search_frame->traverseNext(true) :
2410             search_frame->traversePrevious(true);
2411       } while (!search_frame->hasVisibleContent() &&
2412                search_frame != focused_frame);
2413
2414       // Make sure selection doesn't affect the search operation in new frame.
2415       search_frame->executeCommand(WebString::fromUTF8("Unselect"),
2416                                    GetFocusedElement());
2417
2418       // If we have multiple frames and we have wrapped back around to the
2419       // focused frame, we need to search it once more allowing wrap within
2420       // the frame, otherwise it will report 'no match' if the focused frame has
2421       // reported matches, but no frames after the focused_frame contain a
2422       // match for the search word(s).
2423       if (multi_frame && search_frame == focused_frame) {
2424         result = search_frame->find(
2425             request_id, search_text, options, true,  // Force wrapping.
2426             &selection_rect);
2427       }
2428     }
2429
2430     webview()->setFocusedFrame(search_frame);
2431   } while (!result && search_frame != focused_frame);
2432
2433   if (options.findNext && current_selection.isNull()) {
2434     // Force the main_frame to report the actual count.
2435     main_frame->increaseMatchCount(0, request_id);
2436   } else {
2437     // If nothing is found, set result to "0 of 0", otherwise, set it to
2438     // "-1 of 1" to indicate that we found at least one item, but we don't know
2439     // yet what is active.
2440     int ordinal = result ? -1 : 0;  // -1 here means, we might know more later.
2441     int match_count = result ? 1 : 0;  // 1 here means possibly more coming.
2442
2443     // If we find no matches then this will be our last status update.
2444     // Otherwise the scoping effort will send more results.
2445     bool final_status_update = !result;
2446
2447     SendFindReply(request_id, match_count, ordinal, selection_rect,
2448                   final_status_update);
2449
2450     // Scoping effort begins, starting with the mainframe.
2451     search_frame = main_frame;
2452
2453     main_frame->resetMatchCount();
2454
2455     do {
2456       // Cancel all old scoping requests before starting a new one.
2457       search_frame->cancelPendingScopingEffort();
2458
2459       // We don't start another scoping effort unless at least one match has
2460       // been found.
2461       if (result) {
2462         // Start new scoping request. If the scoping function determines that it
2463         // needs to scope, it will defer until later.
2464         search_frame->scopeStringMatches(request_id,
2465                                          search_text,
2466                                          options,
2467                                          true);  // reset the tickmarks
2468       }
2469
2470       // Iterate to the next frame. The frame will not necessarily scope, for
2471       // example if it is not visible.
2472       search_frame = search_frame->traverseNext(true);
2473     } while (search_frame != main_frame);
2474   }
2475 }
2476
2477 void RenderViewImpl::OnStopFinding(StopFindAction action) {
2478   WebView* view = webview();
2479   if (!view)
2480     return;
2481
2482   blink::WebPlugin* plugin = GetWebPluginForFind();
2483   if (plugin) {
2484     plugin->stopFind();
2485     return;
2486   }
2487
2488   bool clear_selection = action == STOP_FIND_ACTION_CLEAR_SELECTION;
2489   if (clear_selection) {
2490     view->focusedFrame()->executeCommand(WebString::fromUTF8("Unselect"),
2491                                          GetFocusedElement());
2492   }
2493
2494   WebFrame* frame = view->mainFrame();
2495   while (frame) {
2496     frame->stopFinding(clear_selection);
2497     frame = frame->traverseNext(false);
2498   }
2499
2500   if (action == STOP_FIND_ACTION_ACTIVATE_SELECTION) {
2501     WebFrame* focused_frame = view->focusedFrame();
2502     if (focused_frame) {
2503       WebDocument doc = focused_frame->document();
2504       if (!doc.isNull()) {
2505         WebElement element = doc.focusedElement();
2506         if (!element.isNull())
2507           element.simulateClick();
2508       }
2509     }
2510   }
2511 }
2512
2513 #if defined(OS_ANDROID)
2514 void RenderViewImpl::OnActivateNearestFindResult(int request_id,
2515                                                  float x, float y) {
2516   if (!webview())
2517       return;
2518
2519   WebFrame* main_frame = webview()->mainFrame();
2520   WebRect selection_rect;
2521   int ordinal = main_frame->selectNearestFindMatch(WebFloatPoint(x, y),
2522                                                    &selection_rect);
2523   if (ordinal == -1) {
2524     // Something went wrong, so send a no-op reply (force the main_frame to
2525     // report the current match count) in case the host is waiting for a
2526     // response due to rate-limiting).
2527     main_frame->increaseMatchCount(0, request_id);
2528     return;
2529   }
2530
2531   SendFindReply(request_id,
2532                 -1 /* number_of_matches */,
2533                 ordinal,
2534                 selection_rect,
2535                 true /* final_update */);
2536 }
2537
2538 void RenderViewImpl::OnFindMatchRects(int current_version) {
2539   if (!webview())
2540       return;
2541
2542   WebFrame* main_frame = webview()->mainFrame();
2543   std::vector<gfx::RectF> match_rects;
2544
2545   int rects_version = main_frame->findMatchMarkersVersion();
2546   if (current_version != rects_version) {
2547     WebVector<WebFloatRect> web_match_rects;
2548     main_frame->findMatchRects(web_match_rects);
2549     match_rects.reserve(web_match_rects.size());
2550     for (size_t i = 0; i < web_match_rects.size(); ++i)
2551       match_rects.push_back(gfx::RectF(web_match_rects[i]));
2552   }
2553
2554   gfx::RectF active_rect = main_frame->activeFindMatchRect();
2555   Send(new ViewHostMsg_FindMatchRects_Reply(routing_id_,
2556                                                rects_version,
2557                                                match_rects,
2558                                                active_rect));
2559 }
2560 #endif
2561
2562 void RenderViewImpl::OnZoom(PageZoom zoom) {
2563   if (!webview())  // Not sure if this can happen, but no harm in being safe.
2564     return;
2565
2566   webview()->hidePopups();
2567
2568   double old_zoom_level = webview()->zoomLevel();
2569   double zoom_level;
2570   if (zoom == PAGE_ZOOM_RESET) {
2571     zoom_level = 0;
2572   } else if (static_cast<int>(old_zoom_level) == old_zoom_level) {
2573     // Previous zoom level is a whole number, so just increment/decrement.
2574     zoom_level = old_zoom_level + zoom;
2575   } else {
2576     // Either the user hit the zoom factor limit and thus the zoom level is now
2577     // not a whole number, or a plugin changed it to a custom value.  We want
2578     // to go to the next whole number so that the user can always get back to
2579     // 100% with the keyboard/menu.
2580     if ((old_zoom_level > 1 && zoom > 0) ||
2581         (old_zoom_level < 1 && zoom < 0)) {
2582       zoom_level = static_cast<int>(old_zoom_level + zoom);
2583     } else {
2584       // We're going towards 100%, so first go to the next whole number.
2585       zoom_level = static_cast<int>(old_zoom_level);
2586     }
2587   }
2588   webview()->setZoomLevel(zoom_level);
2589   zoomLevelChanged();
2590 }
2591
2592 void RenderViewImpl::OnSetZoomLevelForLoadingURL(const GURL& url,
2593                                                  double zoom_level) {
2594 #if !defined(OS_ANDROID)
2595   // On Android, page zoom isn't used, and in case of WebView, text zoom is used
2596   // for legacy WebView text scaling emulation. Thus, the code that resets
2597   // the zoom level from this map will be effectively resetting text zoom level.
2598   host_zoom_levels_[url] = zoom_level;
2599 #endif
2600 }
2601
2602 void RenderViewImpl::OnSetZoomLevelForView(bool uses_temporary_zoom_level,
2603                                            double level) {
2604   uses_temporary_zoom_level_ = uses_temporary_zoom_level;
2605
2606   webview()->hidePopups();
2607   webview()->setZoomLevel(level);
2608 }
2609
2610 void RenderViewImpl::OnSetPageEncoding(const std::string& encoding_name) {
2611   webview()->setPageEncoding(WebString::fromUTF8(encoding_name));
2612 }
2613
2614 void RenderViewImpl::OnResetPageEncodingToDefault() {
2615   WebString no_encoding;
2616   webview()->setPageEncoding(no_encoding);
2617 }
2618
2619 void RenderViewImpl::OnPostMessageEvent(
2620     const ViewMsg_PostMessage_Params& params) {
2621   // TODO(nasko): Support sending to subframes.
2622   WebFrame* frame = webview()->mainFrame();
2623
2624   // Find the source frame if it exists.
2625   WebFrame* source_frame = NULL;
2626   if (params.source_routing_id != MSG_ROUTING_NONE) {
2627     RenderViewImpl* source_view = FromRoutingID(params.source_routing_id);
2628     if (source_view)
2629       source_frame = source_view->webview()->mainFrame();
2630   }
2631
2632   // If the message contained MessagePorts, create the corresponding endpoints.
2633   DCHECK_EQ(params.message_port_ids.size(), params.new_routing_ids.size());
2634   blink::WebMessagePortChannelArray channels(params.message_port_ids.size());
2635   for (size_t i = 0;
2636        i < params.message_port_ids.size() && i < params.new_routing_ids.size();
2637        ++i) {
2638     channels[i] =
2639         new WebMessagePortChannelImpl(params.new_routing_ids[i],
2640                                       params.message_port_ids[i],
2641                                       base::MessageLoopProxy::current().get());
2642   }
2643
2644   // Create an event with the message.  The final parameter to initMessageEvent
2645   // is the last event ID, which is not used with postMessage.
2646   WebDOMEvent event = frame->document().createEvent("MessageEvent");
2647   WebDOMMessageEvent msg_event = event.to<WebDOMMessageEvent>();
2648   msg_event.initMessageEvent("message",
2649                              // |canBubble| and |cancellable| are always false
2650                              false, false,
2651                              WebSerializedScriptValue::fromString(params.data),
2652                              params.source_origin, source_frame, "", channels);
2653
2654   // We must pass in the target_origin to do the security check on this side,
2655   // since it may have changed since the original postMessage call was made.
2656   WebSecurityOrigin target_origin;
2657   if (!params.target_origin.empty()) {
2658     target_origin =
2659         WebSecurityOrigin::createFromString(WebString(params.target_origin));
2660   }
2661   frame->dispatchMessageEventWithOriginCheck(target_origin, msg_event);
2662 }
2663
2664 void RenderViewImpl::OnAllowBindings(int enabled_bindings_flags) {
2665   if ((enabled_bindings_flags & BINDINGS_POLICY_WEB_UI) &&
2666       !(enabled_bindings_ & BINDINGS_POLICY_WEB_UI)) {
2667     // WebUIExtensionData deletes itself when we're destroyed.
2668     new WebUIExtensionData(this);
2669     // WebUIMojo deletes itself when we're destroyed.
2670     new WebUIMojo(this);
2671   }
2672
2673   enabled_bindings_ |= enabled_bindings_flags;
2674
2675   // Keep track of the total bindings accumulated in this process.
2676   RenderProcess::current()->AddBindings(enabled_bindings_flags);
2677 }
2678
2679 void RenderViewImpl::OnDragTargetDragEnter(const DropData& drop_data,
2680                                            const gfx::Point& client_point,
2681                                            const gfx::Point& screen_point,
2682                                            WebDragOperationsMask ops,
2683                                            int key_modifiers) {
2684   WebDragOperation operation = webview()->dragTargetDragEnter(
2685       DropDataToWebDragData(drop_data),
2686       client_point,
2687       screen_point,
2688       ops,
2689       key_modifiers);
2690
2691   Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
2692 }
2693
2694 void RenderViewImpl::OnDragTargetDragOver(const gfx::Point& client_point,
2695                                           const gfx::Point& screen_point,
2696                                           WebDragOperationsMask ops,
2697                                           int key_modifiers) {
2698   WebDragOperation operation = webview()->dragTargetDragOver(
2699       client_point,
2700       screen_point,
2701       ops,
2702       key_modifiers);
2703
2704   Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
2705 }
2706
2707 void RenderViewImpl::OnDragTargetDragLeave() {
2708   webview()->dragTargetDragLeave();
2709 }
2710
2711 void RenderViewImpl::OnDragTargetDrop(const gfx::Point& client_point,
2712                                       const gfx::Point& screen_point,
2713                                       int key_modifiers) {
2714   webview()->dragTargetDrop(client_point, screen_point, key_modifiers);
2715
2716   Send(new DragHostMsg_TargetDrop_ACK(routing_id_));
2717 }
2718
2719 void RenderViewImpl::OnDragSourceEnded(const gfx::Point& client_point,
2720                                        const gfx::Point& screen_point,
2721                                        WebDragOperation op) {
2722   webview()->dragSourceEndedAt(client_point, screen_point, op);
2723 }
2724
2725 void RenderViewImpl::OnDragSourceSystemDragEnded() {
2726   webview()->dragSourceSystemDragEnded();
2727 }
2728
2729 void RenderViewImpl::OnUpdateWebPreferences(const WebPreferences& prefs) {
2730   webkit_preferences_ = prefs;
2731   ApplyWebPreferences(webkit_preferences_, webview());
2732 }
2733
2734 void RenderViewImpl::OnEnumerateDirectoryResponse(
2735     int id,
2736     const std::vector<base::FilePath>& paths) {
2737   if (!enumeration_completions_[id])
2738     return;
2739
2740   WebVector<WebString> ws_file_names(paths.size());
2741   for (size_t i = 0; i < paths.size(); ++i)
2742     ws_file_names[i] = paths[i].AsUTF16Unsafe();
2743
2744   enumeration_completions_[id]->didChooseFile(ws_file_names);
2745   enumeration_completions_.erase(id);
2746 }
2747
2748 void RenderViewImpl::OnFileChooserResponse(
2749     const std::vector<ui::SelectedFileInfo>& files) {
2750   // This could happen if we navigated to a different page before the user
2751   // closed the chooser.
2752   if (file_chooser_completions_.empty())
2753     return;
2754
2755   // Convert Chrome's SelectedFileInfo list to WebKit's.
2756   WebVector<WebFileChooserCompletion::SelectedFileInfo> selected_files(
2757       files.size());
2758   for (size_t i = 0; i < files.size(); ++i) {
2759     WebFileChooserCompletion::SelectedFileInfo selected_file;
2760     selected_file.path = files[i].local_path.AsUTF16Unsafe();
2761     selected_file.displayName =
2762         base::FilePath(files[i].display_name).AsUTF16Unsafe();
2763     selected_files[i] = selected_file;
2764   }
2765
2766   if (file_chooser_completions_.front()->completion)
2767     file_chooser_completions_.front()->completion->didChooseFile(
2768         selected_files);
2769   file_chooser_completions_.pop_front();
2770
2771   // If there are more pending file chooser requests, schedule one now.
2772   if (!file_chooser_completions_.empty()) {
2773     Send(new ViewHostMsg_RunFileChooser(routing_id_,
2774         file_chooser_completions_.front()->params));
2775   }
2776 }
2777
2778 void RenderViewImpl::OnEnableAutoResize(const gfx::Size& min_size,
2779                                         const gfx::Size& max_size) {
2780   DCHECK(disable_scrollbars_size_limit_.IsEmpty());
2781   if (!webview())
2782     return;
2783   auto_resize_mode_ = true;
2784   webview()->enableAutoResizeMode(min_size, max_size);
2785 }
2786
2787 void RenderViewImpl::OnDisableAutoResize(const gfx::Size& new_size) {
2788   DCHECK(disable_scrollbars_size_limit_.IsEmpty());
2789   if (!webview())
2790     return;
2791   auto_resize_mode_ = false;
2792   webview()->disableAutoResizeMode();
2793
2794   if (!new_size.IsEmpty()) {
2795     Resize(new_size,
2796            physical_backing_size_,
2797            overdraw_bottom_height_,
2798            visible_viewport_size_,
2799            resizer_rect_,
2800            is_fullscreen_,
2801            NO_RESIZE_ACK);
2802   }
2803 }
2804
2805 void RenderViewImpl::OnEnablePreferredSizeChangedMode() {
2806   if (send_preferred_size_changes_)
2807     return;
2808   send_preferred_size_changes_ = true;
2809
2810   // Start off with an initial preferred size notification (in case
2811   // |didUpdateLayout| was already called).
2812   didUpdateLayout();
2813 }
2814
2815 void RenderViewImpl::OnDisableScrollbarsForSmallWindows(
2816     const gfx::Size& disable_scrollbar_size_limit) {
2817   disable_scrollbars_size_limit_ = disable_scrollbar_size_limit;
2818 }
2819
2820 void RenderViewImpl::OnSetRendererPrefs(
2821     const RendererPreferences& renderer_prefs) {
2822   double old_zoom_level = renderer_preferences_.default_zoom_level;
2823   std::string old_accept_languages = renderer_preferences_.accept_languages;
2824
2825   renderer_preferences_ = renderer_prefs;
2826   UpdateFontRenderingFromRendererPrefs();
2827
2828 #if defined(USE_DEFAULT_RENDER_THEME)
2829   if (renderer_prefs.use_custom_colors) {
2830     WebColorName name = blink::WebColorWebkitFocusRingColor;
2831     blink::setNamedColors(&name, &renderer_prefs.focus_ring_color, 1);
2832     blink::setCaretBlinkInterval(renderer_prefs.caret_blink_interval);
2833
2834     if (webview()) {
2835       webview()->setSelectionColors(
2836           renderer_prefs.active_selection_bg_color,
2837           renderer_prefs.active_selection_fg_color,
2838           renderer_prefs.inactive_selection_bg_color,
2839           renderer_prefs.inactive_selection_fg_color);
2840       webview()->themeChanged();
2841     }
2842   }
2843 #endif  // defined(USE_DEFAULT_RENDER_THEME)
2844
2845   if (RenderThreadImpl::current())  // Will be NULL during unit tests.
2846     RenderThreadImpl::current()->SetFlingCurveParameters(
2847         renderer_prefs.touchpad_fling_profile,
2848         renderer_prefs.touchscreen_fling_profile);
2849
2850   // If the zoom level for this page matches the old zoom default, and this
2851   // is not a plugin, update the zoom level to match the new default.
2852   if (webview() && !webview()->mainFrame()->document().isPluginDocument() &&
2853       !ZoomValuesEqual(old_zoom_level,
2854                        renderer_preferences_.default_zoom_level) &&
2855       ZoomValuesEqual(webview()->zoomLevel(), old_zoom_level)) {
2856     webview()->setZoomLevel(renderer_preferences_.default_zoom_level);
2857     zoomLevelChanged();
2858   }
2859
2860   if (webview() &&
2861       old_accept_languages != renderer_preferences_.accept_languages) {
2862     webview()->acceptLanguagesChanged();
2863   }
2864 }
2865
2866 void RenderViewImpl::OnMediaPlayerActionAt(const gfx::Point& location,
2867                                            const WebMediaPlayerAction& action) {
2868   if (webview())
2869     webview()->performMediaPlayerAction(action, location);
2870 }
2871
2872 void RenderViewImpl::OnOrientationChange() {
2873   // TODO(mlamouri): consumers of that event should be using DisplayObserver.
2874   FOR_EACH_OBSERVER(RenderViewObserver,
2875                     observers_,
2876                     OrientationChangeEvent());
2877
2878   webview()->mainFrame()->sendOrientationChangeEvent();
2879 }
2880
2881 void RenderViewImpl::OnPluginActionAt(const gfx::Point& location,
2882                                       const WebPluginAction& action) {
2883   if (webview())
2884     webview()->performPluginAction(action, location);
2885 }
2886
2887 void RenderViewImpl::OnGetAllSavableResourceLinksForCurrentPage(
2888     const GURL& page_url) {
2889   // Prepare list to storage all savable resource links.
2890   std::vector<GURL> resources_list;
2891   std::vector<GURL> referrer_urls_list;
2892   std::vector<blink::WebReferrerPolicy> referrer_policies_list;
2893   std::vector<GURL> frames_list;
2894   SavableResourcesResult result(&resources_list,
2895                                 &referrer_urls_list,
2896                                 &referrer_policies_list,
2897                                 &frames_list);
2898
2899   // webkit/ doesn't know about Referrer.
2900   if (!GetAllSavableResourceLinksForCurrentPage(
2901           webview(),
2902           page_url,
2903           &result,
2904           const_cast<const char**>(GetSavableSchemes()))) {
2905     // If something is wrong when collecting all savable resource links,
2906     // send empty list to embedder(browser) to tell it failed.
2907     referrer_urls_list.clear();
2908     referrer_policies_list.clear();
2909     resources_list.clear();
2910     frames_list.clear();
2911   }
2912
2913   std::vector<Referrer> referrers_list;
2914   CHECK_EQ(referrer_urls_list.size(), referrer_policies_list.size());
2915   for (unsigned i = 0; i < referrer_urls_list.size(); ++i) {
2916     referrers_list.push_back(
2917         Referrer(referrer_urls_list[i], referrer_policies_list[i]));
2918   }
2919
2920   // Send result of all savable resource links to embedder.
2921   Send(new ViewHostMsg_SendCurrentPageAllSavableResourceLinks(routing_id(),
2922                                                               resources_list,
2923                                                               referrers_list,
2924                                                               frames_list));
2925 }
2926
2927 void RenderViewImpl::OnGetSerializedHtmlDataForCurrentPageWithLocalLinks(
2928     const std::vector<GURL>& links,
2929     const std::vector<base::FilePath>& local_paths,
2930     const base::FilePath& local_directory_name) {
2931
2932   // Convert std::vector of GURLs to WebVector<WebURL>
2933   WebVector<WebURL> weburl_links(links);
2934
2935   // Convert std::vector of base::FilePath to WebVector<WebString>
2936   WebVector<WebString> webstring_paths(local_paths.size());
2937   for (size_t i = 0; i < local_paths.size(); i++)
2938     webstring_paths[i] = local_paths[i].AsUTF16Unsafe();
2939
2940   WebPageSerializer::serialize(webview()->mainFrame()->toWebLocalFrame(),
2941                                true,
2942                                this,
2943                                weburl_links,
2944                                webstring_paths,
2945                                local_directory_name.AsUTF16Unsafe());
2946 }
2947
2948 void RenderViewImpl::OnSuppressDialogsUntilSwapOut() {
2949   // Don't show any more dialogs until we finish OnSwapOut.
2950   suppress_dialogs_until_swap_out_ = true;
2951 }
2952
2953 void RenderViewImpl::NavigateToSwappedOutURL(blink::WebFrame* frame) {
2954   // We use loadRequest instead of loadHTMLString because the former commits
2955   // synchronously.  Otherwise a new navigation can interrupt the navigation
2956   // to kSwappedOutURL. If that happens to be to the page we had been
2957   // showing, then WebKit will never send a commit and we'll be left spinning.
2958   // TODO(creis): Until we move this to RenderFrame, we may call this from a
2959   // swapped out RenderFrame while our own is_swapped_out_ is false.
2960   RenderFrameImpl* rf = RenderFrameImpl::FromWebFrame(frame);
2961   CHECK(is_swapped_out_ || rf->is_swapped_out());
2962   GURL swappedOutURL(kSwappedOutURL);
2963   WebURLRequest request(swappedOutURL);
2964   frame->loadRequest(request);
2965 }
2966
2967 void RenderViewImpl::OnClosePage() {
2968   FOR_EACH_OBSERVER(RenderViewObserver, observers_, ClosePage());
2969   // TODO(creis): We'd rather use webview()->Close() here, but that currently
2970   // sets the WebView's delegate_ to NULL, preventing any JavaScript dialogs
2971   // in the onunload handler from appearing.  For now, we're bypassing that and
2972   // calling the FrameLoader's CloseURL method directly.  This should be
2973   // revisited to avoid having two ways to close a page.  Having a single way
2974   // to close that can run onunload is also useful for fixing
2975   // http://b/issue?id=753080.
2976   webview()->mainFrame()->dispatchUnloadEvent();
2977
2978   Send(new ViewHostMsg_ClosePage_ACK(routing_id_));
2979 }
2980
2981 void RenderViewImpl::OnThemeChanged() {
2982 #if defined(USE_AURA)
2983   // Aura doesn't care if we switch themes.
2984 #elif defined(OS_WIN)
2985   ui::NativeThemeWin::instance()->CloseHandles();
2986   if (webview())
2987     webview()->themeChanged();
2988 #else  // defined(OS_WIN)
2989   // TODO(port): we don't support theming on non-Windows platforms yet
2990   NOTIMPLEMENTED();
2991 #endif
2992 }
2993
2994 void RenderViewImpl::OnMoveOrResizeStarted() {
2995   if (webview())
2996     webview()->hidePopups();
2997 }
2998
2999 void RenderViewImpl::OnResize(const ViewMsg_Resize_Params& params) {
3000   if (webview()) {
3001     webview()->hidePopups();
3002     if (send_preferred_size_changes_) {
3003       webview()->mainFrame()->setCanHaveScrollbars(
3004           ShouldDisplayScrollbars(params.new_size.width(),
3005                                   params.new_size.height()));
3006     }
3007     UpdateScrollState(webview()->mainFrame());
3008   }
3009
3010   gfx::Size old_visible_viewport_size = visible_viewport_size_;
3011
3012   RenderWidget::OnResize(params);
3013
3014   if (old_visible_viewport_size != visible_viewport_size_)
3015     has_scrolled_focused_editable_node_into_rect_ = false;
3016 }
3017
3018 void RenderViewImpl::DidInitiatePaint() {
3019 #if defined(ENABLE_PLUGINS)
3020   // Notify all instances that we painted.  The same caveats apply as for
3021   // ViewFlushedPaint regarding instances closing themselves, so we take
3022   // similar precautions.
3023   PepperPluginSet plugins = active_pepper_instances_;
3024   for (PepperPluginSet::iterator i = plugins.begin(); i != plugins.end(); ++i) {
3025     if (active_pepper_instances_.find(*i) != active_pepper_instances_.end())
3026       (*i)->ViewInitiatedPaint();
3027   }
3028 #endif
3029 }
3030
3031 void RenderViewImpl::DidFlushPaint() {
3032 #if defined(ENABLE_PLUGINS)
3033   // Notify all instances that we flushed. This will call into the plugin, and
3034   // we it may ask to close itself as a result. This will, in turn, modify our
3035   // set, possibly invalidating the iterator. So we iterate on a copy that
3036   // won't change out from under us.
3037   PepperPluginSet plugins = active_pepper_instances_;
3038   for (PepperPluginSet::iterator i = plugins.begin(); i != plugins.end(); ++i) {
3039     // The copy above makes sure our iterator is never invalid if some plugins
3040     // are destroyed. But some plugin may decide to close all of its views in
3041     // response to a paint in one of them, so we need to make sure each one is
3042     // still "current" before using it.
3043     //
3044     // It's possible that a plugin was destroyed, but another one was created
3045     // with the same address. In this case, we'll call ViewFlushedPaint on that
3046     // new plugin. But that's OK for this particular case since we're just
3047     // notifying all of our instances that the view flushed, and the new one is
3048     // one of our instances.
3049     //
3050     // What about the case where a new one is created in a callback at a new
3051     // address and we don't issue the callback? We're still OK since this
3052     // callback is used for flush callbacks and we could not have possibly
3053     // started a new paint for the new plugin while processing a previous paint
3054     // for an existing one.
3055     if (active_pepper_instances_.find(*i) != active_pepper_instances_.end())
3056       (*i)->ViewFlushedPaint();
3057   }
3058 #endif
3059
3060   // If the RenderWidget is closing down then early-exit, otherwise we'll crash.
3061   // See crbug.com/112921.
3062   if (!webview())
3063     return;
3064
3065   WebFrame* main_frame = webview()->mainFrame();
3066
3067   // If we have a provisional frame we are between the start and commit stages
3068   // of loading and we don't want to save stats.
3069   if (!main_frame->provisionalDataSource()) {
3070     WebDataSource* ds = main_frame->dataSource();
3071     DocumentState* document_state = DocumentState::FromDataSource(ds);
3072     InternalDocumentStateData* data =
3073         InternalDocumentStateData::FromDocumentState(document_state);
3074     if (data->did_first_visually_non_empty_layout() &&
3075         !data->did_first_visually_non_empty_paint()) {
3076       data->set_did_first_visually_non_empty_paint(true);
3077       Send(new ViewHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_));
3078     }
3079
3080     // TODO(jar): The following code should all be inside a method, probably in
3081     // NavigatorState.
3082     Time now = Time::Now();
3083     if (document_state->first_paint_time().is_null()) {
3084       document_state->set_first_paint_time(now);
3085     }
3086     if (document_state->first_paint_after_load_time().is_null() &&
3087         !document_state->finish_load_time().is_null()) {
3088       document_state->set_first_paint_after_load_time(now);
3089     }
3090   }
3091 }
3092
3093 gfx::Vector2d RenderViewImpl::GetScrollOffset() {
3094   WebSize scroll_offset = webview()->mainFrame()->scrollOffset();
3095   return gfx::Vector2d(scroll_offset.width, scroll_offset.height);
3096 }
3097
3098 void RenderViewImpl::OnClearFocusedElement() {
3099   if (webview())
3100     webview()->clearFocusedElement();
3101 }
3102
3103 void RenderViewImpl::OnSetBackgroundOpaque(bool opaque) {
3104   if (webview())
3105     webview()->setIsTransparent(!opaque);
3106   if (compositor_)
3107     compositor_->setHasTransparentBackground(!opaque);
3108 }
3109
3110 void RenderViewImpl::OnSetAccessibilityMode(AccessibilityMode new_mode) {
3111   if (accessibility_mode_ == new_mode)
3112     return;
3113   accessibility_mode_ = new_mode;
3114   if (renderer_accessibility_) {
3115     delete renderer_accessibility_;
3116     renderer_accessibility_ = NULL;
3117   }
3118   if (accessibility_mode_ == AccessibilityModeOff)
3119     return;
3120
3121   if (accessibility_mode_ & AccessibilityModeFlagFullTree)
3122     renderer_accessibility_ = new RendererAccessibilityComplete(this);
3123 #if !defined(OS_ANDROID)
3124   else
3125     renderer_accessibility_ = new RendererAccessibilityFocusOnly(this);
3126 #endif
3127 }
3128
3129 void RenderViewImpl::OnSetActive(bool active) {
3130   if (webview())
3131     webview()->setIsActive(active);
3132
3133 #if defined(ENABLE_PLUGINS) && defined(OS_MACOSX)
3134   std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3135   for (plugin_it = plugin_delegates_.begin();
3136        plugin_it != plugin_delegates_.end(); ++plugin_it) {
3137     (*plugin_it)->SetWindowFocus(active);
3138   }
3139 #endif
3140 }
3141
3142 #if defined(OS_MACOSX)
3143 void RenderViewImpl::OnSetWindowVisibility(bool visible) {
3144 #if defined(ENABLE_PLUGINS)
3145   // Inform plugins that their container has changed visibility.
3146   std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3147   for (plugin_it = plugin_delegates_.begin();
3148        plugin_it != plugin_delegates_.end(); ++plugin_it) {
3149     (*plugin_it)->SetContainerVisibility(visible);
3150   }
3151 #endif
3152 }
3153
3154 void RenderViewImpl::OnWindowFrameChanged(const gfx::Rect& window_frame,
3155                                           const gfx::Rect& view_frame) {
3156 #if defined(ENABLE_PLUGINS)
3157   // Inform plugins that their window's frame has changed.
3158   std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3159   for (plugin_it = plugin_delegates_.begin();
3160        plugin_it != plugin_delegates_.end(); ++plugin_it) {
3161     (*plugin_it)->WindowFrameChanged(window_frame, view_frame);
3162   }
3163 #endif
3164 }
3165
3166 void RenderViewImpl::OnPluginImeCompositionCompleted(const base::string16& text,
3167                                                      int plugin_id) {
3168   // WebPluginDelegateProxy is responsible for figuring out if this event
3169   // applies to it or not, so inform all the delegates.
3170   std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3171   for (plugin_it = plugin_delegates_.begin();
3172        plugin_it != plugin_delegates_.end(); ++plugin_it) {
3173     (*plugin_it)->ImeCompositionCompleted(text, plugin_id);
3174   }
3175 }
3176 #endif  // OS_MACOSX
3177
3178 void RenderViewImpl::OnClose() {
3179   if (closing_)
3180     RenderThread::Get()->Send(new ViewHostMsg_Close_ACK(routing_id_));
3181   RenderWidget::OnClose();
3182 }
3183
3184 void RenderViewImpl::Close() {
3185   // We need to grab a pointer to the doomed WebView before we destroy it.
3186   WebView* doomed = webview();
3187   RenderWidget::Close();
3188   g_view_map.Get().erase(doomed);
3189   g_routing_id_view_map.Get().erase(routing_id_);
3190   RenderThread::Get()->Send(new ViewHostMsg_Close_ACK(routing_id_));
3191 }
3192
3193 void RenderViewImpl::DidHandleKeyEvent() {
3194   ClearEditCommands();
3195 }
3196
3197 bool RenderViewImpl::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
3198   possible_drag_event_info_.event_source =
3199       ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE;
3200   possible_drag_event_info_.event_location =
3201       gfx::Point(event.globalX, event.globalY);
3202
3203 #if defined(ENABLE_PLUGINS)
3204   // This method is called for every mouse event that the render view receives.
3205   // And then the mouse event is forwarded to WebKit, which dispatches it to the
3206   // event target. Potentially a Pepper plugin will receive the event.
3207   // In order to tell whether a plugin gets the last mouse event and which it
3208   // is, we set |pepper_last_mouse_event_target_| to NULL here. If a plugin gets
3209   // the event, it will notify us via DidReceiveMouseEvent() and set itself as
3210   // |pepper_last_mouse_event_target_|.
3211   pepper_last_mouse_event_target_ = NULL;
3212 #endif
3213
3214   // If the mouse is locked, only the current owner of the mouse lock can
3215   // process mouse events.
3216   return mouse_lock_dispatcher_->WillHandleMouseEvent(event);
3217 }
3218
3219 bool RenderViewImpl::WillHandleGestureEvent(
3220     const blink::WebGestureEvent& event) {
3221   possible_drag_event_info_.event_source =
3222       ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH;
3223   possible_drag_event_info_.event_location =
3224       gfx::Point(event.globalX, event.globalY);
3225   return false;
3226 }
3227
3228 void RenderViewImpl::DidHandleMouseEvent(const WebMouseEvent& event) {
3229   FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidHandleMouseEvent(event));
3230 }
3231
3232 void RenderViewImpl::DidHandleTouchEvent(const WebTouchEvent& event) {
3233   FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidHandleTouchEvent(event));
3234 }
3235
3236 bool RenderViewImpl::HasTouchEventHandlersAt(const gfx::Point& point) const {
3237   if (!webview())
3238     return false;
3239   return webview()->hasTouchEventHandlersAt(point);
3240 }
3241
3242 void RenderViewImpl::OnWasHidden() {
3243   RenderWidget::OnWasHidden();
3244
3245 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3246   RenderThreadImpl::current()->video_capture_impl_manager()->
3247       SuspendDevices(true);
3248   if (speech_recognition_dispatcher_)
3249     speech_recognition_dispatcher_->AbortAllRecognitions();
3250 #endif
3251
3252   if (webview())
3253     webview()->setVisibilityState(visibilityState(), false);
3254
3255 #if defined(ENABLE_PLUGINS)
3256   for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3257        i != active_pepper_instances_.end(); ++i)
3258     (*i)->PageVisibilityChanged(false);
3259
3260 #if defined(OS_MACOSX)
3261   // Inform NPAPI plugins that their container is no longer visible.
3262   std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3263   for (plugin_it = plugin_delegates_.begin();
3264        plugin_it != plugin_delegates_.end(); ++plugin_it) {
3265     (*plugin_it)->SetContainerVisibility(false);
3266   }
3267 #endif  // OS_MACOSX
3268 #endif // ENABLE_PLUGINS
3269 }
3270
3271 void RenderViewImpl::OnWasShown(bool needs_repainting) {
3272   RenderWidget::OnWasShown(needs_repainting);
3273
3274 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3275   RenderThreadImpl::current()->video_capture_impl_manager()->
3276       SuspendDevices(false);
3277 #endif
3278
3279   if (webview())
3280     webview()->setVisibilityState(visibilityState(), false);
3281
3282 #if defined(ENABLE_PLUGINS)
3283   for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3284        i != active_pepper_instances_.end(); ++i)
3285     (*i)->PageVisibilityChanged(true);
3286
3287 #if defined(OS_MACOSX)
3288   // Inform NPAPI plugins that their container is now visible.
3289   std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3290   for (plugin_it = plugin_delegates_.begin();
3291        plugin_it != plugin_delegates_.end(); ++plugin_it) {
3292     (*plugin_it)->SetContainerVisibility(true);
3293   }
3294 #endif  // OS_MACOSX
3295 #endif  // ENABLE_PLUGINS
3296 }
3297
3298 GURL RenderViewImpl::GetURLForGraphicsContext3D() {
3299   DCHECK(webview());
3300   if (webview()->mainFrame())
3301     return GURL(webview()->mainFrame()->document().url());
3302   else
3303     return GURL("chrome://gpu/RenderViewImpl::CreateGraphicsContext3D");
3304 }
3305
3306 void RenderViewImpl::OnSetFocus(bool enable) {
3307   RenderWidget::OnSetFocus(enable);
3308
3309 #if defined(ENABLE_PLUGINS)
3310   if (webview() && webview()->isActive()) {
3311     // Notify all NPAPI plugins.
3312     std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3313     for (plugin_it = plugin_delegates_.begin();
3314          plugin_it != plugin_delegates_.end(); ++plugin_it) {
3315 #if defined(OS_MACOSX)
3316       // RenderWidget's call to setFocus can cause the underlying webview's
3317       // activation state to change just like a call to setIsActive.
3318       if (enable)
3319         (*plugin_it)->SetWindowFocus(true);
3320 #endif
3321       (*plugin_it)->SetContentAreaFocus(enable);
3322     }
3323   }
3324   // Notify all Pepper plugins.
3325   for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3326        i != active_pepper_instances_.end(); ++i)
3327     (*i)->SetContentAreaFocus(enable);
3328 #endif
3329   // Notify all BrowserPlugins of the RenderView's focus state.
3330   if (browser_plugin_manager_.get())
3331     browser_plugin_manager_->UpdateFocusState();
3332 }
3333
3334 void RenderViewImpl::OnImeSetComposition(
3335     const base::string16& text,
3336     const std::vector<blink::WebCompositionUnderline>& underlines,
3337     int selection_start,
3338     int selection_end) {
3339 #if defined(ENABLE_PLUGINS)
3340   if (focused_pepper_plugin_) {
3341     focused_pepper_plugin_->render_frame()->OnImeSetComposition(
3342         text, underlines, selection_start, selection_end);
3343     return;
3344   }
3345
3346 #if defined(OS_WIN)
3347   // When a plug-in has focus, we create platform-specific IME data used by
3348   // our IME emulator and send it directly to the focused plug-in, i.e. we
3349   // bypass WebKit. (WebPluginDelegate dispatches this IME data only when its
3350   // instance ID is the same one as the specified ID.)
3351   if (focused_plugin_id_ >= 0) {
3352     std::vector<int> clauses;
3353     std::vector<int> target;
3354     for (size_t i = 0; i < underlines.size(); ++i) {
3355       clauses.push_back(underlines[i].startOffset);
3356       clauses.push_back(underlines[i].endOffset);
3357       if (underlines[i].thick) {
3358         target.clear();
3359         target.push_back(underlines[i].startOffset);
3360         target.push_back(underlines[i].endOffset);
3361       }
3362     }
3363     std::set<WebPluginDelegateProxy*>::iterator it;
3364     for (it = plugin_delegates_.begin(); it != plugin_delegates_.end(); ++it) {
3365       (*it)->ImeCompositionUpdated(text, clauses, target, selection_end,
3366                                    focused_plugin_id_);
3367     }
3368     return;
3369   }
3370 #endif  // OS_WIN
3371 #endif  // ENABLE_PLUGINS
3372   RenderWidget::OnImeSetComposition(text,
3373                                     underlines,
3374                                     selection_start,
3375                                     selection_end);
3376 }
3377
3378 void RenderViewImpl::OnImeConfirmComposition(
3379     const base::string16& text,
3380     const gfx::Range& replacement_range,
3381     bool keep_selection) {
3382 #if defined(ENABLE_PLUGINS)
3383   if (focused_pepper_plugin_) {
3384     focused_pepper_plugin_->render_frame()->OnImeConfirmComposition(
3385         text, replacement_range, keep_selection);
3386     return;
3387   }
3388 #if defined(OS_WIN)
3389   // Same as OnImeSetComposition(), we send the text from IMEs directly to
3390   // plug-ins. When we send IME text directly to plug-ins, we should not send
3391   // it to WebKit to prevent WebKit from controlling IMEs.
3392   // TODO(thakis): Honor |replacement_range| for plugins?
3393   if (focused_plugin_id_ >= 0) {
3394     std::set<WebPluginDelegateProxy*>::iterator it;
3395     for (it = plugin_delegates_.begin();
3396           it != plugin_delegates_.end(); ++it) {
3397       (*it)->ImeCompositionCompleted(text, focused_plugin_id_);
3398     }
3399     return;
3400   }
3401 #endif  // OS_WIN
3402 #endif  // ENABLE_PLUGINS
3403   if (replacement_range.IsValid() && webview()) {
3404     // Select the text in |replacement_range|, it will then be replaced by
3405     // text added by the call to RenderWidget::OnImeConfirmComposition().
3406     if (WebLocalFrame* frame = webview()->focusedFrame()->toWebLocalFrame()) {
3407       WebRange webrange = WebRange::fromDocumentRange(
3408           frame, replacement_range.start(), replacement_range.length());
3409       if (!webrange.isNull())
3410         frame->selectRange(webrange);
3411     }
3412   }
3413   RenderWidget::OnImeConfirmComposition(text,
3414                                         replacement_range,
3415                                         keep_selection);
3416 }
3417
3418 void RenderViewImpl::SetDeviceScaleFactor(float device_scale_factor) {
3419   RenderWidget::SetDeviceScaleFactor(device_scale_factor);
3420   if (webview()) {
3421     webview()->setDeviceScaleFactor(device_scale_factor);
3422     webview()->settings()->setAcceleratedCompositingForFixedPositionEnabled(
3423         ShouldUseFixedPositionCompositing(device_scale_factor_));
3424     webview()->settings()->setAcceleratedCompositingForOverflowScrollEnabled(
3425         ShouldUseAcceleratedCompositingForOverflowScroll(device_scale_factor_));
3426     webview()->settings()->setAcceleratedCompositingForTransitionEnabled(
3427         ShouldUseTransitionCompositing(device_scale_factor_));
3428     webview()->settings()->
3429         setAcceleratedCompositingForFixedRootBackgroundEnabled(
3430             ShouldUseAcceleratedFixedRootBackground(device_scale_factor_));
3431     webview()->settings()->setCompositedScrollingForFramesEnabled(
3432         ShouldUseCompositedScrollingForFrames(device_scale_factor_));
3433   }
3434   if (auto_resize_mode_)
3435     AutoResizeCompositor();
3436
3437   if (browser_plugin_manager_.get())
3438     browser_plugin_manager_->UpdateDeviceScaleFactor(device_scale_factor_);
3439 }
3440
3441 bool RenderViewImpl::SetDeviceColorProfile(
3442     const std::vector<char>& profile) {
3443   bool changed = RenderWidget::SetDeviceColorProfile(profile);
3444   if (changed && webview()) {
3445     // TODO(noel): notify the webview() of the color profile change so it
3446     // can update and repaint all color profiled page elements.
3447   }
3448   return changed;
3449 }
3450
3451 ui::TextInputType RenderViewImpl::GetTextInputType() {
3452 #if defined(ENABLE_PLUGINS)
3453   if (focused_pepper_plugin_)
3454     return focused_pepper_plugin_->text_input_type();
3455 #endif
3456   return RenderWidget::GetTextInputType();
3457 }
3458
3459 void RenderViewImpl::GetSelectionBounds(gfx::Rect* start, gfx::Rect* end) {
3460 #if defined(ENABLE_PLUGINS)
3461   if (focused_pepper_plugin_) {
3462     // TODO(kinaba) http://crbug.com/101101
3463     // Current Pepper IME API does not handle selection bounds. So we simply
3464     // use the caret position as an empty range for now. It will be updated
3465     // after Pepper API equips features related to surrounding text retrieval.
3466     gfx::Rect caret = focused_pepper_plugin_->GetCaretBounds();
3467     *start = caret;
3468     *end = caret;
3469     return;
3470   }
3471 #endif
3472   RenderWidget::GetSelectionBounds(start, end);
3473 }
3474
3475 #if defined(OS_MACOSX) || defined(USE_AURA)
3476 void RenderViewImpl::GetCompositionCharacterBounds(
3477     std::vector<gfx::Rect>* bounds) {
3478   DCHECK(bounds);
3479   bounds->clear();
3480
3481 #if defined(ENABLE_PLUGINS)
3482   if (focused_pepper_plugin_) {
3483     return;
3484   }
3485 #endif
3486
3487   if (!webview())
3488     return;
3489   size_t start_offset = 0;
3490   size_t character_count = 0;
3491   if (!webview()->compositionRange(&start_offset, &character_count))
3492     return;
3493   if (character_count == 0)
3494     return;
3495
3496   blink::WebFrame* frame = webview()->focusedFrame();
3497   if (!frame)
3498     return;
3499
3500   bounds->reserve(character_count);
3501   blink::WebRect webrect;
3502   for (size_t i = 0; i < character_count; ++i) {
3503     if (!frame->firstRectForCharacterRange(start_offset + i, 1, webrect)) {
3504       DLOG(ERROR) << "Could not retrieve character rectangle at " << i;
3505       bounds->clear();
3506       return;
3507     }
3508     bounds->push_back(webrect);
3509   }
3510 }
3511
3512 void RenderViewImpl::GetCompositionRange(gfx::Range* range) {
3513 #if defined(ENABLE_PLUGINS)
3514   if (focused_pepper_plugin_) {
3515     return;
3516   }
3517 #endif
3518   RenderWidget::GetCompositionRange(range);
3519 }
3520 #endif
3521
3522 bool RenderViewImpl::CanComposeInline() {
3523 #if defined(ENABLE_PLUGINS)
3524   if (focused_pepper_plugin_)
3525     return focused_pepper_plugin_->IsPluginAcceptingCompositionEvents();
3526 #endif
3527   return true;
3528 }
3529
3530 void RenderViewImpl::InstrumentWillBeginFrame(int frame_id) {
3531   if (!webview())
3532     return;
3533   if (!webview()->devToolsAgent())
3534     return;
3535   webview()->devToolsAgent()->didBeginFrame(frame_id);
3536 }
3537
3538 void RenderViewImpl::InstrumentDidBeginFrame() {
3539   if (!webview())
3540     return;
3541   if (!webview()->devToolsAgent())
3542     return;
3543   // TODO(jamesr/caseq): Decide if this needs to be renamed.
3544   webview()->devToolsAgent()->didComposite();
3545 }
3546
3547 void RenderViewImpl::InstrumentDidCancelFrame() {
3548   if (!webview())
3549     return;
3550   if (!webview()->devToolsAgent())
3551     return;
3552   webview()->devToolsAgent()->didCancelFrame();
3553 }
3554
3555 void RenderViewImpl::InstrumentWillComposite() {
3556   if (!webview())
3557     return;
3558   if (!webview()->devToolsAgent())
3559     return;
3560   webview()->devToolsAgent()->willComposite();
3561 }
3562
3563 void RenderViewImpl::SetScreenMetricsEmulationParameters(
3564     float device_scale_factor,
3565     const gfx::Point& root_layer_offset,
3566     float root_layer_scale) {
3567   if (webview() && compositor()) {
3568     webview()->setCompositorDeviceScaleFactorOverride(device_scale_factor);
3569     webview()->setRootLayerTransform(
3570         blink::WebSize(root_layer_offset.x(), root_layer_offset.y()),
3571         root_layer_scale);
3572   }
3573 }
3574
3575 bool RenderViewImpl::ScheduleFileChooser(
3576     const FileChooserParams& params,
3577     WebFileChooserCompletion* completion) {
3578   static const size_t kMaximumPendingFileChooseRequests = 4;
3579   if (file_chooser_completions_.size() > kMaximumPendingFileChooseRequests) {
3580     // This sanity check prevents too many file choose requests from getting
3581     // queued which could DoS the user. Getting these is most likely a
3582     // programming error (there are many ways to DoS the user so it's not
3583     // considered a "real" security check), either in JS requesting many file
3584     // choosers to pop up, or in a plugin.
3585     //
3586     // TODO(brettw) we might possibly want to require a user gesture to open
3587     // a file picker, which will address this issue in a better way.
3588     return false;
3589   }
3590
3591   file_chooser_completions_.push_back(linked_ptr<PendingFileChooser>(
3592       new PendingFileChooser(params, completion)));
3593   if (file_chooser_completions_.size() == 1) {
3594     // Actually show the browse dialog when this is the first request.
3595     Send(new ViewHostMsg_RunFileChooser(routing_id_, params));
3596   }
3597   return true;
3598 }
3599
3600 blink::WebSpeechRecognizer* RenderViewImpl::speechRecognizer() {
3601   if (!speech_recognition_dispatcher_)
3602     speech_recognition_dispatcher_ = new SpeechRecognitionDispatcher(this);
3603   return speech_recognition_dispatcher_;
3604 }
3605
3606 void RenderViewImpl::zoomLimitsChanged(double minimum_level,
3607                                        double maximum_level) {
3608   int minimum_percent = static_cast<int>(
3609       ZoomLevelToZoomFactor(minimum_level) * 100);
3610   int maximum_percent = static_cast<int>(
3611       ZoomLevelToZoomFactor(maximum_level) * 100);
3612
3613   Send(new ViewHostMsg_UpdateZoomLimits(
3614       routing_id_, minimum_percent, maximum_percent));
3615 }
3616
3617 void RenderViewImpl::zoomLevelChanged() {
3618   double zoom_level = webview()->zoomLevel();
3619
3620   FOR_EACH_OBSERVER(RenderViewObserver, observers_, ZoomLevelChanged());
3621
3622   // Do not send empty URLs to the browser when we are just setting the default
3623   // zoom level (from RendererPreferences) before the first navigation.
3624   if (!webview()->mainFrame()->document().url().isEmpty()) {
3625     // Tell the browser which url got zoomed so it can update the menu and the
3626     // saved values if necessary
3627     Send(new ViewHostMsg_DidZoomURL(
3628         routing_id_, zoom_level,
3629         GURL(webview()->mainFrame()->document().url())));
3630   }
3631 }
3632
3633 double RenderViewImpl::zoomLevelToZoomFactor(double zoom_level) const {
3634   return ZoomLevelToZoomFactor(zoom_level);
3635 }
3636
3637 double RenderViewImpl::zoomFactorToZoomLevel(double factor) const {
3638   return ZoomFactorToZoomLevel(factor);
3639 }
3640
3641 void RenderViewImpl::registerProtocolHandler(const WebString& scheme,
3642                                              const WebURL& base_url,
3643                                              const WebURL& url,
3644                                              const WebString& title) {
3645   bool user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
3646   GURL base(base_url);
3647   GURL absolute_url = base.Resolve(base::UTF16ToUTF8(url.string()));
3648   if (base.GetOrigin() != absolute_url.GetOrigin()) {
3649     return;
3650   }
3651   Send(new ViewHostMsg_RegisterProtocolHandler(routing_id_,
3652                                                base::UTF16ToUTF8(scheme),
3653                                                absolute_url,
3654                                                title,
3655                                                user_gesture));
3656 }
3657
3658 blink::WebPageVisibilityState RenderViewImpl::visibilityState() const {
3659   blink::WebPageVisibilityState current_state = is_hidden() ?
3660       blink::WebPageVisibilityStateHidden :
3661       blink::WebPageVisibilityStateVisible;
3662   blink::WebPageVisibilityState override_state = current_state;
3663   // TODO(jam): move this method to WebFrameClient.
3664   if (GetContentClient()->renderer()->
3665           ShouldOverridePageVisibilityState(main_render_frame_.get(),
3666                                             &override_state))
3667     return override_state;
3668   return current_state;
3669 }
3670
3671 blink::WebPushClient* RenderViewImpl::webPushClient() {
3672   if (!push_messaging_dispatcher_)
3673     push_messaging_dispatcher_ = new PushMessagingDispatcher(this);
3674   return push_messaging_dispatcher_;
3675 }
3676
3677 void RenderViewImpl::draggableRegionsChanged() {
3678   FOR_EACH_OBSERVER(
3679       RenderViewObserver,
3680       observers_,
3681       DraggableRegionsChanged(webview()->mainFrame()));
3682 }
3683
3684 #if defined(OS_ANDROID)
3685 WebContentDetectionResult RenderViewImpl::detectContentAround(
3686     const WebHitTestResult& touch_hit) {
3687   DCHECK(!touch_hit.isNull());
3688   DCHECK(!touch_hit.node().isNull());
3689   DCHECK(touch_hit.node().isTextNode());
3690
3691   // Process the position with all the registered content detectors until
3692   // a match is found. Priority is provided by their relative order.
3693   for (ContentDetectorList::const_iterator it = content_detectors_.begin();
3694       it != content_detectors_.end(); ++it) {
3695     ContentDetector::Result content = (*it)->FindTappedContent(touch_hit);
3696     if (content.valid) {
3697       return WebContentDetectionResult(content.content_boundaries,
3698           base::UTF8ToUTF16(content.text), content.intent_url);
3699     }
3700   }
3701   return WebContentDetectionResult();
3702 }
3703
3704 void RenderViewImpl::scheduleContentIntent(const WebURL& intent) {
3705   // Introduce a short delay so that the user can notice the content.
3706   base::MessageLoop::current()->PostDelayedTask(
3707       FROM_HERE,
3708       base::Bind(&RenderViewImpl::LaunchAndroidContentIntent,
3709                  AsWeakPtr(),
3710                  intent,
3711                  expected_content_intent_id_),
3712       base::TimeDelta::FromMilliseconds(kContentIntentDelayMilliseconds));
3713 }
3714
3715 void RenderViewImpl::cancelScheduledContentIntents() {
3716   ++expected_content_intent_id_;
3717 }
3718
3719 void RenderViewImpl::LaunchAndroidContentIntent(const GURL& intent,
3720                                                 size_t request_id) {
3721   if (request_id != expected_content_intent_id_)
3722       return;
3723
3724   // Remove the content highlighting if any.
3725   scheduleComposite();
3726
3727   if (!intent.is_empty())
3728     Send(new ViewHostMsg_StartContentIntent(routing_id_, intent));
3729 }
3730
3731 bool RenderViewImpl::openDateTimeChooser(
3732     const blink::WebDateTimeChooserParams& params,
3733     blink::WebDateTimeChooserCompletion* completion) {
3734   // JavaScript may try to open a date time chooser while one is already open.
3735   if (date_time_picker_client_)
3736     return false;
3737   date_time_picker_client_.reset(
3738       new RendererDateTimePicker(this, params, completion));
3739   return date_time_picker_client_->Open();
3740 }
3741
3742 void RenderViewImpl::DismissDateTimeDialog() {
3743   DCHECK(date_time_picker_client_);
3744   date_time_picker_client_.reset(NULL);
3745 }
3746
3747 #endif  // defined(OS_ANDROID)
3748
3749 #if defined(OS_MACOSX)
3750 void RenderViewImpl::OnSelectPopupMenuItem(int selected_index) {
3751   if (external_popup_menu_ == NULL)
3752     return;
3753   external_popup_menu_->DidSelectItem(selected_index);
3754   external_popup_menu_.reset();
3755 }
3756 #endif
3757
3758 #if defined(OS_ANDROID)
3759 void RenderViewImpl::OnSelectPopupMenuItems(
3760     bool canceled,
3761     const std::vector<int>& selected_indices) {
3762   // It is possible to receive more than one of these calls if the user presses
3763   // a select faster than it takes for the show-select-popup IPC message to make
3764   // it to the browser UI thread.  Ignore the extra-messages.
3765   // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
3766   if (!external_popup_menu_)
3767     return;
3768
3769   external_popup_menu_->DidSelectItems(canceled, selected_indices);
3770   external_popup_menu_.reset();
3771 }
3772 #endif
3773
3774 #if defined(OS_MACOSX) || defined(OS_ANDROID)
3775 void RenderViewImpl::DidHideExternalPopupMenu() {
3776   // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
3777   // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
3778   external_popup_menu_.reset();
3779 }
3780 #endif
3781
3782 void RenderViewImpl::OnShowContextMenu(
3783     ui::MenuSourceType source_type, const gfx::Point& location) {
3784   context_menu_source_type_ = source_type;
3785   has_host_context_menu_location_ = true;
3786   host_context_menu_location_ = location;
3787   if (webview())
3788     webview()->showContextMenu();
3789   has_host_context_menu_location_ = false;
3790 }
3791
3792 void RenderViewImpl::OnEnableViewSourceMode() {
3793   if (!webview())
3794     return;
3795   WebFrame* main_frame = webview()->mainFrame();
3796   if (!main_frame)
3797     return;
3798   main_frame->enableViewSourceMode(true);
3799 }
3800
3801 void RenderViewImpl::OnDisownOpener() {
3802   if (!webview())
3803     return;
3804
3805   WebFrame* main_frame = webview()->mainFrame();
3806   if (main_frame && main_frame->opener())
3807     main_frame->setOpener(NULL);
3808 }
3809
3810 #if defined(OS_ANDROID)
3811 bool RenderViewImpl::didTapMultipleTargets(
3812     const blink::WebGestureEvent& event,
3813     const WebVector<WebRect>& target_rects) {
3814   // Never show a disambiguation popup when accessibility is enabled,
3815   // as this interferes with "touch exploration".
3816   bool matchesAccessibilityModeComplete =
3817       (accessibility_mode_ & AccessibilityModeComplete) ==
3818       AccessibilityModeComplete;
3819   if (matchesAccessibilityModeComplete)
3820     return false;
3821
3822   gfx::Rect finger_rect(
3823       event.x - event.data.tap.width / 2, event.y - event.data.tap.height / 2,
3824       event.data.tap.width, event.data.tap.height);
3825   gfx::Rect zoom_rect;
3826   float new_total_scale =
3827       DisambiguationPopupHelper::ComputeZoomAreaAndScaleFactor(
3828           finger_rect, target_rects, GetSize(),
3829           gfx::Rect(webview()->mainFrame()->visibleContentRect()).size(),
3830           device_scale_factor_ * webview()->pageScaleFactor(), &zoom_rect);
3831   if (!new_total_scale)
3832     return false;
3833
3834   bool handled = false;
3835   switch (renderer_preferences_.tap_multiple_targets_strategy) {
3836     case TAP_MULTIPLE_TARGETS_STRATEGY_ZOOM:
3837       handled = webview()->zoomToMultipleTargetsRect(zoom_rect);
3838       break;
3839     case TAP_MULTIPLE_TARGETS_STRATEGY_POPUP: {
3840       gfx::Size canvas_size =
3841           gfx::ToCeiledSize(gfx::ScaleSize(zoom_rect.size(), new_total_scale));
3842       cc::SharedBitmapManager* manager =
3843           RenderThreadImpl::current()->shared_bitmap_manager();
3844       scoped_ptr<cc::SharedBitmap> shared_bitmap =
3845           manager->AllocateSharedBitmap(canvas_size);
3846       {
3847         SkBitmap bitmap;
3848         SkImageInfo info = SkImageInfo::MakeN32Premul(canvas_size.width(),
3849                                                       canvas_size.height());
3850         bitmap.installPixels(info, shared_bitmap->pixels(), info.minRowBytes());
3851         SkCanvas canvas(bitmap);
3852
3853         // TODO(trchen): Cleanup the device scale factor mess.
3854         // device scale will be applied in WebKit
3855         // --> zoom_rect doesn't include device scale,
3856         //     but WebKit will still draw on zoom_rect * device_scale_factor_
3857         canvas.scale(new_total_scale / device_scale_factor_,
3858                      new_total_scale / device_scale_factor_);
3859         canvas.translate(-zoom_rect.x() * device_scale_factor_,
3860                          -zoom_rect.y() * device_scale_factor_);
3861
3862         DCHECK(webwidget_->isAcceleratedCompositingActive());
3863         // TODO(aelias): The disambiguation popup should be composited so we
3864         // don't have to call this method.
3865         webwidget_->paintCompositedDeprecated(&canvas, zoom_rect);
3866       }
3867
3868       gfx::Rect physical_window_zoom_rect = gfx::ToEnclosingRect(
3869           ClientRectToPhysicalWindowRect(gfx::RectF(zoom_rect)));
3870       Send(new ViewHostMsg_ShowDisambiguationPopup(routing_id_,
3871                                                    physical_window_zoom_rect,
3872                                                    canvas_size,
3873                                                    shared_bitmap->id()));
3874       cc::SharedBitmapId id = shared_bitmap->id();
3875       disambiguation_bitmaps_[id] = shared_bitmap.release();
3876       handled = true;
3877       break;
3878     }
3879     case TAP_MULTIPLE_TARGETS_STRATEGY_NONE:
3880       // No-op.
3881       break;
3882   }
3883
3884   return handled;
3885 }
3886 #endif
3887
3888 unsigned RenderViewImpl::GetLocalSessionHistoryLengthForTesting() const {
3889   return history_list_length_;
3890 }
3891
3892 void RenderViewImpl::SetFocusAndActivateForTesting(bool enable) {
3893   if (enable) {
3894     if (has_focus())
3895       return;
3896     OnSetActive(true);
3897     OnSetFocus(true);
3898   } else {
3899     if (!has_focus())
3900       return;
3901     OnSetFocus(false);
3902     OnSetActive(false);
3903   }
3904 }
3905
3906 void RenderViewImpl::SetDeviceScaleFactorForTesting(float factor) {
3907   ViewMsg_Resize_Params params;
3908   params.screen_info = screen_info_;
3909   params.screen_info.deviceScaleFactor = factor;
3910   params.new_size = size();
3911   params.physical_backing_size =
3912       gfx::ToCeiledSize(gfx::ScaleSize(size(), factor));
3913   params.overdraw_bottom_height = 0.f;
3914   params.resizer_rect = WebRect();
3915   params.is_fullscreen = is_fullscreen();
3916   OnResize(params);
3917 }
3918
3919 void RenderViewImpl::SetScreenOrientationForTesting(
3920     const blink::WebScreenOrientationType& orientation) {
3921   ViewMsg_Resize_Params params;
3922   params.screen_info = screen_info_;
3923   params.screen_info.orientationType = orientation;
3924   // FIXME(ostap): This relationship between orientationType and
3925   // orientationAngle is temporary. The test should be able to specify
3926   // the angle in addition to the orientation type.
3927   switch (orientation) {
3928     case blink::WebScreenOrientationLandscapePrimary:
3929       params.screen_info.orientationAngle = 90;
3930       break;
3931     case blink::WebScreenOrientationLandscapeSecondary:
3932       params.screen_info.orientationAngle = -90;
3933       break;
3934     case blink::WebScreenOrientationPortraitSecondary:
3935       params.screen_info.orientationAngle = 180;
3936       break;
3937     default:
3938       params.screen_info.orientationAngle = 0;
3939   }
3940   params.new_size = size();
3941   params.physical_backing_size = gfx::ToCeiledSize(
3942       gfx::ScaleSize(size(), params.screen_info.deviceScaleFactor));
3943   params.overdraw_bottom_height = 0.f;
3944   params.resizer_rect = WebRect();
3945   params.is_fullscreen = is_fullscreen();
3946   OnResize(params);
3947 }
3948
3949 void RenderViewImpl::SetDeviceColorProfileForTesting(
3950     const std::vector<char>& color_profile) {
3951   SetDeviceColorProfile(color_profile);
3952 }
3953
3954 void RenderViewImpl::ForceResizeForTesting(const gfx::Size& new_size) {
3955   gfx::Rect new_position(rootWindowRect().x,
3956                          rootWindowRect().y,
3957                          new_size.width(),
3958                          new_size.height());
3959   ResizeSynchronously(new_position);
3960 }
3961
3962 void RenderViewImpl::UseSynchronousResizeModeForTesting(bool enable) {
3963   resizing_mode_selector_->set_is_synchronous_mode(enable);
3964 }
3965
3966 void RenderViewImpl::EnableAutoResizeForTesting(const gfx::Size& min_size,
3967                                                 const gfx::Size& max_size) {
3968   OnEnableAutoResize(min_size, max_size);
3969 }
3970
3971 void RenderViewImpl::DisableAutoResizeForTesting(const gfx::Size& new_size) {
3972   OnDisableAutoResize(new_size);
3973 }
3974
3975 void RenderViewImpl::OnReleaseDisambiguationPopupBitmap(
3976     const cc::SharedBitmapId& id) {
3977   BitmapMap::iterator it = disambiguation_bitmaps_.find(id);
3978   DCHECK(it != disambiguation_bitmaps_.end());
3979   delete it->second;
3980   disambiguation_bitmaps_.erase(it);
3981 }
3982
3983 void RenderViewImpl::DidCommitCompositorFrame() {
3984   RenderWidget::DidCommitCompositorFrame();
3985   FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidCommitCompositorFrame());
3986 }
3987
3988 void RenderViewImpl::SendUpdateFaviconURL(const std::vector<FaviconURL>& urls) {
3989   if (!urls.empty())
3990     Send(new ViewHostMsg_UpdateFaviconURL(routing_id_, urls));
3991 }
3992
3993 void RenderViewImpl::DidStopLoadingIcons() {
3994   int icon_types = WebIconURL::TypeFavicon;
3995   if (TouchEnabled())
3996     icon_types |= WebIconURL::TypeTouchPrecomposed | WebIconURL::TypeTouch;
3997
3998   WebVector<WebIconURL> icon_urls =
3999       webview()->mainFrame()->iconURLs(icon_types);
4000
4001   std::vector<FaviconURL> urls;
4002   for (size_t i = 0; i < icon_urls.size(); i++) {
4003     WebURL url = icon_urls[i].iconURL();
4004     std::vector<gfx::Size> sizes;
4005     ConvertToFaviconSizes(icon_urls[i].sizes(), &sizes);
4006     if (!url.isEmpty())
4007       urls.push_back(
4008           FaviconURL(url, ToFaviconType(icon_urls[i].iconType()), sizes));
4009   }
4010   SendUpdateFaviconURL(urls);
4011 }
4012
4013 }  // namespace content