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/ssl_status_serialization.h"
50 #include "content/common/view_messages.h"
51 #include "content/public/common/bindings_policy.h"
52 #include "content/public/common/content_client.h"
53 #include "content/public/common/content_constants.h"
54 #include "content/public/common/content_switches.h"
55 #include "content/public/common/drop_data.h"
56 #include "content/public/common/favicon_url.h"
57 #include "content/public/common/file_chooser_file_info.h"
58 #include "content/public/common/file_chooser_params.h"
59 #include "content/public/common/page_state.h"
60 #include "content/public/common/page_zoom.h"
61 #include "content/public/common/ssl_status.h"
62 #include "content/public/common/three_d_api_types.h"
63 #include "content/public/common/url_constants.h"
64 #include "content/public/common/url_utils.h"
65 #include "content/public/common/web_preferences.h"
66 #include "content/public/renderer/content_renderer_client.h"
67 #include "content/public/renderer/document_state.h"
68 #include "content/public/renderer/navigation_state.h"
69 #include "content/public/renderer/render_view_observer.h"
70 #include "content/public/renderer/render_view_visitor.h"
71 #include "content/renderer/browser_plugin/browser_plugin.h"
72 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
73 #include "content/renderer/disambiguation_popup_helper.h"
74 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
75 #include "content/renderer/drop_data_builder.h"
76 #include "content/renderer/gpu/render_widget_compositor.h"
77 #include "content/renderer/history_controller.h"
78 #include "content/renderer/history_serialization.h"
79 #include "content/renderer/idle_user_detector.h"
80 #include "content/renderer/ime_event_guard.h"
81 #include "content/renderer/input/input_handler_manager.h"
82 #include "content/renderer/internal_document_state_data.h"
83 #include "content/renderer/media/audio_device_factory.h"
84 #include "content/renderer/media/video_capture_impl_manager.h"
85 #include "content/renderer/mhtml_generator.h"
86 #include "content/renderer/navigation_state_impl.h"
87 #include "content/renderer/net_info_helper.h"
88 #include "content/renderer/render_frame_impl.h"
89 #include "content/renderer/render_frame_proxy.h"
90 #include "content/renderer/render_process.h"
91 #include "content/renderer/render_thread_impl.h"
92 #include "content/renderer/render_view_mouse_lock_dispatcher.h"
93 #include "content/renderer/render_widget_fullscreen_pepper.h"
94 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
95 #include "content/renderer/resizing_mode_selector.h"
96 #include "content/renderer/savable_resources.h"
97 #include "content/renderer/speech_recognition_dispatcher.h"
98 #include "content/renderer/text_input_client_observer.h"
99 #include "content/renderer/web_ui_extension_data.h"
100 #include "content/renderer/web_ui_mojo.h"
101 #include "content/renderer/websharedworker_proxy.h"
102 #include "media/audio/audio_output_device.h"
103 #include "media/base/media_switches.h"
104 #include "media/renderers/audio_renderer_impl.h"
105 #include "media/renderers/gpu_video_accelerator_factories.h"
106 #include "net/base/data_url.h"
107 #include "net/base/escape.h"
108 #include "net/base/net_errors.h"
109 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
110 #include "net/http/http_util.h"
111 #include "skia/ext/platform_canvas.h"
112 #include "third_party/WebKit/public/platform/WebCString.h"
113 #include "third_party/WebKit/public/platform/WebConnectionType.h"
114 #include "third_party/WebKit/public/platform/WebDragData.h"
115 #include "third_party/WebKit/public/platform/WebHTTPBody.h"
116 #include "third_party/WebKit/public/platform/WebImage.h"
117 #include "third_party/WebKit/public/platform/WebMessagePortChannel.h"
118 #include "third_party/WebKit/public/platform/WebPoint.h"
119 #include "third_party/WebKit/public/platform/WebRect.h"
120 #include "third_party/WebKit/public/platform/WebSize.h"
121 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
122 #include "third_party/WebKit/public/platform/WebString.h"
123 #include "third_party/WebKit/public/platform/WebURL.h"
124 #include "third_party/WebKit/public/platform/WebURLError.h"
125 #include "third_party/WebKit/public/platform/WebURLRequest.h"
126 #include "third_party/WebKit/public/platform/WebURLResponse.h"
127 #include "third_party/WebKit/public/platform/WebVector.h"
128 #include "third_party/WebKit/public/web/WebAXObject.h"
129 #include "third_party/WebKit/public/web/WebColorName.h"
130 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
131 #include "third_party/WebKit/public/web/WebDOMEvent.h"
132 #include "third_party/WebKit/public/web/WebDOMMessageEvent.h"
133 #include "third_party/WebKit/public/web/WebDataSource.h"
134 #include "third_party/WebKit/public/web/WebDateTimeChooserCompletion.h"
135 #include "third_party/WebKit/public/web/WebDateTimeChooserParams.h"
136 #include "third_party/WebKit/public/web/WebDocument.h"
137 #include "third_party/WebKit/public/web/WebElement.h"
138 #include "third_party/WebKit/public/web/WebFileChooserParams.h"
139 #include "third_party/WebKit/public/web/WebFindOptions.h"
140 #include "third_party/WebKit/public/web/WebFormControlElement.h"
141 #include "third_party/WebKit/public/web/WebFormElement.h"
142 #include "third_party/WebKit/public/web/WebFrame.h"
143 #include "third_party/WebKit/public/web/WebGlyphCache.h"
144 #include "third_party/WebKit/public/web/WebHistoryItem.h"
145 #include "third_party/WebKit/public/web/WebHitTestResult.h"
146 #include "third_party/WebKit/public/web/WebInputElement.h"
147 #include "third_party/WebKit/public/web/WebInputEvent.h"
148 #include "third_party/WebKit/public/web/WebLocalFrame.h"
149 #include "third_party/WebKit/public/web/WebMediaPlayerAction.h"
150 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
151 #include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
152 #include "third_party/WebKit/public/web/WebNodeList.h"
153 #include "third_party/WebKit/public/web/WebPageSerializer.h"
154 #include "third_party/WebKit/public/web/WebPlugin.h"
155 #include "third_party/WebKit/public/web/WebPluginAction.h"
156 #include "third_party/WebKit/public/web/WebPluginContainer.h"
157 #include "third_party/WebKit/public/web/WebPluginDocument.h"
158 #include "third_party/WebKit/public/web/WebRange.h"
159 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
160 #include "third_party/WebKit/public/web/WebScriptSource.h"
161 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
162 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
163 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
164 #include "third_party/WebKit/public/web/WebSettings.h"
165 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
166 #include "third_party/WebKit/public/web/WebView.h"
167 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
168 #include "third_party/WebKit/public/web/default/WebRenderTheme.h"
169 #include "third_party/icu/source/common/unicode/uchar.h"
170 #include "third_party/icu/source/common/unicode/uscript.h"
171 #include "ui/base/clipboard/clipboard.h"
172 #include "ui/base/ui_base_switches_util.h"
173 #include "ui/events/latency_info.h"
174 #include "ui/gfx/geometry/point.h"
175 #include "ui/gfx/geometry/rect.h"
176 #include "ui/gfx/geometry/rect_conversions.h"
177 #include "ui/gfx/geometry/size_conversions.h"
178 #include "ui/gfx/native_widget_types.h"
179 #include "v8/include/v8.h"
181 #if defined(OS_ANDROID)
182 #include <cpu-features.h>
184 #include "content/renderer/android/address_detector.h"
185 #include "content/renderer/android/content_detector.h"
186 #include "content/renderer/android/email_detector.h"
187 #include "content/renderer/android/phone_number_detector.h"
188 #include "third_party/WebKit/public/platform/WebFloatPoint.h"
189 #include "third_party/WebKit/public/platform/WebFloatRect.h"
190 #include "ui/gfx/geometry/rect_f.h"
192 #elif defined(OS_WIN)
193 // TODO(port): these files are currently Windows only because they concern:
195 #include "ui/native_theme/native_theme_win.h"
196 #elif defined(USE_X11)
197 #include "ui/native_theme/native_theme.h"
198 #elif defined(OS_MACOSX)
199 #include "skia/ext/skia_utils_mac.h"
202 #if defined(ENABLE_PLUGINS)
203 #include "content/renderer/npapi/webplugin_delegate_proxy.h"
204 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
205 #include "content/renderer/pepper/pepper_plugin_registry.h"
208 #if defined(ENABLE_WEBRTC)
209 #include "content/renderer/media/rtc_peer_connection_handler.h"
210 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
213 using blink::WebAXObject
;
214 using blink::WebApplicationCacheHost
;
215 using blink::WebApplicationCacheHostClient
;
216 using blink::WebCString
;
217 using blink::WebColor
;
218 using blink::WebColorName
;
219 using blink::WebConsoleMessage
;
220 using blink::WebData
;
221 using blink::WebDataSource
;
222 using blink::WebDocument
;
223 using blink::WebDragData
;
224 using blink::WebDragOperation
;
225 using blink::WebDragOperationsMask
;
226 using blink::WebElement
;
227 using blink::WebFileChooserCompletion
;
228 using blink::WebFindOptions
;
229 using blink::WebFormControlElement
;
230 using blink::WebFormElement
;
231 using blink::WebFrame
;
232 using blink::WebGestureEvent
;
233 using blink::WebHistoryItem
;
234 using blink::WebHTTPBody
;
235 using blink::WebIconURL
;
236 using blink::WebImage
;
237 using blink::WebInputElement
;
238 using blink::WebInputEvent
;
239 using blink::WebLocalFrame
;
240 using blink::WebMediaPlayerAction
;
241 using blink::WebMouseEvent
;
242 using blink::WebNavigationPolicy
;
243 using blink::WebNavigationType
;
244 using blink::WebNode
;
245 using blink::WebPageSerializer
;
246 using blink::WebPageSerializerClient
;
247 using blink::WebPeerConnection00Handler
;
248 using blink::WebPeerConnection00HandlerClient
;
249 using blink::WebPeerConnectionHandler
;
250 using blink::WebPeerConnectionHandlerClient
;
251 using blink::WebPluginAction
;
252 using blink::WebPluginContainer
;
253 using blink::WebPluginDocument
;
254 using blink::WebPoint
;
255 using blink::WebRange
;
256 using blink::WebRect
;
257 using blink::WebReferrerPolicy
;
258 using blink::WebScriptSource
;
259 using blink::WebSearchableFormData
;
260 using blink::WebSecurityOrigin
;
261 using blink::WebSecurityPolicy
;
262 using blink::WebSettings
;
263 using blink::WebSize
;
264 using blink::WebStorageNamespace
;
265 using blink::WebStorageQuotaCallbacks
;
266 using blink::WebStorageQuotaError
;
267 using blink::WebStorageQuotaType
;
268 using blink::WebString
;
269 using blink::WebTextAffinity
;
270 using blink::WebTextDirection
;
271 using blink::WebTouchEvent
;
273 using blink::WebURLError
;
274 using blink::WebURLRequest
;
275 using blink::WebURLResponse
;
276 using blink::WebUserGestureIndicator
;
277 using blink::WebVector
;
278 using blink::WebView
;
279 using blink::WebWidget
;
280 using blink::WebWindowFeatures
;
281 using blink::WebNetworkStateNotifier
;
282 using blink::WebRuntimeFeatures
;
284 using base::TimeDelta
;
286 #if defined(OS_ANDROID)
287 using blink::WebContentDetectionResult
;
288 using blink::WebFloatPoint
;
289 using blink::WebFloatRect
;
290 using blink::WebHitTestResult
;
295 //-----------------------------------------------------------------------------
297 typedef std::map
<blink::WebView
*, RenderViewImpl
*> ViewMap
;
298 static base::LazyInstance
<ViewMap
> g_view_map
= LAZY_INSTANCE_INITIALIZER
;
299 typedef std::map
<int32
, RenderViewImpl
*> RoutingIDViewMap
;
300 static base::LazyInstance
<RoutingIDViewMap
> g_routing_id_view_map
=
301 LAZY_INSTANCE_INITIALIZER
;
303 // Time, in seconds, we delay before sending content state changes (such as form
304 // state and scroll position) to the browser. We delay sending changes to avoid
305 // spamming the browser.
306 // To avoid having tab/session restore require sending a message to get the
307 // current content state during tab closing we use a shorter timeout for the
308 // foreground renderer. This means there is a small window of time from which
309 // content state is modified and not sent to session restore, but this is
310 // better than having to wake up all renderers during shutdown.
311 const int kDelaySecondsForContentStateSyncHidden
= 5;
312 const int kDelaySecondsForContentStateSync
= 1;
314 #if defined(OS_ANDROID)
315 // Delay between tapping in content and launching the associated android intent.
316 // Used to allow users see what has been recognized as content.
317 const size_t kContentIntentDelayMilliseconds
= 700;
320 static RenderViewImpl
* (*g_create_render_view_impl
)(
321 CompositorDependencies
* compositor_deps
,
322 const ViewMsg_New_Params
&) = nullptr;
325 Referrer
RenderViewImpl::GetReferrerFromRequest(
327 const WebURLRequest
& request
) {
328 return Referrer(GURL(request
.httpHeaderField(WebString::fromUTF8("Referer"))),
329 request
.referrerPolicy());
333 WindowOpenDisposition
RenderViewImpl::NavigationPolicyToDisposition(
334 WebNavigationPolicy policy
) {
336 case blink::WebNavigationPolicyIgnore
:
337 return IGNORE_ACTION
;
338 case blink::WebNavigationPolicyDownload
:
340 case blink::WebNavigationPolicyCurrentTab
:
342 case blink::WebNavigationPolicyNewBackgroundTab
:
343 return NEW_BACKGROUND_TAB
;
344 case blink::WebNavigationPolicyNewForegroundTab
:
345 return NEW_FOREGROUND_TAB
;
346 case blink::WebNavigationPolicyNewWindow
:
348 case blink::WebNavigationPolicyNewPopup
:
351 NOTREACHED() << "Unexpected WebNavigationPolicy";
352 return IGNORE_ACTION
;
356 // Returns true if the device scale is high enough that losing subpixel
357 // antialiasing won't have a noticeable effect on text quality.
358 static bool DeviceScaleEnsuresTextQuality(float device_scale_factor
) {
359 #if defined(OS_ANDROID)
360 // On Android, we never have subpixel antialiasing.
363 return device_scale_factor
> 1.5f
;
368 static bool PreferCompositingToLCDText(CompositorDependencies
* compositor_deps
,
369 float device_scale_factor
) {
370 const base::CommandLine
& command_line
=
371 *base::CommandLine::ForCurrentProcess();
372 if (command_line
.HasSwitch(switches::kDisablePreferCompositingToLCDText
))
374 if (command_line
.HasSwitch(switches::kEnablePreferCompositingToLCDText
))
376 if (!compositor_deps
->IsLcdTextEnabled())
378 return DeviceScaleEnsuresTextQuality(device_scale_factor
);
381 static FaviconURL::IconType
ToFaviconType(blink::WebIconURL::Type type
) {
383 case blink::WebIconURL::TypeFavicon
:
384 return FaviconURL::FAVICON
;
385 case blink::WebIconURL::TypeTouch
:
386 return FaviconURL::TOUCH_ICON
;
387 case blink::WebIconURL::TypeTouchPrecomposed
:
388 return FaviconURL::TOUCH_PRECOMPOSED_ICON
;
389 case blink::WebIconURL::TypeInvalid
:
390 return FaviconURL::INVALID_ICON
;
392 return FaviconURL::INVALID_ICON
;
395 static void ConvertToFaviconSizes(
396 const blink::WebVector
<blink::WebSize
>& web_sizes
,
397 std::vector
<gfx::Size
>* sizes
) {
398 DCHECK(sizes
->empty());
399 sizes
->reserve(web_sizes
.size());
400 for (size_t i
= 0; i
< web_sizes
.size(); ++i
)
401 sizes
->push_back(gfx::Size(web_sizes
[i
]));
404 ///////////////////////////////////////////////////////////////////////////////
406 struct RenderViewImpl::PendingFileChooser
{
407 PendingFileChooser(const FileChooserParams
& p
, WebFileChooserCompletion
* c
)
411 FileChooserParams params
;
412 WebFileChooserCompletion
* completion
; // MAY BE NULL to skip callback.
417 class WebWidgetLockTarget
: public MouseLockDispatcher::LockTarget
{
419 explicit WebWidgetLockTarget(blink::WebWidget
* webwidget
)
420 : webwidget_(webwidget
) {}
422 void OnLockMouseACK(bool succeeded
) override
{
424 webwidget_
->didAcquirePointerLock();
426 webwidget_
->didNotAcquirePointerLock();
429 void OnMouseLockLost() override
{ webwidget_
->didLosePointerLock(); }
431 bool HandleMouseLockedInputEvent(const blink::WebMouseEvent
& event
) override
{
432 // The WebWidget handles mouse lock in WebKit's handleInputEvent().
437 blink::WebWidget
* webwidget_
;
440 WebDragData
DropDataToWebDragData(const DropData
& drop_data
) {
441 std::vector
<WebDragData::Item
> item_list
;
443 // These fields are currently unused when dragging into WebKit.
444 DCHECK(drop_data
.download_metadata
.empty());
445 DCHECK(drop_data
.file_contents
.empty());
446 DCHECK(drop_data
.file_description_filename
.empty());
448 if (!drop_data
.text
.is_null()) {
449 WebDragData::Item item
;
450 item
.storageType
= WebDragData::Item::StorageTypeString
;
451 item
.stringType
= WebString::fromUTF8(ui::Clipboard::kMimeTypeText
);
452 item
.stringData
= drop_data
.text
.string();
453 item_list
.push_back(item
);
456 // TODO(dcheng): Do we need to distinguish between null and empty URLs? Is it
457 // meaningful to write an empty URL to the clipboard?
458 if (!drop_data
.url
.is_empty()) {
459 WebDragData::Item item
;
460 item
.storageType
= WebDragData::Item::StorageTypeString
;
461 item
.stringType
= WebString::fromUTF8(ui::Clipboard::kMimeTypeURIList
);
462 item
.stringData
= WebString::fromUTF8(drop_data
.url
.spec());
463 item
.title
= drop_data
.url_title
;
464 item_list
.push_back(item
);
467 if (!drop_data
.html
.is_null()) {
468 WebDragData::Item item
;
469 item
.storageType
= WebDragData::Item::StorageTypeString
;
470 item
.stringType
= WebString::fromUTF8(ui::Clipboard::kMimeTypeHTML
);
471 item
.stringData
= drop_data
.html
.string();
472 item
.baseURL
= drop_data
.html_base_url
;
473 item_list
.push_back(item
);
476 for (std::vector
<ui::FileInfo
>::const_iterator it
=
477 drop_data
.filenames
.begin();
478 it
!= drop_data
.filenames
.end();
480 WebDragData::Item item
;
481 item
.storageType
= WebDragData::Item::StorageTypeFilename
;
482 item
.filenameData
= it
->path
.AsUTF16Unsafe();
483 item
.displayNameData
= it
->display_name
.AsUTF16Unsafe();
484 item_list
.push_back(item
);
487 for (std::vector
<DropData::FileSystemFileInfo
>::const_iterator it
=
488 drop_data
.file_system_files
.begin();
489 it
!= drop_data
.file_system_files
.end();
491 WebDragData::Item item
;
492 item
.storageType
= WebDragData::Item::StorageTypeFileSystemFile
;
493 item
.fileSystemURL
= it
->url
;
494 item
.fileSystemFileSize
= it
->size
;
495 item_list
.push_back(item
);
498 for (std::map
<base::string16
, base::string16
>::const_iterator it
=
499 drop_data
.custom_data
.begin();
500 it
!= drop_data
.custom_data
.end();
502 WebDragData::Item item
;
503 item
.storageType
= WebDragData::Item::StorageTypeString
;
504 item
.stringType
= it
->first
;
505 item
.stringData
= it
->second
;
506 item_list
.push_back(item
);
511 result
.setItems(item_list
);
512 result
.setFilesystemId(drop_data
.filesystem_id
);
516 typedef void (*SetFontFamilyWrapper
)(blink::WebSettings
*,
517 const base::string16
&,
520 void SetStandardFontFamilyWrapper(WebSettings
* settings
,
521 const base::string16
& font
,
522 UScriptCode script
) {
523 settings
->setStandardFontFamily(font
, script
);
526 void SetFixedFontFamilyWrapper(WebSettings
* settings
,
527 const base::string16
& font
,
528 UScriptCode script
) {
529 settings
->setFixedFontFamily(font
, script
);
532 void SetSerifFontFamilyWrapper(WebSettings
* settings
,
533 const base::string16
& font
,
534 UScriptCode script
) {
535 settings
->setSerifFontFamily(font
, script
);
538 void SetSansSerifFontFamilyWrapper(WebSettings
* settings
,
539 const base::string16
& font
,
540 UScriptCode script
) {
541 settings
->setSansSerifFontFamily(font
, script
);
544 void SetCursiveFontFamilyWrapper(WebSettings
* settings
,
545 const base::string16
& font
,
546 UScriptCode script
) {
547 settings
->setCursiveFontFamily(font
, script
);
550 void SetFantasyFontFamilyWrapper(WebSettings
* settings
,
551 const base::string16
& font
,
552 UScriptCode script
) {
553 settings
->setFantasyFontFamily(font
, script
);
556 void SetPictographFontFamilyWrapper(WebSettings
* settings
,
557 const base::string16
& font
,
558 UScriptCode script
) {
559 settings
->setPictographFontFamily(font
, script
);
562 // If |scriptCode| is a member of a family of "similar" script codes, returns
563 // the script code in that family that is used by WebKit for font selection
564 // purposes. For example, USCRIPT_KATAKANA_OR_HIRAGANA and USCRIPT_JAPANESE are
565 // considered equivalent for the purposes of font selection. WebKit uses the
566 // script code USCRIPT_KATAKANA_OR_HIRAGANA. So, if |scriptCode| is
567 // USCRIPT_JAPANESE, the function returns USCRIPT_KATAKANA_OR_HIRAGANA. WebKit
568 // uses different scripts than the ones in Chrome pref names because the version
569 // of ICU included on certain ports does not have some of the newer scripts. If
570 // |scriptCode| is not a member of such a family, returns |scriptCode|.
571 UScriptCode
GetScriptForWebSettings(UScriptCode scriptCode
) {
572 switch (scriptCode
) {
573 case USCRIPT_HIRAGANA
:
574 case USCRIPT_KATAKANA
:
575 case USCRIPT_JAPANESE
:
576 return USCRIPT_KATAKANA_OR_HIRAGANA
;
578 return USCRIPT_HANGUL
;
584 void ApplyFontsFromMap(const ScriptFontFamilyMap
& map
,
585 SetFontFamilyWrapper setter
,
586 WebSettings
* settings
) {
587 for (ScriptFontFamilyMap::const_iterator it
= map
.begin(); it
!= map
.end();
589 int32 script
= u_getPropertyValueEnum(UCHAR_SCRIPT
, (it
->first
).c_str());
590 if (script
>= 0 && script
< USCRIPT_CODE_LIMIT
) {
591 UScriptCode code
= static_cast<UScriptCode
>(script
);
592 (*setter
)(settings
, it
->second
, GetScriptForWebSettings(code
));
597 void ApplyBlinkSettings(const base::CommandLine
& command_line
,
598 WebSettings
* settings
) {
599 if (!command_line
.HasSwitch(switches::kBlinkSettings
))
602 std::vector
<std::string
> blink_settings
;
604 command_line
.GetSwitchValueASCII(switches::kBlinkSettings
), ',',
606 for (const std::string
& setting
: blink_settings
) {
607 size_t pos
= setting
.find('=');
608 settings
->setFromStrings(
609 blink::WebString::fromLatin1(setting
.substr(0, pos
)),
610 blink::WebString::fromLatin1(
611 pos
== std::string::npos
? "" : setting
.substr(pos
+ 1)));
615 // Looks up and returns the WebFrame corresponding to a given opener frame
616 // routing ID. Also stores the opener's RenderView routing ID into
617 // |opener_view_routing_id|.
618 WebFrame
* ResolveOpener(int opener_frame_routing_id
,
619 int* opener_view_routing_id
) {
620 *opener_view_routing_id
= MSG_ROUTING_NONE
;
621 if (opener_frame_routing_id
== MSG_ROUTING_NONE
)
624 // Opener routing ID could refer to either a RenderFrameProxy or a
625 // RenderFrame, so need to check both.
626 RenderFrameProxy
* opener_proxy
=
627 RenderFrameProxy::FromRoutingID(opener_frame_routing_id
);
629 *opener_view_routing_id
= opener_proxy
->render_view()->GetRoutingID();
631 // TODO(nasko,alexmos): This check won't be needed once swapped-out:// is
633 if (opener_proxy
->IsMainFrameDetachedFromTree()) {
634 DCHECK(!RenderFrameProxy::IsSwappedOutStateForbidden());
635 return opener_proxy
->render_view()->webview()->mainFrame();
637 return opener_proxy
->web_frame();
641 RenderFrameImpl
* opener_frame
=
642 RenderFrameImpl::FromRoutingID(opener_frame_routing_id
);
644 *opener_view_routing_id
= opener_frame
->render_view()->GetRoutingID();
645 return opener_frame
->GetWebFrame();
653 RenderViewImpl::RenderViewImpl(CompositorDependencies
* compositor_deps
,
654 const ViewMsg_New_Params
& params
)
655 : RenderWidget(compositor_deps
,
656 blink::WebPopupTypeNone
,
657 params
.initial_size
.screen_info
,
660 params
.never_visible
),
661 webkit_preferences_(params
.web_preferences
),
662 send_content_state_immediately_(false),
663 enabled_bindings_(0),
664 send_preferred_size_changes_(false),
665 navigation_gesture_(NavigationGestureUnknown
),
666 opened_by_user_gesture_(true),
667 opener_suppressed_(false),
668 suppress_dialogs_until_swap_out_(false),
670 next_page_id_(params
.next_page_id
),
671 history_list_offset_(-1),
672 history_list_length_(0),
673 frames_in_progress_(0),
674 target_url_status_(TARGET_NONE
),
675 uses_temporary_zoom_level_(false),
676 #if defined(OS_ANDROID)
677 top_controls_constraints_(TOP_CONTROLS_STATE_BOTH
),
679 has_scrolled_focused_editable_node_into_rect_(false),
680 main_render_frame_(nullptr),
681 speech_recognition_dispatcher_(NULL
),
682 mouse_lock_dispatcher_(NULL
),
683 #if defined(OS_ANDROID)
684 expected_content_intent_id_(0),
687 focused_plugin_id_(-1),
689 #if defined(ENABLE_PLUGINS)
690 plugin_find_handler_(NULL
),
691 focused_pepper_plugin_(NULL
),
692 pepper_last_mouse_event_target_(NULL
),
694 enumeration_completion_id_(0),
695 session_storage_namespace_id_(params
.session_storage_namespace_id
),
696 page_scale_factor_is_one_(true) {
699 void RenderViewImpl::Initialize(const ViewMsg_New_Params
& params
,
700 bool was_created_by_renderer
) {
701 routing_id_
= params
.view_id
;
702 surface_id_
= params
.surface_id
;
704 int opener_view_routing_id
;
705 WebFrame
* opener_frame
=
706 ResolveOpener(params
.opener_frame_route_id
, &opener_view_routing_id
);
707 if (opener_view_routing_id
!= MSG_ROUTING_NONE
&& was_created_by_renderer
)
708 opener_id_
= opener_view_routing_id
;
710 display_mode_
= params
.initial_size
.display_mode
;
712 // Ensure we start with a valid next_page_id_ from the browser.
713 DCHECK_GE(next_page_id_
, 0);
715 if (params
.main_frame_routing_id
!= MSG_ROUTING_NONE
) {
716 main_render_frame_
= RenderFrameImpl::Create(
717 this, params
.main_frame_routing_id
);
718 // The main frame WebLocalFrame object is closed by
719 // RenderFrameImpl::frameDetached().
720 WebLocalFrame
* web_frame
= WebLocalFrame::create(
721 blink::WebTreeScopeType::Document
, main_render_frame_
);
722 main_render_frame_
->SetWebFrame(web_frame
);
725 webwidget_
= WebView::create(this);
726 webwidget_mouse_lock_target_
.reset(new WebWidgetLockTarget(webwidget_
));
728 g_view_map
.Get().insert(std::make_pair(webview(), this));
729 g_routing_id_view_map
.Get().insert(std::make_pair(routing_id_
, this));
731 const base::CommandLine
& command_line
=
732 *base::CommandLine::ForCurrentProcess();
734 if (command_line
.HasSwitch(switches::kStatsCollectionController
))
735 stats_collection_observer_
.reset(new StatsCollectionObserver(this));
737 RenderFrameProxy
* proxy
= NULL
;
738 if (params
.proxy_routing_id
!= MSG_ROUTING_NONE
) {
739 CHECK(params
.swapped_out
);
740 if (main_render_frame_
) {
741 proxy
= RenderFrameProxy::CreateProxyToReplaceFrame(
742 main_render_frame_
, params
.proxy_routing_id
,
743 blink::WebTreeScopeType::Document
);
744 main_render_frame_
->set_render_frame_proxy(proxy
);
746 proxy
= RenderFrameProxy::CreateFrameProxy(
747 params
.proxy_routing_id
,
750 params
.replicated_frame_state
);
754 // When not using swapped out state, just use the WebRemoteFrame as the main
756 if (proxy
&& RenderFrameProxy::IsSwappedOutStateForbidden()) {
757 webview()->setMainFrame(proxy
->web_frame());
758 // Initialize the WebRemoteFrame with information replicated from the
760 proxy
->SetReplicatedState(params
.replicated_frame_state
);
762 webview()->setMainFrame(main_render_frame_
->GetWebFrame());
764 if (main_render_frame_
)
765 main_render_frame_
->Initialize();
767 #if defined(OS_ANDROID)
768 content_detectors_
.push_back(linked_ptr
<ContentDetector
>(
769 new AddressDetector()));
770 const std::string
& contry_iso
=
771 params
.renderer_preferences
.network_contry_iso
;
772 if (!contry_iso
.empty()) {
773 content_detectors_
.push_back(linked_ptr
<ContentDetector
>(
774 new PhoneNumberDetector(contry_iso
)));
776 content_detectors_
.push_back(linked_ptr
<ContentDetector
>(
777 new EmailDetector()));
780 RenderThread::Get()->AddRoute(routing_id_
, this);
781 // Take a reference on behalf of the RenderThread. This will be balanced
782 // when we receive ViewMsg_Close in the RenderWidget (which RenderView
785 if (RenderThreadImpl::current()) {
786 RenderThreadImpl::current()->WidgetCreated();
788 RenderThreadImpl::current()->WidgetHidden();
791 // If this is a popup, we must wait for the CreatingNew_ACK message before
792 // completing initialization. Otherwise, we can finish it now.
793 if (opener_id_
== MSG_ROUTING_NONE
) {
798 webview()->setDeviceScaleFactor(device_scale_factor_
);
799 webview()->setDisplayMode(display_mode_
);
800 webview()->settings()->setPreferCompositingToLCDTextEnabled(
801 PreferCompositingToLCDText(compositor_deps_
, device_scale_factor_
));
802 webview()->settings()->setThreadedScrollingEnabled(
803 !command_line
.HasSwitch(switches::kDisableThreadedScrolling
));
804 webview()->settings()->setRootLayerScrolls(
805 command_line
.HasSwitch(switches::kRootLayerScrolls
));
807 ApplyWebPreferencesInternal(webkit_preferences_
, webview(), compositor_deps_
);
809 if (switches::IsTouchDragDropEnabled())
810 webview()->settings()->setTouchDragDropEnabled(true);
812 if (switches::IsTouchEditingEnabled())
813 webview()->settings()->setTouchEditingEnabled(true);
815 WebSettings::SelectionStrategyType selection_strategy
=
816 WebSettings::SelectionStrategyType::Character
;
817 const std::string selection_strategy_str
=
818 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
819 switches::kTouchTextSelectionStrategy
);
820 if (selection_strategy_str
== "direction")
821 selection_strategy
= WebSettings::SelectionStrategyType::Direction
;
822 webview()->settings()->setSelectionStrategy(selection_strategy
);
824 // Set the main frame's name. Only needs to be done for WebLocalFrames,
825 // since the remote case was handled as part of SetReplicatedState on the
827 if (!params
.replicated_frame_state
.name
.empty() &&
828 webview()->mainFrame()->isWebLocalFrame()) {
829 webview()->mainFrame()->setName(
830 blink::WebString::fromUTF8(params
.replicated_frame_state
.name
));
833 // TODO(davidben): Move this state from Blink into content.
834 if (params
.window_was_created_with_opener
)
835 webview()->setOpenedByDOM();
837 OnSetRendererPrefs(params
.renderer_preferences
);
839 ApplyBlinkSettings(command_line
, webview()->settings());
841 if (!params
.enable_auto_resize
) {
842 OnResize(params
.initial_size
);
844 OnEnableAutoResize(params
.min_size
, params
.max_size
);
847 new MHTMLGenerator(this);
848 #if defined(OS_MACOSX)
849 new TextInputClientObserver(this);
850 #endif // defined(OS_MACOSX)
852 // The next group of objects all implement RenderViewObserver, so are deleted
853 // along with the RenderView automatically.
854 mouse_lock_dispatcher_
= new RenderViewMouseLockDispatcher(this);
856 history_controller_
.reset(new HistoryController(this));
858 new IdleUserDetector(this);
860 if (command_line
.HasSwitch(switches::kDomAutomationController
))
861 enabled_bindings_
|= BINDINGS_POLICY_DOM_AUTOMATION
;
862 if (command_line
.HasSwitch(switches::kStatsCollectionController
))
863 enabled_bindings_
|= BINDINGS_POLICY_STATS_COLLECTION
;
865 GetContentClient()->renderer()->RenderViewCreated(this);
867 // If we have an opener_frame but we weren't created by a renderer, then it's
868 // the browser asking us to set our opener to another frame.
869 if (opener_frame
&& !was_created_by_renderer
)
870 webview()->mainFrame()->setOpener(opener_frame
);
872 // If we are initially swapped out, navigate to kSwappedOutURL.
873 // This ensures we are in a unique origin that others cannot script.
874 if (is_swapped_out_
&& webview()->mainFrame()->isWebLocalFrame())
875 main_render_frame_
->NavigateToSwappedOutURL();
878 RenderViewImpl::~RenderViewImpl() {
879 for (BitmapMap::iterator it
= disambiguation_bitmaps_
.begin();
880 it
!= disambiguation_bitmaps_
.end();
884 // If file chooser is still waiting for answer, dispatch empty answer.
885 while (!file_chooser_completions_
.empty()) {
886 if (file_chooser_completions_
.front()->completion
) {
887 file_chooser_completions_
.front()->completion
->didChooseFile(
888 WebVector
<WebString
>());
890 file_chooser_completions_
.pop_front();
893 #if defined(OS_ANDROID)
894 // The date/time picker client is both a scoped_ptr member of this class and
895 // a RenderViewObserver. Reset it to prevent double deletion.
896 date_time_picker_client_
.reset();
900 // Make sure we are no longer referenced by the ViewMap or RoutingIDViewMap.
901 ViewMap
* views
= g_view_map
.Pointer();
902 for (ViewMap::iterator it
= views
->begin(); it
!= views
->end(); ++it
)
903 DCHECK_NE(this, it
->second
) << "Failed to call Close?";
904 RoutingIDViewMap
* routing_id_views
= g_routing_id_view_map
.Pointer();
905 for (RoutingIDViewMap::iterator it
= routing_id_views
->begin();
906 it
!= routing_id_views
->end(); ++it
)
907 DCHECK_NE(this, it
->second
) << "Failed to call Close?";
910 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, RenderViewGone());
911 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, OnDestruct());
915 RenderViewImpl
* RenderViewImpl::FromWebView(WebView
* webview
) {
916 ViewMap
* views
= g_view_map
.Pointer();
917 ViewMap::iterator it
= views
->find(webview
);
918 return it
== views
->end() ? NULL
: it
->second
;
922 RenderView
* RenderView::FromWebView(blink::WebView
* webview
) {
923 return RenderViewImpl::FromWebView(webview
);
927 RenderViewImpl
* RenderViewImpl::FromRoutingID(int32 routing_id
) {
928 RoutingIDViewMap
* views
= g_routing_id_view_map
.Pointer();
929 RoutingIDViewMap::iterator it
= views
->find(routing_id
);
930 return it
== views
->end() ? NULL
: it
->second
;
934 RenderView
* RenderView::FromRoutingID(int routing_id
) {
935 return RenderViewImpl::FromRoutingID(routing_id
);
939 size_t RenderView::GetRenderViewCount() {
940 return g_view_map
.Get().size();
944 void RenderView::ForEach(RenderViewVisitor
* visitor
) {
945 ViewMap
* views
= g_view_map
.Pointer();
946 for (ViewMap::iterator it
= views
->begin(); it
!= views
->end(); ++it
) {
947 if (!visitor
->Visit(it
->second
))
953 void RenderView::ApplyWebPreferences(const WebPreferences
& prefs
,
955 WebSettings
* settings
= web_view
->settings();
956 ApplyFontsFromMap(prefs
.standard_font_family_map
,
957 SetStandardFontFamilyWrapper
, settings
);
958 ApplyFontsFromMap(prefs
.fixed_font_family_map
,
959 SetFixedFontFamilyWrapper
, settings
);
960 ApplyFontsFromMap(prefs
.serif_font_family_map
,
961 SetSerifFontFamilyWrapper
, settings
);
962 ApplyFontsFromMap(prefs
.sans_serif_font_family_map
,
963 SetSansSerifFontFamilyWrapper
, settings
);
964 ApplyFontsFromMap(prefs
.cursive_font_family_map
,
965 SetCursiveFontFamilyWrapper
, settings
);
966 ApplyFontsFromMap(prefs
.fantasy_font_family_map
,
967 SetFantasyFontFamilyWrapper
, settings
);
968 ApplyFontsFromMap(prefs
.pictograph_font_family_map
,
969 SetPictographFontFamilyWrapper
, settings
);
970 settings
->setDefaultFontSize(prefs
.default_font_size
);
971 settings
->setDefaultFixedFontSize(prefs
.default_fixed_font_size
);
972 settings
->setMinimumFontSize(prefs
.minimum_font_size
);
973 settings
->setMinimumLogicalFontSize(prefs
.minimum_logical_font_size
);
974 settings
->setDefaultTextEncodingName(
975 base::ASCIIToUTF16(prefs
.default_encoding
));
976 settings
->setJavaScriptEnabled(prefs
.javascript_enabled
);
977 settings
->setWebSecurityEnabled(prefs
.web_security_enabled
);
978 settings
->setJavaScriptCanOpenWindowsAutomatically(
979 prefs
.javascript_can_open_windows_automatically
);
980 settings
->setLoadsImagesAutomatically(prefs
.loads_images_automatically
);
981 settings
->setImagesEnabled(prefs
.images_enabled
);
982 settings
->setPluginsEnabled(prefs
.plugins_enabled
);
983 settings
->setDOMPasteAllowed(prefs
.dom_paste_enabled
);
984 settings
->setUsesEncodingDetector(prefs
.uses_universal_detector
);
985 settings
->setTextAreasAreResizable(prefs
.text_areas_are_resizable
);
986 settings
->setAllowScriptsToCloseWindows(prefs
.allow_scripts_to_close_windows
);
987 settings
->setDownloadableBinaryFontsEnabled(prefs
.remote_fonts_enabled
);
988 settings
->setJavaScriptCanAccessClipboard(
989 prefs
.javascript_can_access_clipboard
);
990 WebRuntimeFeatures::enableXSLT(prefs
.xslt_enabled
);
991 WebRuntimeFeatures::enableSlimmingPaint(prefs
.slimming_paint_enabled
);
992 settings
->setXSSAuditorEnabled(prefs
.xss_auditor_enabled
);
993 settings
->setDNSPrefetchingEnabled(prefs
.dns_prefetching_enabled
);
994 settings
->setLocalStorageEnabled(prefs
.local_storage_enabled
);
995 settings
->setSyncXHRInDocumentsEnabled(prefs
.sync_xhr_in_documents_enabled
);
996 WebRuntimeFeatures::enableDatabase(prefs
.databases_enabled
);
997 settings
->setOfflineWebApplicationCacheEnabled(
998 prefs
.application_cache_enabled
);
999 settings
->setCaretBrowsingEnabled(prefs
.caret_browsing_enabled
);
1000 settings
->setHyperlinkAuditingEnabled(prefs
.hyperlink_auditing_enabled
);
1001 settings
->setCookieEnabled(prefs
.cookie_enabled
);
1002 settings
->setNavigateOnDragDrop(prefs
.navigate_on_drag_drop
);
1004 settings
->setJavaEnabled(prefs
.java_enabled
);
1006 // By default, allow_universal_access_from_file_urls is set to false and thus
1007 // we mitigate attacks from local HTML files by not granting file:// URLs
1008 // universal access. Only test shell will enable this.
1009 settings
->setAllowUniversalAccessFromFileURLs(
1010 prefs
.allow_universal_access_from_file_urls
);
1011 settings
->setAllowFileAccessFromFileURLs(
1012 prefs
.allow_file_access_from_file_urls
);
1014 // Enable the web audio API if requested on the command line.
1015 settings
->setWebAudioEnabled(prefs
.webaudio_enabled
);
1017 // Enable experimental WebGL support if requested on command line
1018 // and support is compiled in.
1019 settings
->setExperimentalWebGLEnabled(prefs
.experimental_webgl_enabled
);
1021 // Disable GL multisampling if requested on command line.
1022 settings
->setOpenGLMultisamplingEnabled(prefs
.gl_multisampling_enabled
);
1024 // Enable WebGL errors to the JS console if requested.
1025 settings
->setWebGLErrorsToConsoleEnabled(
1026 prefs
.webgl_errors_to_console_enabled
);
1028 // Uses the mock theme engine for scrollbars.
1029 settings
->setMockScrollbarsEnabled(prefs
.mock_scrollbars_enabled
);
1031 // Enable gpu-accelerated 2d canvas if requested on the command line.
1032 settings
->setAccelerated2dCanvasEnabled(prefs
.accelerated_2d_canvas_enabled
);
1034 settings
->setMinimumAccelerated2dCanvasSize(
1035 prefs
.minimum_accelerated_2d_canvas_size
);
1037 // Disable antialiasing for 2d canvas if requested on the command line.
1038 settings
->setAntialiased2dCanvasEnabled(
1039 !prefs
.antialiased_2d_canvas_disabled
);
1041 // Enabled antialiasing of clips for 2d canvas if requested on the command
1043 settings
->setAntialiasedClips2dCanvasEnabled(
1044 prefs
.antialiased_clips_2d_canvas_enabled
);
1046 // Set MSAA sample count for 2d canvas if requested on the command line (or
1047 // default value if not).
1048 settings
->setAccelerated2dCanvasMSAASampleCount(
1049 prefs
.accelerated_2d_canvas_msaa_sample_count
);
1051 WebRuntimeFeatures::enableTextBlobs(prefs
.text_blobs_enabled
);
1053 settings
->setAsynchronousSpellCheckingEnabled(
1054 prefs
.asynchronous_spell_checking_enabled
);
1055 settings
->setUnifiedTextCheckerEnabled(prefs
.unified_textchecker_enabled
);
1057 // Tabs to link is not part of the settings. WebCore calls
1058 // ChromeClient::tabsToLinks which is part of the glue code.
1059 web_view
->setTabsToLinks(prefs
.tabs_to_links
);
1061 settings
->setAllowDisplayOfInsecureContent(
1062 prefs
.allow_displaying_insecure_content
);
1063 settings
->setAllowRunningOfInsecureContent(
1064 prefs
.allow_running_insecure_content
);
1065 settings
->setDisableReadingFromCanvas(prefs
.disable_reading_from_canvas
);
1066 settings
->setStrictMixedContentChecking(prefs
.strict_mixed_content_checking
);
1067 settings
->setStrictPowerfulFeatureRestrictions(
1068 prefs
.strict_powerful_feature_restrictions
);
1069 settings
->setPasswordEchoEnabled(prefs
.password_echo_enabled
);
1070 settings
->setShouldPrintBackgrounds(prefs
.should_print_backgrounds
);
1071 settings
->setShouldClearDocumentBackground(
1072 prefs
.should_clear_document_background
);
1073 settings
->setEnableScrollAnimator(prefs
.enable_scroll_animator
);
1075 WebRuntimeFeatures::enableTouch(prefs
.touch_enabled
);
1076 settings
->setMaxTouchPoints(prefs
.pointer_events_max_touch_points
);
1077 settings
->setAvailablePointerTypes(prefs
.available_pointer_types
);
1078 settings
->setPrimaryPointerType(
1079 static_cast<WebSettings::PointerType
>(prefs
.primary_pointer_type
));
1080 settings
->setAvailableHoverTypes(prefs
.available_hover_types
);
1081 settings
->setPrimaryHoverType(
1082 static_cast<WebSettings::HoverType
>(prefs
.primary_hover_type
));
1083 settings
->setDeviceSupportsTouch(prefs
.device_supports_touch
);
1084 settings
->setDeviceSupportsMouse(prefs
.device_supports_mouse
);
1085 settings
->setEnableTouchAdjustment(prefs
.touch_adjustment_enabled
);
1086 settings
->setMultiTargetTapNotificationEnabled(
1087 switches::IsLinkDisambiguationPopupEnabled());
1089 WebRuntimeFeatures::enableImageColorProfiles(
1090 prefs
.image_color_profiles_enabled
);
1091 settings
->setShouldRespectImageOrientation(
1092 prefs
.should_respect_image_orientation
);
1094 settings
->setUnsafePluginPastingEnabled(false);
1095 settings
->setEditingBehavior(
1096 static_cast<WebSettings::EditingBehavior
>(prefs
.editing_behavior
));
1098 settings
->setSupportsMultipleWindows(prefs
.supports_multiple_windows
);
1100 settings
->setViewportEnabled(prefs
.viewport_enabled
);
1101 settings
->setLoadWithOverviewMode(prefs
.initialize_at_minimum_page_scale
);
1102 settings
->setViewportMetaEnabled(prefs
.viewport_meta_enabled
);
1103 settings
->setMainFrameResizesAreOrientationChanges(
1104 prefs
.main_frame_resizes_are_orientation_changes
);
1106 settings
->setSmartInsertDeleteEnabled(prefs
.smart_insert_delete_enabled
);
1108 settings
->setSpatialNavigationEnabled(prefs
.spatial_navigation_enabled
);
1110 settings
->setSelectionIncludesAltImageText(true);
1112 settings
->setV8CacheOptions(
1113 static_cast<WebSettings::V8CacheOptions
>(prefs
.v8_cache_options
));
1115 settings
->setImageAnimationPolicy(
1116 static_cast<WebSettings::ImageAnimationPolicy
>(prefs
.animation_policy
));
1118 // Needs to happen before setIgnoreVIewportTagScaleLimits below.
1119 web_view
->setDefaultPageScaleLimits(
1120 prefs
.default_minimum_page_scale_factor
,
1121 prefs
.default_maximum_page_scale_factor
);
1123 #if defined(OS_ANDROID)
1124 settings
->setAllowCustomScrollbarInMainFrame(false);
1125 settings
->setTextAutosizingEnabled(prefs
.text_autosizing_enabled
);
1126 settings
->setAccessibilityFontScaleFactor(prefs
.font_scale_factor
);
1127 settings
->setDeviceScaleAdjustment(prefs
.device_scale_adjustment
);
1128 settings
->setFullscreenSupported(prefs
.fullscreen_supported
);
1129 web_view
->setIgnoreViewportTagScaleLimits(prefs
.force_enable_zoom
);
1130 settings
->setAutoZoomFocusedNodeToLegibleScale(true);
1131 settings
->setDoubleTapToZoomEnabled(prefs
.double_tap_to_zoom_enabled
);
1132 settings
->setMediaControlsOverlayPlayButtonEnabled(true);
1133 settings
->setMediaPlaybackRequiresUserGesture(
1134 prefs
.user_gesture_required_for_media_playback
);
1135 settings
->setDefaultVideoPosterURL(
1136 base::ASCIIToUTF16(prefs
.default_video_poster_url
.spec()));
1137 settings
->setSupportDeprecatedTargetDensityDPI(
1138 prefs
.support_deprecated_target_density_dpi
);
1139 settings
->setUseLegacyBackgroundSizeShorthandBehavior(
1140 prefs
.use_legacy_background_size_shorthand_behavior
);
1141 settings
->setWideViewportQuirkEnabled(prefs
.wide_viewport_quirk
);
1142 settings
->setUseWideViewport(prefs
.use_wide_viewport
);
1143 settings
->setForceZeroLayoutHeight(prefs
.force_zero_layout_height
);
1144 settings
->setViewportMetaLayoutSizeQuirk(
1145 prefs
.viewport_meta_layout_size_quirk
);
1146 settings
->setViewportMetaMergeContentQuirk(
1147 prefs
.viewport_meta_merge_content_quirk
);
1148 settings
->setViewportMetaNonUserScalableQuirk(
1149 prefs
.viewport_meta_non_user_scalable_quirk
);
1150 settings
->setViewportMetaZeroValuesQuirk(
1151 prefs
.viewport_meta_zero_values_quirk
);
1152 settings
->setClobberUserAgentInitialScaleQuirk(
1153 prefs
.clobber_user_agent_initial_scale_quirk
);
1154 settings
->setIgnoreMainFrameOverflowHiddenQuirk(
1155 prefs
.ignore_main_frame_overflow_hidden_quirk
);
1156 settings
->setReportScreenSizeInPhysicalPixelsQuirk(
1157 prefs
.report_screen_size_in_physical_pixels_quirk
);
1159 bool record_full_layer
=
1160 RenderViewImpl::FromWebView(web_view
)
1161 ? RenderViewImpl::FromWebView(web_view
)->DoesRecordFullLayer()
1163 settings
->setMainFrameClipsContent(!record_full_layer
);
1165 settings
->setShrinksViewportContentToFit(true);
1166 settings
->setUseMobileViewportStyle(true);
1169 WebNetworkStateNotifier::setOnLine(prefs
.is_online
);
1170 WebNetworkStateNotifier::setWebConnectionType(
1171 NetConnectionTypeToWebConnectionType(prefs
.connection_type
));
1173 settings
->setPinchOverlayScrollbarThickness(
1174 prefs
.pinch_overlay_scrollbar_thickness
);
1175 settings
->setUseSolidColorScrollbars(prefs
.use_solid_color_scrollbars
);
1177 settings
->setShowContextMenuOnMouseUp(prefs
.context_menu_on_mouse_up
);
1179 #if defined(OS_MACOSX)
1180 settings
->setDoubleTapToZoomEnabled(true);
1181 web_view
->setMaximumLegibleScale(prefs
.default_maximum_page_scale_factor
);
1186 RenderViewImpl
* RenderViewImpl::Create(CompositorDependencies
* compositor_deps
,
1187 const ViewMsg_New_Params
& params
,
1188 bool was_created_by_renderer
) {
1189 DCHECK(params
.view_id
!= MSG_ROUTING_NONE
);
1190 RenderViewImpl
* render_view
= NULL
;
1191 if (g_create_render_view_impl
)
1192 render_view
= g_create_render_view_impl(compositor_deps
, params
);
1194 render_view
= new RenderViewImpl(compositor_deps
, params
);
1196 render_view
->Initialize(params
, was_created_by_renderer
);
1201 void RenderViewImpl::InstallCreateHook(RenderViewImpl
* (
1202 *create_render_view_impl
)(CompositorDependencies
* compositor_deps
,
1203 const ViewMsg_New_Params
&)) {
1204 CHECK(!g_create_render_view_impl
);
1205 g_create_render_view_impl
= create_render_view_impl
;
1208 void RenderViewImpl::AddObserver(RenderViewObserver
* observer
) {
1209 observers_
.AddObserver(observer
);
1212 void RenderViewImpl::RemoveObserver(RenderViewObserver
* observer
) {
1213 observer
->RenderViewGone();
1214 observers_
.RemoveObserver(observer
);
1217 blink::WebView
* RenderViewImpl::webview() const {
1218 return static_cast<blink::WebView
*>(webwidget());
1221 #if defined(ENABLE_PLUGINS)
1222 void RenderViewImpl::PepperInstanceCreated(
1223 PepperPluginInstanceImpl
* instance
) {
1224 active_pepper_instances_
.insert(instance
);
1226 RenderFrameImpl
* const render_frame
= instance
->render_frame();
1228 new FrameHostMsg_PepperInstanceCreated(render_frame
->GetRoutingID()));
1231 void RenderViewImpl::PepperInstanceDeleted(
1232 PepperPluginInstanceImpl
* instance
) {
1233 active_pepper_instances_
.erase(instance
);
1235 if (pepper_last_mouse_event_target_
== instance
)
1236 pepper_last_mouse_event_target_
= NULL
;
1237 if (focused_pepper_plugin_
== instance
)
1238 PepperFocusChanged(instance
, false);
1240 RenderFrameImpl
* const render_frame
= instance
->render_frame();
1243 new FrameHostMsg_PepperInstanceDeleted(render_frame
->GetRoutingID()));
1246 void RenderViewImpl::PepperFocusChanged(PepperPluginInstanceImpl
* instance
,
1249 focused_pepper_plugin_
= instance
;
1250 else if (focused_pepper_plugin_
== instance
)
1251 focused_pepper_plugin_
= NULL
;
1253 UpdateTextInputType();
1254 UpdateSelectionBounds();
1257 void RenderViewImpl::RegisterPluginDelegate(WebPluginDelegateProxy
* delegate
) {
1258 plugin_delegates_
.insert(delegate
);
1259 // If the renderer is visible, set initial visibility and focus state.
1261 #if defined(OS_MACOSX)
1262 delegate
->SetContainerVisibility(true);
1263 if (webview() && webview()->isActive())
1264 delegate
->SetWindowFocus(true);
1267 // Plugins start assuming the content has focus (so that they work in
1268 // environments where RenderView isn't hosting them), so we always have to
1269 // set the initial state. See webplugin_delegate_impl.h for details.
1270 delegate
->SetContentAreaFocus(has_focus());
1273 void RenderViewImpl::UnregisterPluginDelegate(
1274 WebPluginDelegateProxy
* delegate
) {
1275 plugin_delegates_
.erase(delegate
);
1279 void RenderViewImpl::PluginFocusChanged(bool focused
, int plugin_id
) {
1281 focused_plugin_id_
= plugin_id
;
1283 focused_plugin_id_
= -1;
1287 #if defined(OS_MACOSX)
1288 void RenderViewImpl::PluginFocusChanged(bool focused
, int plugin_id
) {
1289 Send(new ViewHostMsg_PluginFocusChanged(routing_id(), focused
, plugin_id
));
1292 void RenderViewImpl::OnGetRenderedText() {
1295 // Get rendered text from WebLocalFrame.
1296 // TODO: Currently IPC truncates any data that has a
1297 // size > kMaximumMessageSize. May be split the text into smaller chunks and
1298 // send back using multiple IPC. See http://crbug.com/393444.
1299 static const size_t kMaximumMessageSize
= 8 * 1024 * 1024;
1300 std::string text
= webview()->mainFrame()->contentAsText(
1301 kMaximumMessageSize
).utf8();
1303 Send(new ViewMsg_GetRenderedTextCompleted(routing_id(), text
));
1306 void RenderViewImpl::StartPluginIme() {
1307 IPC::Message
* msg
= new ViewHostMsg_StartPluginIme(routing_id());
1308 // This message can be sent during event-handling, and needs to be delivered
1309 // within that context.
1310 msg
->set_unblock(true);
1313 #endif // defined(OS_MACOSX)
1315 #endif // ENABLE_PLUGINS
1317 void RenderViewImpl::TransferActiveWheelFlingAnimation(
1318 const blink::WebActiveWheelFlingParameters
& params
) {
1320 webview()->transferActiveWheelFlingAnimation(params
);
1323 bool RenderViewImpl::HasIMETextFocus() {
1324 return GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE
;
1327 bool RenderViewImpl::OnMessageReceived(const IPC::Message
& message
) {
1328 WebFrame
* main_frame
= webview() ? webview()->mainFrame() : NULL
;
1329 if (main_frame
&& main_frame
->isWebLocalFrame())
1330 GetContentClient()->SetActiveURL(main_frame
->document().url());
1332 base::ObserverListBase
<RenderViewObserver
>::Iterator
it(&observers_
);
1333 RenderViewObserver
* observer
;
1334 while ((observer
= it
.GetNext()) != NULL
)
1335 if (observer
->OnMessageReceived(message
))
1338 bool handled
= true;
1339 IPC_BEGIN_MESSAGE_MAP(RenderViewImpl
, message
)
1340 IPC_MESSAGE_HANDLER(InputMsg_ExecuteEditCommand
, OnExecuteEditCommand
)
1341 IPC_MESSAGE_HANDLER(InputMsg_MoveCaret
, OnMoveCaret
)
1342 IPC_MESSAGE_HANDLER(InputMsg_ScrollFocusedEditableNodeIntoRect
,
1343 OnScrollFocusedEditableNodeIntoRect
)
1344 IPC_MESSAGE_HANDLER(InputMsg_SetEditCommandsForNextKeyEvent
,
1345 OnSetEditCommandsForNextKeyEvent
)
1346 IPC_MESSAGE_HANDLER(ViewMsg_CopyImageAt
, OnCopyImageAt
)
1347 IPC_MESSAGE_HANDLER(ViewMsg_SaveImageAt
, OnSaveImageAt
)
1348 IPC_MESSAGE_HANDLER(ViewMsg_Find
, OnFind
)
1349 IPC_MESSAGE_HANDLER(ViewMsg_StopFinding
, OnStopFinding
)
1350 IPC_MESSAGE_HANDLER(ViewMsg_ResetPageScale
, OnResetPageScale
)
1351 IPC_MESSAGE_HANDLER(ViewMsg_Zoom
, OnZoom
)
1352 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForLoadingURL
,
1353 OnSetZoomLevelForLoadingURL
)
1354 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForView
,
1355 OnSetZoomLevelForView
)
1356 IPC_MESSAGE_HANDLER(ViewMsg_SetPageEncoding
, OnSetPageEncoding
)
1357 IPC_MESSAGE_HANDLER(ViewMsg_ResetPageEncodingToDefault
,
1358 OnResetPageEncodingToDefault
)
1359 IPC_MESSAGE_HANDLER(DragMsg_TargetDragEnter
, OnDragTargetDragEnter
)
1360 IPC_MESSAGE_HANDLER(DragMsg_TargetDragOver
, OnDragTargetDragOver
)
1361 IPC_MESSAGE_HANDLER(DragMsg_TargetDragLeave
, OnDragTargetDragLeave
)
1362 IPC_MESSAGE_HANDLER(DragMsg_TargetDrop
, OnDragTargetDrop
)
1363 IPC_MESSAGE_HANDLER(DragMsg_SourceEnded
, OnDragSourceEnded
)
1364 IPC_MESSAGE_HANDLER(DragMsg_SourceSystemDragEnded
,
1365 OnDragSourceSystemDragEnded
)
1366 IPC_MESSAGE_HANDLER(ViewMsg_AllowBindings
, OnAllowBindings
)
1367 IPC_MESSAGE_HANDLER(ViewMsg_SetInitialFocus
, OnSetInitialFocus
)
1368 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTargetURL_ACK
, OnUpdateTargetURLAck
)
1369 IPC_MESSAGE_HANDLER(ViewMsg_UpdateWebPreferences
, OnUpdateWebPreferences
)
1370 IPC_MESSAGE_HANDLER(ViewMsg_EnumerateDirectoryResponse
,
1371 OnEnumerateDirectoryResponse
)
1372 IPC_MESSAGE_HANDLER(ViewMsg_RunFileChooserResponse
, OnFileChooserResponse
)
1373 IPC_MESSAGE_HANDLER(ViewMsg_SuppressDialogsUntilSwapOut
,
1374 OnSuppressDialogsUntilSwapOut
)
1375 IPC_MESSAGE_HANDLER(ViewMsg_ClosePage
, OnClosePage
)
1376 IPC_MESSAGE_HANDLER(ViewMsg_ThemeChanged
, OnThemeChanged
)
1377 IPC_MESSAGE_HANDLER(ViewMsg_MoveOrResizeStarted
, OnMoveOrResizeStarted
)
1378 IPC_MESSAGE_HANDLER(ViewMsg_ClearFocusedElement
, OnClearFocusedElement
)
1379 IPC_MESSAGE_HANDLER(ViewMsg_SetBackgroundOpaque
, OnSetBackgroundOpaque
)
1380 IPC_MESSAGE_HANDLER(ViewMsg_EnablePreferredSizeChangedMode
,
1381 OnEnablePreferredSizeChangedMode
)
1382 IPC_MESSAGE_HANDLER(ViewMsg_EnableAutoResize
, OnEnableAutoResize
)
1383 IPC_MESSAGE_HANDLER(ViewMsg_DisableAutoResize
, OnDisableAutoResize
)
1384 IPC_MESSAGE_HANDLER(ViewMsg_DisableScrollbarsForSmallWindows
,
1385 OnDisableScrollbarsForSmallWindows
)
1386 IPC_MESSAGE_HANDLER(ViewMsg_SetRendererPrefs
, OnSetRendererPrefs
)
1387 IPC_MESSAGE_HANDLER(ViewMsg_MediaPlayerActionAt
, OnMediaPlayerActionAt
)
1388 IPC_MESSAGE_HANDLER(ViewMsg_PluginActionAt
, OnPluginActionAt
)
1389 IPC_MESSAGE_HANDLER(ViewMsg_SetActive
, OnSetActive
)
1390 IPC_MESSAGE_HANDLER(ViewMsg_GetAllSavableResourceLinksForCurrentPage
,
1391 OnGetAllSavableResourceLinksForCurrentPage
)
1392 IPC_MESSAGE_HANDLER(
1393 ViewMsg_GetSerializedHtmlDataForCurrentPageWithLocalLinks
,
1394 OnGetSerializedHtmlDataForCurrentPageWithLocalLinks
)
1395 IPC_MESSAGE_HANDLER(ViewMsg_ShowContextMenu
, OnShowContextMenu
)
1396 // TODO(viettrungluu): Move to a separate message filter.
1397 IPC_MESSAGE_HANDLER(ViewMsg_SetHistoryOffsetAndLength
,
1398 OnSetHistoryOffsetAndLength
)
1399 IPC_MESSAGE_HANDLER(ViewMsg_EnableViewSourceMode
, OnEnableViewSourceMode
)
1400 IPC_MESSAGE_HANDLER(ViewMsg_ReleaseDisambiguationPopupBitmap
,
1401 OnReleaseDisambiguationPopupBitmap
)
1402 IPC_MESSAGE_HANDLER(ViewMsg_ForceRedraw
, OnForceRedraw
)
1403 IPC_MESSAGE_HANDLER(ViewMsg_SelectWordAroundCaret
, OnSelectWordAroundCaret
)
1404 #if defined(OS_ANDROID)
1405 IPC_MESSAGE_HANDLER(InputMsg_ActivateNearestFindResult
,
1406 OnActivateNearestFindResult
)
1407 IPC_MESSAGE_HANDLER(ViewMsg_FindMatchRects
, OnFindMatchRects
)
1408 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTopControlsState
,
1409 OnUpdateTopControlsState
)
1410 IPC_MESSAGE_HANDLER(ViewMsg_ExtractSmartClipData
, OnExtractSmartClipData
)
1411 #elif defined(OS_MACOSX)
1412 IPC_MESSAGE_HANDLER(ViewMsg_GetRenderedText
,
1414 IPC_MESSAGE_HANDLER(ViewMsg_PluginImeCompositionCompleted
,
1415 OnPluginImeCompositionCompleted
)
1416 IPC_MESSAGE_HANDLER(ViewMsg_Close
, OnClose
)
1417 IPC_MESSAGE_HANDLER(ViewMsg_SetInLiveResize
, OnSetInLiveResize
)
1418 IPC_MESSAGE_HANDLER(ViewMsg_SetWindowVisibility
, OnSetWindowVisibility
)
1419 IPC_MESSAGE_HANDLER(ViewMsg_WindowFrameChanged
, OnWindowFrameChanged
)
1421 // Adding a new message? Add platform independent ones first, then put the
1422 // platform specific ones at the end.
1424 // Have the super handle all other messages.
1425 IPC_MESSAGE_UNHANDLED(handled
= RenderWidget::OnMessageReceived(message
))
1426 IPC_END_MESSAGE_MAP()
1431 void RenderViewImpl::OnSelectWordAroundCaret() {
1435 handling_input_event_
= true;
1436 webview()->focusedFrame()->selectWordAroundCaret();
1437 handling_input_event_
= false;
1440 void RenderViewImpl::OnCopyImageAt(int x
, int y
) {
1441 webview()->copyImageAt(WebPoint(x
, y
));
1444 void RenderViewImpl::OnSaveImageAt(int x
, int y
) {
1445 webview()->saveImageAt(WebPoint(x
, y
));
1448 void RenderViewImpl::OnUpdateTargetURLAck() {
1449 // Check if there is a targeturl waiting to be sent.
1450 if (target_url_status_
== TARGET_PENDING
)
1451 Send(new ViewHostMsg_UpdateTargetURL(routing_id_
, pending_target_url_
));
1453 target_url_status_
= TARGET_NONE
;
1456 void RenderViewImpl::OnExecuteEditCommand(const std::string
& name
,
1457 const std::string
& value
) {
1458 if (!webview() || !webview()->focusedFrame())
1461 webview()->focusedFrame()->executeCommand(
1462 WebString::fromUTF8(name
), WebString::fromUTF8(value
));
1465 void RenderViewImpl::OnMoveCaret(const gfx::Point
& point
) {
1469 Send(new InputHostMsg_MoveCaret_ACK(routing_id_
));
1471 webview()->focusedFrame()->moveCaretSelection(point
);
1474 void RenderViewImpl::OnScrollFocusedEditableNodeIntoRect(
1475 const gfx::Rect
& rect
) {
1476 if (has_scrolled_focused_editable_node_into_rect_
&&
1477 rect
== rect_for_scrolled_focused_editable_node_
) {
1478 FocusChangeComplete();
1482 blink::WebElement element
= GetFocusedElement();
1483 bool will_animate
= false;
1484 if (!element
.isNull() && IsEditableNode(element
)) {
1485 rect_for_scrolled_focused_editable_node_
= rect
;
1486 has_scrolled_focused_editable_node_into_rect_
= true;
1487 will_animate
= webview()->scrollFocusedNodeIntoRect(rect
);
1491 FocusChangeComplete();
1494 void RenderViewImpl::OnSetEditCommandsForNextKeyEvent(
1495 const EditCommands
& edit_commands
) {
1496 edit_commands_
= edit_commands
;
1499 void RenderViewImpl::OnSetHistoryOffsetAndLength(int history_offset
,
1500 int history_length
) {
1501 DCHECK_GE(history_offset
, -1);
1502 DCHECK_GE(history_length
, 0);
1504 history_list_offset_
= history_offset
;
1505 history_list_length_
= history_length
;
1508 void RenderViewImpl::OnSetInitialFocus(bool reverse
) {
1511 webview()->setInitialFocus(reverse
);
1514 #if defined(OS_MACOSX)
1515 void RenderViewImpl::OnSetInLiveResize(bool in_live_resize
) {
1519 webview()->willStartLiveResize();
1521 webview()->willEndLiveResize();
1525 ///////////////////////////////////////////////////////////////////////////////
1527 void RenderViewImpl::SendUpdateState() {
1528 HistoryEntry
* entry
= history_controller_
->GetCurrentEntry();
1532 // Don't send state updates for kSwappedOutURL.
1533 if (entry
->root().urlString() == WebString::fromUTF8(kSwappedOutURL
))
1536 Send(new ViewHostMsg_UpdateState(
1537 routing_id_
, page_id_
, HistoryEntryToPageState(entry
)));
1540 void RenderViewImpl::ApplyWebPreferencesInternal(
1541 const WebPreferences
& prefs
,
1542 blink::WebView
* web_view
,
1543 CompositorDependencies
* compositor_deps
) {
1544 ApplyWebPreferences(prefs
, web_view
);
1545 #if defined(OS_MACOSX) && !defined(OS_IOS)
1546 DCHECK(compositor_deps
);
1547 bool is_elastic_overscroll_enabled
=
1548 compositor_deps
->IsElasticOverscrollEnabled();
1549 web_view
->settings()->setReportWheelOverscroll(is_elastic_overscroll_enabled
);
1553 bool RenderViewImpl::SendAndRunNestedMessageLoop(IPC::SyncMessage
* message
) {
1554 // Before WebKit asks us to show an alert (etc.), it takes care of doing the
1555 // equivalent of WebView::willEnterModalLoop. In the case of showModalDialog
1556 // it is particularly important that we do not call willEnterModalLoop as
1557 // that would defer resource loads for the dialog itself.
1558 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
1559 RenderThreadImpl::current()->DoNotNotifyWebKitOfModalLoop();
1561 message
->EnableMessagePumping(); // Runs a nested message loop.
1562 return Send(message
);
1565 void RenderViewImpl::OnForceRedraw(int id
) {
1566 ui::LatencyInfo latency_info
;
1568 latency_info
.AddLatencyNumber(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT
,
1572 scoped_ptr
<cc::SwapPromiseMonitor
> latency_info_swap_promise_monitor
;
1573 if (RenderWidgetCompositor
* rwc
= compositor()) {
1574 latency_info_swap_promise_monitor
=
1575 rwc
->CreateLatencyInfoSwapPromiseMonitor(&latency_info
).Pass();
1577 ScheduleCompositeWithForcedRedraw();
1580 // blink::WebViewClient ------------------------------------------------------
1582 WebView
* RenderViewImpl::createView(WebLocalFrame
* creator
,
1583 const WebURLRequest
& request
,
1584 const WebWindowFeatures
& features
,
1585 const WebString
& frame_name
,
1586 WebNavigationPolicy policy
,
1587 bool suppress_opener
) {
1588 ViewHostMsg_CreateWindow_Params params
;
1589 params
.opener_id
= routing_id_
;
1590 params
.user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
1591 if (GetContentClient()->renderer()->AllowPopup())
1592 params
.user_gesture
= true;
1593 params
.window_container_type
= WindowFeaturesToContainerType(features
);
1594 params
.session_storage_namespace_id
= session_storage_namespace_id_
;
1595 if (frame_name
!= "_blank")
1596 params
.frame_name
= base::UTF16ToUTF8(base::StringPiece16(frame_name
));
1597 params
.opener_render_frame_id
=
1598 RenderFrameImpl::FromWebFrame(creator
)->GetRoutingID();
1599 params
.opener_url
= creator
->document().url();
1601 // The browser process uses the top frame's URL for a content settings check
1602 // to determine whether the popup is allowed. If the top frame is remote,
1603 // its URL is not available, so use its replicated origin instead.
1605 // TODO(alexmos): This works fine for regular origins but may break path
1606 // matching for file URLs with OOP subframes that open popups. This should
1607 // be fixed by either moving this lookup to the browser process or removing
1608 // path-based matching for file URLs from content settings. See
1609 // https://crbug.com/466297.
1610 if (creator
->top()->isWebLocalFrame()) {
1611 params
.opener_top_level_frame_url
= creator
->top()->document().url();
1613 params
.opener_top_level_frame_url
=
1614 GURL(creator
->top()->securityOrigin().toString());
1617 GURL
security_url(creator
->document().securityOrigin().toString());
1618 if (!security_url
.is_valid())
1619 security_url
= GURL();
1620 params
.opener_security_origin
= security_url
;
1621 params
.opener_suppressed
= suppress_opener
;
1622 params
.disposition
= NavigationPolicyToDisposition(policy
);
1623 if (!request
.isNull()) {
1624 params
.target_url
= request
.url();
1625 params
.referrer
= GetReferrerFromRequest(creator
, request
);
1627 params
.features
= features
;
1629 for (size_t i
= 0; i
< features
.additionalFeatures
.size(); ++i
)
1630 params
.additional_features
.push_back(features
.additionalFeatures
[i
]);
1632 int32 routing_id
= MSG_ROUTING_NONE
;
1633 int32 main_frame_routing_id
= MSG_ROUTING_NONE
;
1634 int32 surface_id
= 0;
1635 int64 cloned_session_storage_namespace_id
= 0;
1637 RenderThread::Get()->Send(new ViewHostMsg_CreateWindow(
1638 params
, &routing_id
, &main_frame_routing_id
, &surface_id
,
1639 &cloned_session_storage_namespace_id
));
1640 if (routing_id
== MSG_ROUTING_NONE
)
1643 WebUserGestureIndicator::consumeUserGesture();
1645 // While this view may be a background extension page, it can spawn a visible
1646 // render view. So we just assume that the new one is not another background
1647 // page instead of passing on our own value.
1648 // TODO(vangelis): Can we tell if the new view will be a background page?
1649 bool never_visible
= false;
1651 ViewMsg_Resize_Params initial_size
= ViewMsg_Resize_Params();
1652 initial_size
.screen_info
= screen_info_
;
1654 // The initial hidden state for the RenderViewImpl here has to match what the
1655 // browser will eventually decide for the given disposition. Since we have to
1656 // return from this call synchronously, we just have to make our best guess
1657 // and rely on the browser sending a WasHidden / WasShown message if it
1659 ViewMsg_New_Params view_params
;
1661 RenderFrameImpl
* creator_frame
= RenderFrameImpl::FromWebFrame(creator
);
1662 view_params
.opener_frame_route_id
= creator_frame
->GetRoutingID();
1663 DCHECK_EQ(routing_id_
, creator_frame
->render_view()->GetRoutingID());
1665 view_params
.window_was_created_with_opener
= true;
1666 view_params
.renderer_preferences
= renderer_preferences_
;
1667 view_params
.web_preferences
= webkit_preferences_
;
1668 view_params
.view_id
= routing_id
;
1669 view_params
.main_frame_routing_id
= main_frame_routing_id
;
1670 view_params
.surface_id
= surface_id
;
1671 view_params
.session_storage_namespace_id
=
1672 cloned_session_storage_namespace_id
;
1673 view_params
.swapped_out
= false;
1674 // WebCore will take care of setting the correct name.
1675 view_params
.replicated_frame_state
= FrameReplicationState();
1676 view_params
.proxy_routing_id
= MSG_ROUTING_NONE
;
1677 view_params
.hidden
= (params
.disposition
== NEW_BACKGROUND_TAB
);
1678 view_params
.never_visible
= never_visible
;
1679 view_params
.next_page_id
= 1;
1680 view_params
.initial_size
= initial_size
;
1681 view_params
.enable_auto_resize
= false;
1682 view_params
.min_size
= gfx::Size();
1683 view_params
.max_size
= gfx::Size();
1685 RenderViewImpl
* view
=
1686 RenderViewImpl::Create(compositor_deps_
, view_params
, true);
1687 view
->opened_by_user_gesture_
= params
.user_gesture
;
1689 // Record whether the creator frame is trying to suppress the opener field.
1690 view
->opener_suppressed_
= params
.opener_suppressed
;
1692 return view
->webview();
1695 WebWidget
* RenderViewImpl::createPopupMenu(blink::WebPopupType popup_type
) {
1696 RenderWidget
* widget
= RenderWidget::Create(routing_id_
, compositor_deps_
,
1697 popup_type
, screen_info_
);
1700 if (screen_metrics_emulator_
) {
1701 widget
->SetPopupOriginAdjustmentsForEmulation(
1702 screen_metrics_emulator_
.get());
1704 return widget
->webwidget();
1707 WebStorageNamespace
* RenderViewImpl::createSessionStorageNamespace() {
1708 CHECK(session_storage_namespace_id_
!= kInvalidSessionStorageNamespaceId
);
1709 return new WebStorageNamespaceImpl(session_storage_namespace_id_
);
1712 void RenderViewImpl::printPage(WebLocalFrame
* frame
) {
1713 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
,
1714 PrintPage(frame
, handling_input_event_
));
1717 void RenderViewImpl::saveImageFromDataURL(const blink::WebString
& data_url
) {
1718 // Note: We should basically send GURL but we use size-limited string instead
1719 // in order to send a larger data url to save a image for <canvas> or <img>.
1720 if (data_url
.length() < kMaxLengthOfDataURLString
)
1721 Send(new ViewHostMsg_SaveImageFromDataURL(routing_id_
, data_url
.utf8()));
1724 bool RenderViewImpl::enumerateChosenDirectory(
1725 const WebString
& path
,
1726 WebFileChooserCompletion
* chooser_completion
) {
1727 int id
= enumeration_completion_id_
++;
1728 enumeration_completions_
[id
] = chooser_completion
;
1729 return Send(new ViewHostMsg_EnumerateDirectory(
1732 base::FilePath::FromUTF16Unsafe(path
)));
1735 void RenderViewImpl::FrameDidStartLoading(WebFrame
* frame
) {
1736 DCHECK_GE(frames_in_progress_
, 0);
1737 if (frames_in_progress_
== 0)
1738 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidStartLoading());
1739 frames_in_progress_
++;
1742 void RenderViewImpl::FrameDidStopLoading(WebFrame
* frame
) {
1743 // TODO(japhet): This should be a DCHECK, but the pdf plugin sometimes
1744 // calls DidStopLoading() without a matching DidStartLoading().
1745 if (frames_in_progress_
== 0)
1747 frames_in_progress_
--;
1748 if (frames_in_progress_
== 0) {
1749 DidStopLoadingIcons();
1750 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidStopLoading());
1754 void RenderViewImpl::didCancelCompositionOnSelectionChange() {
1755 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
1758 bool RenderViewImpl::handleCurrentKeyboardEvent() {
1759 if (edit_commands_
.empty())
1762 WebFrame
* frame
= webview()->focusedFrame();
1766 EditCommands::iterator it
= edit_commands_
.begin();
1767 EditCommands::iterator end
= edit_commands_
.end();
1769 bool did_execute_command
= false;
1770 for (; it
!= end
; ++it
) {
1771 // In gtk and cocoa, it's possible to bind multiple edit commands to one
1772 // key (but it's the exception). Once one edit command is not executed, it
1773 // seems safest to not execute the rest.
1774 if (!frame
->executeCommand(WebString::fromUTF8(it
->name
),
1775 WebString::fromUTF8(it
->value
),
1776 GetFocusedElement()))
1778 did_execute_command
= true;
1781 return did_execute_command
;
1784 bool RenderViewImpl::runFileChooser(
1785 const blink::WebFileChooserParams
& params
,
1786 WebFileChooserCompletion
* chooser_completion
) {
1787 // Do not open the file dialog in a hidden RenderView.
1790 FileChooserParams ipc_params
;
1791 if (params
.directory
)
1792 ipc_params
.mode
= FileChooserParams::UploadFolder
;
1793 else if (params
.multiSelect
)
1794 ipc_params
.mode
= FileChooserParams::OpenMultiple
;
1795 else if (params
.saveAs
)
1796 ipc_params
.mode
= FileChooserParams::Save
;
1798 ipc_params
.mode
= FileChooserParams::Open
;
1799 ipc_params
.title
= params
.title
;
1800 ipc_params
.default_file_name
=
1801 base::FilePath::FromUTF16Unsafe(params
.initialValue
).BaseName();
1802 ipc_params
.accept_types
.reserve(params
.acceptTypes
.size());
1803 for (size_t i
= 0; i
< params
.acceptTypes
.size(); ++i
)
1804 ipc_params
.accept_types
.push_back(params
.acceptTypes
[i
]);
1805 ipc_params
.need_local_path
= params
.needLocalPath
;
1806 #if defined(OS_ANDROID)
1807 ipc_params
.capture
= params
.useMediaCapture
;
1810 return ScheduleFileChooser(ipc_params
, chooser_completion
);
1813 void RenderViewImpl::SetValidationMessageDirection(
1814 base::string16
* wrapped_main_text
,
1815 blink::WebTextDirection main_text_hint
,
1816 base::string16
* wrapped_sub_text
,
1817 blink::WebTextDirection sub_text_hint
) {
1818 if (main_text_hint
== blink::WebTextDirectionLeftToRight
) {
1819 *wrapped_main_text
=
1820 base::i18n::GetDisplayStringInLTRDirectionality(*wrapped_main_text
);
1821 } else if (main_text_hint
== blink::WebTextDirectionRightToLeft
&&
1822 !base::i18n::IsRTL()) {
1823 base::i18n::WrapStringWithRTLFormatting(wrapped_main_text
);
1826 if (!wrapped_sub_text
->empty()) {
1827 if (sub_text_hint
== blink::WebTextDirectionLeftToRight
) {
1829 base::i18n::GetDisplayStringInLTRDirectionality(*wrapped_sub_text
);
1830 } else if (sub_text_hint
== blink::WebTextDirectionRightToLeft
) {
1831 base::i18n::WrapStringWithRTLFormatting(wrapped_sub_text
);
1836 void RenderViewImpl::showValidationMessage(
1837 const blink::WebRect
& anchor_in_root_view
,
1838 const blink::WebString
& main_text
,
1839 blink::WebTextDirection main_text_hint
,
1840 const blink::WebString
& sub_text
,
1841 blink::WebTextDirection sub_text_hint
) {
1842 base::string16 wrapped_main_text
= main_text
;
1843 base::string16 wrapped_sub_text
= sub_text
;
1845 SetValidationMessageDirection(
1846 &wrapped_main_text
, main_text_hint
, &wrapped_sub_text
, sub_text_hint
);
1848 Send(new ViewHostMsg_ShowValidationMessage(
1849 routing_id(), AdjustValidationMessageAnchor(anchor_in_root_view
),
1850 wrapped_main_text
, wrapped_sub_text
));
1853 void RenderViewImpl::hideValidationMessage() {
1854 Send(new ViewHostMsg_HideValidationMessage(routing_id()));
1857 void RenderViewImpl::moveValidationMessage(
1858 const blink::WebRect
& anchor_in_root_view
) {
1859 Send(new ViewHostMsg_MoveValidationMessage(
1860 routing_id(), AdjustValidationMessageAnchor(anchor_in_root_view
)));
1863 void RenderViewImpl::setStatusText(const WebString
& text
) {
1866 void RenderViewImpl::UpdateTargetURL(const GURL
& url
,
1867 const GURL
& fallback_url
) {
1868 GURL latest_url
= url
.is_empty() ? fallback_url
: url
;
1869 if (latest_url
== target_url_
)
1872 // Tell the browser to display a destination link.
1873 if (target_url_status_
== TARGET_INFLIGHT
||
1874 target_url_status_
== TARGET_PENDING
) {
1875 // If we have a request in-flight, save the URL to be sent when we
1876 // receive an ACK to the in-flight request. We can happily overwrite
1877 // any existing pending sends.
1878 pending_target_url_
= latest_url
;
1879 target_url_status_
= TARGET_PENDING
;
1881 // URLs larger than |MaxURLChars()| cannot be sent through IPC -
1882 // see |ParamTraits<GURL>|.
1883 if (latest_url
.possibly_invalid_spec().size() > GetMaxURLChars())
1884 latest_url
= GURL();
1885 Send(new ViewHostMsg_UpdateTargetURL(routing_id_
, latest_url
));
1886 target_url_
= latest_url
;
1887 target_url_status_
= TARGET_INFLIGHT
;
1891 gfx::RectF
RenderViewImpl::ClientRectToPhysicalWindowRect(
1892 const gfx::RectF
& rect
) const {
1893 gfx::RectF window_rect
= rect
;
1894 window_rect
.Scale(device_scale_factor_
* webview()->pageScaleFactor());
1898 void RenderViewImpl::StartNavStateSyncTimerIfNecessary() {
1900 if (send_content_state_immediately_
)
1902 else if (is_hidden())
1903 delay
= kDelaySecondsForContentStateSyncHidden
;
1905 delay
= kDelaySecondsForContentStateSync
;
1907 if (nav_state_sync_timer_
.IsRunning()) {
1908 // The timer is already running. If the delay of the timer maches the amount
1909 // we want to delay by, then return. Otherwise stop the timer so that it
1910 // gets started with the right delay.
1911 if (nav_state_sync_timer_
.GetCurrentDelay().InSeconds() == delay
)
1913 nav_state_sync_timer_
.Stop();
1916 nav_state_sync_timer_
.Start(FROM_HERE
, TimeDelta::FromSeconds(delay
), this,
1917 &RenderViewImpl::SendUpdateState
);
1920 void RenderViewImpl::setMouseOverURL(const WebURL
& url
) {
1921 mouse_over_url_
= GURL(url
);
1922 UpdateTargetURL(mouse_over_url_
, focus_url_
);
1925 void RenderViewImpl::setKeyboardFocusURL(const WebURL
& url
) {
1926 focus_url_
= GURL(url
);
1927 UpdateTargetURL(focus_url_
, mouse_over_url_
);
1930 void RenderViewImpl::startDragging(WebLocalFrame
* frame
,
1931 const WebDragData
& data
,
1932 WebDragOperationsMask mask
,
1933 const WebImage
& image
,
1934 const WebPoint
& webImageOffset
) {
1935 DropData
drop_data(DropDataBuilder::Build(data
));
1936 drop_data
.referrer_policy
= frame
->document().referrerPolicy();
1937 gfx::Vector2d
imageOffset(webImageOffset
.x
, webImageOffset
.y
);
1938 Send(new DragHostMsg_StartDragging(routing_id_
,
1941 image
.getSkBitmap(),
1943 possible_drag_event_info_
));
1946 bool RenderViewImpl::acceptsLoadDrops() {
1947 return renderer_preferences_
.can_accept_load_drops
;
1950 void RenderViewImpl::focusNext() {
1951 Send(new ViewHostMsg_TakeFocus(routing_id_
, false));
1954 void RenderViewImpl::focusPrevious() {
1955 Send(new ViewHostMsg_TakeFocus(routing_id_
, true));
1958 void RenderViewImpl::focusedNodeChanged(const WebNode
& fromNode
,
1959 const WebNode
& toNode
) {
1960 has_scrolled_focused_editable_node_into_rect_
= false;
1962 gfx::Rect node_bounds
;
1963 if (!toNode
.isNull() && toNode
.isElementNode()) {
1964 WebNode web_node
= const_cast<WebNode
&>(toNode
);
1965 node_bounds
= gfx::Rect(web_node
.to
<WebElement
>().boundsInViewportSpace());
1967 Send(new ViewHostMsg_FocusedNodeChanged(routing_id_
, IsEditableNode(toNode
),
1970 // TODO(estade): remove.
1971 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, FocusedNodeChanged(toNode
));
1973 RenderFrameImpl
* previous_frame
= nullptr;
1974 if (!fromNode
.isNull())
1975 previous_frame
= RenderFrameImpl::FromWebFrame(fromNode
.document().frame());
1976 RenderFrameImpl
* new_frame
= nullptr;
1977 if (!toNode
.isNull())
1978 new_frame
= RenderFrameImpl::FromWebFrame(toNode
.document().frame());
1980 if (previous_frame
&& previous_frame
!= new_frame
)
1981 previous_frame
->FocusedNodeChanged(WebNode());
1983 new_frame
->FocusedNodeChanged(toNode
);
1985 // TODO(dmazzoni): remove once there's a separate a11y tree per frame.
1986 GetMainRenderFrame()->FocusedNodeChangedForAccessibility(toNode
);
1989 void RenderViewImpl::didUpdateLayout() {
1990 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidUpdateLayout());
1992 // We don't always want to set up a timer, only if we've been put in that
1993 // mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
1995 if (!send_preferred_size_changes_
|| !webview())
1998 if (check_preferred_size_timer_
.IsRunning())
2000 check_preferred_size_timer_
.Start(FROM_HERE
,
2001 TimeDelta::FromMilliseconds(0), this,
2002 &RenderViewImpl::CheckPreferredSize
);
2005 void RenderViewImpl::navigateBackForwardSoon(int offset
) {
2006 Send(new ViewHostMsg_GoToEntryAtOffset(routing_id_
, offset
));
2009 int RenderViewImpl::historyBackListCount() {
2010 return history_list_offset_
< 0 ? 0 : history_list_offset_
;
2013 int RenderViewImpl::historyForwardListCount() {
2014 return history_list_length_
- historyBackListCount() - 1;
2017 // blink::WebWidgetClient ----------------------------------------------------
2019 void RenderViewImpl::didFocus() {
2020 // TODO(jcivelli): when https://bugs.webkit.org/show_bug.cgi?id=33389 is fixed
2021 // we won't have to test for user gesture anymore and we can
2022 // move that code back to render_widget.cc
2023 if (WebUserGestureIndicator::isProcessingUserGesture() &&
2024 !RenderThreadImpl::current()->layout_test_mode()) {
2025 Send(new ViewHostMsg_Focus(routing_id_
));
2029 void RenderViewImpl::didBlur() {
2030 // TODO(jcivelli): see TODO above in didFocus().
2031 if (WebUserGestureIndicator::isProcessingUserGesture() &&
2032 !RenderThreadImpl::current()->layout_test_mode()) {
2033 Send(new ViewHostMsg_Blur(routing_id_
));
2037 // We are supposed to get a single call to Show for a newly created RenderView
2038 // that was created via RenderViewImpl::CreateWebView. So, we wait until this
2039 // point to dispatch the ShowView message.
2041 // This method provides us with the information about how to display the newly
2042 // created RenderView (i.e., as a blocked popup or as a new tab).
2044 void RenderViewImpl::show(WebNavigationPolicy policy
) {
2046 // When supports_multiple_windows is disabled, popups are reusing
2047 // the same view. In some scenarios, this makes WebKit to call show() twice.
2048 if (webkit_preferences_
.supports_multiple_windows
)
2049 NOTREACHED() << "received extraneous Show call";
2054 DCHECK(opener_id_
!= MSG_ROUTING_NONE
);
2056 // NOTE: initial_rect_ may still have its default values at this point, but
2057 // that's okay. It'll be ignored if disposition is not NEW_POPUP, or the
2058 // browser process will impose a default position otherwise.
2059 Send(new ViewHostMsg_ShowView(opener_id_
, routing_id_
,
2060 NavigationPolicyToDisposition(policy
), initial_rect_
,
2061 opened_by_user_gesture_
));
2062 SetPendingWindowRect(initial_rect_
);
2065 bool RenderViewImpl::requestPointerLock() {
2066 return mouse_lock_dispatcher_
->LockMouse(webwidget_mouse_lock_target_
.get());
2069 void RenderViewImpl::requestPointerUnlock() {
2070 mouse_lock_dispatcher_
->UnlockMouse(webwidget_mouse_lock_target_
.get());
2073 bool RenderViewImpl::isPointerLocked() {
2074 return mouse_lock_dispatcher_
->IsMouseLockedTo(
2075 webwidget_mouse_lock_target_
.get());
2078 void RenderViewImpl::onMouseDown(const WebNode
& mouse_down_node
) {
2080 RenderViewObserver
, observers_
, OnMouseDown(mouse_down_node
));
2083 void RenderViewImpl::didHandleGestureEvent(
2084 const WebGestureEvent
& event
,
2085 bool event_cancelled
) {
2086 RenderWidget::didHandleGestureEvent(event
, event_cancelled
);
2088 if (!event_cancelled
) {
2090 RenderViewObserver
, observers_
, DidHandleGestureEvent(event
));
2093 // TODO(ananta): Piggyback off existing IPCs to communicate this information,
2096 if (event
.type
!= blink::WebGestureEvent::GestureTap
)
2099 // TODO(estade): hit test the event against focused node to make sure
2100 // the tap actually hit the focused node.
2101 blink::WebTextInputType text_input_type
=
2102 GetWebView()->textInputInfo().type
;
2104 Send(new ViewHostMsg_FocusedNodeTouched(
2105 routing_id(), text_input_type
!= blink::WebTextInputTypeNone
));
2109 void RenderViewImpl::initializeLayerTreeView() {
2110 RenderWidget::initializeLayerTreeView();
2111 RenderWidgetCompositor
* rwc
= compositor();
2115 bool use_threaded_event_handling
= true;
2116 #if defined(OS_MACOSX) && !defined(OS_IOS)
2117 // Disable threaded event handling if content is not handling the elastic
2118 // overscroll effect. This includes the cases where the elastic overscroll
2119 // effect is being handled by Blink (because of command line flags) and older
2120 // operating system versions which do not have an elastic overscroll effect
2121 // (SnowLeopard, which has Aqua scrollbars which need synchronous updates).
2122 use_threaded_event_handling
= compositor_deps_
->IsElasticOverscrollEnabled();
2124 if (use_threaded_event_handling
) {
2125 RenderThreadImpl
* render_thread
= RenderThreadImpl::current();
2126 // render_thread may be NULL in tests.
2127 InputHandlerManager
* input_handler_manager
=
2128 render_thread
? render_thread
->input_handler_manager() : NULL
;
2129 if (input_handler_manager
) {
2130 input_handler_manager
->AddInputHandler(
2131 routing_id_
, rwc
->GetInputHandler(), AsWeakPtr());
2136 // blink::WebFrameClient -----------------------------------------------------
2138 void RenderViewImpl::Repaint(const gfx::Size
& size
) {
2142 void RenderViewImpl::SetEditCommandForNextKeyEvent(const std::string
& name
,
2143 const std::string
& value
) {
2144 EditCommands edit_commands
;
2145 edit_commands
.push_back(EditCommand(name
, value
));
2146 OnSetEditCommandsForNextKeyEvent(edit_commands
);
2149 void RenderViewImpl::ClearEditCommands() {
2150 edit_commands_
.clear();
2153 SSLStatus
RenderViewImpl::GetSSLStatusOfFrame(blink::WebFrame
* frame
) const {
2154 std::string security_info
;
2155 if (frame
&& frame
->dataSource())
2156 security_info
= frame
->dataSource()->response().securityInfo();
2159 CHECK(DeserializeSecurityInfo(security_info
, &result
));
2163 const std::string
& RenderViewImpl::GetAcceptLanguages() const {
2164 return renderer_preferences_
.accept_languages
;
2167 void RenderViewImpl::didChangeIcon(WebLocalFrame
* frame
,
2168 WebIconURL::Type icon_type
) {
2169 if (frame
->parent())
2172 WebVector
<WebIconURL
> icon_urls
= frame
->iconURLs(icon_type
);
2173 std::vector
<FaviconURL
> urls
;
2174 for (size_t i
= 0; i
< icon_urls
.size(); i
++) {
2175 std::vector
<gfx::Size
> sizes
;
2176 ConvertToFaviconSizes(icon_urls
[i
].sizes(), &sizes
);
2177 urls
.push_back(FaviconURL(
2178 icon_urls
[i
].iconURL(), ToFaviconType(icon_urls
[i
].iconType()), sizes
));
2180 SendUpdateFaviconURL(urls
);
2183 void RenderViewImpl::didUpdateCurrentHistoryItem(WebLocalFrame
* frame
) {
2184 StartNavStateSyncTimerIfNecessary();
2187 void RenderViewImpl::CheckPreferredSize() {
2188 // We don't always want to send the change messages over IPC, only if we've
2189 // been put in that mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
2191 if (!send_preferred_size_changes_
|| !webview())
2194 gfx::Size size
= webview()->contentsPreferredMinimumSize();
2195 if (size
== preferred_size_
)
2198 preferred_size_
= size
;
2199 Send(new ViewHostMsg_DidContentsPreferredSizeChange(routing_id_
,
2203 void RenderViewImpl::didChangeScrollOffset(WebLocalFrame
* frame
) {
2204 StartNavStateSyncTimerIfNecessary();
2207 void RenderViewImpl::SendFindReply(int request_id
,
2210 const WebRect
& selection_rect
,
2211 bool final_status_update
) {
2212 Send(new ViewHostMsg_Find_Reply(routing_id_
,
2217 final_status_update
));
2220 blink::WebString
RenderViewImpl::acceptLanguages() {
2221 return WebString::fromUTF8(renderer_preferences_
.accept_languages
);
2224 // blink::WebPageSerializerClient implementation ------------------------------
2226 void RenderViewImpl::didSerializeDataForFrame(
2227 const WebURL
& frame_url
,
2228 const WebCString
& data
,
2229 WebPageSerializerClient::PageSerializationStatus status
) {
2230 Send(new ViewHostMsg_SendSerializedHtmlData(
2234 static_cast<int32
>(status
)));
2237 // RenderView implementation ---------------------------------------------------
2239 bool RenderViewImpl::Send(IPC::Message
* message
) {
2240 return RenderWidget::Send(message
);
2243 RenderFrameImpl
* RenderViewImpl::GetMainRenderFrame() {
2244 return main_render_frame_
;
2247 int RenderViewImpl::GetRoutingID() const {
2251 gfx::Size
RenderViewImpl::GetSize() const {
2255 WebPreferences
& RenderViewImpl::GetWebkitPreferences() {
2256 return webkit_preferences_
;
2259 void RenderViewImpl::SetWebkitPreferences(const WebPreferences
& preferences
) {
2260 OnUpdateWebPreferences(preferences
);
2263 blink::WebView
* RenderViewImpl::GetWebView() {
2267 bool RenderViewImpl::IsEditableNode(const WebNode
& node
) const {
2271 if (node
.isContentEditable())
2274 if (node
.isElementNode()) {
2275 const WebElement
& element
= node
.toConst
<WebElement
>();
2276 if (element
.isTextFormControlElement()) {
2277 if (!(element
.hasAttribute("readonly") ||
2278 element
.hasAttribute("disabled")))
2282 return base::LowerCaseEqualsASCII(
2283 base::StringPiece16(element
.getAttribute("role")), "textbox");
2289 bool RenderViewImpl::ShouldDisplayScrollbars(int width
, int height
) const {
2290 return (!send_preferred_size_changes_
||
2291 (disable_scrollbars_size_limit_
.width() <= width
||
2292 disable_scrollbars_size_limit_
.height() <= height
));
2295 int RenderViewImpl::GetEnabledBindings() const {
2296 return enabled_bindings_
;
2299 bool RenderViewImpl::GetContentStateImmediately() const {
2300 return send_content_state_immediately_
;
2303 blink::WebPageVisibilityState
RenderViewImpl::GetVisibilityState() const {
2304 return visibilityState();
2307 void RenderViewImpl::DidStartLoading() {
2308 main_render_frame_
->didStartLoading(true);
2311 void RenderViewImpl::DidStopLoading() {
2312 main_render_frame_
->didStopLoading();
2315 blink::WebElement
RenderViewImpl::GetFocusedElement() const {
2317 return WebElement();
2318 WebFrame
* focused_frame
= webview()->focusedFrame();
2319 if (focused_frame
) {
2320 WebDocument doc
= focused_frame
->document();
2322 return doc
.focusedElement();
2325 return WebElement();
2328 blink::WebPlugin
* RenderViewImpl::GetWebPluginForFind() {
2332 WebFrame
* main_frame
= webview()->mainFrame();
2333 if (main_frame
->isWebLocalFrame() &&
2334 main_frame
->document().isPluginDocument())
2335 return webview()->mainFrame()->document().to
<WebPluginDocument
>().plugin();
2337 #if defined(ENABLE_PLUGINS)
2338 if (plugin_find_handler_
)
2339 return plugin_find_handler_
->container()->plugin();
2345 void RenderViewImpl::OnFind(int request_id
,
2346 const base::string16
& search_text
,
2347 const WebFindOptions
& options
) {
2348 WebFrame
* main_frame
= webview()->mainFrame();
2349 blink::WebPlugin
* plugin
= GetWebPluginForFind();
2350 // Check if the plugin still exists in the document.
2352 if (options
.findNext
) {
2353 // Just navigate back/forward.
2354 plugin
->selectFindResult(options
.forward
);
2356 if (!plugin
->startFind(
2357 search_text
, options
.matchCase
, request_id
)) {
2358 // Send "no results".
2359 SendFindReply(request_id
, 0, 0, gfx::Rect(), true);
2365 WebFrame
* frame_after_main
= main_frame
->traverseNext(true);
2366 WebFrame
* focused_frame
= webview()->focusedFrame();
2367 WebFrame
* search_frame
= focused_frame
; // start searching focused frame.
2369 bool multi_frame
= (frame_after_main
!= main_frame
);
2371 // If we have multiple frames, we don't want to wrap the search within the
2372 // frame, so we check here if we only have main_frame in the chain.
2373 bool wrap_within_frame
= !multi_frame
;
2375 WebRect selection_rect
;
2376 bool result
= false;
2378 // If something is selected when we start searching it means we cannot just
2379 // increment the current match ordinal; we need to re-generate it.
2380 WebRange current_selection
= focused_frame
->selectionRange();
2383 result
= search_frame
->find(
2384 request_id
, search_text
, options
, wrap_within_frame
, &selection_rect
);
2387 // don't leave text selected as you move to the next frame.
2388 search_frame
->executeCommand(WebString::fromUTF8("Unselect"),
2389 GetFocusedElement());
2391 // Find the next frame, but skip the invisible ones.
2393 // What is the next frame to search? (we might be going backwards). Note
2394 // that we specify wrap=true so that search_frame never becomes NULL.
2395 search_frame
= options
.forward
?
2396 search_frame
->traverseNext(true) :
2397 search_frame
->traversePrevious(true);
2398 } while (!search_frame
->hasVisibleContent() &&
2399 search_frame
!= focused_frame
);
2401 // Make sure selection doesn't affect the search operation in new frame.
2402 search_frame
->executeCommand(WebString::fromUTF8("Unselect"),
2403 GetFocusedElement());
2405 // If we have multiple frames and we have wrapped back around to the
2406 // focused frame, we need to search it once more allowing wrap within
2407 // the frame, otherwise it will report 'no match' if the focused frame has
2408 // reported matches, but no frames after the focused_frame contain a
2409 // match for the search word(s).
2410 if (multi_frame
&& search_frame
== focused_frame
) {
2411 result
= search_frame
->find(
2412 request_id
, search_text
, options
, true, // Force wrapping.
2417 webview()->setFocusedFrame(search_frame
);
2418 } while (!result
&& search_frame
!= focused_frame
);
2420 if (options
.findNext
&& current_selection
.isNull()) {
2421 // Force the main_frame to report the actual count.
2422 main_frame
->increaseMatchCount(0, request_id
);
2424 // If nothing is found, set result to "0 of 0", otherwise, set it to
2425 // "-1 of 1" to indicate that we found at least one item, but we don't know
2426 // yet what is active.
2427 int ordinal
= result
? -1 : 0; // -1 here means, we might know more later.
2428 int match_count
= result
? 1 : 0; // 1 here means possibly more coming.
2430 // If we find no matches then this will be our last status update.
2431 // Otherwise the scoping effort will send more results.
2432 bool final_status_update
= !result
;
2434 SendFindReply(request_id
, match_count
, ordinal
, selection_rect
,
2435 final_status_update
);
2437 // Scoping effort begins, starting with the mainframe.
2438 search_frame
= main_frame
;
2440 main_frame
->resetMatchCount();
2443 // Cancel all old scoping requests before starting a new one.
2444 search_frame
->cancelPendingScopingEffort();
2446 // We don't start another scoping effort unless at least one match has
2449 // Start new scoping request. If the scoping function determines that it
2450 // needs to scope, it will defer until later.
2451 search_frame
->scopeStringMatches(request_id
,
2454 true); // reset the tickmarks
2457 // Iterate to the next frame. The frame will not necessarily scope, for
2458 // example if it is not visible.
2459 search_frame
= search_frame
->traverseNext(true);
2460 } while (search_frame
!= main_frame
);
2464 void RenderViewImpl::OnStopFinding(StopFindAction action
) {
2465 WebView
* view
= webview();
2469 blink::WebPlugin
* plugin
= GetWebPluginForFind();
2475 bool clear_selection
= action
== STOP_FIND_ACTION_CLEAR_SELECTION
;
2476 if (clear_selection
) {
2477 view
->focusedFrame()->executeCommand(WebString::fromUTF8("Unselect"),
2478 GetFocusedElement());
2481 WebFrame
* frame
= view
->mainFrame();
2483 frame
->stopFinding(clear_selection
);
2484 frame
= frame
->traverseNext(false);
2487 if (action
== STOP_FIND_ACTION_ACTIVATE_SELECTION
) {
2488 WebFrame
* focused_frame
= view
->focusedFrame();
2489 if (focused_frame
) {
2490 WebDocument doc
= focused_frame
->document();
2491 if (!doc
.isNull()) {
2492 WebElement element
= doc
.focusedElement();
2493 if (!element
.isNull())
2494 element
.simulateClick();
2500 #if defined(OS_ANDROID)
2501 void RenderViewImpl::OnActivateNearestFindResult(int request_id
,
2506 WebFrame
* main_frame
= webview()->mainFrame();
2507 WebRect selection_rect
;
2508 int ordinal
= main_frame
->selectNearestFindMatch(WebFloatPoint(x
, y
),
2510 if (ordinal
== -1) {
2511 // Something went wrong, so send a no-op reply (force the main_frame to
2512 // report the current match count) in case the host is waiting for a
2513 // response due to rate-limiting).
2514 main_frame
->increaseMatchCount(0, request_id
);
2518 SendFindReply(request_id
,
2519 -1 /* number_of_matches */,
2522 true /* final_update */);
2525 void RenderViewImpl::OnFindMatchRects(int current_version
) {
2529 WebFrame
* main_frame
= webview()->mainFrame();
2530 std::vector
<gfx::RectF
> match_rects
;
2532 int rects_version
= main_frame
->findMatchMarkersVersion();
2533 if (current_version
!= rects_version
) {
2534 WebVector
<WebFloatRect
> web_match_rects
;
2535 main_frame
->findMatchRects(web_match_rects
);
2536 match_rects
.reserve(web_match_rects
.size());
2537 for (size_t i
= 0; i
< web_match_rects
.size(); ++i
)
2538 match_rects
.push_back(gfx::RectF(web_match_rects
[i
]));
2541 gfx::RectF active_rect
= main_frame
->activeFindMatchRect();
2542 Send(new ViewHostMsg_FindMatchRects_Reply(routing_id_
,
2549 void RenderViewImpl::OnResetPageScale() {
2552 webview()->setPageScaleFactor(1);
2555 void RenderViewImpl::OnZoom(PageZoom zoom
) {
2556 if (!webview()) // Not sure if this can happen, but no harm in being safe.
2559 webview()->hidePopups();
2561 double old_zoom_level
= webview()->zoomLevel();
2563 if (zoom
== PAGE_ZOOM_RESET
) {
2565 } else if (static_cast<int>(old_zoom_level
) == old_zoom_level
) {
2566 // Previous zoom level is a whole number, so just increment/decrement.
2567 zoom_level
= old_zoom_level
+ zoom
;
2569 // Either the user hit the zoom factor limit and thus the zoom level is now
2570 // not a whole number, or a plugin changed it to a custom value. We want
2571 // to go to the next whole number so that the user can always get back to
2572 // 100% with the keyboard/menu.
2573 if ((old_zoom_level
> 1 && zoom
> 0) ||
2574 (old_zoom_level
< 1 && zoom
< 0)) {
2575 zoom_level
= static_cast<int>(old_zoom_level
+ zoom
);
2577 // We're going towards 100%, so first go to the next whole number.
2578 zoom_level
= static_cast<int>(old_zoom_level
);
2581 webview()->setZoomLevel(zoom_level
);
2585 void RenderViewImpl::OnSetZoomLevelForLoadingURL(const GURL
& url
,
2586 double zoom_level
) {
2587 #if !defined(OS_ANDROID)
2588 // On Android, page zoom isn't used, and in case of WebView, text zoom is used
2589 // for legacy WebView text scaling emulation. Thus, the code that resets
2590 // the zoom level from this map will be effectively resetting text zoom level.
2591 host_zoom_levels_
[url
] = zoom_level
;
2595 void RenderViewImpl::OnSetZoomLevelForView(bool uses_temporary_zoom_level
,
2597 uses_temporary_zoom_level_
= uses_temporary_zoom_level
;
2599 webview()->hidePopups();
2600 webview()->setZoomLevel(level
);
2603 void RenderViewImpl::OnSetPageEncoding(const std::string
& encoding_name
) {
2604 webview()->setPageEncoding(WebString::fromUTF8(encoding_name
));
2607 void RenderViewImpl::OnResetPageEncodingToDefault() {
2608 WebString no_encoding
;
2609 webview()->setPageEncoding(no_encoding
);
2612 void RenderViewImpl::OnAllowBindings(int enabled_bindings_flags
) {
2613 if ((enabled_bindings_flags
& BINDINGS_POLICY_WEB_UI
) &&
2614 !(enabled_bindings_
& BINDINGS_POLICY_WEB_UI
)) {
2615 // WebUIExtensionData deletes itself when we're destroyed.
2616 new WebUIExtensionData(this);
2617 // WebUIMojo deletes itself when we're destroyed.
2618 new WebUIMojo(this);
2621 enabled_bindings_
|= enabled_bindings_flags
;
2623 // Keep track of the total bindings accumulated in this process.
2624 RenderProcess::current()->AddBindings(enabled_bindings_flags
);
2627 void RenderViewImpl::OnDragTargetDragEnter(const DropData
& drop_data
,
2628 const gfx::Point
& client_point
,
2629 const gfx::Point
& screen_point
,
2630 WebDragOperationsMask ops
,
2631 int key_modifiers
) {
2632 WebDragOperation operation
= webview()->dragTargetDragEnter(
2633 DropDataToWebDragData(drop_data
),
2639 Send(new DragHostMsg_UpdateDragCursor(routing_id_
, operation
));
2642 void RenderViewImpl::OnDragTargetDragOver(const gfx::Point
& client_point
,
2643 const gfx::Point
& screen_point
,
2644 WebDragOperationsMask ops
,
2645 int key_modifiers
) {
2646 WebDragOperation operation
= webview()->dragTargetDragOver(
2652 Send(new DragHostMsg_UpdateDragCursor(routing_id_
, operation
));
2655 void RenderViewImpl::OnDragTargetDragLeave() {
2656 webview()->dragTargetDragLeave();
2659 void RenderViewImpl::OnDragTargetDrop(const gfx::Point
& client_point
,
2660 const gfx::Point
& screen_point
,
2661 int key_modifiers
) {
2662 webview()->dragTargetDrop(client_point
, screen_point
, key_modifiers
);
2665 void RenderViewImpl::OnDragSourceEnded(const gfx::Point
& client_point
,
2666 const gfx::Point
& screen_point
,
2667 WebDragOperation op
) {
2668 webview()->dragSourceEndedAt(client_point
, screen_point
, op
);
2671 void RenderViewImpl::OnDragSourceSystemDragEnded() {
2672 webview()->dragSourceSystemDragEnded();
2675 void RenderViewImpl::OnUpdateWebPreferences(const WebPreferences
& prefs
) {
2676 webkit_preferences_
= prefs
;
2677 ApplyWebPreferencesInternal(webkit_preferences_
, webview(), compositor_deps_
);
2680 void RenderViewImpl::OnEnumerateDirectoryResponse(
2682 const std::vector
<base::FilePath
>& paths
) {
2683 if (!enumeration_completions_
[id
])
2686 WebVector
<WebString
> ws_file_names(paths
.size());
2687 for (size_t i
= 0; i
< paths
.size(); ++i
)
2688 ws_file_names
[i
] = paths
[i
].AsUTF16Unsafe();
2690 enumeration_completions_
[id
]->didChooseFile(ws_file_names
);
2691 enumeration_completions_
.erase(id
);
2694 void RenderViewImpl::OnFileChooserResponse(
2695 const std::vector
<content::FileChooserFileInfo
>& files
) {
2696 // This could happen if we navigated to a different page before the user
2697 // closed the chooser.
2698 if (file_chooser_completions_
.empty())
2701 // Convert Chrome's SelectedFileInfo list to WebKit's.
2702 WebVector
<WebFileChooserCompletion::SelectedFileInfo
> selected_files(
2704 for (size_t i
= 0; i
< files
.size(); ++i
) {
2705 WebFileChooserCompletion::SelectedFileInfo selected_file
;
2706 selected_file
.path
= files
[i
].file_path
.AsUTF16Unsafe();
2707 selected_file
.displayName
=
2708 base::FilePath(files
[i
].display_name
).AsUTF16Unsafe();
2709 if (files
[i
].file_system_url
.is_valid()) {
2710 selected_file
.fileSystemURL
= files
[i
].file_system_url
;
2711 selected_file
.length
= files
[i
].length
;
2712 selected_file
.modificationTime
= files
[i
].modification_time
.ToDoubleT();
2713 selected_file
.isDirectory
= files
[i
].is_directory
;
2715 selected_files
[i
] = selected_file
;
2718 if (file_chooser_completions_
.front()->completion
)
2719 file_chooser_completions_
.front()->completion
->didChooseFile(
2721 file_chooser_completions_
.pop_front();
2723 // If there are more pending file chooser requests, schedule one now.
2724 if (!file_chooser_completions_
.empty()) {
2725 Send(new ViewHostMsg_RunFileChooser(routing_id_
,
2726 file_chooser_completions_
.front()->params
));
2730 void RenderViewImpl::OnEnableAutoResize(const gfx::Size
& min_size
,
2731 const gfx::Size
& max_size
) {
2732 DCHECK(disable_scrollbars_size_limit_
.IsEmpty());
2735 auto_resize_mode_
= true;
2736 webview()->enableAutoResizeMode(min_size
, max_size
);
2739 void RenderViewImpl::OnDisableAutoResize(const gfx::Size
& new_size
) {
2740 DCHECK(disable_scrollbars_size_limit_
.IsEmpty());
2743 auto_resize_mode_
= false;
2744 webview()->disableAutoResizeMode();
2746 if (!new_size
.IsEmpty()) {
2748 physical_backing_size_
,
2749 top_controls_shrink_blink_size_
,
2750 top_controls_height_
,
2751 visible_viewport_size_
,
2753 is_fullscreen_granted_
,
2759 void RenderViewImpl::OnEnablePreferredSizeChangedMode() {
2760 if (send_preferred_size_changes_
)
2762 send_preferred_size_changes_
= true;
2764 // Start off with an initial preferred size notification (in case
2765 // |didUpdateLayout| was already called).
2769 void RenderViewImpl::OnDisableScrollbarsForSmallWindows(
2770 const gfx::Size
& disable_scrollbar_size_limit
) {
2771 disable_scrollbars_size_limit_
= disable_scrollbar_size_limit
;
2774 void RenderViewImpl::OnSetRendererPrefs(
2775 const RendererPreferences
& renderer_prefs
) {
2776 double old_zoom_level
= renderer_preferences_
.default_zoom_level
;
2777 std::string old_accept_languages
= renderer_preferences_
.accept_languages
;
2779 renderer_preferences_
= renderer_prefs
;
2781 UpdateFontRenderingFromRendererPrefs();
2784 #if defined(USE_DEFAULT_RENDER_THEME)
2785 if (renderer_prefs
.use_custom_colors
) {
2786 WebColorName name
= blink::WebColorWebkitFocusRingColor
;
2787 blink::setNamedColors(&name
, &renderer_prefs
.focus_ring_color
, 1);
2788 blink::setCaretBlinkInterval(renderer_prefs
.caret_blink_interval
);
2791 webview()->setSelectionColors(
2792 renderer_prefs
.active_selection_bg_color
,
2793 renderer_prefs
.active_selection_fg_color
,
2794 renderer_prefs
.inactive_selection_bg_color
,
2795 renderer_prefs
.inactive_selection_fg_color
);
2796 webview()->themeChanged();
2799 #endif // defined(USE_DEFAULT_RENDER_THEME)
2801 // If the zoom level for this page matches the old zoom default, and this
2802 // is not a plugin, update the zoom level to match the new default.
2803 if (webview() && webview()->mainFrame()->isWebLocalFrame() &&
2804 !webview()->mainFrame()->document().isPluginDocument() &&
2805 !ZoomValuesEqual(old_zoom_level
,
2806 renderer_preferences_
.default_zoom_level
) &&
2807 ZoomValuesEqual(webview()->zoomLevel(), old_zoom_level
)) {
2808 webview()->setZoomLevel(renderer_preferences_
.default_zoom_level
);
2813 old_accept_languages
!= renderer_preferences_
.accept_languages
) {
2814 webview()->acceptLanguagesChanged();
2818 void RenderViewImpl::OnMediaPlayerActionAt(const gfx::Point
& location
,
2819 const WebMediaPlayerAction
& action
) {
2821 webview()->performMediaPlayerAction(action
, location
);
2824 void RenderViewImpl::OnOrientationChange() {
2825 if (webview() && webview()->mainFrame()->isWebLocalFrame())
2826 webview()->mainFrame()->toWebLocalFrame()->sendOrientationChangeEvent();
2829 void RenderViewImpl::OnPluginActionAt(const gfx::Point
& location
,
2830 const WebPluginAction
& action
) {
2832 webview()->performPluginAction(action
, location
);
2835 void RenderViewImpl::OnGetAllSavableResourceLinksForCurrentPage(
2836 const GURL
& page_url
) {
2837 // Prepare list to storage all savable resource links.
2838 std::vector
<GURL
> resources_list
;
2839 std::vector
<GURL
> referrer_urls_list
;
2840 std::vector
<blink::WebReferrerPolicy
> referrer_policies_list
;
2841 std::vector
<GURL
> frames_list
;
2842 SavableResourcesResult
result(&resources_list
,
2843 &referrer_urls_list
,
2844 &referrer_policies_list
,
2847 // webkit/ doesn't know about Referrer.
2848 if (!GetAllSavableResourceLinksForCurrentPage(
2852 const_cast<const char**>(GetSavableSchemes()))) {
2853 // If something is wrong when collecting all savable resource links,
2854 // send empty list to embedder(browser) to tell it failed.
2855 referrer_urls_list
.clear();
2856 referrer_policies_list
.clear();
2857 resources_list
.clear();
2858 frames_list
.clear();
2861 std::vector
<Referrer
> referrers_list
;
2862 CHECK_EQ(referrer_urls_list
.size(), referrer_policies_list
.size());
2863 for (unsigned i
= 0; i
< referrer_urls_list
.size(); ++i
) {
2864 referrers_list
.push_back(
2865 Referrer(referrer_urls_list
[i
], referrer_policies_list
[i
]));
2868 // Send result of all savable resource links to embedder.
2869 Send(new ViewHostMsg_SendCurrentPageAllSavableResourceLinks(routing_id(),
2875 void RenderViewImpl::OnGetSerializedHtmlDataForCurrentPageWithLocalLinks(
2876 const std::vector
<GURL
>& links
,
2877 const std::vector
<base::FilePath
>& local_paths
,
2878 const base::FilePath
& local_directory_name
) {
2880 // Convert std::vector of GURLs to WebVector<WebURL>
2881 WebVector
<WebURL
> weburl_links(links
);
2883 // Convert std::vector of base::FilePath to WebVector<WebString>
2884 WebVector
<WebString
> webstring_paths(local_paths
.size());
2885 for (size_t i
= 0; i
< local_paths
.size(); i
++)
2886 webstring_paths
[i
] = local_paths
[i
].AsUTF16Unsafe();
2888 WebPageSerializer::serialize(webview()->mainFrame()->toWebLocalFrame(),
2893 local_directory_name
.AsUTF16Unsafe());
2896 void RenderViewImpl::OnSuppressDialogsUntilSwapOut() {
2897 // Don't show any more dialogs until we finish OnSwapOut.
2898 suppress_dialogs_until_swap_out_
= true;
2901 void RenderViewImpl::OnClosePage() {
2902 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, ClosePage());
2903 // TODO(creis): We'd rather use webview()->Close() here, but that currently
2904 // sets the WebView's delegate_ to NULL, preventing any JavaScript dialogs
2905 // in the onunload handler from appearing. For now, we're bypassing that and
2906 // calling the FrameLoader's CloseURL method directly. This should be
2907 // revisited to avoid having two ways to close a page. Having a single way
2908 // to close that can run onunload is also useful for fixing
2909 // http://b/issue?id=753080.
2910 webview()->mainFrame()->dispatchUnloadEvent();
2912 Send(new ViewHostMsg_ClosePage_ACK(routing_id_
));
2915 void RenderViewImpl::OnClose() {
2917 RenderThread::Get()->Send(new ViewHostMsg_Close_ACK(routing_id_
));
2918 RenderWidget::OnClose();
2921 void RenderViewImpl::OnThemeChanged() {
2922 #if defined(USE_AURA)
2923 // Aura doesn't care if we switch themes.
2924 #elif defined(OS_WIN)
2925 ui::NativeThemeWin::instance()->CloseHandles();
2927 webview()->themeChanged();
2928 #else // defined(OS_WIN)
2929 // TODO(port): we don't support theming on non-Windows platforms yet
2934 void RenderViewImpl::OnMoveOrResizeStarted() {
2936 webview()->hidePopups();
2939 void RenderViewImpl::OnResize(const ViewMsg_Resize_Params
& params
) {
2940 TRACE_EVENT0("renderer", "RenderViewImpl::OnResize");
2942 webview()->hidePopups();
2943 if (send_preferred_size_changes_
) {
2944 webview()->mainFrame()->setCanHaveScrollbars(
2945 ShouldDisplayScrollbars(params
.new_size
.width(),
2946 params
.new_size
.height()));
2948 if (display_mode_
!= params
.display_mode
) {
2949 display_mode_
= params
.display_mode
;
2950 webview()->setDisplayMode(display_mode_
);
2954 gfx::Size old_visible_viewport_size
= visible_viewport_size_
;
2956 RenderWidget::OnResize(params
);
2958 if (old_visible_viewport_size
!= visible_viewport_size_
)
2959 has_scrolled_focused_editable_node_into_rect_
= false;
2962 void RenderViewImpl::DidInitiatePaint() {
2963 #if defined(ENABLE_PLUGINS)
2964 // Notify all instances that we painted. The same caveats apply as for
2965 // ViewFlushedPaint regarding instances closing themselves, so we take
2966 // similar precautions.
2967 PepperPluginSet plugins
= active_pepper_instances_
;
2968 for (PepperPluginSet::iterator i
= plugins
.begin(); i
!= plugins
.end(); ++i
) {
2969 if (active_pepper_instances_
.find(*i
) != active_pepper_instances_
.end())
2970 (*i
)->ViewInitiatedPaint();
2975 void RenderViewImpl::DidFlushPaint() {
2976 // If the RenderWidget is closing down then early-exit, otherwise we'll crash.
2977 // See crbug.com/112921.
2981 WebFrame
* main_frame
= webview()->mainFrame();
2982 for (WebFrame
* frame
= main_frame
; frame
;
2983 frame
= frame
->traverseNext(false)) {
2984 // TODO(nasko): This is a hack for the case in which the top-level
2985 // frame is being rendered in another process. It will not
2986 // behave correctly for out of process iframes.
2987 if (frame
->isWebLocalFrame()) {
2993 // If we have a provisional frame we are between the start and commit stages
2994 // of loading and we don't want to save stats.
2995 if (!main_frame
->provisionalDataSource()) {
2996 WebDataSource
* ds
= main_frame
->dataSource();
3000 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3002 // TODO(jar): The following code should all be inside a method, probably in
3004 Time now
= Time::Now();
3005 if (document_state
->first_paint_time().is_null()) {
3006 document_state
->set_first_paint_time(now
);
3008 if (document_state
->first_paint_after_load_time().is_null() &&
3009 !document_state
->finish_load_time().is_null()) {
3010 document_state
->set_first_paint_after_load_time(now
);
3015 gfx::Vector2d
RenderViewImpl::GetScrollOffset() {
3016 WebFrame
* main_frame
= webview()->mainFrame();
3017 for (WebFrame
* frame
= main_frame
; frame
;
3018 frame
= frame
->traverseNext(false)) {
3019 // TODO(nasko): This is a hack for the case in which the top-level
3020 // frame is being rendered in another process. It will not
3021 // behave correctly for out of process iframes.
3022 if (frame
->isWebLocalFrame()) {
3028 WebSize scroll_offset
= main_frame
->scrollOffset();
3029 return gfx::Vector2d(scroll_offset
.width
, scroll_offset
.height
);
3032 void RenderViewImpl::OnClearFocusedElement() {
3034 webview()->clearFocusedElement();
3037 void RenderViewImpl::OnSetBackgroundOpaque(bool opaque
) {
3039 webview()->setIsTransparent(!opaque
);
3041 compositor_
->setHasTransparentBackground(!opaque
);
3044 void RenderViewImpl::OnSetActive(bool active
) {
3046 webview()->setIsActive(active
);
3048 #if defined(ENABLE_PLUGINS) && defined(OS_MACOSX)
3049 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
3050 for (plugin_it
= plugin_delegates_
.begin();
3051 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
3052 (*plugin_it
)->SetWindowFocus(active
);
3057 #if defined(OS_MACOSX)
3058 void RenderViewImpl::OnSetWindowVisibility(bool visible
) {
3059 #if defined(ENABLE_PLUGINS)
3060 // Inform plugins that their container has changed visibility.
3061 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
3062 for (plugin_it
= plugin_delegates_
.begin();
3063 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
3064 (*plugin_it
)->SetContainerVisibility(visible
);
3069 void RenderViewImpl::OnWindowFrameChanged(const gfx::Rect
& window_frame
,
3070 const gfx::Rect
& view_frame
) {
3071 #if defined(ENABLE_PLUGINS)
3072 // Inform plugins that their window's frame has changed.
3073 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
3074 for (plugin_it
= plugin_delegates_
.begin();
3075 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
3076 (*plugin_it
)->WindowFrameChanged(window_frame
, view_frame
);
3081 void RenderViewImpl::OnPluginImeCompositionCompleted(const base::string16
& text
,
3083 // WebPluginDelegateProxy is responsible for figuring out if this event
3084 // applies to it or not, so inform all the delegates.
3085 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
3086 for (plugin_it
= plugin_delegates_
.begin();
3087 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
3088 (*plugin_it
)->ImeCompositionCompleted(text
, plugin_id
);
3093 void RenderViewImpl::Close() {
3094 // We need to grab a pointer to the doomed WebView before we destroy it.
3095 WebView
* doomed
= webview();
3096 RenderWidget::Close();
3097 g_view_map
.Get().erase(doomed
);
3098 g_routing_id_view_map
.Get().erase(routing_id_
);
3099 RenderThread::Get()->Send(new ViewHostMsg_Close_ACK(routing_id_
));
3102 void RenderViewImpl::DidHandleKeyEvent() {
3103 ClearEditCommands();
3106 bool RenderViewImpl::WillHandleMouseEvent(const blink::WebMouseEvent
& event
) {
3107 possible_drag_event_info_
.event_source
=
3108 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE
;
3109 possible_drag_event_info_
.event_location
=
3110 gfx::Point(event
.globalX
, event
.globalY
);
3112 #if defined(ENABLE_PLUGINS)
3113 // This method is called for every mouse event that the render view receives.
3114 // And then the mouse event is forwarded to WebKit, which dispatches it to the
3115 // event target. Potentially a Pepper plugin will receive the event.
3116 // In order to tell whether a plugin gets the last mouse event and which it
3117 // is, we set |pepper_last_mouse_event_target_| to NULL here. If a plugin gets
3118 // the event, it will notify us via DidReceiveMouseEvent() and set itself as
3119 // |pepper_last_mouse_event_target_|.
3120 pepper_last_mouse_event_target_
= NULL
;
3123 // If the mouse is locked, only the current owner of the mouse lock can
3124 // process mouse events.
3125 return mouse_lock_dispatcher_
->WillHandleMouseEvent(event
);
3128 bool RenderViewImpl::WillHandleGestureEvent(
3129 const blink::WebGestureEvent
& event
) {
3130 possible_drag_event_info_
.event_source
=
3131 ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH
;
3132 possible_drag_event_info_
.event_location
=
3133 gfx::Point(event
.globalX
, event
.globalY
);
3137 bool RenderViewImpl::HasTouchEventHandlersAt(const gfx::Point
& point
) const {
3140 return webview()->hasTouchEventHandlersAt(point
);
3143 void RenderViewImpl::OnWasHidden() {
3144 RenderWidget::OnWasHidden();
3146 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3147 RenderThreadImpl::current()->video_capture_impl_manager()->
3148 SuspendDevices(true);
3149 if (speech_recognition_dispatcher_
)
3150 speech_recognition_dispatcher_
->AbortAllRecognitions();
3154 webview()->setVisibilityState(visibilityState(), false);
3156 #if defined(ENABLE_PLUGINS)
3157 for (PepperPluginSet::iterator i
= active_pepper_instances_
.begin();
3158 i
!= active_pepper_instances_
.end(); ++i
)
3159 (*i
)->PageVisibilityChanged(false);
3161 #if defined(OS_MACOSX)
3162 // Inform NPAPI plugins that their container is no longer visible.
3163 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
3164 for (plugin_it
= plugin_delegates_
.begin();
3165 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
3166 (*plugin_it
)->SetContainerVisibility(false);
3169 #endif // ENABLE_PLUGINS
3172 void RenderViewImpl::OnWasShown(bool needs_repainting
,
3173 const ui::LatencyInfo
& latency_info
) {
3174 RenderWidget::OnWasShown(needs_repainting
, latency_info
);
3176 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3177 RenderThreadImpl::current()->video_capture_impl_manager()->
3178 SuspendDevices(false);
3182 webview()->setVisibilityState(visibilityState(), false);
3184 #if defined(ENABLE_PLUGINS)
3185 for (PepperPluginSet::iterator i
= active_pepper_instances_
.begin();
3186 i
!= active_pepper_instances_
.end(); ++i
)
3187 (*i
)->PageVisibilityChanged(true);
3189 #if defined(OS_MACOSX)
3190 // Inform NPAPI plugins that their container is now visible.
3191 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
3192 for (plugin_it
= plugin_delegates_
.begin();
3193 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
3194 (*plugin_it
)->SetContainerVisibility(true);
3197 #endif // ENABLE_PLUGINS
3200 GURL
RenderViewImpl::GetURLForGraphicsContext3D() {
3202 if (webview()->mainFrame()->isWebLocalFrame())
3203 return GURL(webview()->mainFrame()->document().url());
3205 return GURL("chrome://gpu/RenderViewImpl::CreateGraphicsContext3D");
3208 void RenderViewImpl::OnSetFocus(bool enable
) {
3209 RenderWidget::OnSetFocus(enable
);
3211 #if defined(ENABLE_PLUGINS)
3212 if (webview() && webview()->isActive()) {
3213 // Notify all NPAPI plugins.
3214 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
3215 for (plugin_it
= plugin_delegates_
.begin();
3216 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
3217 #if defined(OS_MACOSX)
3218 // RenderWidget's call to setFocus can cause the underlying webview's
3219 // activation state to change just like a call to setIsActive.
3221 (*plugin_it
)->SetWindowFocus(true);
3223 (*plugin_it
)->SetContentAreaFocus(enable
);
3226 // Notify all Pepper plugins.
3227 for (PepperPluginSet::iterator i
= active_pepper_instances_
.begin();
3228 i
!= active_pepper_instances_
.end(); ++i
)
3229 (*i
)->SetContentAreaFocus(enable
);
3231 // Notify all BrowserPlugins of the RenderView's focus state.
3232 if (BrowserPluginManager::Get())
3233 BrowserPluginManager::Get()->UpdateFocusState();
3236 void RenderViewImpl::OnImeSetComposition(
3237 const base::string16
& text
,
3238 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
3239 int selection_start
,
3240 int selection_end
) {
3241 #if defined(ENABLE_PLUGINS)
3242 if (focused_pepper_plugin_
) {
3243 focused_pepper_plugin_
->render_frame()->OnImeSetComposition(
3244 text
, underlines
, selection_start
, selection_end
);
3249 // When a plugin has focus, we create platform-specific IME data used by
3250 // our IME emulator and send it directly to the focused plugin, i.e. we
3251 // bypass WebKit. (WebPluginDelegate dispatches this IME data only when its
3252 // instance ID is the same one as the specified ID.)
3253 if (focused_plugin_id_
>= 0) {
3254 std::vector
<int> clauses
;
3255 std::vector
<int> target
;
3256 for (size_t i
= 0; i
< underlines
.size(); ++i
) {
3257 clauses
.push_back(underlines
[i
].startOffset
);
3258 clauses
.push_back(underlines
[i
].endOffset
);
3259 if (underlines
[i
].thick
) {
3261 target
.push_back(underlines
[i
].startOffset
);
3262 target
.push_back(underlines
[i
].endOffset
);
3265 std::set
<WebPluginDelegateProxy
*>::iterator it
;
3266 for (it
= plugin_delegates_
.begin(); it
!= plugin_delegates_
.end(); ++it
) {
3267 (*it
)->ImeCompositionUpdated(text
, clauses
, target
, selection_end
,
3268 focused_plugin_id_
);
3273 #endif // ENABLE_PLUGINS
3274 RenderWidget::OnImeSetComposition(text
,
3280 void RenderViewImpl::OnImeConfirmComposition(
3281 const base::string16
& text
,
3282 const gfx::Range
& replacement_range
,
3283 bool keep_selection
) {
3284 #if defined(ENABLE_PLUGINS)
3285 if (focused_pepper_plugin_
) {
3286 focused_pepper_plugin_
->render_frame()->OnImeConfirmComposition(
3287 text
, replacement_range
, keep_selection
);
3291 // Same as OnImeSetComposition(), we send the text from IMEs directly to
3292 // plugins. When we send IME text directly to plugins, we should not send
3293 // it to WebKit to prevent WebKit from controlling IMEs.
3294 // TODO(thakis): Honor |replacement_range| for plugins?
3295 if (focused_plugin_id_
>= 0) {
3296 std::set
<WebPluginDelegateProxy
*>::iterator it
;
3297 for (it
= plugin_delegates_
.begin();
3298 it
!= plugin_delegates_
.end(); ++it
) {
3299 (*it
)->ImeCompositionCompleted(text
, focused_plugin_id_
);
3304 #endif // ENABLE_PLUGINS
3305 if (replacement_range
.IsValid() && webview()) {
3306 // Select the text in |replacement_range|, it will then be replaced by
3307 // text added by the call to RenderWidget::OnImeConfirmComposition().
3308 if (WebLocalFrame
* frame
= webview()->focusedFrame()->toWebLocalFrame()) {
3309 WebRange webrange
= WebRange::fromDocumentRange(
3310 frame
, replacement_range
.start(), replacement_range
.length());
3311 if (!webrange
.isNull())
3312 frame
->selectRange(webrange
);
3315 RenderWidget::OnImeConfirmComposition(text
,
3320 void RenderViewImpl::SetDeviceScaleFactor(float device_scale_factor
) {
3321 RenderWidget::SetDeviceScaleFactor(device_scale_factor
);
3323 webview()->setDeviceScaleFactor(device_scale_factor
);
3324 webview()->settings()->setPreferCompositingToLCDTextEnabled(
3325 PreferCompositingToLCDText(compositor_deps_
, device_scale_factor_
));
3327 if (auto_resize_mode_
)
3328 AutoResizeCompositor();
3331 bool RenderViewImpl::SetDeviceColorProfile(
3332 const std::vector
<char>& profile
) {
3333 bool changed
= RenderWidget::SetDeviceColorProfile(profile
);
3334 if (changed
&& webview()) {
3335 WebVector
<char> colorProfile
= profile
;
3336 webview()->setDeviceColorProfile(colorProfile
);
3341 void RenderViewImpl::ResetDeviceColorProfileForTesting() {
3342 RenderWidget::ResetDeviceColorProfileForTesting();
3344 webview()->resetDeviceColorProfile();
3347 ui::TextInputType
RenderViewImpl::GetTextInputType() {
3348 #if defined(ENABLE_PLUGINS)
3349 if (focused_pepper_plugin_
)
3350 return focused_pepper_plugin_
->text_input_type();
3352 return RenderWidget::GetTextInputType();
3355 void RenderViewImpl::GetSelectionBounds(gfx::Rect
* start
, gfx::Rect
* end
) {
3356 #if defined(ENABLE_PLUGINS)
3357 if (focused_pepper_plugin_
) {
3358 // TODO(kinaba) http://crbug.com/101101
3359 // Current Pepper IME API does not handle selection bounds. So we simply
3360 // use the caret position as an empty range for now. It will be updated
3361 // after Pepper API equips features related to surrounding text retrieval.
3362 gfx::Rect caret
= focused_pepper_plugin_
->GetCaretBounds();
3368 RenderWidget::GetSelectionBounds(start
, end
);
3371 void RenderViewImpl::FocusChangeComplete() {
3372 RenderWidget::FocusChangeComplete();
3373 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, FocusChangeComplete());
3376 void RenderViewImpl::GetCompositionCharacterBounds(
3377 std::vector
<gfx::Rect
>* bounds
) {
3381 #if defined(ENABLE_PLUGINS)
3382 if (focused_pepper_plugin_
) {
3389 size_t start_offset
= 0;
3390 size_t character_count
= 0;
3391 if (!webview()->compositionRange(&start_offset
, &character_count
))
3393 if (character_count
== 0)
3396 blink::WebFrame
* frame
= webview()->focusedFrame();
3400 bounds
->reserve(character_count
);
3401 blink::WebRect webrect
;
3402 for (size_t i
= 0; i
< character_count
; ++i
) {
3403 if (!frame
->firstRectForCharacterRange(start_offset
+ i
, 1, webrect
)) {
3404 DLOG(ERROR
) << "Could not retrieve character rectangle at " << i
;
3408 bounds
->push_back(webrect
);
3412 void RenderViewImpl::GetCompositionRange(gfx::Range
* range
) {
3413 #if defined(ENABLE_PLUGINS)
3414 if (focused_pepper_plugin_
) {
3418 RenderWidget::GetCompositionRange(range
);
3421 bool RenderViewImpl::CanComposeInline() {
3422 #if defined(ENABLE_PLUGINS)
3423 if (focused_pepper_plugin_
)
3424 return focused_pepper_plugin_
->IsPluginAcceptingCompositionEvents();
3429 void RenderViewImpl::DidCompletePageScaleAnimation() {
3430 FocusChangeComplete();
3433 void RenderViewImpl::SetScreenMetricsEmulationParameters(
3435 const blink::WebDeviceEmulationParams
& params
) {
3436 if (webview() && compositor()) {
3438 webview()->enableDeviceEmulation(params
);
3440 webview()->disableDeviceEmulation();
3444 bool RenderViewImpl::ScheduleFileChooser(
3445 const FileChooserParams
& params
,
3446 WebFileChooserCompletion
* completion
) {
3447 static const size_t kMaximumPendingFileChooseRequests
= 4;
3448 if (file_chooser_completions_
.size() > kMaximumPendingFileChooseRequests
) {
3449 // This sanity check prevents too many file choose requests from getting
3450 // queued which could DoS the user. Getting these is most likely a
3451 // programming error (there are many ways to DoS the user so it's not
3452 // considered a "real" security check), either in JS requesting many file
3453 // choosers to pop up, or in a plugin.
3455 // TODO(brettw) we might possibly want to require a user gesture to open
3456 // a file picker, which will address this issue in a better way.
3460 file_chooser_completions_
.push_back(linked_ptr
<PendingFileChooser
>(
3461 new PendingFileChooser(params
, completion
)));
3462 if (file_chooser_completions_
.size() == 1) {
3463 // Actually show the browse dialog when this is the first request.
3464 Send(new ViewHostMsg_RunFileChooser(routing_id_
, params
));
3469 blink::WebSpeechRecognizer
* RenderViewImpl::speechRecognizer() {
3470 if (!speech_recognition_dispatcher_
)
3471 speech_recognition_dispatcher_
= new SpeechRecognitionDispatcher(this);
3472 return speech_recognition_dispatcher_
;
3475 void RenderViewImpl::zoomLimitsChanged(double minimum_level
,
3476 double maximum_level
) {
3477 // Round the double to avoid returning incorrect minimum/maximum zoom
3479 int minimum_percent
= round(
3480 ZoomLevelToZoomFactor(minimum_level
) * 100);
3481 int maximum_percent
= round(
3482 ZoomLevelToZoomFactor(maximum_level
) * 100);
3484 Send(new ViewHostMsg_UpdateZoomLimits(
3485 routing_id_
, minimum_percent
, maximum_percent
));
3488 void RenderViewImpl::zoomLevelChanged() {
3489 double zoom_level
= webview()->zoomLevel();
3491 // Do not send empty URLs to the browser when we are just setting the default
3492 // zoom level (from RendererPreferences) before the first navigation.
3493 if (!webview()->mainFrame()->document().url().isEmpty()) {
3494 // Tell the browser which url got zoomed so it can update the menu and the
3495 // saved values if necessary
3496 Send(new ViewHostMsg_DidZoomURL(
3497 routing_id_
, zoom_level
,
3498 GURL(webview()->mainFrame()->document().url())));
3502 void RenderViewImpl::pageScaleFactorChanged() {
3505 bool page_scale_factor_is_one
= webview()->pageScaleFactor() == 1;
3506 if (page_scale_factor_is_one
== page_scale_factor_is_one_
)
3508 page_scale_factor_is_one_
= page_scale_factor_is_one
;
3509 Send(new ViewHostMsg_PageScaleFactorIsOneChanged(routing_id_
,
3510 page_scale_factor_is_one_
));
3513 double RenderViewImpl::zoomLevelToZoomFactor(double zoom_level
) const {
3514 return ZoomLevelToZoomFactor(zoom_level
);
3517 double RenderViewImpl::zoomFactorToZoomLevel(double factor
) const {
3518 return ZoomFactorToZoomLevel(factor
);
3521 blink::WebPageVisibilityState
RenderViewImpl::visibilityState() const {
3522 blink::WebPageVisibilityState current_state
= is_hidden() ?
3523 blink::WebPageVisibilityStateHidden
:
3524 blink::WebPageVisibilityStateVisible
;
3525 blink::WebPageVisibilityState override_state
= current_state
;
3526 // TODO(jam): move this method to WebFrameClient.
3527 if (GetContentClient()->renderer()->
3528 ShouldOverridePageVisibilityState(main_render_frame_
,
3530 return override_state
;
3531 return current_state
;
3534 void RenderViewImpl::draggableRegionsChanged() {
3538 DraggableRegionsChanged(webview()->mainFrame()));
3541 #if defined(OS_ANDROID)
3542 WebContentDetectionResult
RenderViewImpl::detectContentAround(
3543 const WebHitTestResult
& touch_hit
) {
3544 DCHECK(touch_hit
.node().isTextNode());
3546 // Process the position with all the registered content detectors until
3547 // a match is found. Priority is provided by their relative order.
3548 for (ContentDetectorList::const_iterator it
= content_detectors_
.begin();
3549 it
!= content_detectors_
.end(); ++it
) {
3550 ContentDetector::Result content
= (*it
)->FindTappedContent(touch_hit
);
3551 if (content
.valid
) {
3552 return WebContentDetectionResult(content
.content_boundaries
,
3553 base::UTF8ToUTF16(content
.text
), content
.intent_url
);
3556 return WebContentDetectionResult();
3559 void RenderViewImpl::scheduleContentIntent(const WebURL
& intent
) {
3560 // Introduce a short delay so that the user can notice the content.
3561 base::MessageLoop::current()->PostDelayedTask(
3563 base::Bind(&RenderViewImpl::LaunchAndroidContentIntent
,
3566 expected_content_intent_id_
),
3567 base::TimeDelta::FromMilliseconds(kContentIntentDelayMilliseconds
));
3570 void RenderViewImpl::cancelScheduledContentIntents() {
3571 ++expected_content_intent_id_
;
3574 void RenderViewImpl::LaunchAndroidContentIntent(const GURL
& intent
,
3575 size_t request_id
) {
3576 if (request_id
!= expected_content_intent_id_
)
3579 // Remove the content highlighting if any.
3580 ScheduleComposite();
3582 if (!intent
.is_empty())
3583 Send(new ViewHostMsg_StartContentIntent(routing_id_
, intent
));
3586 bool RenderViewImpl::openDateTimeChooser(
3587 const blink::WebDateTimeChooserParams
& params
,
3588 blink::WebDateTimeChooserCompletion
* completion
) {
3589 // JavaScript may try to open a date time chooser while one is already open.
3590 if (date_time_picker_client_
)
3592 date_time_picker_client_
.reset(
3593 new RendererDateTimePicker(this, params
, completion
));
3594 return date_time_picker_client_
->Open();
3597 void RenderViewImpl::DismissDateTimeDialog() {
3598 DCHECK(date_time_picker_client_
);
3599 date_time_picker_client_
.reset(NULL
);
3602 #endif // defined(OS_ANDROID)
3604 void RenderViewImpl::OnShowContextMenu(
3605 ui::MenuSourceType source_type
, const gfx::Point
& location
) {
3606 context_menu_source_type_
= source_type
;
3607 has_host_context_menu_location_
= true;
3608 host_context_menu_location_
= location
;
3610 webview()->showContextMenu();
3611 has_host_context_menu_location_
= false;
3614 void RenderViewImpl::OnEnableViewSourceMode() {
3617 WebFrame
* main_frame
= webview()->mainFrame();
3620 main_frame
->enableViewSourceMode(true);
3623 #if defined(OS_ANDROID) || defined(USE_AURA)
3624 bool RenderViewImpl::didTapMultipleTargets(
3625 const WebSize
& inner_viewport_offset
,
3626 const WebRect
& touch_rect
,
3627 const WebVector
<WebRect
>& target_rects
) {
3628 DCHECK(switches::IsLinkDisambiguationPopupEnabled());
3630 // Never show a disambiguation popup when accessibility is enabled,
3631 // as this interferes with "touch exploration".
3632 AccessibilityMode accessibility_mode
=
3633 GetMainRenderFrame()->accessibility_mode();
3634 bool matches_accessibility_mode_complete
=
3635 (accessibility_mode
& AccessibilityModeComplete
) ==
3636 AccessibilityModeComplete
;
3637 if (matches_accessibility_mode_complete
)
3640 // The touch_rect, target_rects and zoom_rect are in the outer viewport
3642 gfx::Rect zoom_rect
;
3643 float new_total_scale
=
3644 DisambiguationPopupHelper::ComputeZoomAreaAndScaleFactor(
3645 touch_rect
, target_rects
, GetSize(),
3646 gfx::Rect(webview()->mainFrame()->visibleContentRect()).size(),
3647 device_scale_factor_
* webview()->pageScaleFactor(), &zoom_rect
);
3648 if (!new_total_scale
|| zoom_rect
.IsEmpty())
3651 bool handled
= false;
3652 switch (renderer_preferences_
.tap_multiple_targets_strategy
) {
3653 case TAP_MULTIPLE_TARGETS_STRATEGY_ZOOM
:
3654 handled
= webview()->zoomToMultipleTargetsRect(zoom_rect
);
3656 case TAP_MULTIPLE_TARGETS_STRATEGY_POPUP
: {
3657 gfx::Size canvas_size
=
3658 gfx::ToCeiledSize(gfx::ScaleSize(zoom_rect
.size(), new_total_scale
));
3659 cc::SharedBitmapManager
* manager
=
3660 RenderThreadImpl::current()->shared_bitmap_manager();
3661 scoped_ptr
<cc::SharedBitmap
> shared_bitmap
=
3662 manager
->AllocateSharedBitmap(canvas_size
);
3663 CHECK(!!shared_bitmap
);
3666 SkImageInfo info
= SkImageInfo::MakeN32Premul(canvas_size
.width(),
3667 canvas_size
.height());
3668 bitmap
.installPixels(info
, shared_bitmap
->pixels(), info
.minRowBytes());
3669 SkCanvas
canvas(bitmap
);
3671 // TODO(trchen): Cleanup the device scale factor mess.
3672 // device scale will be applied in WebKit
3673 // --> zoom_rect doesn't include device scale,
3674 // but WebKit will still draw on zoom_rect * device_scale_factor_
3675 canvas
.scale(new_total_scale
/ device_scale_factor_
,
3676 new_total_scale
/ device_scale_factor_
);
3677 canvas
.translate(-zoom_rect
.x() * device_scale_factor_
,
3678 -zoom_rect
.y() * device_scale_factor_
);
3680 DCHECK(webwidget_
->isAcceleratedCompositingActive());
3681 // TODO(aelias): The disambiguation popup should be composited so we
3682 // don't have to call this method.
3683 webwidget_
->paintCompositedDeprecated(&canvas
, zoom_rect
);
3686 gfx::Rect zoom_rect_in_screen
=
3687 zoom_rect
- gfx::Vector2d(inner_viewport_offset
.width
,
3688 inner_viewport_offset
.height
);
3690 gfx::Rect physical_window_zoom_rect
= gfx::ToEnclosingRect(
3691 ClientRectToPhysicalWindowRect(gfx::RectF(zoom_rect_in_screen
)));
3693 Send(new ViewHostMsg_ShowDisambiguationPopup(routing_id_
,
3694 physical_window_zoom_rect
,
3696 shared_bitmap
->id()));
3697 cc::SharedBitmapId id
= shared_bitmap
->id();
3698 disambiguation_bitmaps_
[id
] = shared_bitmap
.release();
3702 case TAP_MULTIPLE_TARGETS_STRATEGY_NONE
:
3709 #endif // defined(OS_ANDROID) || defined(USE_AURA)
3711 unsigned RenderViewImpl::GetLocalSessionHistoryLengthForTesting() const {
3712 return history_list_length_
;
3715 void RenderViewImpl::SetFocusAndActivateForTesting(bool enable
) {
3729 void RenderViewImpl::SetDeviceScaleFactorForTesting(float factor
) {
3730 ViewMsg_Resize_Params params
;
3731 params
.screen_info
= screen_info_
;
3732 params
.screen_info
.deviceScaleFactor
= factor
;
3733 params
.new_size
= size();
3734 params
.visible_viewport_size
= visible_viewport_size_
;
3735 params
.physical_backing_size
=
3736 gfx::ToCeiledSize(gfx::ScaleSize(size(), factor
));
3737 params
.top_controls_shrink_blink_size
= false;
3738 params
.top_controls_height
= 0.f
;
3739 params
.resizer_rect
= WebRect();
3740 params
.is_fullscreen_granted
= is_fullscreen_granted();
3741 params
.display_mode
= display_mode_
;
3745 void RenderViewImpl::SetDeviceColorProfileForTesting(
3746 const std::vector
<char>& color_profile
) {
3747 SetDeviceColorProfile(color_profile
);
3750 void RenderViewImpl::ForceResizeForTesting(const gfx::Size
& new_size
) {
3751 gfx::Rect
new_window_rect(rootWindowRect().x
,
3755 SetWindowRectSynchronously(new_window_rect
);
3758 void RenderViewImpl::UseSynchronousResizeModeForTesting(bool enable
) {
3759 resizing_mode_selector_
->set_is_synchronous_mode(enable
);
3762 void RenderViewImpl::EnableAutoResizeForTesting(const gfx::Size
& min_size
,
3763 const gfx::Size
& max_size
) {
3764 OnEnableAutoResize(min_size
, max_size
);
3767 void RenderViewImpl::DisableAutoResizeForTesting(const gfx::Size
& new_size
) {
3768 OnDisableAutoResize(new_size
);
3771 void RenderViewImpl::OnReleaseDisambiguationPopupBitmap(
3772 const cc::SharedBitmapId
& id
) {
3773 BitmapMap::iterator it
= disambiguation_bitmaps_
.find(id
);
3774 DCHECK(it
!= disambiguation_bitmaps_
.end());
3776 disambiguation_bitmaps_
.erase(it
);
3779 void RenderViewImpl::DidCommitCompositorFrame() {
3780 RenderWidget::DidCommitCompositorFrame();
3781 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidCommitCompositorFrame());
3784 void RenderViewImpl::SendUpdateFaviconURL(const std::vector
<FaviconURL
>& urls
) {
3786 Send(new ViewHostMsg_UpdateFaviconURL(routing_id_
, urls
));
3789 void RenderViewImpl::DidStopLoadingIcons() {
3790 int icon_types
= WebIconURL::TypeFavicon
| WebIconURL::TypeTouchPrecomposed
|
3791 WebIconURL::TypeTouch
;
3793 // Favicons matter only for the top-level frame. If it is a WebRemoteFrame,
3794 // just return early.
3795 if (webview()->mainFrame()->isWebRemoteFrame())
3798 WebVector
<WebIconURL
> icon_urls
=
3799 webview()->mainFrame()->iconURLs(icon_types
);
3801 std::vector
<FaviconURL
> urls
;
3802 for (size_t i
= 0; i
< icon_urls
.size(); i
++) {
3803 WebURL url
= icon_urls
[i
].iconURL();
3804 std::vector
<gfx::Size
> sizes
;
3805 ConvertToFaviconSizes(icon_urls
[i
].sizes(), &sizes
);
3808 FaviconURL(url
, ToFaviconType(icon_urls
[i
].iconType()), sizes
));
3810 SendUpdateFaviconURL(urls
);
3813 } // namespace content