Roll src/third_party/WebKit eac3800:0237a66 (svn 202606:202607)
[chromium-blink-merge.git] / content / renderer / render_view_impl.cc
blob91713f5523e65f1930bccb4df7a7e0129cad955b
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/metrics/field_trial.h"
22 #include "base/metrics/histogram.h"
23 #include "base/process/kill.h"
24 #include "base/process/process.h"
25 #include "base/strings/string_number_conversions.h"
26 #include "base/strings/string_piece.h"
27 #include "base/strings/string_split.h"
28 #include "base/strings/string_util.h"
29 #include "base/strings/sys_string_conversions.h"
30 #include "base/strings/utf_string_conversions.h"
31 #include "base/time/time.h"
32 #include "base/trace_event/trace_event.h"
33 #include "content/child/appcache/appcache_dispatcher.h"
34 #include "content/child/appcache/web_application_cache_host_impl.h"
35 #include "content/child/child_shared_bitmap_manager.h"
36 #include "content/child/npapi/webplugin_delegate_impl.h"
37 #include "content/child/request_extra_data.h"
38 #include "content/child/v8_value_converter_impl.h"
39 #include "content/child/webmessageportchannel_impl.h"
40 #include "content/common/content_constants_internal.h"
41 #include "content/common/database_messages.h"
42 #include "content/common/dom_storage/dom_storage_types.h"
43 #include "content/common/drag_messages.h"
44 #include "content/common/frame_messages.h"
45 #include "content/common/frame_replication_state.h"
46 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
47 #include "content/common/input_messages.h"
48 #include "content/common/pepper_messages.h"
49 #include "content/common/site_isolation_policy.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/WebDocument.h"
138 #include "third_party/WebKit/public/web/WebElement.h"
139 #include "third_party/WebKit/public/web/WebFileChooserParams.h"
140 #include "third_party/WebKit/public/web/WebFindOptions.h"
141 #include "third_party/WebKit/public/web/WebFormControlElement.h"
142 #include "third_party/WebKit/public/web/WebFormElement.h"
143 #include "third_party/WebKit/public/web/WebFrame.h"
144 #include "third_party/WebKit/public/web/WebGlyphCache.h"
145 #include "third_party/WebKit/public/web/WebHistoryItem.h"
146 #include "third_party/WebKit/public/web/WebHitTestResult.h"
147 #include "third_party/WebKit/public/web/WebInputElement.h"
148 #include "third_party/WebKit/public/web/WebInputEvent.h"
149 #include "third_party/WebKit/public/web/WebLocalFrame.h"
150 #include "third_party/WebKit/public/web/WebMediaPlayerAction.h"
151 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
152 #include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
153 #include "third_party/WebKit/public/web/WebNodeList.h"
154 #include "third_party/WebKit/public/web/WebPageSerializer.h"
155 #include "third_party/WebKit/public/web/WebPlugin.h"
156 #include "third_party/WebKit/public/web/WebPluginAction.h"
157 #include "third_party/WebKit/public/web/WebPluginContainer.h"
158 #include "third_party/WebKit/public/web/WebPluginDocument.h"
159 #include "third_party/WebKit/public/web/WebRange.h"
160 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
161 #include "third_party/WebKit/public/web/WebScriptSource.h"
162 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
163 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
164 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
165 #include "third_party/WebKit/public/web/WebSettings.h"
166 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
167 #include "third_party/WebKit/public/web/WebView.h"
168 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
169 #include "third_party/WebKit/public/web/default/WebRenderTheme.h"
170 #include "third_party/icu/source/common/unicode/uchar.h"
171 #include "third_party/icu/source/common/unicode/uscript.h"
172 #include "ui/base/clipboard/clipboard.h"
173 #include "ui/base/ui_base_switches_util.h"
174 #include "ui/events/latency_info.h"
175 #include "ui/gfx/geometry/point.h"
176 #include "ui/gfx/geometry/rect.h"
177 #include "ui/gfx/geometry/rect_conversions.h"
178 #include "ui/gfx/geometry/size_conversions.h"
179 #include "ui/gfx/native_widget_types.h"
180 #include "v8/include/v8.h"
182 #if defined(OS_ANDROID)
183 #include <cpu-features.h>
185 #include "content/renderer/android/address_detector.h"
186 #include "content/renderer/android/content_detector.h"
187 #include "content/renderer/android/email_detector.h"
188 #include "content/renderer/android/phone_number_detector.h"
189 #include "third_party/WebKit/public/platform/WebFloatPoint.h"
190 #include "third_party/WebKit/public/platform/WebFloatRect.h"
191 #include "ui/gfx/geometry/rect_f.h"
193 #elif defined(OS_WIN)
194 // TODO(port): these files are currently Windows only because they concern:
195 // * theming
196 #include "ui/native_theme/native_theme_win.h"
197 #elif defined(USE_X11)
198 #include "ui/native_theme/native_theme.h"
199 #elif defined(OS_MACOSX)
200 #include "skia/ext/skia_utils_mac.h"
201 #endif
203 #if defined(ENABLE_PLUGINS)
204 #include "content/renderer/npapi/webplugin_delegate_proxy.h"
205 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
206 #include "content/renderer/pepper/pepper_plugin_registry.h"
207 #endif
209 #if defined(ENABLE_WEBRTC)
210 #include "content/renderer/media/rtc_peer_connection_handler.h"
211 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
212 #endif
214 using blink::WebAXObject;
215 using blink::WebApplicationCacheHost;
216 using blink::WebApplicationCacheHostClient;
217 using blink::WebCString;
218 using blink::WebColor;
219 using blink::WebColorName;
220 using blink::WebConsoleMessage;
221 using blink::WebData;
222 using blink::WebDataSource;
223 using blink::WebDocument;
224 using blink::WebDragData;
225 using blink::WebDragOperation;
226 using blink::WebDragOperationsMask;
227 using blink::WebElement;
228 using blink::WebFileChooserCompletion;
229 using blink::WebFindOptions;
230 using blink::WebFormControlElement;
231 using blink::WebFormElement;
232 using blink::WebFrame;
233 using blink::WebGestureEvent;
234 using blink::WebHistoryItem;
235 using blink::WebHTTPBody;
236 using blink::WebIconURL;
237 using blink::WebImage;
238 using blink::WebInputElement;
239 using blink::WebInputEvent;
240 using blink::WebLocalFrame;
241 using blink::WebMediaPlayerAction;
242 using blink::WebMouseEvent;
243 using blink::WebNavigationPolicy;
244 using blink::WebNavigationType;
245 using blink::WebNode;
246 using blink::WebPageSerializer;
247 using blink::WebPageSerializerClient;
248 using blink::WebPeerConnection00Handler;
249 using blink::WebPeerConnection00HandlerClient;
250 using blink::WebPeerConnectionHandler;
251 using blink::WebPeerConnectionHandlerClient;
252 using blink::WebPluginAction;
253 using blink::WebPluginContainer;
254 using blink::WebPluginDocument;
255 using blink::WebPoint;
256 using blink::WebRange;
257 using blink::WebRect;
258 using blink::WebReferrerPolicy;
259 using blink::WebScriptSource;
260 using blink::WebSearchableFormData;
261 using blink::WebSecurityOrigin;
262 using blink::WebSecurityPolicy;
263 using blink::WebSettings;
264 using blink::WebSize;
265 using blink::WebStorageNamespace;
266 using blink::WebStorageQuotaCallbacks;
267 using blink::WebStorageQuotaError;
268 using blink::WebStorageQuotaType;
269 using blink::WebString;
270 using blink::WebTextAffinity;
271 using blink::WebTextDirection;
272 using blink::WebTouchEvent;
273 using blink::WebURL;
274 using blink::WebURLError;
275 using blink::WebURLRequest;
276 using blink::WebURLResponse;
277 using blink::WebUserGestureIndicator;
278 using blink::WebVector;
279 using blink::WebView;
280 using blink::WebWidget;
281 using blink::WebWindowFeatures;
282 using blink::WebNetworkStateNotifier;
283 using blink::WebRuntimeFeatures;
284 using base::Time;
285 using base::TimeDelta;
287 #if defined(OS_ANDROID)
288 using blink::WebContentDetectionResult;
289 using blink::WebFloatPoint;
290 using blink::WebFloatRect;
291 using blink::WebHitTestResult;
292 #endif
294 namespace content {
296 //-----------------------------------------------------------------------------
298 typedef std::map<blink::WebView*, RenderViewImpl*> ViewMap;
299 static base::LazyInstance<ViewMap> g_view_map = LAZY_INSTANCE_INITIALIZER;
300 typedef std::map<int32, RenderViewImpl*> RoutingIDViewMap;
301 static base::LazyInstance<RoutingIDViewMap> g_routing_id_view_map =
302 LAZY_INSTANCE_INITIALIZER;
304 // Time, in seconds, we delay before sending content state changes (such as form
305 // state and scroll position) to the browser. We delay sending changes to avoid
306 // spamming the browser.
307 // To avoid having tab/session restore require sending a message to get the
308 // current content state during tab closing we use a shorter timeout for the
309 // foreground renderer. This means there is a small window of time from which
310 // content state is modified and not sent to session restore, but this is
311 // better than having to wake up all renderers during shutdown.
312 const int kDelaySecondsForContentStateSyncHidden = 5;
313 const int kDelaySecondsForContentStateSync = 1;
315 #if defined(OS_ANDROID)
316 // Delay between tapping in content and launching the associated android intent.
317 // Used to allow users see what has been recognized as content.
318 const size_t kContentIntentDelayMilliseconds = 700;
319 #endif
321 static RenderViewImpl* (*g_create_render_view_impl)(
322 CompositorDependencies* compositor_deps,
323 const ViewMsg_New_Params&) = nullptr;
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 // 1.5 is a common touchscreen tablet device scale factor. For such
365 // devices main thread antialiasing is a heavy burden.
366 return device_scale_factor >= 1.5f;
367 #endif
371 static bool PreferCompositingToLCDText(CompositorDependencies* compositor_deps,
372 float device_scale_factor) {
373 const base::CommandLine& command_line =
374 *base::CommandLine::ForCurrentProcess();
375 if (command_line.HasSwitch(switches::kDisablePreferCompositingToLCDText))
376 return false;
377 if (command_line.HasSwitch(switches::kEnablePreferCompositingToLCDText))
378 return true;
379 if (!compositor_deps->IsLcdTextEnabled())
380 return true;
381 return DeviceScaleEnsuresTextQuality(device_scale_factor);
384 static FaviconURL::IconType ToFaviconType(blink::WebIconURL::Type type) {
385 switch (type) {
386 case blink::WebIconURL::TypeFavicon:
387 return FaviconURL::FAVICON;
388 case blink::WebIconURL::TypeTouch:
389 return FaviconURL::TOUCH_ICON;
390 case blink::WebIconURL::TypeTouchPrecomposed:
391 return FaviconURL::TOUCH_PRECOMPOSED_ICON;
392 case blink::WebIconURL::TypeInvalid:
393 return FaviconURL::INVALID_ICON;
395 return FaviconURL::INVALID_ICON;
398 static void ConvertToFaviconSizes(
399 const blink::WebVector<blink::WebSize>& web_sizes,
400 std::vector<gfx::Size>* sizes) {
401 DCHECK(sizes->empty());
402 sizes->reserve(web_sizes.size());
403 for (size_t i = 0; i < web_sizes.size(); ++i)
404 sizes->push_back(gfx::Size(web_sizes[i]));
407 ///////////////////////////////////////////////////////////////////////////////
409 struct RenderViewImpl::PendingFileChooser {
410 PendingFileChooser(const FileChooserParams& p, WebFileChooserCompletion* c)
411 : params(p),
412 completion(c) {
414 FileChooserParams params;
415 WebFileChooserCompletion* completion; // MAY BE NULL to skip callback.
418 namespace {
420 class WebWidgetLockTarget : public MouseLockDispatcher::LockTarget {
421 public:
422 explicit WebWidgetLockTarget(blink::WebWidget* webwidget)
423 : webwidget_(webwidget) {}
425 void OnLockMouseACK(bool succeeded) override {
426 if (succeeded)
427 webwidget_->didAcquirePointerLock();
428 else
429 webwidget_->didNotAcquirePointerLock();
432 void OnMouseLockLost() override { webwidget_->didLosePointerLock(); }
434 bool HandleMouseLockedInputEvent(const blink::WebMouseEvent& event) override {
435 // The WebWidget handles mouse lock in WebKit's handleInputEvent().
436 return false;
439 private:
440 blink::WebWidget* webwidget_;
443 WebDragData DropDataToWebDragData(const DropData& drop_data) {
444 std::vector<WebDragData::Item> item_list;
446 // These fields are currently unused when dragging into WebKit.
447 DCHECK(drop_data.download_metadata.empty());
448 DCHECK(drop_data.file_contents.empty());
449 DCHECK(drop_data.file_description_filename.empty());
451 if (!drop_data.text.is_null()) {
452 WebDragData::Item item;
453 item.storageType = WebDragData::Item::StorageTypeString;
454 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeText);
455 item.stringData = drop_data.text.string();
456 item_list.push_back(item);
459 // TODO(dcheng): Do we need to distinguish between null and empty URLs? Is it
460 // meaningful to write an empty URL to the clipboard?
461 if (!drop_data.url.is_empty()) {
462 WebDragData::Item item;
463 item.storageType = WebDragData::Item::StorageTypeString;
464 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeURIList);
465 item.stringData = WebString::fromUTF8(drop_data.url.spec());
466 item.title = drop_data.url_title;
467 item_list.push_back(item);
470 if (!drop_data.html.is_null()) {
471 WebDragData::Item item;
472 item.storageType = WebDragData::Item::StorageTypeString;
473 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeHTML);
474 item.stringData = drop_data.html.string();
475 item.baseURL = drop_data.html_base_url;
476 item_list.push_back(item);
479 for (std::vector<ui::FileInfo>::const_iterator it =
480 drop_data.filenames.begin();
481 it != drop_data.filenames.end();
482 ++it) {
483 WebDragData::Item item;
484 item.storageType = WebDragData::Item::StorageTypeFilename;
485 item.filenameData = it->path.AsUTF16Unsafe();
486 item.displayNameData = it->display_name.AsUTF16Unsafe();
487 item_list.push_back(item);
490 for (std::vector<DropData::FileSystemFileInfo>::const_iterator it =
491 drop_data.file_system_files.begin();
492 it != drop_data.file_system_files.end();
493 ++it) {
494 WebDragData::Item item;
495 item.storageType = WebDragData::Item::StorageTypeFileSystemFile;
496 item.fileSystemURL = it->url;
497 item.fileSystemFileSize = it->size;
498 item_list.push_back(item);
501 for (std::map<base::string16, base::string16>::const_iterator it =
502 drop_data.custom_data.begin();
503 it != drop_data.custom_data.end();
504 ++it) {
505 WebDragData::Item item;
506 item.storageType = WebDragData::Item::StorageTypeString;
507 item.stringType = it->first;
508 item.stringData = it->second;
509 item_list.push_back(item);
512 WebDragData result;
513 result.initialize();
514 result.setItems(item_list);
515 result.setFilesystemId(drop_data.filesystem_id);
516 return result;
519 typedef void (*SetFontFamilyWrapper)(blink::WebSettings*,
520 const base::string16&,
521 UScriptCode);
523 void SetStandardFontFamilyWrapper(WebSettings* settings,
524 const base::string16& font,
525 UScriptCode script) {
526 settings->setStandardFontFamily(font, script);
529 void SetFixedFontFamilyWrapper(WebSettings* settings,
530 const base::string16& font,
531 UScriptCode script) {
532 settings->setFixedFontFamily(font, script);
535 void SetSerifFontFamilyWrapper(WebSettings* settings,
536 const base::string16& font,
537 UScriptCode script) {
538 settings->setSerifFontFamily(font, script);
541 void SetSansSerifFontFamilyWrapper(WebSettings* settings,
542 const base::string16& font,
543 UScriptCode script) {
544 settings->setSansSerifFontFamily(font, script);
547 void SetCursiveFontFamilyWrapper(WebSettings* settings,
548 const base::string16& font,
549 UScriptCode script) {
550 settings->setCursiveFontFamily(font, script);
553 void SetFantasyFontFamilyWrapper(WebSettings* settings,
554 const base::string16& font,
555 UScriptCode script) {
556 settings->setFantasyFontFamily(font, script);
559 void SetPictographFontFamilyWrapper(WebSettings* settings,
560 const base::string16& font,
561 UScriptCode script) {
562 settings->setPictographFontFamily(font, script);
565 // If |scriptCode| is a member of a family of "similar" script codes, returns
566 // the script code in that family that is used by WebKit for font selection
567 // purposes. For example, USCRIPT_KATAKANA_OR_HIRAGANA and USCRIPT_JAPANESE are
568 // considered equivalent for the purposes of font selection. WebKit uses the
569 // script code USCRIPT_KATAKANA_OR_HIRAGANA. So, if |scriptCode| is
570 // USCRIPT_JAPANESE, the function returns USCRIPT_KATAKANA_OR_HIRAGANA. WebKit
571 // uses different scripts than the ones in Chrome pref names because the version
572 // of ICU included on certain ports does not have some of the newer scripts. If
573 // |scriptCode| is not a member of such a family, returns |scriptCode|.
574 UScriptCode GetScriptForWebSettings(UScriptCode scriptCode) {
575 switch (scriptCode) {
576 case USCRIPT_HIRAGANA:
577 case USCRIPT_KATAKANA:
578 case USCRIPT_JAPANESE:
579 return USCRIPT_KATAKANA_OR_HIRAGANA;
580 case USCRIPT_KOREAN:
581 return USCRIPT_HANGUL;
582 default:
583 return scriptCode;
587 void ApplyFontsFromMap(const ScriptFontFamilyMap& map,
588 SetFontFamilyWrapper setter,
589 WebSettings* settings) {
590 for (ScriptFontFamilyMap::const_iterator it = map.begin(); it != map.end();
591 ++it) {
592 int32 script = u_getPropertyValueEnum(UCHAR_SCRIPT, (it->first).c_str());
593 if (script >= 0 && script < USCRIPT_CODE_LIMIT) {
594 UScriptCode code = static_cast<UScriptCode>(script);
595 (*setter)(settings, it->second, GetScriptForWebSettings(code));
600 void ApplyBlinkSettings(const base::CommandLine& command_line,
601 WebSettings* settings) {
602 if (!command_line.HasSwitch(switches::kBlinkSettings))
603 return;
605 std::vector<std::string> blink_settings = base::SplitString(
606 command_line.GetSwitchValueASCII(switches::kBlinkSettings),
607 ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
608 for (const std::string& setting : blink_settings) {
609 size_t pos = setting.find('=');
610 settings->setFromStrings(
611 blink::WebString::fromLatin1(setting.substr(0, pos)),
612 blink::WebString::fromLatin1(
613 pos == std::string::npos ? "" : setting.substr(pos + 1)));
617 } // namespace
619 RenderViewImpl::RenderViewImpl(CompositorDependencies* compositor_deps,
620 const ViewMsg_New_Params& params)
621 : RenderWidget(compositor_deps,
622 blink::WebPopupTypeNone,
623 params.initial_size.screen_info,
624 params.swapped_out,
625 params.hidden,
626 params.never_visible),
627 webkit_preferences_(params.web_preferences),
628 send_content_state_immediately_(false),
629 enabled_bindings_(0),
630 send_preferred_size_changes_(false),
631 navigation_gesture_(NavigationGestureUnknown),
632 opened_by_user_gesture_(true),
633 opener_suppressed_(false),
634 suppress_dialogs_until_swap_out_(false),
635 page_id_(-1),
636 next_page_id_(params.next_page_id),
637 history_list_offset_(-1),
638 history_list_length_(0),
639 frames_in_progress_(0),
640 target_url_status_(TARGET_NONE),
641 uses_temporary_zoom_level_(false),
642 #if defined(OS_ANDROID)
643 top_controls_constraints_(TOP_CONTROLS_STATE_BOTH),
644 #endif
645 has_scrolled_focused_editable_node_into_rect_(false),
646 main_render_frame_(nullptr),
647 speech_recognition_dispatcher_(NULL),
648 mouse_lock_dispatcher_(NULL),
649 #if defined(OS_ANDROID)
650 expected_content_intent_id_(0),
651 #endif
652 #if defined(OS_WIN)
653 focused_plugin_id_(-1),
654 #endif
655 #if defined(ENABLE_PLUGINS)
656 plugin_find_handler_(NULL),
657 focused_pepper_plugin_(NULL),
658 pepper_last_mouse_event_target_(NULL),
659 #endif
660 enumeration_completion_id_(0),
661 session_storage_namespace_id_(params.session_storage_namespace_id),
662 page_scale_factor_is_one_(true) {
665 void RenderViewImpl::Initialize(const ViewMsg_New_Params& params,
666 bool was_created_by_renderer) {
667 routing_id_ = params.view_id;
668 surface_id_ = params.surface_id;
670 int opener_view_routing_id;
671 WebFrame* opener_frame = RenderFrameImpl::ResolveOpener(
672 params.opener_frame_route_id, &opener_view_routing_id);
673 if (opener_view_routing_id != MSG_ROUTING_NONE && was_created_by_renderer)
674 opener_id_ = opener_view_routing_id;
676 display_mode_= params.initial_size.display_mode;
678 // Ensure we start with a valid next_page_id_ from the browser.
679 DCHECK_GE(next_page_id_, 0);
681 webwidget_ = WebView::create(this);
682 webwidget_mouse_lock_target_.reset(new WebWidgetLockTarget(webwidget_));
684 g_view_map.Get().insert(std::make_pair(webview(), this));
685 g_routing_id_view_map.Get().insert(std::make_pair(routing_id_, this));
687 const base::CommandLine& command_line =
688 *base::CommandLine::ForCurrentProcess();
690 if (command_line.HasSwitch(switches::kStatsCollectionController))
691 stats_collection_observer_.reset(new StatsCollectionObserver(this));
693 if (params.main_frame_routing_id != MSG_ROUTING_NONE) {
694 main_render_frame_ =
695 RenderFrameImpl::CreateMainFrame(this, params.main_frame_routing_id);
698 if (params.proxy_routing_id != MSG_ROUTING_NONE) {
699 CHECK(params.swapped_out);
700 if (main_render_frame_) {
701 DCHECK(!SiteIsolationPolicy::IsSwappedOutStateForbidden());
702 RenderFrameProxy* proxy = RenderFrameProxy::CreateProxyToReplaceFrame(
703 main_render_frame_, params.proxy_routing_id,
704 blink::WebTreeScopeType::Document);
705 main_render_frame_->set_render_frame_proxy(proxy);
706 } else {
707 DCHECK(SiteIsolationPolicy::IsSwappedOutStateForbidden());
708 // Pass MSG_ROUTING_NONE for opener, since actual opener (if any) will be
709 // set separately below.
710 RenderFrameProxy::CreateFrameProxy(params.proxy_routing_id, routing_id_,
711 MSG_ROUTING_NONE, MSG_ROUTING_NONE,
712 params.replicated_frame_state);
716 if (main_render_frame_)
717 main_render_frame_->Initialize();
719 #if defined(OS_ANDROID)
720 content_detectors_.push_back(linked_ptr<ContentDetector>(
721 new AddressDetector()));
722 const std::string& contry_iso =
723 params.renderer_preferences.network_contry_iso;
724 if (!contry_iso.empty()) {
725 content_detectors_.push_back(linked_ptr<ContentDetector>(
726 new PhoneNumberDetector(contry_iso)));
728 content_detectors_.push_back(linked_ptr<ContentDetector>(
729 new EmailDetector()));
730 #endif
732 RenderThread::Get()->AddRoute(routing_id_, this);
733 // Take a reference on behalf of the RenderThread. This will be balanced
734 // when we receive ViewMsg_Close in the RenderWidget (which RenderView
735 // inherits from).
736 AddRef();
737 if (RenderThreadImpl::current()) {
738 RenderThreadImpl::current()->WidgetCreated();
739 if (is_hidden_)
740 RenderThreadImpl::current()->WidgetHidden();
743 // If this is a popup, we must wait for the CreatingNew_ACK message before
744 // completing initialization. Otherwise, we can finish it now.
745 if (opener_id_ == MSG_ROUTING_NONE) {
746 did_show_ = true;
747 CompleteInit();
750 webview()->setDeviceScaleFactor(device_scale_factor_);
751 webview()->setDisplayMode(display_mode_);
752 webview()->settings()->setPreferCompositingToLCDTextEnabled(
753 PreferCompositingToLCDText(compositor_deps_, device_scale_factor_));
754 webview()->settings()->setThreadedScrollingEnabled(
755 !command_line.HasSwitch(switches::kDisableThreadedScrolling));
756 webview()->settings()->setRootLayerScrolls(
757 command_line.HasSwitch(switches::kRootLayerScrolls));
759 ApplyWebPreferencesInternal(webkit_preferences_, webview(), compositor_deps_);
761 if (switches::IsTouchDragDropEnabled())
762 webview()->settings()->setTouchDragDropEnabled(true);
764 if (switches::IsTouchEditingEnabled())
765 webview()->settings()->setTouchEditingEnabled(true);
767 WebSettings::SelectionStrategyType selection_strategy =
768 WebSettings::SelectionStrategyType::Character;
769 const std::string selection_strategy_str =
770 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
771 switches::kTouchTextSelectionStrategy);
772 if (selection_strategy_str == "direction")
773 selection_strategy = WebSettings::SelectionStrategyType::Direction;
774 webview()->settings()->setSelectionStrategy(selection_strategy);
776 // Set the main frame's name. Only needs to be done for WebLocalFrames,
777 // since the remote case was handled as part of SetReplicatedState on the
778 // proxy above.
779 if (!params.replicated_frame_state.name.empty() &&
780 webview()->mainFrame()->isWebLocalFrame()) {
781 webview()->mainFrame()->setName(
782 blink::WebString::fromUTF8(params.replicated_frame_state.name));
785 // TODO(davidben): Move this state from Blink into content.
786 if (params.window_was_created_with_opener)
787 webview()->setOpenedByDOM();
789 OnSetRendererPrefs(params.renderer_preferences);
791 ApplyBlinkSettings(command_line, webview()->settings());
793 if (!params.enable_auto_resize) {
794 OnResize(params.initial_size);
795 } else {
796 OnEnableAutoResize(params.min_size, params.max_size);
799 new MHTMLGenerator(this);
800 #if defined(OS_MACOSX)
801 new TextInputClientObserver(this);
802 #endif // defined(OS_MACOSX)
804 // The next group of objects all implement RenderViewObserver, so are deleted
805 // along with the RenderView automatically.
806 mouse_lock_dispatcher_ = new RenderViewMouseLockDispatcher(this);
808 history_controller_.reset(new HistoryController(this));
810 new IdleUserDetector(this);
812 if (command_line.HasSwitch(switches::kDomAutomationController))
813 enabled_bindings_ |= BINDINGS_POLICY_DOM_AUTOMATION;
814 if (command_line.HasSwitch(switches::kStatsCollectionController))
815 enabled_bindings_ |= BINDINGS_POLICY_STATS_COLLECTION;
817 GetContentClient()->renderer()->RenderViewCreated(this);
819 // If we have an opener_frame but we weren't created by a renderer, then it's
820 // the browser asking us to set our opener to another frame.
821 if (opener_frame && !was_created_by_renderer)
822 webview()->mainFrame()->setOpener(opener_frame);
824 // If we are initially swapped out, navigate to kSwappedOutURL.
825 // This ensures we are in a unique origin that others cannot script.
826 if (is_swapped_out_ && webview()->mainFrame()->isWebLocalFrame())
827 main_render_frame_->NavigateToSwappedOutURL();
830 RenderViewImpl::~RenderViewImpl() {
831 for (BitmapMap::iterator it = disambiguation_bitmaps_.begin();
832 it != disambiguation_bitmaps_.end();
833 ++it)
834 delete it->second;
836 // If file chooser is still waiting for answer, dispatch empty answer.
837 while (!file_chooser_completions_.empty()) {
838 if (file_chooser_completions_.front()->completion) {
839 file_chooser_completions_.front()->completion->didChooseFile(
840 WebVector<WebString>());
842 file_chooser_completions_.pop_front();
845 #if defined(OS_ANDROID)
846 // The date/time picker client is both a scoped_ptr member of this class and
847 // a RenderViewObserver. Reset it to prevent double deletion.
848 date_time_picker_client_.reset();
849 #endif
851 #ifndef NDEBUG
852 // Make sure we are no longer referenced by the ViewMap or RoutingIDViewMap.
853 ViewMap* views = g_view_map.Pointer();
854 for (ViewMap::iterator it = views->begin(); it != views->end(); ++it)
855 DCHECK_NE(this, it->second) << "Failed to call Close?";
856 RoutingIDViewMap* routing_id_views = g_routing_id_view_map.Pointer();
857 for (RoutingIDViewMap::iterator it = routing_id_views->begin();
858 it != routing_id_views->end(); ++it)
859 DCHECK_NE(this, it->second) << "Failed to call Close?";
860 #endif
862 FOR_EACH_OBSERVER(RenderViewObserver, observers_, RenderViewGone());
863 FOR_EACH_OBSERVER(RenderViewObserver, observers_, OnDestruct());
866 /*static*/
867 RenderViewImpl* RenderViewImpl::FromWebView(WebView* webview) {
868 ViewMap* views = g_view_map.Pointer();
869 ViewMap::iterator it = views->find(webview);
870 return it == views->end() ? NULL : it->second;
873 /*static*/
874 RenderView* RenderView::FromWebView(blink::WebView* webview) {
875 return RenderViewImpl::FromWebView(webview);
878 /*static*/
879 RenderViewImpl* RenderViewImpl::FromRoutingID(int32 routing_id) {
880 RoutingIDViewMap* views = g_routing_id_view_map.Pointer();
881 RoutingIDViewMap::iterator it = views->find(routing_id);
882 return it == views->end() ? NULL : it->second;
885 /*static*/
886 RenderView* RenderView::FromRoutingID(int routing_id) {
887 return RenderViewImpl::FromRoutingID(routing_id);
890 /* static */
891 size_t RenderView::GetRenderViewCount() {
892 return g_view_map.Get().size();
895 /*static*/
896 void RenderView::ForEach(RenderViewVisitor* visitor) {
897 ViewMap* views = g_view_map.Pointer();
898 for (ViewMap::iterator it = views->begin(); it != views->end(); ++it) {
899 if (!visitor->Visit(it->second))
900 return;
904 /*static*/
905 void RenderView::ApplyWebPreferences(const WebPreferences& prefs,
906 WebView* web_view) {
907 WebSettings* settings = web_view->settings();
908 ApplyFontsFromMap(prefs.standard_font_family_map,
909 SetStandardFontFamilyWrapper, settings);
910 ApplyFontsFromMap(prefs.fixed_font_family_map,
911 SetFixedFontFamilyWrapper, settings);
912 ApplyFontsFromMap(prefs.serif_font_family_map,
913 SetSerifFontFamilyWrapper, settings);
914 ApplyFontsFromMap(prefs.sans_serif_font_family_map,
915 SetSansSerifFontFamilyWrapper, settings);
916 ApplyFontsFromMap(prefs.cursive_font_family_map,
917 SetCursiveFontFamilyWrapper, settings);
918 ApplyFontsFromMap(prefs.fantasy_font_family_map,
919 SetFantasyFontFamilyWrapper, settings);
920 ApplyFontsFromMap(prefs.pictograph_font_family_map,
921 SetPictographFontFamilyWrapper, settings);
922 settings->setDefaultFontSize(prefs.default_font_size);
923 settings->setDefaultFixedFontSize(prefs.default_fixed_font_size);
924 settings->setMinimumFontSize(prefs.minimum_font_size);
925 settings->setMinimumLogicalFontSize(prefs.minimum_logical_font_size);
926 settings->setDefaultTextEncodingName(
927 base::ASCIIToUTF16(prefs.default_encoding));
928 settings->setJavaScriptEnabled(prefs.javascript_enabled);
929 settings->setWebSecurityEnabled(prefs.web_security_enabled);
930 settings->setJavaScriptCanOpenWindowsAutomatically(
931 prefs.javascript_can_open_windows_automatically);
932 settings->setLoadsImagesAutomatically(prefs.loads_images_automatically);
933 settings->setImagesEnabled(prefs.images_enabled);
934 settings->setPluginsEnabled(prefs.plugins_enabled);
935 settings->setDOMPasteAllowed(prefs.dom_paste_enabled);
936 settings->setUsesEncodingDetector(prefs.uses_universal_detector);
937 settings->setTextAreasAreResizable(prefs.text_areas_are_resizable);
938 settings->setAllowScriptsToCloseWindows(prefs.allow_scripts_to_close_windows);
939 settings->setDownloadableBinaryFontsEnabled(prefs.remote_fonts_enabled);
940 settings->setJavaScriptCanAccessClipboard(
941 prefs.javascript_can_access_clipboard);
942 WebRuntimeFeatures::enableXSLT(prefs.xslt_enabled);
943 WebRuntimeFeatures::enableSlimmingPaintV2(prefs.slimming_paint_v2_enabled);
944 settings->setXSSAuditorEnabled(prefs.xss_auditor_enabled);
945 settings->setDNSPrefetchingEnabled(prefs.dns_prefetching_enabled);
946 settings->setLocalStorageEnabled(prefs.local_storage_enabled);
947 settings->setSyncXHRInDocumentsEnabled(prefs.sync_xhr_in_documents_enabled);
948 WebRuntimeFeatures::enableDatabase(prefs.databases_enabled);
949 settings->setOfflineWebApplicationCacheEnabled(
950 prefs.application_cache_enabled);
951 settings->setCaretBrowsingEnabled(prefs.caret_browsing_enabled);
952 settings->setHyperlinkAuditingEnabled(prefs.hyperlink_auditing_enabled);
953 settings->setCookieEnabled(prefs.cookie_enabled);
954 settings->setNavigateOnDragDrop(prefs.navigate_on_drag_drop);
956 // By default, allow_universal_access_from_file_urls is set to false and thus
957 // we mitigate attacks from local HTML files by not granting file:// URLs
958 // universal access. Only test shell will enable this.
959 settings->setAllowUniversalAccessFromFileURLs(
960 prefs.allow_universal_access_from_file_urls);
961 settings->setAllowFileAccessFromFileURLs(
962 prefs.allow_file_access_from_file_urls);
964 // Enable the web audio API if requested on the command line.
965 settings->setWebAudioEnabled(prefs.webaudio_enabled);
967 // Enable experimental WebGL support if requested on command line
968 // and support is compiled in.
969 settings->setExperimentalWebGLEnabled(prefs.experimental_webgl_enabled);
971 // Disable GL multisampling if requested on command line.
972 settings->setOpenGLMultisamplingEnabled(prefs.gl_multisampling_enabled);
974 // Enable WebGL errors to the JS console if requested.
975 settings->setWebGLErrorsToConsoleEnabled(
976 prefs.webgl_errors_to_console_enabled);
978 // Uses the mock theme engine for scrollbars.
979 settings->setMockScrollbarsEnabled(prefs.mock_scrollbars_enabled);
981 // Enable gpu-accelerated 2d canvas if requested on the command line.
982 settings->setAccelerated2dCanvasEnabled(prefs.accelerated_2d_canvas_enabled);
984 settings->setMinimumAccelerated2dCanvasSize(
985 prefs.minimum_accelerated_2d_canvas_size);
987 // Disable antialiasing for 2d canvas if requested on the command line.
988 settings->setAntialiased2dCanvasEnabled(
989 !prefs.antialiased_2d_canvas_disabled);
991 // Enabled antialiasing of clips for 2d canvas if requested on the command
992 // line.
993 settings->setAntialiasedClips2dCanvasEnabled(
994 prefs.antialiased_clips_2d_canvas_enabled);
996 // Set MSAA sample count for 2d canvas if requested on the command line (or
997 // default value if not).
998 settings->setAccelerated2dCanvasMSAASampleCount(
999 prefs.accelerated_2d_canvas_msaa_sample_count);
1001 settings->setAsynchronousSpellCheckingEnabled(
1002 prefs.asynchronous_spell_checking_enabled);
1003 settings->setUnifiedTextCheckerEnabled(prefs.unified_textchecker_enabled);
1005 // Tabs to link is not part of the settings. WebCore calls
1006 // ChromeClient::tabsToLinks which is part of the glue code.
1007 web_view->setTabsToLinks(prefs.tabs_to_links);
1009 settings->setAllowDisplayOfInsecureContent(
1010 prefs.allow_displaying_insecure_content);
1011 settings->setAllowRunningOfInsecureContent(
1012 prefs.allow_running_insecure_content);
1013 settings->setDisableReadingFromCanvas(prefs.disable_reading_from_canvas);
1014 settings->setStrictMixedContentChecking(prefs.strict_mixed_content_checking);
1016 settings->setStrictlyBlockBlockableMixedContent(
1017 prefs.strictly_block_blockable_mixed_content);
1019 settings->setStrictMixedContentCheckingForPlugin(
1020 prefs.block_mixed_plugin_content);
1022 settings->setStrictPowerfulFeatureRestrictions(
1023 prefs.strict_powerful_feature_restrictions);
1024 settings->setPasswordEchoEnabled(prefs.password_echo_enabled);
1025 settings->setShouldPrintBackgrounds(prefs.should_print_backgrounds);
1026 settings->setShouldClearDocumentBackground(
1027 prefs.should_clear_document_background);
1028 settings->setEnableScrollAnimator(prefs.enable_scroll_animator);
1030 WebRuntimeFeatures::enableTouch(prefs.touch_enabled);
1031 settings->setMaxTouchPoints(prefs.pointer_events_max_touch_points);
1032 settings->setAvailablePointerTypes(prefs.available_pointer_types);
1033 settings->setPrimaryPointerType(
1034 static_cast<WebSettings::PointerType>(prefs.primary_pointer_type));
1035 settings->setAvailableHoverTypes(prefs.available_hover_types);
1036 settings->setPrimaryHoverType(
1037 static_cast<WebSettings::HoverType>(prefs.primary_hover_type));
1038 settings->setDeviceSupportsTouch(prefs.device_supports_touch);
1039 settings->setDeviceSupportsMouse(prefs.device_supports_mouse);
1040 settings->setEnableTouchAdjustment(prefs.touch_adjustment_enabled);
1041 settings->setMultiTargetTapNotificationEnabled(
1042 switches::IsLinkDisambiguationPopupEnabled());
1044 WebRuntimeFeatures::enableImageColorProfiles(
1045 prefs.image_color_profiles_enabled);
1046 settings->setShouldRespectImageOrientation(
1047 prefs.should_respect_image_orientation);
1049 settings->setUnsafePluginPastingEnabled(false);
1050 settings->setEditingBehavior(
1051 static_cast<WebSettings::EditingBehavior>(prefs.editing_behavior));
1053 settings->setSupportsMultipleWindows(prefs.supports_multiple_windows);
1055 // TODO(bokan): Remove once Blink side is gone.
1056 settings->setInvertViewportScrollOrder(true);
1058 settings->setViewportEnabled(prefs.viewport_enabled);
1059 settings->setLoadWithOverviewMode(prefs.initialize_at_minimum_page_scale);
1060 settings->setViewportMetaEnabled(prefs.viewport_meta_enabled);
1061 settings->setMainFrameResizesAreOrientationChanges(
1062 prefs.main_frame_resizes_are_orientation_changes);
1064 settings->setSmartInsertDeleteEnabled(prefs.smart_insert_delete_enabled);
1066 settings->setSpatialNavigationEnabled(prefs.spatial_navigation_enabled);
1068 settings->setSelectionIncludesAltImageText(true);
1070 settings->setV8CacheOptions(
1071 static_cast<WebSettings::V8CacheOptions>(prefs.v8_cache_options));
1073 settings->setImageAnimationPolicy(
1074 static_cast<WebSettings::ImageAnimationPolicy>(prefs.animation_policy));
1076 // Needs to happen before setIgnoreVIewportTagScaleLimits below.
1077 web_view->setDefaultPageScaleLimits(
1078 prefs.default_minimum_page_scale_factor,
1079 prefs.default_maximum_page_scale_factor);
1081 #if defined(OS_ANDROID)
1082 settings->setAllowCustomScrollbarInMainFrame(false);
1083 settings->setTextAutosizingEnabled(prefs.text_autosizing_enabled);
1084 settings->setAccessibilityFontScaleFactor(prefs.font_scale_factor);
1085 settings->setDeviceScaleAdjustment(prefs.device_scale_adjustment);
1086 settings->setFullscreenSupported(prefs.fullscreen_supported);
1087 web_view->setIgnoreViewportTagScaleLimits(prefs.force_enable_zoom);
1088 settings->setAutoZoomFocusedNodeToLegibleScale(true);
1089 settings->setDoubleTapToZoomEnabled(prefs.double_tap_to_zoom_enabled);
1090 settings->setMediaControlsOverlayPlayButtonEnabled(true);
1091 settings->setMediaPlaybackRequiresUserGesture(
1092 prefs.user_gesture_required_for_media_playback);
1093 settings->setDefaultVideoPosterURL(
1094 base::ASCIIToUTF16(prefs.default_video_poster_url.spec()));
1095 settings->setSupportDeprecatedTargetDensityDPI(
1096 prefs.support_deprecated_target_density_dpi);
1097 settings->setUseLegacyBackgroundSizeShorthandBehavior(
1098 prefs.use_legacy_background_size_shorthand_behavior);
1099 settings->setWideViewportQuirkEnabled(prefs.wide_viewport_quirk);
1100 settings->setUseWideViewport(prefs.use_wide_viewport);
1101 settings->setForceZeroLayoutHeight(prefs.force_zero_layout_height);
1102 settings->setViewportMetaLayoutSizeQuirk(
1103 prefs.viewport_meta_layout_size_quirk);
1104 settings->setViewportMetaMergeContentQuirk(
1105 prefs.viewport_meta_merge_content_quirk);
1106 settings->setViewportMetaNonUserScalableQuirk(
1107 prefs.viewport_meta_non_user_scalable_quirk);
1108 settings->setViewportMetaZeroValuesQuirk(
1109 prefs.viewport_meta_zero_values_quirk);
1110 settings->setClobberUserAgentInitialScaleQuirk(
1111 prefs.clobber_user_agent_initial_scale_quirk);
1112 settings->setIgnoreMainFrameOverflowHiddenQuirk(
1113 prefs.ignore_main_frame_overflow_hidden_quirk);
1114 settings->setReportScreenSizeInPhysicalPixelsQuirk(
1115 prefs.report_screen_size_in_physical_pixels_quirk);
1116 settings->setPreferHiddenVolumeControls(true);
1117 settings->setMainFrameClipsContent(!prefs.record_whole_document);
1118 settings->setShrinksViewportContentToFit(true);
1119 settings->setUseMobileViewportStyle(true);
1120 settings->setAutoplayExperimentMode(
1121 blink::WebString::fromUTF8(prefs.autoplay_experiment_mode));
1122 #endif
1124 WebNetworkStateNotifier::setOnLine(prefs.is_online);
1125 WebNetworkStateNotifier::setWebConnection(
1126 NetConnectionTypeToWebConnectionType(prefs.net_info_connection_type),
1127 prefs.net_info_max_bandwidth_mbps);
1129 settings->setPinchOverlayScrollbarThickness(
1130 prefs.pinch_overlay_scrollbar_thickness);
1131 settings->setUseSolidColorScrollbars(prefs.use_solid_color_scrollbars);
1133 settings->setShowContextMenuOnMouseUp(prefs.context_menu_on_mouse_up);
1135 #if defined(OS_MACOSX)
1136 settings->setDoubleTapToZoomEnabled(true);
1137 web_view->setMaximumLegibleScale(prefs.default_maximum_page_scale_factor);
1138 #endif
1140 #if !defined(OS_ANDROID) && !defined(OS_MACOSX)
1141 // On platforms where the pinch viewport and the layout viewport can
1142 // both show scrollbars, hide pinch scrollbars when we are near minimum
1143 // page scale. (See http://crbug.com/446411 and http://crbug.com/515746.)
1144 settings->setHidePinchScrollbarsNearMinScale(true);
1145 #endif
1148 /*static*/
1149 RenderViewImpl* RenderViewImpl::Create(CompositorDependencies* compositor_deps,
1150 const ViewMsg_New_Params& params,
1151 bool was_created_by_renderer) {
1152 DCHECK(params.view_id != MSG_ROUTING_NONE);
1153 RenderViewImpl* render_view = NULL;
1154 if (g_create_render_view_impl)
1155 render_view = g_create_render_view_impl(compositor_deps, params);
1156 else
1157 render_view = new RenderViewImpl(compositor_deps, params);
1159 render_view->Initialize(params, was_created_by_renderer);
1160 return render_view;
1163 // static
1164 void RenderViewImpl::InstallCreateHook(RenderViewImpl* (
1165 *create_render_view_impl)(CompositorDependencies* compositor_deps,
1166 const ViewMsg_New_Params&)) {
1167 CHECK(!g_create_render_view_impl);
1168 g_create_render_view_impl = create_render_view_impl;
1171 void RenderViewImpl::AddObserver(RenderViewObserver* observer) {
1172 observers_.AddObserver(observer);
1175 void RenderViewImpl::RemoveObserver(RenderViewObserver* observer) {
1176 observer->RenderViewGone();
1177 observers_.RemoveObserver(observer);
1180 blink::WebView* RenderViewImpl::webview() const {
1181 return static_cast<blink::WebView*>(webwidget());
1184 #if defined(ENABLE_PLUGINS)
1185 void RenderViewImpl::PepperInstanceCreated(
1186 PepperPluginInstanceImpl* instance) {
1187 active_pepper_instances_.insert(instance);
1189 RenderFrameImpl* const render_frame = instance->render_frame();
1190 render_frame->Send(
1191 new FrameHostMsg_PepperInstanceCreated(render_frame->GetRoutingID()));
1194 void RenderViewImpl::PepperInstanceDeleted(
1195 PepperPluginInstanceImpl* instance) {
1196 active_pepper_instances_.erase(instance);
1198 if (pepper_last_mouse_event_target_ == instance)
1199 pepper_last_mouse_event_target_ = NULL;
1200 if (focused_pepper_plugin_ == instance)
1201 PepperFocusChanged(instance, false);
1203 RenderFrameImpl* const render_frame = instance->render_frame();
1204 if (render_frame)
1205 render_frame->Send(
1206 new FrameHostMsg_PepperInstanceDeleted(render_frame->GetRoutingID()));
1209 void RenderViewImpl::PepperFocusChanged(PepperPluginInstanceImpl* instance,
1210 bool focused) {
1211 if (focused)
1212 focused_pepper_plugin_ = instance;
1213 else if (focused_pepper_plugin_ == instance)
1214 focused_pepper_plugin_ = NULL;
1216 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
1217 UpdateSelectionBounds();
1220 void RenderViewImpl::RegisterPluginDelegate(WebPluginDelegateProxy* delegate) {
1221 plugin_delegates_.insert(delegate);
1222 // If the renderer is visible, set initial visibility and focus state.
1223 if (!is_hidden()) {
1224 #if defined(OS_MACOSX)
1225 delegate->SetContainerVisibility(true);
1226 if (webview() && webview()->isActive())
1227 delegate->SetWindowFocus(true);
1228 #endif
1230 // Plugins start assuming the content has focus (so that they work in
1231 // environments where RenderView isn't hosting them), so we always have to
1232 // set the initial state. See webplugin_delegate_impl.h for details.
1233 delegate->SetContentAreaFocus(has_focus());
1236 void RenderViewImpl::UnregisterPluginDelegate(
1237 WebPluginDelegateProxy* delegate) {
1238 plugin_delegates_.erase(delegate);
1241 #if defined(OS_WIN)
1242 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1243 if (focused)
1244 focused_plugin_id_ = plugin_id;
1245 else
1246 focused_plugin_id_ = -1;
1248 #endif
1250 #if defined(OS_MACOSX)
1251 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1252 Send(new ViewHostMsg_PluginFocusChanged(routing_id(), focused, plugin_id));
1255 void RenderViewImpl::OnGetRenderedText() {
1256 if (!webview())
1257 return;
1258 // Get rendered text from WebLocalFrame.
1259 // TODO: Currently IPC truncates any data that has a
1260 // size > kMaximumMessageSize. May be split the text into smaller chunks and
1261 // send back using multiple IPC. See http://crbug.com/393444.
1262 static const size_t kMaximumMessageSize = 8 * 1024 * 1024;
1263 std::string text = webview()->mainFrame()->contentAsText(
1264 kMaximumMessageSize).utf8();
1266 Send(new ViewMsg_GetRenderedTextCompleted(routing_id(), text));
1269 void RenderViewImpl::StartPluginIme() {
1270 IPC::Message* msg = new ViewHostMsg_StartPluginIme(routing_id());
1271 // This message can be sent during event-handling, and needs to be delivered
1272 // within that context.
1273 msg->set_unblock(true);
1274 Send(msg);
1276 #endif // defined(OS_MACOSX)
1278 #endif // ENABLE_PLUGINS
1280 void RenderViewImpl::TransferActiveWheelFlingAnimation(
1281 const blink::WebActiveWheelFlingParameters& params) {
1282 if (webview())
1283 webview()->transferActiveWheelFlingAnimation(params);
1286 bool RenderViewImpl::HasIMETextFocus() {
1287 return GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE;
1290 bool RenderViewImpl::OnMessageReceived(const IPC::Message& message) {
1291 WebFrame* main_frame = webview() ? webview()->mainFrame() : NULL;
1292 if (main_frame && main_frame->isWebLocalFrame())
1293 GetContentClient()->SetActiveURL(main_frame->document().url());
1295 base::ObserverListBase<RenderViewObserver>::Iterator it(&observers_);
1296 RenderViewObserver* observer;
1297 while ((observer = it.GetNext()) != NULL)
1298 if (observer->OnMessageReceived(message))
1299 return true;
1301 bool handled = true;
1302 IPC_BEGIN_MESSAGE_MAP(RenderViewImpl, message)
1303 IPC_MESSAGE_HANDLER(InputMsg_ExecuteEditCommand, OnExecuteEditCommand)
1304 IPC_MESSAGE_HANDLER(InputMsg_MoveCaret, OnMoveCaret)
1305 IPC_MESSAGE_HANDLER(InputMsg_ScrollFocusedEditableNodeIntoRect,
1306 OnScrollFocusedEditableNodeIntoRect)
1307 IPC_MESSAGE_HANDLER(InputMsg_SetEditCommandsForNextKeyEvent,
1308 OnSetEditCommandsForNextKeyEvent)
1309 IPC_MESSAGE_HANDLER(ViewMsg_CopyImageAt, OnCopyImageAt)
1310 IPC_MESSAGE_HANDLER(ViewMsg_SaveImageAt, OnSaveImageAt)
1311 IPC_MESSAGE_HANDLER(ViewMsg_Find, OnFind)
1312 IPC_MESSAGE_HANDLER(ViewMsg_StopFinding, OnStopFinding)
1313 IPC_MESSAGE_HANDLER(ViewMsg_ResetPageScale, OnResetPageScale)
1314 IPC_MESSAGE_HANDLER(ViewMsg_Zoom, OnZoom)
1315 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForLoadingURL,
1316 OnSetZoomLevelForLoadingURL)
1317 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForView,
1318 OnSetZoomLevelForView)
1319 IPC_MESSAGE_HANDLER(ViewMsg_SetPageEncoding, OnSetPageEncoding)
1320 IPC_MESSAGE_HANDLER(ViewMsg_ResetPageEncodingToDefault,
1321 OnResetPageEncodingToDefault)
1322 IPC_MESSAGE_HANDLER(DragMsg_TargetDragEnter, OnDragTargetDragEnter)
1323 IPC_MESSAGE_HANDLER(DragMsg_TargetDragOver, OnDragTargetDragOver)
1324 IPC_MESSAGE_HANDLER(DragMsg_TargetDragLeave, OnDragTargetDragLeave)
1325 IPC_MESSAGE_HANDLER(DragMsg_TargetDrop, OnDragTargetDrop)
1326 IPC_MESSAGE_HANDLER(DragMsg_SourceEnded, OnDragSourceEnded)
1327 IPC_MESSAGE_HANDLER(DragMsg_SourceSystemDragEnded,
1328 OnDragSourceSystemDragEnded)
1329 IPC_MESSAGE_HANDLER(ViewMsg_AllowBindings, OnAllowBindings)
1330 IPC_MESSAGE_HANDLER(ViewMsg_SetInitialFocus, OnSetInitialFocus)
1331 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTargetURL_ACK, OnUpdateTargetURLAck)
1332 IPC_MESSAGE_HANDLER(ViewMsg_UpdateWebPreferences, OnUpdateWebPreferences)
1333 IPC_MESSAGE_HANDLER(ViewMsg_EnumerateDirectoryResponse,
1334 OnEnumerateDirectoryResponse)
1335 IPC_MESSAGE_HANDLER(ViewMsg_RunFileChooserResponse, OnFileChooserResponse)
1336 IPC_MESSAGE_HANDLER(ViewMsg_SuppressDialogsUntilSwapOut,
1337 OnSuppressDialogsUntilSwapOut)
1338 IPC_MESSAGE_HANDLER(ViewMsg_ClosePage, OnClosePage)
1339 IPC_MESSAGE_HANDLER(ViewMsg_ThemeChanged, OnThemeChanged)
1340 IPC_MESSAGE_HANDLER(ViewMsg_MoveOrResizeStarted, OnMoveOrResizeStarted)
1341 IPC_MESSAGE_HANDLER(ViewMsg_ClearFocusedElement, OnClearFocusedElement)
1342 IPC_MESSAGE_HANDLER(ViewMsg_SetBackgroundOpaque, OnSetBackgroundOpaque)
1343 IPC_MESSAGE_HANDLER(ViewMsg_EnablePreferredSizeChangedMode,
1344 OnEnablePreferredSizeChangedMode)
1345 IPC_MESSAGE_HANDLER(ViewMsg_EnableAutoResize, OnEnableAutoResize)
1346 IPC_MESSAGE_HANDLER(ViewMsg_DisableAutoResize, OnDisableAutoResize)
1347 IPC_MESSAGE_HANDLER(ViewMsg_DisableScrollbarsForSmallWindows,
1348 OnDisableScrollbarsForSmallWindows)
1349 IPC_MESSAGE_HANDLER(ViewMsg_SetRendererPrefs, OnSetRendererPrefs)
1350 IPC_MESSAGE_HANDLER(ViewMsg_MediaPlayerActionAt, OnMediaPlayerActionAt)
1351 IPC_MESSAGE_HANDLER(ViewMsg_PluginActionAt, OnPluginActionAt)
1352 IPC_MESSAGE_HANDLER(ViewMsg_SetActive, OnSetActive)
1353 IPC_MESSAGE_HANDLER(
1354 ViewMsg_GetSerializedHtmlDataForCurrentPageWithLocalLinks,
1355 OnGetSerializedHtmlDataForCurrentPageWithLocalLinks)
1356 IPC_MESSAGE_HANDLER(ViewMsg_ShowContextMenu, OnShowContextMenu)
1357 // TODO(viettrungluu): Move to a separate message filter.
1358 IPC_MESSAGE_HANDLER(ViewMsg_SetHistoryOffsetAndLength,
1359 OnSetHistoryOffsetAndLength)
1360 IPC_MESSAGE_HANDLER(ViewMsg_EnableViewSourceMode, OnEnableViewSourceMode)
1361 IPC_MESSAGE_HANDLER(ViewMsg_ReleaseDisambiguationPopupBitmap,
1362 OnReleaseDisambiguationPopupBitmap)
1363 IPC_MESSAGE_HANDLER(ViewMsg_ForceRedraw, OnForceRedraw)
1364 IPC_MESSAGE_HANDLER(ViewMsg_SelectWordAroundCaret, OnSelectWordAroundCaret)
1365 #if defined(OS_ANDROID)
1366 IPC_MESSAGE_HANDLER(InputMsg_ActivateNearestFindResult,
1367 OnActivateNearestFindResult)
1368 IPC_MESSAGE_HANDLER(ViewMsg_FindMatchRects, OnFindMatchRects)
1369 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTopControlsState,
1370 OnUpdateTopControlsState)
1371 IPC_MESSAGE_HANDLER(ViewMsg_ExtractSmartClipData, OnExtractSmartClipData)
1372 #elif defined(OS_MACOSX)
1373 IPC_MESSAGE_HANDLER(ViewMsg_GetRenderedText,
1374 OnGetRenderedText)
1375 IPC_MESSAGE_HANDLER(ViewMsg_PluginImeCompositionCompleted,
1376 OnPluginImeCompositionCompleted)
1377 IPC_MESSAGE_HANDLER(ViewMsg_Close, OnClose)
1378 IPC_MESSAGE_HANDLER(ViewMsg_SetInLiveResize, OnSetInLiveResize)
1379 IPC_MESSAGE_HANDLER(ViewMsg_SetWindowVisibility, OnSetWindowVisibility)
1380 IPC_MESSAGE_HANDLER(ViewMsg_WindowFrameChanged, OnWindowFrameChanged)
1381 #endif
1382 // Adding a new message? Add platform independent ones first, then put the
1383 // platform specific ones at the end.
1385 // Have the super handle all other messages.
1386 IPC_MESSAGE_UNHANDLED(handled = RenderWidget::OnMessageReceived(message))
1387 IPC_END_MESSAGE_MAP()
1389 return handled;
1392 void RenderViewImpl::OnSelectWordAroundCaret() {
1393 if (!webview())
1394 return;
1396 handling_input_event_ = true;
1397 webview()->focusedFrame()->selectWordAroundCaret();
1398 handling_input_event_ = false;
1401 void RenderViewImpl::OnCopyImageAt(int x, int y) {
1402 webview()->copyImageAt(WebPoint(x, y));
1405 void RenderViewImpl::OnSaveImageAt(int x, int y) {
1406 webview()->saveImageAt(WebPoint(x, y));
1409 void RenderViewImpl::OnUpdateTargetURLAck() {
1410 // Check if there is a targeturl waiting to be sent.
1411 if (target_url_status_ == TARGET_PENDING)
1412 Send(new ViewHostMsg_UpdateTargetURL(routing_id_, pending_target_url_));
1414 target_url_status_ = TARGET_NONE;
1417 void RenderViewImpl::OnExecuteEditCommand(const std::string& name,
1418 const std::string& value) {
1419 if (!webview() || !webview()->focusedFrame())
1420 return;
1422 webview()->focusedFrame()->executeCommand(
1423 WebString::fromUTF8(name), WebString::fromUTF8(value));
1426 void RenderViewImpl::OnMoveCaret(const gfx::Point& point) {
1427 if (!webview())
1428 return;
1430 Send(new InputHostMsg_MoveCaret_ACK(routing_id_));
1432 webview()->focusedFrame()->moveCaretSelection(point);
1435 void RenderViewImpl::OnScrollFocusedEditableNodeIntoRect(
1436 const gfx::Rect& rect) {
1437 if (has_scrolled_focused_editable_node_into_rect_ &&
1438 rect == rect_for_scrolled_focused_editable_node_) {
1439 FocusChangeComplete();
1440 return;
1443 blink::WebElement element = GetFocusedElement();
1444 bool will_animate = false;
1445 if (!element.isNull() && element.isEditable()) {
1446 rect_for_scrolled_focused_editable_node_ = rect;
1447 has_scrolled_focused_editable_node_into_rect_ = true;
1448 will_animate = webview()->scrollFocusedNodeIntoRect(rect);
1451 if (!will_animate)
1452 FocusChangeComplete();
1455 void RenderViewImpl::OnSetEditCommandsForNextKeyEvent(
1456 const EditCommands& edit_commands) {
1457 edit_commands_ = edit_commands;
1460 void RenderViewImpl::OnSetHistoryOffsetAndLength(int history_offset,
1461 int history_length) {
1462 DCHECK_GE(history_offset, -1);
1463 DCHECK_GE(history_length, 0);
1465 history_list_offset_ = history_offset;
1466 history_list_length_ = history_length;
1469 void RenderViewImpl::OnSetInitialFocus(bool reverse) {
1470 if (!webview())
1471 return;
1472 webview()->setInitialFocus(reverse);
1475 #if defined(OS_MACOSX)
1476 void RenderViewImpl::OnSetInLiveResize(bool in_live_resize) {
1477 if (!webview())
1478 return;
1479 if (in_live_resize)
1480 webview()->willStartLiveResize();
1481 else
1482 webview()->willEndLiveResize();
1484 #endif
1486 ///////////////////////////////////////////////////////////////////////////////
1488 void RenderViewImpl::SendUpdateState() {
1489 HistoryEntry* entry = history_controller_->GetCurrentEntry();
1490 if (!entry)
1491 return;
1493 // Don't send state updates for kSwappedOutURL.
1494 if (entry->root().urlString() == WebString::fromUTF8(kSwappedOutURL))
1495 return;
1497 Send(new ViewHostMsg_UpdateState(
1498 routing_id_, page_id_, HistoryEntryToPageState(entry)));
1501 void RenderViewImpl::ApplyWebPreferencesInternal(
1502 const WebPreferences& prefs,
1503 blink::WebView* web_view,
1504 CompositorDependencies* compositor_deps) {
1505 ApplyWebPreferences(prefs, web_view);
1506 #if defined(OS_MACOSX) && !defined(OS_IOS)
1507 DCHECK(compositor_deps);
1508 bool is_elastic_overscroll_enabled =
1509 compositor_deps->IsElasticOverscrollEnabled();
1510 web_view->settings()->setReportWheelOverscroll(is_elastic_overscroll_enabled);
1511 #endif
1514 bool RenderViewImpl::SendAndRunNestedMessageLoop(IPC::SyncMessage* message) {
1515 // Before WebKit asks us to show an alert (etc.), it takes care of doing the
1516 // equivalent of WebView::willEnterModalLoop. In the case of showModalDialog
1517 // it is particularly important that we do not call willEnterModalLoop as
1518 // that would defer resource loads for the dialog itself.
1519 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
1520 RenderThreadImpl::current()->DoNotNotifyWebKitOfModalLoop();
1522 message->EnableMessagePumping(); // Runs a nested message loop.
1523 return Send(message);
1526 void RenderViewImpl::OnForceRedraw(int id) {
1527 ui::LatencyInfo latency_info;
1528 if (id) {
1529 latency_info.AddLatencyNumber(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
1531 id);
1533 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1534 if (RenderWidgetCompositor* rwc = compositor()) {
1535 latency_info_swap_promise_monitor =
1536 rwc->CreateLatencyInfoSwapPromiseMonitor(&latency_info).Pass();
1538 ScheduleCompositeWithForcedRedraw();
1541 // blink::WebViewClient ------------------------------------------------------
1543 WebView* RenderViewImpl::createView(WebLocalFrame* creator,
1544 const WebURLRequest& request,
1545 const WebWindowFeatures& features,
1546 const WebString& frame_name,
1547 WebNavigationPolicy policy,
1548 bool suppress_opener) {
1549 ViewHostMsg_CreateWindow_Params params;
1550 params.opener_id = routing_id_;
1551 params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
1552 if (GetContentClient()->renderer()->AllowPopup())
1553 params.user_gesture = true;
1554 params.window_container_type = WindowFeaturesToContainerType(features);
1555 params.session_storage_namespace_id = session_storage_namespace_id_;
1556 if (frame_name != "_blank")
1557 params.frame_name = base::UTF16ToUTF8(base::StringPiece16(frame_name));
1558 params.opener_render_frame_id =
1559 RenderFrameImpl::FromWebFrame(creator)->GetRoutingID();
1560 params.opener_url = creator->document().url();
1562 // The browser process uses the top frame's URL for a content settings check
1563 // to determine whether the popup is allowed. If the top frame is remote,
1564 // its URL is not available, so use its replicated origin instead.
1566 // TODO(alexmos): This works fine for regular origins but may break path
1567 // matching for file URLs with OOP subframes that open popups. This should
1568 // be fixed by either moving this lookup to the browser process or removing
1569 // path-based matching for file URLs from content settings. See
1570 // https://crbug.com/466297.
1571 if (creator->top()->isWebLocalFrame()) {
1572 params.opener_top_level_frame_url = creator->top()->document().url();
1573 } else {
1574 params.opener_top_level_frame_url =
1575 GURL(creator->top()->securityOrigin().toString());
1578 GURL security_url(creator->document().securityOrigin().toString());
1579 if (!security_url.is_valid())
1580 security_url = GURL();
1581 params.opener_security_origin = security_url;
1582 params.opener_suppressed = suppress_opener;
1583 params.disposition = NavigationPolicyToDisposition(policy);
1584 if (!request.isNull()) {
1585 params.target_url = request.url();
1586 params.referrer = GetReferrerFromRequest(creator, request);
1588 params.features = features;
1590 for (size_t i = 0; i < features.additionalFeatures.size(); ++i)
1591 params.additional_features.push_back(features.additionalFeatures[i]);
1593 int32 routing_id = MSG_ROUTING_NONE;
1594 int32 main_frame_routing_id = MSG_ROUTING_NONE;
1595 int32 surface_id = 0;
1596 int64 cloned_session_storage_namespace_id = 0;
1598 RenderThread::Get()->Send(new ViewHostMsg_CreateWindow(
1599 params, &routing_id, &main_frame_routing_id, &surface_id,
1600 &cloned_session_storage_namespace_id));
1601 if (routing_id == MSG_ROUTING_NONE)
1602 return NULL;
1604 WebUserGestureIndicator::consumeUserGesture();
1606 // While this view may be a background extension page, it can spawn a visible
1607 // render view. So we just assume that the new one is not another background
1608 // page instead of passing on our own value.
1609 // TODO(vangelis): Can we tell if the new view will be a background page?
1610 bool never_visible = false;
1612 ViewMsg_Resize_Params initial_size = ViewMsg_Resize_Params();
1613 initial_size.screen_info = screen_info_;
1615 // The initial hidden state for the RenderViewImpl here has to match what the
1616 // browser will eventually decide for the given disposition. Since we have to
1617 // return from this call synchronously, we just have to make our best guess
1618 // and rely on the browser sending a WasHidden / WasShown message if it
1619 // disagrees.
1620 ViewMsg_New_Params view_params;
1622 RenderFrameImpl* creator_frame = RenderFrameImpl::FromWebFrame(creator);
1623 view_params.opener_frame_route_id = creator_frame->GetRoutingID();
1624 DCHECK_EQ(routing_id_, creator_frame->render_view()->GetRoutingID());
1626 view_params.window_was_created_with_opener = true;
1627 view_params.renderer_preferences = renderer_preferences_;
1628 view_params.web_preferences = webkit_preferences_;
1629 view_params.view_id = routing_id;
1630 view_params.main_frame_routing_id = main_frame_routing_id;
1631 view_params.surface_id = surface_id;
1632 view_params.session_storage_namespace_id =
1633 cloned_session_storage_namespace_id;
1634 view_params.swapped_out = false;
1635 // WebCore will take care of setting the correct name.
1636 view_params.replicated_frame_state = FrameReplicationState();
1637 view_params.proxy_routing_id = MSG_ROUTING_NONE;
1638 view_params.hidden = (params.disposition == NEW_BACKGROUND_TAB);
1639 view_params.never_visible = never_visible;
1640 view_params.next_page_id = 1;
1641 view_params.initial_size = initial_size;
1642 view_params.enable_auto_resize = false;
1643 view_params.min_size = gfx::Size();
1644 view_params.max_size = gfx::Size();
1646 RenderViewImpl* view =
1647 RenderViewImpl::Create(compositor_deps_, view_params, true);
1648 view->opened_by_user_gesture_ = params.user_gesture;
1650 // Record whether the creator frame is trying to suppress the opener field.
1651 view->opener_suppressed_ = params.opener_suppressed;
1653 return view->webview();
1656 WebWidget* RenderViewImpl::createPopupMenu(blink::WebPopupType popup_type) {
1657 RenderWidget* widget = RenderWidget::Create(routing_id_, compositor_deps_,
1658 popup_type, screen_info_);
1659 if (!widget)
1660 return NULL;
1661 if (screen_metrics_emulator_) {
1662 widget->SetPopupOriginAdjustmentsForEmulation(
1663 screen_metrics_emulator_.get());
1665 return widget->webwidget();
1668 WebStorageNamespace* RenderViewImpl::createSessionStorageNamespace() {
1669 CHECK(session_storage_namespace_id_ != kInvalidSessionStorageNamespaceId);
1670 return new WebStorageNamespaceImpl(session_storage_namespace_id_);
1673 void RenderViewImpl::printPage(WebLocalFrame* frame) {
1674 FOR_EACH_OBSERVER(RenderViewObserver, observers_,
1675 PrintPage(frame, handling_input_event_));
1678 void RenderViewImpl::saveImageFromDataURL(const blink::WebString& data_url) {
1679 // Note: We should basically send GURL but we use size-limited string instead
1680 // in order to send a larger data url to save a image for <canvas> or <img>.
1681 if (data_url.length() < kMaxLengthOfDataURLString)
1682 Send(new ViewHostMsg_SaveImageFromDataURL(
1683 routing_id_, GetMainRenderFrame()->GetRoutingID(), data_url.utf8()));
1686 bool RenderViewImpl::enumerateChosenDirectory(
1687 const WebString& path,
1688 WebFileChooserCompletion* chooser_completion) {
1689 int id = enumeration_completion_id_++;
1690 enumeration_completions_[id] = chooser_completion;
1691 return Send(new ViewHostMsg_EnumerateDirectory(
1692 routing_id_,
1694 base::FilePath::FromUTF16Unsafe(path)));
1697 void RenderViewImpl::FrameDidStartLoading(WebFrame* frame) {
1698 DCHECK_GE(frames_in_progress_, 0);
1699 if (frames_in_progress_ == 0)
1700 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStartLoading());
1701 frames_in_progress_++;
1704 void RenderViewImpl::FrameDidStopLoading(WebFrame* frame) {
1705 // TODO(japhet): This should be a DCHECK, but the pdf plugin sometimes
1706 // calls DidStopLoading() without a matching DidStartLoading().
1707 if (frames_in_progress_ == 0)
1708 return;
1709 frames_in_progress_--;
1710 if (frames_in_progress_ == 0) {
1711 DidStopLoadingIcons();
1712 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStopLoading());
1716 void RenderViewImpl::SetZoomLevel(double zoom_level) {
1717 webview()->setZoomLevel(zoom_level);
1718 FOR_EACH_OBSERVER(RenderViewObserver, observers_, OnZoomLevelChanged());
1721 void RenderViewImpl::didCancelCompositionOnSelectionChange() {
1722 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
1725 bool RenderViewImpl::handleCurrentKeyboardEvent() {
1726 if (edit_commands_.empty())
1727 return false;
1729 WebFrame* frame = webview()->focusedFrame();
1730 if (!frame)
1731 return false;
1733 EditCommands::iterator it = edit_commands_.begin();
1734 EditCommands::iterator end = edit_commands_.end();
1736 bool did_execute_command = false;
1737 for (; it != end; ++it) {
1738 // In gtk and cocoa, it's possible to bind multiple edit commands to one
1739 // key (but it's the exception). Once one edit command is not executed, it
1740 // seems safest to not execute the rest.
1741 if (!frame->executeCommand(WebString::fromUTF8(it->name),
1742 WebString::fromUTF8(it->value),
1743 GetFocusedElement()))
1744 break;
1745 did_execute_command = true;
1748 return did_execute_command;
1751 bool RenderViewImpl::runFileChooser(
1752 const blink::WebFileChooserParams& params,
1753 WebFileChooserCompletion* chooser_completion) {
1754 // Do not open the file dialog in a hidden RenderView.
1755 if (is_hidden())
1756 return false;
1757 FileChooserParams ipc_params;
1758 if (params.directory)
1759 ipc_params.mode = FileChooserParams::UploadFolder;
1760 else if (params.multiSelect)
1761 ipc_params.mode = FileChooserParams::OpenMultiple;
1762 else if (params.saveAs)
1763 ipc_params.mode = FileChooserParams::Save;
1764 else
1765 ipc_params.mode = FileChooserParams::Open;
1766 ipc_params.title = params.title;
1767 ipc_params.default_file_name =
1768 base::FilePath::FromUTF16Unsafe(params.initialValue).BaseName();
1769 ipc_params.accept_types.reserve(params.acceptTypes.size());
1770 for (size_t i = 0; i < params.acceptTypes.size(); ++i)
1771 ipc_params.accept_types.push_back(params.acceptTypes[i]);
1772 ipc_params.need_local_path = params.needLocalPath;
1773 #if defined(OS_ANDROID)
1774 ipc_params.capture = params.useMediaCapture;
1775 #endif
1777 return ScheduleFileChooser(ipc_params, chooser_completion);
1780 void RenderViewImpl::SetValidationMessageDirection(
1781 base::string16* wrapped_main_text,
1782 blink::WebTextDirection main_text_hint,
1783 base::string16* wrapped_sub_text,
1784 blink::WebTextDirection sub_text_hint) {
1785 if (main_text_hint == blink::WebTextDirectionLeftToRight) {
1786 *wrapped_main_text =
1787 base::i18n::GetDisplayStringInLTRDirectionality(*wrapped_main_text);
1788 } else if (main_text_hint == blink::WebTextDirectionRightToLeft &&
1789 !base::i18n::IsRTL()) {
1790 base::i18n::WrapStringWithRTLFormatting(wrapped_main_text);
1793 if (!wrapped_sub_text->empty()) {
1794 if (sub_text_hint == blink::WebTextDirectionLeftToRight) {
1795 *wrapped_sub_text =
1796 base::i18n::GetDisplayStringInLTRDirectionality(*wrapped_sub_text);
1797 } else if (sub_text_hint == blink::WebTextDirectionRightToLeft) {
1798 base::i18n::WrapStringWithRTLFormatting(wrapped_sub_text);
1803 void RenderViewImpl::showValidationMessage(
1804 const blink::WebRect& anchor_in_root_view,
1805 const blink::WebString& main_text,
1806 blink::WebTextDirection main_text_hint,
1807 const blink::WebString& sub_text,
1808 blink::WebTextDirection sub_text_hint) {
1809 base::string16 wrapped_main_text = main_text;
1810 base::string16 wrapped_sub_text = sub_text;
1812 SetValidationMessageDirection(
1813 &wrapped_main_text, main_text_hint, &wrapped_sub_text, sub_text_hint);
1815 Send(new ViewHostMsg_ShowValidationMessage(
1816 routing_id(), AdjustValidationMessageAnchor(anchor_in_root_view),
1817 wrapped_main_text, wrapped_sub_text));
1820 void RenderViewImpl::hideValidationMessage() {
1821 Send(new ViewHostMsg_HideValidationMessage(routing_id()));
1824 void RenderViewImpl::moveValidationMessage(
1825 const blink::WebRect& anchor_in_root_view) {
1826 Send(new ViewHostMsg_MoveValidationMessage(
1827 routing_id(), AdjustValidationMessageAnchor(anchor_in_root_view)));
1830 void RenderViewImpl::setStatusText(const WebString& text) {
1833 void RenderViewImpl::UpdateTargetURL(const GURL& url,
1834 const GURL& fallback_url) {
1835 GURL latest_url = url.is_empty() ? fallback_url : url;
1836 if (latest_url == target_url_)
1837 return;
1839 // Tell the browser to display a destination link.
1840 if (target_url_status_ == TARGET_INFLIGHT ||
1841 target_url_status_ == TARGET_PENDING) {
1842 // If we have a request in-flight, save the URL to be sent when we
1843 // receive an ACK to the in-flight request. We can happily overwrite
1844 // any existing pending sends.
1845 pending_target_url_ = latest_url;
1846 target_url_status_ = TARGET_PENDING;
1847 } else {
1848 // URLs larger than |MaxURLChars()| cannot be sent through IPC -
1849 // see |ParamTraits<GURL>|.
1850 if (latest_url.possibly_invalid_spec().size() > GetMaxURLChars())
1851 latest_url = GURL();
1852 Send(new ViewHostMsg_UpdateTargetURL(routing_id_, latest_url));
1853 target_url_ = latest_url;
1854 target_url_status_ = TARGET_INFLIGHT;
1858 gfx::RectF RenderViewImpl::ClientRectToPhysicalWindowRect(
1859 const gfx::RectF& rect) const {
1860 gfx::RectF window_rect = rect;
1861 window_rect.Scale(device_scale_factor_ * webview()->pageScaleFactor());
1862 return window_rect;
1865 void RenderViewImpl::StartNavStateSyncTimerIfNecessary() {
1866 int delay;
1867 if (send_content_state_immediately_)
1868 delay = 0;
1869 else if (is_hidden())
1870 delay = kDelaySecondsForContentStateSyncHidden;
1871 else
1872 delay = kDelaySecondsForContentStateSync;
1874 if (nav_state_sync_timer_.IsRunning()) {
1875 // The timer is already running. If the delay of the timer maches the amount
1876 // we want to delay by, then return. Otherwise stop the timer so that it
1877 // gets started with the right delay.
1878 if (nav_state_sync_timer_.GetCurrentDelay().InSeconds() == delay)
1879 return;
1880 nav_state_sync_timer_.Stop();
1883 nav_state_sync_timer_.Start(FROM_HERE, TimeDelta::FromSeconds(delay), this,
1884 &RenderViewImpl::SendUpdateState);
1887 void RenderViewImpl::setMouseOverURL(const WebURL& url) {
1888 mouse_over_url_ = GURL(url);
1889 UpdateTargetURL(mouse_over_url_, focus_url_);
1892 void RenderViewImpl::setKeyboardFocusURL(const WebURL& url) {
1893 focus_url_ = GURL(url);
1894 UpdateTargetURL(focus_url_, mouse_over_url_);
1897 void RenderViewImpl::startDragging(WebLocalFrame* frame,
1898 const WebDragData& data,
1899 WebDragOperationsMask mask,
1900 const WebImage& image,
1901 const WebPoint& webImageOffset) {
1902 DropData drop_data(DropDataBuilder::Build(data));
1903 drop_data.referrer_policy = frame->document().referrerPolicy();
1904 gfx::Vector2d imageOffset(webImageOffset.x, webImageOffset.y);
1905 Send(new DragHostMsg_StartDragging(routing_id_,
1906 drop_data,
1907 mask,
1908 image.getSkBitmap(),
1909 imageOffset,
1910 possible_drag_event_info_));
1913 bool RenderViewImpl::acceptsLoadDrops() {
1914 return renderer_preferences_.can_accept_load_drops;
1917 void RenderViewImpl::focusNext() {
1918 Send(new ViewHostMsg_TakeFocus(routing_id_, false));
1921 void RenderViewImpl::focusPrevious() {
1922 Send(new ViewHostMsg_TakeFocus(routing_id_, true));
1925 // TODO(esprehn): Blink only ever passes Elements, this should take WebElement.
1926 void RenderViewImpl::focusedNodeChanged(const WebNode& fromNode,
1927 const WebNode& toNode) {
1928 has_scrolled_focused_editable_node_into_rect_ = false;
1930 gfx::Rect node_bounds;
1931 bool is_editable = false;
1932 if (!toNode.isNull() && toNode.isElementNode()) {
1933 WebElement element = const_cast<WebNode&>(toNode).to<WebElement>();
1934 node_bounds = gfx::Rect(element.boundsInViewportSpace());
1935 is_editable = element.isEditable();
1937 Send(new ViewHostMsg_FocusedNodeChanged(routing_id_, is_editable,
1938 node_bounds));
1940 // TODO(estade): remove.
1941 FOR_EACH_OBSERVER(RenderViewObserver, observers_, FocusedNodeChanged(toNode));
1943 RenderFrameImpl* previous_frame = nullptr;
1944 if (!fromNode.isNull())
1945 previous_frame = RenderFrameImpl::FromWebFrame(fromNode.document().frame());
1946 RenderFrameImpl* new_frame = nullptr;
1947 if (!toNode.isNull())
1948 new_frame = RenderFrameImpl::FromWebFrame(toNode.document().frame());
1950 if (previous_frame && previous_frame != new_frame)
1951 previous_frame->FocusedNodeChanged(WebNode());
1952 if (new_frame)
1953 new_frame->FocusedNodeChanged(toNode);
1955 // TODO(dmazzoni): remove once there's a separate a11y tree per frame.
1956 if (main_render_frame_)
1957 main_render_frame_->FocusedNodeChangedForAccessibility(toNode);
1960 void RenderViewImpl::didUpdateLayout() {
1961 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidUpdateLayout());
1963 // We don't always want to set up a timer, only if we've been put in that
1964 // mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
1965 // message.
1966 if (!send_preferred_size_changes_ || !webview())
1967 return;
1969 if (check_preferred_size_timer_.IsRunning())
1970 return;
1971 check_preferred_size_timer_.Start(FROM_HERE,
1972 TimeDelta::FromMilliseconds(0), this,
1973 &RenderViewImpl::CheckPreferredSize);
1976 void RenderViewImpl::navigateBackForwardSoon(int offset) {
1977 Send(new ViewHostMsg_GoToEntryAtOffset(routing_id_, offset));
1980 int RenderViewImpl::historyBackListCount() {
1981 return history_list_offset_ < 0 ? 0 : history_list_offset_;
1984 int RenderViewImpl::historyForwardListCount() {
1985 return history_list_length_ - historyBackListCount() - 1;
1988 // blink::WebWidgetClient ----------------------------------------------------
1990 void RenderViewImpl::didFocus() {
1991 // TODO(jcivelli): when https://bugs.webkit.org/show_bug.cgi?id=33389 is fixed
1992 // we won't have to test for user gesture anymore and we can
1993 // move that code back to render_widget.cc
1994 if (WebUserGestureIndicator::isProcessingUserGesture() &&
1995 !RenderThreadImpl::current()->layout_test_mode()) {
1996 Send(new ViewHostMsg_Focus(routing_id_));
2000 void RenderViewImpl::didBlur() {
2001 // TODO(jcivelli): see TODO above in didFocus().
2002 if (WebUserGestureIndicator::isProcessingUserGesture() &&
2003 !RenderThreadImpl::current()->layout_test_mode()) {
2004 Send(new ViewHostMsg_Blur(routing_id_));
2008 // We are supposed to get a single call to Show for a newly created RenderView
2009 // that was created via RenderViewImpl::CreateWebView. So, we wait until this
2010 // point to dispatch the ShowView message.
2012 // This method provides us with the information about how to display the newly
2013 // created RenderView (i.e., as a blocked popup or as a new tab).
2015 void RenderViewImpl::show(WebNavigationPolicy policy) {
2016 if (did_show_) {
2017 // When supports_multiple_windows is disabled, popups are reusing
2018 // the same view. In some scenarios, this makes WebKit to call show() twice.
2019 if (webkit_preferences_.supports_multiple_windows)
2020 NOTREACHED() << "received extraneous Show call";
2021 return;
2023 did_show_ = true;
2025 DCHECK(opener_id_ != MSG_ROUTING_NONE);
2027 // NOTE: initial_rect_ may still have its default values at this point, but
2028 // that's okay. It'll be ignored if disposition is not NEW_POPUP, or the
2029 // browser process will impose a default position otherwise.
2030 Send(new ViewHostMsg_ShowView(opener_id_, routing_id_,
2031 NavigationPolicyToDisposition(policy), initial_rect_,
2032 opened_by_user_gesture_));
2033 SetPendingWindowRect(initial_rect_);
2036 bool RenderViewImpl::requestPointerLock() {
2037 return mouse_lock_dispatcher_->LockMouse(webwidget_mouse_lock_target_.get());
2040 void RenderViewImpl::requestPointerUnlock() {
2041 mouse_lock_dispatcher_->UnlockMouse(webwidget_mouse_lock_target_.get());
2044 bool RenderViewImpl::isPointerLocked() {
2045 return mouse_lock_dispatcher_->IsMouseLockedTo(
2046 webwidget_mouse_lock_target_.get());
2049 void RenderViewImpl::onMouseDown(const WebNode& mouse_down_node) {
2050 FOR_EACH_OBSERVER(
2051 RenderViewObserver, observers_, OnMouseDown(mouse_down_node));
2054 void RenderViewImpl::didHandleGestureEvent(
2055 const WebGestureEvent& event,
2056 bool event_cancelled) {
2057 RenderWidget::didHandleGestureEvent(event, event_cancelled);
2059 if (!event_cancelled) {
2060 FOR_EACH_OBSERVER(
2061 RenderViewObserver, observers_, DidHandleGestureEvent(event));
2064 // TODO(ananta): Piggyback off existing IPCs to communicate this information,
2065 // crbug/420130.
2066 #if defined(OS_WIN)
2067 if (event.type != blink::WebGestureEvent::GestureTap)
2068 return;
2070 // TODO(estade): hit test the event against focused node to make sure
2071 // the tap actually hit the focused node.
2072 blink::WebTextInputType text_input_type =
2073 GetWebView()->textInputInfo().type;
2075 Send(new ViewHostMsg_FocusedNodeTouched(
2076 routing_id(), text_input_type != blink::WebTextInputTypeNone));
2077 #endif
2080 void RenderViewImpl::initializeLayerTreeView() {
2081 RenderWidget::initializeLayerTreeView();
2082 RenderWidgetCompositor* rwc = compositor();
2083 if (!rwc)
2084 return;
2086 bool use_threaded_event_handling = true;
2087 #if defined(OS_MACOSX) && !defined(OS_IOS)
2088 // Disable threaded event handling if content is not handling the elastic
2089 // overscroll effect. This includes the cases where the elastic overscroll
2090 // effect is being handled by Blink (because of command line flags) and older
2091 // operating system versions which do not have an elastic overscroll effect
2092 // (SnowLeopard, which has Aqua scrollbars which need synchronous updates).
2093 use_threaded_event_handling = compositor_deps_->IsElasticOverscrollEnabled();
2094 #endif
2095 if (use_threaded_event_handling) {
2096 RenderThreadImpl* render_thread = RenderThreadImpl::current();
2097 // render_thread may be NULL in tests.
2098 InputHandlerManager* input_handler_manager =
2099 render_thread ? render_thread->input_handler_manager() : NULL;
2100 if (input_handler_manager) {
2101 input_handler_manager->AddInputHandler(
2102 routing_id_, rwc->GetInputHandler(), AsWeakPtr());
2107 // blink::WebFrameClient -----------------------------------------------------
2109 void RenderViewImpl::Repaint(const gfx::Size& size) {
2110 OnRepaint(size);
2113 void RenderViewImpl::SetEditCommandForNextKeyEvent(const std::string& name,
2114 const std::string& value) {
2115 EditCommands edit_commands;
2116 edit_commands.push_back(EditCommand(name, value));
2117 OnSetEditCommandsForNextKeyEvent(edit_commands);
2120 void RenderViewImpl::ClearEditCommands() {
2121 edit_commands_.clear();
2124 SSLStatus RenderViewImpl::GetSSLStatusOfFrame(blink::WebFrame* frame) const {
2125 std::string security_info;
2126 if (frame && frame->dataSource())
2127 security_info = frame->dataSource()->response().securityInfo();
2129 SSLStatus result;
2130 CHECK(DeserializeSecurityInfo(security_info, &result));
2131 return result;
2134 const std::string& RenderViewImpl::GetAcceptLanguages() const {
2135 return renderer_preferences_.accept_languages;
2138 void RenderViewImpl::didChangeIcon(WebLocalFrame* frame,
2139 WebIconURL::Type icon_type) {
2140 if (frame->parent())
2141 return;
2143 WebVector<WebIconURL> icon_urls = frame->iconURLs(icon_type);
2144 std::vector<FaviconURL> urls;
2145 for (size_t i = 0; i < icon_urls.size(); i++) {
2146 std::vector<gfx::Size> sizes;
2147 ConvertToFaviconSizes(icon_urls[i].sizes(), &sizes);
2148 urls.push_back(FaviconURL(
2149 icon_urls[i].iconURL(), ToFaviconType(icon_urls[i].iconType()), sizes));
2151 SendUpdateFaviconURL(urls);
2154 void RenderViewImpl::didUpdateCurrentHistoryItem(WebLocalFrame* frame) {
2155 StartNavStateSyncTimerIfNecessary();
2158 void RenderViewImpl::CheckPreferredSize() {
2159 // We don't always want to send the change messages over IPC, only if we've
2160 // been put in that mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
2161 // message.
2162 if (!send_preferred_size_changes_ || !webview())
2163 return;
2165 gfx::Size size = webview()->contentsPreferredMinimumSize();
2166 if (size == preferred_size_)
2167 return;
2169 preferred_size_ = size;
2170 Send(new ViewHostMsg_DidContentsPreferredSizeChange(routing_id_,
2171 preferred_size_));
2174 void RenderViewImpl::didChangeScrollOffset(WebLocalFrame* frame) {
2175 StartNavStateSyncTimerIfNecessary();
2178 void RenderViewImpl::SendFindReply(int request_id,
2179 int match_count,
2180 int ordinal,
2181 const WebRect& selection_rect,
2182 bool final_status_update) {
2183 Send(new ViewHostMsg_Find_Reply(routing_id_,
2184 request_id,
2185 match_count,
2186 selection_rect,
2187 ordinal,
2188 final_status_update));
2191 blink::WebString RenderViewImpl::acceptLanguages() {
2192 return WebString::fromUTF8(renderer_preferences_.accept_languages);
2195 // blink::WebPageSerializerClient implementation ------------------------------
2197 void RenderViewImpl::didSerializeDataForFrame(
2198 const WebURL& frame_url,
2199 const WebCString& data,
2200 WebPageSerializerClient::PageSerializationStatus status) {
2201 Send(new ViewHostMsg_SendSerializedHtmlData(
2202 routing_id(),
2203 frame_url,
2204 data.data(),
2205 static_cast<int32>(status)));
2208 // RenderView implementation ---------------------------------------------------
2210 bool RenderViewImpl::Send(IPC::Message* message) {
2211 return RenderWidget::Send(message);
2214 RenderFrameImpl* RenderViewImpl::GetMainRenderFrame() {
2215 return main_render_frame_;
2218 int RenderViewImpl::GetRoutingID() const {
2219 return routing_id_;
2222 gfx::Size RenderViewImpl::GetSize() const {
2223 return size();
2226 WebPreferences& RenderViewImpl::GetWebkitPreferences() {
2227 return webkit_preferences_;
2230 void RenderViewImpl::SetWebkitPreferences(const WebPreferences& preferences) {
2231 OnUpdateWebPreferences(preferences);
2234 blink::WebView* RenderViewImpl::GetWebView() {
2235 return webview();
2238 bool RenderViewImpl::ShouldDisplayScrollbars(int width, int height) const {
2239 return (!send_preferred_size_changes_ ||
2240 (disable_scrollbars_size_limit_.width() <= width ||
2241 disable_scrollbars_size_limit_.height() <= height));
2244 int RenderViewImpl::GetEnabledBindings() const {
2245 return enabled_bindings_;
2248 bool RenderViewImpl::GetContentStateImmediately() const {
2249 return send_content_state_immediately_;
2252 blink::WebPageVisibilityState RenderViewImpl::GetVisibilityState() const {
2253 return visibilityState();
2256 void RenderViewImpl::DidStartLoading() {
2257 main_render_frame_->didStartLoading(true);
2260 void RenderViewImpl::DidStopLoading() {
2261 main_render_frame_->didStopLoading();
2264 blink::WebElement RenderViewImpl::GetFocusedElement() const {
2265 if (!webview())
2266 return WebElement();
2267 WebFrame* focused_frame = webview()->focusedFrame();
2268 if (focused_frame) {
2269 WebDocument doc = focused_frame->document();
2270 if (!doc.isNull())
2271 return doc.focusedElement();
2274 return WebElement();
2277 blink::WebPlugin* RenderViewImpl::GetWebPluginForFind() {
2278 if (!webview())
2279 return NULL;
2281 WebFrame* main_frame = webview()->mainFrame();
2282 if (main_frame->isWebLocalFrame() &&
2283 main_frame->document().isPluginDocument())
2284 return webview()->mainFrame()->document().to<WebPluginDocument>().plugin();
2286 #if defined(ENABLE_PLUGINS)
2287 if (plugin_find_handler_)
2288 return plugin_find_handler_->container()->plugin();
2289 #endif
2291 return NULL;
2294 void RenderViewImpl::OnFind(int request_id,
2295 const base::string16& search_text,
2296 const WebFindOptions& options) {
2297 WebFrame* main_frame = webview()->mainFrame();
2298 blink::WebPlugin* plugin = GetWebPluginForFind();
2299 // Check if the plugin still exists in the document.
2300 if (plugin) {
2301 if (options.findNext) {
2302 // Just navigate back/forward.
2303 plugin->selectFindResult(options.forward);
2304 } else {
2305 if (!plugin->startFind(
2306 search_text, options.matchCase, request_id)) {
2307 // Send "no results".
2308 SendFindReply(request_id, 0, 0, gfx::Rect(), true);
2311 return;
2314 WebFrame* frame_after_main = main_frame->traverseNext(true);
2315 WebFrame* focused_frame = webview()->focusedFrame();
2316 WebFrame* search_frame = focused_frame; // start searching focused frame.
2318 bool multi_frame = (frame_after_main != main_frame);
2320 // If we have multiple frames, we don't want to wrap the search within the
2321 // frame, so we check here if we only have main_frame in the chain.
2322 bool wrap_within_frame = !multi_frame;
2324 WebRect selection_rect;
2325 bool result = false;
2327 // If something is selected when we start searching it means we cannot just
2328 // increment the current match ordinal; we need to re-generate it.
2329 WebRange current_selection = focused_frame->selectionRange();
2331 do {
2332 result = search_frame->find(
2333 request_id, search_text, options, wrap_within_frame, &selection_rect);
2335 if (!result) {
2336 // don't leave text selected as you move to the next frame.
2337 search_frame->executeCommand(WebString::fromUTF8("Unselect"),
2338 GetFocusedElement());
2340 // Find the next frame, but skip the invisible ones.
2341 do {
2342 // What is the next frame to search? (we might be going backwards). Note
2343 // that we specify wrap=true so that search_frame never becomes NULL.
2344 search_frame = options.forward ?
2345 search_frame->traverseNext(true) :
2346 search_frame->traversePrevious(true);
2347 } while (!search_frame->hasVisibleContent() &&
2348 search_frame != focused_frame);
2350 // Make sure selection doesn't affect the search operation in new frame.
2351 search_frame->executeCommand(WebString::fromUTF8("Unselect"),
2352 GetFocusedElement());
2354 // If we have multiple frames and we have wrapped back around to the
2355 // focused frame, we need to search it once more allowing wrap within
2356 // the frame, otherwise it will report 'no match' if the focused frame has
2357 // reported matches, but no frames after the focused_frame contain a
2358 // match for the search word(s).
2359 if (multi_frame && search_frame == focused_frame) {
2360 result = search_frame->find(
2361 request_id, search_text, options, true, // Force wrapping.
2362 &selection_rect);
2366 webview()->setFocusedFrame(search_frame);
2367 } while (!result && search_frame != focused_frame);
2369 if (options.findNext && current_selection.isNull()) {
2370 // Force the main_frame to report the actual count.
2371 main_frame->increaseMatchCount(0, request_id);
2372 } else {
2373 // If nothing is found, set result to "0 of 0", otherwise, set it to
2374 // "-1 of 1" to indicate that we found at least one item, but we don't know
2375 // yet what is active.
2376 int ordinal = result ? -1 : 0; // -1 here means, we might know more later.
2377 int match_count = result ? 1 : 0; // 1 here means possibly more coming.
2379 // If we find no matches then this will be our last status update.
2380 // Otherwise the scoping effort will send more results.
2381 bool final_status_update = !result;
2383 SendFindReply(request_id, match_count, ordinal, selection_rect,
2384 final_status_update);
2386 // Scoping effort begins, starting with the mainframe.
2387 search_frame = main_frame;
2389 main_frame->resetMatchCount();
2391 do {
2392 // Cancel all old scoping requests before starting a new one.
2393 search_frame->cancelPendingScopingEffort();
2395 // We don't start another scoping effort unless at least one match has
2396 // been found.
2397 if (result) {
2398 // Start new scoping request. If the scoping function determines that it
2399 // needs to scope, it will defer until later.
2400 search_frame->scopeStringMatches(request_id,
2401 search_text,
2402 options,
2403 true); // reset the tickmarks
2406 // Iterate to the next frame. The frame will not necessarily scope, for
2407 // example if it is not visible.
2408 search_frame = search_frame->traverseNext(true);
2409 } while (search_frame != main_frame);
2413 void RenderViewImpl::OnStopFinding(StopFindAction action) {
2414 WebView* view = webview();
2415 if (!view)
2416 return;
2418 blink::WebPlugin* plugin = GetWebPluginForFind();
2419 if (plugin) {
2420 plugin->stopFind();
2421 return;
2424 bool clear_selection = action == STOP_FIND_ACTION_CLEAR_SELECTION;
2425 if (clear_selection) {
2426 view->focusedFrame()->executeCommand(WebString::fromUTF8("Unselect"),
2427 GetFocusedElement());
2430 WebFrame* frame = view->mainFrame();
2431 while (frame) {
2432 frame->stopFinding(clear_selection);
2433 frame = frame->traverseNext(false);
2436 if (action == STOP_FIND_ACTION_ACTIVATE_SELECTION) {
2437 WebFrame* focused_frame = view->focusedFrame();
2438 if (focused_frame) {
2439 WebDocument doc = focused_frame->document();
2440 if (!doc.isNull()) {
2441 WebElement element = doc.focusedElement();
2442 if (!element.isNull())
2443 element.simulateClick();
2449 #if defined(OS_ANDROID)
2450 void RenderViewImpl::OnActivateNearestFindResult(int request_id,
2451 float x, float y) {
2452 if (!webview())
2453 return;
2455 WebFrame* main_frame = webview()->mainFrame();
2456 WebRect selection_rect;
2457 int ordinal = main_frame->selectNearestFindMatch(WebFloatPoint(x, y),
2458 &selection_rect);
2459 if (ordinal == -1) {
2460 // Something went wrong, so send a no-op reply (force the main_frame to
2461 // report the current match count) in case the host is waiting for a
2462 // response due to rate-limiting).
2463 main_frame->increaseMatchCount(0, request_id);
2464 return;
2467 SendFindReply(request_id,
2468 -1 /* number_of_matches */,
2469 ordinal,
2470 selection_rect,
2471 true /* final_update */);
2474 void RenderViewImpl::OnFindMatchRects(int current_version) {
2475 if (!webview())
2476 return;
2478 WebFrame* main_frame = webview()->mainFrame();
2479 std::vector<gfx::RectF> match_rects;
2481 int rects_version = main_frame->findMatchMarkersVersion();
2482 if (current_version != rects_version) {
2483 WebVector<WebFloatRect> web_match_rects;
2484 main_frame->findMatchRects(web_match_rects);
2485 match_rects.reserve(web_match_rects.size());
2486 for (size_t i = 0; i < web_match_rects.size(); ++i)
2487 match_rects.push_back(gfx::RectF(web_match_rects[i]));
2490 gfx::RectF active_rect = main_frame->activeFindMatchRect();
2491 Send(new ViewHostMsg_FindMatchRects_Reply(routing_id_,
2492 rects_version,
2493 match_rects,
2494 active_rect));
2496 #endif
2498 void RenderViewImpl::OnResetPageScale() {
2499 if (!webview())
2500 return;
2501 webview()->setPageScaleFactor(1);
2504 void RenderViewImpl::OnZoom(PageZoom zoom) {
2505 if (!webview()) // Not sure if this can happen, but no harm in being safe.
2506 return;
2508 webview()->hidePopups();
2510 double old_zoom_level = webview()->zoomLevel();
2511 double zoom_level;
2512 if (zoom == PAGE_ZOOM_RESET) {
2513 zoom_level = 0;
2514 } else if (static_cast<int>(old_zoom_level) == old_zoom_level) {
2515 // Previous zoom level is a whole number, so just increment/decrement.
2516 zoom_level = old_zoom_level + zoom;
2517 } else {
2518 // Either the user hit the zoom factor limit and thus the zoom level is now
2519 // not a whole number, or a plugin changed it to a custom value. We want
2520 // to go to the next whole number so that the user can always get back to
2521 // 100% with the keyboard/menu.
2522 if ((old_zoom_level > 1 && zoom > 0) ||
2523 (old_zoom_level < 1 && zoom < 0)) {
2524 zoom_level = static_cast<int>(old_zoom_level + zoom);
2525 } else {
2526 // We're going towards 100%, so first go to the next whole number.
2527 zoom_level = static_cast<int>(old_zoom_level);
2530 SetZoomLevel(zoom_level);
2531 zoomLevelChanged();
2534 void RenderViewImpl::OnSetZoomLevelForLoadingURL(const GURL& url,
2535 double zoom_level) {
2536 #if !defined(OS_ANDROID)
2537 // On Android, page zoom isn't used, and in case of WebView, text zoom is used
2538 // for legacy WebView text scaling emulation. Thus, the code that resets
2539 // the zoom level from this map will be effectively resetting text zoom level.
2540 host_zoom_levels_[url] = zoom_level;
2541 #endif
2544 void RenderViewImpl::OnSetZoomLevelForView(bool uses_temporary_zoom_level,
2545 double level) {
2546 uses_temporary_zoom_level_ = uses_temporary_zoom_level;
2548 webview()->hidePopups();
2549 SetZoomLevel(level);
2552 void RenderViewImpl::OnSetPageEncoding(const std::string& encoding_name) {
2553 webview()->setPageEncoding(WebString::fromUTF8(encoding_name));
2556 void RenderViewImpl::OnResetPageEncodingToDefault() {
2557 WebString no_encoding;
2558 webview()->setPageEncoding(no_encoding);
2561 void RenderViewImpl::OnAllowBindings(int enabled_bindings_flags) {
2562 if ((enabled_bindings_flags & BINDINGS_POLICY_WEB_UI) &&
2563 !(enabled_bindings_ & BINDINGS_POLICY_WEB_UI)) {
2564 // WebUIExtensionData deletes itself when we're destroyed.
2565 new WebUIExtensionData(this);
2566 // WebUIMojo deletes itself when we're destroyed.
2567 new WebUIMojo(this);
2570 enabled_bindings_ |= enabled_bindings_flags;
2572 // Keep track of the total bindings accumulated in this process.
2573 RenderProcess::current()->AddBindings(enabled_bindings_flags);
2576 void RenderViewImpl::OnDragTargetDragEnter(const DropData& drop_data,
2577 const gfx::Point& client_point,
2578 const gfx::Point& screen_point,
2579 WebDragOperationsMask ops,
2580 int key_modifiers) {
2581 WebDragOperation operation = webview()->dragTargetDragEnter(
2582 DropDataToWebDragData(drop_data),
2583 client_point,
2584 screen_point,
2585 ops,
2586 key_modifiers);
2588 Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
2591 void RenderViewImpl::OnDragTargetDragOver(const gfx::Point& client_point,
2592 const gfx::Point& screen_point,
2593 WebDragOperationsMask ops,
2594 int key_modifiers) {
2595 WebDragOperation operation = webview()->dragTargetDragOver(
2596 client_point,
2597 screen_point,
2598 ops,
2599 key_modifiers);
2601 Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
2604 void RenderViewImpl::OnDragTargetDragLeave() {
2605 webview()->dragTargetDragLeave();
2608 void RenderViewImpl::OnDragTargetDrop(const gfx::Point& client_point,
2609 const gfx::Point& screen_point,
2610 int key_modifiers) {
2611 webview()->dragTargetDrop(client_point, screen_point, key_modifiers);
2614 void RenderViewImpl::OnDragSourceEnded(const gfx::Point& client_point,
2615 const gfx::Point& screen_point,
2616 WebDragOperation op) {
2617 webview()->dragSourceEndedAt(client_point, screen_point, op);
2620 void RenderViewImpl::OnDragSourceSystemDragEnded() {
2621 webview()->dragSourceSystemDragEnded();
2624 void RenderViewImpl::OnUpdateWebPreferences(const WebPreferences& prefs) {
2625 webkit_preferences_ = prefs;
2626 ApplyWebPreferencesInternal(webkit_preferences_, webview(), compositor_deps_);
2629 void RenderViewImpl::OnEnumerateDirectoryResponse(
2630 int id,
2631 const std::vector<base::FilePath>& paths) {
2632 if (!enumeration_completions_[id])
2633 return;
2635 WebVector<WebString> ws_file_names(paths.size());
2636 for (size_t i = 0; i < paths.size(); ++i)
2637 ws_file_names[i] = paths[i].AsUTF16Unsafe();
2639 enumeration_completions_[id]->didChooseFile(ws_file_names);
2640 enumeration_completions_.erase(id);
2643 void RenderViewImpl::OnFileChooserResponse(
2644 const std::vector<content::FileChooserFileInfo>& files) {
2645 // This could happen if we navigated to a different page before the user
2646 // closed the chooser.
2647 if (file_chooser_completions_.empty())
2648 return;
2650 // Convert Chrome's SelectedFileInfo list to WebKit's.
2651 WebVector<WebFileChooserCompletion::SelectedFileInfo> selected_files(
2652 files.size());
2653 for (size_t i = 0; i < files.size(); ++i) {
2654 WebFileChooserCompletion::SelectedFileInfo selected_file;
2655 selected_file.path = files[i].file_path.AsUTF16Unsafe();
2656 selected_file.displayName =
2657 base::FilePath(files[i].display_name).AsUTF16Unsafe();
2658 if (files[i].file_system_url.is_valid()) {
2659 selected_file.fileSystemURL = files[i].file_system_url;
2660 selected_file.length = files[i].length;
2661 selected_file.modificationTime = files[i].modification_time.ToDoubleT();
2662 selected_file.isDirectory = files[i].is_directory;
2664 selected_files[i] = selected_file;
2667 if (file_chooser_completions_.front()->completion)
2668 file_chooser_completions_.front()->completion->didChooseFile(
2669 selected_files);
2670 file_chooser_completions_.pop_front();
2672 // If there are more pending file chooser requests, schedule one now.
2673 if (!file_chooser_completions_.empty()) {
2674 Send(new ViewHostMsg_RunFileChooser(routing_id_,
2675 file_chooser_completions_.front()->params));
2679 void RenderViewImpl::OnEnableAutoResize(const gfx::Size& min_size,
2680 const gfx::Size& max_size) {
2681 DCHECK(disable_scrollbars_size_limit_.IsEmpty());
2682 if (!webview())
2683 return;
2684 auto_resize_mode_ = true;
2685 webview()->enableAutoResizeMode(min_size, max_size);
2688 void RenderViewImpl::OnDisableAutoResize(const gfx::Size& new_size) {
2689 DCHECK(disable_scrollbars_size_limit_.IsEmpty());
2690 if (!webview())
2691 return;
2692 auto_resize_mode_ = false;
2693 webview()->disableAutoResizeMode();
2695 if (!new_size.IsEmpty()) {
2696 Resize(new_size,
2697 physical_backing_size_,
2698 top_controls_shrink_blink_size_,
2699 top_controls_height_,
2700 visible_viewport_size_,
2701 resizer_rect_,
2702 is_fullscreen_granted_,
2703 display_mode_,
2704 NO_RESIZE_ACK);
2708 void RenderViewImpl::OnEnablePreferredSizeChangedMode() {
2709 if (send_preferred_size_changes_)
2710 return;
2711 send_preferred_size_changes_ = true;
2713 // Start off with an initial preferred size notification (in case
2714 // |didUpdateLayout| was already called).
2715 didUpdateLayout();
2718 void RenderViewImpl::OnDisableScrollbarsForSmallWindows(
2719 const gfx::Size& disable_scrollbar_size_limit) {
2720 disable_scrollbars_size_limit_ = disable_scrollbar_size_limit;
2723 void RenderViewImpl::OnSetRendererPrefs(
2724 const RendererPreferences& renderer_prefs) {
2725 double old_zoom_level = renderer_preferences_.default_zoom_level;
2726 std::string old_accept_languages = renderer_preferences_.accept_languages;
2728 renderer_preferences_ = renderer_prefs;
2730 UpdateFontRenderingFromRendererPrefs();
2731 UpdateThemePrefs();
2733 #if defined(USE_DEFAULT_RENDER_THEME)
2734 if (renderer_prefs.use_custom_colors) {
2735 WebColorName name = blink::WebColorWebkitFocusRingColor;
2736 blink::setNamedColors(&name, &renderer_prefs.focus_ring_color, 1);
2737 blink::setCaretBlinkInterval(renderer_prefs.caret_blink_interval);
2739 if (webview()) {
2740 webview()->setSelectionColors(
2741 renderer_prefs.active_selection_bg_color,
2742 renderer_prefs.active_selection_fg_color,
2743 renderer_prefs.inactive_selection_bg_color,
2744 renderer_prefs.inactive_selection_fg_color);
2745 webview()->themeChanged();
2748 #endif // defined(USE_DEFAULT_RENDER_THEME)
2750 // If the zoom level for this page matches the old zoom default, and this
2751 // is not a plugin, update the zoom level to match the new default.
2752 if (webview() && webview()->mainFrame()->isWebLocalFrame() &&
2753 !webview()->mainFrame()->document().isPluginDocument() &&
2754 !ZoomValuesEqual(old_zoom_level,
2755 renderer_preferences_.default_zoom_level) &&
2756 ZoomValuesEqual(webview()->zoomLevel(), old_zoom_level)) {
2757 SetZoomLevel(renderer_preferences_.default_zoom_level);
2758 zoomLevelChanged();
2761 if (webview() &&
2762 old_accept_languages != renderer_preferences_.accept_languages) {
2763 webview()->acceptLanguagesChanged();
2767 void RenderViewImpl::OnMediaPlayerActionAt(const gfx::Point& location,
2768 const WebMediaPlayerAction& action) {
2769 if (webview())
2770 webview()->performMediaPlayerAction(action, location);
2773 void RenderViewImpl::OnOrientationChange() {
2774 if (webview() && webview()->mainFrame()->isWebLocalFrame())
2775 webview()->mainFrame()->toWebLocalFrame()->sendOrientationChangeEvent();
2778 void RenderViewImpl::OnPluginActionAt(const gfx::Point& location,
2779 const WebPluginAction& action) {
2780 if (webview())
2781 webview()->performPluginAction(action, location);
2784 void RenderViewImpl::OnGetSerializedHtmlDataForCurrentPageWithLocalLinks(
2785 const std::vector<GURL>& links,
2786 const std::vector<base::FilePath>& local_paths,
2787 const base::FilePath& local_directory_name) {
2789 // Convert std::vector of GURLs to WebVector<WebURL>
2790 WebVector<WebURL> weburl_links(links);
2792 // Convert std::vector of base::FilePath to WebVector<WebString>
2793 WebVector<WebString> webstring_paths(local_paths.size());
2794 for (size_t i = 0; i < local_paths.size(); i++)
2795 webstring_paths[i] = local_paths[i].AsUTF16Unsafe();
2797 WebPageSerializer::serialize(webview()->mainFrame()->toWebLocalFrame(),
2798 true,
2799 this,
2800 weburl_links,
2801 webstring_paths,
2802 local_directory_name.AsUTF16Unsafe());
2805 void RenderViewImpl::OnSuppressDialogsUntilSwapOut() {
2806 // Don't show any more dialogs until we finish OnSwapOut.
2807 suppress_dialogs_until_swap_out_ = true;
2810 void RenderViewImpl::OnClosePage() {
2811 FOR_EACH_OBSERVER(RenderViewObserver, observers_, ClosePage());
2812 // TODO(creis): We'd rather use webview()->Close() here, but that currently
2813 // sets the WebView's delegate_ to NULL, preventing any JavaScript dialogs
2814 // in the onunload handler from appearing. For now, we're bypassing that and
2815 // calling the FrameLoader's CloseURL method directly. This should be
2816 // revisited to avoid having two ways to close a page. Having a single way
2817 // to close that can run onunload is also useful for fixing
2818 // http://b/issue?id=753080.
2819 webview()->mainFrame()->dispatchUnloadEvent();
2821 Send(new ViewHostMsg_ClosePage_ACK(routing_id_));
2824 void RenderViewImpl::OnClose() {
2825 if (closing_)
2826 RenderThread::Get()->Send(new ViewHostMsg_Close_ACK(routing_id_));
2827 RenderWidget::OnClose();
2830 void RenderViewImpl::OnThemeChanged() {
2831 #if defined(USE_AURA)
2832 // Aura doesn't care if we switch themes.
2833 #elif defined(OS_WIN)
2834 ui::NativeThemeWin::instance()->CloseHandles();
2835 if (webview())
2836 webview()->themeChanged();
2837 #else // defined(OS_WIN)
2838 // TODO(port): we don't support theming on non-Windows platforms yet
2839 NOTIMPLEMENTED();
2840 #endif
2843 void RenderViewImpl::OnMoveOrResizeStarted() {
2844 if (webview())
2845 webview()->hidePopups();
2848 void RenderViewImpl::OnResize(const ViewMsg_Resize_Params& params) {
2849 TRACE_EVENT0("renderer", "RenderViewImpl::OnResize");
2850 if (webview()) {
2851 webview()->hidePopups();
2852 if (send_preferred_size_changes_) {
2853 webview()->mainFrame()->setCanHaveScrollbars(
2854 ShouldDisplayScrollbars(params.new_size.width(),
2855 params.new_size.height()));
2857 if (display_mode_ != params.display_mode) {
2858 display_mode_ = params.display_mode;
2859 webview()->setDisplayMode(display_mode_);
2863 gfx::Size old_visible_viewport_size = visible_viewport_size_;
2865 RenderWidget::OnResize(params);
2867 if (old_visible_viewport_size != visible_viewport_size_)
2868 has_scrolled_focused_editable_node_into_rect_ = false;
2871 void RenderViewImpl::DidInitiatePaint() {
2872 #if defined(ENABLE_PLUGINS)
2873 // Notify all instances that we painted. The same caveats apply as for
2874 // ViewFlushedPaint regarding instances closing themselves, so we take
2875 // similar precautions.
2876 PepperPluginSet plugins = active_pepper_instances_;
2877 for (PepperPluginSet::iterator i = plugins.begin(); i != plugins.end(); ++i) {
2878 if (active_pepper_instances_.find(*i) != active_pepper_instances_.end())
2879 (*i)->ViewInitiatedPaint();
2881 #endif
2884 void RenderViewImpl::DidFlushPaint() {
2885 // If the RenderWidget is closing down then early-exit, otherwise we'll crash.
2886 // See crbug.com/112921.
2887 if (!webview())
2888 return;
2890 WebFrame* main_frame = webview()->mainFrame();
2891 for (WebFrame* frame = main_frame; frame;
2892 frame = frame->traverseNext(false)) {
2893 // TODO(nasko): This is a hack for the case in which the top-level
2894 // frame is being rendered in another process. It will not
2895 // behave correctly for out of process iframes.
2896 if (frame->isWebLocalFrame()) {
2897 main_frame = frame;
2898 break;
2902 // There's nothing to do if there are no local frames in this RenderView's
2903 // frame tree. This can happen if DidFlushPaint is called after the
2904 // RenderView's local main frame is swapped to a remote frame. See
2905 // http://crbug.com/513552.
2906 if (main_frame->isWebRemoteFrame())
2907 return;
2909 // If we have a provisional frame we are between the start and commit stages
2910 // of loading and we don't want to save stats.
2911 if (!main_frame->provisionalDataSource()) {
2912 WebDataSource* ds = main_frame->dataSource();
2913 if (!ds)
2914 return;
2916 DocumentState* document_state = DocumentState::FromDataSource(ds);
2918 // TODO(jar): The following code should all be inside a method, probably in
2919 // NavigatorState.
2920 Time now = Time::Now();
2921 if (document_state->first_paint_time().is_null()) {
2922 document_state->set_first_paint_time(now);
2924 if (document_state->first_paint_after_load_time().is_null() &&
2925 !document_state->finish_load_time().is_null()) {
2926 document_state->set_first_paint_after_load_time(now);
2931 gfx::Vector2d RenderViewImpl::GetScrollOffset() {
2932 WebFrame* main_frame = webview()->mainFrame();
2933 for (WebFrame* frame = main_frame; frame;
2934 frame = frame->traverseNext(false)) {
2935 // TODO(nasko): This is a hack for the case in which the top-level
2936 // frame is being rendered in another process. It will not
2937 // behave correctly for out of process iframes.
2938 if (frame->isWebLocalFrame()) {
2939 main_frame = frame;
2940 break;
2944 WebSize scroll_offset = main_frame->scrollOffset();
2945 return gfx::Vector2d(scroll_offset.width, scroll_offset.height);
2948 void RenderViewImpl::OnClearFocusedElement() {
2949 if (webview())
2950 webview()->clearFocusedElement();
2953 void RenderViewImpl::OnSetBackgroundOpaque(bool opaque) {
2954 if (webview())
2955 webview()->setIsTransparent(!opaque);
2956 if (compositor_)
2957 compositor_->setHasTransparentBackground(!opaque);
2960 void RenderViewImpl::OnSetActive(bool active) {
2961 if (webview())
2962 webview()->setIsActive(active);
2964 #if defined(ENABLE_PLUGINS) && defined(OS_MACOSX)
2965 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
2966 for (plugin_it = plugin_delegates_.begin();
2967 plugin_it != plugin_delegates_.end(); ++plugin_it) {
2968 (*plugin_it)->SetWindowFocus(active);
2970 #endif
2973 #if defined(OS_MACOSX)
2974 void RenderViewImpl::OnSetWindowVisibility(bool visible) {
2975 #if defined(ENABLE_PLUGINS)
2976 // Inform plugins that their container has changed visibility.
2977 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
2978 for (plugin_it = plugin_delegates_.begin();
2979 plugin_it != plugin_delegates_.end(); ++plugin_it) {
2980 (*plugin_it)->SetContainerVisibility(visible);
2982 #endif
2985 void RenderViewImpl::OnWindowFrameChanged(const gfx::Rect& window_frame,
2986 const gfx::Rect& view_frame) {
2987 #if defined(ENABLE_PLUGINS)
2988 // Inform plugins that their window's frame has changed.
2989 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
2990 for (plugin_it = plugin_delegates_.begin();
2991 plugin_it != plugin_delegates_.end(); ++plugin_it) {
2992 (*plugin_it)->WindowFrameChanged(window_frame, view_frame);
2994 #endif
2997 void RenderViewImpl::OnPluginImeCompositionCompleted(const base::string16& text,
2998 int plugin_id) {
2999 // WebPluginDelegateProxy is responsible for figuring out if this event
3000 // applies to it or not, so inform all the delegates.
3001 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3002 for (plugin_it = plugin_delegates_.begin();
3003 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3004 (*plugin_it)->ImeCompositionCompleted(text, plugin_id);
3007 #endif // OS_MACOSX
3009 void RenderViewImpl::Close() {
3010 // We need to grab a pointer to the doomed WebView before we destroy it.
3011 WebView* doomed = webview();
3012 RenderWidget::Close();
3013 g_view_map.Get().erase(doomed);
3014 g_routing_id_view_map.Get().erase(routing_id_);
3015 RenderThread::Get()->Send(new ViewHostMsg_Close_ACK(routing_id_));
3018 void RenderViewImpl::DidHandleKeyEvent() {
3019 ClearEditCommands();
3022 bool RenderViewImpl::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
3023 possible_drag_event_info_.event_source =
3024 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE;
3025 possible_drag_event_info_.event_location =
3026 gfx::Point(event.globalX, event.globalY);
3028 #if defined(ENABLE_PLUGINS)
3029 // This method is called for every mouse event that the render view receives.
3030 // And then the mouse event is forwarded to WebKit, which dispatches it to the
3031 // event target. Potentially a Pepper plugin will receive the event.
3032 // In order to tell whether a plugin gets the last mouse event and which it
3033 // is, we set |pepper_last_mouse_event_target_| to NULL here. If a plugin gets
3034 // the event, it will notify us via DidReceiveMouseEvent() and set itself as
3035 // |pepper_last_mouse_event_target_|.
3036 pepper_last_mouse_event_target_ = NULL;
3037 #endif
3039 // If the mouse is locked, only the current owner of the mouse lock can
3040 // process mouse events.
3041 return mouse_lock_dispatcher_->WillHandleMouseEvent(event);
3044 bool RenderViewImpl::WillHandleGestureEvent(
3045 const blink::WebGestureEvent& event) {
3046 possible_drag_event_info_.event_source =
3047 ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH;
3048 possible_drag_event_info_.event_location =
3049 gfx::Point(event.globalX, event.globalY);
3050 return false;
3053 bool RenderViewImpl::HasTouchEventHandlersAt(const gfx::Point& point) const {
3054 if (!webview())
3055 return false;
3056 return webview()->hasTouchEventHandlersAt(point);
3059 void RenderViewImpl::OnWasHidden() {
3060 RenderWidget::OnWasHidden();
3062 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3063 RenderThreadImpl::current()->video_capture_impl_manager()->
3064 SuspendDevices(true);
3065 if (speech_recognition_dispatcher_)
3066 speech_recognition_dispatcher_->AbortAllRecognitions();
3067 #endif
3069 if (webview())
3070 webview()->setVisibilityState(visibilityState(), false);
3072 #if defined(ENABLE_PLUGINS)
3073 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3074 i != active_pepper_instances_.end(); ++i)
3075 (*i)->PageVisibilityChanged(false);
3077 #if defined(OS_MACOSX)
3078 // Inform NPAPI plugins that their container is no longer visible.
3079 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3080 for (plugin_it = plugin_delegates_.begin();
3081 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3082 (*plugin_it)->SetContainerVisibility(false);
3084 #endif // OS_MACOSX
3085 #endif // ENABLE_PLUGINS
3088 void RenderViewImpl::OnWasShown(bool needs_repainting,
3089 const ui::LatencyInfo& latency_info) {
3090 RenderWidget::OnWasShown(needs_repainting, latency_info);
3092 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3093 RenderThreadImpl::current()->video_capture_impl_manager()->
3094 SuspendDevices(false);
3095 #endif
3097 if (webview())
3098 webview()->setVisibilityState(visibilityState(), false);
3100 #if defined(ENABLE_PLUGINS)
3101 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3102 i != active_pepper_instances_.end(); ++i)
3103 (*i)->PageVisibilityChanged(true);
3105 #if defined(OS_MACOSX)
3106 // Inform NPAPI plugins that their container is now visible.
3107 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3108 for (plugin_it = plugin_delegates_.begin();
3109 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3110 (*plugin_it)->SetContainerVisibility(true);
3112 #endif // OS_MACOSX
3113 #endif // ENABLE_PLUGINS
3116 GURL RenderViewImpl::GetURLForGraphicsContext3D() {
3117 DCHECK(webview());
3118 if (webview()->mainFrame()->isWebLocalFrame())
3119 return GURL(webview()->mainFrame()->document().url());
3120 else
3121 return GURL("chrome://gpu/RenderViewImpl::CreateGraphicsContext3D");
3124 void RenderViewImpl::OnSetFocus(bool enable) {
3125 RenderWidget::OnSetFocus(enable);
3127 #if defined(ENABLE_PLUGINS)
3128 if (webview() && webview()->isActive()) {
3129 // Notify all NPAPI plugins.
3130 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3131 for (plugin_it = plugin_delegates_.begin();
3132 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3133 #if defined(OS_MACOSX)
3134 // RenderWidget's call to setFocus can cause the underlying webview's
3135 // activation state to change just like a call to setIsActive.
3136 if (enable)
3137 (*plugin_it)->SetWindowFocus(true);
3138 #endif
3139 (*plugin_it)->SetContentAreaFocus(enable);
3142 // Notify all Pepper plugins.
3143 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3144 i != active_pepper_instances_.end(); ++i)
3145 (*i)->SetContentAreaFocus(enable);
3146 #endif
3147 // Notify all BrowserPlugins of the RenderView's focus state.
3148 if (BrowserPluginManager::Get())
3149 BrowserPluginManager::Get()->UpdateFocusState();
3152 void RenderViewImpl::OnImeSetComposition(
3153 const base::string16& text,
3154 const std::vector<blink::WebCompositionUnderline>& underlines,
3155 int selection_start,
3156 int selection_end) {
3157 #if defined(ENABLE_PLUGINS)
3158 if (focused_pepper_plugin_) {
3159 focused_pepper_plugin_->render_frame()->OnImeSetComposition(
3160 text, underlines, selection_start, selection_end);
3161 return;
3164 #if defined(OS_WIN)
3165 // When a plugin has focus, we create platform-specific IME data used by
3166 // our IME emulator and send it directly to the focused plugin, i.e. we
3167 // bypass WebKit. (WebPluginDelegate dispatches this IME data only when its
3168 // instance ID is the same one as the specified ID.)
3169 if (focused_plugin_id_ >= 0) {
3170 std::vector<int> clauses;
3171 std::vector<int> target;
3172 for (size_t i = 0; i < underlines.size(); ++i) {
3173 clauses.push_back(underlines[i].startOffset);
3174 clauses.push_back(underlines[i].endOffset);
3175 if (underlines[i].thick) {
3176 target.clear();
3177 target.push_back(underlines[i].startOffset);
3178 target.push_back(underlines[i].endOffset);
3181 std::set<WebPluginDelegateProxy*>::iterator it;
3182 for (it = plugin_delegates_.begin(); it != plugin_delegates_.end(); ++it) {
3183 (*it)->ImeCompositionUpdated(text, clauses, target, selection_end,
3184 focused_plugin_id_);
3186 return;
3188 #endif // OS_WIN
3189 #endif // ENABLE_PLUGINS
3190 RenderWidget::OnImeSetComposition(text,
3191 underlines,
3192 selection_start,
3193 selection_end);
3196 void RenderViewImpl::OnImeConfirmComposition(
3197 const base::string16& text,
3198 const gfx::Range& replacement_range,
3199 bool keep_selection) {
3200 #if defined(ENABLE_PLUGINS)
3201 if (focused_pepper_plugin_) {
3202 focused_pepper_plugin_->render_frame()->OnImeConfirmComposition(
3203 text, replacement_range, keep_selection);
3204 return;
3206 #if defined(OS_WIN)
3207 // Same as OnImeSetComposition(), we send the text from IMEs directly to
3208 // plugins. When we send IME text directly to plugins, we should not send
3209 // it to WebKit to prevent WebKit from controlling IMEs.
3210 // TODO(thakis): Honor |replacement_range| for plugins?
3211 if (focused_plugin_id_ >= 0) {
3212 std::set<WebPluginDelegateProxy*>::iterator it;
3213 for (it = plugin_delegates_.begin();
3214 it != plugin_delegates_.end(); ++it) {
3215 (*it)->ImeCompositionCompleted(text, focused_plugin_id_);
3217 return;
3219 #endif // OS_WIN
3220 #endif // ENABLE_PLUGINS
3221 if (replacement_range.IsValid() && webview()) {
3222 // Select the text in |replacement_range|, it will then be replaced by
3223 // text added by the call to RenderWidget::OnImeConfirmComposition().
3224 if (WebLocalFrame* frame = webview()->focusedFrame()->toWebLocalFrame()) {
3225 WebRange webrange = WebRange::fromDocumentRange(
3226 frame, replacement_range.start(), replacement_range.length());
3227 if (!webrange.isNull())
3228 frame->selectRange(webrange);
3231 RenderWidget::OnImeConfirmComposition(text,
3232 replacement_range,
3233 keep_selection);
3236 void RenderViewImpl::SetDeviceScaleFactor(float device_scale_factor) {
3237 RenderWidget::SetDeviceScaleFactor(device_scale_factor);
3238 if (webview()) {
3239 webview()->setDeviceScaleFactor(device_scale_factor);
3240 webview()->settings()->setPreferCompositingToLCDTextEnabled(
3241 PreferCompositingToLCDText(compositor_deps_, device_scale_factor_));
3243 if (auto_resize_mode_)
3244 AutoResizeCompositor();
3247 bool RenderViewImpl::SetDeviceColorProfile(
3248 const std::vector<char>& profile) {
3249 bool changed = RenderWidget::SetDeviceColorProfile(profile);
3250 if (changed && webview()) {
3251 WebVector<char> colorProfile = profile;
3252 webview()->setDeviceColorProfile(colorProfile);
3254 return changed;
3257 void RenderViewImpl::ResetDeviceColorProfileForTesting() {
3258 RenderWidget::ResetDeviceColorProfileForTesting();
3259 if (webview())
3260 webview()->resetDeviceColorProfile();
3263 ui::TextInputType RenderViewImpl::GetTextInputType() {
3264 #if defined(ENABLE_PLUGINS)
3265 if (focused_pepper_plugin_)
3266 return focused_pepper_plugin_->text_input_type();
3267 #endif
3268 return RenderWidget::GetTextInputType();
3271 void RenderViewImpl::GetSelectionBounds(gfx::Rect* start, gfx::Rect* end) {
3272 #if defined(ENABLE_PLUGINS)
3273 if (focused_pepper_plugin_) {
3274 // TODO(kinaba) http://crbug.com/101101
3275 // Current Pepper IME API does not handle selection bounds. So we simply
3276 // use the caret position as an empty range for now. It will be updated
3277 // after Pepper API equips features related to surrounding text retrieval.
3278 gfx::Rect caret = focused_pepper_plugin_->GetCaretBounds();
3279 *start = caret;
3280 *end = caret;
3281 return;
3283 #endif
3284 RenderWidget::GetSelectionBounds(start, end);
3287 void RenderViewImpl::FocusChangeComplete() {
3288 RenderWidget::FocusChangeComplete();
3289 FOR_EACH_OBSERVER(RenderViewObserver, observers_, FocusChangeComplete());
3292 void RenderViewImpl::GetCompositionCharacterBounds(
3293 std::vector<gfx::Rect>* bounds) {
3294 DCHECK(bounds);
3295 bounds->clear();
3297 #if defined(ENABLE_PLUGINS)
3298 if (focused_pepper_plugin_) {
3299 return;
3301 #endif
3303 if (!webview())
3304 return;
3305 size_t start_offset = 0;
3306 size_t character_count = 0;
3307 if (!webview()->compositionRange(&start_offset, &character_count))
3308 return;
3309 if (character_count == 0)
3310 return;
3312 blink::WebFrame* frame = webview()->focusedFrame();
3313 if (!frame)
3314 return;
3316 bounds->reserve(character_count);
3317 blink::WebRect webrect;
3318 for (size_t i = 0; i < character_count; ++i) {
3319 if (!frame->firstRectForCharacterRange(start_offset + i, 1, webrect)) {
3320 DLOG(ERROR) << "Could not retrieve character rectangle at " << i;
3321 bounds->clear();
3322 return;
3324 bounds->push_back(webrect);
3328 void RenderViewImpl::GetCompositionRange(gfx::Range* range) {
3329 #if defined(ENABLE_PLUGINS)
3330 if (focused_pepper_plugin_) {
3331 return;
3333 #endif
3334 RenderWidget::GetCompositionRange(range);
3337 bool RenderViewImpl::CanComposeInline() {
3338 #if defined(ENABLE_PLUGINS)
3339 if (focused_pepper_plugin_)
3340 return focused_pepper_plugin_->IsPluginAcceptingCompositionEvents();
3341 #endif
3342 return true;
3345 void RenderViewImpl::DidCompletePageScaleAnimation() {
3346 FocusChangeComplete();
3349 #if defined(OS_ANDROID)
3350 bool RenderViewImpl::DoesRecordFullLayer() const {
3351 return webkit_preferences_.record_whole_document;
3353 #endif
3355 void RenderViewImpl::SetScreenMetricsEmulationParameters(
3356 bool enabled,
3357 const blink::WebDeviceEmulationParams& params) {
3358 if (webview() && compositor()) {
3359 if (enabled)
3360 webview()->enableDeviceEmulation(params);
3361 else
3362 webview()->disableDeviceEmulation();
3366 bool RenderViewImpl::ScheduleFileChooser(
3367 const FileChooserParams& params,
3368 WebFileChooserCompletion* completion) {
3369 static const size_t kMaximumPendingFileChooseRequests = 4;
3370 if (file_chooser_completions_.size() > kMaximumPendingFileChooseRequests) {
3371 // This sanity check prevents too many file choose requests from getting
3372 // queued which could DoS the user. Getting these is most likely a
3373 // programming error (there are many ways to DoS the user so it's not
3374 // considered a "real" security check), either in JS requesting many file
3375 // choosers to pop up, or in a plugin.
3377 // TODO(brettw) we might possibly want to require a user gesture to open
3378 // a file picker, which will address this issue in a better way.
3379 return false;
3382 file_chooser_completions_.push_back(linked_ptr<PendingFileChooser>(
3383 new PendingFileChooser(params, completion)));
3384 if (file_chooser_completions_.size() == 1) {
3385 // Actually show the browse dialog when this is the first request.
3386 Send(new ViewHostMsg_RunFileChooser(routing_id_, params));
3388 return true;
3391 blink::WebSpeechRecognizer* RenderViewImpl::speechRecognizer() {
3392 if (!speech_recognition_dispatcher_)
3393 speech_recognition_dispatcher_ = new SpeechRecognitionDispatcher(this);
3394 return speech_recognition_dispatcher_;
3397 void RenderViewImpl::zoomLimitsChanged(double minimum_level,
3398 double maximum_level) {
3399 // Round the double to avoid returning incorrect minimum/maximum zoom
3400 // percentages.
3401 int minimum_percent = round(
3402 ZoomLevelToZoomFactor(minimum_level) * 100);
3403 int maximum_percent = round(
3404 ZoomLevelToZoomFactor(maximum_level) * 100);
3406 Send(new ViewHostMsg_UpdateZoomLimits(
3407 routing_id_, minimum_percent, maximum_percent));
3410 void RenderViewImpl::zoomLevelChanged() {
3411 double zoom_level = webview()->zoomLevel();
3413 // Do not send empty URLs to the browser when we are just setting the default
3414 // zoom level (from RendererPreferences) before the first navigation.
3415 if (!webview()->mainFrame()->document().url().isEmpty()) {
3416 // Tell the browser which url got zoomed so it can update the menu and the
3417 // saved values if necessary
3418 Send(new ViewHostMsg_DidZoomURL(
3419 routing_id_, zoom_level,
3420 GURL(webview()->mainFrame()->document().url())));
3424 void RenderViewImpl::pageScaleFactorChanged() {
3425 if (!webview())
3426 return;
3427 bool page_scale_factor_is_one = webview()->pageScaleFactor() == 1;
3428 if (page_scale_factor_is_one == page_scale_factor_is_one_)
3429 return;
3430 page_scale_factor_is_one_ = page_scale_factor_is_one;
3431 Send(new ViewHostMsg_PageScaleFactorIsOneChanged(routing_id_,
3432 page_scale_factor_is_one_));
3435 double RenderViewImpl::zoomLevelToZoomFactor(double zoom_level) const {
3436 return ZoomLevelToZoomFactor(zoom_level);
3439 double RenderViewImpl::zoomFactorToZoomLevel(double factor) const {
3440 return ZoomFactorToZoomLevel(factor);
3443 blink::WebPageVisibilityState RenderViewImpl::visibilityState() const {
3444 blink::WebPageVisibilityState current_state = is_hidden() ?
3445 blink::WebPageVisibilityStateHidden :
3446 blink::WebPageVisibilityStateVisible;
3447 blink::WebPageVisibilityState override_state = current_state;
3448 // TODO(jam): move this method to WebFrameClient.
3449 if (GetContentClient()->renderer()->
3450 ShouldOverridePageVisibilityState(main_render_frame_,
3451 &override_state))
3452 return override_state;
3453 return current_state;
3456 void RenderViewImpl::draggableRegionsChanged() {
3457 FOR_EACH_OBSERVER(
3458 RenderViewObserver,
3459 observers_,
3460 DraggableRegionsChanged(webview()->mainFrame()));
3463 #if defined(OS_ANDROID)
3464 WebContentDetectionResult RenderViewImpl::detectContentAround(
3465 const WebHitTestResult& touch_hit) {
3466 DCHECK(touch_hit.node().isTextNode());
3468 // Process the position with all the registered content detectors until
3469 // a match is found. Priority is provided by their relative order.
3470 for (ContentDetectorList::const_iterator it = content_detectors_.begin();
3471 it != content_detectors_.end(); ++it) {
3472 ContentDetector::Result content = (*it)->FindTappedContent(touch_hit);
3473 if (content.valid) {
3474 return WebContentDetectionResult(content.content_boundaries,
3475 base::UTF8ToUTF16(content.text), content.intent_url);
3478 return WebContentDetectionResult();
3481 void RenderViewImpl::scheduleContentIntent(const WebURL& intent) {
3482 // Introduce a short delay so that the user can notice the content.
3483 base::MessageLoop::current()->PostDelayedTask(
3484 FROM_HERE,
3485 base::Bind(&RenderViewImpl::LaunchAndroidContentIntent,
3486 AsWeakPtr(),
3487 intent,
3488 expected_content_intent_id_),
3489 base::TimeDelta::FromMilliseconds(kContentIntentDelayMilliseconds));
3492 void RenderViewImpl::cancelScheduledContentIntents() {
3493 ++expected_content_intent_id_;
3496 void RenderViewImpl::LaunchAndroidContentIntent(const GURL& intent,
3497 size_t request_id) {
3498 if (request_id != expected_content_intent_id_)
3499 return;
3501 // Remove the content highlighting if any.
3502 ScheduleComposite();
3504 if (!intent.is_empty())
3505 Send(new ViewHostMsg_StartContentIntent(routing_id_, intent));
3508 bool RenderViewImpl::openDateTimeChooser(
3509 const blink::WebDateTimeChooserParams& params,
3510 blink::WebDateTimeChooserCompletion* completion) {
3511 // JavaScript may try to open a date time chooser while one is already open.
3512 if (date_time_picker_client_)
3513 return false;
3514 date_time_picker_client_.reset(
3515 new RendererDateTimePicker(this, params, completion));
3516 return date_time_picker_client_->Open();
3519 void RenderViewImpl::DismissDateTimeDialog() {
3520 DCHECK(date_time_picker_client_);
3521 date_time_picker_client_.reset(NULL);
3524 #endif // defined(OS_ANDROID)
3526 void RenderViewImpl::OnShowContextMenu(
3527 ui::MenuSourceType source_type, const gfx::Point& location) {
3528 context_menu_source_type_ = source_type;
3529 has_host_context_menu_location_ = true;
3530 host_context_menu_location_ = location;
3531 if (webview())
3532 webview()->showContextMenu();
3533 has_host_context_menu_location_ = false;
3536 void RenderViewImpl::OnEnableViewSourceMode() {
3537 if (!webview())
3538 return;
3539 WebFrame* main_frame = webview()->mainFrame();
3540 if (!main_frame)
3541 return;
3542 main_frame->enableViewSourceMode(true);
3545 #if defined(OS_ANDROID) || defined(USE_AURA)
3546 bool RenderViewImpl::didTapMultipleTargets(
3547 const WebSize& inner_viewport_offset,
3548 const WebRect& touch_rect,
3549 const WebVector<WebRect>& target_rects) {
3550 DCHECK(switches::IsLinkDisambiguationPopupEnabled());
3552 // Never show a disambiguation popup when accessibility is enabled,
3553 // as this interferes with "touch exploration".
3554 AccessibilityMode accessibility_mode =
3555 GetMainRenderFrame()->accessibility_mode();
3556 bool matches_accessibility_mode_complete =
3557 (accessibility_mode & AccessibilityModeComplete) ==
3558 AccessibilityModeComplete;
3559 if (matches_accessibility_mode_complete)
3560 return false;
3562 // The touch_rect, target_rects and zoom_rect are in the outer viewport
3563 // reference frame.
3564 gfx::Rect zoom_rect;
3565 float new_total_scale =
3566 DisambiguationPopupHelper::ComputeZoomAreaAndScaleFactor(
3567 touch_rect, target_rects, GetSize(),
3568 gfx::Rect(webview()->mainFrame()->visibleContentRect()).size(),
3569 device_scale_factor_ * webview()->pageScaleFactor(), &zoom_rect);
3570 if (!new_total_scale || zoom_rect.IsEmpty())
3571 return false;
3573 bool handled = false;
3574 switch (renderer_preferences_.tap_multiple_targets_strategy) {
3575 case TAP_MULTIPLE_TARGETS_STRATEGY_ZOOM:
3576 handled = webview()->zoomToMultipleTargetsRect(zoom_rect);
3577 break;
3578 case TAP_MULTIPLE_TARGETS_STRATEGY_POPUP: {
3579 gfx::Size canvas_size =
3580 gfx::ToCeiledSize(gfx::ScaleSize(zoom_rect.size(), new_total_scale));
3581 cc::SharedBitmapManager* manager =
3582 RenderThreadImpl::current()->shared_bitmap_manager();
3583 scoped_ptr<cc::SharedBitmap> shared_bitmap =
3584 manager->AllocateSharedBitmap(canvas_size);
3585 CHECK(!!shared_bitmap);
3587 SkBitmap bitmap;
3588 SkImageInfo info = SkImageInfo::MakeN32Premul(canvas_size.width(),
3589 canvas_size.height());
3590 bitmap.installPixels(info, shared_bitmap->pixels(), info.minRowBytes());
3591 SkCanvas canvas(bitmap);
3593 // TODO(trchen): Cleanup the device scale factor mess.
3594 // device scale will be applied in WebKit
3595 // --> zoom_rect doesn't include device scale,
3596 // but WebKit will still draw on zoom_rect * device_scale_factor_
3597 canvas.scale(new_total_scale / device_scale_factor_,
3598 new_total_scale / device_scale_factor_);
3599 canvas.translate(-zoom_rect.x() * device_scale_factor_,
3600 -zoom_rect.y() * device_scale_factor_);
3602 DCHECK(webwidget_->isAcceleratedCompositingActive());
3603 // TODO(aelias): The disambiguation popup should be composited so we
3604 // don't have to call this method.
3605 webwidget_->paintCompositedDeprecated(&canvas, zoom_rect);
3608 gfx::Rect zoom_rect_in_screen =
3609 zoom_rect - gfx::Vector2d(inner_viewport_offset.width,
3610 inner_viewport_offset.height);
3612 gfx::Rect physical_window_zoom_rect = gfx::ToEnclosingRect(
3613 ClientRectToPhysicalWindowRect(gfx::RectF(zoom_rect_in_screen)));
3615 Send(new ViewHostMsg_ShowDisambiguationPopup(routing_id_,
3616 physical_window_zoom_rect,
3617 canvas_size,
3618 shared_bitmap->id()));
3619 cc::SharedBitmapId id = shared_bitmap->id();
3620 disambiguation_bitmaps_[id] = shared_bitmap.release();
3621 handled = true;
3622 break;
3624 case TAP_MULTIPLE_TARGETS_STRATEGY_NONE:
3625 // No-op.
3626 break;
3629 return handled;
3631 #endif // defined(OS_ANDROID) || defined(USE_AURA)
3633 unsigned RenderViewImpl::GetLocalSessionHistoryLengthForTesting() const {
3634 return history_list_length_;
3637 void RenderViewImpl::SetFocusAndActivateForTesting(bool enable) {
3638 if (enable) {
3639 if (has_focus())
3640 return;
3641 OnSetActive(true);
3642 OnSetFocus(true);
3643 } else {
3644 if (!has_focus())
3645 return;
3646 OnSetFocus(false);
3647 OnSetActive(false);
3651 void RenderViewImpl::SetDeviceScaleFactorForTesting(float factor) {
3652 ViewMsg_Resize_Params params;
3653 params.screen_info = screen_info_;
3654 params.screen_info.deviceScaleFactor = factor;
3655 params.new_size = size();
3656 params.visible_viewport_size = visible_viewport_size_;
3657 params.physical_backing_size =
3658 gfx::ToCeiledSize(gfx::ScaleSize(size(), factor));
3659 params.top_controls_shrink_blink_size = false;
3660 params.top_controls_height = 0.f;
3661 params.resizer_rect = WebRect();
3662 params.is_fullscreen_granted = is_fullscreen_granted();
3663 params.display_mode = display_mode_;
3664 OnResize(params);
3667 void RenderViewImpl::SetDeviceColorProfileForTesting(
3668 const std::vector<char>& color_profile) {
3669 SetDeviceColorProfile(color_profile);
3672 void RenderViewImpl::ForceResizeForTesting(const gfx::Size& new_size) {
3673 gfx::Rect new_window_rect(rootWindowRect().x,
3674 rootWindowRect().y,
3675 new_size.width(),
3676 new_size.height());
3677 SetWindowRectSynchronously(new_window_rect);
3680 void RenderViewImpl::UseSynchronousResizeModeForTesting(bool enable) {
3681 resizing_mode_selector_->set_is_synchronous_mode(enable);
3684 void RenderViewImpl::EnableAutoResizeForTesting(const gfx::Size& min_size,
3685 const gfx::Size& max_size) {
3686 OnEnableAutoResize(min_size, max_size);
3689 void RenderViewImpl::DisableAutoResizeForTesting(const gfx::Size& new_size) {
3690 OnDisableAutoResize(new_size);
3693 void RenderViewImpl::OnReleaseDisambiguationPopupBitmap(
3694 const cc::SharedBitmapId& id) {
3695 BitmapMap::iterator it = disambiguation_bitmaps_.find(id);
3696 DCHECK(it != disambiguation_bitmaps_.end());
3697 delete it->second;
3698 disambiguation_bitmaps_.erase(it);
3701 void RenderViewImpl::DidCommitCompositorFrame() {
3702 RenderWidget::DidCommitCompositorFrame();
3703 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidCommitCompositorFrame());
3706 void RenderViewImpl::SendUpdateFaviconURL(const std::vector<FaviconURL>& urls) {
3707 if (!urls.empty())
3708 Send(new ViewHostMsg_UpdateFaviconURL(routing_id_, urls));
3711 void RenderViewImpl::DidStopLoadingIcons() {
3712 int icon_types = WebIconURL::TypeFavicon | WebIconURL::TypeTouchPrecomposed |
3713 WebIconURL::TypeTouch;
3715 // Favicons matter only for the top-level frame. If it is a WebRemoteFrame,
3716 // just return early.
3717 if (webview()->mainFrame()->isWebRemoteFrame())
3718 return;
3720 WebVector<WebIconURL> icon_urls =
3721 webview()->mainFrame()->iconURLs(icon_types);
3723 std::vector<FaviconURL> urls;
3724 for (size_t i = 0; i < icon_urls.size(); i++) {
3725 WebURL url = icon_urls[i].iconURL();
3726 std::vector<gfx::Size> sizes;
3727 ConvertToFaviconSizes(icon_urls[i].sizes(), &sizes);
3728 if (!url.isEmpty())
3729 urls.push_back(
3730 FaviconURL(url, ToFaviconType(icon_urls[i].iconType()), sizes));
3732 SendUpdateFaviconURL(urls);
3735 } // namespace content