[Android WebView] Upstream WebViewShell to chromium.
[chromium-blink-merge.git] / content / renderer / render_view_impl.cc
blob66d2c0d45daa14ace02dee5f2bdec6516e07ae3f
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.
5 #include "content/renderer/render_view_impl.h"
7 #include <algorithm>
8 #include <cmath>
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/files/file_path.h"
17 #include "base/i18n/rtl.h"
18 #include "base/json/json_writer.h"
19 #include "base/lazy_instance.h"
20 #include "base/memory/scoped_ptr.h"
21 #include "base/message_loop/message_loop_proxy.h"
22 #include "base/metrics/field_trial.h"
23 #include "base/metrics/histogram.h"
24 #include "base/process/kill.h"
25 #include "base/process/process.h"
26 #include "base/strings/string_number_conversions.h"
27 #include "base/strings/string_piece.h"
28 #include "base/strings/string_split.h"
29 #include "base/strings/string_util.h"
30 #include "base/strings/sys_string_conversions.h"
31 #include "base/strings/utf_string_conversions.h"
32 #include "base/time/time.h"
33 #include "base/trace_event/trace_event.h"
34 #include "content/child/appcache/appcache_dispatcher.h"
35 #include "content/child/appcache/web_application_cache_host_impl.h"
36 #include "content/child/child_shared_bitmap_manager.h"
37 #include "content/child/npapi/webplugin_delegate_impl.h"
38 #include "content/child/request_extra_data.h"
39 #include "content/child/v8_value_converter_impl.h"
40 #include "content/child/webmessageportchannel_impl.h"
41 #include "content/common/content_constants_internal.h"
42 #include "content/common/database_messages.h"
43 #include "content/common/dom_storage/dom_storage_types.h"
44 #include "content/common/drag_messages.h"
45 #include "content/common/frame_messages.h"
46 #include "content/common/frame_replication_state.h"
47 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
48 #include "content/common/input_messages.h"
49 #include "content/common/pepper_messages.h"
50 #include "content/common/ssl_status_serialization.h"
51 #include "content/common/view_messages.h"
52 #include "content/public/common/bindings_policy.h"
53 #include "content/public/common/content_client.h"
54 #include "content/public/common/content_constants.h"
55 #include "content/public/common/content_switches.h"
56 #include "content/public/common/drop_data.h"
57 #include "content/public/common/favicon_url.h"
58 #include "content/public/common/file_chooser_file_info.h"
59 #include "content/public/common/file_chooser_params.h"
60 #include "content/public/common/page_state.h"
61 #include "content/public/common/page_zoom.h"
62 #include "content/public/common/ssl_status.h"
63 #include "content/public/common/three_d_api_types.h"
64 #include "content/public/common/url_constants.h"
65 #include "content/public/common/url_utils.h"
66 #include "content/public/common/web_preferences.h"
67 #include "content/public/renderer/content_renderer_client.h"
68 #include "content/public/renderer/document_state.h"
69 #include "content/public/renderer/navigation_state.h"
70 #include "content/public/renderer/render_view_observer.h"
71 #include "content/public/renderer/render_view_visitor.h"
72 #include "content/renderer/browser_plugin/browser_plugin.h"
73 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
74 #include "content/renderer/disambiguation_popup_helper.h"
75 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
76 #include "content/renderer/drop_data_builder.h"
77 #include "content/renderer/gpu/render_widget_compositor.h"
78 #include "content/renderer/history_controller.h"
79 #include "content/renderer/history_serialization.h"
80 #include "content/renderer/idle_user_detector.h"
81 #include "content/renderer/ime_event_guard.h"
82 #include "content/renderer/input/input_handler_manager.h"
83 #include "content/renderer/internal_document_state_data.h"
84 #include "content/renderer/media/audio_device_factory.h"
85 #include "content/renderer/media/video_capture_impl_manager.h"
86 #include "content/renderer/mhtml_generator.h"
87 #include "content/renderer/navigation_state_impl.h"
88 #include "content/renderer/net_info_helper.h"
89 #include "content/renderer/render_frame_impl.h"
90 #include "content/renderer/render_frame_proxy.h"
91 #include "content/renderer/render_process.h"
92 #include "content/renderer/render_thread_impl.h"
93 #include "content/renderer/render_view_mouse_lock_dispatcher.h"
94 #include "content/renderer/render_widget_fullscreen_pepper.h"
95 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
96 #include "content/renderer/resizing_mode_selector.h"
97 #include "content/renderer/savable_resources.h"
98 #include "content/renderer/speech_recognition_dispatcher.h"
99 #include "content/renderer/text_input_client_observer.h"
100 #include "content/renderer/web_ui_extension_data.h"
101 #include "content/renderer/web_ui_mojo.h"
102 #include "content/renderer/websharedworker_proxy.h"
103 #include "media/audio/audio_output_device.h"
104 #include "media/base/media_switches.h"
105 #include "media/renderers/audio_renderer_impl.h"
106 #include "media/renderers/gpu_video_accelerator_factories.h"
107 #include "net/base/data_url.h"
108 #include "net/base/escape.h"
109 #include "net/base/net_errors.h"
110 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
111 #include "net/http/http_util.h"
112 #include "skia/ext/platform_canvas.h"
113 #include "third_party/WebKit/public/platform/WebCString.h"
114 #include "third_party/WebKit/public/platform/WebConnectionType.h"
115 #include "third_party/WebKit/public/platform/WebDragData.h"
116 #include "third_party/WebKit/public/platform/WebHTTPBody.h"
117 #include "third_party/WebKit/public/platform/WebImage.h"
118 #include "third_party/WebKit/public/platform/WebMessagePortChannel.h"
119 #include "third_party/WebKit/public/platform/WebPoint.h"
120 #include "third_party/WebKit/public/platform/WebRect.h"
121 #include "third_party/WebKit/public/platform/WebSize.h"
122 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
123 #include "third_party/WebKit/public/platform/WebString.h"
124 #include "third_party/WebKit/public/platform/WebURL.h"
125 #include "third_party/WebKit/public/platform/WebURLError.h"
126 #include "third_party/WebKit/public/platform/WebURLRequest.h"
127 #include "third_party/WebKit/public/platform/WebURLResponse.h"
128 #include "third_party/WebKit/public/platform/WebVector.h"
129 #include "third_party/WebKit/public/web/WebAXObject.h"
130 #include "third_party/WebKit/public/web/WebColorName.h"
131 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
132 #include "third_party/WebKit/public/web/WebDOMEvent.h"
133 #include "third_party/WebKit/public/web/WebDOMMessageEvent.h"
134 #include "third_party/WebKit/public/web/WebDataSource.h"
135 #include "third_party/WebKit/public/web/WebDateTimeChooserCompletion.h"
136 #include "third_party/WebKit/public/web/WebDateTimeChooserParams.h"
137 #include "third_party/WebKit/public/web/WebDevToolsAgent.h"
138 #include "third_party/WebKit/public/web/WebDocument.h"
139 #include "third_party/WebKit/public/web/WebElement.h"
140 #include "third_party/WebKit/public/web/WebFileChooserParams.h"
141 #include "third_party/WebKit/public/web/WebFindOptions.h"
142 #include "third_party/WebKit/public/web/WebFormControlElement.h"
143 #include "third_party/WebKit/public/web/WebFormElement.h"
144 #include "third_party/WebKit/public/web/WebFrame.h"
145 #include "third_party/WebKit/public/web/WebGlyphCache.h"
146 #include "third_party/WebKit/public/web/WebHistoryItem.h"
147 #include "third_party/WebKit/public/web/WebHitTestResult.h"
148 #include "third_party/WebKit/public/web/WebInputElement.h"
149 #include "third_party/WebKit/public/web/WebInputEvent.h"
150 #include "third_party/WebKit/public/web/WebLocalFrame.h"
151 #include "third_party/WebKit/public/web/WebMediaPlayerAction.h"
152 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
153 #include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
154 #include "third_party/WebKit/public/web/WebNodeList.h"
155 #include "third_party/WebKit/public/web/WebPageSerializer.h"
156 #include "third_party/WebKit/public/web/WebPlugin.h"
157 #include "third_party/WebKit/public/web/WebPluginAction.h"
158 #include "third_party/WebKit/public/web/WebPluginContainer.h"
159 #include "third_party/WebKit/public/web/WebPluginDocument.h"
160 #include "third_party/WebKit/public/web/WebRange.h"
161 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
162 #include "third_party/WebKit/public/web/WebScriptSource.h"
163 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
164 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
165 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
166 #include "third_party/WebKit/public/web/WebSettings.h"
167 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
168 #include "third_party/WebKit/public/web/WebView.h"
169 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
170 #include "third_party/WebKit/public/web/default/WebRenderTheme.h"
171 #include "third_party/icu/source/common/unicode/uchar.h"
172 #include "third_party/icu/source/common/unicode/uscript.h"
173 #include "ui/base/clipboard/clipboard.h"
174 #include "ui/base/ui_base_switches_util.h"
175 #include "ui/events/latency_info.h"
176 #include "ui/gfx/geometry/point.h"
177 #include "ui/gfx/geometry/rect.h"
178 #include "ui/gfx/geometry/rect_conversions.h"
179 #include "ui/gfx/geometry/size_conversions.h"
180 #include "ui/gfx/native_widget_types.h"
181 #include "v8/include/v8.h"
183 #if defined(OS_ANDROID)
184 #include <cpu-features.h>
186 #include "content/renderer/android/address_detector.h"
187 #include "content/renderer/android/content_detector.h"
188 #include "content/renderer/android/email_detector.h"
189 #include "content/renderer/android/phone_number_detector.h"
190 #include "third_party/WebKit/public/platform/WebFloatPoint.h"
191 #include "third_party/WebKit/public/platform/WebFloatRect.h"
192 #include "ui/gfx/geometry/rect_f.h"
194 #elif defined(OS_WIN)
195 // TODO(port): these files are currently Windows only because they concern:
196 // * theming
197 #include "ui/native_theme/native_theme_win.h"
198 #elif defined(USE_X11)
199 #include "ui/native_theme/native_theme.h"
200 #elif defined(OS_MACOSX)
201 #include "skia/ext/skia_utils_mac.h"
202 #endif
204 #if defined(ENABLE_PLUGINS)
205 #include "content/renderer/npapi/webplugin_delegate_proxy.h"
206 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
207 #include "content/renderer/pepper/pepper_plugin_registry.h"
208 #endif
210 #if defined(ENABLE_WEBRTC)
211 #include "content/renderer/media/rtc_peer_connection_handler.h"
212 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
213 #endif
215 using blink::WebAXObject;
216 using blink::WebApplicationCacheHost;
217 using blink::WebApplicationCacheHostClient;
218 using blink::WebCString;
219 using blink::WebColor;
220 using blink::WebColorName;
221 using blink::WebConsoleMessage;
222 using blink::WebData;
223 using blink::WebDataSource;
224 using blink::WebDocument;
225 using blink::WebDragData;
226 using blink::WebDragOperation;
227 using blink::WebDragOperationsMask;
228 using blink::WebElement;
229 using blink::WebFileChooserCompletion;
230 using blink::WebFindOptions;
231 using blink::WebFormControlElement;
232 using blink::WebFormElement;
233 using blink::WebFrame;
234 using blink::WebGestureEvent;
235 using blink::WebHistoryItem;
236 using blink::WebHTTPBody;
237 using blink::WebIconURL;
238 using blink::WebImage;
239 using blink::WebInputElement;
240 using blink::WebInputEvent;
241 using blink::WebLocalFrame;
242 using blink::WebMediaPlayerAction;
243 using blink::WebMouseEvent;
244 using blink::WebNavigationPolicy;
245 using blink::WebNavigationType;
246 using blink::WebNode;
247 using blink::WebPageSerializer;
248 using blink::WebPageSerializerClient;
249 using blink::WebPeerConnection00Handler;
250 using blink::WebPeerConnection00HandlerClient;
251 using blink::WebPeerConnectionHandler;
252 using blink::WebPeerConnectionHandlerClient;
253 using blink::WebPluginAction;
254 using blink::WebPluginContainer;
255 using blink::WebPluginDocument;
256 using blink::WebPoint;
257 using blink::WebRange;
258 using blink::WebRect;
259 using blink::WebReferrerPolicy;
260 using blink::WebScriptSource;
261 using blink::WebSearchableFormData;
262 using blink::WebSecurityOrigin;
263 using blink::WebSecurityPolicy;
264 using blink::WebSettings;
265 using blink::WebSize;
266 using blink::WebStorageNamespace;
267 using blink::WebStorageQuotaCallbacks;
268 using blink::WebStorageQuotaError;
269 using blink::WebStorageQuotaType;
270 using blink::WebString;
271 using blink::WebTextAffinity;
272 using blink::WebTextDirection;
273 using blink::WebTouchEvent;
274 using blink::WebURL;
275 using blink::WebURLError;
276 using blink::WebURLRequest;
277 using blink::WebURLResponse;
278 using blink::WebUserGestureIndicator;
279 using blink::WebVector;
280 using blink::WebView;
281 using blink::WebWidget;
282 using blink::WebWindowFeatures;
283 using blink::WebNetworkStateNotifier;
284 using blink::WebRuntimeFeatures;
285 using base::Time;
286 using base::TimeDelta;
288 #if defined(OS_ANDROID)
289 using blink::WebContentDetectionResult;
290 using blink::WebFloatPoint;
291 using blink::WebFloatRect;
292 using blink::WebHitTestResult;
293 #endif
295 namespace content {
297 //-----------------------------------------------------------------------------
299 typedef std::map<blink::WebView*, RenderViewImpl*> ViewMap;
300 static base::LazyInstance<ViewMap> g_view_map = LAZY_INSTANCE_INITIALIZER;
301 typedef std::map<int32, RenderViewImpl*> RoutingIDViewMap;
302 static base::LazyInstance<RoutingIDViewMap> g_routing_id_view_map =
303 LAZY_INSTANCE_INITIALIZER;
305 // Time, in seconds, we delay before sending content state changes (such as form
306 // state and scroll position) to the browser. We delay sending changes to avoid
307 // spamming the browser.
308 // To avoid having tab/session restore require sending a message to get the
309 // current content state during tab closing we use a shorter timeout for the
310 // foreground renderer. This means there is a small window of time from which
311 // content state is modified and not sent to session restore, but this is
312 // better than having to wake up all renderers during shutdown.
313 const int kDelaySecondsForContentStateSyncHidden = 5;
314 const int kDelaySecondsForContentStateSync = 1;
316 #if defined(OS_ANDROID)
317 // Delay between tapping in content and launching the associated android intent.
318 // Used to allow users see what has been recognized as content.
319 const size_t kContentIntentDelayMilliseconds = 700;
320 #endif
322 static RenderViewImpl* (*g_create_render_view_impl)(const ViewMsg_New_Params&) =
323 NULL;
325 // static
326 Referrer RenderViewImpl::GetReferrerFromRequest(
327 WebFrame* frame,
328 const WebURLRequest& request) {
329 return Referrer(GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
330 request.referrerPolicy());
333 // static
334 WindowOpenDisposition RenderViewImpl::NavigationPolicyToDisposition(
335 WebNavigationPolicy policy) {
336 switch (policy) {
337 case blink::WebNavigationPolicyIgnore:
338 return IGNORE_ACTION;
339 case blink::WebNavigationPolicyDownload:
340 return SAVE_TO_DISK;
341 case blink::WebNavigationPolicyCurrentTab:
342 return CURRENT_TAB;
343 case blink::WebNavigationPolicyNewBackgroundTab:
344 return NEW_BACKGROUND_TAB;
345 case blink::WebNavigationPolicyNewForegroundTab:
346 return NEW_FOREGROUND_TAB;
347 case blink::WebNavigationPolicyNewWindow:
348 return NEW_WINDOW;
349 case blink::WebNavigationPolicyNewPopup:
350 return NEW_POPUP;
351 default:
352 NOTREACHED() << "Unexpected WebNavigationPolicy";
353 return IGNORE_ACTION;
357 // Returns true if the device scale is high enough that losing subpixel
358 // antialiasing won't have a noticeable effect on text quality.
359 static bool DeviceScaleEnsuresTextQuality(float device_scale_factor) {
360 #if defined(OS_ANDROID)
361 // On Android, we never have subpixel antialiasing.
362 return true;
363 #else
364 return device_scale_factor > 1.5f;
365 #endif
369 static bool PreferCompositingToLCDText(CompositorDependencies* compositor_deps,
370 float device_scale_factor) {
371 const base::CommandLine& command_line =
372 *base::CommandLine::ForCurrentProcess();
373 if (command_line.HasSwitch(switches::kDisablePreferCompositingToLCDText))
374 return false;
375 if (command_line.HasSwitch(switches::kEnablePreferCompositingToLCDText))
376 return true;
377 if (!compositor_deps->IsLcdTextEnabled())
378 return true;
379 return DeviceScaleEnsuresTextQuality(device_scale_factor);
382 static FaviconURL::IconType ToFaviconType(blink::WebIconURL::Type type) {
383 switch (type) {
384 case blink::WebIconURL::TypeFavicon:
385 return FaviconURL::FAVICON;
386 case blink::WebIconURL::TypeTouch:
387 return FaviconURL::TOUCH_ICON;
388 case blink::WebIconURL::TypeTouchPrecomposed:
389 return FaviconURL::TOUCH_PRECOMPOSED_ICON;
390 case blink::WebIconURL::TypeInvalid:
391 return FaviconURL::INVALID_ICON;
393 return FaviconURL::INVALID_ICON;
396 static void ConvertToFaviconSizes(
397 const blink::WebVector<blink::WebSize>& web_sizes,
398 std::vector<gfx::Size>* sizes) {
399 DCHECK(sizes->empty());
400 sizes->reserve(web_sizes.size());
401 for (size_t i = 0; i < web_sizes.size(); ++i)
402 sizes->push_back(gfx::Size(web_sizes[i]));
405 static blink::WebDevToolsAgent* GetWebDevToolsAgent(WebView* webview) {
406 if (!webview || !webview->mainFrame()->isWebLocalFrame())
407 return nullptr;
408 return webview->mainFrame()->toWebLocalFrame()->devToolsAgent();
411 ///////////////////////////////////////////////////////////////////////////////
413 struct RenderViewImpl::PendingFileChooser {
414 PendingFileChooser(const FileChooserParams& p, WebFileChooserCompletion* c)
415 : params(p),
416 completion(c) {
418 FileChooserParams params;
419 WebFileChooserCompletion* completion; // MAY BE NULL to skip callback.
422 namespace {
424 class WebWidgetLockTarget : public MouseLockDispatcher::LockTarget {
425 public:
426 explicit WebWidgetLockTarget(blink::WebWidget* webwidget)
427 : webwidget_(webwidget) {}
429 void OnLockMouseACK(bool succeeded) override {
430 if (succeeded)
431 webwidget_->didAcquirePointerLock();
432 else
433 webwidget_->didNotAcquirePointerLock();
436 void OnMouseLockLost() override { webwidget_->didLosePointerLock(); }
438 bool HandleMouseLockedInputEvent(const blink::WebMouseEvent& event) override {
439 // The WebWidget handles mouse lock in WebKit's handleInputEvent().
440 return false;
443 private:
444 blink::WebWidget* webwidget_;
447 WebDragData DropDataToWebDragData(const DropData& drop_data) {
448 std::vector<WebDragData::Item> item_list;
450 // These fields are currently unused when dragging into WebKit.
451 DCHECK(drop_data.download_metadata.empty());
452 DCHECK(drop_data.file_contents.empty());
453 DCHECK(drop_data.file_description_filename.empty());
455 if (!drop_data.text.is_null()) {
456 WebDragData::Item item;
457 item.storageType = WebDragData::Item::StorageTypeString;
458 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeText);
459 item.stringData = drop_data.text.string();
460 item_list.push_back(item);
463 // TODO(dcheng): Do we need to distinguish between null and empty URLs? Is it
464 // meaningful to write an empty URL to the clipboard?
465 if (!drop_data.url.is_empty()) {
466 WebDragData::Item item;
467 item.storageType = WebDragData::Item::StorageTypeString;
468 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeURIList);
469 item.stringData = WebString::fromUTF8(drop_data.url.spec());
470 item.title = drop_data.url_title;
471 item_list.push_back(item);
474 if (!drop_data.html.is_null()) {
475 WebDragData::Item item;
476 item.storageType = WebDragData::Item::StorageTypeString;
477 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeHTML);
478 item.stringData = drop_data.html.string();
479 item.baseURL = drop_data.html_base_url;
480 item_list.push_back(item);
483 for (std::vector<ui::FileInfo>::const_iterator it =
484 drop_data.filenames.begin();
485 it != drop_data.filenames.end();
486 ++it) {
487 WebDragData::Item item;
488 item.storageType = WebDragData::Item::StorageTypeFilename;
489 item.filenameData = it->path.AsUTF16Unsafe();
490 item.displayNameData = it->display_name.AsUTF16Unsafe();
491 item_list.push_back(item);
494 for (std::vector<DropData::FileSystemFileInfo>::const_iterator it =
495 drop_data.file_system_files.begin();
496 it != drop_data.file_system_files.end();
497 ++it) {
498 WebDragData::Item item;
499 item.storageType = WebDragData::Item::StorageTypeFileSystemFile;
500 item.fileSystemURL = it->url;
501 item.fileSystemFileSize = it->size;
502 item_list.push_back(item);
505 for (std::map<base::string16, base::string16>::const_iterator it =
506 drop_data.custom_data.begin();
507 it != drop_data.custom_data.end();
508 ++it) {
509 WebDragData::Item item;
510 item.storageType = WebDragData::Item::StorageTypeString;
511 item.stringType = it->first;
512 item.stringData = it->second;
513 item_list.push_back(item);
516 WebDragData result;
517 result.initialize();
518 result.setItems(item_list);
519 result.setFilesystemId(drop_data.filesystem_id);
520 return result;
523 typedef void (*SetFontFamilyWrapper)(blink::WebSettings*,
524 const base::string16&,
525 UScriptCode);
527 void SetStandardFontFamilyWrapper(WebSettings* settings,
528 const base::string16& font,
529 UScriptCode script) {
530 settings->setStandardFontFamily(font, script);
533 void SetFixedFontFamilyWrapper(WebSettings* settings,
534 const base::string16& font,
535 UScriptCode script) {
536 settings->setFixedFontFamily(font, script);
539 void SetSerifFontFamilyWrapper(WebSettings* settings,
540 const base::string16& font,
541 UScriptCode script) {
542 settings->setSerifFontFamily(font, script);
545 void SetSansSerifFontFamilyWrapper(WebSettings* settings,
546 const base::string16& font,
547 UScriptCode script) {
548 settings->setSansSerifFontFamily(font, script);
551 void SetCursiveFontFamilyWrapper(WebSettings* settings,
552 const base::string16& font,
553 UScriptCode script) {
554 settings->setCursiveFontFamily(font, script);
557 void SetFantasyFontFamilyWrapper(WebSettings* settings,
558 const base::string16& font,
559 UScriptCode script) {
560 settings->setFantasyFontFamily(font, script);
563 void SetPictographFontFamilyWrapper(WebSettings* settings,
564 const base::string16& font,
565 UScriptCode script) {
566 settings->setPictographFontFamily(font, script);
569 // If |scriptCode| is a member of a family of "similar" script codes, returns
570 // the script code in that family that is used by WebKit for font selection
571 // purposes. For example, USCRIPT_KATAKANA_OR_HIRAGANA and USCRIPT_JAPANESE are
572 // considered equivalent for the purposes of font selection. WebKit uses the
573 // script code USCRIPT_KATAKANA_OR_HIRAGANA. So, if |scriptCode| is
574 // USCRIPT_JAPANESE, the function returns USCRIPT_KATAKANA_OR_HIRAGANA. WebKit
575 // uses different scripts than the ones in Chrome pref names because the version
576 // of ICU included on certain ports does not have some of the newer scripts. If
577 // |scriptCode| is not a member of such a family, returns |scriptCode|.
578 UScriptCode GetScriptForWebSettings(UScriptCode scriptCode) {
579 switch (scriptCode) {
580 case USCRIPT_HIRAGANA:
581 case USCRIPT_KATAKANA:
582 case USCRIPT_JAPANESE:
583 return USCRIPT_KATAKANA_OR_HIRAGANA;
584 case USCRIPT_KOREAN:
585 return USCRIPT_HANGUL;
586 default:
587 return scriptCode;
591 void ApplyFontsFromMap(const ScriptFontFamilyMap& map,
592 SetFontFamilyWrapper setter,
593 WebSettings* settings) {
594 for (ScriptFontFamilyMap::const_iterator it = map.begin(); it != map.end();
595 ++it) {
596 int32 script = u_getPropertyValueEnum(UCHAR_SCRIPT, (it->first).c_str());
597 if (script >= 0 && script < USCRIPT_CODE_LIMIT) {
598 UScriptCode code = static_cast<UScriptCode>(script);
599 (*setter)(settings, it->second, GetScriptForWebSettings(code));
604 void ApplyBlinkSettings(const base::CommandLine& command_line,
605 WebSettings* settings) {
606 if (!command_line.HasSwitch(switches::kBlinkSettings))
607 return;
609 std::vector<std::string> blink_settings;
610 base::SplitString(
611 command_line.GetSwitchValueASCII(switches::kBlinkSettings), ',',
612 &blink_settings);
613 for (const std::string& setting : blink_settings) {
614 size_t pos = setting.find('=');
615 settings->setFromStrings(
616 blink::WebString::fromLatin1(setting.substr(0, pos)),
617 blink::WebString::fromLatin1(
618 pos == std::string::npos ? "" : setting.substr(pos + 1)));
622 } // namespace
624 RenderViewImpl::RenderViewImpl(const ViewMsg_New_Params& params)
625 : RenderWidget(blink::WebPopupTypeNone,
626 params.initial_size.screen_info,
627 params.swapped_out,
628 params.hidden,
629 params.never_visible),
630 webkit_preferences_(params.web_preferences),
631 send_content_state_immediately_(false),
632 enabled_bindings_(0),
633 send_preferred_size_changes_(false),
634 navigation_gesture_(NavigationGestureUnknown),
635 opened_by_user_gesture_(true),
636 opener_suppressed_(false),
637 suppress_dialogs_until_swap_out_(false),
638 page_id_(-1),
639 next_page_id_(params.next_page_id),
640 history_list_offset_(-1),
641 history_list_length_(0),
642 frames_in_progress_(0),
643 target_url_status_(TARGET_NONE),
644 uses_temporary_zoom_level_(false),
645 #if defined(OS_ANDROID)
646 top_controls_constraints_(TOP_CONTROLS_STATE_BOTH),
647 #endif
648 has_scrolled_focused_editable_node_into_rect_(false),
649 speech_recognition_dispatcher_(NULL),
650 mouse_lock_dispatcher_(NULL),
651 #if defined(OS_ANDROID)
652 expected_content_intent_id_(0),
653 #endif
654 #if defined(OS_WIN)
655 focused_plugin_id_(-1),
656 #endif
657 #if defined(ENABLE_PLUGINS)
658 plugin_find_handler_(NULL),
659 focused_pepper_plugin_(NULL),
660 pepper_last_mouse_event_target_(NULL),
661 #endif
662 enumeration_completion_id_(0),
663 session_storage_namespace_id_(params.session_storage_namespace_id),
664 page_scale_factor_is_one_(true) {
667 void RenderViewImpl::Initialize(const ViewMsg_New_Params& params,
668 CompositorDependencies* compositor_deps,
669 bool was_created_by_renderer) {
670 routing_id_ = params.view_id;
671 surface_id_ = params.surface_id;
672 if (params.opener_route_id != MSG_ROUTING_NONE && was_created_by_renderer)
673 opener_id_ = params.opener_route_id;
674 display_mode_= params.initial_size.display_mode;
676 // Ensure we start with a valid next_page_id_ from the browser.
677 DCHECK_GE(next_page_id_, 0);
679 main_render_frame_.reset(RenderFrameImpl::Create(
680 this, params.main_frame_routing_id));
681 // The main frame WebLocalFrame object is closed by
682 // RenderFrameImpl::frameDetached().
683 WebLocalFrame* web_frame = WebLocalFrame::create(main_render_frame_.get());
684 main_render_frame_->SetWebFrame(web_frame);
686 compositor_deps_ = compositor_deps;
687 webwidget_ = WebView::create(this);
688 webwidget_mouse_lock_target_.reset(new WebWidgetLockTarget(webwidget_));
690 const base::CommandLine& command_line =
691 *base::CommandLine::ForCurrentProcess();
693 if (command_line.HasSwitch(switches::kStatsCollectionController))
694 stats_collection_observer_.reset(new StatsCollectionObserver(this));
696 #if defined(OS_ANDROID)
697 content_detectors_.push_back(linked_ptr<ContentDetector>(
698 new AddressDetector()));
699 const std::string& contry_iso =
700 params.renderer_preferences.network_contry_iso;
701 if (!contry_iso.empty()) {
702 content_detectors_.push_back(linked_ptr<ContentDetector>(
703 new PhoneNumberDetector(contry_iso)));
705 content_detectors_.push_back(linked_ptr<ContentDetector>(
706 new EmailDetector()));
707 #endif
709 RenderThread::Get()->AddRoute(routing_id_, this);
710 // Take a reference on behalf of the RenderThread. This will be balanced
711 // when we receive ViewMsg_Close in the RenderWidget (which RenderView
712 // inherits from).
713 AddRef();
714 if (RenderThreadImpl::current()) {
715 RenderThreadImpl::current()->WidgetCreated();
716 if (is_hidden_)
717 RenderThreadImpl::current()->WidgetHidden();
720 // If this is a popup, we must wait for the CreatingNew_ACK message before
721 // completing initialization. Otherwise, we can finish it now.
722 if (opener_id_ == MSG_ROUTING_NONE) {
723 did_show_ = true;
724 CompleteInit();
727 g_view_map.Get().insert(std::make_pair(webview(), this));
728 g_routing_id_view_map.Get().insert(std::make_pair(routing_id_, this));
729 webview()->setDeviceScaleFactor(device_scale_factor_);
730 webview()->setDisplayMode(display_mode_);
731 webview()->settings()->setPreferCompositingToLCDTextEnabled(
732 PreferCompositingToLCDText(compositor_deps_, device_scale_factor_));
733 webview()->settings()->setThreadedScrollingEnabled(
734 !command_line.HasSwitch(switches::kDisableThreadedScrolling));
735 webview()->settings()->setRootLayerScrolls(
736 command_line.HasSwitch(switches::kRootLayerScrolls));
738 ApplyWebPreferences(webkit_preferences_, webview());
740 RenderFrameProxy* proxy = NULL;
741 if (params.proxy_routing_id != MSG_ROUTING_NONE) {
742 CHECK(params.swapped_out);
743 proxy = RenderFrameProxy::CreateProxyToReplaceFrame(
744 main_render_frame_.get(), params.proxy_routing_id);
745 main_render_frame_->set_render_frame_proxy(proxy);
748 // In --site-per-process, just use the WebRemoteFrame as the main frame.
749 if (command_line.HasSwitch(switches::kSitePerProcess) && proxy) {
750 webview()->setMainFrame(proxy->web_frame());
751 // Initialize the WebRemoteFrame with information replicated from the
752 // browser process.
753 proxy->SetReplicatedState(params.replicated_frame_state);
754 } else {
755 webview()->setMainFrame(main_render_frame_->GetWebFrame());
757 main_render_frame_->Initialize();
759 if (switches::IsTouchDragDropEnabled())
760 webview()->settings()->setTouchDragDropEnabled(true);
762 if (switches::IsTouchEditingEnabled())
763 webview()->settings()->setTouchEditingEnabled(true);
765 if (!params.frame_name.empty())
766 webview()->mainFrame()->setName(params.frame_name);
768 // TODO(davidben): Move this state from Blink into content.
769 if (params.window_was_created_with_opener)
770 webview()->setOpenedByDOM();
772 OnSetRendererPrefs(params.renderer_preferences);
774 ApplyBlinkSettings(command_line, webview()->settings());
776 if (!params.enable_auto_resize) {
777 OnResize(params.initial_size);
778 } else {
779 OnEnableAutoResize(params.min_size, params.max_size);
782 new MHTMLGenerator(this);
783 #if defined(OS_MACOSX)
784 new TextInputClientObserver(this);
785 #endif // defined(OS_MACOSX)
787 // TODO(dgozman): do this not for main frame, but for local frame roots.
788 if (blink::WebDevToolsAgent* devToolsAgent = GetWebDevToolsAgent(webview())) {
789 if (RenderWidgetCompositor* rwc = compositor())
790 devToolsAgent->setLayerTreeId(rwc->GetLayerTreeId());
793 // The next group of objects all implement RenderViewObserver, so are deleted
794 // along with the RenderView automatically.
795 mouse_lock_dispatcher_ = new RenderViewMouseLockDispatcher(this);
797 history_controller_.reset(new HistoryController(this));
799 new IdleUserDetector(this);
801 if (command_line.HasSwitch(switches::kDomAutomationController))
802 enabled_bindings_ |= BINDINGS_POLICY_DOM_AUTOMATION;
803 if (command_line.HasSwitch(switches::kStatsCollectionController))
804 enabled_bindings_ |= BINDINGS_POLICY_STATS_COLLECTION;
806 GetContentClient()->renderer()->RenderViewCreated(this);
808 // If we have an opener_id but we weren't created by a renderer, then
809 // it's the browser asking us to set our opener to another RenderView.
810 if (params.opener_route_id != MSG_ROUTING_NONE && !was_created_by_renderer) {
811 RenderViewImpl* opener_view = FromRoutingID(params.opener_route_id);
812 if (opener_view)
813 webview()->mainFrame()->setOpener(opener_view->webview()->mainFrame());
816 // If we are initially swapped out, navigate to kSwappedOutURL.
817 // This ensures we are in a unique origin that others cannot script.
818 if (is_swapped_out_ && webview()->mainFrame()->isWebLocalFrame())
819 main_render_frame_->NavigateToSwappedOutURL();
822 RenderViewImpl::~RenderViewImpl() {
823 for (BitmapMap::iterator it = disambiguation_bitmaps_.begin();
824 it != disambiguation_bitmaps_.end();
825 ++it)
826 delete it->second;
827 base::trace_event::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_);
829 // If file chooser is still waiting for answer, dispatch empty answer.
830 while (!file_chooser_completions_.empty()) {
831 if (file_chooser_completions_.front()->completion) {
832 file_chooser_completions_.front()->completion->didChooseFile(
833 WebVector<WebString>());
835 file_chooser_completions_.pop_front();
838 #if defined(OS_ANDROID)
839 // The date/time picker client is both a scoped_ptr member of this class and
840 // a RenderViewObserver. Reset it to prevent double deletion.
841 date_time_picker_client_.reset();
842 #endif
844 #ifndef NDEBUG
845 // Make sure we are no longer referenced by the ViewMap or RoutingIDViewMap.
846 ViewMap* views = g_view_map.Pointer();
847 for (ViewMap::iterator it = views->begin(); it != views->end(); ++it)
848 DCHECK_NE(this, it->second) << "Failed to call Close?";
849 RoutingIDViewMap* routing_id_views = g_routing_id_view_map.Pointer();
850 for (RoutingIDViewMap::iterator it = routing_id_views->begin();
851 it != routing_id_views->end(); ++it)
852 DCHECK_NE(this, it->second) << "Failed to call Close?";
853 #endif
855 FOR_EACH_OBSERVER(RenderViewObserver, observers_, RenderViewGone());
856 FOR_EACH_OBSERVER(RenderViewObserver, observers_, OnDestruct());
859 /*static*/
860 RenderViewImpl* RenderViewImpl::FromWebView(WebView* webview) {
861 ViewMap* views = g_view_map.Pointer();
862 ViewMap::iterator it = views->find(webview);
863 return it == views->end() ? NULL : it->second;
866 /*static*/
867 RenderView* RenderView::FromWebView(blink::WebView* webview) {
868 return RenderViewImpl::FromWebView(webview);
871 /*static*/
872 RenderViewImpl* RenderViewImpl::FromRoutingID(int32 routing_id) {
873 RoutingIDViewMap* views = g_routing_id_view_map.Pointer();
874 RoutingIDViewMap::iterator it = views->find(routing_id);
875 return it == views->end() ? NULL : it->second;
878 /*static*/
879 RenderView* RenderView::FromRoutingID(int routing_id) {
880 return RenderViewImpl::FromRoutingID(routing_id);
883 /* static */
884 size_t RenderViewImpl::GetRenderViewCount() {
885 return g_view_map.Get().size();
888 /*static*/
889 void RenderView::ForEach(RenderViewVisitor* visitor) {
890 ViewMap* views = g_view_map.Pointer();
891 for (ViewMap::iterator it = views->begin(); it != views->end(); ++it) {
892 if (!visitor->Visit(it->second))
893 return;
897 /*static*/
898 void RenderView::ApplyWebPreferences(const WebPreferences& prefs,
899 WebView* web_view) {
900 WebSettings* settings = web_view->settings();
901 ApplyFontsFromMap(prefs.standard_font_family_map,
902 SetStandardFontFamilyWrapper, settings);
903 ApplyFontsFromMap(prefs.fixed_font_family_map,
904 SetFixedFontFamilyWrapper, settings);
905 ApplyFontsFromMap(prefs.serif_font_family_map,
906 SetSerifFontFamilyWrapper, settings);
907 ApplyFontsFromMap(prefs.sans_serif_font_family_map,
908 SetSansSerifFontFamilyWrapper, settings);
909 ApplyFontsFromMap(prefs.cursive_font_family_map,
910 SetCursiveFontFamilyWrapper, settings);
911 ApplyFontsFromMap(prefs.fantasy_font_family_map,
912 SetFantasyFontFamilyWrapper, settings);
913 ApplyFontsFromMap(prefs.pictograph_font_family_map,
914 SetPictographFontFamilyWrapper, settings);
915 settings->setDefaultFontSize(prefs.default_font_size);
916 settings->setDefaultFixedFontSize(prefs.default_fixed_font_size);
917 settings->setMinimumFontSize(prefs.minimum_font_size);
918 settings->setMinimumLogicalFontSize(prefs.minimum_logical_font_size);
919 settings->setDefaultTextEncodingName(
920 base::ASCIIToUTF16(prefs.default_encoding));
921 settings->setJavaScriptEnabled(prefs.javascript_enabled);
922 settings->setWebSecurityEnabled(prefs.web_security_enabled);
923 settings->setJavaScriptCanOpenWindowsAutomatically(
924 prefs.javascript_can_open_windows_automatically);
925 settings->setLoadsImagesAutomatically(prefs.loads_images_automatically);
926 settings->setImagesEnabled(prefs.images_enabled);
927 settings->setPluginsEnabled(prefs.plugins_enabled);
928 settings->setDOMPasteAllowed(prefs.dom_paste_enabled);
929 settings->setShrinksStandaloneImagesToFit(
930 prefs.shrinks_standalone_images_to_fit);
931 settings->setUsesEncodingDetector(prefs.uses_universal_detector);
932 settings->setTextAreasAreResizable(prefs.text_areas_are_resizable);
933 settings->setAllowScriptsToCloseWindows(prefs.allow_scripts_to_close_windows);
934 settings->setDownloadableBinaryFontsEnabled(prefs.remote_fonts_enabled);
935 settings->setJavaScriptCanAccessClipboard(
936 prefs.javascript_can_access_clipboard);
937 WebRuntimeFeatures::enableXSLT(prefs.xslt_enabled);
938 WebRuntimeFeatures::enableSlimmingPaint(prefs.slimming_paint_enabled);
939 settings->setXSSAuditorEnabled(prefs.xss_auditor_enabled);
940 settings->setDNSPrefetchingEnabled(prefs.dns_prefetching_enabled);
941 settings->setLocalStorageEnabled(prefs.local_storage_enabled);
942 settings->setSyncXHRInDocumentsEnabled(prefs.sync_xhr_in_documents_enabled);
943 WebRuntimeFeatures::enableDatabase(prefs.databases_enabled);
944 settings->setOfflineWebApplicationCacheEnabled(
945 prefs.application_cache_enabled);
946 settings->setCaretBrowsingEnabled(prefs.caret_browsing_enabled);
947 settings->setHyperlinkAuditingEnabled(prefs.hyperlink_auditing_enabled);
948 settings->setCookieEnabled(prefs.cookie_enabled);
949 settings->setNavigateOnDragDrop(prefs.navigate_on_drag_drop);
951 settings->setJavaEnabled(prefs.java_enabled);
953 // By default, allow_universal_access_from_file_urls is set to false and thus
954 // we mitigate attacks from local HTML files by not granting file:// URLs
955 // universal access. Only test shell will enable this.
956 settings->setAllowUniversalAccessFromFileURLs(
957 prefs.allow_universal_access_from_file_urls);
958 settings->setAllowFileAccessFromFileURLs(
959 prefs.allow_file_access_from_file_urls);
961 // Enable the web audio API if requested on the command line.
962 settings->setWebAudioEnabled(prefs.webaudio_enabled);
964 // Enable experimental WebGL support if requested on command line
965 // and support is compiled in.
966 settings->setExperimentalWebGLEnabled(prefs.experimental_webgl_enabled);
968 // Disable GL multisampling if requested on command line.
969 settings->setOpenGLMultisamplingEnabled(prefs.gl_multisampling_enabled);
971 // Enable WebGL errors to the JS console if requested.
972 settings->setWebGLErrorsToConsoleEnabled(
973 prefs.webgl_errors_to_console_enabled);
975 // Uses the mock theme engine for scrollbars.
976 settings->setMockScrollbarsEnabled(prefs.mock_scrollbars_enabled);
978 // Enable gpu-accelerated 2d canvas if requested on the command line.
979 settings->setAccelerated2dCanvasEnabled(prefs.accelerated_2d_canvas_enabled);
981 settings->setMinimumAccelerated2dCanvasSize(
982 prefs.minimum_accelerated_2d_canvas_size);
984 // Disable antialiasing for 2d canvas if requested on the command line.
985 settings->setAntialiased2dCanvasEnabled(
986 !prefs.antialiased_2d_canvas_disabled);
988 // Enabled antialiasing of clips for 2d canvas if requested on the command
989 // line.
990 settings->setAntialiasedClips2dCanvasEnabled(
991 prefs.antialiased_clips_2d_canvas_enabled);
993 // Set MSAA sample count for 2d canvas if requested on the command line (or
994 // default value if not).
995 settings->setAccelerated2dCanvasMSAASampleCount(
996 prefs.accelerated_2d_canvas_msaa_sample_count);
998 WebRuntimeFeatures::enableTextBlobs(prefs.text_blobs_enabled);
1000 settings->setAsynchronousSpellCheckingEnabled(
1001 prefs.asynchronous_spell_checking_enabled);
1002 settings->setUnifiedTextCheckerEnabled(prefs.unified_textchecker_enabled);
1004 // Tabs to link is not part of the settings. WebCore calls
1005 // ChromeClient::tabsToLinks which is part of the glue code.
1006 web_view->setTabsToLinks(prefs.tabs_to_links);
1008 settings->setAllowDisplayOfInsecureContent(
1009 prefs.allow_displaying_insecure_content);
1010 settings->setAllowRunningOfInsecureContent(
1011 prefs.allow_running_insecure_content);
1012 settings->setDisableReadingFromCanvas(prefs.disable_reading_from_canvas);
1013 settings->setStrictMixedContentChecking(prefs.strict_mixed_content_checking);
1014 settings->setStrictPowerfulFeatureRestrictions(
1015 prefs.strict_powerful_feature_restrictions);
1016 settings->setPasswordEchoEnabled(prefs.password_echo_enabled);
1017 settings->setShouldPrintBackgrounds(prefs.should_print_backgrounds);
1018 settings->setShouldClearDocumentBackground(
1019 prefs.should_clear_document_background);
1020 settings->setEnableScrollAnimator(prefs.enable_scroll_animator);
1022 settings->setRegionBasedColumnsEnabled(prefs.region_based_columns_enabled);
1024 WebRuntimeFeatures::enableTouch(prefs.touch_enabled);
1025 settings->setMaxTouchPoints(prefs.pointer_events_max_touch_points);
1026 settings->setAvailablePointerTypes(prefs.available_pointer_types);
1027 settings->setPrimaryPointerType(
1028 static_cast<WebSettings::PointerType>(prefs.primary_pointer_type));
1029 settings->setAvailableHoverTypes(prefs.available_hover_types);
1030 settings->setPrimaryHoverType(
1031 static_cast<WebSettings::HoverType>(prefs.primary_hover_type));
1032 settings->setDeviceSupportsTouch(prefs.device_supports_touch);
1033 settings->setDeviceSupportsMouse(prefs.device_supports_mouse);
1034 settings->setEnableTouchAdjustment(prefs.touch_adjustment_enabled);
1036 settings->setDeferredImageDecodingEnabled(
1037 prefs.deferred_image_decoding_enabled);
1038 WebRuntimeFeatures::enableImageColorProfiles(
1039 prefs.image_color_profiles_enabled);
1040 settings->setShouldRespectImageOrientation(
1041 prefs.should_respect_image_orientation);
1043 settings->setUnsafePluginPastingEnabled(false);
1044 settings->setEditingBehavior(
1045 static_cast<WebSettings::EditingBehavior>(prefs.editing_behavior));
1047 settings->setSupportsMultipleWindows(prefs.supports_multiple_windows);
1049 settings->setViewportEnabled(prefs.viewport_enabled);
1050 settings->setLoadWithOverviewMode(prefs.initialize_at_minimum_page_scale);
1051 settings->setViewportMetaEnabled(prefs.viewport_meta_enabled);
1052 settings->setMainFrameResizesAreOrientationChanges(
1053 prefs.main_frame_resizes_are_orientation_changes);
1055 settings->setSmartInsertDeleteEnabled(prefs.smart_insert_delete_enabled);
1057 settings->setSpatialNavigationEnabled(prefs.spatial_navigation_enabled);
1059 settings->setSelectionIncludesAltImageText(true);
1061 settings->setV8CacheOptions(
1062 static_cast<WebSettings::V8CacheOptions>(prefs.v8_cache_options));
1064 settings->setImageAnimationPolicy(
1065 static_cast<WebSettings::ImageAnimationPolicy>(prefs.animation_policy));
1067 // Needs to happen before setIgnoreVIewportTagScaleLimits below.
1068 web_view->setDefaultPageScaleLimits(
1069 prefs.default_minimum_page_scale_factor,
1070 prefs.default_maximum_page_scale_factor);
1072 #if defined(OS_ANDROID)
1073 settings->setAllowCustomScrollbarInMainFrame(false);
1074 settings->setTextAutosizingEnabled(prefs.text_autosizing_enabled);
1075 settings->setAccessibilityFontScaleFactor(prefs.font_scale_factor);
1076 settings->setDeviceScaleAdjustment(prefs.device_scale_adjustment);
1077 settings->setFullscreenSupported(prefs.fullscreen_supported);
1078 web_view->setIgnoreViewportTagScaleLimits(prefs.force_enable_zoom);
1079 settings->setAutoZoomFocusedNodeToLegibleScale(true);
1080 settings->setDoubleTapToZoomEnabled(prefs.double_tap_to_zoom_enabled);
1081 settings->setMediaControlsOverlayPlayButtonEnabled(true);
1082 settings->setMediaPlaybackRequiresUserGesture(
1083 prefs.user_gesture_required_for_media_playback);
1084 settings->setDefaultVideoPosterURL(
1085 base::ASCIIToUTF16(prefs.default_video_poster_url.spec()));
1086 settings->setSupportDeprecatedTargetDensityDPI(
1087 prefs.support_deprecated_target_density_dpi);
1088 settings->setUseLegacyBackgroundSizeShorthandBehavior(
1089 prefs.use_legacy_background_size_shorthand_behavior);
1090 settings->setWideViewportQuirkEnabled(prefs.wide_viewport_quirk);
1091 settings->setUseWideViewport(prefs.use_wide_viewport);
1092 settings->setForceZeroLayoutHeight(prefs.force_zero_layout_height);
1093 settings->setViewportMetaLayoutSizeQuirk(
1094 prefs.viewport_meta_layout_size_quirk);
1095 settings->setViewportMetaMergeContentQuirk(
1096 prefs.viewport_meta_merge_content_quirk);
1097 settings->setViewportMetaNonUserScalableQuirk(
1098 prefs.viewport_meta_non_user_scalable_quirk);
1099 settings->setViewportMetaZeroValuesQuirk(
1100 prefs.viewport_meta_zero_values_quirk);
1101 settings->setClobberUserAgentInitialScaleQuirk(
1102 prefs.clobber_user_agent_initial_scale_quirk);
1103 settings->setIgnoreMainFrameOverflowHiddenQuirk(
1104 prefs.ignore_main_frame_overflow_hidden_quirk);
1105 settings->setReportScreenSizeInPhysicalPixelsQuirk(
1106 prefs.report_screen_size_in_physical_pixels_quirk);
1108 bool record_full_layer =
1109 RenderViewImpl::FromWebView(web_view)
1110 ? RenderViewImpl::FromWebView(web_view)->DoesRecordFullLayer()
1111 : false;
1112 settings->setMainFrameClipsContent(!record_full_layer);
1114 settings->setShrinksStandaloneImagesToFit(false);
1115 settings->setShrinksViewportContentToFit(true);
1116 settings->setUseMobileViewportStyle(true);
1117 #endif
1119 WebNetworkStateNotifier::setOnLine(prefs.is_online);
1120 WebNetworkStateNotifier::setWebConnectionType(
1121 NetConnectionTypeToWebConnectionType(prefs.connection_type));
1122 settings->setPinchVirtualViewportEnabled(
1123 prefs.pinch_virtual_viewport_enabled);
1125 settings->setPinchOverlayScrollbarThickness(
1126 prefs.pinch_overlay_scrollbar_thickness);
1127 settings->setUseSolidColorScrollbars(prefs.use_solid_color_scrollbars);
1129 settings->setShowContextMenuOnMouseUp(prefs.context_menu_on_mouse_up);
1131 #if defined(OS_MACOSX)
1132 settings->setDoubleTapToZoomEnabled(true);
1133 web_view->setMaximumLegibleScale(prefs.default_maximum_page_scale_factor);
1134 #endif
1137 /*static*/
1138 RenderViewImpl* RenderViewImpl::Create(const ViewMsg_New_Params& params,
1139 CompositorDependencies* compositor_deps,
1140 bool was_created_by_renderer) {
1141 DCHECK(params.view_id != MSG_ROUTING_NONE);
1142 RenderViewImpl* render_view = NULL;
1143 if (g_create_render_view_impl)
1144 render_view = g_create_render_view_impl(params);
1145 else
1146 render_view = new RenderViewImpl(params);
1148 render_view->Initialize(params, compositor_deps, was_created_by_renderer);
1149 return render_view;
1152 // static
1153 void RenderViewImpl::InstallCreateHook(
1154 RenderViewImpl* (*create_render_view_impl)(const ViewMsg_New_Params&)) {
1155 CHECK(!g_create_render_view_impl);
1156 g_create_render_view_impl = create_render_view_impl;
1159 void RenderViewImpl::AddObserver(RenderViewObserver* observer) {
1160 observers_.AddObserver(observer);
1163 void RenderViewImpl::RemoveObserver(RenderViewObserver* observer) {
1164 observer->RenderViewGone();
1165 observers_.RemoveObserver(observer);
1168 blink::WebView* RenderViewImpl::webview() const {
1169 return static_cast<blink::WebView*>(webwidget());
1172 #if defined(ENABLE_PLUGINS)
1173 void RenderViewImpl::PepperInstanceCreated(
1174 PepperPluginInstanceImpl* instance) {
1175 active_pepper_instances_.insert(instance);
1178 void RenderViewImpl::PepperInstanceDeleted(
1179 PepperPluginInstanceImpl* instance) {
1180 active_pepper_instances_.erase(instance);
1182 if (pepper_last_mouse_event_target_ == instance)
1183 pepper_last_mouse_event_target_ = NULL;
1184 if (focused_pepper_plugin_ == instance)
1185 PepperFocusChanged(instance, false);
1188 void RenderViewImpl::PepperFocusChanged(PepperPluginInstanceImpl* instance,
1189 bool focused) {
1190 if (focused)
1191 focused_pepper_plugin_ = instance;
1192 else if (focused_pepper_plugin_ == instance)
1193 focused_pepper_plugin_ = NULL;
1195 UpdateTextInputType();
1196 UpdateSelectionBounds();
1199 void RenderViewImpl::RegisterPluginDelegate(WebPluginDelegateProxy* delegate) {
1200 plugin_delegates_.insert(delegate);
1201 // If the renderer is visible, set initial visibility and focus state.
1202 if (!is_hidden()) {
1203 #if defined(OS_MACOSX)
1204 delegate->SetContainerVisibility(true);
1205 if (webview() && webview()->isActive())
1206 delegate->SetWindowFocus(true);
1207 #endif
1209 // Plugins start assuming the content has focus (so that they work in
1210 // environments where RenderView isn't hosting them), so we always have to
1211 // set the initial state. See webplugin_delegate_impl.h for details.
1212 delegate->SetContentAreaFocus(has_focus());
1215 void RenderViewImpl::UnregisterPluginDelegate(
1216 WebPluginDelegateProxy* delegate) {
1217 plugin_delegates_.erase(delegate);
1220 #if defined(OS_WIN)
1221 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1222 if (focused)
1223 focused_plugin_id_ = plugin_id;
1224 else
1225 focused_plugin_id_ = -1;
1227 #endif
1229 #if defined(OS_MACOSX)
1230 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1231 Send(new ViewHostMsg_PluginFocusChanged(routing_id(), focused, plugin_id));
1234 void RenderViewImpl::OnGetRenderedText() {
1235 if (!webview())
1236 return;
1237 // Get rendered text from WebLocalFrame.
1238 // TODO: Currently IPC truncates any data that has a
1239 // size > kMaximumMessageSize. May be split the text into smaller chunks and
1240 // send back using multiple IPC. See http://crbug.com/393444.
1241 static const size_t kMaximumMessageSize = 8 * 1024 * 1024;
1242 std::string text = webview()->mainFrame()->contentAsText(
1243 kMaximumMessageSize).utf8();
1245 Send(new ViewMsg_GetRenderedTextCompleted(routing_id(), text));
1248 void RenderViewImpl::StartPluginIme() {
1249 IPC::Message* msg = new ViewHostMsg_StartPluginIme(routing_id());
1250 // This message can be sent during event-handling, and needs to be delivered
1251 // within that context.
1252 msg->set_unblock(true);
1253 Send(msg);
1255 #endif // defined(OS_MACOSX)
1257 #endif // ENABLE_PLUGINS
1259 void RenderViewImpl::TransferActiveWheelFlingAnimation(
1260 const blink::WebActiveWheelFlingParameters& params) {
1261 if (webview())
1262 webview()->transferActiveWheelFlingAnimation(params);
1265 bool RenderViewImpl::HasIMETextFocus() {
1266 return GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE;
1269 bool RenderViewImpl::OnMessageReceived(const IPC::Message& message) {
1270 WebFrame* main_frame = webview() ? webview()->mainFrame() : NULL;
1271 if (main_frame && main_frame->isWebLocalFrame())
1272 GetContentClient()->SetActiveURL(main_frame->document().url());
1274 ObserverListBase<RenderViewObserver>::Iterator it(&observers_);
1275 RenderViewObserver* observer;
1276 while ((observer = it.GetNext()) != NULL)
1277 if (observer->OnMessageReceived(message))
1278 return true;
1280 bool handled = true;
1281 IPC_BEGIN_MESSAGE_MAP(RenderViewImpl, message)
1282 IPC_MESSAGE_HANDLER(InputMsg_ExecuteEditCommand, OnExecuteEditCommand)
1283 IPC_MESSAGE_HANDLER(InputMsg_MoveCaret, OnMoveCaret)
1284 IPC_MESSAGE_HANDLER(InputMsg_ScrollFocusedEditableNodeIntoRect,
1285 OnScrollFocusedEditableNodeIntoRect)
1286 IPC_MESSAGE_HANDLER(InputMsg_SetEditCommandsForNextKeyEvent,
1287 OnSetEditCommandsForNextKeyEvent)
1288 IPC_MESSAGE_HANDLER(ViewMsg_CopyImageAt, OnCopyImageAt)
1289 IPC_MESSAGE_HANDLER(ViewMsg_SaveImageAt, OnSaveImageAt)
1290 IPC_MESSAGE_HANDLER(ViewMsg_Find, OnFind)
1291 IPC_MESSAGE_HANDLER(ViewMsg_StopFinding, OnStopFinding)
1292 IPC_MESSAGE_HANDLER(ViewMsg_ResetPageScale, OnResetPageScale)
1293 IPC_MESSAGE_HANDLER(ViewMsg_Zoom, OnZoom)
1294 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForLoadingURL,
1295 OnSetZoomLevelForLoadingURL)
1296 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForView,
1297 OnSetZoomLevelForView)
1298 IPC_MESSAGE_HANDLER(ViewMsg_SetPageEncoding, OnSetPageEncoding)
1299 IPC_MESSAGE_HANDLER(ViewMsg_ResetPageEncodingToDefault,
1300 OnResetPageEncodingToDefault)
1301 IPC_MESSAGE_HANDLER(DragMsg_TargetDragEnter, OnDragTargetDragEnter)
1302 IPC_MESSAGE_HANDLER(DragMsg_TargetDragOver, OnDragTargetDragOver)
1303 IPC_MESSAGE_HANDLER(DragMsg_TargetDragLeave, OnDragTargetDragLeave)
1304 IPC_MESSAGE_HANDLER(DragMsg_TargetDrop, OnDragTargetDrop)
1305 IPC_MESSAGE_HANDLER(DragMsg_SourceEnded, OnDragSourceEnded)
1306 IPC_MESSAGE_HANDLER(DragMsg_SourceSystemDragEnded,
1307 OnDragSourceSystemDragEnded)
1308 IPC_MESSAGE_HANDLER(ViewMsg_AllowBindings, OnAllowBindings)
1309 IPC_MESSAGE_HANDLER(ViewMsg_SetInitialFocus, OnSetInitialFocus)
1310 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTargetURL_ACK, OnUpdateTargetURLAck)
1311 IPC_MESSAGE_HANDLER(ViewMsg_UpdateWebPreferences, OnUpdateWebPreferences)
1312 IPC_MESSAGE_HANDLER(ViewMsg_EnumerateDirectoryResponse,
1313 OnEnumerateDirectoryResponse)
1314 IPC_MESSAGE_HANDLER(ViewMsg_RunFileChooserResponse, OnFileChooserResponse)
1315 IPC_MESSAGE_HANDLER(ViewMsg_SuppressDialogsUntilSwapOut,
1316 OnSuppressDialogsUntilSwapOut)
1317 IPC_MESSAGE_HANDLER(ViewMsg_ClosePage, OnClosePage)
1318 IPC_MESSAGE_HANDLER(ViewMsg_ThemeChanged, OnThemeChanged)
1319 IPC_MESSAGE_HANDLER(ViewMsg_MoveOrResizeStarted, OnMoveOrResizeStarted)
1320 IPC_MESSAGE_HANDLER(ViewMsg_ClearFocusedElement, OnClearFocusedElement)
1321 IPC_MESSAGE_HANDLER(ViewMsg_SetBackgroundOpaque, OnSetBackgroundOpaque)
1322 IPC_MESSAGE_HANDLER(ViewMsg_EnablePreferredSizeChangedMode,
1323 OnEnablePreferredSizeChangedMode)
1324 IPC_MESSAGE_HANDLER(ViewMsg_EnableAutoResize, OnEnableAutoResize)
1325 IPC_MESSAGE_HANDLER(ViewMsg_DisableAutoResize, OnDisableAutoResize)
1326 IPC_MESSAGE_HANDLER(ViewMsg_DisableScrollbarsForSmallWindows,
1327 OnDisableScrollbarsForSmallWindows)
1328 IPC_MESSAGE_HANDLER(ViewMsg_SetRendererPrefs, OnSetRendererPrefs)
1329 IPC_MESSAGE_HANDLER(ViewMsg_MediaPlayerActionAt, OnMediaPlayerActionAt)
1330 IPC_MESSAGE_HANDLER(ViewMsg_PluginActionAt, OnPluginActionAt)
1331 IPC_MESSAGE_HANDLER(ViewMsg_SetActive, OnSetActive)
1332 IPC_MESSAGE_HANDLER(ViewMsg_GetAllSavableResourceLinksForCurrentPage,
1333 OnGetAllSavableResourceLinksForCurrentPage)
1334 IPC_MESSAGE_HANDLER(
1335 ViewMsg_GetSerializedHtmlDataForCurrentPageWithLocalLinks,
1336 OnGetSerializedHtmlDataForCurrentPageWithLocalLinks)
1337 IPC_MESSAGE_HANDLER(ViewMsg_ShowContextMenu, OnShowContextMenu)
1338 // TODO(viettrungluu): Move to a separate message filter.
1339 IPC_MESSAGE_HANDLER(ViewMsg_SetHistoryOffsetAndLength,
1340 OnSetHistoryOffsetAndLength)
1341 IPC_MESSAGE_HANDLER(ViewMsg_EnableViewSourceMode, OnEnableViewSourceMode)
1342 IPC_MESSAGE_HANDLER(ViewMsg_ReleaseDisambiguationPopupBitmap,
1343 OnReleaseDisambiguationPopupBitmap)
1344 IPC_MESSAGE_HANDLER(ViewMsg_ForceRedraw, OnForceRedraw)
1345 IPC_MESSAGE_HANDLER(ViewMsg_SelectWordAroundCaret, OnSelectWordAroundCaret)
1346 #if defined(OS_ANDROID)
1347 IPC_MESSAGE_HANDLER(InputMsg_ActivateNearestFindResult,
1348 OnActivateNearestFindResult)
1349 IPC_MESSAGE_HANDLER(ViewMsg_FindMatchRects, OnFindMatchRects)
1350 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTopControlsState,
1351 OnUpdateTopControlsState)
1352 IPC_MESSAGE_HANDLER(ViewMsg_ExtractSmartClipData, OnExtractSmartClipData)
1353 #elif defined(OS_MACOSX)
1354 IPC_MESSAGE_HANDLER(ViewMsg_GetRenderedText,
1355 OnGetRenderedText)
1356 IPC_MESSAGE_HANDLER(ViewMsg_PluginImeCompositionCompleted,
1357 OnPluginImeCompositionCompleted)
1358 IPC_MESSAGE_HANDLER(ViewMsg_SetInLiveResize, OnSetInLiveResize)
1359 IPC_MESSAGE_HANDLER(ViewMsg_SetWindowVisibility, OnSetWindowVisibility)
1360 IPC_MESSAGE_HANDLER(ViewMsg_WindowFrameChanged, OnWindowFrameChanged)
1361 #endif
1362 // Adding a new message? Add platform independent ones first, then put the
1363 // platform specific ones at the end.
1365 // Have the super handle all other messages.
1366 IPC_MESSAGE_UNHANDLED(handled = RenderWidget::OnMessageReceived(message))
1367 IPC_END_MESSAGE_MAP()
1369 return handled;
1372 void RenderViewImpl::OnSelectWordAroundCaret() {
1373 if (!webview())
1374 return;
1376 handling_input_event_ = true;
1377 webview()->focusedFrame()->selectWordAroundCaret();
1378 handling_input_event_ = false;
1381 void RenderViewImpl::OnCopyImageAt(int x, int y) {
1382 webview()->copyImageAt(WebPoint(x, y));
1385 void RenderViewImpl::OnSaveImageAt(int x, int y) {
1386 webview()->saveImageAt(WebPoint(x, y));
1389 void RenderViewImpl::OnUpdateTargetURLAck() {
1390 // Check if there is a targeturl waiting to be sent.
1391 if (target_url_status_ == TARGET_PENDING)
1392 Send(new ViewHostMsg_UpdateTargetURL(routing_id_, pending_target_url_));
1394 target_url_status_ = TARGET_NONE;
1397 void RenderViewImpl::OnExecuteEditCommand(const std::string& name,
1398 const std::string& value) {
1399 if (!webview() || !webview()->focusedFrame())
1400 return;
1402 webview()->focusedFrame()->executeCommand(
1403 WebString::fromUTF8(name), WebString::fromUTF8(value));
1406 void RenderViewImpl::OnMoveCaret(const gfx::Point& point) {
1407 if (!webview())
1408 return;
1410 Send(new InputHostMsg_MoveCaret_ACK(routing_id_));
1412 webview()->focusedFrame()->moveCaretSelection(point);
1415 void RenderViewImpl::OnScrollFocusedEditableNodeIntoRect(
1416 const gfx::Rect& rect) {
1417 if (has_scrolled_focused_editable_node_into_rect_ &&
1418 rect == rect_for_scrolled_focused_editable_node_) {
1419 FocusChangeComplete();
1420 return;
1423 blink::WebElement element = GetFocusedElement();
1424 bool will_animate = false;
1425 if (!element.isNull() && IsEditableNode(element)) {
1426 rect_for_scrolled_focused_editable_node_ = rect;
1427 has_scrolled_focused_editable_node_into_rect_ = true;
1428 will_animate = webview()->scrollFocusedNodeIntoRect(rect);
1431 if (!will_animate)
1432 FocusChangeComplete();
1435 void RenderViewImpl::OnSetEditCommandsForNextKeyEvent(
1436 const EditCommands& edit_commands) {
1437 edit_commands_ = edit_commands;
1440 void RenderViewImpl::OnSetHistoryOffsetAndLength(int history_offset,
1441 int history_length) {
1442 DCHECK_GE(history_offset, -1);
1443 DCHECK_GE(history_length, 0);
1445 history_list_offset_ = history_offset;
1446 history_list_length_ = history_length;
1449 void RenderViewImpl::OnSetInitialFocus(bool reverse) {
1450 if (!webview())
1451 return;
1452 webview()->setInitialFocus(reverse);
1455 #if defined(OS_MACOSX)
1456 void RenderViewImpl::OnSetInLiveResize(bool in_live_resize) {
1457 if (!webview())
1458 return;
1459 if (in_live_resize)
1460 webview()->willStartLiveResize();
1461 else
1462 webview()->willEndLiveResize();
1464 #endif
1466 ///////////////////////////////////////////////////////////////////////////////
1468 // Sends the current history state to the browser so it will be saved before we
1469 // navigate to a new page.
1470 void RenderViewImpl::UpdateSessionHistory(WebFrame* frame) {
1471 // If we have a valid page ID at this point, then it corresponds to the page
1472 // we are navigating away from. Otherwise, this is the first navigation, so
1473 // there is no past session history to record.
1474 if (page_id_ == -1)
1475 return;
1476 SendUpdateState(history_controller_->GetCurrentEntry());
1479 void RenderViewImpl::SendUpdateState(HistoryEntry* entry) {
1480 if (!entry)
1481 return;
1483 // Don't send state updates for kSwappedOutURL.
1484 if (entry->root().urlString() == WebString::fromUTF8(kSwappedOutURL))
1485 return;
1487 Send(new ViewHostMsg_UpdateState(
1488 routing_id_, page_id_, HistoryEntryToPageState(entry)));
1491 bool RenderViewImpl::SendAndRunNestedMessageLoop(IPC::SyncMessage* message) {
1492 // Before WebKit asks us to show an alert (etc.), it takes care of doing the
1493 // equivalent of WebView::willEnterModalLoop. In the case of showModalDialog
1494 // it is particularly important that we do not call willEnterModalLoop as
1495 // that would defer resource loads for the dialog itself.
1496 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
1497 RenderThreadImpl::current()->DoNotNotifyWebKitOfModalLoop();
1499 message->EnableMessagePumping(); // Runs a nested message loop.
1500 return Send(message);
1503 void RenderViewImpl::OnForceRedraw(int id) {
1504 ui::LatencyInfo latency_info;
1505 if (id) {
1506 latency_info.AddLatencyNumber(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
1508 id);
1510 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1511 if (RenderWidgetCompositor* rwc = compositor()) {
1512 latency_info_swap_promise_monitor =
1513 rwc->CreateLatencyInfoSwapPromiseMonitor(&latency_info).Pass();
1515 ScheduleCompositeWithForcedRedraw();
1518 // blink::WebViewClient ------------------------------------------------------
1520 WebView* RenderViewImpl::createView(WebLocalFrame* creator,
1521 const WebURLRequest& request,
1522 const WebWindowFeatures& features,
1523 const WebString& frame_name,
1524 WebNavigationPolicy policy,
1525 bool suppress_opener) {
1526 ViewHostMsg_CreateWindow_Params params;
1527 params.opener_id = routing_id_;
1528 params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
1529 if (GetContentClient()->renderer()->AllowPopup())
1530 params.user_gesture = true;
1531 params.window_container_type = WindowFeaturesToContainerType(features);
1532 params.session_storage_namespace_id = session_storage_namespace_id_;
1533 if (frame_name != "_blank")
1534 params.frame_name = frame_name;
1535 params.opener_render_frame_id =
1536 RenderFrameImpl::FromWebFrame(creator)->GetRoutingID();
1537 params.opener_url = creator->document().url();
1538 params.opener_top_level_frame_url = creator->top()->document().url();
1539 GURL security_url(creator->document().securityOrigin().toString());
1540 if (!security_url.is_valid())
1541 security_url = GURL();
1542 params.opener_security_origin = security_url;
1543 params.opener_suppressed = suppress_opener;
1544 params.disposition = NavigationPolicyToDisposition(policy);
1545 if (!request.isNull()) {
1546 params.target_url = request.url();
1547 params.referrer = GetReferrerFromRequest(creator, request);
1549 params.features = features;
1551 for (size_t i = 0; i < features.additionalFeatures.size(); ++i)
1552 params.additional_features.push_back(features.additionalFeatures[i]);
1554 int32 routing_id = MSG_ROUTING_NONE;
1555 int32 main_frame_routing_id = MSG_ROUTING_NONE;
1556 int32 surface_id = 0;
1557 int64 cloned_session_storage_namespace_id = 0;
1559 RenderThread::Get()->Send(new ViewHostMsg_CreateWindow(
1560 params, &routing_id, &main_frame_routing_id, &surface_id,
1561 &cloned_session_storage_namespace_id));
1562 if (routing_id == MSG_ROUTING_NONE)
1563 return NULL;
1565 WebUserGestureIndicator::consumeUserGesture();
1567 // While this view may be a background extension page, it can spawn a visible
1568 // render view. So we just assume that the new one is not another background
1569 // page instead of passing on our own value.
1570 // TODO(vangelis): Can we tell if the new view will be a background page?
1571 bool never_visible = false;
1573 ViewMsg_Resize_Params initial_size = ViewMsg_Resize_Params();
1574 initial_size.screen_info = screen_info_;
1576 // The initial hidden state for the RenderViewImpl here has to match what the
1577 // browser will eventually decide for the given disposition. Since we have to
1578 // return from this call synchronously, we just have to make our best guess
1579 // and rely on the browser sending a WasHidden / WasShown message if it
1580 // disagrees.
1581 ViewMsg_New_Params view_params;
1582 view_params.opener_route_id = routing_id_;
1583 view_params.window_was_created_with_opener = true;
1584 view_params.renderer_preferences = renderer_preferences_;
1585 view_params.web_preferences = webkit_preferences_;
1586 view_params.view_id = routing_id;
1587 view_params.main_frame_routing_id = main_frame_routing_id;
1588 view_params.surface_id = surface_id;
1589 view_params.session_storage_namespace_id =
1590 cloned_session_storage_namespace_id;
1591 // WebCore will take care of setting the correct name.
1592 view_params.frame_name = base::string16();
1593 view_params.swapped_out = false;
1594 view_params.replicated_frame_state = FrameReplicationState();
1595 view_params.proxy_routing_id = MSG_ROUTING_NONE;
1596 view_params.hidden = (params.disposition == NEW_BACKGROUND_TAB);
1597 view_params.never_visible = never_visible;
1598 view_params.next_page_id = 1;
1599 view_params.initial_size = initial_size;
1600 view_params.enable_auto_resize = false;
1601 view_params.min_size = gfx::Size();
1602 view_params.max_size = gfx::Size();
1604 RenderViewImpl* view =
1605 RenderViewImpl::Create(view_params, compositor_deps_, true);
1606 view->opened_by_user_gesture_ = params.user_gesture;
1608 // Record whether the creator frame is trying to suppress the opener field.
1609 view->opener_suppressed_ = params.opener_suppressed;
1611 return view->webview();
1614 WebWidget* RenderViewImpl::createPopupMenu(blink::WebPopupType popup_type) {
1615 RenderWidget* widget = RenderWidget::Create(routing_id_, compositor_deps_,
1616 popup_type, screen_info_);
1617 if (!widget)
1618 return NULL;
1619 if (screen_metrics_emulator_) {
1620 widget->SetPopupOriginAdjustmentsForEmulation(
1621 screen_metrics_emulator_.get());
1623 return widget->webwidget();
1626 WebStorageNamespace* RenderViewImpl::createSessionStorageNamespace() {
1627 CHECK(session_storage_namespace_id_ != kInvalidSessionStorageNamespaceId);
1628 return new WebStorageNamespaceImpl(session_storage_namespace_id_);
1631 void RenderViewImpl::printPage(WebLocalFrame* frame) {
1632 FOR_EACH_OBSERVER(RenderViewObserver, observers_,
1633 PrintPage(frame, handling_input_event_));
1636 void RenderViewImpl::saveImageFromDataURL(const blink::WebString& data_url) {
1637 // Note: We should basically send GURL but we use size-limited string instead
1638 // in order to send a larger data url to save a image for <canvas> or <img>.
1639 if (data_url.length() < kMaxLengthOfDataURLString)
1640 Send(new ViewHostMsg_SaveImageFromDataURL(routing_id_, data_url.utf8()));
1643 bool RenderViewImpl::enumerateChosenDirectory(
1644 const WebString& path,
1645 WebFileChooserCompletion* chooser_completion) {
1646 int id = enumeration_completion_id_++;
1647 enumeration_completions_[id] = chooser_completion;
1648 return Send(new ViewHostMsg_EnumerateDirectory(
1649 routing_id_,
1651 base::FilePath::FromUTF16Unsafe(path)));
1654 void RenderViewImpl::FrameDidStartLoading(WebFrame* frame) {
1655 DCHECK_GE(frames_in_progress_, 0);
1656 if (frames_in_progress_ == 0)
1657 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStartLoading());
1658 frames_in_progress_++;
1661 void RenderViewImpl::FrameDidStopLoading(WebFrame* frame) {
1662 // TODO(japhet): This should be a DCHECK, but the pdf plugin sometimes
1663 // calls DidStopLoading() without a matching DidStartLoading().
1664 if (frames_in_progress_ == 0)
1665 return;
1666 frames_in_progress_--;
1667 if (frames_in_progress_ == 0) {
1668 DidStopLoadingIcons();
1669 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStopLoading());
1673 void RenderViewImpl::didCancelCompositionOnSelectionChange() {
1674 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
1677 bool RenderViewImpl::handleCurrentKeyboardEvent() {
1678 if (edit_commands_.empty())
1679 return false;
1681 WebFrame* frame = webview()->focusedFrame();
1682 if (!frame)
1683 return false;
1685 EditCommands::iterator it = edit_commands_.begin();
1686 EditCommands::iterator end = edit_commands_.end();
1688 bool did_execute_command = false;
1689 for (; it != end; ++it) {
1690 // In gtk and cocoa, it's possible to bind multiple edit commands to one
1691 // key (but it's the exception). Once one edit command is not executed, it
1692 // seems safest to not execute the rest.
1693 if (!frame->executeCommand(WebString::fromUTF8(it->name),
1694 WebString::fromUTF8(it->value),
1695 GetFocusedElement()))
1696 break;
1697 did_execute_command = true;
1700 return did_execute_command;
1703 bool RenderViewImpl::runFileChooser(
1704 const blink::WebFileChooserParams& params,
1705 WebFileChooserCompletion* chooser_completion) {
1706 // Do not open the file dialog in a hidden RenderView.
1707 if (is_hidden())
1708 return false;
1709 FileChooserParams ipc_params;
1710 if (params.directory)
1711 ipc_params.mode = FileChooserParams::UploadFolder;
1712 else if (params.multiSelect)
1713 ipc_params.mode = FileChooserParams::OpenMultiple;
1714 else if (params.saveAs)
1715 ipc_params.mode = FileChooserParams::Save;
1716 else
1717 ipc_params.mode = FileChooserParams::Open;
1718 ipc_params.title = params.title;
1719 ipc_params.default_file_name =
1720 base::FilePath::FromUTF16Unsafe(params.initialValue).BaseName();
1721 ipc_params.accept_types.reserve(params.acceptTypes.size());
1722 for (size_t i = 0; i < params.acceptTypes.size(); ++i)
1723 ipc_params.accept_types.push_back(params.acceptTypes[i]);
1724 ipc_params.need_local_path = params.needLocalPath;
1725 #if defined(OS_ANDROID)
1726 ipc_params.capture = params.useMediaCapture;
1727 #endif
1729 return ScheduleFileChooser(ipc_params, chooser_completion);
1732 void RenderViewImpl::SetValidationMessageDirection(
1733 base::string16* wrapped_main_text,
1734 blink::WebTextDirection main_text_hint,
1735 base::string16* wrapped_sub_text,
1736 blink::WebTextDirection sub_text_hint) {
1737 if (main_text_hint == blink::WebTextDirectionLeftToRight) {
1738 *wrapped_main_text =
1739 base::i18n::GetDisplayStringInLTRDirectionality(*wrapped_main_text);
1740 } else if (main_text_hint == blink::WebTextDirectionRightToLeft &&
1741 !base::i18n::IsRTL()) {
1742 base::i18n::WrapStringWithRTLFormatting(wrapped_main_text);
1745 if (!wrapped_sub_text->empty()) {
1746 if (sub_text_hint == blink::WebTextDirectionLeftToRight) {
1747 *wrapped_sub_text =
1748 base::i18n::GetDisplayStringInLTRDirectionality(*wrapped_sub_text);
1749 } else if (sub_text_hint == blink::WebTextDirectionRightToLeft) {
1750 base::i18n::WrapStringWithRTLFormatting(wrapped_sub_text);
1755 void RenderViewImpl::showValidationMessage(
1756 const blink::WebRect& anchor_in_root_view,
1757 const blink::WebString& main_text,
1758 blink::WebTextDirection main_text_hint,
1759 const blink::WebString& sub_text,
1760 blink::WebTextDirection sub_text_hint) {
1761 base::string16 wrapped_main_text = main_text;
1762 base::string16 wrapped_sub_text = sub_text;
1764 SetValidationMessageDirection(
1765 &wrapped_main_text, main_text_hint, &wrapped_sub_text, sub_text_hint);
1767 Send(new ViewHostMsg_ShowValidationMessage(
1768 routing_id(), AdjustValidationMessageAnchor(anchor_in_root_view),
1769 wrapped_main_text, wrapped_sub_text));
1772 void RenderViewImpl::hideValidationMessage() {
1773 Send(new ViewHostMsg_HideValidationMessage(routing_id()));
1776 void RenderViewImpl::moveValidationMessage(
1777 const blink::WebRect& anchor_in_root_view) {
1778 Send(new ViewHostMsg_MoveValidationMessage(
1779 routing_id(), AdjustValidationMessageAnchor(anchor_in_root_view)));
1782 void RenderViewImpl::setStatusText(const WebString& text) {
1785 void RenderViewImpl::UpdateTargetURL(const GURL& url,
1786 const GURL& fallback_url) {
1787 GURL latest_url = url.is_empty() ? fallback_url : url;
1788 if (latest_url == target_url_)
1789 return;
1791 // Tell the browser to display a destination link.
1792 if (target_url_status_ == TARGET_INFLIGHT ||
1793 target_url_status_ == TARGET_PENDING) {
1794 // If we have a request in-flight, save the URL to be sent when we
1795 // receive an ACK to the in-flight request. We can happily overwrite
1796 // any existing pending sends.
1797 pending_target_url_ = latest_url;
1798 target_url_status_ = TARGET_PENDING;
1799 } else {
1800 // URLs larger than |MaxURLChars()| cannot be sent through IPC -
1801 // see |ParamTraits<GURL>|.
1802 if (latest_url.possibly_invalid_spec().size() > GetMaxURLChars())
1803 latest_url = GURL();
1804 Send(new ViewHostMsg_UpdateTargetURL(routing_id_, latest_url));
1805 target_url_ = latest_url;
1806 target_url_status_ = TARGET_INFLIGHT;
1810 gfx::RectF RenderViewImpl::ClientRectToPhysicalWindowRect(
1811 const gfx::RectF& rect) const {
1812 gfx::RectF window_rect = rect;
1813 window_rect.Scale(device_scale_factor_ * webview()->pageScaleFactor());
1814 return window_rect;
1817 void RenderViewImpl::StartNavStateSyncTimerIfNecessary() {
1818 // No need to update state if no page has committed yet.
1819 if (page_id_ == -1)
1820 return;
1822 int delay;
1823 if (send_content_state_immediately_)
1824 delay = 0;
1825 else if (is_hidden())
1826 delay = kDelaySecondsForContentStateSyncHidden;
1827 else
1828 delay = kDelaySecondsForContentStateSync;
1830 if (nav_state_sync_timer_.IsRunning()) {
1831 // The timer is already running. If the delay of the timer maches the amount
1832 // we want to delay by, then return. Otherwise stop the timer so that it
1833 // gets started with the right delay.
1834 if (nav_state_sync_timer_.GetCurrentDelay().InSeconds() == delay)
1835 return;
1836 nav_state_sync_timer_.Stop();
1839 nav_state_sync_timer_.Start(FROM_HERE, TimeDelta::FromSeconds(delay), this,
1840 &RenderViewImpl::SyncNavigationState);
1843 void RenderViewImpl::setMouseOverURL(const WebURL& url) {
1844 mouse_over_url_ = GURL(url);
1845 UpdateTargetURL(mouse_over_url_, focus_url_);
1848 void RenderViewImpl::setKeyboardFocusURL(const WebURL& url) {
1849 focus_url_ = GURL(url);
1850 UpdateTargetURL(focus_url_, mouse_over_url_);
1853 void RenderViewImpl::startDragging(WebLocalFrame* frame,
1854 const WebDragData& data,
1855 WebDragOperationsMask mask,
1856 const WebImage& image,
1857 const WebPoint& webImageOffset) {
1858 DropData drop_data(DropDataBuilder::Build(data));
1859 drop_data.referrer_policy = frame->document().referrerPolicy();
1860 gfx::Vector2d imageOffset(webImageOffset.x, webImageOffset.y);
1861 Send(new DragHostMsg_StartDragging(routing_id_,
1862 drop_data,
1863 mask,
1864 image.getSkBitmap(),
1865 imageOffset,
1866 possible_drag_event_info_));
1869 bool RenderViewImpl::acceptsLoadDrops() {
1870 return renderer_preferences_.can_accept_load_drops;
1873 void RenderViewImpl::focusNext() {
1874 Send(new ViewHostMsg_TakeFocus(routing_id_, false));
1877 void RenderViewImpl::focusPrevious() {
1878 Send(new ViewHostMsg_TakeFocus(routing_id_, true));
1881 void RenderViewImpl::focusedNodeChanged(const WebNode& fromNode,
1882 const WebNode& toNode) {
1883 has_scrolled_focused_editable_node_into_rect_ = false;
1885 gfx::Rect node_bounds;
1886 if (!toNode.isNull() && toNode.isElementNode()) {
1887 WebNode web_node = const_cast<WebNode&>(toNode);
1888 node_bounds = gfx::Rect(web_node.to<WebElement>().boundsInViewportSpace());
1890 Send(new ViewHostMsg_FocusedNodeChanged(routing_id_, IsEditableNode(toNode),
1891 node_bounds));
1893 // TODO(estade): remove.
1894 FOR_EACH_OBSERVER(RenderViewObserver, observers_, FocusedNodeChanged(toNode));
1896 RenderFrameImpl* previous_frame = nullptr;
1897 if (!fromNode.isNull())
1898 previous_frame = RenderFrameImpl::FromWebFrame(fromNode.document().frame());
1899 RenderFrameImpl* new_frame = nullptr;
1900 if (!toNode.isNull())
1901 new_frame = RenderFrameImpl::FromWebFrame(toNode.document().frame());
1903 if (previous_frame && previous_frame != new_frame)
1904 previous_frame->FocusedNodeChanged(WebNode());
1905 if (new_frame)
1906 new_frame->FocusedNodeChanged(toNode);
1908 // TODO(dmazzoni): remove once there's a separate a11y tree per frame.
1909 GetMainRenderFrame()->FocusedNodeChangedForAccessibility(toNode);
1912 void RenderViewImpl::didUpdateLayout() {
1913 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidUpdateLayout());
1915 // We don't always want to set up a timer, only if we've been put in that
1916 // mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
1917 // message.
1918 if (!send_preferred_size_changes_ || !webview())
1919 return;
1921 if (check_preferred_size_timer_.IsRunning())
1922 return;
1923 check_preferred_size_timer_.Start(FROM_HERE,
1924 TimeDelta::FromMilliseconds(0), this,
1925 &RenderViewImpl::CheckPreferredSize);
1928 void RenderViewImpl::navigateBackForwardSoon(int offset) {
1929 Send(new ViewHostMsg_GoToEntryAtOffset(routing_id_, offset));
1932 int RenderViewImpl::historyBackListCount() {
1933 return history_list_offset_ < 0 ? 0 : history_list_offset_;
1936 int RenderViewImpl::historyForwardListCount() {
1937 return history_list_length_ - historyBackListCount() - 1;
1940 // blink::WebWidgetClient ----------------------------------------------------
1942 void RenderViewImpl::didFocus() {
1943 // TODO(jcivelli): when https://bugs.webkit.org/show_bug.cgi?id=33389 is fixed
1944 // we won't have to test for user gesture anymore and we can
1945 // move that code back to render_widget.cc
1946 if (WebUserGestureIndicator::isProcessingUserGesture() &&
1947 !RenderThreadImpl::current()->layout_test_mode()) {
1948 Send(new ViewHostMsg_Focus(routing_id_));
1952 void RenderViewImpl::didBlur() {
1953 // TODO(jcivelli): see TODO above in didFocus().
1954 if (WebUserGestureIndicator::isProcessingUserGesture() &&
1955 !RenderThreadImpl::current()->layout_test_mode()) {
1956 Send(new ViewHostMsg_Blur(routing_id_));
1960 // We are supposed to get a single call to Show for a newly created RenderView
1961 // that was created via RenderViewImpl::CreateWebView. So, we wait until this
1962 // point to dispatch the ShowView message.
1964 // This method provides us with the information about how to display the newly
1965 // created RenderView (i.e., as a blocked popup or as a new tab).
1967 void RenderViewImpl::show(WebNavigationPolicy policy) {
1968 if (did_show_) {
1969 // When supports_multiple_windows is disabled, popups are reusing
1970 // the same view. In some scenarios, this makes WebKit to call show() twice.
1971 if (webkit_preferences_.supports_multiple_windows)
1972 NOTREACHED() << "received extraneous Show call";
1973 return;
1975 did_show_ = true;
1977 DCHECK(opener_id_ != MSG_ROUTING_NONE);
1979 // NOTE: initial_rect_ may still have its default values at this point, but
1980 // that's okay. It'll be ignored if disposition is not NEW_POPUP, or the
1981 // browser process will impose a default position otherwise.
1982 Send(new ViewHostMsg_ShowView(opener_id_, routing_id_,
1983 NavigationPolicyToDisposition(policy), initial_rect_,
1984 opened_by_user_gesture_));
1985 SetPendingWindowRect(initial_rect_);
1988 bool RenderViewImpl::requestPointerLock() {
1989 return mouse_lock_dispatcher_->LockMouse(webwidget_mouse_lock_target_.get());
1992 void RenderViewImpl::requestPointerUnlock() {
1993 mouse_lock_dispatcher_->UnlockMouse(webwidget_mouse_lock_target_.get());
1996 bool RenderViewImpl::isPointerLocked() {
1997 return mouse_lock_dispatcher_->IsMouseLockedTo(
1998 webwidget_mouse_lock_target_.get());
2001 void RenderViewImpl::didHandleGestureEvent(
2002 const WebGestureEvent& event,
2003 bool event_cancelled) {
2004 RenderWidget::didHandleGestureEvent(event, event_cancelled);
2006 if (!event_cancelled) {
2007 FOR_EACH_OBSERVER(
2008 RenderViewObserver, observers_, DidHandleGestureEvent(event));
2011 // TODO(ananta): Piggyback off existing IPCs to communicate this information,
2012 // crbug/420130.
2013 #if defined(OS_WIN)
2014 if (event.type != blink::WebGestureEvent::GestureTap)
2015 return;
2017 // TODO(estade): hit test the event against focused node to make sure
2018 // the tap actually hit the focused node.
2019 blink::WebTextInputType text_input_type =
2020 GetWebView()->textInputInfo().type;
2022 Send(new ViewHostMsg_FocusedNodeTouched(
2023 routing_id(), text_input_type != blink::WebTextInputTypeNone));
2024 #endif
2027 void RenderViewImpl::initializeLayerTreeView() {
2028 RenderWidget::initializeLayerTreeView();
2029 RenderWidgetCompositor* rwc = compositor();
2030 if (!rwc)
2031 return;
2032 // TODO(dgozman): do this not for main frame, but for local frame roots.
2033 if (blink::WebDevToolsAgent* devToolsAgent = GetWebDevToolsAgent(webview()))
2034 devToolsAgent->setLayerTreeId(rwc->GetLayerTreeId());
2036 bool use_threaded_event_handling = true;
2037 #if defined(OS_MACOSX) && !defined(OS_IOS)
2038 // Disable threaded event handling if content is not handling the elastic
2039 // overscroll effect. This includes the cases where the elastic overscroll
2040 // effect is being handled by Blink (because of command line flags) and older
2041 // operating system versions which do not have an elastic overscroll effect
2042 // (SnowLeopard, which has Aqua scrollbars which need synchronous updates).
2043 use_threaded_event_handling = compositor_deps_->IsElasticOverscrollEnabled();
2044 #endif
2045 if (use_threaded_event_handling) {
2046 RenderThreadImpl* render_thread = RenderThreadImpl::current();
2047 // render_thread may be NULL in tests.
2048 InputHandlerManager* input_handler_manager =
2049 render_thread ? render_thread->input_handler_manager() : NULL;
2050 if (input_handler_manager) {
2051 input_handler_manager->AddInputHandler(
2052 routing_id_, rwc->GetInputHandler(), AsWeakPtr());
2057 // blink::WebFrameClient -----------------------------------------------------
2059 void RenderViewImpl::Repaint(const gfx::Size& size) {
2060 OnRepaint(size);
2063 void RenderViewImpl::SetEditCommandForNextKeyEvent(const std::string& name,
2064 const std::string& value) {
2065 EditCommands edit_commands;
2066 edit_commands.push_back(EditCommand(name, value));
2067 OnSetEditCommandsForNextKeyEvent(edit_commands);
2070 void RenderViewImpl::ClearEditCommands() {
2071 edit_commands_.clear();
2074 SSLStatus RenderViewImpl::GetSSLStatusOfFrame(blink::WebFrame* frame) const {
2075 std::string security_info;
2076 if (frame && frame->dataSource())
2077 security_info = frame->dataSource()->response().securityInfo();
2079 SSLStatus ssl_status;
2080 DeserializeSecurityInfo(security_info,
2081 &ssl_status.cert_id,
2082 &ssl_status.cert_status,
2083 &ssl_status.security_bits,
2084 &ssl_status.connection_status,
2085 &ssl_status.signed_certificate_timestamp_ids);
2086 return ssl_status;
2089 const std::string& RenderViewImpl::GetAcceptLanguages() const {
2090 return renderer_preferences_.accept_languages;
2093 void RenderViewImpl::didChangeIcon(WebLocalFrame* frame,
2094 WebIconURL::Type icon_type) {
2095 if (frame->parent())
2096 return;
2098 WebVector<WebIconURL> icon_urls = frame->iconURLs(icon_type);
2099 std::vector<FaviconURL> urls;
2100 for (size_t i = 0; i < icon_urls.size(); i++) {
2101 std::vector<gfx::Size> sizes;
2102 ConvertToFaviconSizes(icon_urls[i].sizes(), &sizes);
2103 urls.push_back(FaviconURL(
2104 icon_urls[i].iconURL(), ToFaviconType(icon_urls[i].iconType()), sizes));
2106 SendUpdateFaviconURL(urls);
2109 void RenderViewImpl::didUpdateCurrentHistoryItem(WebLocalFrame* frame) {
2110 StartNavStateSyncTimerIfNecessary();
2113 void RenderViewImpl::CheckPreferredSize() {
2114 // We don't always want to send the change messages over IPC, only if we've
2115 // been put in that mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
2116 // message.
2117 if (!send_preferred_size_changes_ || !webview())
2118 return;
2120 gfx::Size size = webview()->contentsPreferredMinimumSize();
2121 if (size == preferred_size_)
2122 return;
2124 preferred_size_ = size;
2125 Send(new ViewHostMsg_DidContentsPreferredSizeChange(routing_id_,
2126 preferred_size_));
2129 void RenderViewImpl::didChangeScrollOffset(WebLocalFrame* frame) {
2130 StartNavStateSyncTimerIfNecessary();
2133 void RenderViewImpl::SendFindReply(int request_id,
2134 int match_count,
2135 int ordinal,
2136 const WebRect& selection_rect,
2137 bool final_status_update) {
2138 Send(new ViewHostMsg_Find_Reply(routing_id_,
2139 request_id,
2140 match_count,
2141 selection_rect,
2142 ordinal,
2143 final_status_update));
2146 blink::WebString RenderViewImpl::acceptLanguages() {
2147 return WebString::fromUTF8(renderer_preferences_.accept_languages);
2150 // blink::WebPageSerializerClient implementation ------------------------------
2152 void RenderViewImpl::didSerializeDataForFrame(
2153 const WebURL& frame_url,
2154 const WebCString& data,
2155 WebPageSerializerClient::PageSerializationStatus status) {
2156 Send(new ViewHostMsg_SendSerializedHtmlData(
2157 routing_id(),
2158 frame_url,
2159 data.data(),
2160 static_cast<int32>(status)));
2163 // RenderView implementation ---------------------------------------------------
2165 bool RenderViewImpl::Send(IPC::Message* message) {
2166 return RenderWidget::Send(message);
2169 RenderFrameImpl* RenderViewImpl::GetMainRenderFrame() {
2170 return main_render_frame_.get();
2173 int RenderViewImpl::GetRoutingID() const {
2174 return routing_id_;
2177 gfx::Size RenderViewImpl::GetSize() const {
2178 return size();
2181 WebPreferences& RenderViewImpl::GetWebkitPreferences() {
2182 return webkit_preferences_;
2185 void RenderViewImpl::SetWebkitPreferences(const WebPreferences& preferences) {
2186 OnUpdateWebPreferences(preferences);
2189 blink::WebView* RenderViewImpl::GetWebView() {
2190 return webview();
2193 bool RenderViewImpl::IsEditableNode(const WebNode& node) const {
2194 if (node.isNull())
2195 return false;
2197 if (node.isContentEditable())
2198 return true;
2200 if (node.isElementNode()) {
2201 const WebElement& element = node.toConst<WebElement>();
2202 if (element.isTextFormControlElement()) {
2203 if (!(element.hasAttribute("readonly") ||
2204 element.hasAttribute("disabled")))
2205 return true;
2208 // Also return true if it has an ARIA role of 'textbox'.
2209 for (unsigned i = 0; i < element.attributeCount(); ++i) {
2210 if (LowerCaseEqualsASCII(element.attributeLocalName(i), "role")) {
2211 if (LowerCaseEqualsASCII(element.attributeValue(i), "textbox"))
2212 return true;
2213 break;
2218 return false;
2221 bool RenderViewImpl::ShouldDisplayScrollbars(int width, int height) const {
2222 return (!send_preferred_size_changes_ ||
2223 (disable_scrollbars_size_limit_.width() <= width ||
2224 disable_scrollbars_size_limit_.height() <= height));
2227 int RenderViewImpl::GetEnabledBindings() const {
2228 return enabled_bindings_;
2231 bool RenderViewImpl::GetContentStateImmediately() const {
2232 return send_content_state_immediately_;
2235 blink::WebPageVisibilityState RenderViewImpl::GetVisibilityState() const {
2236 return visibilityState();
2239 void RenderViewImpl::DidStartLoading() {
2240 main_render_frame_->didStartLoading(true);
2243 void RenderViewImpl::DidStopLoading() {
2244 main_render_frame_->didStopLoading();
2247 void RenderViewImpl::SyncNavigationState() {
2248 if (!webview())
2249 return;
2250 SendUpdateState(history_controller_->GetCurrentEntry());
2253 blink::WebElement RenderViewImpl::GetFocusedElement() const {
2254 if (!webview())
2255 return WebElement();
2256 WebFrame* focused_frame = webview()->focusedFrame();
2257 if (focused_frame) {
2258 WebDocument doc = focused_frame->document();
2259 if (!doc.isNull())
2260 return doc.focusedElement();
2263 return WebElement();
2266 blink::WebPlugin* RenderViewImpl::GetWebPluginForFind() {
2267 if (!webview())
2268 return NULL;
2270 WebFrame* main_frame = webview()->mainFrame();
2271 if (main_frame->isWebLocalFrame() &&
2272 main_frame->document().isPluginDocument())
2273 return webview()->mainFrame()->document().to<WebPluginDocument>().plugin();
2275 #if defined(ENABLE_PLUGINS)
2276 if (plugin_find_handler_)
2277 return plugin_find_handler_->container()->plugin();
2278 #endif
2280 return NULL;
2283 void RenderViewImpl::OnFind(int request_id,
2284 const base::string16& search_text,
2285 const WebFindOptions& options) {
2286 WebFrame* main_frame = webview()->mainFrame();
2287 blink::WebPlugin* plugin = GetWebPluginForFind();
2288 // Check if the plugin still exists in the document.
2289 if (plugin) {
2290 if (options.findNext) {
2291 // Just navigate back/forward.
2292 plugin->selectFindResult(options.forward);
2293 } else {
2294 if (!plugin->startFind(
2295 search_text, options.matchCase, request_id)) {
2296 // Send "no results".
2297 SendFindReply(request_id, 0, 0, gfx::Rect(), true);
2300 return;
2303 WebFrame* frame_after_main = main_frame->traverseNext(true);
2304 WebFrame* focused_frame = webview()->focusedFrame();
2305 WebFrame* search_frame = focused_frame; // start searching focused frame.
2307 bool multi_frame = (frame_after_main != main_frame);
2309 // If we have multiple frames, we don't want to wrap the search within the
2310 // frame, so we check here if we only have main_frame in the chain.
2311 bool wrap_within_frame = !multi_frame;
2313 WebRect selection_rect;
2314 bool result = false;
2316 // If something is selected when we start searching it means we cannot just
2317 // increment the current match ordinal; we need to re-generate it.
2318 WebRange current_selection = focused_frame->selectionRange();
2320 do {
2321 result = search_frame->find(
2322 request_id, search_text, options, wrap_within_frame, &selection_rect);
2324 if (!result) {
2325 // don't leave text selected as you move to the next frame.
2326 search_frame->executeCommand(WebString::fromUTF8("Unselect"),
2327 GetFocusedElement());
2329 // Find the next frame, but skip the invisible ones.
2330 do {
2331 // What is the next frame to search? (we might be going backwards). Note
2332 // that we specify wrap=true so that search_frame never becomes NULL.
2333 search_frame = options.forward ?
2334 search_frame->traverseNext(true) :
2335 search_frame->traversePrevious(true);
2336 } while (!search_frame->hasVisibleContent() &&
2337 search_frame != focused_frame);
2339 // Make sure selection doesn't affect the search operation in new frame.
2340 search_frame->executeCommand(WebString::fromUTF8("Unselect"),
2341 GetFocusedElement());
2343 // If we have multiple frames and we have wrapped back around to the
2344 // focused frame, we need to search it once more allowing wrap within
2345 // the frame, otherwise it will report 'no match' if the focused frame has
2346 // reported matches, but no frames after the focused_frame contain a
2347 // match for the search word(s).
2348 if (multi_frame && search_frame == focused_frame) {
2349 result = search_frame->find(
2350 request_id, search_text, options, true, // Force wrapping.
2351 &selection_rect);
2355 webview()->setFocusedFrame(search_frame);
2356 } while (!result && search_frame != focused_frame);
2358 if (options.findNext && current_selection.isNull()) {
2359 // Force the main_frame to report the actual count.
2360 main_frame->increaseMatchCount(0, request_id);
2361 } else {
2362 // If nothing is found, set result to "0 of 0", otherwise, set it to
2363 // "-1 of 1" to indicate that we found at least one item, but we don't know
2364 // yet what is active.
2365 int ordinal = result ? -1 : 0; // -1 here means, we might know more later.
2366 int match_count = result ? 1 : 0; // 1 here means possibly more coming.
2368 // If we find no matches then this will be our last status update.
2369 // Otherwise the scoping effort will send more results.
2370 bool final_status_update = !result;
2372 SendFindReply(request_id, match_count, ordinal, selection_rect,
2373 final_status_update);
2375 // Scoping effort begins, starting with the mainframe.
2376 search_frame = main_frame;
2378 main_frame->resetMatchCount();
2380 do {
2381 // Cancel all old scoping requests before starting a new one.
2382 search_frame->cancelPendingScopingEffort();
2384 // We don't start another scoping effort unless at least one match has
2385 // been found.
2386 if (result) {
2387 // Start new scoping request. If the scoping function determines that it
2388 // needs to scope, it will defer until later.
2389 search_frame->scopeStringMatches(request_id,
2390 search_text,
2391 options,
2392 true); // reset the tickmarks
2395 // Iterate to the next frame. The frame will not necessarily scope, for
2396 // example if it is not visible.
2397 search_frame = search_frame->traverseNext(true);
2398 } while (search_frame != main_frame);
2402 void RenderViewImpl::OnStopFinding(StopFindAction action) {
2403 WebView* view = webview();
2404 if (!view)
2405 return;
2407 blink::WebPlugin* plugin = GetWebPluginForFind();
2408 if (plugin) {
2409 plugin->stopFind();
2410 return;
2413 bool clear_selection = action == STOP_FIND_ACTION_CLEAR_SELECTION;
2414 if (clear_selection) {
2415 view->focusedFrame()->executeCommand(WebString::fromUTF8("Unselect"),
2416 GetFocusedElement());
2419 WebFrame* frame = view->mainFrame();
2420 while (frame) {
2421 frame->stopFinding(clear_selection);
2422 frame = frame->traverseNext(false);
2425 if (action == STOP_FIND_ACTION_ACTIVATE_SELECTION) {
2426 WebFrame* focused_frame = view->focusedFrame();
2427 if (focused_frame) {
2428 WebDocument doc = focused_frame->document();
2429 if (!doc.isNull()) {
2430 WebElement element = doc.focusedElement();
2431 if (!element.isNull())
2432 element.simulateClick();
2438 #if defined(OS_ANDROID)
2439 void RenderViewImpl::OnActivateNearestFindResult(int request_id,
2440 float x, float y) {
2441 if (!webview())
2442 return;
2444 WebFrame* main_frame = webview()->mainFrame();
2445 WebRect selection_rect;
2446 int ordinal = main_frame->selectNearestFindMatch(WebFloatPoint(x, y),
2447 &selection_rect);
2448 if (ordinal == -1) {
2449 // Something went wrong, so send a no-op reply (force the main_frame to
2450 // report the current match count) in case the host is waiting for a
2451 // response due to rate-limiting).
2452 main_frame->increaseMatchCount(0, request_id);
2453 return;
2456 SendFindReply(request_id,
2457 -1 /* number_of_matches */,
2458 ordinal,
2459 selection_rect,
2460 true /* final_update */);
2463 void RenderViewImpl::OnFindMatchRects(int current_version) {
2464 if (!webview())
2465 return;
2467 WebFrame* main_frame = webview()->mainFrame();
2468 std::vector<gfx::RectF> match_rects;
2470 int rects_version = main_frame->findMatchMarkersVersion();
2471 if (current_version != rects_version) {
2472 WebVector<WebFloatRect> web_match_rects;
2473 main_frame->findMatchRects(web_match_rects);
2474 match_rects.reserve(web_match_rects.size());
2475 for (size_t i = 0; i < web_match_rects.size(); ++i)
2476 match_rects.push_back(gfx::RectF(web_match_rects[i]));
2479 gfx::RectF active_rect = main_frame->activeFindMatchRect();
2480 Send(new ViewHostMsg_FindMatchRects_Reply(routing_id_,
2481 rects_version,
2482 match_rects,
2483 active_rect));
2485 #endif
2487 void RenderViewImpl::OnResetPageScale() {
2488 if (!webview())
2489 return;
2490 webview()->setPageScaleFactor(1);
2493 void RenderViewImpl::OnZoom(PageZoom zoom) {
2494 if (!webview()) // Not sure if this can happen, but no harm in being safe.
2495 return;
2497 webview()->hidePopups();
2499 double old_zoom_level = webview()->zoomLevel();
2500 double zoom_level;
2501 if (zoom == PAGE_ZOOM_RESET) {
2502 zoom_level = 0;
2503 } else if (static_cast<int>(old_zoom_level) == old_zoom_level) {
2504 // Previous zoom level is a whole number, so just increment/decrement.
2505 zoom_level = old_zoom_level + zoom;
2506 } else {
2507 // Either the user hit the zoom factor limit and thus the zoom level is now
2508 // not a whole number, or a plugin changed it to a custom value. We want
2509 // to go to the next whole number so that the user can always get back to
2510 // 100% with the keyboard/menu.
2511 if ((old_zoom_level > 1 && zoom > 0) ||
2512 (old_zoom_level < 1 && zoom < 0)) {
2513 zoom_level = static_cast<int>(old_zoom_level + zoom);
2514 } else {
2515 // We're going towards 100%, so first go to the next whole number.
2516 zoom_level = static_cast<int>(old_zoom_level);
2519 webview()->setZoomLevel(zoom_level);
2520 zoomLevelChanged();
2523 void RenderViewImpl::OnSetZoomLevelForLoadingURL(const GURL& url,
2524 double zoom_level) {
2525 #if !defined(OS_ANDROID)
2526 // On Android, page zoom isn't used, and in case of WebView, text zoom is used
2527 // for legacy WebView text scaling emulation. Thus, the code that resets
2528 // the zoom level from this map will be effectively resetting text zoom level.
2529 host_zoom_levels_[url] = zoom_level;
2530 #endif
2533 void RenderViewImpl::OnSetZoomLevelForView(bool uses_temporary_zoom_level,
2534 double level) {
2535 uses_temporary_zoom_level_ = uses_temporary_zoom_level;
2537 webview()->hidePopups();
2538 webview()->setZoomLevel(level);
2541 void RenderViewImpl::OnSetPageEncoding(const std::string& encoding_name) {
2542 webview()->setPageEncoding(WebString::fromUTF8(encoding_name));
2545 void RenderViewImpl::OnResetPageEncodingToDefault() {
2546 WebString no_encoding;
2547 webview()->setPageEncoding(no_encoding);
2550 void RenderViewImpl::OnAllowBindings(int enabled_bindings_flags) {
2551 if ((enabled_bindings_flags & BINDINGS_POLICY_WEB_UI) &&
2552 !(enabled_bindings_ & BINDINGS_POLICY_WEB_UI)) {
2553 // WebUIExtensionData deletes itself when we're destroyed.
2554 new WebUIExtensionData(this);
2555 // WebUIMojo deletes itself when we're destroyed.
2556 new WebUIMojo(this);
2559 enabled_bindings_ |= enabled_bindings_flags;
2561 // Keep track of the total bindings accumulated in this process.
2562 RenderProcess::current()->AddBindings(enabled_bindings_flags);
2565 void RenderViewImpl::OnDragTargetDragEnter(const DropData& drop_data,
2566 const gfx::Point& client_point,
2567 const gfx::Point& screen_point,
2568 WebDragOperationsMask ops,
2569 int key_modifiers) {
2570 WebDragOperation operation = webview()->dragTargetDragEnter(
2571 DropDataToWebDragData(drop_data),
2572 client_point,
2573 screen_point,
2574 ops,
2575 key_modifiers);
2577 Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
2580 void RenderViewImpl::OnDragTargetDragOver(const gfx::Point& client_point,
2581 const gfx::Point& screen_point,
2582 WebDragOperationsMask ops,
2583 int key_modifiers) {
2584 WebDragOperation operation = webview()->dragTargetDragOver(
2585 client_point,
2586 screen_point,
2587 ops,
2588 key_modifiers);
2590 Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
2593 void RenderViewImpl::OnDragTargetDragLeave() {
2594 webview()->dragTargetDragLeave();
2597 void RenderViewImpl::OnDragTargetDrop(const gfx::Point& client_point,
2598 const gfx::Point& screen_point,
2599 int key_modifiers) {
2600 webview()->dragTargetDrop(client_point, screen_point, key_modifiers);
2602 Send(new DragHostMsg_TargetDrop_ACK(routing_id_));
2605 void RenderViewImpl::OnDragSourceEnded(const gfx::Point& client_point,
2606 const gfx::Point& screen_point,
2607 WebDragOperation op) {
2608 webview()->dragSourceEndedAt(client_point, screen_point, op);
2611 void RenderViewImpl::OnDragSourceSystemDragEnded() {
2612 webview()->dragSourceSystemDragEnded();
2615 void RenderViewImpl::OnUpdateWebPreferences(const WebPreferences& prefs) {
2616 webkit_preferences_ = prefs;
2617 ApplyWebPreferences(webkit_preferences_, webview());
2620 void RenderViewImpl::OnEnumerateDirectoryResponse(
2621 int id,
2622 const std::vector<base::FilePath>& paths) {
2623 if (!enumeration_completions_[id])
2624 return;
2626 WebVector<WebString> ws_file_names(paths.size());
2627 for (size_t i = 0; i < paths.size(); ++i)
2628 ws_file_names[i] = paths[i].AsUTF16Unsafe();
2630 enumeration_completions_[id]->didChooseFile(ws_file_names);
2631 enumeration_completions_.erase(id);
2634 void RenderViewImpl::OnFileChooserResponse(
2635 const std::vector<content::FileChooserFileInfo>& files) {
2636 // This could happen if we navigated to a different page before the user
2637 // closed the chooser.
2638 if (file_chooser_completions_.empty())
2639 return;
2641 // Convert Chrome's SelectedFileInfo list to WebKit's.
2642 WebVector<WebFileChooserCompletion::SelectedFileInfo> selected_files(
2643 files.size());
2644 for (size_t i = 0; i < files.size(); ++i) {
2645 WebFileChooserCompletion::SelectedFileInfo selected_file;
2646 selected_file.path = files[i].file_path.AsUTF16Unsafe();
2647 selected_file.displayName =
2648 base::FilePath(files[i].display_name).AsUTF16Unsafe();
2649 if (files[i].file_system_url.is_valid()) {
2650 selected_file.fileSystemURL = files[i].file_system_url;
2651 selected_file.length = files[i].length;
2652 selected_file.modificationTime = files[i].modification_time.ToDoubleT();
2653 selected_file.isDirectory = files[i].is_directory;
2655 selected_files[i] = selected_file;
2658 if (file_chooser_completions_.front()->completion)
2659 file_chooser_completions_.front()->completion->didChooseFile(
2660 selected_files);
2661 file_chooser_completions_.pop_front();
2663 // If there are more pending file chooser requests, schedule one now.
2664 if (!file_chooser_completions_.empty()) {
2665 Send(new ViewHostMsg_RunFileChooser(routing_id_,
2666 file_chooser_completions_.front()->params));
2670 void RenderViewImpl::OnEnableAutoResize(const gfx::Size& min_size,
2671 const gfx::Size& max_size) {
2672 DCHECK(disable_scrollbars_size_limit_.IsEmpty());
2673 if (!webview())
2674 return;
2675 auto_resize_mode_ = true;
2676 webview()->enableAutoResizeMode(min_size, max_size);
2679 void RenderViewImpl::OnDisableAutoResize(const gfx::Size& new_size) {
2680 DCHECK(disable_scrollbars_size_limit_.IsEmpty());
2681 if (!webview())
2682 return;
2683 auto_resize_mode_ = false;
2684 webview()->disableAutoResizeMode();
2686 if (!new_size.IsEmpty()) {
2687 Resize(new_size,
2688 physical_backing_size_,
2689 top_controls_shrink_blink_size_,
2690 top_controls_height_,
2691 visible_viewport_size_,
2692 resizer_rect_,
2693 is_fullscreen_granted_,
2694 display_mode_,
2695 NO_RESIZE_ACK);
2699 void RenderViewImpl::OnEnablePreferredSizeChangedMode() {
2700 if (send_preferred_size_changes_)
2701 return;
2702 send_preferred_size_changes_ = true;
2704 // Start off with an initial preferred size notification (in case
2705 // |didUpdateLayout| was already called).
2706 didUpdateLayout();
2709 void RenderViewImpl::OnDisableScrollbarsForSmallWindows(
2710 const gfx::Size& disable_scrollbar_size_limit) {
2711 disable_scrollbars_size_limit_ = disable_scrollbar_size_limit;
2714 void RenderViewImpl::OnSetRendererPrefs(
2715 const RendererPreferences& renderer_prefs) {
2716 double old_zoom_level = renderer_preferences_.default_zoom_level;
2717 std::string old_accept_languages = renderer_preferences_.accept_languages;
2719 renderer_preferences_ = renderer_prefs;
2721 UpdateFontRenderingFromRendererPrefs();
2722 UpdateThemePrefs();
2724 #if defined(USE_DEFAULT_RENDER_THEME)
2725 if (renderer_prefs.use_custom_colors) {
2726 WebColorName name = blink::WebColorWebkitFocusRingColor;
2727 blink::setNamedColors(&name, &renderer_prefs.focus_ring_color, 1);
2728 blink::setCaretBlinkInterval(renderer_prefs.caret_blink_interval);
2730 if (webview()) {
2731 webview()->setSelectionColors(
2732 renderer_prefs.active_selection_bg_color,
2733 renderer_prefs.active_selection_fg_color,
2734 renderer_prefs.inactive_selection_bg_color,
2735 renderer_prefs.inactive_selection_fg_color);
2736 webview()->themeChanged();
2739 #endif // defined(USE_DEFAULT_RENDER_THEME)
2741 // If the zoom level for this page matches the old zoom default, and this
2742 // is not a plugin, update the zoom level to match the new default.
2743 if (webview() && webview()->mainFrame()->isWebLocalFrame() &&
2744 !webview()->mainFrame()->document().isPluginDocument() &&
2745 !ZoomValuesEqual(old_zoom_level,
2746 renderer_preferences_.default_zoom_level) &&
2747 ZoomValuesEqual(webview()->zoomLevel(), old_zoom_level)) {
2748 webview()->setZoomLevel(renderer_preferences_.default_zoom_level);
2749 zoomLevelChanged();
2752 if (webview() &&
2753 old_accept_languages != renderer_preferences_.accept_languages) {
2754 webview()->acceptLanguagesChanged();
2758 void RenderViewImpl::OnMediaPlayerActionAt(const gfx::Point& location,
2759 const WebMediaPlayerAction& action) {
2760 if (webview())
2761 webview()->performMediaPlayerAction(action, location);
2764 void RenderViewImpl::OnOrientationChange() {
2765 if (webview() && webview()->mainFrame()->isWebLocalFrame())
2766 webview()->mainFrame()->toWebLocalFrame()->sendOrientationChangeEvent();
2769 void RenderViewImpl::OnPluginActionAt(const gfx::Point& location,
2770 const WebPluginAction& action) {
2771 if (webview())
2772 webview()->performPluginAction(action, location);
2775 void RenderViewImpl::OnGetAllSavableResourceLinksForCurrentPage(
2776 const GURL& page_url) {
2777 // Prepare list to storage all savable resource links.
2778 std::vector<GURL> resources_list;
2779 std::vector<GURL> referrer_urls_list;
2780 std::vector<blink::WebReferrerPolicy> referrer_policies_list;
2781 std::vector<GURL> frames_list;
2782 SavableResourcesResult result(&resources_list,
2783 &referrer_urls_list,
2784 &referrer_policies_list,
2785 &frames_list);
2787 // webkit/ doesn't know about Referrer.
2788 if (!GetAllSavableResourceLinksForCurrentPage(
2789 webview(),
2790 page_url,
2791 &result,
2792 const_cast<const char**>(GetSavableSchemes()))) {
2793 // If something is wrong when collecting all savable resource links,
2794 // send empty list to embedder(browser) to tell it failed.
2795 referrer_urls_list.clear();
2796 referrer_policies_list.clear();
2797 resources_list.clear();
2798 frames_list.clear();
2801 std::vector<Referrer> referrers_list;
2802 CHECK_EQ(referrer_urls_list.size(), referrer_policies_list.size());
2803 for (unsigned i = 0; i < referrer_urls_list.size(); ++i) {
2804 referrers_list.push_back(
2805 Referrer(referrer_urls_list[i], referrer_policies_list[i]));
2808 // Send result of all savable resource links to embedder.
2809 Send(new ViewHostMsg_SendCurrentPageAllSavableResourceLinks(routing_id(),
2810 resources_list,
2811 referrers_list,
2812 frames_list));
2815 void RenderViewImpl::OnGetSerializedHtmlDataForCurrentPageWithLocalLinks(
2816 const std::vector<GURL>& links,
2817 const std::vector<base::FilePath>& local_paths,
2818 const base::FilePath& local_directory_name) {
2820 // Convert std::vector of GURLs to WebVector<WebURL>
2821 WebVector<WebURL> weburl_links(links);
2823 // Convert std::vector of base::FilePath to WebVector<WebString>
2824 WebVector<WebString> webstring_paths(local_paths.size());
2825 for (size_t i = 0; i < local_paths.size(); i++)
2826 webstring_paths[i] = local_paths[i].AsUTF16Unsafe();
2828 WebPageSerializer::serialize(webview()->mainFrame()->toWebLocalFrame(),
2829 true,
2830 this,
2831 weburl_links,
2832 webstring_paths,
2833 local_directory_name.AsUTF16Unsafe());
2836 void RenderViewImpl::OnSuppressDialogsUntilSwapOut() {
2837 // Don't show any more dialogs until we finish OnSwapOut.
2838 suppress_dialogs_until_swap_out_ = true;
2841 void RenderViewImpl::OnClosePage() {
2842 FOR_EACH_OBSERVER(RenderViewObserver, observers_, ClosePage());
2843 // TODO(creis): We'd rather use webview()->Close() here, but that currently
2844 // sets the WebView's delegate_ to NULL, preventing any JavaScript dialogs
2845 // in the onunload handler from appearing. For now, we're bypassing that and
2846 // calling the FrameLoader's CloseURL method directly. This should be
2847 // revisited to avoid having two ways to close a page. Having a single way
2848 // to close that can run onunload is also useful for fixing
2849 // http://b/issue?id=753080.
2850 webview()->mainFrame()->dispatchUnloadEvent();
2852 Send(new ViewHostMsg_ClosePage_ACK(routing_id_));
2855 void RenderViewImpl::OnThemeChanged() {
2856 #if defined(USE_AURA)
2857 // Aura doesn't care if we switch themes.
2858 #elif defined(OS_WIN)
2859 ui::NativeThemeWin::instance()->CloseHandles();
2860 if (webview())
2861 webview()->themeChanged();
2862 #else // defined(OS_WIN)
2863 // TODO(port): we don't support theming on non-Windows platforms yet
2864 NOTIMPLEMENTED();
2865 #endif
2868 void RenderViewImpl::OnMoveOrResizeStarted() {
2869 if (webview())
2870 webview()->hidePopups();
2873 void RenderViewImpl::OnResize(const ViewMsg_Resize_Params& params) {
2874 TRACE_EVENT0("renderer", "RenderViewImpl::OnResize");
2875 if (webview()) {
2876 webview()->hidePopups();
2877 if (send_preferred_size_changes_) {
2878 webview()->mainFrame()->setCanHaveScrollbars(
2879 ShouldDisplayScrollbars(params.new_size.width(),
2880 params.new_size.height()));
2882 if (display_mode_ != params.display_mode) {
2883 display_mode_ = params.display_mode;
2884 webview()->setDisplayMode(display_mode_);
2888 gfx::Size old_visible_viewport_size = visible_viewport_size_;
2890 RenderWidget::OnResize(params);
2892 if (old_visible_viewport_size != visible_viewport_size_)
2893 has_scrolled_focused_editable_node_into_rect_ = false;
2896 void RenderViewImpl::DidInitiatePaint() {
2897 #if defined(ENABLE_PLUGINS)
2898 // Notify all instances that we painted. The same caveats apply as for
2899 // ViewFlushedPaint regarding instances closing themselves, so we take
2900 // similar precautions.
2901 PepperPluginSet plugins = active_pepper_instances_;
2902 for (PepperPluginSet::iterator i = plugins.begin(); i != plugins.end(); ++i) {
2903 if (active_pepper_instances_.find(*i) != active_pepper_instances_.end())
2904 (*i)->ViewInitiatedPaint();
2906 #endif
2909 void RenderViewImpl::DidFlushPaint() {
2910 // If the RenderWidget is closing down then early-exit, otherwise we'll crash.
2911 // See crbug.com/112921.
2912 if (!webview())
2913 return;
2915 WebFrame* main_frame = webview()->mainFrame();
2916 for (WebFrame* frame = main_frame; frame;
2917 frame = frame->traverseNext(false)) {
2918 // TODO(nasko): This is a hack for the case in which the top-level
2919 // frame is being rendered in another process. It will not
2920 // behave correctly for out of process iframes.
2921 if (frame->isWebLocalFrame()) {
2922 main_frame = frame;
2923 break;
2927 // If we have a provisional frame we are between the start and commit stages
2928 // of loading and we don't want to save stats.
2929 if (!main_frame->provisionalDataSource()) {
2930 WebDataSource* ds = main_frame->dataSource();
2931 DocumentState* document_state = DocumentState::FromDataSource(ds);
2933 // TODO(jar): The following code should all be inside a method, probably in
2934 // NavigatorState.
2935 Time now = Time::Now();
2936 if (document_state->first_paint_time().is_null()) {
2937 document_state->set_first_paint_time(now);
2939 if (document_state->first_paint_after_load_time().is_null() &&
2940 !document_state->finish_load_time().is_null()) {
2941 document_state->set_first_paint_after_load_time(now);
2946 gfx::Vector2d RenderViewImpl::GetScrollOffset() {
2947 WebFrame* main_frame = webview()->mainFrame();
2948 for (WebFrame* frame = main_frame; frame;
2949 frame = frame->traverseNext(false)) {
2950 // TODO(nasko): This is a hack for the case in which the top-level
2951 // frame is being rendered in another process. It will not
2952 // behave correctly for out of process iframes.
2953 if (frame->isWebLocalFrame()) {
2954 main_frame = frame;
2955 break;
2959 WebSize scroll_offset = main_frame->scrollOffset();
2960 return gfx::Vector2d(scroll_offset.width, scroll_offset.height);
2963 void RenderViewImpl::OnClearFocusedElement() {
2964 if (webview())
2965 webview()->clearFocusedElement();
2968 void RenderViewImpl::OnSetBackgroundOpaque(bool opaque) {
2969 if (webview())
2970 webview()->setIsTransparent(!opaque);
2971 if (compositor_)
2972 compositor_->setHasTransparentBackground(!opaque);
2975 void RenderViewImpl::OnSetActive(bool active) {
2976 if (webview())
2977 webview()->setIsActive(active);
2979 #if defined(ENABLE_PLUGINS) && defined(OS_MACOSX)
2980 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
2981 for (plugin_it = plugin_delegates_.begin();
2982 plugin_it != plugin_delegates_.end(); ++plugin_it) {
2983 (*plugin_it)->SetWindowFocus(active);
2985 #endif
2988 #if defined(OS_MACOSX)
2989 void RenderViewImpl::OnSetWindowVisibility(bool visible) {
2990 #if defined(ENABLE_PLUGINS)
2991 // Inform plugins that their container has changed visibility.
2992 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
2993 for (plugin_it = plugin_delegates_.begin();
2994 plugin_it != plugin_delegates_.end(); ++plugin_it) {
2995 (*plugin_it)->SetContainerVisibility(visible);
2997 #endif
3000 void RenderViewImpl::OnWindowFrameChanged(const gfx::Rect& window_frame,
3001 const gfx::Rect& view_frame) {
3002 #if defined(ENABLE_PLUGINS)
3003 // Inform plugins that their window's frame has changed.
3004 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3005 for (plugin_it = plugin_delegates_.begin();
3006 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3007 (*plugin_it)->WindowFrameChanged(window_frame, view_frame);
3009 #endif
3012 void RenderViewImpl::OnPluginImeCompositionCompleted(const base::string16& text,
3013 int plugin_id) {
3014 // WebPluginDelegateProxy is responsible for figuring out if this event
3015 // applies to it or not, so inform all the delegates.
3016 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3017 for (plugin_it = plugin_delegates_.begin();
3018 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3019 (*plugin_it)->ImeCompositionCompleted(text, plugin_id);
3022 #endif // OS_MACOSX
3024 void RenderViewImpl::OnClose() {
3025 if (closing_)
3026 RenderThread::Get()->Send(new ViewHostMsg_Close_ACK(routing_id_));
3027 RenderWidget::OnClose();
3030 void RenderViewImpl::Close() {
3031 // We need to grab a pointer to the doomed WebView before we destroy it.
3032 WebView* doomed = webview();
3033 RenderWidget::Close();
3034 g_view_map.Get().erase(doomed);
3035 g_routing_id_view_map.Get().erase(routing_id_);
3036 RenderThread::Get()->Send(new ViewHostMsg_Close_ACK(routing_id_));
3039 void RenderViewImpl::DidHandleKeyEvent() {
3040 ClearEditCommands();
3043 bool RenderViewImpl::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
3044 possible_drag_event_info_.event_source =
3045 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE;
3046 possible_drag_event_info_.event_location =
3047 gfx::Point(event.globalX, event.globalY);
3049 #if defined(ENABLE_PLUGINS)
3050 // This method is called for every mouse event that the render view receives.
3051 // And then the mouse event is forwarded to WebKit, which dispatches it to the
3052 // event target. Potentially a Pepper plugin will receive the event.
3053 // In order to tell whether a plugin gets the last mouse event and which it
3054 // is, we set |pepper_last_mouse_event_target_| to NULL here. If a plugin gets
3055 // the event, it will notify us via DidReceiveMouseEvent() and set itself as
3056 // |pepper_last_mouse_event_target_|.
3057 pepper_last_mouse_event_target_ = NULL;
3058 #endif
3060 // If the mouse is locked, only the current owner of the mouse lock can
3061 // process mouse events.
3062 return mouse_lock_dispatcher_->WillHandleMouseEvent(event);
3065 bool RenderViewImpl::WillHandleGestureEvent(
3066 const blink::WebGestureEvent& event) {
3067 possible_drag_event_info_.event_source =
3068 ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH;
3069 possible_drag_event_info_.event_location =
3070 gfx::Point(event.globalX, event.globalY);
3071 return false;
3074 void RenderViewImpl::DidHandleMouseEvent(const WebMouseEvent& event) {
3075 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidHandleMouseEvent(event));
3078 void RenderViewImpl::DidHandleTouchEvent(const WebTouchEvent& event) {
3079 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidHandleTouchEvent(event));
3082 bool RenderViewImpl::HasTouchEventHandlersAt(const gfx::Point& point) const {
3083 if (!webview())
3084 return false;
3085 return webview()->hasTouchEventHandlersAt(point);
3088 void RenderViewImpl::OnWasHidden() {
3089 RenderWidget::OnWasHidden();
3091 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3092 RenderThreadImpl::current()->video_capture_impl_manager()->
3093 SuspendDevices(true);
3094 if (speech_recognition_dispatcher_)
3095 speech_recognition_dispatcher_->AbortAllRecognitions();
3096 #endif
3098 if (webview())
3099 webview()->setVisibilityState(visibilityState(), false);
3101 #if defined(ENABLE_PLUGINS)
3102 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3103 i != active_pepper_instances_.end(); ++i)
3104 (*i)->PageVisibilityChanged(false);
3106 #if defined(OS_MACOSX)
3107 // Inform NPAPI plugins that their container is no longer visible.
3108 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3109 for (plugin_it = plugin_delegates_.begin();
3110 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3111 (*plugin_it)->SetContainerVisibility(false);
3113 #endif // OS_MACOSX
3114 #endif // ENABLE_PLUGINS
3117 void RenderViewImpl::OnWasShown(bool needs_repainting,
3118 const ui::LatencyInfo& latency_info) {
3119 RenderWidget::OnWasShown(needs_repainting, latency_info);
3121 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3122 RenderThreadImpl::current()->video_capture_impl_manager()->
3123 SuspendDevices(false);
3124 #endif
3126 if (webview())
3127 webview()->setVisibilityState(visibilityState(), false);
3129 #if defined(ENABLE_PLUGINS)
3130 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3131 i != active_pepper_instances_.end(); ++i)
3132 (*i)->PageVisibilityChanged(true);
3134 #if defined(OS_MACOSX)
3135 // Inform NPAPI plugins that their container is now visible.
3136 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3137 for (plugin_it = plugin_delegates_.begin();
3138 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3139 (*plugin_it)->SetContainerVisibility(true);
3141 #endif // OS_MACOSX
3142 #endif // ENABLE_PLUGINS
3145 GURL RenderViewImpl::GetURLForGraphicsContext3D() {
3146 DCHECK(webview());
3147 if (webview()->mainFrame()->isWebLocalFrame())
3148 return GURL(webview()->mainFrame()->document().url());
3149 else
3150 return GURL("chrome://gpu/RenderViewImpl::CreateGraphicsContext3D");
3153 void RenderViewImpl::OnSetFocus(bool enable) {
3154 RenderWidget::OnSetFocus(enable);
3156 #if defined(ENABLE_PLUGINS)
3157 if (webview() && webview()->isActive()) {
3158 // Notify all NPAPI plugins.
3159 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3160 for (plugin_it = plugin_delegates_.begin();
3161 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3162 #if defined(OS_MACOSX)
3163 // RenderWidget's call to setFocus can cause the underlying webview's
3164 // activation state to change just like a call to setIsActive.
3165 if (enable)
3166 (*plugin_it)->SetWindowFocus(true);
3167 #endif
3168 (*plugin_it)->SetContentAreaFocus(enable);
3171 // Notify all Pepper plugins.
3172 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3173 i != active_pepper_instances_.end(); ++i)
3174 (*i)->SetContentAreaFocus(enable);
3175 #endif
3176 // Notify all BrowserPlugins of the RenderView's focus state.
3177 if (BrowserPluginManager::Get())
3178 BrowserPluginManager::Get()->UpdateFocusState();
3181 void RenderViewImpl::OnImeSetComposition(
3182 const base::string16& text,
3183 const std::vector<blink::WebCompositionUnderline>& underlines,
3184 int selection_start,
3185 int selection_end) {
3186 #if defined(ENABLE_PLUGINS)
3187 if (focused_pepper_plugin_) {
3188 focused_pepper_plugin_->render_frame()->OnImeSetComposition(
3189 text, underlines, selection_start, selection_end);
3190 return;
3193 #if defined(OS_WIN)
3194 // When a plugin has focus, we create platform-specific IME data used by
3195 // our IME emulator and send it directly to the focused plugin, i.e. we
3196 // bypass WebKit. (WebPluginDelegate dispatches this IME data only when its
3197 // instance ID is the same one as the specified ID.)
3198 if (focused_plugin_id_ >= 0) {
3199 std::vector<int> clauses;
3200 std::vector<int> target;
3201 for (size_t i = 0; i < underlines.size(); ++i) {
3202 clauses.push_back(underlines[i].startOffset);
3203 clauses.push_back(underlines[i].endOffset);
3204 if (underlines[i].thick) {
3205 target.clear();
3206 target.push_back(underlines[i].startOffset);
3207 target.push_back(underlines[i].endOffset);
3210 std::set<WebPluginDelegateProxy*>::iterator it;
3211 for (it = plugin_delegates_.begin(); it != plugin_delegates_.end(); ++it) {
3212 (*it)->ImeCompositionUpdated(text, clauses, target, selection_end,
3213 focused_plugin_id_);
3215 return;
3217 #endif // OS_WIN
3218 #endif // ENABLE_PLUGINS
3219 RenderWidget::OnImeSetComposition(text,
3220 underlines,
3221 selection_start,
3222 selection_end);
3225 void RenderViewImpl::OnImeConfirmComposition(
3226 const base::string16& text,
3227 const gfx::Range& replacement_range,
3228 bool keep_selection) {
3229 #if defined(ENABLE_PLUGINS)
3230 if (focused_pepper_plugin_) {
3231 focused_pepper_plugin_->render_frame()->OnImeConfirmComposition(
3232 text, replacement_range, keep_selection);
3233 return;
3235 #if defined(OS_WIN)
3236 // Same as OnImeSetComposition(), we send the text from IMEs directly to
3237 // plugins. When we send IME text directly to plugins, we should not send
3238 // it to WebKit to prevent WebKit from controlling IMEs.
3239 // TODO(thakis): Honor |replacement_range| for plugins?
3240 if (focused_plugin_id_ >= 0) {
3241 std::set<WebPluginDelegateProxy*>::iterator it;
3242 for (it = plugin_delegates_.begin();
3243 it != plugin_delegates_.end(); ++it) {
3244 (*it)->ImeCompositionCompleted(text, focused_plugin_id_);
3246 return;
3248 #endif // OS_WIN
3249 #endif // ENABLE_PLUGINS
3250 if (replacement_range.IsValid() && webview()) {
3251 // Select the text in |replacement_range|, it will then be replaced by
3252 // text added by the call to RenderWidget::OnImeConfirmComposition().
3253 if (WebLocalFrame* frame = webview()->focusedFrame()->toWebLocalFrame()) {
3254 WebRange webrange = WebRange::fromDocumentRange(
3255 frame, replacement_range.start(), replacement_range.length());
3256 if (!webrange.isNull())
3257 frame->selectRange(webrange);
3260 RenderWidget::OnImeConfirmComposition(text,
3261 replacement_range,
3262 keep_selection);
3265 void RenderViewImpl::SetDeviceScaleFactor(float device_scale_factor) {
3266 RenderWidget::SetDeviceScaleFactor(device_scale_factor);
3267 if (webview()) {
3268 webview()->setDeviceScaleFactor(device_scale_factor);
3269 webview()->settings()->setPreferCompositingToLCDTextEnabled(
3270 PreferCompositingToLCDText(compositor_deps_, device_scale_factor_));
3272 if (auto_resize_mode_)
3273 AutoResizeCompositor();
3276 bool RenderViewImpl::SetDeviceColorProfile(
3277 const std::vector<char>& profile) {
3278 bool changed = RenderWidget::SetDeviceColorProfile(profile);
3279 if (changed && webview()) {
3280 WebVector<char> colorProfile = profile;
3281 webview()->setDeviceColorProfile(colorProfile);
3283 return changed;
3286 void RenderViewImpl::ResetDeviceColorProfileForTesting() {
3287 RenderWidget::ResetDeviceColorProfileForTesting();
3288 if (webview())
3289 webview()->resetDeviceColorProfile();
3292 ui::TextInputType RenderViewImpl::GetTextInputType() {
3293 #if defined(ENABLE_PLUGINS)
3294 if (focused_pepper_plugin_)
3295 return focused_pepper_plugin_->text_input_type();
3296 #endif
3297 return RenderWidget::GetTextInputType();
3300 void RenderViewImpl::GetSelectionBounds(gfx::Rect* start, gfx::Rect* end) {
3301 #if defined(ENABLE_PLUGINS)
3302 if (focused_pepper_plugin_) {
3303 // TODO(kinaba) http://crbug.com/101101
3304 // Current Pepper IME API does not handle selection bounds. So we simply
3305 // use the caret position as an empty range for now. It will be updated
3306 // after Pepper API equips features related to surrounding text retrieval.
3307 gfx::Rect caret = focused_pepper_plugin_->GetCaretBounds();
3308 *start = caret;
3309 *end = caret;
3310 return;
3312 #endif
3313 RenderWidget::GetSelectionBounds(start, end);
3316 void RenderViewImpl::FocusChangeComplete() {
3317 RenderWidget::FocusChangeComplete();
3318 FOR_EACH_OBSERVER(RenderViewObserver, observers_, FocusChangeComplete());
3321 void RenderViewImpl::GetCompositionCharacterBounds(
3322 std::vector<gfx::Rect>* bounds) {
3323 DCHECK(bounds);
3324 bounds->clear();
3326 #if defined(ENABLE_PLUGINS)
3327 if (focused_pepper_plugin_) {
3328 return;
3330 #endif
3332 if (!webview())
3333 return;
3334 size_t start_offset = 0;
3335 size_t character_count = 0;
3336 if (!webview()->compositionRange(&start_offset, &character_count))
3337 return;
3338 if (character_count == 0)
3339 return;
3341 blink::WebFrame* frame = webview()->focusedFrame();
3342 if (!frame)
3343 return;
3345 bounds->reserve(character_count);
3346 blink::WebRect webrect;
3347 for (size_t i = 0; i < character_count; ++i) {
3348 if (!frame->firstRectForCharacterRange(start_offset + i, 1, webrect)) {
3349 DLOG(ERROR) << "Could not retrieve character rectangle at " << i;
3350 bounds->clear();
3351 return;
3353 bounds->push_back(webrect);
3357 void RenderViewImpl::GetCompositionRange(gfx::Range* range) {
3358 #if defined(ENABLE_PLUGINS)
3359 if (focused_pepper_plugin_) {
3360 return;
3362 #endif
3363 RenderWidget::GetCompositionRange(range);
3366 bool RenderViewImpl::CanComposeInline() {
3367 #if defined(ENABLE_PLUGINS)
3368 if (focused_pepper_plugin_)
3369 return focused_pepper_plugin_->IsPluginAcceptingCompositionEvents();
3370 #endif
3371 return true;
3374 void RenderViewImpl::DidCompletePageScaleAnimation() {
3375 FocusChangeComplete();
3378 void RenderViewImpl::SetScreenMetricsEmulationParameters(
3379 bool enabled,
3380 const blink::WebDeviceEmulationParams& params) {
3381 if (webview() && compositor()) {
3382 if (enabled)
3383 webview()->enableDeviceEmulation(params);
3384 else
3385 webview()->disableDeviceEmulation();
3389 bool RenderViewImpl::ScheduleFileChooser(
3390 const FileChooserParams& params,
3391 WebFileChooserCompletion* completion) {
3392 static const size_t kMaximumPendingFileChooseRequests = 4;
3393 if (file_chooser_completions_.size() > kMaximumPendingFileChooseRequests) {
3394 // This sanity check prevents too many file choose requests from getting
3395 // queued which could DoS the user. Getting these is most likely a
3396 // programming error (there are many ways to DoS the user so it's not
3397 // considered a "real" security check), either in JS requesting many file
3398 // choosers to pop up, or in a plugin.
3400 // TODO(brettw) we might possibly want to require a user gesture to open
3401 // a file picker, which will address this issue in a better way.
3402 return false;
3405 file_chooser_completions_.push_back(linked_ptr<PendingFileChooser>(
3406 new PendingFileChooser(params, completion)));
3407 if (file_chooser_completions_.size() == 1) {
3408 // Actually show the browse dialog when this is the first request.
3409 Send(new ViewHostMsg_RunFileChooser(routing_id_, params));
3411 return true;
3414 blink::WebSpeechRecognizer* RenderViewImpl::speechRecognizer() {
3415 if (!speech_recognition_dispatcher_)
3416 speech_recognition_dispatcher_ = new SpeechRecognitionDispatcher(this);
3417 return speech_recognition_dispatcher_;
3420 void RenderViewImpl::zoomLimitsChanged(double minimum_level,
3421 double maximum_level) {
3422 // Round the double to avoid returning incorrect minimum/maximum zoom
3423 // percentages.
3424 int minimum_percent = round(
3425 ZoomLevelToZoomFactor(minimum_level) * 100);
3426 int maximum_percent = round(
3427 ZoomLevelToZoomFactor(maximum_level) * 100);
3429 Send(new ViewHostMsg_UpdateZoomLimits(
3430 routing_id_, minimum_percent, maximum_percent));
3433 void RenderViewImpl::zoomLevelChanged() {
3434 double zoom_level = webview()->zoomLevel();
3436 // Do not send empty URLs to the browser when we are just setting the default
3437 // zoom level (from RendererPreferences) before the first navigation.
3438 if (!webview()->mainFrame()->document().url().isEmpty()) {
3439 // Tell the browser which url got zoomed so it can update the menu and the
3440 // saved values if necessary
3441 Send(new ViewHostMsg_DidZoomURL(
3442 routing_id_, zoom_level,
3443 GURL(webview()->mainFrame()->document().url())));
3447 void RenderViewImpl::pageScaleFactorChanged() {
3448 if (!webview())
3449 return;
3450 bool page_scale_factor_is_one = webview()->pageScaleFactor() == 1;
3451 if (page_scale_factor_is_one == page_scale_factor_is_one_)
3452 return;
3453 page_scale_factor_is_one_ = page_scale_factor_is_one;
3454 Send(new ViewHostMsg_PageScaleFactorIsOneChanged(routing_id_,
3455 page_scale_factor_is_one_));
3458 double RenderViewImpl::zoomLevelToZoomFactor(double zoom_level) const {
3459 return ZoomLevelToZoomFactor(zoom_level);
3462 double RenderViewImpl::zoomFactorToZoomLevel(double factor) const {
3463 return ZoomFactorToZoomLevel(factor);
3466 void RenderViewImpl::registerProtocolHandler(const WebString& scheme,
3467 const WebURL& url,
3468 const WebString& title) {
3469 bool user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
3470 Send(new ViewHostMsg_RegisterProtocolHandler(routing_id_,
3471 base::UTF16ToUTF8(scheme),
3472 url,
3473 title,
3474 user_gesture));
3477 void RenderViewImpl::unregisterProtocolHandler(const WebString& scheme,
3478 const WebURL& url) {
3479 bool user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
3480 Send(new ViewHostMsg_UnregisterProtocolHandler(routing_id_,
3481 base::UTF16ToUTF8(scheme),
3482 url,
3483 user_gesture));
3486 blink::WebPageVisibilityState RenderViewImpl::visibilityState() const {
3487 blink::WebPageVisibilityState current_state = is_hidden() ?
3488 blink::WebPageVisibilityStateHidden :
3489 blink::WebPageVisibilityStateVisible;
3490 blink::WebPageVisibilityState override_state = current_state;
3491 // TODO(jam): move this method to WebFrameClient.
3492 if (GetContentClient()->renderer()->
3493 ShouldOverridePageVisibilityState(main_render_frame_.get(),
3494 &override_state))
3495 return override_state;
3496 return current_state;
3499 void RenderViewImpl::draggableRegionsChanged() {
3500 FOR_EACH_OBSERVER(
3501 RenderViewObserver,
3502 observers_,
3503 DraggableRegionsChanged(webview()->mainFrame()));
3506 #if defined(OS_ANDROID)
3507 WebContentDetectionResult RenderViewImpl::detectContentAround(
3508 const WebHitTestResult& touch_hit) {
3509 DCHECK(touch_hit.node().isTextNode());
3511 // Process the position with all the registered content detectors until
3512 // a match is found. Priority is provided by their relative order.
3513 for (ContentDetectorList::const_iterator it = content_detectors_.begin();
3514 it != content_detectors_.end(); ++it) {
3515 ContentDetector::Result content = (*it)->FindTappedContent(touch_hit);
3516 if (content.valid) {
3517 return WebContentDetectionResult(content.content_boundaries,
3518 base::UTF8ToUTF16(content.text), content.intent_url);
3521 return WebContentDetectionResult();
3524 void RenderViewImpl::scheduleContentIntent(const WebURL& intent) {
3525 // Introduce a short delay so that the user can notice the content.
3526 base::MessageLoop::current()->PostDelayedTask(
3527 FROM_HERE,
3528 base::Bind(&RenderViewImpl::LaunchAndroidContentIntent,
3529 AsWeakPtr(),
3530 intent,
3531 expected_content_intent_id_),
3532 base::TimeDelta::FromMilliseconds(kContentIntentDelayMilliseconds));
3535 void RenderViewImpl::cancelScheduledContentIntents() {
3536 ++expected_content_intent_id_;
3539 void RenderViewImpl::LaunchAndroidContentIntent(const GURL& intent,
3540 size_t request_id) {
3541 if (request_id != expected_content_intent_id_)
3542 return;
3544 // Remove the content highlighting if any.
3545 scheduleComposite();
3547 if (!intent.is_empty())
3548 Send(new ViewHostMsg_StartContentIntent(routing_id_, intent));
3551 bool RenderViewImpl::openDateTimeChooser(
3552 const blink::WebDateTimeChooserParams& params,
3553 blink::WebDateTimeChooserCompletion* completion) {
3554 // JavaScript may try to open a date time chooser while one is already open.
3555 if (date_time_picker_client_)
3556 return false;
3557 date_time_picker_client_.reset(
3558 new RendererDateTimePicker(this, params, completion));
3559 return date_time_picker_client_->Open();
3562 void RenderViewImpl::DismissDateTimeDialog() {
3563 DCHECK(date_time_picker_client_);
3564 date_time_picker_client_.reset(NULL);
3567 #endif // defined(OS_ANDROID)
3569 void RenderViewImpl::OnShowContextMenu(
3570 ui::MenuSourceType source_type, const gfx::Point& location) {
3571 context_menu_source_type_ = source_type;
3572 has_host_context_menu_location_ = true;
3573 host_context_menu_location_ = location;
3574 if (webview())
3575 webview()->showContextMenu();
3576 has_host_context_menu_location_ = false;
3579 void RenderViewImpl::OnEnableViewSourceMode() {
3580 if (!webview())
3581 return;
3582 WebFrame* main_frame = webview()->mainFrame();
3583 if (!main_frame)
3584 return;
3585 main_frame->enableViewSourceMode(true);
3588 #if defined(OS_ANDROID) || defined(TOOLKIT_VIEWS)
3589 bool RenderViewImpl::didTapMultipleTargets(
3590 const WebSize& inner_viewport_offset,
3591 const WebRect& touch_rect,
3592 const WebVector<WebRect>& target_rects) {
3593 if (!switches::IsLinkDisambiguationPopupEnabled())
3594 return false;
3596 // Never show a disambiguation popup when accessibility is enabled,
3597 // as this interferes with "touch exploration".
3598 AccessibilityMode accessibility_mode =
3599 GetMainRenderFrame()->accessibility_mode();
3600 bool matches_accessibility_mode_complete =
3601 (accessibility_mode & AccessibilityModeComplete) ==
3602 AccessibilityModeComplete;
3603 if (matches_accessibility_mode_complete)
3604 return false;
3606 // The touch_rect, target_rects and zoom_rect are in the outer viewport
3607 // reference frame.
3608 gfx::Rect zoom_rect;
3609 float new_total_scale =
3610 DisambiguationPopupHelper::ComputeZoomAreaAndScaleFactor(
3611 touch_rect, target_rects, GetSize(),
3612 gfx::Rect(webview()->mainFrame()->visibleContentRect()).size(),
3613 device_scale_factor_ * webview()->pageScaleFactor(), &zoom_rect);
3614 if (!new_total_scale || zoom_rect.IsEmpty())
3615 return false;
3617 bool handled = false;
3618 switch (renderer_preferences_.tap_multiple_targets_strategy) {
3619 case TAP_MULTIPLE_TARGETS_STRATEGY_ZOOM:
3620 handled = webview()->zoomToMultipleTargetsRect(zoom_rect);
3621 break;
3622 case TAP_MULTIPLE_TARGETS_STRATEGY_POPUP: {
3623 gfx::Size canvas_size =
3624 gfx::ToCeiledSize(gfx::ScaleSize(zoom_rect.size(), new_total_scale));
3625 cc::SharedBitmapManager* manager =
3626 RenderThreadImpl::current()->shared_bitmap_manager();
3627 scoped_ptr<cc::SharedBitmap> shared_bitmap =
3628 manager->AllocateSharedBitmap(canvas_size);
3629 CHECK(!!shared_bitmap);
3631 SkBitmap bitmap;
3632 SkImageInfo info = SkImageInfo::MakeN32Premul(canvas_size.width(),
3633 canvas_size.height());
3634 bitmap.installPixels(info, shared_bitmap->pixels(), info.minRowBytes());
3635 SkCanvas canvas(bitmap);
3637 // TODO(trchen): Cleanup the device scale factor mess.
3638 // device scale will be applied in WebKit
3639 // --> zoom_rect doesn't include device scale,
3640 // but WebKit will still draw on zoom_rect * device_scale_factor_
3641 canvas.scale(new_total_scale / device_scale_factor_,
3642 new_total_scale / device_scale_factor_);
3643 canvas.translate(-zoom_rect.x() * device_scale_factor_,
3644 -zoom_rect.y() * device_scale_factor_);
3646 DCHECK(webwidget_->isAcceleratedCompositingActive());
3647 // TODO(aelias): The disambiguation popup should be composited so we
3648 // don't have to call this method.
3649 webwidget_->paintCompositedDeprecated(&canvas, zoom_rect);
3652 gfx::Rect zoom_rect_in_screen =
3653 zoom_rect - gfx::Vector2d(inner_viewport_offset.width,
3654 inner_viewport_offset.height);
3656 gfx::Rect physical_window_zoom_rect = gfx::ToEnclosingRect(
3657 ClientRectToPhysicalWindowRect(gfx::RectF(zoom_rect_in_screen)));
3659 Send(new ViewHostMsg_ShowDisambiguationPopup(routing_id_,
3660 physical_window_zoom_rect,
3661 canvas_size,
3662 shared_bitmap->id()));
3663 cc::SharedBitmapId id = shared_bitmap->id();
3664 disambiguation_bitmaps_[id] = shared_bitmap.release();
3665 handled = true;
3666 break;
3668 case TAP_MULTIPLE_TARGETS_STRATEGY_NONE:
3669 // No-op.
3670 break;
3673 return handled;
3675 #endif // defined(OS_ANDROID) || defined(TOOLKIT_VIEWS)
3677 unsigned RenderViewImpl::GetLocalSessionHistoryLengthForTesting() const {
3678 return history_list_length_;
3681 void RenderViewImpl::SetFocusAndActivateForTesting(bool enable) {
3682 if (enable) {
3683 if (has_focus())
3684 return;
3685 OnSetActive(true);
3686 OnSetFocus(true);
3687 } else {
3688 if (!has_focus())
3689 return;
3690 OnSetFocus(false);
3691 OnSetActive(false);
3695 void RenderViewImpl::SetDeviceScaleFactorForTesting(float factor) {
3696 ViewMsg_Resize_Params params;
3697 params.screen_info = screen_info_;
3698 params.screen_info.deviceScaleFactor = factor;
3699 params.new_size = size();
3700 params.visible_viewport_size = visible_viewport_size_;
3701 params.physical_backing_size =
3702 gfx::ToCeiledSize(gfx::ScaleSize(size(), factor));
3703 params.top_controls_shrink_blink_size = false;
3704 params.top_controls_height = 0.f;
3705 params.resizer_rect = WebRect();
3706 params.is_fullscreen_granted = is_fullscreen_granted();
3707 params.display_mode = display_mode_;
3708 OnResize(params);
3711 void RenderViewImpl::SetDeviceColorProfileForTesting(
3712 const std::vector<char>& color_profile) {
3713 SetDeviceColorProfile(color_profile);
3716 void RenderViewImpl::ForceResizeForTesting(const gfx::Size& new_size) {
3717 gfx::Rect new_window_rect(rootWindowRect().x,
3718 rootWindowRect().y,
3719 new_size.width(),
3720 new_size.height());
3721 SetWindowRectSynchronously(new_window_rect);
3724 void RenderViewImpl::UseSynchronousResizeModeForTesting(bool enable) {
3725 resizing_mode_selector_->set_is_synchronous_mode(enable);
3728 void RenderViewImpl::EnableAutoResizeForTesting(const gfx::Size& min_size,
3729 const gfx::Size& max_size) {
3730 OnEnableAutoResize(min_size, max_size);
3733 void RenderViewImpl::DisableAutoResizeForTesting(const gfx::Size& new_size) {
3734 OnDisableAutoResize(new_size);
3737 void RenderViewImpl::OnReleaseDisambiguationPopupBitmap(
3738 const cc::SharedBitmapId& id) {
3739 BitmapMap::iterator it = disambiguation_bitmaps_.find(id);
3740 DCHECK(it != disambiguation_bitmaps_.end());
3741 delete it->second;
3742 disambiguation_bitmaps_.erase(it);
3745 void RenderViewImpl::DidCommitCompositorFrame() {
3746 RenderWidget::DidCommitCompositorFrame();
3747 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidCommitCompositorFrame());
3750 void RenderViewImpl::SendUpdateFaviconURL(const std::vector<FaviconURL>& urls) {
3751 if (!urls.empty())
3752 Send(new ViewHostMsg_UpdateFaviconURL(routing_id_, urls));
3755 void RenderViewImpl::DidStopLoadingIcons() {
3756 int icon_types = WebIconURL::TypeFavicon | WebIconURL::TypeTouchPrecomposed |
3757 WebIconURL::TypeTouch;
3759 // Favicons matter only for the top-level frame. If it is a WebRemoteFrame,
3760 // just return early.
3761 if (webview()->mainFrame()->isWebRemoteFrame())
3762 return;
3764 WebVector<WebIconURL> icon_urls =
3765 webview()->mainFrame()->iconURLs(icon_types);
3767 std::vector<FaviconURL> urls;
3768 for (size_t i = 0; i < icon_urls.size(); i++) {
3769 WebURL url = icon_urls[i].iconURL();
3770 std::vector<gfx::Size> sizes;
3771 ConvertToFaviconSizes(icon_urls[i].sizes(), &sizes);
3772 if (!url.isEmpty())
3773 urls.push_back(
3774 FaviconURL(url, ToFaviconType(icon_urls[i].iconType()), sizes));
3776 SendUpdateFaviconURL(urls);
3779 } // namespace content