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"
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:
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"
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"
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"
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
;
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
;
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
;
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;
321 static RenderViewImpl
* (*g_create_render_view_impl
)(
322 CompositorDependencies
* compositor_deps
,
323 const ViewMsg_New_Params
&) = nullptr;
326 Referrer
RenderViewImpl::GetReferrerFromRequest(
328 const WebURLRequest
& request
) {
329 return Referrer(GURL(request
.httpHeaderField(WebString::fromUTF8("Referer"))),
330 request
.referrerPolicy());
334 WindowOpenDisposition
RenderViewImpl::NavigationPolicyToDisposition(
335 WebNavigationPolicy policy
) {
337 case blink::WebNavigationPolicyIgnore
:
338 return IGNORE_ACTION
;
339 case blink::WebNavigationPolicyDownload
:
341 case blink::WebNavigationPolicyCurrentTab
:
343 case blink::WebNavigationPolicyNewBackgroundTab
:
344 return NEW_BACKGROUND_TAB
;
345 case blink::WebNavigationPolicyNewForegroundTab
:
346 return NEW_FOREGROUND_TAB
;
347 case blink::WebNavigationPolicyNewWindow
:
349 case blink::WebNavigationPolicyNewPopup
:
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.
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
;
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
))
377 if (command_line
.HasSwitch(switches::kEnablePreferCompositingToLCDText
))
379 if (!compositor_deps
->IsLcdTextEnabled())
381 return DeviceScaleEnsuresTextQuality(device_scale_factor
);
384 static FaviconURL::IconType
ToFaviconType(blink::WebIconURL::Type 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
)
414 FileChooserParams params
;
415 WebFileChooserCompletion
* completion
; // MAY BE NULL to skip callback.
420 class WebWidgetLockTarget
: public MouseLockDispatcher::LockTarget
{
422 explicit WebWidgetLockTarget(blink::WebWidget
* webwidget
)
423 : webwidget_(webwidget
) {}
425 void OnLockMouseACK(bool succeeded
) override
{
427 webwidget_
->didAcquirePointerLock();
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().
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();
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();
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();
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
);
514 result
.setItems(item_list
);
515 result
.setFilesystemId(drop_data
.filesystem_id
);
519 typedef void (*SetFontFamilyWrapper
)(blink::WebSettings
*,
520 const base::string16
&,
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
;
581 return USCRIPT_HANGUL
;
587 void ApplyFontsFromMap(const ScriptFontFamilyMap
& map
,
588 SetFontFamilyWrapper setter
,
589 WebSettings
* settings
) {
590 for (ScriptFontFamilyMap::const_iterator it
= map
.begin(); it
!= map
.end();
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
))
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 // Looks up and returns the WebFrame corresponding to a given opener frame
618 // routing ID. Also stores the opener's RenderView routing ID into
619 // |opener_view_routing_id|.
620 WebFrame
* ResolveOpener(int opener_frame_routing_id
,
621 int* opener_view_routing_id
) {
622 *opener_view_routing_id
= MSG_ROUTING_NONE
;
623 if (opener_frame_routing_id
== MSG_ROUTING_NONE
)
626 // Opener routing ID could refer to either a RenderFrameProxy or a
627 // RenderFrame, so need to check both.
628 RenderFrameProxy
* opener_proxy
=
629 RenderFrameProxy::FromRoutingID(opener_frame_routing_id
);
631 *opener_view_routing_id
= opener_proxy
->render_view()->GetRoutingID();
633 // TODO(nasko,alexmos): This check won't be needed once swapped-out:// is
635 if (opener_proxy
->IsMainFrameDetachedFromTree()) {
636 DCHECK(!SiteIsolationPolicy::IsSwappedOutStateForbidden());
637 return opener_proxy
->render_view()->webview()->mainFrame();
639 return opener_proxy
->web_frame();
643 RenderFrameImpl
* opener_frame
=
644 RenderFrameImpl::FromRoutingID(opener_frame_routing_id
);
646 *opener_view_routing_id
= opener_frame
->render_view()->GetRoutingID();
647 return opener_frame
->GetWebFrame();
655 RenderViewImpl::RenderViewImpl(CompositorDependencies
* compositor_deps
,
656 const ViewMsg_New_Params
& params
)
657 : RenderWidget(compositor_deps
,
658 blink::WebPopupTypeNone
,
659 params
.initial_size
.screen_info
,
662 params
.never_visible
),
663 webkit_preferences_(params
.web_preferences
),
664 send_content_state_immediately_(false),
665 enabled_bindings_(0),
666 send_preferred_size_changes_(false),
667 navigation_gesture_(NavigationGestureUnknown
),
668 opened_by_user_gesture_(true),
669 opener_suppressed_(false),
670 suppress_dialogs_until_swap_out_(false),
672 next_page_id_(params
.next_page_id
),
673 history_list_offset_(-1),
674 history_list_length_(0),
675 frames_in_progress_(0),
676 target_url_status_(TARGET_NONE
),
677 uses_temporary_zoom_level_(false),
678 #if defined(OS_ANDROID)
679 top_controls_constraints_(TOP_CONTROLS_STATE_BOTH
),
681 has_scrolled_focused_editable_node_into_rect_(false),
682 main_render_frame_(nullptr),
683 speech_recognition_dispatcher_(NULL
),
684 mouse_lock_dispatcher_(NULL
),
685 #if defined(OS_ANDROID)
686 expected_content_intent_id_(0),
689 focused_plugin_id_(-1),
691 #if defined(ENABLE_PLUGINS)
692 plugin_find_handler_(NULL
),
693 focused_pepper_plugin_(NULL
),
694 pepper_last_mouse_event_target_(NULL
),
696 enumeration_completion_id_(0),
697 session_storage_namespace_id_(params
.session_storage_namespace_id
),
698 page_scale_factor_is_one_(true) {
701 void RenderViewImpl::Initialize(const ViewMsg_New_Params
& params
,
702 bool was_created_by_renderer
) {
703 routing_id_
= params
.view_id
;
704 surface_id_
= params
.surface_id
;
706 int opener_view_routing_id
;
707 WebFrame
* opener_frame
=
708 ResolveOpener(params
.opener_frame_route_id
, &opener_view_routing_id
);
709 if (opener_view_routing_id
!= MSG_ROUTING_NONE
&& was_created_by_renderer
)
710 opener_id_
= opener_view_routing_id
;
712 display_mode_
= params
.initial_size
.display_mode
;
714 // Ensure we start with a valid next_page_id_ from the browser.
715 DCHECK_GE(next_page_id_
, 0);
717 if (params
.main_frame_routing_id
!= MSG_ROUTING_NONE
) {
718 main_render_frame_
= RenderFrameImpl::Create(
719 this, params
.main_frame_routing_id
);
720 // The main frame WebLocalFrame object is closed by
721 // RenderFrameImpl::frameDetached().
722 WebLocalFrame
* web_frame
= WebLocalFrame::create(
723 blink::WebTreeScopeType::Document
, main_render_frame_
);
724 main_render_frame_
->SetWebFrame(web_frame
);
727 webwidget_
= WebView::create(this);
728 webwidget_mouse_lock_target_
.reset(new WebWidgetLockTarget(webwidget_
));
730 g_view_map
.Get().insert(std::make_pair(webview(), this));
731 g_routing_id_view_map
.Get().insert(std::make_pair(routing_id_
, this));
733 const base::CommandLine
& command_line
=
734 *base::CommandLine::ForCurrentProcess();
736 if (command_line
.HasSwitch(switches::kStatsCollectionController
))
737 stats_collection_observer_
.reset(new StatsCollectionObserver(this));
739 RenderFrameProxy
* proxy
= NULL
;
740 if (params
.proxy_routing_id
!= MSG_ROUTING_NONE
) {
741 CHECK(params
.swapped_out
);
742 if (main_render_frame_
) {
743 proxy
= RenderFrameProxy::CreateProxyToReplaceFrame(
744 main_render_frame_
, params
.proxy_routing_id
,
745 blink::WebTreeScopeType::Document
);
746 main_render_frame_
->set_render_frame_proxy(proxy
);
748 proxy
= RenderFrameProxy::CreateFrameProxy(
749 params
.proxy_routing_id
,
752 params
.replicated_frame_state
);
756 // When not using swapped out state, just use the WebRemoteFrame as the main
758 if (proxy
&& SiteIsolationPolicy::IsSwappedOutStateForbidden()) {
759 webview()->setMainFrame(proxy
->web_frame());
760 // Initialize the WebRemoteFrame with information replicated from the
762 proxy
->SetReplicatedState(params
.replicated_frame_state
);
764 webview()->setMainFrame(main_render_frame_
->GetWebFrame());
766 if (main_render_frame_
)
767 main_render_frame_
->Initialize();
769 #if defined(OS_ANDROID)
770 content_detectors_
.push_back(linked_ptr
<ContentDetector
>(
771 new AddressDetector()));
772 const std::string
& contry_iso
=
773 params
.renderer_preferences
.network_contry_iso
;
774 if (!contry_iso
.empty()) {
775 content_detectors_
.push_back(linked_ptr
<ContentDetector
>(
776 new PhoneNumberDetector(contry_iso
)));
778 content_detectors_
.push_back(linked_ptr
<ContentDetector
>(
779 new EmailDetector()));
782 RenderThread::Get()->AddRoute(routing_id_
, this);
783 // Take a reference on behalf of the RenderThread. This will be balanced
784 // when we receive ViewMsg_Close in the RenderWidget (which RenderView
787 if (RenderThreadImpl::current()) {
788 RenderThreadImpl::current()->WidgetCreated();
790 RenderThreadImpl::current()->WidgetHidden();
793 // If this is a popup, we must wait for the CreatingNew_ACK message before
794 // completing initialization. Otherwise, we can finish it now.
795 if (opener_id_
== MSG_ROUTING_NONE
) {
800 webview()->setDeviceScaleFactor(device_scale_factor_
);
801 webview()->setDisplayMode(display_mode_
);
802 webview()->settings()->setPreferCompositingToLCDTextEnabled(
803 PreferCompositingToLCDText(compositor_deps_
, device_scale_factor_
));
804 webview()->settings()->setThreadedScrollingEnabled(
805 !command_line
.HasSwitch(switches::kDisableThreadedScrolling
));
806 webview()->settings()->setRootLayerScrolls(
807 command_line
.HasSwitch(switches::kRootLayerScrolls
));
809 ApplyWebPreferencesInternal(webkit_preferences_
, webview(), compositor_deps_
);
811 if (switches::IsTouchDragDropEnabled())
812 webview()->settings()->setTouchDragDropEnabled(true);
814 if (switches::IsTouchEditingEnabled())
815 webview()->settings()->setTouchEditingEnabled(true);
817 WebSettings::SelectionStrategyType selection_strategy
=
818 WebSettings::SelectionStrategyType::Character
;
819 const std::string selection_strategy_str
=
820 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
821 switches::kTouchTextSelectionStrategy
);
822 if (selection_strategy_str
== "direction")
823 selection_strategy
= WebSettings::SelectionStrategyType::Direction
;
824 webview()->settings()->setSelectionStrategy(selection_strategy
);
826 // Set the main frame's name. Only needs to be done for WebLocalFrames,
827 // since the remote case was handled as part of SetReplicatedState on the
829 if (!params
.replicated_frame_state
.name
.empty() &&
830 webview()->mainFrame()->isWebLocalFrame()) {
831 webview()->mainFrame()->setName(
832 blink::WebString::fromUTF8(params
.replicated_frame_state
.name
));
835 // TODO(davidben): Move this state from Blink into content.
836 if (params
.window_was_created_with_opener
)
837 webview()->setOpenedByDOM();
839 OnSetRendererPrefs(params
.renderer_preferences
);
841 ApplyBlinkSettings(command_line
, webview()->settings());
843 if (!params
.enable_auto_resize
) {
844 OnResize(params
.initial_size
);
846 OnEnableAutoResize(params
.min_size
, params
.max_size
);
849 new MHTMLGenerator(this);
850 #if defined(OS_MACOSX)
851 new TextInputClientObserver(this);
852 #endif // defined(OS_MACOSX)
854 // The next group of objects all implement RenderViewObserver, so are deleted
855 // along with the RenderView automatically.
856 mouse_lock_dispatcher_
= new RenderViewMouseLockDispatcher(this);
858 history_controller_
.reset(new HistoryController(this));
860 new IdleUserDetector(this);
862 if (command_line
.HasSwitch(switches::kDomAutomationController
))
863 enabled_bindings_
|= BINDINGS_POLICY_DOM_AUTOMATION
;
864 if (command_line
.HasSwitch(switches::kStatsCollectionController
))
865 enabled_bindings_
|= BINDINGS_POLICY_STATS_COLLECTION
;
867 GetContentClient()->renderer()->RenderViewCreated(this);
869 // If we have an opener_frame but we weren't created by a renderer, then it's
870 // the browser asking us to set our opener to another frame.
871 if (opener_frame
&& !was_created_by_renderer
)
872 webview()->mainFrame()->setOpener(opener_frame
);
874 // If we are initially swapped out, navigate to kSwappedOutURL.
875 // This ensures we are in a unique origin that others cannot script.
876 if (is_swapped_out_
&& webview()->mainFrame()->isWebLocalFrame())
877 main_render_frame_
->NavigateToSwappedOutURL();
880 RenderViewImpl::~RenderViewImpl() {
881 for (BitmapMap::iterator it
= disambiguation_bitmaps_
.begin();
882 it
!= disambiguation_bitmaps_
.end();
886 // If file chooser is still waiting for answer, dispatch empty answer.
887 while (!file_chooser_completions_
.empty()) {
888 if (file_chooser_completions_
.front()->completion
) {
889 file_chooser_completions_
.front()->completion
->didChooseFile(
890 WebVector
<WebString
>());
892 file_chooser_completions_
.pop_front();
895 #if defined(OS_ANDROID)
896 // The date/time picker client is both a scoped_ptr member of this class and
897 // a RenderViewObserver. Reset it to prevent double deletion.
898 date_time_picker_client_
.reset();
902 // Make sure we are no longer referenced by the ViewMap or RoutingIDViewMap.
903 ViewMap
* views
= g_view_map
.Pointer();
904 for (ViewMap::iterator it
= views
->begin(); it
!= views
->end(); ++it
)
905 DCHECK_NE(this, it
->second
) << "Failed to call Close?";
906 RoutingIDViewMap
* routing_id_views
= g_routing_id_view_map
.Pointer();
907 for (RoutingIDViewMap::iterator it
= routing_id_views
->begin();
908 it
!= routing_id_views
->end(); ++it
)
909 DCHECK_NE(this, it
->second
) << "Failed to call Close?";
912 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, RenderViewGone());
913 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, OnDestruct());
917 RenderViewImpl
* RenderViewImpl::FromWebView(WebView
* webview
) {
918 ViewMap
* views
= g_view_map
.Pointer();
919 ViewMap::iterator it
= views
->find(webview
);
920 return it
== views
->end() ? NULL
: it
->second
;
924 RenderView
* RenderView::FromWebView(blink::WebView
* webview
) {
925 return RenderViewImpl::FromWebView(webview
);
929 RenderViewImpl
* RenderViewImpl::FromRoutingID(int32 routing_id
) {
930 RoutingIDViewMap
* views
= g_routing_id_view_map
.Pointer();
931 RoutingIDViewMap::iterator it
= views
->find(routing_id
);
932 return it
== views
->end() ? NULL
: it
->second
;
936 RenderView
* RenderView::FromRoutingID(int routing_id
) {
937 return RenderViewImpl::FromRoutingID(routing_id
);
941 size_t RenderView::GetRenderViewCount() {
942 return g_view_map
.Get().size();
946 void RenderView::ForEach(RenderViewVisitor
* visitor
) {
947 ViewMap
* views
= g_view_map
.Pointer();
948 for (ViewMap::iterator it
= views
->begin(); it
!= views
->end(); ++it
) {
949 if (!visitor
->Visit(it
->second
))
955 void RenderView::ApplyWebPreferences(const WebPreferences
& prefs
,
957 WebSettings
* settings
= web_view
->settings();
958 ApplyFontsFromMap(prefs
.standard_font_family_map
,
959 SetStandardFontFamilyWrapper
, settings
);
960 ApplyFontsFromMap(prefs
.fixed_font_family_map
,
961 SetFixedFontFamilyWrapper
, settings
);
962 ApplyFontsFromMap(prefs
.serif_font_family_map
,
963 SetSerifFontFamilyWrapper
, settings
);
964 ApplyFontsFromMap(prefs
.sans_serif_font_family_map
,
965 SetSansSerifFontFamilyWrapper
, settings
);
966 ApplyFontsFromMap(prefs
.cursive_font_family_map
,
967 SetCursiveFontFamilyWrapper
, settings
);
968 ApplyFontsFromMap(prefs
.fantasy_font_family_map
,
969 SetFantasyFontFamilyWrapper
, settings
);
970 ApplyFontsFromMap(prefs
.pictograph_font_family_map
,
971 SetPictographFontFamilyWrapper
, settings
);
972 settings
->setDefaultFontSize(prefs
.default_font_size
);
973 settings
->setDefaultFixedFontSize(prefs
.default_fixed_font_size
);
974 settings
->setMinimumFontSize(prefs
.minimum_font_size
);
975 settings
->setMinimumLogicalFontSize(prefs
.minimum_logical_font_size
);
976 settings
->setDefaultTextEncodingName(
977 base::ASCIIToUTF16(prefs
.default_encoding
));
978 settings
->setJavaScriptEnabled(prefs
.javascript_enabled
);
979 settings
->setWebSecurityEnabled(prefs
.web_security_enabled
);
980 settings
->setJavaScriptCanOpenWindowsAutomatically(
981 prefs
.javascript_can_open_windows_automatically
);
982 settings
->setLoadsImagesAutomatically(prefs
.loads_images_automatically
);
983 settings
->setImagesEnabled(prefs
.images_enabled
);
984 settings
->setPluginsEnabled(prefs
.plugins_enabled
);
985 settings
->setDOMPasteAllowed(prefs
.dom_paste_enabled
);
986 settings
->setUsesEncodingDetector(prefs
.uses_universal_detector
);
987 settings
->setTextAreasAreResizable(prefs
.text_areas_are_resizable
);
988 settings
->setAllowScriptsToCloseWindows(prefs
.allow_scripts_to_close_windows
);
989 settings
->setDownloadableBinaryFontsEnabled(prefs
.remote_fonts_enabled
);
990 settings
->setJavaScriptCanAccessClipboard(
991 prefs
.javascript_can_access_clipboard
);
992 WebRuntimeFeatures::enableXSLT(prefs
.xslt_enabled
);
993 WebRuntimeFeatures::enableSlimmingPaint(prefs
.slimming_paint_enabled
);
994 WebRuntimeFeatures::enableSlimmingPaintV2(prefs
.slimming_paint_v2_enabled
);
995 settings
->setXSSAuditorEnabled(prefs
.xss_auditor_enabled
);
996 settings
->setDNSPrefetchingEnabled(prefs
.dns_prefetching_enabled
);
997 settings
->setLocalStorageEnabled(prefs
.local_storage_enabled
);
998 settings
->setSyncXHRInDocumentsEnabled(prefs
.sync_xhr_in_documents_enabled
);
999 WebRuntimeFeatures::enableDatabase(prefs
.databases_enabled
);
1000 settings
->setOfflineWebApplicationCacheEnabled(
1001 prefs
.application_cache_enabled
);
1002 settings
->setCaretBrowsingEnabled(prefs
.caret_browsing_enabled
);
1003 settings
->setHyperlinkAuditingEnabled(prefs
.hyperlink_auditing_enabled
);
1004 settings
->setCookieEnabled(prefs
.cookie_enabled
);
1005 settings
->setNavigateOnDragDrop(prefs
.navigate_on_drag_drop
);
1007 settings
->setJavaEnabled(prefs
.java_enabled
);
1009 // By default, allow_universal_access_from_file_urls is set to false and thus
1010 // we mitigate attacks from local HTML files by not granting file:// URLs
1011 // universal access. Only test shell will enable this.
1012 settings
->setAllowUniversalAccessFromFileURLs(
1013 prefs
.allow_universal_access_from_file_urls
);
1014 settings
->setAllowFileAccessFromFileURLs(
1015 prefs
.allow_file_access_from_file_urls
);
1017 // Enable the web audio API if requested on the command line.
1018 settings
->setWebAudioEnabled(prefs
.webaudio_enabled
);
1020 // Enable experimental WebGL support if requested on command line
1021 // and support is compiled in.
1022 settings
->setExperimentalWebGLEnabled(prefs
.experimental_webgl_enabled
);
1024 // Disable GL multisampling if requested on command line.
1025 settings
->setOpenGLMultisamplingEnabled(prefs
.gl_multisampling_enabled
);
1027 // Enable WebGL errors to the JS console if requested.
1028 settings
->setWebGLErrorsToConsoleEnabled(
1029 prefs
.webgl_errors_to_console_enabled
);
1031 // Uses the mock theme engine for scrollbars.
1032 settings
->setMockScrollbarsEnabled(prefs
.mock_scrollbars_enabled
);
1034 // Enable gpu-accelerated 2d canvas if requested on the command line.
1035 settings
->setAccelerated2dCanvasEnabled(prefs
.accelerated_2d_canvas_enabled
);
1037 settings
->setMinimumAccelerated2dCanvasSize(
1038 prefs
.minimum_accelerated_2d_canvas_size
);
1040 // Disable antialiasing for 2d canvas if requested on the command line.
1041 settings
->setAntialiased2dCanvasEnabled(
1042 !prefs
.antialiased_2d_canvas_disabled
);
1044 // Enabled antialiasing of clips for 2d canvas if requested on the command
1046 settings
->setAntialiasedClips2dCanvasEnabled(
1047 prefs
.antialiased_clips_2d_canvas_enabled
);
1049 // Set MSAA sample count for 2d canvas if requested on the command line (or
1050 // default value if not).
1051 settings
->setAccelerated2dCanvasMSAASampleCount(
1052 prefs
.accelerated_2d_canvas_msaa_sample_count
);
1054 settings
->setAsynchronousSpellCheckingEnabled(
1055 prefs
.asynchronous_spell_checking_enabled
);
1056 settings
->setUnifiedTextCheckerEnabled(prefs
.unified_textchecker_enabled
);
1058 // Tabs to link is not part of the settings. WebCore calls
1059 // ChromeClient::tabsToLinks which is part of the glue code.
1060 web_view
->setTabsToLinks(prefs
.tabs_to_links
);
1062 settings
->setAllowDisplayOfInsecureContent(
1063 prefs
.allow_displaying_insecure_content
);
1064 settings
->setAllowRunningOfInsecureContent(
1065 prefs
.allow_running_insecure_content
);
1066 settings
->setDisableReadingFromCanvas(prefs
.disable_reading_from_canvas
);
1067 settings
->setStrictMixedContentChecking(prefs
.strict_mixed_content_checking
);
1069 settings
->setStrictlyBlockBlockableMixedContent(
1070 prefs
.strictly_block_blockable_mixed_content
);
1072 settings
->setStrictMixedContentCheckingForPlugin(
1073 prefs
.block_mixed_plugin_content
);
1075 settings
->setStrictPowerfulFeatureRestrictions(
1076 prefs
.strict_powerful_feature_restrictions
);
1077 settings
->setPasswordEchoEnabled(prefs
.password_echo_enabled
);
1078 settings
->setShouldPrintBackgrounds(prefs
.should_print_backgrounds
);
1079 settings
->setShouldClearDocumentBackground(
1080 prefs
.should_clear_document_background
);
1081 settings
->setEnableScrollAnimator(prefs
.enable_scroll_animator
);
1083 WebRuntimeFeatures::enableTouch(prefs
.touch_enabled
);
1084 settings
->setMaxTouchPoints(prefs
.pointer_events_max_touch_points
);
1085 settings
->setAvailablePointerTypes(prefs
.available_pointer_types
);
1086 settings
->setPrimaryPointerType(
1087 static_cast<WebSettings::PointerType
>(prefs
.primary_pointer_type
));
1088 settings
->setAvailableHoverTypes(prefs
.available_hover_types
);
1089 settings
->setPrimaryHoverType(
1090 static_cast<WebSettings::HoverType
>(prefs
.primary_hover_type
));
1091 settings
->setDeviceSupportsTouch(prefs
.device_supports_touch
);
1092 settings
->setDeviceSupportsMouse(prefs
.device_supports_mouse
);
1093 settings
->setEnableTouchAdjustment(prefs
.touch_adjustment_enabled
);
1094 settings
->setMultiTargetTapNotificationEnabled(
1095 switches::IsLinkDisambiguationPopupEnabled());
1097 WebRuntimeFeatures::enableImageColorProfiles(
1098 prefs
.image_color_profiles_enabled
);
1099 settings
->setShouldRespectImageOrientation(
1100 prefs
.should_respect_image_orientation
);
1102 settings
->setUnsafePluginPastingEnabled(false);
1103 settings
->setEditingBehavior(
1104 static_cast<WebSettings::EditingBehavior
>(prefs
.editing_behavior
));
1106 settings
->setSupportsMultipleWindows(prefs
.supports_multiple_windows
);
1108 settings
->setInvertViewportScrollOrder(prefs
.invert_viewport_scroll_order
);
1109 settings
->setViewportEnabled(prefs
.viewport_enabled
);
1110 settings
->setLoadWithOverviewMode(prefs
.initialize_at_minimum_page_scale
);
1111 settings
->setViewportMetaEnabled(prefs
.viewport_meta_enabled
);
1112 settings
->setMainFrameResizesAreOrientationChanges(
1113 prefs
.main_frame_resizes_are_orientation_changes
);
1115 settings
->setSmartInsertDeleteEnabled(prefs
.smart_insert_delete_enabled
);
1117 settings
->setSpatialNavigationEnabled(prefs
.spatial_navigation_enabled
);
1119 settings
->setSelectionIncludesAltImageText(true);
1121 settings
->setV8CacheOptions(
1122 static_cast<WebSettings::V8CacheOptions
>(prefs
.v8_cache_options
));
1124 settings
->setImageAnimationPolicy(
1125 static_cast<WebSettings::ImageAnimationPolicy
>(prefs
.animation_policy
));
1127 // Needs to happen before setIgnoreVIewportTagScaleLimits below.
1128 web_view
->setDefaultPageScaleLimits(
1129 prefs
.default_minimum_page_scale_factor
,
1130 prefs
.default_maximum_page_scale_factor
);
1132 #if defined(OS_ANDROID)
1133 settings
->setAllowCustomScrollbarInMainFrame(false);
1134 settings
->setTextAutosizingEnabled(prefs
.text_autosizing_enabled
);
1135 settings
->setAccessibilityFontScaleFactor(prefs
.font_scale_factor
);
1136 settings
->setDeviceScaleAdjustment(prefs
.device_scale_adjustment
);
1137 settings
->setFullscreenSupported(prefs
.fullscreen_supported
);
1138 web_view
->setIgnoreViewportTagScaleLimits(prefs
.force_enable_zoom
);
1139 settings
->setAutoZoomFocusedNodeToLegibleScale(true);
1140 settings
->setDoubleTapToZoomEnabled(prefs
.double_tap_to_zoom_enabled
);
1141 settings
->setMediaControlsOverlayPlayButtonEnabled(true);
1142 settings
->setMediaPlaybackRequiresUserGesture(
1143 prefs
.user_gesture_required_for_media_playback
);
1144 settings
->setDefaultVideoPosterURL(
1145 base::ASCIIToUTF16(prefs
.default_video_poster_url
.spec()));
1146 settings
->setSupportDeprecatedTargetDensityDPI(
1147 prefs
.support_deprecated_target_density_dpi
);
1148 settings
->setUseLegacyBackgroundSizeShorthandBehavior(
1149 prefs
.use_legacy_background_size_shorthand_behavior
);
1150 settings
->setWideViewportQuirkEnabled(prefs
.wide_viewport_quirk
);
1151 settings
->setUseWideViewport(prefs
.use_wide_viewport
);
1152 settings
->setForceZeroLayoutHeight(prefs
.force_zero_layout_height
);
1153 settings
->setViewportMetaLayoutSizeQuirk(
1154 prefs
.viewport_meta_layout_size_quirk
);
1155 settings
->setViewportMetaMergeContentQuirk(
1156 prefs
.viewport_meta_merge_content_quirk
);
1157 settings
->setViewportMetaNonUserScalableQuirk(
1158 prefs
.viewport_meta_non_user_scalable_quirk
);
1159 settings
->setViewportMetaZeroValuesQuirk(
1160 prefs
.viewport_meta_zero_values_quirk
);
1161 settings
->setClobberUserAgentInitialScaleQuirk(
1162 prefs
.clobber_user_agent_initial_scale_quirk
);
1163 settings
->setIgnoreMainFrameOverflowHiddenQuirk(
1164 prefs
.ignore_main_frame_overflow_hidden_quirk
);
1165 settings
->setReportScreenSizeInPhysicalPixelsQuirk(
1166 prefs
.report_screen_size_in_physical_pixels_quirk
);
1167 settings
->setPreferHiddenVolumeControls(true);
1169 bool record_full_layer
=
1170 RenderViewImpl::FromWebView(web_view
)
1171 ? RenderViewImpl::FromWebView(web_view
)->DoesRecordFullLayer()
1173 settings
->setMainFrameClipsContent(!record_full_layer
);
1175 settings
->setShrinksViewportContentToFit(true);
1176 settings
->setUseMobileViewportStyle(true);
1179 WebNetworkStateNotifier::setOnLine(prefs
.is_online
);
1180 WebNetworkStateNotifier::setWebConnectionType(
1181 NetConnectionTypeToWebConnectionType(prefs
.connection_type
));
1183 settings
->setPinchOverlayScrollbarThickness(
1184 prefs
.pinch_overlay_scrollbar_thickness
);
1185 settings
->setUseSolidColorScrollbars(prefs
.use_solid_color_scrollbars
);
1187 settings
->setShowContextMenuOnMouseUp(prefs
.context_menu_on_mouse_up
);
1189 #if defined(OS_MACOSX)
1190 settings
->setDoubleTapToZoomEnabled(true);
1191 web_view
->setMaximumLegibleScale(prefs
.default_maximum_page_scale_factor
);
1194 #if !defined(OS_ANDROID) && !defined(OS_MACOSX)
1195 // On platforms where the pinch viewport and the layout viewport can
1196 // both show scrollbars, hide pinch scrollbars when we are near minimum
1197 // page scale. (See http://crbug.com/446411 and http://crbug.com/515746.)
1198 settings
->setHidePinchScrollbarsNearMinScale(true);
1203 RenderViewImpl
* RenderViewImpl::Create(CompositorDependencies
* compositor_deps
,
1204 const ViewMsg_New_Params
& params
,
1205 bool was_created_by_renderer
) {
1206 DCHECK(params
.view_id
!= MSG_ROUTING_NONE
);
1207 RenderViewImpl
* render_view
= NULL
;
1208 if (g_create_render_view_impl
)
1209 render_view
= g_create_render_view_impl(compositor_deps
, params
);
1211 render_view
= new RenderViewImpl(compositor_deps
, params
);
1213 render_view
->Initialize(params
, was_created_by_renderer
);
1218 void RenderViewImpl::InstallCreateHook(RenderViewImpl
* (
1219 *create_render_view_impl
)(CompositorDependencies
* compositor_deps
,
1220 const ViewMsg_New_Params
&)) {
1221 CHECK(!g_create_render_view_impl
);
1222 g_create_render_view_impl
= create_render_view_impl
;
1225 void RenderViewImpl::AddObserver(RenderViewObserver
* observer
) {
1226 observers_
.AddObserver(observer
);
1229 void RenderViewImpl::RemoveObserver(RenderViewObserver
* observer
) {
1230 observer
->RenderViewGone();
1231 observers_
.RemoveObserver(observer
);
1234 blink::WebView
* RenderViewImpl::webview() const {
1235 return static_cast<blink::WebView
*>(webwidget());
1238 #if defined(ENABLE_PLUGINS)
1239 void RenderViewImpl::PepperInstanceCreated(
1240 PepperPluginInstanceImpl
* instance
) {
1241 active_pepper_instances_
.insert(instance
);
1243 RenderFrameImpl
* const render_frame
= instance
->render_frame();
1245 new FrameHostMsg_PepperInstanceCreated(render_frame
->GetRoutingID()));
1248 void RenderViewImpl::PepperInstanceDeleted(
1249 PepperPluginInstanceImpl
* instance
) {
1250 active_pepper_instances_
.erase(instance
);
1252 if (pepper_last_mouse_event_target_
== instance
)
1253 pepper_last_mouse_event_target_
= NULL
;
1254 if (focused_pepper_plugin_
== instance
)
1255 PepperFocusChanged(instance
, false);
1257 RenderFrameImpl
* const render_frame
= instance
->render_frame();
1260 new FrameHostMsg_PepperInstanceDeleted(render_frame
->GetRoutingID()));
1263 void RenderViewImpl::PepperFocusChanged(PepperPluginInstanceImpl
* instance
,
1266 focused_pepper_plugin_
= instance
;
1267 else if (focused_pepper_plugin_
== instance
)
1268 focused_pepper_plugin_
= NULL
;
1270 UpdateTextInputState(NO_SHOW_IME
, FROM_NON_IME
);
1271 UpdateSelectionBounds();
1274 void RenderViewImpl::RegisterPluginDelegate(WebPluginDelegateProxy
* delegate
) {
1275 plugin_delegates_
.insert(delegate
);
1276 // If the renderer is visible, set initial visibility and focus state.
1278 #if defined(OS_MACOSX)
1279 delegate
->SetContainerVisibility(true);
1280 if (webview() && webview()->isActive())
1281 delegate
->SetWindowFocus(true);
1284 // Plugins start assuming the content has focus (so that they work in
1285 // environments where RenderView isn't hosting them), so we always have to
1286 // set the initial state. See webplugin_delegate_impl.h for details.
1287 delegate
->SetContentAreaFocus(has_focus());
1290 void RenderViewImpl::UnregisterPluginDelegate(
1291 WebPluginDelegateProxy
* delegate
) {
1292 plugin_delegates_
.erase(delegate
);
1296 void RenderViewImpl::PluginFocusChanged(bool focused
, int plugin_id
) {
1298 focused_plugin_id_
= plugin_id
;
1300 focused_plugin_id_
= -1;
1304 #if defined(OS_MACOSX)
1305 void RenderViewImpl::PluginFocusChanged(bool focused
, int plugin_id
) {
1306 Send(new ViewHostMsg_PluginFocusChanged(routing_id(), focused
, plugin_id
));
1309 void RenderViewImpl::OnGetRenderedText() {
1312 // Get rendered text from WebLocalFrame.
1313 // TODO: Currently IPC truncates any data that has a
1314 // size > kMaximumMessageSize. May be split the text into smaller chunks and
1315 // send back using multiple IPC. See http://crbug.com/393444.
1316 static const size_t kMaximumMessageSize
= 8 * 1024 * 1024;
1317 std::string text
= webview()->mainFrame()->contentAsText(
1318 kMaximumMessageSize
).utf8();
1320 Send(new ViewMsg_GetRenderedTextCompleted(routing_id(), text
));
1323 void RenderViewImpl::StartPluginIme() {
1324 IPC::Message
* msg
= new ViewHostMsg_StartPluginIme(routing_id());
1325 // This message can be sent during event-handling, and needs to be delivered
1326 // within that context.
1327 msg
->set_unblock(true);
1330 #endif // defined(OS_MACOSX)
1332 #endif // ENABLE_PLUGINS
1334 void RenderViewImpl::TransferActiveWheelFlingAnimation(
1335 const blink::WebActiveWheelFlingParameters
& params
) {
1337 webview()->transferActiveWheelFlingAnimation(params
);
1340 bool RenderViewImpl::HasIMETextFocus() {
1341 return GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE
;
1344 bool RenderViewImpl::OnMessageReceived(const IPC::Message
& message
) {
1345 WebFrame
* main_frame
= webview() ? webview()->mainFrame() : NULL
;
1346 if (main_frame
&& main_frame
->isWebLocalFrame())
1347 GetContentClient()->SetActiveURL(main_frame
->document().url());
1349 base::ObserverListBase
<RenderViewObserver
>::Iterator
it(&observers_
);
1350 RenderViewObserver
* observer
;
1351 while ((observer
= it
.GetNext()) != NULL
)
1352 if (observer
->OnMessageReceived(message
))
1355 bool handled
= true;
1356 IPC_BEGIN_MESSAGE_MAP(RenderViewImpl
, message
)
1357 IPC_MESSAGE_HANDLER(InputMsg_ExecuteEditCommand
, OnExecuteEditCommand
)
1358 IPC_MESSAGE_HANDLER(InputMsg_MoveCaret
, OnMoveCaret
)
1359 IPC_MESSAGE_HANDLER(InputMsg_ScrollFocusedEditableNodeIntoRect
,
1360 OnScrollFocusedEditableNodeIntoRect
)
1361 IPC_MESSAGE_HANDLER(InputMsg_SetEditCommandsForNextKeyEvent
,
1362 OnSetEditCommandsForNextKeyEvent
)
1363 IPC_MESSAGE_HANDLER(ViewMsg_CopyImageAt
, OnCopyImageAt
)
1364 IPC_MESSAGE_HANDLER(ViewMsg_SaveImageAt
, OnSaveImageAt
)
1365 IPC_MESSAGE_HANDLER(ViewMsg_Find
, OnFind
)
1366 IPC_MESSAGE_HANDLER(ViewMsg_StopFinding
, OnStopFinding
)
1367 IPC_MESSAGE_HANDLER(ViewMsg_ResetPageScale
, OnResetPageScale
)
1368 IPC_MESSAGE_HANDLER(ViewMsg_Zoom
, OnZoom
)
1369 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForLoadingURL
,
1370 OnSetZoomLevelForLoadingURL
)
1371 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForView
,
1372 OnSetZoomLevelForView
)
1373 IPC_MESSAGE_HANDLER(ViewMsg_SetPageEncoding
, OnSetPageEncoding
)
1374 IPC_MESSAGE_HANDLER(ViewMsg_ResetPageEncodingToDefault
,
1375 OnResetPageEncodingToDefault
)
1376 IPC_MESSAGE_HANDLER(DragMsg_TargetDragEnter
, OnDragTargetDragEnter
)
1377 IPC_MESSAGE_HANDLER(DragMsg_TargetDragOver
, OnDragTargetDragOver
)
1378 IPC_MESSAGE_HANDLER(DragMsg_TargetDragLeave
, OnDragTargetDragLeave
)
1379 IPC_MESSAGE_HANDLER(DragMsg_TargetDrop
, OnDragTargetDrop
)
1380 IPC_MESSAGE_HANDLER(DragMsg_SourceEnded
, OnDragSourceEnded
)
1381 IPC_MESSAGE_HANDLER(DragMsg_SourceSystemDragEnded
,
1382 OnDragSourceSystemDragEnded
)
1383 IPC_MESSAGE_HANDLER(ViewMsg_AllowBindings
, OnAllowBindings
)
1384 IPC_MESSAGE_HANDLER(ViewMsg_SetInitialFocus
, OnSetInitialFocus
)
1385 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTargetURL_ACK
, OnUpdateTargetURLAck
)
1386 IPC_MESSAGE_HANDLER(ViewMsg_UpdateWebPreferences
, OnUpdateWebPreferences
)
1387 IPC_MESSAGE_HANDLER(ViewMsg_EnumerateDirectoryResponse
,
1388 OnEnumerateDirectoryResponse
)
1389 IPC_MESSAGE_HANDLER(ViewMsg_RunFileChooserResponse
, OnFileChooserResponse
)
1390 IPC_MESSAGE_HANDLER(ViewMsg_SuppressDialogsUntilSwapOut
,
1391 OnSuppressDialogsUntilSwapOut
)
1392 IPC_MESSAGE_HANDLER(ViewMsg_ClosePage
, OnClosePage
)
1393 IPC_MESSAGE_HANDLER(ViewMsg_ThemeChanged
, OnThemeChanged
)
1394 IPC_MESSAGE_HANDLER(ViewMsg_MoveOrResizeStarted
, OnMoveOrResizeStarted
)
1395 IPC_MESSAGE_HANDLER(ViewMsg_ClearFocusedElement
, OnClearFocusedElement
)
1396 IPC_MESSAGE_HANDLER(ViewMsg_SetBackgroundOpaque
, OnSetBackgroundOpaque
)
1397 IPC_MESSAGE_HANDLER(ViewMsg_EnablePreferredSizeChangedMode
,
1398 OnEnablePreferredSizeChangedMode
)
1399 IPC_MESSAGE_HANDLER(ViewMsg_EnableAutoResize
, OnEnableAutoResize
)
1400 IPC_MESSAGE_HANDLER(ViewMsg_DisableAutoResize
, OnDisableAutoResize
)
1401 IPC_MESSAGE_HANDLER(ViewMsg_DisableScrollbarsForSmallWindows
,
1402 OnDisableScrollbarsForSmallWindows
)
1403 IPC_MESSAGE_HANDLER(ViewMsg_SetRendererPrefs
, OnSetRendererPrefs
)
1404 IPC_MESSAGE_HANDLER(ViewMsg_MediaPlayerActionAt
, OnMediaPlayerActionAt
)
1405 IPC_MESSAGE_HANDLER(ViewMsg_PluginActionAt
, OnPluginActionAt
)
1406 IPC_MESSAGE_HANDLER(ViewMsg_SetActive
, OnSetActive
)
1407 IPC_MESSAGE_HANDLER(ViewMsg_GetAllSavableResourceLinksForCurrentPage
,
1408 OnGetAllSavableResourceLinksForCurrentPage
)
1409 IPC_MESSAGE_HANDLER(
1410 ViewMsg_GetSerializedHtmlDataForCurrentPageWithLocalLinks
,
1411 OnGetSerializedHtmlDataForCurrentPageWithLocalLinks
)
1412 IPC_MESSAGE_HANDLER(ViewMsg_ShowContextMenu
, OnShowContextMenu
)
1413 // TODO(viettrungluu): Move to a separate message filter.
1414 IPC_MESSAGE_HANDLER(ViewMsg_SetHistoryOffsetAndLength
,
1415 OnSetHistoryOffsetAndLength
)
1416 IPC_MESSAGE_HANDLER(ViewMsg_EnableViewSourceMode
, OnEnableViewSourceMode
)
1417 IPC_MESSAGE_HANDLER(ViewMsg_ReleaseDisambiguationPopupBitmap
,
1418 OnReleaseDisambiguationPopupBitmap
)
1419 IPC_MESSAGE_HANDLER(ViewMsg_ForceRedraw
, OnForceRedraw
)
1420 IPC_MESSAGE_HANDLER(ViewMsg_SelectWordAroundCaret
, OnSelectWordAroundCaret
)
1421 #if defined(OS_ANDROID)
1422 IPC_MESSAGE_HANDLER(InputMsg_ActivateNearestFindResult
,
1423 OnActivateNearestFindResult
)
1424 IPC_MESSAGE_HANDLER(ViewMsg_FindMatchRects
, OnFindMatchRects
)
1425 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTopControlsState
,
1426 OnUpdateTopControlsState
)
1427 IPC_MESSAGE_HANDLER(ViewMsg_ExtractSmartClipData
, OnExtractSmartClipData
)
1428 #elif defined(OS_MACOSX)
1429 IPC_MESSAGE_HANDLER(ViewMsg_GetRenderedText
,
1431 IPC_MESSAGE_HANDLER(ViewMsg_PluginImeCompositionCompleted
,
1432 OnPluginImeCompositionCompleted
)
1433 IPC_MESSAGE_HANDLER(ViewMsg_Close
, OnClose
)
1434 IPC_MESSAGE_HANDLER(ViewMsg_SetInLiveResize
, OnSetInLiveResize
)
1435 IPC_MESSAGE_HANDLER(ViewMsg_SetWindowVisibility
, OnSetWindowVisibility
)
1436 IPC_MESSAGE_HANDLER(ViewMsg_WindowFrameChanged
, OnWindowFrameChanged
)
1438 // Adding a new message? Add platform independent ones first, then put the
1439 // platform specific ones at the end.
1441 // Have the super handle all other messages.
1442 IPC_MESSAGE_UNHANDLED(handled
= RenderWidget::OnMessageReceived(message
))
1443 IPC_END_MESSAGE_MAP()
1448 void RenderViewImpl::OnSelectWordAroundCaret() {
1452 handling_input_event_
= true;
1453 webview()->focusedFrame()->selectWordAroundCaret();
1454 handling_input_event_
= false;
1457 void RenderViewImpl::OnCopyImageAt(int x
, int y
) {
1458 webview()->copyImageAt(WebPoint(x
, y
));
1461 void RenderViewImpl::OnSaveImageAt(int x
, int y
) {
1462 webview()->saveImageAt(WebPoint(x
, y
));
1465 void RenderViewImpl::OnUpdateTargetURLAck() {
1466 // Check if there is a targeturl waiting to be sent.
1467 if (target_url_status_
== TARGET_PENDING
)
1468 Send(new ViewHostMsg_UpdateTargetURL(routing_id_
, pending_target_url_
));
1470 target_url_status_
= TARGET_NONE
;
1473 void RenderViewImpl::OnExecuteEditCommand(const std::string
& name
,
1474 const std::string
& value
) {
1475 if (!webview() || !webview()->focusedFrame())
1478 webview()->focusedFrame()->executeCommand(
1479 WebString::fromUTF8(name
), WebString::fromUTF8(value
));
1482 void RenderViewImpl::OnMoveCaret(const gfx::Point
& point
) {
1486 Send(new InputHostMsg_MoveCaret_ACK(routing_id_
));
1488 webview()->focusedFrame()->moveCaretSelection(point
);
1491 void RenderViewImpl::OnScrollFocusedEditableNodeIntoRect(
1492 const gfx::Rect
& rect
) {
1493 if (has_scrolled_focused_editable_node_into_rect_
&&
1494 rect
== rect_for_scrolled_focused_editable_node_
) {
1495 FocusChangeComplete();
1499 blink::WebElement element
= GetFocusedElement();
1500 bool will_animate
= false;
1501 if (!element
.isNull() && IsEditableNode(element
)) {
1502 rect_for_scrolled_focused_editable_node_
= rect
;
1503 has_scrolled_focused_editable_node_into_rect_
= true;
1504 will_animate
= webview()->scrollFocusedNodeIntoRect(rect
);
1508 FocusChangeComplete();
1511 void RenderViewImpl::OnSetEditCommandsForNextKeyEvent(
1512 const EditCommands
& edit_commands
) {
1513 edit_commands_
= edit_commands
;
1516 void RenderViewImpl::OnSetHistoryOffsetAndLength(int history_offset
,
1517 int history_length
) {
1518 DCHECK_GE(history_offset
, -1);
1519 DCHECK_GE(history_length
, 0);
1521 history_list_offset_
= history_offset
;
1522 history_list_length_
= history_length
;
1525 void RenderViewImpl::OnSetInitialFocus(bool reverse
) {
1528 webview()->setInitialFocus(reverse
);
1531 #if defined(OS_MACOSX)
1532 void RenderViewImpl::OnSetInLiveResize(bool in_live_resize
) {
1536 webview()->willStartLiveResize();
1538 webview()->willEndLiveResize();
1542 ///////////////////////////////////////////////////////////////////////////////
1544 void RenderViewImpl::SendUpdateState() {
1545 HistoryEntry
* entry
= history_controller_
->GetCurrentEntry();
1549 // Don't send state updates for kSwappedOutURL.
1550 if (entry
->root().urlString() == WebString::fromUTF8(kSwappedOutURL
))
1553 Send(new ViewHostMsg_UpdateState(
1554 routing_id_
, page_id_
, HistoryEntryToPageState(entry
)));
1557 void RenderViewImpl::ApplyWebPreferencesInternal(
1558 const WebPreferences
& prefs
,
1559 blink::WebView
* web_view
,
1560 CompositorDependencies
* compositor_deps
) {
1561 ApplyWebPreferences(prefs
, web_view
);
1562 #if defined(OS_MACOSX) && !defined(OS_IOS)
1563 DCHECK(compositor_deps
);
1564 bool is_elastic_overscroll_enabled
=
1565 compositor_deps
->IsElasticOverscrollEnabled();
1566 web_view
->settings()->setReportWheelOverscroll(is_elastic_overscroll_enabled
);
1570 bool RenderViewImpl::SendAndRunNestedMessageLoop(IPC::SyncMessage
* message
) {
1571 // Before WebKit asks us to show an alert (etc.), it takes care of doing the
1572 // equivalent of WebView::willEnterModalLoop. In the case of showModalDialog
1573 // it is particularly important that we do not call willEnterModalLoop as
1574 // that would defer resource loads for the dialog itself.
1575 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
1576 RenderThreadImpl::current()->DoNotNotifyWebKitOfModalLoop();
1578 message
->EnableMessagePumping(); // Runs a nested message loop.
1579 return Send(message
);
1582 void RenderViewImpl::OnForceRedraw(int id
) {
1583 ui::LatencyInfo latency_info
;
1585 latency_info
.AddLatencyNumber(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT
,
1589 scoped_ptr
<cc::SwapPromiseMonitor
> latency_info_swap_promise_monitor
;
1590 if (RenderWidgetCompositor
* rwc
= compositor()) {
1591 latency_info_swap_promise_monitor
=
1592 rwc
->CreateLatencyInfoSwapPromiseMonitor(&latency_info
).Pass();
1594 ScheduleCompositeWithForcedRedraw();
1597 // blink::WebViewClient ------------------------------------------------------
1599 WebView
* RenderViewImpl::createView(WebLocalFrame
* creator
,
1600 const WebURLRequest
& request
,
1601 const WebWindowFeatures
& features
,
1602 const WebString
& frame_name
,
1603 WebNavigationPolicy policy
,
1604 bool suppress_opener
) {
1605 ViewHostMsg_CreateWindow_Params params
;
1606 params
.opener_id
= routing_id_
;
1607 params
.user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
1608 if (GetContentClient()->renderer()->AllowPopup())
1609 params
.user_gesture
= true;
1610 params
.window_container_type
= WindowFeaturesToContainerType(features
);
1611 params
.session_storage_namespace_id
= session_storage_namespace_id_
;
1612 if (frame_name
!= "_blank")
1613 params
.frame_name
= base::UTF16ToUTF8(base::StringPiece16(frame_name
));
1614 params
.opener_render_frame_id
=
1615 RenderFrameImpl::FromWebFrame(creator
)->GetRoutingID();
1616 params
.opener_url
= creator
->document().url();
1618 // The browser process uses the top frame's URL for a content settings check
1619 // to determine whether the popup is allowed. If the top frame is remote,
1620 // its URL is not available, so use its replicated origin instead.
1622 // TODO(alexmos): This works fine for regular origins but may break path
1623 // matching for file URLs with OOP subframes that open popups. This should
1624 // be fixed by either moving this lookup to the browser process or removing
1625 // path-based matching for file URLs from content settings. See
1626 // https://crbug.com/466297.
1627 if (creator
->top()->isWebLocalFrame()) {
1628 params
.opener_top_level_frame_url
= creator
->top()->document().url();
1630 params
.opener_top_level_frame_url
=
1631 GURL(creator
->top()->securityOrigin().toString());
1634 GURL
security_url(creator
->document().securityOrigin().toString());
1635 if (!security_url
.is_valid())
1636 security_url
= GURL();
1637 params
.opener_security_origin
= security_url
;
1638 params
.opener_suppressed
= suppress_opener
;
1639 params
.disposition
= NavigationPolicyToDisposition(policy
);
1640 if (!request
.isNull()) {
1641 params
.target_url
= request
.url();
1642 params
.referrer
= GetReferrerFromRequest(creator
, request
);
1644 params
.features
= features
;
1646 for (size_t i
= 0; i
< features
.additionalFeatures
.size(); ++i
)
1647 params
.additional_features
.push_back(features
.additionalFeatures
[i
]);
1649 int32 routing_id
= MSG_ROUTING_NONE
;
1650 int32 main_frame_routing_id
= MSG_ROUTING_NONE
;
1651 int32 surface_id
= 0;
1652 int64 cloned_session_storage_namespace_id
= 0;
1654 RenderThread::Get()->Send(new ViewHostMsg_CreateWindow(
1655 params
, &routing_id
, &main_frame_routing_id
, &surface_id
,
1656 &cloned_session_storage_namespace_id
));
1657 if (routing_id
== MSG_ROUTING_NONE
)
1660 WebUserGestureIndicator::consumeUserGesture();
1662 // While this view may be a background extension page, it can spawn a visible
1663 // render view. So we just assume that the new one is not another background
1664 // page instead of passing on our own value.
1665 // TODO(vangelis): Can we tell if the new view will be a background page?
1666 bool never_visible
= false;
1668 ViewMsg_Resize_Params initial_size
= ViewMsg_Resize_Params();
1669 initial_size
.screen_info
= screen_info_
;
1671 // The initial hidden state for the RenderViewImpl here has to match what the
1672 // browser will eventually decide for the given disposition. Since we have to
1673 // return from this call synchronously, we just have to make our best guess
1674 // and rely on the browser sending a WasHidden / WasShown message if it
1676 ViewMsg_New_Params view_params
;
1678 RenderFrameImpl
* creator_frame
= RenderFrameImpl::FromWebFrame(creator
);
1679 view_params
.opener_frame_route_id
= creator_frame
->GetRoutingID();
1680 DCHECK_EQ(routing_id_
, creator_frame
->render_view()->GetRoutingID());
1682 view_params
.window_was_created_with_opener
= true;
1683 view_params
.renderer_preferences
= renderer_preferences_
;
1684 view_params
.web_preferences
= webkit_preferences_
;
1685 view_params
.view_id
= routing_id
;
1686 view_params
.main_frame_routing_id
= main_frame_routing_id
;
1687 view_params
.surface_id
= surface_id
;
1688 view_params
.session_storage_namespace_id
=
1689 cloned_session_storage_namespace_id
;
1690 view_params
.swapped_out
= false;
1691 // WebCore will take care of setting the correct name.
1692 view_params
.replicated_frame_state
= FrameReplicationState();
1693 view_params
.proxy_routing_id
= MSG_ROUTING_NONE
;
1694 view_params
.hidden
= (params
.disposition
== NEW_BACKGROUND_TAB
);
1695 view_params
.never_visible
= never_visible
;
1696 view_params
.next_page_id
= 1;
1697 view_params
.initial_size
= initial_size
;
1698 view_params
.enable_auto_resize
= false;
1699 view_params
.min_size
= gfx::Size();
1700 view_params
.max_size
= gfx::Size();
1702 RenderViewImpl
* view
=
1703 RenderViewImpl::Create(compositor_deps_
, view_params
, true);
1704 view
->opened_by_user_gesture_
= params
.user_gesture
;
1706 // Record whether the creator frame is trying to suppress the opener field.
1707 view
->opener_suppressed_
= params
.opener_suppressed
;
1709 return view
->webview();
1712 WebWidget
* RenderViewImpl::createPopupMenu(blink::WebPopupType popup_type
) {
1713 RenderWidget
* widget
= RenderWidget::Create(routing_id_
, compositor_deps_
,
1714 popup_type
, screen_info_
);
1717 if (screen_metrics_emulator_
) {
1718 widget
->SetPopupOriginAdjustmentsForEmulation(
1719 screen_metrics_emulator_
.get());
1721 return widget
->webwidget();
1724 WebStorageNamespace
* RenderViewImpl::createSessionStorageNamespace() {
1725 CHECK(session_storage_namespace_id_
!= kInvalidSessionStorageNamespaceId
);
1726 return new WebStorageNamespaceImpl(session_storage_namespace_id_
);
1729 void RenderViewImpl::printPage(WebLocalFrame
* frame
) {
1730 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
,
1731 PrintPage(frame
, handling_input_event_
));
1734 void RenderViewImpl::saveImageFromDataURL(const blink::WebString
& data_url
) {
1735 // Note: We should basically send GURL but we use size-limited string instead
1736 // in order to send a larger data url to save a image for <canvas> or <img>.
1737 if (data_url
.length() < kMaxLengthOfDataURLString
)
1738 Send(new ViewHostMsg_SaveImageFromDataURL(routing_id_
, data_url
.utf8()));
1741 bool RenderViewImpl::enumerateChosenDirectory(
1742 const WebString
& path
,
1743 WebFileChooserCompletion
* chooser_completion
) {
1744 int id
= enumeration_completion_id_
++;
1745 enumeration_completions_
[id
] = chooser_completion
;
1746 return Send(new ViewHostMsg_EnumerateDirectory(
1749 base::FilePath::FromUTF16Unsafe(path
)));
1752 void RenderViewImpl::FrameDidStartLoading(WebFrame
* frame
) {
1753 DCHECK_GE(frames_in_progress_
, 0);
1754 if (frames_in_progress_
== 0)
1755 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidStartLoading());
1756 frames_in_progress_
++;
1759 void RenderViewImpl::FrameDidStopLoading(WebFrame
* frame
) {
1760 // TODO(japhet): This should be a DCHECK, but the pdf plugin sometimes
1761 // calls DidStopLoading() without a matching DidStartLoading().
1762 if (frames_in_progress_
== 0)
1764 frames_in_progress_
--;
1765 if (frames_in_progress_
== 0) {
1766 DidStopLoadingIcons();
1767 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidStopLoading());
1771 void RenderViewImpl::SetZoomLevel(double zoom_level
) {
1772 webview()->setZoomLevel(zoom_level
);
1773 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, OnZoomLevelChanged());
1776 void RenderViewImpl::didCancelCompositionOnSelectionChange() {
1777 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
1780 bool RenderViewImpl::handleCurrentKeyboardEvent() {
1781 if (edit_commands_
.empty())
1784 WebFrame
* frame
= webview()->focusedFrame();
1788 EditCommands::iterator it
= edit_commands_
.begin();
1789 EditCommands::iterator end
= edit_commands_
.end();
1791 bool did_execute_command
= false;
1792 for (; it
!= end
; ++it
) {
1793 // In gtk and cocoa, it's possible to bind multiple edit commands to one
1794 // key (but it's the exception). Once one edit command is not executed, it
1795 // seems safest to not execute the rest.
1796 if (!frame
->executeCommand(WebString::fromUTF8(it
->name
),
1797 WebString::fromUTF8(it
->value
),
1798 GetFocusedElement()))
1800 did_execute_command
= true;
1803 return did_execute_command
;
1806 bool RenderViewImpl::runFileChooser(
1807 const blink::WebFileChooserParams
& params
,
1808 WebFileChooserCompletion
* chooser_completion
) {
1809 // Do not open the file dialog in a hidden RenderView.
1812 FileChooserParams ipc_params
;
1813 if (params
.directory
)
1814 ipc_params
.mode
= FileChooserParams::UploadFolder
;
1815 else if (params
.multiSelect
)
1816 ipc_params
.mode
= FileChooserParams::OpenMultiple
;
1817 else if (params
.saveAs
)
1818 ipc_params
.mode
= FileChooserParams::Save
;
1820 ipc_params
.mode
= FileChooserParams::Open
;
1821 ipc_params
.title
= params
.title
;
1822 ipc_params
.default_file_name
=
1823 base::FilePath::FromUTF16Unsafe(params
.initialValue
).BaseName();
1824 ipc_params
.accept_types
.reserve(params
.acceptTypes
.size());
1825 for (size_t i
= 0; i
< params
.acceptTypes
.size(); ++i
)
1826 ipc_params
.accept_types
.push_back(params
.acceptTypes
[i
]);
1827 ipc_params
.need_local_path
= params
.needLocalPath
;
1828 #if defined(OS_ANDROID)
1829 ipc_params
.capture
= params
.useMediaCapture
;
1832 return ScheduleFileChooser(ipc_params
, chooser_completion
);
1835 void RenderViewImpl::SetValidationMessageDirection(
1836 base::string16
* wrapped_main_text
,
1837 blink::WebTextDirection main_text_hint
,
1838 base::string16
* wrapped_sub_text
,
1839 blink::WebTextDirection sub_text_hint
) {
1840 if (main_text_hint
== blink::WebTextDirectionLeftToRight
) {
1841 *wrapped_main_text
=
1842 base::i18n::GetDisplayStringInLTRDirectionality(*wrapped_main_text
);
1843 } else if (main_text_hint
== blink::WebTextDirectionRightToLeft
&&
1844 !base::i18n::IsRTL()) {
1845 base::i18n::WrapStringWithRTLFormatting(wrapped_main_text
);
1848 if (!wrapped_sub_text
->empty()) {
1849 if (sub_text_hint
== blink::WebTextDirectionLeftToRight
) {
1851 base::i18n::GetDisplayStringInLTRDirectionality(*wrapped_sub_text
);
1852 } else if (sub_text_hint
== blink::WebTextDirectionRightToLeft
) {
1853 base::i18n::WrapStringWithRTLFormatting(wrapped_sub_text
);
1858 void RenderViewImpl::showValidationMessage(
1859 const blink::WebRect
& anchor_in_root_view
,
1860 const blink::WebString
& main_text
,
1861 blink::WebTextDirection main_text_hint
,
1862 const blink::WebString
& sub_text
,
1863 blink::WebTextDirection sub_text_hint
) {
1864 base::string16 wrapped_main_text
= main_text
;
1865 base::string16 wrapped_sub_text
= sub_text
;
1867 SetValidationMessageDirection(
1868 &wrapped_main_text
, main_text_hint
, &wrapped_sub_text
, sub_text_hint
);
1870 Send(new ViewHostMsg_ShowValidationMessage(
1871 routing_id(), AdjustValidationMessageAnchor(anchor_in_root_view
),
1872 wrapped_main_text
, wrapped_sub_text
));
1875 void RenderViewImpl::hideValidationMessage() {
1876 Send(new ViewHostMsg_HideValidationMessage(routing_id()));
1879 void RenderViewImpl::moveValidationMessage(
1880 const blink::WebRect
& anchor_in_root_view
) {
1881 Send(new ViewHostMsg_MoveValidationMessage(
1882 routing_id(), AdjustValidationMessageAnchor(anchor_in_root_view
)));
1885 void RenderViewImpl::setStatusText(const WebString
& text
) {
1888 void RenderViewImpl::UpdateTargetURL(const GURL
& url
,
1889 const GURL
& fallback_url
) {
1890 GURL latest_url
= url
.is_empty() ? fallback_url
: url
;
1891 if (latest_url
== target_url_
)
1894 // Tell the browser to display a destination link.
1895 if (target_url_status_
== TARGET_INFLIGHT
||
1896 target_url_status_
== TARGET_PENDING
) {
1897 // If we have a request in-flight, save the URL to be sent when we
1898 // receive an ACK to the in-flight request. We can happily overwrite
1899 // any existing pending sends.
1900 pending_target_url_
= latest_url
;
1901 target_url_status_
= TARGET_PENDING
;
1903 // URLs larger than |MaxURLChars()| cannot be sent through IPC -
1904 // see |ParamTraits<GURL>|.
1905 if (latest_url
.possibly_invalid_spec().size() > GetMaxURLChars())
1906 latest_url
= GURL();
1907 Send(new ViewHostMsg_UpdateTargetURL(routing_id_
, latest_url
));
1908 target_url_
= latest_url
;
1909 target_url_status_
= TARGET_INFLIGHT
;
1913 gfx::RectF
RenderViewImpl::ClientRectToPhysicalWindowRect(
1914 const gfx::RectF
& rect
) const {
1915 gfx::RectF window_rect
= rect
;
1916 window_rect
.Scale(device_scale_factor_
* webview()->pageScaleFactor());
1920 void RenderViewImpl::StartNavStateSyncTimerIfNecessary() {
1922 if (send_content_state_immediately_
)
1924 else if (is_hidden())
1925 delay
= kDelaySecondsForContentStateSyncHidden
;
1927 delay
= kDelaySecondsForContentStateSync
;
1929 if (nav_state_sync_timer_
.IsRunning()) {
1930 // The timer is already running. If the delay of the timer maches the amount
1931 // we want to delay by, then return. Otherwise stop the timer so that it
1932 // gets started with the right delay.
1933 if (nav_state_sync_timer_
.GetCurrentDelay().InSeconds() == delay
)
1935 nav_state_sync_timer_
.Stop();
1938 nav_state_sync_timer_
.Start(FROM_HERE
, TimeDelta::FromSeconds(delay
), this,
1939 &RenderViewImpl::SendUpdateState
);
1942 void RenderViewImpl::setMouseOverURL(const WebURL
& url
) {
1943 mouse_over_url_
= GURL(url
);
1944 UpdateTargetURL(mouse_over_url_
, focus_url_
);
1947 void RenderViewImpl::setKeyboardFocusURL(const WebURL
& url
) {
1948 focus_url_
= GURL(url
);
1949 UpdateTargetURL(focus_url_
, mouse_over_url_
);
1952 void RenderViewImpl::startDragging(WebLocalFrame
* frame
,
1953 const WebDragData
& data
,
1954 WebDragOperationsMask mask
,
1955 const WebImage
& image
,
1956 const WebPoint
& webImageOffset
) {
1957 DropData
drop_data(DropDataBuilder::Build(data
));
1958 drop_data
.referrer_policy
= frame
->document().referrerPolicy();
1959 gfx::Vector2d
imageOffset(webImageOffset
.x
, webImageOffset
.y
);
1960 Send(new DragHostMsg_StartDragging(routing_id_
,
1963 image
.getSkBitmap(),
1965 possible_drag_event_info_
));
1968 bool RenderViewImpl::acceptsLoadDrops() {
1969 return renderer_preferences_
.can_accept_load_drops
;
1972 void RenderViewImpl::focusNext() {
1973 Send(new ViewHostMsg_TakeFocus(routing_id_
, false));
1976 void RenderViewImpl::focusPrevious() {
1977 Send(new ViewHostMsg_TakeFocus(routing_id_
, true));
1980 void RenderViewImpl::focusedNodeChanged(const WebNode
& fromNode
,
1981 const WebNode
& toNode
) {
1982 has_scrolled_focused_editable_node_into_rect_
= false;
1984 gfx::Rect node_bounds
;
1985 if (!toNode
.isNull() && toNode
.isElementNode()) {
1986 WebNode web_node
= const_cast<WebNode
&>(toNode
);
1987 node_bounds
= gfx::Rect(web_node
.to
<WebElement
>().boundsInViewportSpace());
1989 Send(new ViewHostMsg_FocusedNodeChanged(routing_id_
, IsEditableNode(toNode
),
1992 // TODO(estade): remove.
1993 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, FocusedNodeChanged(toNode
));
1995 RenderFrameImpl
* previous_frame
= nullptr;
1996 if (!fromNode
.isNull())
1997 previous_frame
= RenderFrameImpl::FromWebFrame(fromNode
.document().frame());
1998 RenderFrameImpl
* new_frame
= nullptr;
1999 if (!toNode
.isNull())
2000 new_frame
= RenderFrameImpl::FromWebFrame(toNode
.document().frame());
2002 if (previous_frame
&& previous_frame
!= new_frame
)
2003 previous_frame
->FocusedNodeChanged(WebNode());
2005 new_frame
->FocusedNodeChanged(toNode
);
2007 // TODO(dmazzoni): remove once there's a separate a11y tree per frame.
2008 if (main_render_frame_
)
2009 main_render_frame_
->FocusedNodeChangedForAccessibility(toNode
);
2012 void RenderViewImpl::didUpdateLayout() {
2013 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidUpdateLayout());
2015 // We don't always want to set up a timer, only if we've been put in that
2016 // mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
2018 if (!send_preferred_size_changes_
|| !webview())
2021 if (check_preferred_size_timer_
.IsRunning())
2023 check_preferred_size_timer_
.Start(FROM_HERE
,
2024 TimeDelta::FromMilliseconds(0), this,
2025 &RenderViewImpl::CheckPreferredSize
);
2028 void RenderViewImpl::navigateBackForwardSoon(int offset
) {
2029 Send(new ViewHostMsg_GoToEntryAtOffset(routing_id_
, offset
));
2032 int RenderViewImpl::historyBackListCount() {
2033 return history_list_offset_
< 0 ? 0 : history_list_offset_
;
2036 int RenderViewImpl::historyForwardListCount() {
2037 return history_list_length_
- historyBackListCount() - 1;
2040 // blink::WebWidgetClient ----------------------------------------------------
2042 void RenderViewImpl::didFocus() {
2043 // TODO(jcivelli): when https://bugs.webkit.org/show_bug.cgi?id=33389 is fixed
2044 // we won't have to test for user gesture anymore and we can
2045 // move that code back to render_widget.cc
2046 if (WebUserGestureIndicator::isProcessingUserGesture() &&
2047 !RenderThreadImpl::current()->layout_test_mode()) {
2048 Send(new ViewHostMsg_Focus(routing_id_
));
2052 void RenderViewImpl::didBlur() {
2053 // TODO(jcivelli): see TODO above in didFocus().
2054 if (WebUserGestureIndicator::isProcessingUserGesture() &&
2055 !RenderThreadImpl::current()->layout_test_mode()) {
2056 Send(new ViewHostMsg_Blur(routing_id_
));
2060 // We are supposed to get a single call to Show for a newly created RenderView
2061 // that was created via RenderViewImpl::CreateWebView. So, we wait until this
2062 // point to dispatch the ShowView message.
2064 // This method provides us with the information about how to display the newly
2065 // created RenderView (i.e., as a blocked popup or as a new tab).
2067 void RenderViewImpl::show(WebNavigationPolicy policy
) {
2069 // When supports_multiple_windows is disabled, popups are reusing
2070 // the same view. In some scenarios, this makes WebKit to call show() twice.
2071 if (webkit_preferences_
.supports_multiple_windows
)
2072 NOTREACHED() << "received extraneous Show call";
2077 DCHECK(opener_id_
!= MSG_ROUTING_NONE
);
2079 // NOTE: initial_rect_ may still have its default values at this point, but
2080 // that's okay. It'll be ignored if disposition is not NEW_POPUP, or the
2081 // browser process will impose a default position otherwise.
2082 Send(new ViewHostMsg_ShowView(opener_id_
, routing_id_
,
2083 NavigationPolicyToDisposition(policy
), initial_rect_
,
2084 opened_by_user_gesture_
));
2085 SetPendingWindowRect(initial_rect_
);
2088 bool RenderViewImpl::requestPointerLock() {
2089 return mouse_lock_dispatcher_
->LockMouse(webwidget_mouse_lock_target_
.get());
2092 void RenderViewImpl::requestPointerUnlock() {
2093 mouse_lock_dispatcher_
->UnlockMouse(webwidget_mouse_lock_target_
.get());
2096 bool RenderViewImpl::isPointerLocked() {
2097 return mouse_lock_dispatcher_
->IsMouseLockedTo(
2098 webwidget_mouse_lock_target_
.get());
2101 void RenderViewImpl::onMouseDown(const WebNode
& mouse_down_node
) {
2103 RenderViewObserver
, observers_
, OnMouseDown(mouse_down_node
));
2106 void RenderViewImpl::didHandleGestureEvent(
2107 const WebGestureEvent
& event
,
2108 bool event_cancelled
) {
2109 RenderWidget::didHandleGestureEvent(event
, event_cancelled
);
2111 if (!event_cancelled
) {
2113 RenderViewObserver
, observers_
, DidHandleGestureEvent(event
));
2116 // TODO(ananta): Piggyback off existing IPCs to communicate this information,
2119 if (event
.type
!= blink::WebGestureEvent::GestureTap
)
2122 // TODO(estade): hit test the event against focused node to make sure
2123 // the tap actually hit the focused node.
2124 blink::WebTextInputType text_input_type
=
2125 GetWebView()->textInputInfo().type
;
2127 Send(new ViewHostMsg_FocusedNodeTouched(
2128 routing_id(), text_input_type
!= blink::WebTextInputTypeNone
));
2132 void RenderViewImpl::initializeLayerTreeView() {
2133 RenderWidget::initializeLayerTreeView();
2134 RenderWidgetCompositor
* rwc
= compositor();
2138 bool use_threaded_event_handling
= true;
2139 #if defined(OS_MACOSX) && !defined(OS_IOS)
2140 // Disable threaded event handling if content is not handling the elastic
2141 // overscroll effect. This includes the cases where the elastic overscroll
2142 // effect is being handled by Blink (because of command line flags) and older
2143 // operating system versions which do not have an elastic overscroll effect
2144 // (SnowLeopard, which has Aqua scrollbars which need synchronous updates).
2145 use_threaded_event_handling
= compositor_deps_
->IsElasticOverscrollEnabled();
2147 if (use_threaded_event_handling
) {
2148 RenderThreadImpl
* render_thread
= RenderThreadImpl::current();
2149 // render_thread may be NULL in tests.
2150 InputHandlerManager
* input_handler_manager
=
2151 render_thread
? render_thread
->input_handler_manager() : NULL
;
2152 if (input_handler_manager
) {
2153 input_handler_manager
->AddInputHandler(
2154 routing_id_
, rwc
->GetInputHandler(), AsWeakPtr());
2159 // blink::WebFrameClient -----------------------------------------------------
2161 void RenderViewImpl::Repaint(const gfx::Size
& size
) {
2165 void RenderViewImpl::SetEditCommandForNextKeyEvent(const std::string
& name
,
2166 const std::string
& value
) {
2167 EditCommands edit_commands
;
2168 edit_commands
.push_back(EditCommand(name
, value
));
2169 OnSetEditCommandsForNextKeyEvent(edit_commands
);
2172 void RenderViewImpl::ClearEditCommands() {
2173 edit_commands_
.clear();
2176 SSLStatus
RenderViewImpl::GetSSLStatusOfFrame(blink::WebFrame
* frame
) const {
2177 std::string security_info
;
2178 if (frame
&& frame
->dataSource())
2179 security_info
= frame
->dataSource()->response().securityInfo();
2182 CHECK(DeserializeSecurityInfo(security_info
, &result
));
2186 const std::string
& RenderViewImpl::GetAcceptLanguages() const {
2187 return renderer_preferences_
.accept_languages
;
2190 void RenderViewImpl::didChangeIcon(WebLocalFrame
* frame
,
2191 WebIconURL::Type icon_type
) {
2192 if (frame
->parent())
2195 WebVector
<WebIconURL
> icon_urls
= frame
->iconURLs(icon_type
);
2196 std::vector
<FaviconURL
> urls
;
2197 for (size_t i
= 0; i
< icon_urls
.size(); i
++) {
2198 std::vector
<gfx::Size
> sizes
;
2199 ConvertToFaviconSizes(icon_urls
[i
].sizes(), &sizes
);
2200 urls
.push_back(FaviconURL(
2201 icon_urls
[i
].iconURL(), ToFaviconType(icon_urls
[i
].iconType()), sizes
));
2203 SendUpdateFaviconURL(urls
);
2206 void RenderViewImpl::didUpdateCurrentHistoryItem(WebLocalFrame
* frame
) {
2207 StartNavStateSyncTimerIfNecessary();
2210 void RenderViewImpl::CheckPreferredSize() {
2211 // We don't always want to send the change messages over IPC, only if we've
2212 // been put in that mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
2214 if (!send_preferred_size_changes_
|| !webview())
2217 gfx::Size size
= webview()->contentsPreferredMinimumSize();
2218 if (size
== preferred_size_
)
2221 preferred_size_
= size
;
2222 Send(new ViewHostMsg_DidContentsPreferredSizeChange(routing_id_
,
2226 void RenderViewImpl::didChangeScrollOffset(WebLocalFrame
* frame
) {
2227 StartNavStateSyncTimerIfNecessary();
2230 void RenderViewImpl::SendFindReply(int request_id
,
2233 const WebRect
& selection_rect
,
2234 bool final_status_update
) {
2235 Send(new ViewHostMsg_Find_Reply(routing_id_
,
2240 final_status_update
));
2243 blink::WebString
RenderViewImpl::acceptLanguages() {
2244 return WebString::fromUTF8(renderer_preferences_
.accept_languages
);
2247 // blink::WebPageSerializerClient implementation ------------------------------
2249 void RenderViewImpl::didSerializeDataForFrame(
2250 const WebURL
& frame_url
,
2251 const WebCString
& data
,
2252 WebPageSerializerClient::PageSerializationStatus status
) {
2253 Send(new ViewHostMsg_SendSerializedHtmlData(
2257 static_cast<int32
>(status
)));
2260 // RenderView implementation ---------------------------------------------------
2262 bool RenderViewImpl::Send(IPC::Message
* message
) {
2263 return RenderWidget::Send(message
);
2266 RenderFrameImpl
* RenderViewImpl::GetMainRenderFrame() {
2267 return main_render_frame_
;
2270 int RenderViewImpl::GetRoutingID() const {
2274 gfx::Size
RenderViewImpl::GetSize() const {
2278 WebPreferences
& RenderViewImpl::GetWebkitPreferences() {
2279 return webkit_preferences_
;
2282 void RenderViewImpl::SetWebkitPreferences(const WebPreferences
& preferences
) {
2283 OnUpdateWebPreferences(preferences
);
2286 blink::WebView
* RenderViewImpl::GetWebView() {
2290 bool RenderViewImpl::IsEditableNode(const WebNode
& node
) const {
2294 if (node
.isContentEditable())
2297 if (node
.isElementNode()) {
2298 const WebElement
& element
= node
.toConst
<WebElement
>();
2299 if (element
.isTextFormControlElement()) {
2300 if (!(element
.hasAttribute("readonly") ||
2301 element
.hasAttribute("disabled")))
2305 return base::LowerCaseEqualsASCII(
2306 base::StringPiece16(element
.getAttribute("role")), "textbox");
2312 bool RenderViewImpl::ShouldDisplayScrollbars(int width
, int height
) const {
2313 return (!send_preferred_size_changes_
||
2314 (disable_scrollbars_size_limit_
.width() <= width
||
2315 disable_scrollbars_size_limit_
.height() <= height
));
2318 int RenderViewImpl::GetEnabledBindings() const {
2319 return enabled_bindings_
;
2322 bool RenderViewImpl::GetContentStateImmediately() const {
2323 return send_content_state_immediately_
;
2326 blink::WebPageVisibilityState
RenderViewImpl::GetVisibilityState() const {
2327 return visibilityState();
2330 void RenderViewImpl::DidStartLoading() {
2331 main_render_frame_
->didStartLoading(true);
2334 void RenderViewImpl::DidStopLoading() {
2335 main_render_frame_
->didStopLoading();
2338 blink::WebElement
RenderViewImpl::GetFocusedElement() const {
2340 return WebElement();
2341 WebFrame
* focused_frame
= webview()->focusedFrame();
2342 if (focused_frame
) {
2343 WebDocument doc
= focused_frame
->document();
2345 return doc
.focusedElement();
2348 return WebElement();
2351 blink::WebPlugin
* RenderViewImpl::GetWebPluginForFind() {
2355 WebFrame
* main_frame
= webview()->mainFrame();
2356 if (main_frame
->isWebLocalFrame() &&
2357 main_frame
->document().isPluginDocument())
2358 return webview()->mainFrame()->document().to
<WebPluginDocument
>().plugin();
2360 #if defined(ENABLE_PLUGINS)
2361 if (plugin_find_handler_
)
2362 return plugin_find_handler_
->container()->plugin();
2368 void RenderViewImpl::OnFind(int request_id
,
2369 const base::string16
& search_text
,
2370 const WebFindOptions
& options
) {
2371 WebFrame
* main_frame
= webview()->mainFrame();
2372 blink::WebPlugin
* plugin
= GetWebPluginForFind();
2373 // Check if the plugin still exists in the document.
2375 if (options
.findNext
) {
2376 // Just navigate back/forward.
2377 plugin
->selectFindResult(options
.forward
);
2379 if (!plugin
->startFind(
2380 search_text
, options
.matchCase
, request_id
)) {
2381 // Send "no results".
2382 SendFindReply(request_id
, 0, 0, gfx::Rect(), true);
2388 WebFrame
* frame_after_main
= main_frame
->traverseNext(true);
2389 WebFrame
* focused_frame
= webview()->focusedFrame();
2390 WebFrame
* search_frame
= focused_frame
; // start searching focused frame.
2392 bool multi_frame
= (frame_after_main
!= main_frame
);
2394 // If we have multiple frames, we don't want to wrap the search within the
2395 // frame, so we check here if we only have main_frame in the chain.
2396 bool wrap_within_frame
= !multi_frame
;
2398 WebRect selection_rect
;
2399 bool result
= false;
2401 // If something is selected when we start searching it means we cannot just
2402 // increment the current match ordinal; we need to re-generate it.
2403 WebRange current_selection
= focused_frame
->selectionRange();
2406 result
= search_frame
->find(
2407 request_id
, search_text
, options
, wrap_within_frame
, &selection_rect
);
2410 // don't leave text selected as you move to the next frame.
2411 search_frame
->executeCommand(WebString::fromUTF8("Unselect"),
2412 GetFocusedElement());
2414 // Find the next frame, but skip the invisible ones.
2416 // What is the next frame to search? (we might be going backwards). Note
2417 // that we specify wrap=true so that search_frame never becomes NULL.
2418 search_frame
= options
.forward
?
2419 search_frame
->traverseNext(true) :
2420 search_frame
->traversePrevious(true);
2421 } while (!search_frame
->hasVisibleContent() &&
2422 search_frame
!= focused_frame
);
2424 // Make sure selection doesn't affect the search operation in new frame.
2425 search_frame
->executeCommand(WebString::fromUTF8("Unselect"),
2426 GetFocusedElement());
2428 // If we have multiple frames and we have wrapped back around to the
2429 // focused frame, we need to search it once more allowing wrap within
2430 // the frame, otherwise it will report 'no match' if the focused frame has
2431 // reported matches, but no frames after the focused_frame contain a
2432 // match for the search word(s).
2433 if (multi_frame
&& search_frame
== focused_frame
) {
2434 result
= search_frame
->find(
2435 request_id
, search_text
, options
, true, // Force wrapping.
2440 webview()->setFocusedFrame(search_frame
);
2441 } while (!result
&& search_frame
!= focused_frame
);
2443 if (options
.findNext
&& current_selection
.isNull()) {
2444 // Force the main_frame to report the actual count.
2445 main_frame
->increaseMatchCount(0, request_id
);
2447 // If nothing is found, set result to "0 of 0", otherwise, set it to
2448 // "-1 of 1" to indicate that we found at least one item, but we don't know
2449 // yet what is active.
2450 int ordinal
= result
? -1 : 0; // -1 here means, we might know more later.
2451 int match_count
= result
? 1 : 0; // 1 here means possibly more coming.
2453 // If we find no matches then this will be our last status update.
2454 // Otherwise the scoping effort will send more results.
2455 bool final_status_update
= !result
;
2457 SendFindReply(request_id
, match_count
, ordinal
, selection_rect
,
2458 final_status_update
);
2460 // Scoping effort begins, starting with the mainframe.
2461 search_frame
= main_frame
;
2463 main_frame
->resetMatchCount();
2466 // Cancel all old scoping requests before starting a new one.
2467 search_frame
->cancelPendingScopingEffort();
2469 // We don't start another scoping effort unless at least one match has
2472 // Start new scoping request. If the scoping function determines that it
2473 // needs to scope, it will defer until later.
2474 search_frame
->scopeStringMatches(request_id
,
2477 true); // reset the tickmarks
2480 // Iterate to the next frame. The frame will not necessarily scope, for
2481 // example if it is not visible.
2482 search_frame
= search_frame
->traverseNext(true);
2483 } while (search_frame
!= main_frame
);
2487 void RenderViewImpl::OnStopFinding(StopFindAction action
) {
2488 WebView
* view
= webview();
2492 blink::WebPlugin
* plugin
= GetWebPluginForFind();
2498 bool clear_selection
= action
== STOP_FIND_ACTION_CLEAR_SELECTION
;
2499 if (clear_selection
) {
2500 view
->focusedFrame()->executeCommand(WebString::fromUTF8("Unselect"),
2501 GetFocusedElement());
2504 WebFrame
* frame
= view
->mainFrame();
2506 frame
->stopFinding(clear_selection
);
2507 frame
= frame
->traverseNext(false);
2510 if (action
== STOP_FIND_ACTION_ACTIVATE_SELECTION
) {
2511 WebFrame
* focused_frame
= view
->focusedFrame();
2512 if (focused_frame
) {
2513 WebDocument doc
= focused_frame
->document();
2514 if (!doc
.isNull()) {
2515 WebElement element
= doc
.focusedElement();
2516 if (!element
.isNull())
2517 element
.simulateClick();
2523 #if defined(OS_ANDROID)
2524 void RenderViewImpl::OnActivateNearestFindResult(int request_id
,
2529 WebFrame
* main_frame
= webview()->mainFrame();
2530 WebRect selection_rect
;
2531 int ordinal
= main_frame
->selectNearestFindMatch(WebFloatPoint(x
, y
),
2533 if (ordinal
== -1) {
2534 // Something went wrong, so send a no-op reply (force the main_frame to
2535 // report the current match count) in case the host is waiting for a
2536 // response due to rate-limiting).
2537 main_frame
->increaseMatchCount(0, request_id
);
2541 SendFindReply(request_id
,
2542 -1 /* number_of_matches */,
2545 true /* final_update */);
2548 void RenderViewImpl::OnFindMatchRects(int current_version
) {
2552 WebFrame
* main_frame
= webview()->mainFrame();
2553 std::vector
<gfx::RectF
> match_rects
;
2555 int rects_version
= main_frame
->findMatchMarkersVersion();
2556 if (current_version
!= rects_version
) {
2557 WebVector
<WebFloatRect
> web_match_rects
;
2558 main_frame
->findMatchRects(web_match_rects
);
2559 match_rects
.reserve(web_match_rects
.size());
2560 for (size_t i
= 0; i
< web_match_rects
.size(); ++i
)
2561 match_rects
.push_back(gfx::RectF(web_match_rects
[i
]));
2564 gfx::RectF active_rect
= main_frame
->activeFindMatchRect();
2565 Send(new ViewHostMsg_FindMatchRects_Reply(routing_id_
,
2572 void RenderViewImpl::OnResetPageScale() {
2575 webview()->setPageScaleFactor(1);
2578 void RenderViewImpl::OnZoom(PageZoom zoom
) {
2579 if (!webview()) // Not sure if this can happen, but no harm in being safe.
2582 webview()->hidePopups();
2584 double old_zoom_level
= webview()->zoomLevel();
2586 if (zoom
== PAGE_ZOOM_RESET
) {
2588 } else if (static_cast<int>(old_zoom_level
) == old_zoom_level
) {
2589 // Previous zoom level is a whole number, so just increment/decrement.
2590 zoom_level
= old_zoom_level
+ zoom
;
2592 // Either the user hit the zoom factor limit and thus the zoom level is now
2593 // not a whole number, or a plugin changed it to a custom value. We want
2594 // to go to the next whole number so that the user can always get back to
2595 // 100% with the keyboard/menu.
2596 if ((old_zoom_level
> 1 && zoom
> 0) ||
2597 (old_zoom_level
< 1 && zoom
< 0)) {
2598 zoom_level
= static_cast<int>(old_zoom_level
+ zoom
);
2600 // We're going towards 100%, so first go to the next whole number.
2601 zoom_level
= static_cast<int>(old_zoom_level
);
2604 SetZoomLevel(zoom_level
);
2608 void RenderViewImpl::OnSetZoomLevelForLoadingURL(const GURL
& url
,
2609 double zoom_level
) {
2610 #if !defined(OS_ANDROID)
2611 // On Android, page zoom isn't used, and in case of WebView, text zoom is used
2612 // for legacy WebView text scaling emulation. Thus, the code that resets
2613 // the zoom level from this map will be effectively resetting text zoom level.
2614 host_zoom_levels_
[url
] = zoom_level
;
2618 void RenderViewImpl::OnSetZoomLevelForView(bool uses_temporary_zoom_level
,
2620 uses_temporary_zoom_level_
= uses_temporary_zoom_level
;
2622 webview()->hidePopups();
2623 SetZoomLevel(level
);
2626 void RenderViewImpl::OnSetPageEncoding(const std::string
& encoding_name
) {
2627 webview()->setPageEncoding(WebString::fromUTF8(encoding_name
));
2630 void RenderViewImpl::OnResetPageEncodingToDefault() {
2631 WebString no_encoding
;
2632 webview()->setPageEncoding(no_encoding
);
2635 void RenderViewImpl::OnAllowBindings(int enabled_bindings_flags
) {
2636 if ((enabled_bindings_flags
& BINDINGS_POLICY_WEB_UI
) &&
2637 !(enabled_bindings_
& BINDINGS_POLICY_WEB_UI
)) {
2638 // WebUIExtensionData deletes itself when we're destroyed.
2639 new WebUIExtensionData(this);
2640 // WebUIMojo deletes itself when we're destroyed.
2641 new WebUIMojo(this);
2644 enabled_bindings_
|= enabled_bindings_flags
;
2646 // Keep track of the total bindings accumulated in this process.
2647 RenderProcess::current()->AddBindings(enabled_bindings_flags
);
2650 void RenderViewImpl::OnDragTargetDragEnter(const DropData
& drop_data
,
2651 const gfx::Point
& client_point
,
2652 const gfx::Point
& screen_point
,
2653 WebDragOperationsMask ops
,
2654 int key_modifiers
) {
2655 WebDragOperation operation
= webview()->dragTargetDragEnter(
2656 DropDataToWebDragData(drop_data
),
2662 Send(new DragHostMsg_UpdateDragCursor(routing_id_
, operation
));
2665 void RenderViewImpl::OnDragTargetDragOver(const gfx::Point
& client_point
,
2666 const gfx::Point
& screen_point
,
2667 WebDragOperationsMask ops
,
2668 int key_modifiers
) {
2669 WebDragOperation operation
= webview()->dragTargetDragOver(
2675 Send(new DragHostMsg_UpdateDragCursor(routing_id_
, operation
));
2678 void RenderViewImpl::OnDragTargetDragLeave() {
2679 webview()->dragTargetDragLeave();
2682 void RenderViewImpl::OnDragTargetDrop(const gfx::Point
& client_point
,
2683 const gfx::Point
& screen_point
,
2684 int key_modifiers
) {
2685 webview()->dragTargetDrop(client_point
, screen_point
, key_modifiers
);
2688 void RenderViewImpl::OnDragSourceEnded(const gfx::Point
& client_point
,
2689 const gfx::Point
& screen_point
,
2690 WebDragOperation op
) {
2691 webview()->dragSourceEndedAt(client_point
, screen_point
, op
);
2694 void RenderViewImpl::OnDragSourceSystemDragEnded() {
2695 webview()->dragSourceSystemDragEnded();
2698 void RenderViewImpl::OnUpdateWebPreferences(const WebPreferences
& prefs
) {
2699 webkit_preferences_
= prefs
;
2700 ApplyWebPreferencesInternal(webkit_preferences_
, webview(), compositor_deps_
);
2703 void RenderViewImpl::OnEnumerateDirectoryResponse(
2705 const std::vector
<base::FilePath
>& paths
) {
2706 if (!enumeration_completions_
[id
])
2709 WebVector
<WebString
> ws_file_names(paths
.size());
2710 for (size_t i
= 0; i
< paths
.size(); ++i
)
2711 ws_file_names
[i
] = paths
[i
].AsUTF16Unsafe();
2713 enumeration_completions_
[id
]->didChooseFile(ws_file_names
);
2714 enumeration_completions_
.erase(id
);
2717 void RenderViewImpl::OnFileChooserResponse(
2718 const std::vector
<content::FileChooserFileInfo
>& files
) {
2719 // This could happen if we navigated to a different page before the user
2720 // closed the chooser.
2721 if (file_chooser_completions_
.empty())
2724 // Convert Chrome's SelectedFileInfo list to WebKit's.
2725 WebVector
<WebFileChooserCompletion::SelectedFileInfo
> selected_files(
2727 for (size_t i
= 0; i
< files
.size(); ++i
) {
2728 WebFileChooserCompletion::SelectedFileInfo selected_file
;
2729 selected_file
.path
= files
[i
].file_path
.AsUTF16Unsafe();
2730 selected_file
.displayName
=
2731 base::FilePath(files
[i
].display_name
).AsUTF16Unsafe();
2732 if (files
[i
].file_system_url
.is_valid()) {
2733 selected_file
.fileSystemURL
= files
[i
].file_system_url
;
2734 selected_file
.length
= files
[i
].length
;
2735 selected_file
.modificationTime
= files
[i
].modification_time
.ToDoubleT();
2736 selected_file
.isDirectory
= files
[i
].is_directory
;
2738 selected_files
[i
] = selected_file
;
2741 if (file_chooser_completions_
.front()->completion
)
2742 file_chooser_completions_
.front()->completion
->didChooseFile(
2744 file_chooser_completions_
.pop_front();
2746 // If there are more pending file chooser requests, schedule one now.
2747 if (!file_chooser_completions_
.empty()) {
2748 Send(new ViewHostMsg_RunFileChooser(routing_id_
,
2749 file_chooser_completions_
.front()->params
));
2753 void RenderViewImpl::OnEnableAutoResize(const gfx::Size
& min_size
,
2754 const gfx::Size
& max_size
) {
2755 DCHECK(disable_scrollbars_size_limit_
.IsEmpty());
2758 auto_resize_mode_
= true;
2759 webview()->enableAutoResizeMode(min_size
, max_size
);
2762 void RenderViewImpl::OnDisableAutoResize(const gfx::Size
& new_size
) {
2763 DCHECK(disable_scrollbars_size_limit_
.IsEmpty());
2766 auto_resize_mode_
= false;
2767 webview()->disableAutoResizeMode();
2769 if (!new_size
.IsEmpty()) {
2771 physical_backing_size_
,
2772 top_controls_shrink_blink_size_
,
2773 top_controls_height_
,
2774 visible_viewport_size_
,
2776 is_fullscreen_granted_
,
2782 void RenderViewImpl::OnEnablePreferredSizeChangedMode() {
2783 if (send_preferred_size_changes_
)
2785 send_preferred_size_changes_
= true;
2787 // Start off with an initial preferred size notification (in case
2788 // |didUpdateLayout| was already called).
2792 void RenderViewImpl::OnDisableScrollbarsForSmallWindows(
2793 const gfx::Size
& disable_scrollbar_size_limit
) {
2794 disable_scrollbars_size_limit_
= disable_scrollbar_size_limit
;
2797 void RenderViewImpl::OnSetRendererPrefs(
2798 const RendererPreferences
& renderer_prefs
) {
2799 double old_zoom_level
= renderer_preferences_
.default_zoom_level
;
2800 std::string old_accept_languages
= renderer_preferences_
.accept_languages
;
2802 renderer_preferences_
= renderer_prefs
;
2804 UpdateFontRenderingFromRendererPrefs();
2807 #if defined(USE_DEFAULT_RENDER_THEME)
2808 if (renderer_prefs
.use_custom_colors
) {
2809 WebColorName name
= blink::WebColorWebkitFocusRingColor
;
2810 blink::setNamedColors(&name
, &renderer_prefs
.focus_ring_color
, 1);
2811 blink::setCaretBlinkInterval(renderer_prefs
.caret_blink_interval
);
2814 webview()->setSelectionColors(
2815 renderer_prefs
.active_selection_bg_color
,
2816 renderer_prefs
.active_selection_fg_color
,
2817 renderer_prefs
.inactive_selection_bg_color
,
2818 renderer_prefs
.inactive_selection_fg_color
);
2819 webview()->themeChanged();
2822 #endif // defined(USE_DEFAULT_RENDER_THEME)
2824 // If the zoom level for this page matches the old zoom default, and this
2825 // is not a plugin, update the zoom level to match the new default.
2826 if (webview() && webview()->mainFrame()->isWebLocalFrame() &&
2827 !webview()->mainFrame()->document().isPluginDocument() &&
2828 !ZoomValuesEqual(old_zoom_level
,
2829 renderer_preferences_
.default_zoom_level
) &&
2830 ZoomValuesEqual(webview()->zoomLevel(), old_zoom_level
)) {
2831 SetZoomLevel(renderer_preferences_
.default_zoom_level
);
2836 old_accept_languages
!= renderer_preferences_
.accept_languages
) {
2837 webview()->acceptLanguagesChanged();
2841 void RenderViewImpl::OnMediaPlayerActionAt(const gfx::Point
& location
,
2842 const WebMediaPlayerAction
& action
) {
2844 webview()->performMediaPlayerAction(action
, location
);
2847 void RenderViewImpl::OnOrientationChange() {
2848 if (webview() && webview()->mainFrame()->isWebLocalFrame())
2849 webview()->mainFrame()->toWebLocalFrame()->sendOrientationChangeEvent();
2852 void RenderViewImpl::OnPluginActionAt(const gfx::Point
& location
,
2853 const WebPluginAction
& action
) {
2855 webview()->performPluginAction(action
, location
);
2858 void RenderViewImpl::OnGetAllSavableResourceLinksForCurrentPage(
2859 const GURL
& page_url
) {
2860 // Prepare list to storage all savable resource links.
2861 std::vector
<GURL
> resources_list
;
2862 std::vector
<GURL
> referrer_urls_list
;
2863 std::vector
<blink::WebReferrerPolicy
> referrer_policies_list
;
2864 std::vector
<GURL
> frames_list
;
2865 SavableResourcesResult
result(&resources_list
,
2866 &referrer_urls_list
,
2867 &referrer_policies_list
,
2870 // webkit/ doesn't know about Referrer.
2871 if (!GetAllSavableResourceLinksForCurrentPage(
2875 const_cast<const char**>(GetSavableSchemes()))) {
2876 // If something is wrong when collecting all savable resource links,
2877 // send empty list to embedder(browser) to tell it failed.
2878 referrer_urls_list
.clear();
2879 referrer_policies_list
.clear();
2880 resources_list
.clear();
2881 frames_list
.clear();
2884 std::vector
<Referrer
> referrers_list
;
2885 CHECK_EQ(referrer_urls_list
.size(), referrer_policies_list
.size());
2886 for (unsigned i
= 0; i
< referrer_urls_list
.size(); ++i
) {
2887 referrers_list
.push_back(
2888 Referrer(referrer_urls_list
[i
], referrer_policies_list
[i
]));
2891 // Send result of all savable resource links to embedder.
2892 Send(new ViewHostMsg_SendCurrentPageAllSavableResourceLinks(routing_id(),
2898 void RenderViewImpl::OnGetSerializedHtmlDataForCurrentPageWithLocalLinks(
2899 const std::vector
<GURL
>& links
,
2900 const std::vector
<base::FilePath
>& local_paths
,
2901 const base::FilePath
& local_directory_name
) {
2903 // Convert std::vector of GURLs to WebVector<WebURL>
2904 WebVector
<WebURL
> weburl_links(links
);
2906 // Convert std::vector of base::FilePath to WebVector<WebString>
2907 WebVector
<WebString
> webstring_paths(local_paths
.size());
2908 for (size_t i
= 0; i
< local_paths
.size(); i
++)
2909 webstring_paths
[i
] = local_paths
[i
].AsUTF16Unsafe();
2911 WebPageSerializer::serialize(webview()->mainFrame()->toWebLocalFrame(),
2916 local_directory_name
.AsUTF16Unsafe());
2919 void RenderViewImpl::OnSuppressDialogsUntilSwapOut() {
2920 // Don't show any more dialogs until we finish OnSwapOut.
2921 suppress_dialogs_until_swap_out_
= true;
2924 void RenderViewImpl::OnClosePage() {
2925 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, ClosePage());
2926 // TODO(creis): We'd rather use webview()->Close() here, but that currently
2927 // sets the WebView's delegate_ to NULL, preventing any JavaScript dialogs
2928 // in the onunload handler from appearing. For now, we're bypassing that and
2929 // calling the FrameLoader's CloseURL method directly. This should be
2930 // revisited to avoid having two ways to close a page. Having a single way
2931 // to close that can run onunload is also useful for fixing
2932 // http://b/issue?id=753080.
2933 webview()->mainFrame()->dispatchUnloadEvent();
2935 Send(new ViewHostMsg_ClosePage_ACK(routing_id_
));
2938 void RenderViewImpl::OnClose() {
2940 RenderThread::Get()->Send(new ViewHostMsg_Close_ACK(routing_id_
));
2941 RenderWidget::OnClose();
2944 void RenderViewImpl::OnThemeChanged() {
2945 #if defined(USE_AURA)
2946 // Aura doesn't care if we switch themes.
2947 #elif defined(OS_WIN)
2948 ui::NativeThemeWin::instance()->CloseHandles();
2950 webview()->themeChanged();
2951 #else // defined(OS_WIN)
2952 // TODO(port): we don't support theming on non-Windows platforms yet
2957 void RenderViewImpl::OnMoveOrResizeStarted() {
2959 webview()->hidePopups();
2962 void RenderViewImpl::OnResize(const ViewMsg_Resize_Params
& params
) {
2963 TRACE_EVENT0("renderer", "RenderViewImpl::OnResize");
2965 webview()->hidePopups();
2966 if (send_preferred_size_changes_
) {
2967 webview()->mainFrame()->setCanHaveScrollbars(
2968 ShouldDisplayScrollbars(params
.new_size
.width(),
2969 params
.new_size
.height()));
2971 if (display_mode_
!= params
.display_mode
) {
2972 display_mode_
= params
.display_mode
;
2973 webview()->setDisplayMode(display_mode_
);
2977 gfx::Size old_visible_viewport_size
= visible_viewport_size_
;
2979 RenderWidget::OnResize(params
);
2981 if (old_visible_viewport_size
!= visible_viewport_size_
)
2982 has_scrolled_focused_editable_node_into_rect_
= false;
2985 void RenderViewImpl::DidInitiatePaint() {
2986 #if defined(ENABLE_PLUGINS)
2987 // Notify all instances that we painted. The same caveats apply as for
2988 // ViewFlushedPaint regarding instances closing themselves, so we take
2989 // similar precautions.
2990 PepperPluginSet plugins
= active_pepper_instances_
;
2991 for (PepperPluginSet::iterator i
= plugins
.begin(); i
!= plugins
.end(); ++i
) {
2992 if (active_pepper_instances_
.find(*i
) != active_pepper_instances_
.end())
2993 (*i
)->ViewInitiatedPaint();
2998 void RenderViewImpl::DidFlushPaint() {
2999 // If the RenderWidget is closing down then early-exit, otherwise we'll crash.
3000 // See crbug.com/112921.
3004 WebFrame
* main_frame
= webview()->mainFrame();
3005 for (WebFrame
* frame
= main_frame
; frame
;
3006 frame
= frame
->traverseNext(false)) {
3007 // TODO(nasko): This is a hack for the case in which the top-level
3008 // frame is being rendered in another process. It will not
3009 // behave correctly for out of process iframes.
3010 if (frame
->isWebLocalFrame()) {
3016 // There's nothing to do if there are no local frames in this RenderView's
3017 // frame tree. This can happen if DidFlushPaint is called after the
3018 // RenderView's local main frame is swapped to a remote frame. See
3019 // http://crbug.com/513552.
3020 if (main_frame
->isWebRemoteFrame())
3023 // If we have a provisional frame we are between the start and commit stages
3024 // of loading and we don't want to save stats.
3025 if (!main_frame
->provisionalDataSource()) {
3026 WebDataSource
* ds
= main_frame
->dataSource();
3030 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3032 // TODO(jar): The following code should all be inside a method, probably in
3034 Time now
= Time::Now();
3035 if (document_state
->first_paint_time().is_null()) {
3036 document_state
->set_first_paint_time(now
);
3038 if (document_state
->first_paint_after_load_time().is_null() &&
3039 !document_state
->finish_load_time().is_null()) {
3040 document_state
->set_first_paint_after_load_time(now
);
3045 gfx::Vector2d
RenderViewImpl::GetScrollOffset() {
3046 WebFrame
* main_frame
= webview()->mainFrame();
3047 for (WebFrame
* frame
= main_frame
; frame
;
3048 frame
= frame
->traverseNext(false)) {
3049 // TODO(nasko): This is a hack for the case in which the top-level
3050 // frame is being rendered in another process. It will not
3051 // behave correctly for out of process iframes.
3052 if (frame
->isWebLocalFrame()) {
3058 WebSize scroll_offset
= main_frame
->scrollOffset();
3059 return gfx::Vector2d(scroll_offset
.width
, scroll_offset
.height
);
3062 void RenderViewImpl::OnClearFocusedElement() {
3064 webview()->clearFocusedElement();
3067 void RenderViewImpl::OnSetBackgroundOpaque(bool opaque
) {
3069 webview()->setIsTransparent(!opaque
);
3071 compositor_
->setHasTransparentBackground(!opaque
);
3074 void RenderViewImpl::OnSetActive(bool active
) {
3076 webview()->setIsActive(active
);
3078 #if defined(ENABLE_PLUGINS) && defined(OS_MACOSX)
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
)->SetWindowFocus(active
);
3087 #if defined(OS_MACOSX)
3088 void RenderViewImpl::OnSetWindowVisibility(bool visible
) {
3089 #if defined(ENABLE_PLUGINS)
3090 // Inform plugins that their container has changed visibility.
3091 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
3092 for (plugin_it
= plugin_delegates_
.begin();
3093 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
3094 (*plugin_it
)->SetContainerVisibility(visible
);
3099 void RenderViewImpl::OnWindowFrameChanged(const gfx::Rect
& window_frame
,
3100 const gfx::Rect
& view_frame
) {
3101 #if defined(ENABLE_PLUGINS)
3102 // Inform plugins that their window's frame has changed.
3103 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
3104 for (plugin_it
= plugin_delegates_
.begin();
3105 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
3106 (*plugin_it
)->WindowFrameChanged(window_frame
, view_frame
);
3111 void RenderViewImpl::OnPluginImeCompositionCompleted(const base::string16
& text
,
3113 // WebPluginDelegateProxy is responsible for figuring out if this event
3114 // applies to it or not, so inform all the delegates.
3115 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
3116 for (plugin_it
= plugin_delegates_
.begin();
3117 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
3118 (*plugin_it
)->ImeCompositionCompleted(text
, plugin_id
);
3123 void RenderViewImpl::Close() {
3124 // We need to grab a pointer to the doomed WebView before we destroy it.
3125 WebView
* doomed
= webview();
3126 RenderWidget::Close();
3127 g_view_map
.Get().erase(doomed
);
3128 g_routing_id_view_map
.Get().erase(routing_id_
);
3129 RenderThread::Get()->Send(new ViewHostMsg_Close_ACK(routing_id_
));
3132 void RenderViewImpl::DidHandleKeyEvent() {
3133 ClearEditCommands();
3136 bool RenderViewImpl::WillHandleMouseEvent(const blink::WebMouseEvent
& event
) {
3137 possible_drag_event_info_
.event_source
=
3138 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE
;
3139 possible_drag_event_info_
.event_location
=
3140 gfx::Point(event
.globalX
, event
.globalY
);
3142 #if defined(ENABLE_PLUGINS)
3143 // This method is called for every mouse event that the render view receives.
3144 // And then the mouse event is forwarded to WebKit, which dispatches it to the
3145 // event target. Potentially a Pepper plugin will receive the event.
3146 // In order to tell whether a plugin gets the last mouse event and which it
3147 // is, we set |pepper_last_mouse_event_target_| to NULL here. If a plugin gets
3148 // the event, it will notify us via DidReceiveMouseEvent() and set itself as
3149 // |pepper_last_mouse_event_target_|.
3150 pepper_last_mouse_event_target_
= NULL
;
3153 // If the mouse is locked, only the current owner of the mouse lock can
3154 // process mouse events.
3155 return mouse_lock_dispatcher_
->WillHandleMouseEvent(event
);
3158 bool RenderViewImpl::WillHandleGestureEvent(
3159 const blink::WebGestureEvent
& event
) {
3160 possible_drag_event_info_
.event_source
=
3161 ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH
;
3162 possible_drag_event_info_
.event_location
=
3163 gfx::Point(event
.globalX
, event
.globalY
);
3167 bool RenderViewImpl::HasTouchEventHandlersAt(const gfx::Point
& point
) const {
3170 return webview()->hasTouchEventHandlersAt(point
);
3173 void RenderViewImpl::OnWasHidden() {
3174 RenderWidget::OnWasHidden();
3176 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3177 RenderThreadImpl::current()->video_capture_impl_manager()->
3178 SuspendDevices(true);
3179 if (speech_recognition_dispatcher_
)
3180 speech_recognition_dispatcher_
->AbortAllRecognitions();
3184 webview()->setVisibilityState(visibilityState(), false);
3186 #if defined(ENABLE_PLUGINS)
3187 for (PepperPluginSet::iterator i
= active_pepper_instances_
.begin();
3188 i
!= active_pepper_instances_
.end(); ++i
)
3189 (*i
)->PageVisibilityChanged(false);
3191 #if defined(OS_MACOSX)
3192 // Inform NPAPI plugins that their container is no longer visible.
3193 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
3194 for (plugin_it
= plugin_delegates_
.begin();
3195 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
3196 (*plugin_it
)->SetContainerVisibility(false);
3199 #endif // ENABLE_PLUGINS
3202 void RenderViewImpl::OnWasShown(bool needs_repainting
,
3203 const ui::LatencyInfo
& latency_info
) {
3204 RenderWidget::OnWasShown(needs_repainting
, latency_info
);
3206 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3207 RenderThreadImpl::current()->video_capture_impl_manager()->
3208 SuspendDevices(false);
3212 webview()->setVisibilityState(visibilityState(), false);
3214 #if defined(ENABLE_PLUGINS)
3215 for (PepperPluginSet::iterator i
= active_pepper_instances_
.begin();
3216 i
!= active_pepper_instances_
.end(); ++i
)
3217 (*i
)->PageVisibilityChanged(true);
3219 #if defined(OS_MACOSX)
3220 // Inform NPAPI plugins that their container is now visible.
3221 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
3222 for (plugin_it
= plugin_delegates_
.begin();
3223 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
3224 (*plugin_it
)->SetContainerVisibility(true);
3227 #endif // ENABLE_PLUGINS
3230 GURL
RenderViewImpl::GetURLForGraphicsContext3D() {
3232 if (webview()->mainFrame()->isWebLocalFrame())
3233 return GURL(webview()->mainFrame()->document().url());
3235 return GURL("chrome://gpu/RenderViewImpl::CreateGraphicsContext3D");
3238 void RenderViewImpl::OnSetFocus(bool enable
) {
3239 RenderWidget::OnSetFocus(enable
);
3241 #if defined(ENABLE_PLUGINS)
3242 if (webview() && webview()->isActive()) {
3243 // Notify all NPAPI plugins.
3244 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
3245 for (plugin_it
= plugin_delegates_
.begin();
3246 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
3247 #if defined(OS_MACOSX)
3248 // RenderWidget's call to setFocus can cause the underlying webview's
3249 // activation state to change just like a call to setIsActive.
3251 (*plugin_it
)->SetWindowFocus(true);
3253 (*plugin_it
)->SetContentAreaFocus(enable
);
3256 // Notify all Pepper plugins.
3257 for (PepperPluginSet::iterator i
= active_pepper_instances_
.begin();
3258 i
!= active_pepper_instances_
.end(); ++i
)
3259 (*i
)->SetContentAreaFocus(enable
);
3261 // Notify all BrowserPlugins of the RenderView's focus state.
3262 if (BrowserPluginManager::Get())
3263 BrowserPluginManager::Get()->UpdateFocusState();
3266 void RenderViewImpl::OnImeSetComposition(
3267 const base::string16
& text
,
3268 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
3269 int selection_start
,
3270 int selection_end
) {
3271 #if defined(ENABLE_PLUGINS)
3272 if (focused_pepper_plugin_
) {
3273 focused_pepper_plugin_
->render_frame()->OnImeSetComposition(
3274 text
, underlines
, selection_start
, selection_end
);
3279 // When a plugin has focus, we create platform-specific IME data used by
3280 // our IME emulator and send it directly to the focused plugin, i.e. we
3281 // bypass WebKit. (WebPluginDelegate dispatches this IME data only when its
3282 // instance ID is the same one as the specified ID.)
3283 if (focused_plugin_id_
>= 0) {
3284 std::vector
<int> clauses
;
3285 std::vector
<int> target
;
3286 for (size_t i
= 0; i
< underlines
.size(); ++i
) {
3287 clauses
.push_back(underlines
[i
].startOffset
);
3288 clauses
.push_back(underlines
[i
].endOffset
);
3289 if (underlines
[i
].thick
) {
3291 target
.push_back(underlines
[i
].startOffset
);
3292 target
.push_back(underlines
[i
].endOffset
);
3295 std::set
<WebPluginDelegateProxy
*>::iterator it
;
3296 for (it
= plugin_delegates_
.begin(); it
!= plugin_delegates_
.end(); ++it
) {
3297 (*it
)->ImeCompositionUpdated(text
, clauses
, target
, selection_end
,
3298 focused_plugin_id_
);
3303 #endif // ENABLE_PLUGINS
3304 RenderWidget::OnImeSetComposition(text
,
3310 void RenderViewImpl::OnImeConfirmComposition(
3311 const base::string16
& text
,
3312 const gfx::Range
& replacement_range
,
3313 bool keep_selection
) {
3314 #if defined(ENABLE_PLUGINS)
3315 if (focused_pepper_plugin_
) {
3316 focused_pepper_plugin_
->render_frame()->OnImeConfirmComposition(
3317 text
, replacement_range
, keep_selection
);
3321 // Same as OnImeSetComposition(), we send the text from IMEs directly to
3322 // plugins. When we send IME text directly to plugins, we should not send
3323 // it to WebKit to prevent WebKit from controlling IMEs.
3324 // TODO(thakis): Honor |replacement_range| for plugins?
3325 if (focused_plugin_id_
>= 0) {
3326 std::set
<WebPluginDelegateProxy
*>::iterator it
;
3327 for (it
= plugin_delegates_
.begin();
3328 it
!= plugin_delegates_
.end(); ++it
) {
3329 (*it
)->ImeCompositionCompleted(text
, focused_plugin_id_
);
3334 #endif // ENABLE_PLUGINS
3335 if (replacement_range
.IsValid() && webview()) {
3336 // Select the text in |replacement_range|, it will then be replaced by
3337 // text added by the call to RenderWidget::OnImeConfirmComposition().
3338 if (WebLocalFrame
* frame
= webview()->focusedFrame()->toWebLocalFrame()) {
3339 WebRange webrange
= WebRange::fromDocumentRange(
3340 frame
, replacement_range
.start(), replacement_range
.length());
3341 if (!webrange
.isNull())
3342 frame
->selectRange(webrange
);
3345 RenderWidget::OnImeConfirmComposition(text
,
3350 void RenderViewImpl::SetDeviceScaleFactor(float device_scale_factor
) {
3351 RenderWidget::SetDeviceScaleFactor(device_scale_factor
);
3353 webview()->setDeviceScaleFactor(device_scale_factor
);
3354 webview()->settings()->setPreferCompositingToLCDTextEnabled(
3355 PreferCompositingToLCDText(compositor_deps_
, device_scale_factor_
));
3357 if (auto_resize_mode_
)
3358 AutoResizeCompositor();
3361 bool RenderViewImpl::SetDeviceColorProfile(
3362 const std::vector
<char>& profile
) {
3363 bool changed
= RenderWidget::SetDeviceColorProfile(profile
);
3364 if (changed
&& webview()) {
3365 WebVector
<char> colorProfile
= profile
;
3366 webview()->setDeviceColorProfile(colorProfile
);
3371 void RenderViewImpl::ResetDeviceColorProfileForTesting() {
3372 RenderWidget::ResetDeviceColorProfileForTesting();
3374 webview()->resetDeviceColorProfile();
3377 ui::TextInputType
RenderViewImpl::GetTextInputType() {
3378 #if defined(ENABLE_PLUGINS)
3379 if (focused_pepper_plugin_
)
3380 return focused_pepper_plugin_
->text_input_type();
3382 return RenderWidget::GetTextInputType();
3385 void RenderViewImpl::GetSelectionBounds(gfx::Rect
* start
, gfx::Rect
* end
) {
3386 #if defined(ENABLE_PLUGINS)
3387 if (focused_pepper_plugin_
) {
3388 // TODO(kinaba) http://crbug.com/101101
3389 // Current Pepper IME API does not handle selection bounds. So we simply
3390 // use the caret position as an empty range for now. It will be updated
3391 // after Pepper API equips features related to surrounding text retrieval.
3392 gfx::Rect caret
= focused_pepper_plugin_
->GetCaretBounds();
3398 RenderWidget::GetSelectionBounds(start
, end
);
3401 void RenderViewImpl::FocusChangeComplete() {
3402 RenderWidget::FocusChangeComplete();
3403 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, FocusChangeComplete());
3406 void RenderViewImpl::GetCompositionCharacterBounds(
3407 std::vector
<gfx::Rect
>* bounds
) {
3411 #if defined(ENABLE_PLUGINS)
3412 if (focused_pepper_plugin_
) {
3419 size_t start_offset
= 0;
3420 size_t character_count
= 0;
3421 if (!webview()->compositionRange(&start_offset
, &character_count
))
3423 if (character_count
== 0)
3426 blink::WebFrame
* frame
= webview()->focusedFrame();
3430 bounds
->reserve(character_count
);
3431 blink::WebRect webrect
;
3432 for (size_t i
= 0; i
< character_count
; ++i
) {
3433 if (!frame
->firstRectForCharacterRange(start_offset
+ i
, 1, webrect
)) {
3434 DLOG(ERROR
) << "Could not retrieve character rectangle at " << i
;
3438 bounds
->push_back(webrect
);
3442 void RenderViewImpl::GetCompositionRange(gfx::Range
* range
) {
3443 #if defined(ENABLE_PLUGINS)
3444 if (focused_pepper_plugin_
) {
3448 RenderWidget::GetCompositionRange(range
);
3451 bool RenderViewImpl::CanComposeInline() {
3452 #if defined(ENABLE_PLUGINS)
3453 if (focused_pepper_plugin_
)
3454 return focused_pepper_plugin_
->IsPluginAcceptingCompositionEvents();
3459 void RenderViewImpl::DidCompletePageScaleAnimation() {
3460 FocusChangeComplete();
3463 void RenderViewImpl::SetScreenMetricsEmulationParameters(
3465 const blink::WebDeviceEmulationParams
& params
) {
3466 if (webview() && compositor()) {
3468 webview()->enableDeviceEmulation(params
);
3470 webview()->disableDeviceEmulation();
3474 bool RenderViewImpl::ScheduleFileChooser(
3475 const FileChooserParams
& params
,
3476 WebFileChooserCompletion
* completion
) {
3477 static const size_t kMaximumPendingFileChooseRequests
= 4;
3478 if (file_chooser_completions_
.size() > kMaximumPendingFileChooseRequests
) {
3479 // This sanity check prevents too many file choose requests from getting
3480 // queued which could DoS the user. Getting these is most likely a
3481 // programming error (there are many ways to DoS the user so it's not
3482 // considered a "real" security check), either in JS requesting many file
3483 // choosers to pop up, or in a plugin.
3485 // TODO(brettw) we might possibly want to require a user gesture to open
3486 // a file picker, which will address this issue in a better way.
3490 file_chooser_completions_
.push_back(linked_ptr
<PendingFileChooser
>(
3491 new PendingFileChooser(params
, completion
)));
3492 if (file_chooser_completions_
.size() == 1) {
3493 // Actually show the browse dialog when this is the first request.
3494 Send(new ViewHostMsg_RunFileChooser(routing_id_
, params
));
3499 blink::WebSpeechRecognizer
* RenderViewImpl::speechRecognizer() {
3500 if (!speech_recognition_dispatcher_
)
3501 speech_recognition_dispatcher_
= new SpeechRecognitionDispatcher(this);
3502 return speech_recognition_dispatcher_
;
3505 void RenderViewImpl::zoomLimitsChanged(double minimum_level
,
3506 double maximum_level
) {
3507 // Round the double to avoid returning incorrect minimum/maximum zoom
3509 int minimum_percent
= round(
3510 ZoomLevelToZoomFactor(minimum_level
) * 100);
3511 int maximum_percent
= round(
3512 ZoomLevelToZoomFactor(maximum_level
) * 100);
3514 Send(new ViewHostMsg_UpdateZoomLimits(
3515 routing_id_
, minimum_percent
, maximum_percent
));
3518 void RenderViewImpl::zoomLevelChanged() {
3519 double zoom_level
= webview()->zoomLevel();
3521 // Do not send empty URLs to the browser when we are just setting the default
3522 // zoom level (from RendererPreferences) before the first navigation.
3523 if (!webview()->mainFrame()->document().url().isEmpty()) {
3524 // Tell the browser which url got zoomed so it can update the menu and the
3525 // saved values if necessary
3526 Send(new ViewHostMsg_DidZoomURL(
3527 routing_id_
, zoom_level
,
3528 GURL(webview()->mainFrame()->document().url())));
3532 void RenderViewImpl::pageScaleFactorChanged() {
3535 bool page_scale_factor_is_one
= webview()->pageScaleFactor() == 1;
3536 if (page_scale_factor_is_one
== page_scale_factor_is_one_
)
3538 page_scale_factor_is_one_
= page_scale_factor_is_one
;
3539 Send(new ViewHostMsg_PageScaleFactorIsOneChanged(routing_id_
,
3540 page_scale_factor_is_one_
));
3543 double RenderViewImpl::zoomLevelToZoomFactor(double zoom_level
) const {
3544 return ZoomLevelToZoomFactor(zoom_level
);
3547 double RenderViewImpl::zoomFactorToZoomLevel(double factor
) const {
3548 return ZoomFactorToZoomLevel(factor
);
3551 blink::WebPageVisibilityState
RenderViewImpl::visibilityState() const {
3552 blink::WebPageVisibilityState current_state
= is_hidden() ?
3553 blink::WebPageVisibilityStateHidden
:
3554 blink::WebPageVisibilityStateVisible
;
3555 blink::WebPageVisibilityState override_state
= current_state
;
3556 // TODO(jam): move this method to WebFrameClient.
3557 if (GetContentClient()->renderer()->
3558 ShouldOverridePageVisibilityState(main_render_frame_
,
3560 return override_state
;
3561 return current_state
;
3564 void RenderViewImpl::draggableRegionsChanged() {
3568 DraggableRegionsChanged(webview()->mainFrame()));
3571 #if defined(OS_ANDROID)
3572 WebContentDetectionResult
RenderViewImpl::detectContentAround(
3573 const WebHitTestResult
& touch_hit
) {
3574 DCHECK(touch_hit
.node().isTextNode());
3576 // Process the position with all the registered content detectors until
3577 // a match is found. Priority is provided by their relative order.
3578 for (ContentDetectorList::const_iterator it
= content_detectors_
.begin();
3579 it
!= content_detectors_
.end(); ++it
) {
3580 ContentDetector::Result content
= (*it
)->FindTappedContent(touch_hit
);
3581 if (content
.valid
) {
3582 return WebContentDetectionResult(content
.content_boundaries
,
3583 base::UTF8ToUTF16(content
.text
), content
.intent_url
);
3586 return WebContentDetectionResult();
3589 void RenderViewImpl::scheduleContentIntent(const WebURL
& intent
) {
3590 // Introduce a short delay so that the user can notice the content.
3591 base::MessageLoop::current()->PostDelayedTask(
3593 base::Bind(&RenderViewImpl::LaunchAndroidContentIntent
,
3596 expected_content_intent_id_
),
3597 base::TimeDelta::FromMilliseconds(kContentIntentDelayMilliseconds
));
3600 void RenderViewImpl::cancelScheduledContentIntents() {
3601 ++expected_content_intent_id_
;
3604 void RenderViewImpl::LaunchAndroidContentIntent(const GURL
& intent
,
3605 size_t request_id
) {
3606 if (request_id
!= expected_content_intent_id_
)
3609 // Remove the content highlighting if any.
3610 ScheduleComposite();
3612 if (!intent
.is_empty())
3613 Send(new ViewHostMsg_StartContentIntent(routing_id_
, intent
));
3616 bool RenderViewImpl::openDateTimeChooser(
3617 const blink::WebDateTimeChooserParams
& params
,
3618 blink::WebDateTimeChooserCompletion
* completion
) {
3619 // JavaScript may try to open a date time chooser while one is already open.
3620 if (date_time_picker_client_
)
3622 date_time_picker_client_
.reset(
3623 new RendererDateTimePicker(this, params
, completion
));
3624 return date_time_picker_client_
->Open();
3627 void RenderViewImpl::DismissDateTimeDialog() {
3628 DCHECK(date_time_picker_client_
);
3629 date_time_picker_client_
.reset(NULL
);
3632 #endif // defined(OS_ANDROID)
3634 void RenderViewImpl::OnShowContextMenu(
3635 ui::MenuSourceType source_type
, const gfx::Point
& location
) {
3636 context_menu_source_type_
= source_type
;
3637 has_host_context_menu_location_
= true;
3638 host_context_menu_location_
= location
;
3640 webview()->showContextMenu();
3641 has_host_context_menu_location_
= false;
3644 void RenderViewImpl::OnEnableViewSourceMode() {
3647 WebFrame
* main_frame
= webview()->mainFrame();
3650 main_frame
->enableViewSourceMode(true);
3653 #if defined(OS_ANDROID) || defined(USE_AURA)
3654 bool RenderViewImpl::didTapMultipleTargets(
3655 const WebSize
& inner_viewport_offset
,
3656 const WebRect
& touch_rect
,
3657 const WebVector
<WebRect
>& target_rects
) {
3658 DCHECK(switches::IsLinkDisambiguationPopupEnabled());
3660 // Never show a disambiguation popup when accessibility is enabled,
3661 // as this interferes with "touch exploration".
3662 AccessibilityMode accessibility_mode
=
3663 GetMainRenderFrame()->accessibility_mode();
3664 bool matches_accessibility_mode_complete
=
3665 (accessibility_mode
& AccessibilityModeComplete
) ==
3666 AccessibilityModeComplete
;
3667 if (matches_accessibility_mode_complete
)
3670 // The touch_rect, target_rects and zoom_rect are in the outer viewport
3672 gfx::Rect zoom_rect
;
3673 float new_total_scale
=
3674 DisambiguationPopupHelper::ComputeZoomAreaAndScaleFactor(
3675 touch_rect
, target_rects
, GetSize(),
3676 gfx::Rect(webview()->mainFrame()->visibleContentRect()).size(),
3677 device_scale_factor_
* webview()->pageScaleFactor(), &zoom_rect
);
3678 if (!new_total_scale
|| zoom_rect
.IsEmpty())
3681 bool handled
= false;
3682 switch (renderer_preferences_
.tap_multiple_targets_strategy
) {
3683 case TAP_MULTIPLE_TARGETS_STRATEGY_ZOOM
:
3684 handled
= webview()->zoomToMultipleTargetsRect(zoom_rect
);
3686 case TAP_MULTIPLE_TARGETS_STRATEGY_POPUP
: {
3687 gfx::Size canvas_size
=
3688 gfx::ToCeiledSize(gfx::ScaleSize(zoom_rect
.size(), new_total_scale
));
3689 cc::SharedBitmapManager
* manager
=
3690 RenderThreadImpl::current()->shared_bitmap_manager();
3691 scoped_ptr
<cc::SharedBitmap
> shared_bitmap
=
3692 manager
->AllocateSharedBitmap(canvas_size
);
3693 CHECK(!!shared_bitmap
);
3696 SkImageInfo info
= SkImageInfo::MakeN32Premul(canvas_size
.width(),
3697 canvas_size
.height());
3698 bitmap
.installPixels(info
, shared_bitmap
->pixels(), info
.minRowBytes());
3699 SkCanvas
canvas(bitmap
);
3701 // TODO(trchen): Cleanup the device scale factor mess.
3702 // device scale will be applied in WebKit
3703 // --> zoom_rect doesn't include device scale,
3704 // but WebKit will still draw on zoom_rect * device_scale_factor_
3705 canvas
.scale(new_total_scale
/ device_scale_factor_
,
3706 new_total_scale
/ device_scale_factor_
);
3707 canvas
.translate(-zoom_rect
.x() * device_scale_factor_
,
3708 -zoom_rect
.y() * device_scale_factor_
);
3710 DCHECK(webwidget_
->isAcceleratedCompositingActive());
3711 // TODO(aelias): The disambiguation popup should be composited so we
3712 // don't have to call this method.
3713 webwidget_
->paintCompositedDeprecated(&canvas
, zoom_rect
);
3716 gfx::Rect zoom_rect_in_screen
=
3717 zoom_rect
- gfx::Vector2d(inner_viewport_offset
.width
,
3718 inner_viewport_offset
.height
);
3720 gfx::Rect physical_window_zoom_rect
= gfx::ToEnclosingRect(
3721 ClientRectToPhysicalWindowRect(gfx::RectF(zoom_rect_in_screen
)));
3723 Send(new ViewHostMsg_ShowDisambiguationPopup(routing_id_
,
3724 physical_window_zoom_rect
,
3726 shared_bitmap
->id()));
3727 cc::SharedBitmapId id
= shared_bitmap
->id();
3728 disambiguation_bitmaps_
[id
] = shared_bitmap
.release();
3732 case TAP_MULTIPLE_TARGETS_STRATEGY_NONE
:
3739 #endif // defined(OS_ANDROID) || defined(USE_AURA)
3741 unsigned RenderViewImpl::GetLocalSessionHistoryLengthForTesting() const {
3742 return history_list_length_
;
3745 void RenderViewImpl::SetFocusAndActivateForTesting(bool enable
) {
3759 void RenderViewImpl::SetDeviceScaleFactorForTesting(float factor
) {
3760 ViewMsg_Resize_Params params
;
3761 params
.screen_info
= screen_info_
;
3762 params
.screen_info
.deviceScaleFactor
= factor
;
3763 params
.new_size
= size();
3764 params
.visible_viewport_size
= visible_viewport_size_
;
3765 params
.physical_backing_size
=
3766 gfx::ToCeiledSize(gfx::ScaleSize(size(), factor
));
3767 params
.top_controls_shrink_blink_size
= false;
3768 params
.top_controls_height
= 0.f
;
3769 params
.resizer_rect
= WebRect();
3770 params
.is_fullscreen_granted
= is_fullscreen_granted();
3771 params
.display_mode
= display_mode_
;
3775 void RenderViewImpl::SetDeviceColorProfileForTesting(
3776 const std::vector
<char>& color_profile
) {
3777 SetDeviceColorProfile(color_profile
);
3780 void RenderViewImpl::ForceResizeForTesting(const gfx::Size
& new_size
) {
3781 gfx::Rect
new_window_rect(rootWindowRect().x
,
3785 SetWindowRectSynchronously(new_window_rect
);
3788 void RenderViewImpl::UseSynchronousResizeModeForTesting(bool enable
) {
3789 resizing_mode_selector_
->set_is_synchronous_mode(enable
);
3792 void RenderViewImpl::EnableAutoResizeForTesting(const gfx::Size
& min_size
,
3793 const gfx::Size
& max_size
) {
3794 OnEnableAutoResize(min_size
, max_size
);
3797 void RenderViewImpl::DisableAutoResizeForTesting(const gfx::Size
& new_size
) {
3798 OnDisableAutoResize(new_size
);
3801 void RenderViewImpl::OnReleaseDisambiguationPopupBitmap(
3802 const cc::SharedBitmapId
& id
) {
3803 BitmapMap::iterator it
= disambiguation_bitmaps_
.find(id
);
3804 DCHECK(it
!= disambiguation_bitmaps_
.end());
3806 disambiguation_bitmaps_
.erase(it
);
3809 void RenderViewImpl::DidCommitCompositorFrame() {
3810 RenderWidget::DidCommitCompositorFrame();
3811 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidCommitCompositorFrame());
3814 void RenderViewImpl::SendUpdateFaviconURL(const std::vector
<FaviconURL
>& urls
) {
3816 Send(new ViewHostMsg_UpdateFaviconURL(routing_id_
, urls
));
3819 void RenderViewImpl::DidStopLoadingIcons() {
3820 int icon_types
= WebIconURL::TypeFavicon
| WebIconURL::TypeTouchPrecomposed
|
3821 WebIconURL::TypeTouch
;
3823 // Favicons matter only for the top-level frame. If it is a WebRemoteFrame,
3824 // just return early.
3825 if (webview()->mainFrame()->isWebRemoteFrame())
3828 WebVector
<WebIconURL
> icon_urls
=
3829 webview()->mainFrame()->iconURLs(icon_types
);
3831 std::vector
<FaviconURL
> urls
;
3832 for (size_t i
= 0; i
< icon_urls
.size(); i
++) {
3833 WebURL url
= icon_urls
[i
].iconURL();
3834 std::vector
<gfx::Size
> sizes
;
3835 ConvertToFaviconSizes(icon_urls
[i
].sizes(), &sizes
);
3838 FaviconURL(url
, ToFaviconType(icon_urls
[i
].iconType()), sizes
));
3840 SendUpdateFaviconURL(urls
);
3843 } // namespace content