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