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