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