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