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/debug/trace_event.h"
17 #include "base/files/file_path.h"
18 #include "base/i18n/rtl.h"
19 #include "base/json/json_writer.h"
20 #include "base/lazy_instance.h"
21 #include "base/memory/scoped_ptr.h"
22 #include "base/message_loop/message_loop_proxy.h"
23 #include "base/metrics/histogram.h"
24 #include "base/path_service.h"
25 #include "base/process/kill.h"
26 #include "base/process/process.h"
27 #include "base/strings/string_number_conversions.h"
28 #include "base/strings/string_piece.h"
29 #include "base/strings/string_split.h"
30 #include "base/strings/string_util.h"
31 #include "base/strings/sys_string_conversions.h"
32 #include "base/strings/utf_string_conversions.h"
33 #include "base/time/time.h"
34 #include "cc/base/switches.h"
35 #include "content/child/appcache/appcache_dispatcher.h"
36 #include "content/child/appcache/web_application_cache_host_impl.h"
37 #include "content/child/child_thread.h"
38 #include "content/child/npapi/webplugin_delegate_impl.h"
39 #include "content/child/request_extra_data.h"
40 #include "content/child/webmessageportchannel_impl.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/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
46 #include "content/common/input_messages.h"
47 #include "content/common/pepper_messages.h"
48 #include "content/common/socket_stream_handle_data.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_params.h"
58 #include "content/public/common/page_zoom.h"
59 #include "content/public/common/ssl_status.h"
60 #include "content/public/common/three_d_api_types.h"
61 #include "content/public/common/url_constants.h"
62 #include "content/public/common/url_utils.h"
63 #include "content/public/renderer/content_renderer_client.h"
64 #include "content/public/renderer/document_state.h"
65 #include "content/public/renderer/history_item_serialization.h"
66 #include "content/public/renderer/navigation_state.h"
67 #include "content/public/renderer/render_view_observer.h"
68 #include "content/public/renderer/render_view_visitor.h"
69 #include "content/public/renderer/web_preferences.h"
70 #include "content/renderer/accessibility/renderer_accessibility.h"
71 #include "content/renderer/accessibility/renderer_accessibility_complete.h"
72 #include "content/renderer/accessibility/renderer_accessibility_focus_only.h"
73 #include "content/renderer/browser_plugin/browser_plugin.h"
74 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
75 #include "content/renderer/browser_plugin/browser_plugin_manager_impl.h"
76 #include "content/renderer/devtools/devtools_agent.h"
77 #include "content/renderer/disambiguation_popup_helper.h"
78 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
79 #include "content/renderer/drop_data_builder.h"
80 #include "content/renderer/external_popup_menu.h"
81 #include "content/renderer/geolocation_dispatcher.h"
82 #include "content/renderer/gpu/render_widget_compositor.h"
83 #include "content/renderer/history_controller.h"
84 #include "content/renderer/idle_user_detector.h"
85 #include "content/renderer/ime_event_guard.h"
86 #include "content/renderer/input/input_handler_manager.h"
87 #include "content/renderer/input_tag_speech_dispatcher.h"
88 #include "content/renderer/internal_document_state_data.h"
89 #include "content/renderer/load_progress_tracker.h"
90 #include "content/renderer/media/audio_device_factory.h"
91 #include "content/renderer/media/audio_renderer_mixer_manager.h"
92 #include "content/renderer/media/media_stream_dependency_factory.h"
93 #include "content/renderer/media/media_stream_dispatcher.h"
94 #include "content/renderer/media/media_stream_impl.h"
95 #include "content/renderer/media/midi_dispatcher.h"
96 #include "content/renderer/media/render_media_log.h"
97 #include "content/renderer/media/video_capture_impl_manager.h"
98 #include "content/renderer/media/webmediaplayer_impl.h"
99 #include "content/renderer/media/webmediaplayer_ms.h"
100 #include "content/renderer/media/webmediaplayer_params.h"
101 #include "content/renderer/memory_benchmarking_extension.h"
102 #include "content/renderer/mhtml_generator.h"
103 #include "content/renderer/notification_provider.h"
104 #include "content/renderer/push_messaging_dispatcher.h"
105 #include "content/renderer/render_frame_impl.h"
106 #include "content/renderer/render_process.h"
107 #include "content/renderer/render_thread_impl.h"
108 #include "content/renderer/render_view_impl_params.h"
109 #include "content/renderer/render_view_mouse_lock_dispatcher.h"
110 #include "content/renderer/render_widget_fullscreen_pepper.h"
111 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
112 #include "content/renderer/resizing_mode_selector.h"
113 #include "content/renderer/savable_resources.h"
114 #include "content/renderer/skia_benchmarking_extension.h"
115 #include "content/renderer/speech_recognition_dispatcher.h"
116 #include "content/renderer/stats_collection_controller.h"
117 #include "content/renderer/stats_collection_observer.h"
118 #include "content/renderer/text_input_client_observer.h"
119 #include "content/renderer/v8_value_converter_impl.h"
120 #include "content/renderer/web_ui_extension.h"
121 #include "content/renderer/web_ui_extension_data.h"
122 #include "content/renderer/web_ui_mojo.h"
123 #include "content/renderer/websharedworker_proxy.h"
124 #include "media/audio/audio_output_device.h"
125 #include "media/base/audio_renderer_mixer_input.h"
126 #include "media/base/filter_collection.h"
127 #include "media/base/media_switches.h"
128 #include "media/filters/audio_renderer_impl.h"
129 #include "media/filters/gpu_video_accelerator_factories.h"
130 #include "net/base/data_url.h"
131 #include "net/base/escape.h"
132 #include "net/base/net_errors.h"
133 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
134 #include "net/http/http_util.h"
135 #include "third_party/WebKit/public/platform/WebCString.h"
136 #include "third_party/WebKit/public/platform/WebDragData.h"
137 #include "third_party/WebKit/public/platform/WebHTTPBody.h"
138 #include "third_party/WebKit/public/platform/WebImage.h"
139 #include "third_party/WebKit/public/platform/WebMessagePortChannel.h"
140 #include "third_party/WebKit/public/platform/WebPoint.h"
141 #include "third_party/WebKit/public/platform/WebRect.h"
142 #include "third_party/WebKit/public/platform/WebSize.h"
143 #include "third_party/WebKit/public/platform/WebSocketStreamHandle.h"
144 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
145 #include "third_party/WebKit/public/platform/WebString.h"
146 #include "third_party/WebKit/public/platform/WebURL.h"
147 #include "third_party/WebKit/public/platform/WebURLError.h"
148 #include "third_party/WebKit/public/platform/WebURLRequest.h"
149 #include "third_party/WebKit/public/platform/WebURLResponse.h"
150 #include "third_party/WebKit/public/platform/WebVector.h"
151 #include "third_party/WebKit/public/web/WebAXObject.h"
152 #include "third_party/WebKit/public/web/WebColorName.h"
153 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
154 #include "third_party/WebKit/public/web/WebDOMEvent.h"
155 #include "third_party/WebKit/public/web/WebDOMMessageEvent.h"
156 #include "third_party/WebKit/public/web/WebDataSource.h"
157 #include "third_party/WebKit/public/web/WebDateTimeChooserCompletion.h"
158 #include "third_party/WebKit/public/web/WebDateTimeChooserParams.h"
159 #include "third_party/WebKit/public/web/WebDevToolsAgent.h"
160 #include "third_party/WebKit/public/web/WebDocument.h"
161 #include "third_party/WebKit/public/web/WebElement.h"
162 #include "third_party/WebKit/public/web/WebFileChooserParams.h"
163 #include "third_party/WebKit/public/web/WebFindOptions.h"
164 #include "third_party/WebKit/public/web/WebFormControlElement.h"
165 #include "third_party/WebKit/public/web/WebFormElement.h"
166 #include "third_party/WebKit/public/web/WebFrame.h"
167 #include "third_party/WebKit/public/web/WebGlyphCache.h"
168 #include "third_party/WebKit/public/web/WebHistoryItem.h"
169 #include "third_party/WebKit/public/web/WebInputElement.h"
170 #include "third_party/WebKit/public/web/WebInputEvent.h"
171 #include "third_party/WebKit/public/web/WebLocalFrame.h"
172 #include "third_party/WebKit/public/web/WebMediaPlayerAction.h"
173 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
174 #include "third_party/WebKit/public/web/WebNodeList.h"
175 #include "third_party/WebKit/public/web/WebPageSerializer.h"
176 #include "third_party/WebKit/public/web/WebPlugin.h"
177 #include "third_party/WebKit/public/web/WebPluginAction.h"
178 #include "third_party/WebKit/public/web/WebPluginContainer.h"
179 #include "third_party/WebKit/public/web/WebPluginDocument.h"
180 #include "third_party/WebKit/public/web/WebRange.h"
181 #include "third_party/WebKit/public/web/WebScriptSource.h"
182 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
183 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
184 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
185 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
186 #include "third_party/WebKit/public/web/WebSettings.h"
187 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
188 #include "third_party/WebKit/public/web/WebUserMediaClient.h"
189 #include "third_party/WebKit/public/web/WebView.h"
190 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
191 #include "third_party/WebKit/public/web/default/WebRenderTheme.h"
192 #include "ui/base/clipboard/clipboard.h"
193 #include "ui/base/ui_base_switches_util.h"
194 #include "ui/events/latency_info.h"
195 #include "ui/gfx/native_widget_types.h"
196 #include "ui/gfx/point.h"
197 #include "ui/gfx/rect.h"
198 #include "ui/gfx/rect_conversions.h"
199 #include "ui/gfx/size_conversions.h"
200 #include "ui/shell_dialogs/selected_file_info.h"
201 #include "v8/include/v8.h"
202 #include "webkit/child/weburlresponse_extradata_impl.h"
204 #if defined(OS_ANDROID)
205 #include <cpu-features.h>
207 #include "content/common/android/device_telephony_info.h"
208 #include "content/common/gpu/client/context_provider_command_buffer.h"
209 #include "content/renderer/android/address_detector.h"
210 #include "content/renderer/android/content_detector.h"
211 #include "content/renderer/android/email_detector.h"
212 #include "content/renderer/android/phone_number_detector.h"
213 #include "content/renderer/android/synchronous_compositor_factory.h"
214 #include "content/renderer/media/android/renderer_media_player_manager.h"
215 #include "content/renderer/media/android/stream_texture_factory_impl.h"
216 #include "content/renderer/media/android/webmediaplayer_android.h"
217 #include "skia/ext/platform_canvas.h"
218 #include "third_party/WebKit/public/platform/WebFloatPoint.h"
219 #include "third_party/WebKit/public/platform/WebFloatRect.h"
220 #include "third_party/WebKit/public/web/WebHitTestResult.h"
221 #include "ui/gfx/rect_f.h"
223 #elif defined(OS_WIN)
224 // TODO(port): these files are currently Windows only because they concern:
226 #include "ui/native_theme/native_theme_win.h"
227 #elif defined(USE_X11)
228 #include "ui/native_theme/native_theme.h"
229 #elif defined(OS_MACOSX)
230 #include "skia/ext/skia_utils_mac.h"
233 #if defined(ENABLE_PLUGINS)
234 #include "content/renderer/npapi/webplugin_delegate_proxy.h"
235 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
236 #include "content/renderer/pepper/pepper_plugin_registry.h"
239 #if defined(ENABLE_WEBRTC)
240 #include "content/renderer/media/rtc_peer_connection_handler.h"
243 using blink::WebAXObject
;
244 using blink::WebApplicationCacheHost
;
245 using blink::WebApplicationCacheHostClient
;
246 using blink::WebCString
;
247 using blink::WebColor
;
248 using blink::WebColorName
;
249 using blink::WebConsoleMessage
;
250 using blink::WebData
;
251 using blink::WebDataSource
;
252 using blink::WebDocument
;
253 using blink::WebDOMEvent
;
254 using blink::WebDOMMessageEvent
;
255 using blink::WebDragData
;
256 using blink::WebDragOperation
;
257 using blink::WebDragOperationsMask
;
258 using blink::WebElement
;
259 using blink::WebExternalPopupMenu
;
260 using blink::WebExternalPopupMenuClient
;
261 using blink::WebFileChooserCompletion
;
262 using blink::WebFindOptions
;
263 using blink::WebFormControlElement
;
264 using blink::WebFormElement
;
265 using blink::WebFrame
;
266 using blink::WebGestureEvent
;
267 using blink::WebHistoryItem
;
268 using blink::WebHTTPBody
;
269 using blink::WebIconURL
;
270 using blink::WebImage
;
271 using blink::WebInputElement
;
272 using blink::WebInputEvent
;
273 using blink::WebLocalFrame
;
274 using blink::WebMediaPlayer
;
275 using blink::WebMediaPlayerAction
;
276 using blink::WebMediaPlayerClient
;
277 using blink::WebMouseEvent
;
278 using blink::WebNavigationPolicy
;
279 using blink::WebNavigationType
;
280 using blink::WebNode
;
281 using blink::WebPageSerializer
;
282 using blink::WebPageSerializerClient
;
283 using blink::WebPeerConnection00Handler
;
284 using blink::WebPeerConnection00HandlerClient
;
285 using blink::WebPeerConnectionHandler
;
286 using blink::WebPeerConnectionHandlerClient
;
287 using blink::WebPluginAction
;
288 using blink::WebPluginContainer
;
289 using blink::WebPluginDocument
;
290 using blink::WebPoint
;
291 using blink::WebPopupMenuInfo
;
292 using blink::WebRange
;
293 using blink::WebRect
;
294 using blink::WebReferrerPolicy
;
295 using blink::WebScriptSource
;
296 using blink::WebSearchableFormData
;
297 using blink::WebSecurityOrigin
;
298 using blink::WebSecurityPolicy
;
299 using blink::WebSerializedScriptValue
;
300 using blink::WebSettings
;
301 using blink::WebSize
;
302 using blink::WebSocketStreamHandle
;
303 using blink::WebStorageNamespace
;
304 using blink::WebStorageQuotaCallbacks
;
305 using blink::WebStorageQuotaError
;
306 using blink::WebStorageQuotaType
;
307 using blink::WebString
;
308 using blink::WebTextAffinity
;
309 using blink::WebTextDirection
;
310 using blink::WebTouchEvent
;
312 using blink::WebURLError
;
313 using blink::WebURLRequest
;
314 using blink::WebURLResponse
;
315 using blink::WebUserGestureIndicator
;
316 using blink::WebVector
;
317 using blink::WebView
;
318 using blink::WebWidget
;
319 using blink::WebWindowFeatures
;
321 using base::TimeDelta
;
322 using webkit_glue::WebURLResponseExtraDataImpl
;
324 #if defined(OS_ANDROID)
325 using blink::WebContentDetectionResult
;
326 using blink::WebFloatPoint
;
327 using blink::WebFloatRect
;
328 using blink::WebHitTestResult
;
333 //-----------------------------------------------------------------------------
335 typedef std::map
<blink::WebView
*, RenderViewImpl
*> ViewMap
;
336 static base::LazyInstance
<ViewMap
> g_view_map
= LAZY_INSTANCE_INITIALIZER
;
337 typedef std::map
<int32
, RenderViewImpl
*> RoutingIDViewMap
;
338 static base::LazyInstance
<RoutingIDViewMap
> g_routing_id_view_map
=
339 LAZY_INSTANCE_INITIALIZER
;
341 // Time, in seconds, we delay before sending content state changes (such as form
342 // state and scroll position) to the browser. We delay sending changes to avoid
343 // spamming the browser.
344 // To avoid having tab/session restore require sending a message to get the
345 // current content state during tab closing we use a shorter timeout for the
346 // foreground renderer. This means there is a small window of time from which
347 // content state is modified and not sent to session restore, but this is
348 // better than having to wake up all renderers during shutdown.
349 const int kDelaySecondsForContentStateSyncHidden
= 5;
350 const int kDelaySecondsForContentStateSync
= 1;
352 #if defined(OS_ANDROID)
353 // Delay between tapping in content and launching the associated android intent.
354 // Used to allow users see what has been recognized as content.
355 const size_t kContentIntentDelayMilliseconds
= 700;
358 static RenderViewImpl
* (*g_create_render_view_impl
)(RenderViewImplParams
*) =
362 bool RenderViewImpl::IsReload(const FrameMsg_Navigate_Params
& params
) {
364 params
.navigation_type
== FrameMsg_Navigate_Type::RELOAD
||
365 params
.navigation_type
== FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
||
366 params
.navigation_type
==
367 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
;
371 Referrer
RenderViewImpl::GetReferrerFromRequest(
373 const WebURLRequest
& request
) {
374 return Referrer(GURL(request
.httpHeaderField(WebString::fromUTF8("Referer"))),
375 request
.referrerPolicy());
379 WindowOpenDisposition
RenderViewImpl::NavigationPolicyToDisposition(
380 WebNavigationPolicy policy
) {
382 case blink::WebNavigationPolicyIgnore
:
383 return IGNORE_ACTION
;
384 case blink::WebNavigationPolicyDownload
:
386 case blink::WebNavigationPolicyCurrentTab
:
388 case blink::WebNavigationPolicyNewBackgroundTab
:
389 return NEW_BACKGROUND_TAB
;
390 case blink::WebNavigationPolicyNewForegroundTab
:
391 return NEW_FOREGROUND_TAB
;
392 case blink::WebNavigationPolicyNewWindow
:
394 case blink::WebNavigationPolicyNewPopup
:
397 NOTREACHED() << "Unexpected WebNavigationPolicy";
398 return IGNORE_ACTION
;
402 // Returns true if the device scale is high enough that losing subpixel
403 // antialiasing won't have a noticeable effect on text quality.
404 static bool DeviceScaleEnsuresTextQuality(float device_scale_factor
) {
405 #if defined(OS_ANDROID)
406 // On Android, we never have subpixel antialiasing.
409 return device_scale_factor
> 1.5f
;
414 static bool ShouldUseFixedPositionCompositing(float device_scale_factor
) {
415 // Compositing for fixed-position elements is dependent on
416 // device_scale_factor if no flag is set. http://crbug.com/172738
417 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
419 if (command_line
.HasSwitch(switches::kDisableCompositingForFixedPosition
))
422 if (command_line
.HasSwitch(switches::kEnableCompositingForFixedPosition
))
425 return DeviceScaleEnsuresTextQuality(device_scale_factor
);
428 static bool ShouldUseAcceleratedCompositingForOverflowScroll(
429 float device_scale_factor
) {
430 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
432 if (command_line
.HasSwitch(switches::kDisableAcceleratedOverflowScroll
))
435 if (command_line
.HasSwitch(switches::kEnableAcceleratedOverflowScroll
))
438 return DeviceScaleEnsuresTextQuality(device_scale_factor
);
441 static bool ShouldUseCompositedScrollingForFrames(
442 float device_scale_factor
) {
443 if (RenderThreadImpl::current() &&
444 !RenderThreadImpl::current()->is_lcd_text_enabled())
447 return DeviceScaleEnsuresTextQuality(device_scale_factor
);
450 static bool ShouldUseUniversalAcceleratedCompositingForOverflowScroll() {
451 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
453 if (command_line
.HasSwitch(
454 switches::kDisableUniversalAcceleratedOverflowScroll
))
457 if (command_line
.HasSwitch(
458 switches::kEnableUniversalAcceleratedOverflowScroll
))
464 static bool ShouldUseTransitionCompositing(float device_scale_factor
) {
465 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
467 if (command_line
.HasSwitch(switches::kDisableCompositingForTransition
))
470 if (command_line
.HasSwitch(switches::kEnableCompositingForTransition
))
473 // TODO(ajuma): Re-enable this by default for high-DPI once the problem
474 // of excessive layer promotion caused by overlap has been addressed.
475 // http://crbug.com/178119.
479 static bool ShouldUseAcceleratedFixedRootBackground(float device_scale_factor
) {
480 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
482 if (command_line
.HasSwitch(switches::kDisableAcceleratedFixedRootBackground
))
485 if (command_line
.HasSwitch(switches::kEnableAcceleratedFixedRootBackground
))
488 return DeviceScaleEnsuresTextQuality(device_scale_factor
);
491 static bool ShouldUseCompositingForGpuRasterizationHint() {
492 return RenderThreadImpl::current() &&
493 RenderThreadImpl::current()->is_gpu_rasterization_enabled();
496 static FaviconURL::IconType
ToFaviconType(blink::WebIconURL::Type type
) {
498 case blink::WebIconURL::TypeFavicon
:
499 return FaviconURL::FAVICON
;
500 case blink::WebIconURL::TypeTouch
:
501 return FaviconURL::TOUCH_ICON
;
502 case blink::WebIconURL::TypeTouchPrecomposed
:
503 return FaviconURL::TOUCH_PRECOMPOSED_ICON
;
504 case blink::WebIconURL::TypeInvalid
:
505 return FaviconURL::INVALID_ICON
;
507 return FaviconURL::INVALID_ICON
;
510 static void ConvertToFaviconSizes(
511 const blink::WebVector
<blink::WebSize
>& web_sizes
,
512 std::vector
<gfx::Size
>* sizes
) {
513 DCHECK(sizes
->empty());
514 sizes
->reserve(web_sizes
.size());
515 for (size_t i
= 0; i
< web_sizes
.size(); ++i
)
516 sizes
->push_back(gfx::Size(web_sizes
[i
]));
519 ///////////////////////////////////////////////////////////////////////////////
521 struct RenderViewImpl::PendingFileChooser
{
522 PendingFileChooser(const FileChooserParams
& p
, WebFileChooserCompletion
* c
)
526 FileChooserParams params
;
527 WebFileChooserCompletion
* completion
; // MAY BE NULL to skip callback.
532 class WebWidgetLockTarget
: public MouseLockDispatcher::LockTarget
{
534 explicit WebWidgetLockTarget(blink::WebWidget
* webwidget
)
535 : webwidget_(webwidget
) {}
537 virtual void OnLockMouseACK(bool succeeded
) OVERRIDE
{
539 webwidget_
->didAcquirePointerLock();
541 webwidget_
->didNotAcquirePointerLock();
544 virtual void OnMouseLockLost() OVERRIDE
{
545 webwidget_
->didLosePointerLock();
548 virtual bool HandleMouseLockedInputEvent(
549 const blink::WebMouseEvent
&event
) OVERRIDE
{
550 // The WebWidget handles mouse lock in WebKit's handleInputEvent().
555 blink::WebWidget
* webwidget_
;
558 bool TouchEnabled() {
559 // Based on the definition of chrome::kEnableTouchIcon.
560 #if defined(OS_ANDROID)
567 WebDragData
DropDataToWebDragData(const DropData
& drop_data
) {
568 std::vector
<WebDragData::Item
> item_list
;
570 // These fields are currently unused when dragging into WebKit.
571 DCHECK(drop_data
.download_metadata
.empty());
572 DCHECK(drop_data
.file_contents
.empty());
573 DCHECK(drop_data
.file_description_filename
.empty());
575 if (!drop_data
.text
.is_null()) {
576 WebDragData::Item item
;
577 item
.storageType
= WebDragData::Item::StorageTypeString
;
578 item
.stringType
= WebString::fromUTF8(ui::Clipboard::kMimeTypeText
);
579 item
.stringData
= drop_data
.text
.string();
580 item_list
.push_back(item
);
583 // TODO(dcheng): Do we need to distinguish between null and empty URLs? Is it
584 // meaningful to write an empty URL to the clipboard?
585 if (!drop_data
.url
.is_empty()) {
586 WebDragData::Item item
;
587 item
.storageType
= WebDragData::Item::StorageTypeString
;
588 item
.stringType
= WebString::fromUTF8(ui::Clipboard::kMimeTypeURIList
);
589 item
.stringData
= WebString::fromUTF8(drop_data
.url
.spec());
590 item
.title
= drop_data
.url_title
;
591 item_list
.push_back(item
);
594 if (!drop_data
.html
.is_null()) {
595 WebDragData::Item item
;
596 item
.storageType
= WebDragData::Item::StorageTypeString
;
597 item
.stringType
= WebString::fromUTF8(ui::Clipboard::kMimeTypeHTML
);
598 item
.stringData
= drop_data
.html
.string();
599 item
.baseURL
= drop_data
.html_base_url
;
600 item_list
.push_back(item
);
603 for (std::vector
<ui::FileInfo
>::const_iterator it
=
604 drop_data
.filenames
.begin();
605 it
!= drop_data
.filenames
.end();
607 WebDragData::Item item
;
608 item
.storageType
= WebDragData::Item::StorageTypeFilename
;
609 item
.filenameData
= it
->path
.AsUTF16Unsafe();
610 item
.displayNameData
= it
->display_name
.AsUTF16Unsafe();
611 item_list
.push_back(item
);
614 for (std::map
<base::string16
, base::string16
>::const_iterator it
=
615 drop_data
.custom_data
.begin();
616 it
!= drop_data
.custom_data
.end();
618 WebDragData::Item item
;
619 item
.storageType
= WebDragData::Item::StorageTypeString
;
620 item
.stringType
= it
->first
;
621 item
.stringData
= it
->second
;
622 item_list
.push_back(item
);
627 result
.setItems(item_list
);
628 result
.setFilesystemId(drop_data
.filesystem_id
);
634 RenderViewImpl::RenderViewImpl(RenderViewImplParams
* params
)
635 : RenderWidget(blink::WebPopupTypeNone
,
639 params
->never_visible
),
640 webkit_preferences_(params
->webkit_prefs
),
641 send_content_state_immediately_(false),
642 enabled_bindings_(0),
643 send_preferred_size_changes_(false),
644 navigation_gesture_(NavigationGestureUnknown
),
645 opened_by_user_gesture_(true),
646 opener_suppressed_(false),
647 suppress_dialogs_until_swap_out_(false),
649 last_page_id_sent_to_browser_(-1),
650 next_page_id_(params
->next_page_id
),
651 history_list_offset_(-1),
652 history_list_length_(0),
653 frames_in_progress_(0),
654 target_url_status_(TARGET_NONE
),
655 #if defined(OS_ANDROID)
656 top_controls_constraints_(cc::BOTH
),
658 cached_is_main_frame_pinned_to_left_(false),
659 cached_is_main_frame_pinned_to_right_(false),
660 cached_has_main_frame_horizontal_scrollbar_(false),
661 cached_has_main_frame_vertical_scrollbar_(false),
662 has_scrolled_focused_editable_node_into_rect_(false),
663 notification_provider_(NULL
),
664 push_messaging_dispatcher_(NULL
),
665 geolocation_dispatcher_(NULL
),
666 input_tag_speech_dispatcher_(NULL
),
667 speech_recognition_dispatcher_(NULL
),
668 media_stream_dispatcher_(NULL
),
669 browser_plugin_manager_(NULL
),
670 media_stream_client_(NULL
),
671 web_user_media_client_(NULL
),
672 midi_dispatcher_(NULL
),
673 devtools_agent_(NULL
),
674 accessibility_mode_(AccessibilityModeOff
),
675 renderer_accessibility_(NULL
),
676 mouse_lock_dispatcher_(NULL
),
677 #if defined(OS_ANDROID)
678 body_background_color_(SK_ColorWHITE
),
679 expected_content_intent_id_(0),
680 media_player_manager_(NULL
),
683 focused_plugin_id_(-1),
685 #if defined(ENABLE_PLUGINS)
686 plugin_find_handler_(NULL
),
687 focused_pepper_plugin_(NULL
),
688 pepper_last_mouse_event_target_(NULL
),
690 enumeration_completion_id_(0),
691 load_progress_tracker_(new LoadProgressTracker(this)),
692 session_storage_namespace_id_(params
->session_storage_namespace_id
),
693 next_snapshot_id_(0) {
696 void RenderViewImpl::Initialize(
697 RenderViewImplParams
* params
,
698 RenderFrameImpl
* main_render_frame
) {
699 routing_id_
= params
->routing_id
;
700 surface_id_
= params
->surface_id
;
701 if (params
->opener_id
!= MSG_ROUTING_NONE
&& params
->is_renderer_created
)
702 opener_id_
= params
->opener_id
;
704 // Ensure we start with a valid next_page_id_ from the browser.
705 DCHECK_GE(next_page_id_
, 0);
707 #if defined(ENABLE_NOTIFICATIONS)
708 notification_provider_
= new NotificationProvider(this);
710 notification_provider_
= NULL
;
713 webwidget_
= WebView::create(this);
714 webwidget_mouse_lock_target_
.reset(new WebWidgetLockTarget(webwidget_
));
716 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
718 if (command_line
.HasSwitch(switches::kStatsCollectionController
))
719 stats_collection_observer_
.reset(new StatsCollectionObserver(this));
721 #if defined(OS_ANDROID)
722 content::DeviceTelephonyInfo device_info
;
724 const std::string region_code
=
725 command_line
.HasSwitch(switches::kNetworkCountryIso
)
726 ? command_line
.GetSwitchValueASCII(switches::kNetworkCountryIso
)
727 : device_info
.GetNetworkCountryIso();
728 content_detectors_
.push_back(linked_ptr
<ContentDetector
>(
729 new AddressDetector()));
730 content_detectors_
.push_back(linked_ptr
<ContentDetector
>(
731 new PhoneNumberDetector(region_code
)));
732 content_detectors_
.push_back(linked_ptr
<ContentDetector
>(
733 new EmailDetector()));
736 RenderThread::Get()->AddRoute(routing_id_
, this);
737 // Take a reference on behalf of the RenderThread. This will be balanced
738 // when we receive ViewMsg_ClosePage.
740 if (RenderThreadImpl::current()) {
741 RenderThreadImpl::current()->WidgetCreated();
743 RenderThreadImpl::current()->WidgetHidden();
746 // If this is a popup, we must wait for the CreatingNew_ACK message before
747 // completing initialization. Otherwise, we can finish it now.
748 if (opener_id_
== MSG_ROUTING_NONE
) {
753 g_view_map
.Get().insert(std::make_pair(webview(), this));
754 g_routing_id_view_map
.Get().insert(std::make_pair(routing_id_
, this));
755 webview()->setDeviceScaleFactor(device_scale_factor_
);
756 webview()->settings()->setAcceleratedCompositingForFixedPositionEnabled(
757 ShouldUseFixedPositionCompositing(device_scale_factor_
));
758 webview()->settings()->setAcceleratedCompositingForOverflowScrollEnabled(
759 ShouldUseAcceleratedCompositingForOverflowScroll(device_scale_factor_
));
760 webview()->settings()->setCompositorDrivenAcceleratedScrollingEnabled(
761 ShouldUseUniversalAcceleratedCompositingForOverflowScroll());
762 webview()->settings()->setAcceleratedCompositingForTransitionEnabled(
763 ShouldUseTransitionCompositing(device_scale_factor_
));
764 webview()->settings()->setAcceleratedCompositingForFixedRootBackgroundEnabled(
765 ShouldUseAcceleratedFixedRootBackground(device_scale_factor_
));
766 webview()->settings()->setCompositedScrollingForFramesEnabled(
767 ShouldUseCompositedScrollingForFrames(device_scale_factor_
));
768 webview()->settings()
769 ->setAcceleratedCompositingForGpuRasterizationHintEnabled(
770 ShouldUseCompositingForGpuRasterizationHint());
772 ApplyWebPreferences(webkit_preferences_
, webview());
774 main_render_frame_
.reset(main_render_frame
);
775 webview()->setMainFrame(main_render_frame_
->GetWebFrame());
776 main_render_frame_
->Initialize();
778 if (switches::IsTouchDragDropEnabled())
779 webview()->settings()->setTouchDragDropEnabled(true);
781 if (switches::IsTouchEditingEnabled())
782 webview()->settings()->setTouchEditingEnabled(true);
784 if (!params
->frame_name
.empty())
785 webview()->mainFrame()->setName(params
->frame_name
);
787 // TODO(davidben): Move this state from Blink into content.
788 if (params
->window_was_created_with_opener
)
789 webview()->setOpenedByDOM();
791 OnSetRendererPrefs(params
->renderer_prefs
);
793 #if defined(ENABLE_WEBRTC)
794 if (!media_stream_dispatcher_
)
795 media_stream_dispatcher_
= new MediaStreamDispatcher(this);
798 new MHTMLGenerator(this);
799 #if defined(OS_MACOSX)
800 new TextInputClientObserver(this);
801 #endif // defined(OS_MACOSX)
803 #if defined(OS_ANDROID)
804 media_player_manager_
= new RendererMediaPlayerManager(this);
807 // The next group of objects all implement RenderViewObserver, so are deleted
808 // along with the RenderView automatically.
809 devtools_agent_
= new DevToolsAgent(this);
810 if (RenderWidgetCompositor
* rwc
= compositor()) {
811 webview()->devToolsAgent()->setLayerTreeId(rwc
->GetLayerTreeId());
813 mouse_lock_dispatcher_
= new RenderViewMouseLockDispatcher(this);
815 history_controller_
.reset(new HistoryController(this));
817 // Create renderer_accessibility_ if needed.
818 OnSetAccessibilityMode(params
->accessibility_mode
);
820 new IdleUserDetector(this);
822 if (command_line
.HasSwitch(switches::kDomAutomationController
))
823 enabled_bindings_
|= BINDINGS_POLICY_DOM_AUTOMATION
;
824 if (command_line
.HasSwitch(switches::kStatsCollectionController
))
825 enabled_bindings_
|= BINDINGS_POLICY_STATS_COLLECTION
;
827 ProcessViewLayoutFlags(command_line
);
829 GetContentClient()->renderer()->RenderViewCreated(this);
831 // If we have an opener_id but we weren't created by a renderer, then
832 // it's the browser asking us to set our opener to another RenderView.
833 if (params
->opener_id
!= MSG_ROUTING_NONE
&& !params
->is_renderer_created
) {
834 RenderViewImpl
* opener_view
= FromRoutingID(params
->opener_id
);
836 webview()->mainFrame()->setOpener(opener_view
->webview()->mainFrame());
839 // If we are initially swapped out, navigate to kSwappedOutURL.
840 // This ensures we are in a unique origin that others cannot script.
842 NavigateToSwappedOutURL(webview()->mainFrame());
845 RenderViewImpl::~RenderViewImpl() {
846 history_page_ids_
.clear();
848 base::debug::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_
);
850 // If file chooser is still waiting for answer, dispatch empty answer.
851 while (!file_chooser_completions_
.empty()) {
852 if (file_chooser_completions_
.front()->completion
) {
853 file_chooser_completions_
.front()->completion
->didChooseFile(
854 WebVector
<WebString
>());
856 file_chooser_completions_
.pop_front();
859 #if defined(OS_ANDROID)
860 // The date/time picker client is both a scoped_ptr member of this class and
861 // a RenderViewObserver. Reset it to prevent double deletion.
862 date_time_picker_client_
.reset();
866 // Make sure we are no longer referenced by the ViewMap or RoutingIDViewMap.
867 ViewMap
* views
= g_view_map
.Pointer();
868 for (ViewMap::iterator it
= views
->begin(); it
!= views
->end(); ++it
)
869 DCHECK_NE(this, it
->second
) << "Failed to call Close?";
870 RoutingIDViewMap
* routing_id_views
= g_routing_id_view_map
.Pointer();
871 for (RoutingIDViewMap::iterator it
= routing_id_views
->begin();
872 it
!= routing_id_views
->end(); ++it
)
873 DCHECK_NE(this, it
->second
) << "Failed to call Close?";
876 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, RenderViewGone());
877 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, OnDestruct());
881 RenderViewImpl
* RenderViewImpl::FromWebView(WebView
* webview
) {
882 ViewMap
* views
= g_view_map
.Pointer();
883 ViewMap::iterator it
= views
->find(webview
);
884 return it
== views
->end() ? NULL
: it
->second
;
888 RenderView
* RenderView::FromWebView(blink::WebView
* webview
) {
889 return RenderViewImpl::FromWebView(webview
);
893 RenderViewImpl
* RenderViewImpl::FromRoutingID(int32 routing_id
) {
894 RoutingIDViewMap
* views
= g_routing_id_view_map
.Pointer();
895 RoutingIDViewMap::iterator it
= views
->find(routing_id
);
896 return it
== views
->end() ? NULL
: it
->second
;
900 RenderView
* RenderView::FromRoutingID(int routing_id
) {
901 return RenderViewImpl::FromRoutingID(routing_id
);
905 void RenderView::ForEach(RenderViewVisitor
* visitor
) {
906 ViewMap
* views
= g_view_map
.Pointer();
907 for (ViewMap::iterator it
= views
->begin(); it
!= views
->end(); ++it
) {
908 if (!visitor
->Visit(it
->second
))
914 RenderViewImpl
* RenderViewImpl::Create(
916 bool window_was_created_with_opener
,
917 const RendererPreferences
& renderer_prefs
,
918 const WebPreferences
& webkit_prefs
,
920 int32 main_frame_routing_id
,
922 int64 session_storage_namespace_id
,
923 const base::string16
& frame_name
,
924 bool is_renderer_created
,
929 const blink::WebScreenInfo
& screen_info
,
930 AccessibilityMode accessibility_mode
) {
931 DCHECK(routing_id
!= MSG_ROUTING_NONE
);
932 RenderViewImplParams
params(opener_id
,
933 window_was_created_with_opener
,
937 main_frame_routing_id
,
939 session_storage_namespace_id
,
948 RenderViewImpl
* render_view
= NULL
;
949 if (g_create_render_view_impl
)
950 render_view
= g_create_render_view_impl(¶ms
);
952 render_view
= new RenderViewImpl(¶ms
);
954 RenderFrameImpl
* main_frame
= RenderFrameImpl::Create(
955 render_view
, main_frame_routing_id
);
956 // The main frame WebLocalFrame object is closed by
957 // RenderFrameImpl::frameDetached().
958 WebLocalFrame
* web_frame
= WebLocalFrame::create(main_frame
);
959 main_frame
->SetWebFrame(web_frame
);
961 render_view
->Initialize(¶ms
, main_frame
);
966 void RenderViewImpl::InstallCreateHook(
967 RenderViewImpl
* (*create_render_view_impl
)(RenderViewImplParams
*)) {
968 CHECK(!g_create_render_view_impl
);
969 g_create_render_view_impl
= create_render_view_impl
;
972 void RenderViewImpl::AddObserver(RenderViewObserver
* observer
) {
973 observers_
.AddObserver(observer
);
976 void RenderViewImpl::RemoveObserver(RenderViewObserver
* observer
) {
977 observer
->RenderViewGone();
978 observers_
.RemoveObserver(observer
);
981 blink::WebView
* RenderViewImpl::webview() const {
982 return static_cast<blink::WebView
*>(webwidget());
985 #if defined(ENABLE_PLUGINS)
986 void RenderViewImpl::PepperInstanceCreated(
987 PepperPluginInstanceImpl
* instance
) {
988 active_pepper_instances_
.insert(instance
);
991 void RenderViewImpl::PepperInstanceDeleted(
992 PepperPluginInstanceImpl
* instance
) {
993 active_pepper_instances_
.erase(instance
);
995 if (pepper_last_mouse_event_target_
== instance
)
996 pepper_last_mouse_event_target_
= NULL
;
997 if (focused_pepper_plugin_
== instance
)
998 PepperFocusChanged(instance
, false);
1001 void RenderViewImpl::PepperFocusChanged(PepperPluginInstanceImpl
* instance
,
1004 focused_pepper_plugin_
= instance
;
1005 else if (focused_pepper_plugin_
== instance
)
1006 focused_pepper_plugin_
= NULL
;
1008 UpdateTextInputType();
1009 UpdateSelectionBounds();
1012 void RenderViewImpl::RegisterPluginDelegate(WebPluginDelegateProxy
* delegate
) {
1013 plugin_delegates_
.insert(delegate
);
1014 // If the renderer is visible, set initial visibility and focus state.
1016 #if defined(OS_MACOSX)
1017 delegate
->SetContainerVisibility(true);
1018 if (webview() && webview()->isActive())
1019 delegate
->SetWindowFocus(true);
1022 // Plugins start assuming the content has focus (so that they work in
1023 // environments where RenderView isn't hosting them), so we always have to
1024 // set the initial state. See webplugin_delegate_impl.h for details.
1025 delegate
->SetContentAreaFocus(has_focus());
1028 void RenderViewImpl::UnregisterPluginDelegate(
1029 WebPluginDelegateProxy
* delegate
) {
1030 plugin_delegates_
.erase(delegate
);
1034 void RenderViewImpl::PluginFocusChanged(bool focused
, int plugin_id
) {
1036 focused_plugin_id_
= plugin_id
;
1038 focused_plugin_id_
= -1;
1042 #if defined(OS_MACOSX)
1043 void RenderViewImpl::PluginFocusChanged(bool focused
, int plugin_id
) {
1044 Send(new ViewHostMsg_PluginFocusChanged(routing_id(), focused
, plugin_id
));
1047 void RenderViewImpl::StartPluginIme() {
1048 IPC::Message
* msg
= new ViewHostMsg_StartPluginIme(routing_id());
1049 // This message can be sent during event-handling, and needs to be delivered
1050 // within that context.
1051 msg
->set_unblock(true);
1054 #endif // defined(OS_MACOSX)
1056 #endif // ENABLE_PLUGINS
1058 void RenderViewImpl::TransferActiveWheelFlingAnimation(
1059 const blink::WebActiveWheelFlingParameters
& params
) {
1061 webview()->transferActiveWheelFlingAnimation(params
);
1064 bool RenderViewImpl::HasIMETextFocus() {
1065 return GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE
;
1068 bool RenderViewImpl::OnMessageReceived(const IPC::Message
& message
) {
1069 WebFrame
* main_frame
= webview() ? webview()->mainFrame() : NULL
;
1071 GetContentClient()->SetActiveURL(main_frame
->document().url());
1073 ObserverListBase
<RenderViewObserver
>::Iterator
it(observers_
);
1074 RenderViewObserver
* observer
;
1075 while ((observer
= it
.GetNext()) != NULL
)
1076 if (observer
->OnMessageReceived(message
))
1079 bool handled
= true;
1080 bool msg_is_ok
= true;
1081 IPC_BEGIN_MESSAGE_MAP_EX(RenderViewImpl
, message
, msg_is_ok
)
1082 IPC_MESSAGE_HANDLER(InputMsg_ExecuteEditCommand
, OnExecuteEditCommand
)
1083 IPC_MESSAGE_HANDLER(InputMsg_MoveCaret
, OnMoveCaret
)
1084 IPC_MESSAGE_HANDLER(InputMsg_ScrollFocusedEditableNodeIntoRect
,
1085 OnScrollFocusedEditableNodeIntoRect
)
1086 IPC_MESSAGE_HANDLER(InputMsg_SetEditCommandsForNextKeyEvent
,
1087 OnSetEditCommandsForNextKeyEvent
)
1088 IPC_MESSAGE_HANDLER(FrameMsg_Navigate
, OnNavigate
)
1089 IPC_MESSAGE_HANDLER(ViewMsg_Stop
, OnStop
)
1090 IPC_MESSAGE_HANDLER(ViewMsg_SetName
, OnSetName
)
1091 IPC_MESSAGE_HANDLER(ViewMsg_CopyImageAt
, OnCopyImageAt
)
1092 IPC_MESSAGE_HANDLER(ViewMsg_Find
, OnFind
)
1093 IPC_MESSAGE_HANDLER(ViewMsg_StopFinding
, OnStopFinding
)
1094 IPC_MESSAGE_HANDLER(ViewMsg_Zoom
, OnZoom
)
1095 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevel
, OnSetZoomLevel
)
1096 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForLoadingURL
,
1097 OnSetZoomLevelForLoadingURL
)
1098 IPC_MESSAGE_HANDLER(ViewMsg_SetPageEncoding
, OnSetPageEncoding
)
1099 IPC_MESSAGE_HANDLER(ViewMsg_ResetPageEncodingToDefault
,
1100 OnResetPageEncodingToDefault
)
1101 IPC_MESSAGE_HANDLER(ViewMsg_PostMessageEvent
, OnPostMessageEvent
)
1102 IPC_MESSAGE_HANDLER(DragMsg_TargetDragEnter
, OnDragTargetDragEnter
)
1103 IPC_MESSAGE_HANDLER(DragMsg_TargetDragOver
, OnDragTargetDragOver
)
1104 IPC_MESSAGE_HANDLER(DragMsg_TargetDragLeave
, OnDragTargetDragLeave
)
1105 IPC_MESSAGE_HANDLER(DragMsg_TargetDrop
, OnDragTargetDrop
)
1106 IPC_MESSAGE_HANDLER(DragMsg_SourceEnded
, OnDragSourceEnded
)
1107 IPC_MESSAGE_HANDLER(DragMsg_SourceSystemDragEnded
,
1108 OnDragSourceSystemDragEnded
)
1109 IPC_MESSAGE_HANDLER(ViewMsg_AllowBindings
, OnAllowBindings
)
1110 IPC_MESSAGE_HANDLER(ViewMsg_SetInitialFocus
, OnSetInitialFocus
)
1111 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTargetURL_ACK
, OnUpdateTargetURLAck
)
1112 IPC_MESSAGE_HANDLER(ViewMsg_UpdateWebPreferences
, OnUpdateWebPreferences
)
1113 IPC_MESSAGE_HANDLER(ViewMsg_EnumerateDirectoryResponse
,
1114 OnEnumerateDirectoryResponse
)
1115 IPC_MESSAGE_HANDLER(ViewMsg_RunFileChooserResponse
, OnFileChooserResponse
)
1116 IPC_MESSAGE_HANDLER(ViewMsg_SuppressDialogsUntilSwapOut
,
1117 OnSuppressDialogsUntilSwapOut
)
1118 IPC_MESSAGE_HANDLER(ViewMsg_ClosePage
, OnClosePage
)
1119 IPC_MESSAGE_HANDLER(ViewMsg_ThemeChanged
, OnThemeChanged
)
1120 IPC_MESSAGE_HANDLER(ViewMsg_MoveOrResizeStarted
, OnMoveOrResizeStarted
)
1121 IPC_MESSAGE_HANDLER(ViewMsg_ClearFocusedElement
, OnClearFocusedElement
)
1122 IPC_MESSAGE_HANDLER(ViewMsg_SetBackground
, OnSetBackground
)
1123 IPC_MESSAGE_HANDLER(ViewMsg_EnablePreferredSizeChangedMode
,
1124 OnEnablePreferredSizeChangedMode
)
1125 IPC_MESSAGE_HANDLER(ViewMsg_EnableAutoResize
, OnEnableAutoResize
)
1126 IPC_MESSAGE_HANDLER(ViewMsg_DisableAutoResize
, OnDisableAutoResize
)
1127 IPC_MESSAGE_HANDLER(ViewMsg_DisableScrollbarsForSmallWindows
,
1128 OnDisableScrollbarsForSmallWindows
)
1129 IPC_MESSAGE_HANDLER(ViewMsg_SetRendererPrefs
, OnSetRendererPrefs
)
1130 IPC_MESSAGE_HANDLER(ViewMsg_MediaPlayerActionAt
, OnMediaPlayerActionAt
)
1131 IPC_MESSAGE_HANDLER(ViewMsg_OrientationChangeEvent
,
1132 OnOrientationChangeEvent
)
1133 IPC_MESSAGE_HANDLER(ViewMsg_PluginActionAt
, OnPluginActionAt
)
1134 IPC_MESSAGE_HANDLER(ViewMsg_SetActive
, OnSetActive
)
1135 IPC_MESSAGE_HANDLER(ViewMsg_GetAllSavableResourceLinksForCurrentPage
,
1136 OnGetAllSavableResourceLinksForCurrentPage
)
1137 IPC_MESSAGE_HANDLER(
1138 ViewMsg_GetSerializedHtmlDataForCurrentPageWithLocalLinks
,
1139 OnGetSerializedHtmlDataForCurrentPageWithLocalLinks
)
1140 IPC_MESSAGE_HANDLER(ViewMsg_ShowContextMenu
, OnShowContextMenu
)
1141 // TODO(viettrungluu): Move to a separate message filter.
1142 IPC_MESSAGE_HANDLER(ViewMsg_SetHistoryLengthAndPrune
,
1143 OnSetHistoryLengthAndPrune
)
1144 IPC_MESSAGE_HANDLER(ViewMsg_EnableViewSourceMode
, OnEnableViewSourceMode
)
1145 IPC_MESSAGE_HANDLER(ViewMsg_SetAccessibilityMode
, OnSetAccessibilityMode
)
1146 IPC_MESSAGE_HANDLER(ViewMsg_DisownOpener
, OnDisownOpener
)
1147 IPC_MESSAGE_HANDLER(ViewMsg_ReleaseDisambiguationPopupDIB
,
1148 OnReleaseDisambiguationPopupDIB
)
1149 IPC_MESSAGE_HANDLER(ViewMsg_WindowSnapshotCompleted
,
1150 OnWindowSnapshotCompleted
)
1151 #if defined(OS_ANDROID)
1152 IPC_MESSAGE_HANDLER(InputMsg_ActivateNearestFindResult
,
1153 OnActivateNearestFindResult
)
1154 IPC_MESSAGE_HANDLER(ViewMsg_FindMatchRects
, OnFindMatchRects
)
1155 IPC_MESSAGE_HANDLER(ViewMsg_SelectPopupMenuItems
, OnSelectPopupMenuItems
)
1156 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTopControlsState
,
1157 OnUpdateTopControlsState
)
1158 IPC_MESSAGE_HANDLER(ViewMsg_PauseVideo
, OnPauseVideo
)
1159 IPC_MESSAGE_HANDLER(ViewMsg_ExtractSmartClipData
, OnExtractSmartClipData
)
1160 #elif defined(OS_MACOSX)
1161 IPC_MESSAGE_HANDLER(ViewMsg_PluginImeCompositionCompleted
,
1162 OnPluginImeCompositionCompleted
)
1163 IPC_MESSAGE_HANDLER(ViewMsg_SelectPopupMenuItem
, OnSelectPopupMenuItem
)
1164 IPC_MESSAGE_HANDLER(ViewMsg_SetInLiveResize
, OnSetInLiveResize
)
1165 IPC_MESSAGE_HANDLER(ViewMsg_SetWindowVisibility
, OnSetWindowVisibility
)
1166 IPC_MESSAGE_HANDLER(ViewMsg_WindowFrameChanged
, OnWindowFrameChanged
)
1168 // Adding a new message? Add platform independent ones first, then put the
1169 // platform specific ones at the end.
1171 // Have the super handle all other messages.
1172 IPC_MESSAGE_UNHANDLED(handled
= RenderWidget::OnMessageReceived(message
))
1173 IPC_END_MESSAGE_MAP()
1176 // The message had a handler, but its deserialization failed.
1177 // Kill the renderer to avoid potential spoofing attacks.
1178 CHECK(false) << "Unable to deserialize message in RenderViewImpl.";
1184 void RenderViewImpl::OnNavigate(const FrameMsg_Navigate_Params
& params
) {
1185 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, Navigate(params
.url
));
1188 bool RenderViewImpl::IsBackForwardToStaleEntry(
1189 const FrameMsg_Navigate_Params
& params
,
1191 // Make sure this isn't a back/forward to an entry we have already cropped
1192 // or replaced from our history, before the browser knew about it. If so,
1193 // a new navigation has committed in the mean time, and we can ignore this.
1194 bool is_back_forward
= !is_reload
&& params
.page_state
.IsValid();
1196 // Note: if the history_list_length_ is 0 for a back/forward, we must be
1197 // restoring from a previous session. We'll update our state in OnNavigate.
1198 if (!is_back_forward
|| history_list_length_
<= 0)
1201 DCHECK_EQ(static_cast<int>(history_page_ids_
.size()), history_list_length_
);
1203 // Check for whether the forward history has been cropped due to a recent
1204 // navigation the browser didn't know about.
1205 if (params
.pending_history_list_offset
>= history_list_length_
)
1208 // Check for whether this entry has been replaced with a new one.
1209 int expected_page_id
=
1210 history_page_ids_
[params
.pending_history_list_offset
];
1211 if (expected_page_id
> 0 && params
.page_id
!= expected_page_id
) {
1212 if (params
.page_id
< expected_page_id
)
1215 // Otherwise we've removed an earlier entry and should have shifted all
1216 // entries left. For now, it's ok to lazily update the list.
1217 // TODO(creis): Notify all live renderers when we remove entries from
1218 // the front of the list, so that we don't hit this case.
1219 history_page_ids_
[params
.pending_history_list_offset
] = params
.page_id
;
1225 // Stop loading the current page.
1226 void RenderViewImpl::OnStop() {
1228 webview()->mainFrame()->stopLoading();
1229 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, OnStop());
1230 main_render_frame_
->OnStop();
1233 void RenderViewImpl::OnCopyImageAt(int x
, int y
) {
1234 webview()->copyImageAt(WebPoint(x
, y
));
1237 void RenderViewImpl::OnUpdateTargetURLAck() {
1238 // Check if there is a targeturl waiting to be sent.
1239 if (target_url_status_
== TARGET_PENDING
) {
1240 Send(new ViewHostMsg_UpdateTargetURL(routing_id_
, page_id_
,
1241 pending_target_url_
));
1244 target_url_status_
= TARGET_NONE
;
1247 void RenderViewImpl::OnExecuteEditCommand(const std::string
& name
,
1248 const std::string
& value
) {
1249 if (!webview() || !webview()->focusedFrame())
1252 webview()->focusedFrame()->executeCommand(
1253 WebString::fromUTF8(name
), WebString::fromUTF8(value
));
1256 void RenderViewImpl::OnMoveCaret(const gfx::Point
& point
) {
1260 Send(new ViewHostMsg_MoveCaret_ACK(routing_id_
));
1262 webview()->focusedFrame()->moveCaretSelection(point
);
1265 void RenderViewImpl::OnScrollFocusedEditableNodeIntoRect(
1266 const gfx::Rect
& rect
) {
1267 if (has_scrolled_focused_editable_node_into_rect_
&&
1268 rect
== rect_for_scrolled_focused_editable_node_
) {
1272 blink::WebElement element
= GetFocusedElement();
1273 if (!element
.isNull() && IsEditableNode(element
)) {
1274 rect_for_scrolled_focused_editable_node_
= rect
;
1275 has_scrolled_focused_editable_node_into_rect_
= true;
1276 webview()->scrollFocusedNodeIntoRect(rect
);
1280 void RenderViewImpl::OnSetEditCommandsForNextKeyEvent(
1281 const EditCommands
& edit_commands
) {
1282 edit_commands_
= edit_commands
;
1285 void RenderViewImpl::OnSetName(const std::string
& name
) {
1289 webview()->mainFrame()->setName(WebString::fromUTF8(name
));
1292 void RenderViewImpl::OnSetHistoryLengthAndPrune(int history_length
,
1293 int32 minimum_page_id
) {
1294 DCHECK_GE(history_length
, 0);
1295 DCHECK(history_list_offset_
== history_list_length_
- 1);
1296 DCHECK_GE(minimum_page_id
, -1);
1298 // Generate the new list.
1299 std::vector
<int32
> new_history_page_ids(history_length
, -1);
1300 for (size_t i
= 0; i
< history_page_ids_
.size(); ++i
) {
1301 if (minimum_page_id
>= 0 && history_page_ids_
[i
] < minimum_page_id
)
1303 new_history_page_ids
.push_back(history_page_ids_
[i
]);
1305 new_history_page_ids
.swap(history_page_ids_
);
1308 history_list_length_
= history_page_ids_
.size();
1309 history_list_offset_
= history_list_length_
- 1;
1313 void RenderViewImpl::OnSetInitialFocus(bool reverse
) {
1316 webview()->setInitialFocus(reverse
);
1319 #if defined(OS_MACOSX)
1320 void RenderViewImpl::OnSetInLiveResize(bool in_live_resize
) {
1324 webview()->willStartLiveResize();
1326 webview()->willEndLiveResize();
1330 #if defined(OS_ANDROID)
1331 void RenderViewImpl::OnPauseVideo() {
1332 // Inform RendererMediaPlayerManager to release all video player resources.
1333 // If something is in progress the resource will not be freed, it will
1334 // only be freed once the tab is destroyed or if the user navigates away
1335 // via WebMediaPlayerAndroid::Destroy.
1336 media_player_manager_
->ReleaseVideoResources();
1340 ///////////////////////////////////////////////////////////////////////////////
1342 // Tell the embedding application that the title of the active page has changed
1343 void RenderViewImpl::UpdateTitle(WebFrame
* frame
,
1344 const base::string16
& title
,
1345 WebTextDirection title_direction
) {
1346 // Ignore all but top level navigations.
1347 if (frame
->parent())
1350 base::debug::TraceLog::GetInstance()->UpdateProcessLabel(
1351 routing_id_
, base::UTF16ToUTF8(title
));
1353 base::string16 shortened_title
= title
.substr(0, kMaxTitleChars
);
1354 Send(new ViewHostMsg_UpdateTitle(routing_id_
, page_id_
, shortened_title
,
1358 void RenderViewImpl::UpdateEncoding(WebFrame
* frame
,
1359 const std::string
& encoding_name
) {
1360 // Only update main frame's encoding_name.
1361 if (webview()->mainFrame() == frame
&&
1362 last_encoding_name_
!= encoding_name
) {
1363 // Save the encoding name for later comparing.
1364 last_encoding_name_
= encoding_name
;
1366 Send(new ViewHostMsg_UpdateEncoding(routing_id_
, last_encoding_name_
));
1370 // Sends the last committed session history state to the browser so it will be
1371 // saved before we navigate to a new page. This must be called *before* the
1372 // page ID has been updated so we know what it was.
1373 void RenderViewImpl::UpdateSessionHistory(WebFrame
* frame
) {
1374 // If we have a valid page ID at this point, then it corresponds to the page
1375 // we are navigating away from. Otherwise, this is the first navigation, so
1376 // there is no past session history to record.
1380 WebHistoryItem item
= history_controller_
->GetPreviousItemForExport();
1381 SendUpdateState(item
);
1384 void RenderViewImpl::SendUpdateState(const WebHistoryItem
& item
) {
1388 // Don't send state updates for kSwappedOutURL.
1389 if (item
.urlString() == WebString::fromUTF8(kSwappedOutURL
))
1392 Send(new ViewHostMsg_UpdateState(
1393 routing_id_
, page_id_
, HistoryItemToPageState(item
)));
1396 // WebViewDelegate ------------------------------------------------------------
1398 void RenderViewImpl::LoadNavigationErrorPage(
1400 const WebURLRequest
& failed_request
,
1401 const WebURLError
& error
,
1403 std::string error_html
;
1404 GetContentClient()->renderer()->GetNavigationErrorStrings(
1405 this, frame
, failed_request
, error
, &error_html
, NULL
);
1407 frame
->loadHTMLString(error_html
,
1408 GURL(kUnreachableWebDataURL
),
1409 error
.unreachableURL
,
1413 bool RenderViewImpl::SendAndRunNestedMessageLoop(IPC::SyncMessage
* message
) {
1414 // Before WebKit asks us to show an alert (etc.), it takes care of doing the
1415 // equivalent of WebView::willEnterModalLoop. In the case of showModalDialog
1416 // it is particularly important that we do not call willEnterModalLoop as
1417 // that would defer resource loads for the dialog itself.
1418 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
1419 RenderThreadImpl::current()->DoNotNotifyWebKitOfModalLoop();
1421 message
->EnableMessagePumping(); // Runs a nested message loop.
1422 return Send(message
);
1425 void RenderViewImpl::GetWindowSnapshot(const WindowSnapshotCallback
& callback
) {
1426 int id
= next_snapshot_id_
++;
1427 pending_snapshots_
.insert(std::make_pair(id
, callback
));
1428 ui::LatencyInfo latency_info
;
1429 latency_info
.AddLatencyNumber(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT
,
1432 scoped_ptr
<cc::SwapPromiseMonitor
> latency_info_swap_promise_monitor
;
1433 if (RenderWidgetCompositor
* rwc
= compositor()) {
1434 latency_info_swap_promise_monitor
=
1435 rwc
->CreateLatencyInfoSwapPromiseMonitor(&latency_info
).Pass();
1437 latency_info_
.push_back(latency_info
);
1439 ScheduleCompositeWithForcedRedraw();
1442 void RenderViewImpl::OnWindowSnapshotCompleted(const int snapshot_id
,
1443 const gfx::Size
& size
, const std::vector
<unsigned char>& png
) {
1445 // Any pending snapshots with a lower ID than the one received are considered
1446 // to be implicitly complete, and returned the same snapshot data.
1447 PendingSnapshotMap::iterator it
= pending_snapshots_
.begin();
1448 while(it
!= pending_snapshots_
.end()) {
1449 if (it
->first
<= snapshot_id
) {
1450 it
->second
.Run(size
, png
);
1451 pending_snapshots_
.erase(it
++);
1458 // blink::WebViewClient ------------------------------------------------------
1460 WebView
* RenderViewImpl::createView(WebLocalFrame
* creator
,
1461 const WebURLRequest
& request
,
1462 const WebWindowFeatures
& features
,
1463 const WebString
& frame_name
,
1464 WebNavigationPolicy policy
,
1465 bool suppress_opener
) {
1466 ViewHostMsg_CreateWindow_Params params
;
1467 params
.opener_id
= routing_id_
;
1468 params
.user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
1469 if (GetContentClient()->renderer()->AllowPopup())
1470 params
.user_gesture
= true;
1471 params
.window_container_type
= WindowFeaturesToContainerType(features
);
1472 params
.session_storage_namespace_id
= session_storage_namespace_id_
;
1473 if (frame_name
!= "_blank")
1474 params
.frame_name
= frame_name
;
1475 params
.opener_render_frame_id
=
1476 RenderFrameImpl::FromWebFrame(creator
)->GetRoutingID();
1477 params
.opener_url
= creator
->document().url();
1478 params
.opener_top_level_frame_url
= creator
->top()->document().url();
1479 GURL
security_url(creator
->document().securityOrigin().toString());
1480 if (!security_url
.is_valid())
1481 security_url
= GURL();
1482 params
.opener_security_origin
= security_url
;
1483 params
.opener_suppressed
= suppress_opener
;
1484 params
.disposition
= NavigationPolicyToDisposition(policy
);
1485 if (!request
.isNull()) {
1486 params
.target_url
= request
.url();
1487 params
.referrer
= GetReferrerFromRequest(creator
, request
);
1489 params
.features
= features
;
1491 for (size_t i
= 0; i
< features
.additionalFeatures
.size(); ++i
)
1492 params
.additional_features
.push_back(features
.additionalFeatures
[i
]);
1494 int32 routing_id
= MSG_ROUTING_NONE
;
1495 int32 main_frame_routing_id
= MSG_ROUTING_NONE
;
1496 int32 surface_id
= 0;
1497 int64 cloned_session_storage_namespace_id
;
1499 RenderThread::Get()->Send(
1500 new ViewHostMsg_CreateWindow(params
,
1502 &main_frame_routing_id
,
1504 &cloned_session_storage_namespace_id
));
1505 if (routing_id
== MSG_ROUTING_NONE
)
1508 WebUserGestureIndicator::consumeUserGesture();
1510 // While this view may be a background extension page, it can spawn a visible
1511 // render view. So we just assume that the new one is not another background
1512 // page instead of passing on our own value.
1513 // TODO(vangelis): Can we tell if the new view will be a background page?
1514 bool never_visible
= false;
1516 // The initial hidden state for the RenderViewImpl here has to match what the
1517 // browser will eventually decide for the given disposition. Since we have to
1518 // return from this call synchronously, we just have to make our best guess
1519 // and rely on the browser sending a WasHidden / WasShown message if it
1521 RenderViewImpl
* view
= RenderViewImpl::Create(
1523 true, // window_was_created_with_opener
1524 renderer_preferences_
,
1525 webkit_preferences_
,
1527 main_frame_routing_id
,
1529 cloned_session_storage_namespace_id
,
1530 base::string16(), // WebCore will take care of setting the correct name.
1531 true, // is_renderer_created
1532 false, // swapped_out
1533 params
.disposition
== NEW_BACKGROUND_TAB
, // hidden
1537 accessibility_mode_
);
1538 view
->opened_by_user_gesture_
= params
.user_gesture
;
1540 // Record whether the creator frame is trying to suppress the opener field.
1541 view
->opener_suppressed_
= params
.opener_suppressed
;
1543 return view
->webview();
1546 WebWidget
* RenderViewImpl::createPopupMenu(blink::WebPopupType popup_type
) {
1547 RenderWidget
* widget
=
1548 RenderWidget::Create(routing_id_
, popup_type
, screen_info_
);
1551 if (screen_metrics_emulator_
) {
1552 widget
->SetPopupOriginAdjustmentsForEmulation(
1553 screen_metrics_emulator_
.get());
1555 return widget
->webwidget();
1558 WebExternalPopupMenu
* RenderViewImpl::createExternalPopupMenu(
1559 const WebPopupMenuInfo
& popup_menu_info
,
1560 WebExternalPopupMenuClient
* popup_menu_client
) {
1561 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1562 // An IPC message is sent to the browser to build and display the actual
1563 // popup. The user could have time to click a different select by the time
1564 // the popup is shown. In that case external_popup_menu_ is non NULL.
1565 // By returning NULL in that case, we instruct WebKit to cancel that new
1566 // popup. So from the user perspective, only the first one will show, and
1567 // will have to close the first one before another one can be shown.
1568 if (external_popup_menu_
)
1570 external_popup_menu_
.reset(
1571 new ExternalPopupMenu(this, popup_menu_info
, popup_menu_client
));
1572 if (screen_metrics_emulator_
) {
1573 SetExternalPopupOriginAdjustmentsForEmulation(
1574 external_popup_menu_
.get(), screen_metrics_emulator_
.get());
1576 return external_popup_menu_
.get();
1582 WebStorageNamespace
* RenderViewImpl::createSessionStorageNamespace() {
1583 CHECK(session_storage_namespace_id_
!= kInvalidSessionStorageNamespaceId
);
1584 return new WebStorageNamespaceImpl(session_storage_namespace_id_
);
1587 void RenderViewImpl::printPage(WebLocalFrame
* frame
) {
1588 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
,
1589 PrintPage(frame
, handling_input_event_
));
1592 blink::WebNotificationPresenter
* RenderViewImpl::notificationPresenter() {
1593 return notification_provider_
;
1596 bool RenderViewImpl::enumerateChosenDirectory(
1597 const WebString
& path
,
1598 WebFileChooserCompletion
* chooser_completion
) {
1599 int id
= enumeration_completion_id_
++;
1600 enumeration_completions_
[id
] = chooser_completion
;
1601 return Send(new ViewHostMsg_EnumerateDirectory(
1604 base::FilePath::FromUTF16Unsafe(path
)));
1607 void RenderViewImpl::FrameDidStartLoading(WebFrame
* frame
) {
1608 if (load_progress_tracker_
!= NULL
) {
1609 load_progress_tracker_
->DidStartLoading(
1610 RenderFrameImpl::FromWebFrame(frame
)->GetRoutingID());
1612 DCHECK_GE(frames_in_progress_
, 0);
1613 if (frames_in_progress_
== 0)
1614 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidStartLoading());
1615 frames_in_progress_
++;
1618 void RenderViewImpl::FrameDidStopLoading(WebFrame
* frame
) {
1619 if (load_progress_tracker_
!= NULL
) {
1620 load_progress_tracker_
->DidStopLoading(
1621 RenderFrameImpl::FromWebFrame(frame
)->GetRoutingID());
1623 // TODO(japhet): This should be a DCHECK, but the pdf plugin sometimes
1624 // calls DidStopLoading() without a matching DidStartLoading().
1625 if (frames_in_progress_
== 0)
1627 frames_in_progress_
--;
1628 if (frames_in_progress_
== 0) {
1629 DidStopLoadingIcons();
1630 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidStopLoading());
1634 void RenderViewImpl::FrameDidChangeLoadProgress(WebFrame
* frame
,
1635 double load_progress
) {
1636 if (load_progress_tracker_
!= NULL
) {
1637 load_progress_tracker_
->DidChangeLoadProgress(
1638 RenderFrameImpl::FromWebFrame(frame
)->GetRoutingID(), load_progress
);
1642 void RenderViewImpl::didCancelCompositionOnSelectionChange() {
1643 Send(new ViewHostMsg_ImeCancelComposition(routing_id()));
1646 void RenderViewImpl::didExecuteCommand(const WebString
& command_name
) {
1647 const std::string
& name
= base::UTF16ToUTF8(command_name
);
1648 if (StartsWithASCII(name
, "Move", true) ||
1649 StartsWithASCII(name
, "Insert", true) ||
1650 StartsWithASCII(name
, "Delete", true))
1652 RenderThreadImpl::current()->RecordComputedAction(name
);
1655 bool RenderViewImpl::handleCurrentKeyboardEvent() {
1656 if (edit_commands_
.empty())
1659 WebFrame
* frame
= webview()->focusedFrame();
1663 EditCommands::iterator it
= edit_commands_
.begin();
1664 EditCommands::iterator end
= edit_commands_
.end();
1666 bool did_execute_command
= false;
1667 for (; it
!= end
; ++it
) {
1668 // In gtk and cocoa, it's possible to bind multiple edit commands to one
1669 // key (but it's the exception). Once one edit command is not executed, it
1670 // seems safest to not execute the rest.
1671 if (!frame
->executeCommand(WebString::fromUTF8(it
->name
),
1672 WebString::fromUTF8(it
->value
),
1673 GetFocusedElement()))
1675 did_execute_command
= true;
1678 return did_execute_command
;
1681 bool RenderViewImpl::runFileChooser(
1682 const blink::WebFileChooserParams
& params
,
1683 WebFileChooserCompletion
* chooser_completion
) {
1684 // Do not open the file dialog in a hidden RenderView.
1687 FileChooserParams ipc_params
;
1688 if (params
.directory
)
1689 ipc_params
.mode
= FileChooserParams::UploadFolder
;
1690 else if (params
.multiSelect
)
1691 ipc_params
.mode
= FileChooserParams::OpenMultiple
;
1692 else if (params
.saveAs
)
1693 ipc_params
.mode
= FileChooserParams::Save
;
1695 ipc_params
.mode
= FileChooserParams::Open
;
1696 ipc_params
.title
= params
.title
;
1697 ipc_params
.default_file_name
=
1698 base::FilePath::FromUTF16Unsafe(params
.initialValue
);
1699 ipc_params
.accept_types
.reserve(params
.acceptTypes
.size());
1700 for (size_t i
= 0; i
< params
.acceptTypes
.size(); ++i
)
1701 ipc_params
.accept_types
.push_back(params
.acceptTypes
[i
]);
1702 #if defined(OS_ANDROID)
1703 ipc_params
.capture
= params
.useMediaCapture
;
1706 return ScheduleFileChooser(ipc_params
, chooser_completion
);
1709 void RenderViewImpl::showValidationMessage(
1710 const blink::WebRect
& anchor_in_root_view
,
1711 const blink::WebString
& main_text
,
1712 const blink::WebString
& sub_text
,
1713 blink::WebTextDirection hint
) {
1714 base::string16 wrapped_main_text
= main_text
;
1715 base::string16 wrapped_sub_text
= sub_text
;
1716 if (hint
== blink::WebTextDirectionLeftToRight
) {
1718 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_main_text
);
1719 if (!wrapped_sub_text
.empty()) {
1721 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_sub_text
);
1723 } else if (hint
== blink::WebTextDirectionRightToLeft
1724 && !base::i18n::IsRTL()) {
1725 base::i18n::WrapStringWithRTLFormatting(&wrapped_main_text
);
1726 if (!wrapped_sub_text
.empty()) {
1727 base::i18n::WrapStringWithRTLFormatting(&wrapped_sub_text
);
1730 Send(new ViewHostMsg_ShowValidationMessage(
1731 routing_id(), anchor_in_root_view
, wrapped_main_text
, wrapped_sub_text
));
1734 void RenderViewImpl::hideValidationMessage() {
1735 Send(new ViewHostMsg_HideValidationMessage(routing_id()));
1738 void RenderViewImpl::moveValidationMessage(
1739 const blink::WebRect
& anchor_in_root_view
) {
1740 Send(new ViewHostMsg_MoveValidationMessage(routing_id(),
1741 anchor_in_root_view
));
1744 void RenderViewImpl::setStatusText(const WebString
& text
) {
1747 void RenderViewImpl::UpdateTargetURL(const GURL
& url
,
1748 const GURL
& fallback_url
) {
1749 GURL latest_url
= url
.is_empty() ? fallback_url
: url
;
1750 if (latest_url
== target_url_
)
1753 // Tell the browser to display a destination link.
1754 if (target_url_status_
== TARGET_INFLIGHT
||
1755 target_url_status_
== TARGET_PENDING
) {
1756 // If we have a request in-flight, save the URL to be sent when we
1757 // receive an ACK to the in-flight request. We can happily overwrite
1758 // any existing pending sends.
1759 pending_target_url_
= latest_url
;
1760 target_url_status_
= TARGET_PENDING
;
1762 // URLs larger than |MaxURLChars()| cannot be sent through IPC -
1763 // see |ParamTraits<GURL>|.
1764 if (latest_url
.possibly_invalid_spec().size() > GetMaxURLChars())
1765 latest_url
= GURL();
1766 Send(new ViewHostMsg_UpdateTargetURL(routing_id_
, page_id_
, latest_url
));
1767 target_url_
= latest_url
;
1768 target_url_status_
= TARGET_INFLIGHT
;
1772 gfx::RectF
RenderViewImpl::ClientRectToPhysicalWindowRect(
1773 const gfx::RectF
& rect
) const {
1774 gfx::RectF window_rect
= rect
;
1775 window_rect
.Scale(device_scale_factor_
* webview()->pageScaleFactor());
1779 void RenderViewImpl::StartNavStateSyncTimerIfNecessary() {
1780 // No need to update state if no page has committed yet.
1785 if (send_content_state_immediately_
)
1787 else if (is_hidden())
1788 delay
= kDelaySecondsForContentStateSyncHidden
;
1790 delay
= kDelaySecondsForContentStateSync
;
1792 if (nav_state_sync_timer_
.IsRunning()) {
1793 // The timer is already running. If the delay of the timer maches the amount
1794 // we want to delay by, then return. Otherwise stop the timer so that it
1795 // gets started with the right delay.
1796 if (nav_state_sync_timer_
.GetCurrentDelay().InSeconds() == delay
)
1798 nav_state_sync_timer_
.Stop();
1801 nav_state_sync_timer_
.Start(FROM_HERE
, TimeDelta::FromSeconds(delay
), this,
1802 &RenderViewImpl::SyncNavigationState
);
1805 void RenderViewImpl::setMouseOverURL(const WebURL
& url
) {
1806 mouse_over_url_
= GURL(url
);
1807 UpdateTargetURL(mouse_over_url_
, focus_url_
);
1810 void RenderViewImpl::setKeyboardFocusURL(const WebURL
& url
) {
1811 focus_url_
= GURL(url
);
1812 UpdateTargetURL(focus_url_
, mouse_over_url_
);
1815 void RenderViewImpl::startDragging(WebLocalFrame
* frame
,
1816 const WebDragData
& data
,
1817 WebDragOperationsMask mask
,
1818 const WebImage
& image
,
1819 const WebPoint
& webImageOffset
) {
1820 DropData
drop_data(DropDataBuilder::Build(data
));
1821 drop_data
.referrer_policy
= frame
->document().referrerPolicy();
1822 gfx::Vector2d
imageOffset(webImageOffset
.x
, webImageOffset
.y
);
1823 Send(new DragHostMsg_StartDragging(routing_id_
,
1826 image
.getSkBitmap(),
1828 possible_drag_event_info_
));
1831 bool RenderViewImpl::acceptsLoadDrops() {
1832 return renderer_preferences_
.can_accept_load_drops
;
1835 void RenderViewImpl::focusNext() {
1836 Send(new ViewHostMsg_TakeFocus(routing_id_
, false));
1839 void RenderViewImpl::focusPrevious() {
1840 Send(new ViewHostMsg_TakeFocus(routing_id_
, true));
1843 void RenderViewImpl::focusedNodeChanged(const WebNode
& node
) {
1844 has_scrolled_focused_editable_node_into_rect_
= false;
1846 Send(new ViewHostMsg_FocusedNodeChanged(routing_id_
, IsEditableNode(node
)));
1848 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, FocusedNodeChanged(node
));
1851 void RenderViewImpl::numberOfWheelEventHandlersChanged(unsigned num_handlers
) {
1852 Send(new ViewHostMsg_DidChangeNumWheelEvents(routing_id_
, num_handlers
));
1855 void RenderViewImpl::didUpdateLayout() {
1856 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidUpdateLayout());
1858 // We don't always want to set up a timer, only if we've been put in that
1859 // mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
1861 if (!send_preferred_size_changes_
|| !webview())
1864 if (check_preferred_size_timer_
.IsRunning())
1866 check_preferred_size_timer_
.Start(FROM_HERE
,
1867 TimeDelta::FromMilliseconds(0), this,
1868 &RenderViewImpl::CheckPreferredSize
);
1871 void RenderViewImpl::navigateBackForwardSoon(int offset
) {
1872 Send(new ViewHostMsg_GoToEntryAtOffset(routing_id_
, offset
));
1875 int RenderViewImpl::historyBackListCount() {
1876 return history_list_offset_
< 0 ? 0 : history_list_offset_
;
1879 int RenderViewImpl::historyForwardListCount() {
1880 return history_list_length_
- historyBackListCount() - 1;
1883 void RenderViewImpl::postAccessibilityEvent(
1884 const WebAXObject
& obj
, blink::WebAXEvent event
) {
1885 if (renderer_accessibility_
) {
1886 renderer_accessibility_
->HandleWebAccessibilityEvent(obj
, event
);
1890 void RenderViewImpl::didUpdateInspectorSetting(const WebString
& key
,
1891 const WebString
& value
) {
1892 Send(new ViewHostMsg_UpdateInspectorSetting(routing_id_
,
1897 // blink::WebWidgetClient ----------------------------------------------------
1899 void RenderViewImpl::didFocus() {
1900 // TODO(jcivelli): when https://bugs.webkit.org/show_bug.cgi?id=33389 is fixed
1901 // we won't have to test for user gesture anymore and we can
1902 // move that code back to render_widget.cc
1903 if (WebUserGestureIndicator::isProcessingUserGesture() &&
1904 !RenderThreadImpl::current()->layout_test_mode()) {
1905 Send(new ViewHostMsg_Focus(routing_id_
));
1909 void RenderViewImpl::didBlur() {
1910 // TODO(jcivelli): see TODO above in didFocus().
1911 if (WebUserGestureIndicator::isProcessingUserGesture() &&
1912 !RenderThreadImpl::current()->layout_test_mode()) {
1913 Send(new ViewHostMsg_Blur(routing_id_
));
1917 // We are supposed to get a single call to Show for a newly created RenderView
1918 // that was created via RenderViewImpl::CreateWebView. So, we wait until this
1919 // point to dispatch the ShowView message.
1921 // This method provides us with the information about how to display the newly
1922 // created RenderView (i.e., as a blocked popup or as a new tab).
1924 void RenderViewImpl::show(WebNavigationPolicy policy
) {
1926 // When supports_multiple_windows is disabled, popups are reusing
1927 // the same view. In some scenarios, this makes WebKit to call show() twice.
1928 if (webkit_preferences_
.supports_multiple_windows
)
1929 NOTREACHED() << "received extraneous Show call";
1934 DCHECK(opener_id_
!= MSG_ROUTING_NONE
);
1936 // Force new windows to a popup if they were not opened with a user gesture.
1937 if (!opened_by_user_gesture_
) {
1938 // We exempt background tabs for compat with older versions of Chrome.
1939 // TODO(darin): This seems bogus. These should have a user gesture, so
1940 // we probably don't need this check.
1941 if (policy
!= blink::WebNavigationPolicyNewBackgroundTab
)
1942 policy
= blink::WebNavigationPolicyNewPopup
;
1945 // NOTE: initial_pos_ may still have its default values at this point, but
1946 // that's okay. It'll be ignored if disposition is not NEW_POPUP, or the
1947 // browser process will impose a default position otherwise.
1948 Send(new ViewHostMsg_ShowView(opener_id_
, routing_id_
,
1949 NavigationPolicyToDisposition(policy
), initial_pos_
,
1950 opened_by_user_gesture_
));
1951 SetPendingWindowRect(initial_pos_
);
1954 void RenderViewImpl::runModal() {
1955 DCHECK(did_show_
) << "should already have shown the view";
1957 // Don't allow further dialogs if we are waiting to swap out, since the
1958 // PageGroupLoadDeferrer in our stack prevents it.
1959 if (suppress_dialogs_until_swap_out_
)
1962 // We must keep WebKit's shared timer running in this case in order to allow
1963 // showModalDialog to function properly.
1965 // TODO(darin): WebKit should really be smarter about suppressing events and
1966 // timers so that we do not need to manage the shared timer in such a heavy
1969 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
1970 RenderThreadImpl::current()->DoNotSuspendWebKitSharedTimer();
1972 SendAndRunNestedMessageLoop(new ViewHostMsg_RunModal(
1973 routing_id_
, opener_id_
));
1976 bool RenderViewImpl::enterFullScreen() {
1977 Send(new ViewHostMsg_ToggleFullscreen(routing_id_
, true));
1981 void RenderViewImpl::exitFullScreen() {
1982 Send(new ViewHostMsg_ToggleFullscreen(routing_id_
, false));
1985 bool RenderViewImpl::requestPointerLock() {
1986 return mouse_lock_dispatcher_
->LockMouse(webwidget_mouse_lock_target_
.get());
1989 void RenderViewImpl::requestPointerUnlock() {
1990 mouse_lock_dispatcher_
->UnlockMouse(webwidget_mouse_lock_target_
.get());
1993 bool RenderViewImpl::isPointerLocked() {
1994 return mouse_lock_dispatcher_
->IsMouseLockedTo(
1995 webwidget_mouse_lock_target_
.get());
1998 // FIXME: To be removed as soon as chromium and blink side changes land
1999 // didActivateCompositor with parameters is still kept in order to land
2000 // these changes s-chromium - https://codereview.chromium.org/137893025/.
2001 // s-blink - https://codereview.chromium.org/138523003/
2002 void RenderViewImpl::didActivateCompositor(int input_handler_identifier
) {
2003 #if !defined(OS_MACOSX) // many events are unhandled - http://crbug.com/138003
2004 InputHandlerManager
* input_handler_manager
=
2005 RenderThreadImpl::current()->input_handler_manager();
2006 if (input_handler_manager
) {
2007 input_handler_manager
->AddInputHandler(
2009 compositor_
->GetInputHandler(),
2014 RenderWidget::didActivateCompositor(input_handler_identifier
);
2017 void RenderViewImpl::didActivateCompositor() {
2018 #if !defined(OS_MACOSX) // many events are unhandled - http://crbug.com/138003
2019 InputHandlerManager
* input_handler_manager
=
2020 RenderThreadImpl::current()->input_handler_manager();
2021 if (input_handler_manager
) {
2022 input_handler_manager
->AddInputHandler(
2024 compositor_
->GetInputHandler(),
2029 RenderWidget::didActivateCompositor();
2032 void RenderViewImpl::didHandleGestureEvent(
2033 const WebGestureEvent
& event
,
2034 bool event_cancelled
) {
2035 RenderWidget::didHandleGestureEvent(event
, event_cancelled
);
2037 if (event
.type
!= blink::WebGestureEvent::GestureTap
)
2040 blink::WebTextInputType text_input_type
=
2041 GetWebView()->textInputInfo().type
;
2043 Send(new ViewHostMsg_FocusedNodeTouched(
2044 routing_id(), text_input_type
!= blink::WebTextInputTypeNone
));
2047 void RenderViewImpl::initializeLayerTreeView() {
2048 RenderWidget::initializeLayerTreeView();
2049 RenderWidgetCompositor
* rwc
= compositor();
2050 if (!rwc
|| !webview() || !webview()->devToolsAgent())
2052 webview()->devToolsAgent()->setLayerTreeId(rwc
->GetLayerTreeId());
2055 // blink::WebFrameClient -----------------------------------------------------
2057 blink::WebMediaPlayer
* RenderViewImpl::CreateMediaPlayer(
2058 RenderFrame
* render_frame
,
2059 blink::WebLocalFrame
* frame
,
2060 const blink::WebURL
& url
,
2061 blink::WebMediaPlayerClient
* client
) {
2063 RenderViewObserver
, observers_
, WillCreateMediaPlayer(frame
, client
));
2065 WebMediaPlayer
* player
= CreateWebMediaPlayerForMediaStream(frame
, url
,
2070 #if defined(OS_ANDROID)
2071 return CreateAndroidWebMediaPlayer(frame
, url
, client
);
2073 WebMediaPlayerParams
params(
2074 base::Bind(&ContentRendererClient::DeferMediaLoad
,
2075 base::Unretained(GetContentClient()->renderer()),
2076 static_cast<RenderFrame
*>(render_frame
)),
2077 RenderThreadImpl::current()->GetAudioRendererMixerManager()->CreateInput(
2078 routing_id_
, render_frame
->GetRoutingID()));
2079 return new WebMediaPlayerImpl(frame
, client
, AsWeakPtr(), params
);
2080 #endif // defined(OS_ANDROID)
2083 void RenderViewImpl::didAccessInitialDocument(WebLocalFrame
* frame
) {
2084 // Notify the browser process that it is no longer safe to show the pending
2085 // URL of the main frame, since a URL spoof is now possible.
2086 if (!frame
->parent() && page_id_
== -1)
2087 Send(new ViewHostMsg_DidAccessInitialDocument(routing_id_
));
2090 void RenderViewImpl::didDisownOpener(blink::WebLocalFrame
* frame
) {
2091 // We only need to notify the browser if the active, top-level frame clears
2092 // its opener. We can ignore cases where a swapped out frame clears its
2093 // opener after hearing about it from the browser, and the browser does not
2094 // (yet) care about subframe openers.
2095 if (is_swapped_out_
|| frame
->parent())
2098 // Notify WebContents and all its swapped out RenderViews.
2099 Send(new ViewHostMsg_DidDisownOpener(routing_id_
));
2102 void RenderViewImpl::frameDetached(WebFrame
* frame
) {
2103 // NOTE: We may get here for either the main frame or for subframes. The
2104 // RenderFrameImpl will be deleted immediately after this call for subframes
2105 // but not for the main frame, which is owned by |main_render_frame_|.
2107 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, FrameDetached(frame
));
2110 void RenderViewImpl::willClose(WebFrame
* frame
) {
2111 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, FrameWillClose(frame
));
2114 void RenderViewImpl::didMatchCSS(
2115 WebLocalFrame
* frame
,
2116 const WebVector
<WebString
>& newly_matching_selectors
,
2117 const WebVector
<WebString
>& stopped_matching_selectors
) {
2119 RenderViewObserver
, observers_
,
2120 DidMatchCSS(frame
, newly_matching_selectors
, stopped_matching_selectors
));
2123 void RenderViewImpl::Repaint(const gfx::Size
& size
) {
2127 void RenderViewImpl::SetEditCommandForNextKeyEvent(const std::string
& name
,
2128 const std::string
& value
) {
2129 EditCommands edit_commands
;
2130 edit_commands
.push_back(EditCommand(name
, value
));
2131 OnSetEditCommandsForNextKeyEvent(edit_commands
);
2134 void RenderViewImpl::ClearEditCommands() {
2135 edit_commands_
.clear();
2138 SSLStatus
RenderViewImpl::GetSSLStatusOfFrame(blink::WebFrame
* frame
) const {
2139 std::string security_info
;
2140 if (frame
&& frame
->dataSource())
2141 security_info
= frame
->dataSource()->response().securityInfo();
2143 SSLStatus ssl_status
;
2144 DeserializeSecurityInfo(security_info
,
2145 &ssl_status
.cert_id
,
2146 &ssl_status
.cert_status
,
2147 &ssl_status
.security_bits
,
2148 &ssl_status
.connection_status
,
2149 &ssl_status
.signed_certificate_timestamp_ids
);
2153 const std::string
& RenderViewImpl::GetAcceptLanguages() const {
2154 return renderer_preferences_
.accept_languages
;
2157 void RenderViewImpl::willSendSubmitEvent(blink::WebLocalFrame
* frame
,
2158 const blink::WebFormElement
& form
) {
2160 RenderViewObserver
, observers_
, WillSendSubmitEvent(frame
, form
));
2163 void RenderViewImpl::willSubmitForm(WebLocalFrame
* frame
,
2164 const WebFormElement
& form
) {
2166 RenderViewObserver
, observers_
, WillSubmitForm(frame
, form
));
2169 void RenderViewImpl::didCreateDataSource(WebLocalFrame
* frame
,
2170 WebDataSource
* ds
) {
2171 bool content_initiated
= !pending_navigation_params_
.get();
2173 // Make sure any previous redirect URLs end up in our new data source.
2174 if (pending_navigation_params_
.get()) {
2175 for (std::vector
<GURL
>::const_iterator i
=
2176 pending_navigation_params_
->redirects
.begin();
2177 i
!= pending_navigation_params_
->redirects
.end(); ++i
) {
2178 ds
->appendRedirect(*i
);
2182 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2183 if (!document_state
) {
2184 document_state
= new DocumentState
;
2185 ds
->setExtraData(document_state
);
2186 if (!content_initiated
)
2187 PopulateDocumentStateFromPending(document_state
);
2190 // Carry over the user agent override flag, if it exists.
2191 if (content_initiated
&& webview() && webview()->mainFrame() &&
2192 webview()->mainFrame()->dataSource()) {
2193 DocumentState
* old_document_state
=
2194 DocumentState::FromDataSource(webview()->mainFrame()->dataSource());
2195 if (old_document_state
) {
2196 InternalDocumentStateData
* internal_data
=
2197 InternalDocumentStateData::FromDocumentState(document_state
);
2198 InternalDocumentStateData
* old_internal_data
=
2199 InternalDocumentStateData::FromDocumentState(old_document_state
);
2200 internal_data
->set_is_overriding_user_agent(
2201 old_internal_data
->is_overriding_user_agent());
2205 // The rest of RenderView assumes that a WebDataSource will always have a
2206 // non-null NavigationState.
2207 if (content_initiated
) {
2208 document_state
->set_navigation_state(
2209 NavigationState::CreateContentInitiated());
2211 document_state
->set_navigation_state(CreateNavigationStateFromPending());
2212 pending_navigation_params_
.reset();
2215 // DocumentState::referred_by_prefetcher_ is true if we are
2216 // navigating from a page that used prefetching using a link on that
2217 // page. We are early enough in the request process here that we
2218 // can still see the DocumentState of the previous page and set
2219 // this value appropriately.
2220 // TODO(gavinp): catch the important case of navigation in a new
2221 // renderer process.
2223 if (WebFrame
* old_frame
= webview()->mainFrame()) {
2224 const WebURLRequest
& original_request
= ds
->originalRequest();
2225 const GURL
referrer(
2226 original_request
.httpHeaderField(WebString::fromUTF8("Referer")));
2227 if (!referrer
.is_empty() &&
2228 DocumentState::FromDataSource(
2229 old_frame
->dataSource())->was_prefetcher()) {
2230 for (; old_frame
; old_frame
= old_frame
->traverseNext(false)) {
2231 WebDataSource
* old_frame_ds
= old_frame
->dataSource();
2232 if (old_frame_ds
&& referrer
== GURL(old_frame_ds
->request().url())) {
2233 document_state
->set_was_referred_by_prefetcher(true);
2241 if (content_initiated
) {
2242 const WebURLRequest
& request
= ds
->request();
2243 switch (request
.cachePolicy()) {
2244 case WebURLRequest::UseProtocolCachePolicy
: // normal load.
2245 document_state
->set_load_type(DocumentState::LINK_LOAD_NORMAL
);
2247 case WebURLRequest::ReloadIgnoringCacheData
: // reload.
2248 document_state
->set_load_type(DocumentState::LINK_LOAD_RELOAD
);
2250 case WebURLRequest::ReturnCacheDataElseLoad
: // allow stale data.
2251 document_state
->set_load_type(
2252 DocumentState::LINK_LOAD_CACHE_STALE_OK
);
2254 case WebURLRequest::ReturnCacheDataDontLoad
: // Don't re-post.
2255 document_state
->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY
);
2261 RenderViewObserver
, observers_
, DidCreateDataSource(frame
, ds
));
2264 void RenderViewImpl::PopulateDocumentStateFromPending(
2265 DocumentState
* document_state
) {
2266 const FrameMsg_Navigate_Params
& params
= *pending_navigation_params_
.get();
2267 document_state
->set_request_time(params
.request_time
);
2269 InternalDocumentStateData
* internal_data
=
2270 InternalDocumentStateData::FromDocumentState(document_state
);
2272 if (!params
.url
.SchemeIs(kJavaScriptScheme
) &&
2273 params
.navigation_type
== FrameMsg_Navigate_Type::RESTORE
) {
2274 // We're doing a load of a page that was restored from the last session. By
2275 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
2276 // can result in stale data for pages that are set to expire. We explicitly
2277 // override that by setting the policy here so that as necessary we load
2278 // from the network.
2280 // TODO(davidben): Remove this in favor of passing a cache policy to the
2281 // loadHistoryItem call in OnNavigate. That requires not overloading
2282 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
2283 // policy based on load type, etc".
2284 internal_data
->set_cache_policy_override(
2285 WebURLRequest::UseProtocolCachePolicy
);
2288 if (IsReload(params
))
2289 document_state
->set_load_type(DocumentState::RELOAD
);
2290 else if (params
.page_state
.IsValid())
2291 document_state
->set_load_type(DocumentState::HISTORY_LOAD
);
2293 document_state
->set_load_type(DocumentState::NORMAL_LOAD
);
2295 internal_data
->set_is_overriding_user_agent(params
.is_overriding_user_agent
);
2296 internal_data
->set_must_reset_scroll_and_scale_state(
2297 params
.navigation_type
==
2298 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
);
2299 document_state
->set_can_load_local_resources(params
.can_load_local_resources
);
2302 NavigationState
* RenderViewImpl::CreateNavigationStateFromPending() {
2303 const FrameMsg_Navigate_Params
& params
= *pending_navigation_params_
.get();
2304 NavigationState
* navigation_state
= NULL
;
2306 // A navigation resulting from loading a javascript URL should not be treated
2307 // as a browser initiated event. Instead, we want it to look as if the page
2308 // initiated any load resulting from JS execution.
2309 if (!params
.url
.SchemeIs(kJavaScriptScheme
)) {
2310 navigation_state
= NavigationState::CreateBrowserInitiated(
2312 params
.pending_history_list_offset
,
2313 params
.should_clear_history_list
,
2315 navigation_state
->set_should_replace_current_entry(
2316 params
.should_replace_current_entry
);
2317 navigation_state
->set_transferred_request_child_id(
2318 params
.transferred_request_child_id
);
2319 navigation_state
->set_transferred_request_request_id(
2320 params
.transferred_request_request_id
);
2321 navigation_state
->set_allow_download(params
.allow_download
);
2322 navigation_state
->set_extra_headers(params
.extra_headers
);
2324 navigation_state
= NavigationState::CreateContentInitiated();
2326 return navigation_state
;
2329 void RenderViewImpl::ProcessViewLayoutFlags(const CommandLine
& command_line
) {
2330 bool enable_viewport
=
2331 command_line
.HasSwitch(switches::kEnableViewport
) ||
2332 command_line
.HasSwitch(switches::kEnableViewportMeta
);
2334 // If viewport tag is enabled, then the WebKit side will take care
2335 // of setting the fixed layout size and page scale limits.
2336 if (enable_viewport
)
2339 // When navigating to a new page, reset the page scale factor to be 1.0.
2340 webview()->setInitialPageScaleOverride(1.f
);
2342 float maxPageScaleFactor
=
2343 command_line
.HasSwitch(switches::kEnablePinch
) ? 4.f
: 1.f
;
2344 webview()->setPageScaleFactorLimits(1, maxPageScaleFactor
);
2347 void RenderViewImpl::didFailProvisionalLoad(WebLocalFrame
* frame
,
2348 const WebURLError
& error
) {
2349 // Notify the browser that we failed a provisional load with an error.
2351 // Note: It is important this notification occur before DidStopLoading so the
2352 // SSL manager can react to the provisional load failure before being
2353 // notified the load stopped.
2356 RenderViewObserver
, observers_
, DidFailProvisionalLoad(frame
, error
));
2359 void RenderViewImpl::FrameDidCommitProvisionalLoad(WebLocalFrame
* frame
,
2360 bool is_new_navigation
) {
2361 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
,
2362 DidCommitProvisionalLoad(frame
, is_new_navigation
));
2364 // TODO(nasko): Transition this code to RenderFrameImpl, since g_view_map is
2365 // not accessible from there.
2366 if (!frame
->parent()) { // Only for top frames.
2367 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
2368 if (render_thread_impl
) { // Can be NULL in tests.
2369 render_thread_impl
->histogram_customizer()->
2370 RenderViewNavigatedToHost(GURL(GetLoadingUrl(frame
)).host(),
2371 g_view_map
.Get().size());
2376 void RenderViewImpl::didClearWindowObject(WebLocalFrame
* frame
, int world_id
) {
2377 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
,
2378 DidClearWindowObject(frame
, world_id
));
2380 // Only install controllers into the main world.
2384 if (enabled_bindings_
& BINDINGS_POLICY_WEB_UI
)
2385 WebUIExtension::Install(frame
);
2387 if (enabled_bindings_
& BINDINGS_POLICY_STATS_COLLECTION
)
2388 StatsCollectionController::Install(frame
);
2390 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
2392 if (command_line
.HasSwitch(switches::kEnableSkiaBenchmarking
))
2393 SkiaBenchmarking::Install(frame
);
2395 if (command_line
.HasSwitch(switches::kEnableMemoryBenchmarking
))
2396 MemoryBenchmarkingExtension::Install(frame
);
2399 void RenderViewImpl::didCreateDocumentElement(WebLocalFrame
* frame
) {
2400 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
,
2401 DidCreateDocumentElement(frame
));
2404 void RenderViewImpl::didReceiveTitle(WebLocalFrame
* frame
,
2405 const WebString
& title
,
2406 WebTextDirection direction
) {
2407 UpdateTitle(frame
, title
, direction
);
2409 // Also check whether we have new encoding name.
2410 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2413 void RenderViewImpl::didChangeIcon(WebLocalFrame
* frame
,
2414 WebIconURL::Type icon_type
) {
2415 if (frame
->parent())
2418 if (!TouchEnabled() && icon_type
!= WebIconURL::TypeFavicon
)
2421 WebVector
<WebIconURL
> icon_urls
= frame
->iconURLs(icon_type
);
2422 std::vector
<FaviconURL
> urls
;
2423 for (size_t i
= 0; i
< icon_urls
.size(); i
++) {
2424 std::vector
<gfx::Size
> sizes
;
2425 ConvertToFaviconSizes(icon_urls
[i
].sizes(), &sizes
);
2426 urls
.push_back(FaviconURL(
2427 icon_urls
[i
].iconURL(), ToFaviconType(icon_urls
[i
].iconType()), sizes
));
2429 SendUpdateFaviconURL(urls
);
2432 void RenderViewImpl::didFinishDocumentLoad(WebLocalFrame
* frame
) {
2433 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
,
2434 DidFinishDocumentLoad(frame
));
2437 void RenderViewImpl::didHandleOnloadEvents(WebLocalFrame
* frame
) {
2438 if (webview()->mainFrame() == frame
) {
2439 Send(new ViewHostMsg_DocumentOnLoadCompletedInMainFrame(routing_id_
,
2444 void RenderViewImpl::didFailLoad(WebLocalFrame
* frame
,
2445 const WebURLError
& error
) {
2446 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidFailLoad(frame
, error
));
2449 void RenderViewImpl::didFinishLoad(WebLocalFrame
* frame
) {
2450 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidFinishLoad(frame
));
2453 void RenderViewImpl::didUpdateCurrentHistoryItem(WebLocalFrame
* frame
) {
2454 StartNavStateSyncTimerIfNecessary();
2457 void RenderViewImpl::didFinishResourceLoad(WebLocalFrame
* frame
,
2458 unsigned identifier
) {
2459 InternalDocumentStateData
* internal_data
=
2460 InternalDocumentStateData::FromDataSource(frame
->dataSource());
2461 if (!internal_data
->use_error_page())
2464 // Do not show error page when DevTools is attached.
2465 if (devtools_agent_
->IsAttached())
2468 // Display error page, if appropriate.
2469 std::string error_domain
= "http";
2470 int http_status_code
= internal_data
->http_status_code();
2471 if (GetContentClient()->renderer()->HasErrorPage(
2472 http_status_code
, &error_domain
)) {
2474 error
.unreachableURL
= frame
->document().url();
2475 error
.domain
= WebString::fromUTF8(error_domain
);
2476 error
.reason
= http_status_code
;
2477 LoadNavigationErrorPage(frame
, frame
->dataSource()->request(), error
, true);
2481 void RenderViewImpl::CheckPreferredSize() {
2482 // We don't always want to send the change messages over IPC, only if we've
2483 // been put in that mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
2485 if (!send_preferred_size_changes_
|| !webview())
2488 gfx::Size size
= webview()->contentsPreferredMinimumSize();
2490 // In the presence of zoom, these sizes are still reported as if unzoomed,
2491 // so we need to adjust.
2492 double zoom_factor
= ZoomLevelToZoomFactor(webview()->zoomLevel());
2493 size
.set_width(static_cast<int>(size
.width() * zoom_factor
));
2494 size
.set_height(static_cast<int>(size
.height() * zoom_factor
));
2496 if (size
== preferred_size_
)
2499 preferred_size_
= size
;
2500 Send(new ViewHostMsg_DidContentsPreferredSizeChange(routing_id_
,
2504 BrowserPluginManager
* RenderViewImpl::GetBrowserPluginManager() {
2505 if (!browser_plugin_manager_
.get())
2506 browser_plugin_manager_
= BrowserPluginManager::Create(this);
2507 return browser_plugin_manager_
.get();
2510 bool RenderViewImpl::InitializeMediaStreamClient() {
2511 if (media_stream_client_
)
2514 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
2517 #if defined(OS_ANDROID)
2518 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableWebRTC
))
2522 #if defined(ENABLE_WEBRTC)
2523 if (!media_stream_dispatcher_
)
2524 media_stream_dispatcher_
= new MediaStreamDispatcher(this);
2526 MediaStreamImpl
* media_stream_impl
= new MediaStreamImpl(
2528 media_stream_dispatcher_
,
2529 RenderThreadImpl::current()->GetMediaStreamDependencyFactory());
2530 media_stream_client_
= media_stream_impl
;
2531 web_user_media_client_
= media_stream_impl
;
2538 void RenderViewImpl::didChangeContentsSize(WebLocalFrame
* frame
,
2539 const WebSize
& size
) {
2540 if (webview()->mainFrame() != frame
)
2542 WebView
* frameView
= frame
->view();
2546 bool has_horizontal_scrollbar
= frame
->hasHorizontalScrollbar();
2547 bool has_vertical_scrollbar
= frame
->hasVerticalScrollbar();
2549 if (has_horizontal_scrollbar
!= cached_has_main_frame_horizontal_scrollbar_
||
2550 has_vertical_scrollbar
!= cached_has_main_frame_vertical_scrollbar_
) {
2551 Send(new ViewHostMsg_DidChangeScrollbarsForMainFrame(
2552 routing_id_
, has_horizontal_scrollbar
, has_vertical_scrollbar
));
2554 cached_has_main_frame_horizontal_scrollbar_
= has_horizontal_scrollbar
;
2555 cached_has_main_frame_vertical_scrollbar_
= has_vertical_scrollbar
;
2559 void RenderViewImpl::UpdateScrollState(WebFrame
* frame
) {
2560 WebSize offset
= frame
->scrollOffset();
2561 WebSize minimum_offset
= frame
->minimumScrollOffset();
2562 WebSize maximum_offset
= frame
->maximumScrollOffset();
2564 bool is_pinned_to_left
= offset
.width
<= minimum_offset
.width
;
2565 bool is_pinned_to_right
= offset
.width
>= maximum_offset
.width
;
2567 if (is_pinned_to_left
!= cached_is_main_frame_pinned_to_left_
||
2568 is_pinned_to_right
!= cached_is_main_frame_pinned_to_right_
) {
2569 Send(new ViewHostMsg_DidChangeScrollOffsetPinningForMainFrame(
2570 routing_id_
, is_pinned_to_left
, is_pinned_to_right
));
2572 cached_is_main_frame_pinned_to_left_
= is_pinned_to_left
;
2573 cached_is_main_frame_pinned_to_right_
= is_pinned_to_right
;
2576 Send(new ViewHostMsg_DidChangeScrollOffset(routing_id_
));
2579 void RenderViewImpl::didChangeScrollOffset(WebLocalFrame
* frame
) {
2580 StartNavStateSyncTimerIfNecessary();
2582 if (webview()->mainFrame() == frame
)
2583 UpdateScrollState(frame
);
2586 RenderViewObserver
, observers_
, DidChangeScrollOffset(frame
));
2589 void RenderViewImpl::didFirstVisuallyNonEmptyLayout(WebLocalFrame
* frame
) {
2590 if (frame
!= webview()->mainFrame())
2593 InternalDocumentStateData
* data
=
2594 InternalDocumentStateData::FromDataSource(frame
->dataSource());
2595 data
->set_did_first_visually_non_empty_layout(true);
2597 #if defined(OS_ANDROID)
2598 // Update body background color if necessary.
2599 SkColor bg_color
= webwidget_
->backgroundColor();
2601 // If not initialized, default to white. Note that 0 is different from black
2602 // as black still has alpha 0xFF.
2604 bg_color
= SK_ColorWHITE
;
2606 if (bg_color
!= body_background_color_
) {
2607 body_background_color_
= bg_color
;
2608 Send(new ViewHostMsg_DidChangeBodyBackgroundColor(
2609 GetRoutingID(), bg_color
));
2614 void RenderViewImpl::SendFindReply(int request_id
,
2617 const WebRect
& selection_rect
,
2618 bool final_status_update
) {
2619 Send(new ViewHostMsg_Find_Reply(routing_id_
,
2624 final_status_update
));
2627 bool RenderViewImpl::willCheckAndDispatchMessageEvent(
2628 blink::WebLocalFrame
* sourceFrame
,
2629 blink::WebFrame
* targetFrame
,
2630 blink::WebSecurityOrigin target_origin
,
2631 blink::WebDOMMessageEvent event
) {
2632 if (!is_swapped_out_
)
2635 ViewMsg_PostMessage_Params params
;
2636 params
.data
= event
.data().toString();
2637 params
.source_origin
= event
.origin();
2638 if (!target_origin
.isNull())
2639 params
.target_origin
= target_origin
.toString();
2641 blink::WebMessagePortChannelArray channels
= event
.releaseChannels();
2642 if (!channels
.isEmpty()) {
2643 std::vector
<int> message_port_ids(channels
.size());
2644 // Extract the port IDs from the channel array.
2645 for (size_t i
= 0; i
< channels
.size(); ++i
) {
2646 WebMessagePortChannelImpl
* webchannel
=
2647 static_cast<WebMessagePortChannelImpl
*>(channels
[i
]);
2648 message_port_ids
[i
] = webchannel
->message_port_id();
2649 webchannel
->QueueMessages();
2650 DCHECK_NE(message_port_ids
[i
], MSG_ROUTING_NONE
);
2652 params
.message_port_ids
= message_port_ids
;
2655 // Include the routing ID for the source frame (if one exists), which the
2656 // browser process will translate into the routing ID for the equivalent
2657 // frame in the target process.
2658 params
.source_routing_id
= MSG_ROUTING_NONE
;
2660 RenderViewImpl
* source_view
= FromWebView(sourceFrame
->view());
2662 params
.source_routing_id
= source_view
->routing_id();
2665 Send(new ViewHostMsg_RouteMessageEvent(routing_id_
, params
));
2669 blink::WebString
RenderViewImpl::acceptLanguages() {
2670 return WebString::fromUTF8(renderer_preferences_
.accept_languages
);
2673 // blink::WebPageSerializerClient implementation ------------------------------
2675 void RenderViewImpl::didSerializeDataForFrame(
2676 const WebURL
& frame_url
,
2677 const WebCString
& data
,
2678 WebPageSerializerClient::PageSerializationStatus status
) {
2679 Send(new ViewHostMsg_SendSerializedHtmlData(
2683 static_cast<int32
>(status
)));
2686 // RenderView implementation ---------------------------------------------------
2688 bool RenderViewImpl::Send(IPC::Message
* message
) {
2689 return RenderWidget::Send(message
);
2692 RenderFrame
* RenderViewImpl::GetMainRenderFrame() {
2693 return main_render_frame_
.get();
2696 int RenderViewImpl::GetRoutingID() const {
2700 int RenderViewImpl::GetPageId() const {
2704 gfx::Size
RenderViewImpl::GetSize() const {
2708 WebPreferences
& RenderViewImpl::GetWebkitPreferences() {
2709 return webkit_preferences_
;
2712 void RenderViewImpl::SetWebkitPreferences(const WebPreferences
& preferences
) {
2713 OnUpdateWebPreferences(preferences
);
2716 blink::WebView
* RenderViewImpl::GetWebView() {
2720 blink::WebElement
RenderViewImpl::GetFocusedElement() const {
2722 return WebElement();
2723 WebFrame
* focused_frame
= webview()->focusedFrame();
2724 if (focused_frame
) {
2725 WebDocument doc
= focused_frame
->document();
2727 return doc
.focusedElement();
2730 return WebElement();
2733 bool RenderViewImpl::IsEditableNode(const WebNode
& node
) const {
2737 if (node
.isContentEditable())
2740 if (node
.isElementNode()) {
2741 const WebElement
& element
= node
.toConst
<WebElement
>();
2742 if (element
.isTextFormControlElement())
2745 // Also return true if it has an ARIA role of 'textbox'.
2746 for (unsigned i
= 0; i
< element
.attributeCount(); ++i
) {
2747 if (LowerCaseEqualsASCII(element
.attributeLocalName(i
), "role")) {
2748 if (LowerCaseEqualsASCII(element
.attributeValue(i
), "textbox"))
2758 bool RenderViewImpl::ShouldDisplayScrollbars(int width
, int height
) const {
2759 return (!send_preferred_size_changes_
||
2760 (disable_scrollbars_size_limit_
.width() <= width
||
2761 disable_scrollbars_size_limit_
.height() <= height
));
2764 int RenderViewImpl::GetEnabledBindings() const {
2765 return enabled_bindings_
;
2768 bool RenderViewImpl::GetContentStateImmediately() const {
2769 return send_content_state_immediately_
;
2772 float RenderViewImpl::GetFilteredTimePerFrame() const {
2773 return filtered_time_per_frame();
2776 blink::WebPageVisibilityState
RenderViewImpl::GetVisibilityState() const {
2777 return visibilityState();
2780 void RenderViewImpl::DidStartLoading() {
2781 main_render_frame_
->didStartLoading(true);
2784 void RenderViewImpl::DidStopLoading() {
2785 main_render_frame_
->didStopLoading();
2788 void RenderViewImpl::DidPlay(blink::WebMediaPlayer
* player
) {
2789 Send(new ViewHostMsg_MediaPlayingNotification(routing_id_
,
2790 reinterpret_cast<int64
>(player
),
2792 player
->hasAudio()));
2795 void RenderViewImpl::DidPause(blink::WebMediaPlayer
* player
) {
2796 Send(new ViewHostMsg_MediaPausedNotification(
2797 routing_id_
, reinterpret_cast<int64
>(player
)));
2800 void RenderViewImpl::PlayerGone(blink::WebMediaPlayer
* player
) {
2804 void RenderViewImpl::SyncNavigationState() {
2808 WebHistoryItem item
= history_controller_
->GetCurrentItemForExport();
2809 SendUpdateState(item
);
2812 GURL
RenderViewImpl::GetLoadingUrl(blink::WebFrame
* frame
) const {
2813 WebDataSource
* ds
= frame
->dataSource();
2814 if (ds
->hasUnreachableURL())
2815 return ds
->unreachableURL();
2817 const WebURLRequest
& request
= ds
->request();
2818 return request
.url();
2821 blink::WebPlugin
* RenderViewImpl::GetWebPluginForFind() {
2825 WebFrame
* main_frame
= webview()->mainFrame();
2826 if (main_frame
->document().isPluginDocument())
2827 return webview()->mainFrame()->document().to
<WebPluginDocument
>().plugin();
2829 #if defined(ENABLE_PLUGINS)
2830 if (plugin_find_handler_
)
2831 return plugin_find_handler_
->container()->plugin();
2837 void RenderViewImpl::OnFind(int request_id
,
2838 const base::string16
& search_text
,
2839 const WebFindOptions
& options
) {
2840 WebFrame
* main_frame
= webview()->mainFrame();
2841 blink::WebPlugin
* plugin
= GetWebPluginForFind();
2842 // Check if the plugin still exists in the document.
2844 if (options
.findNext
) {
2845 // Just navigate back/forward.
2846 plugin
->selectFindResult(options
.forward
);
2848 if (!plugin
->startFind(
2849 search_text
, options
.matchCase
, request_id
)) {
2850 // Send "no results".
2851 SendFindReply(request_id
, 0, 0, gfx::Rect(), true);
2857 WebFrame
* frame_after_main
= main_frame
->traverseNext(true);
2858 WebFrame
* focused_frame
= webview()->focusedFrame();
2859 WebFrame
* search_frame
= focused_frame
; // start searching focused frame.
2861 bool multi_frame
= (frame_after_main
!= main_frame
);
2863 // If we have multiple frames, we don't want to wrap the search within the
2864 // frame, so we check here if we only have main_frame in the chain.
2865 bool wrap_within_frame
= !multi_frame
;
2867 WebRect selection_rect
;
2868 bool result
= false;
2870 // If something is selected when we start searching it means we cannot just
2871 // increment the current match ordinal; we need to re-generate it.
2872 WebRange current_selection
= focused_frame
->selectionRange();
2875 result
= search_frame
->find(
2876 request_id
, search_text
, options
, wrap_within_frame
, &selection_rect
);
2879 // don't leave text selected as you move to the next frame.
2880 search_frame
->executeCommand(WebString::fromUTF8("Unselect"),
2881 GetFocusedElement());
2883 // Find the next frame, but skip the invisible ones.
2885 // What is the next frame to search? (we might be going backwards). Note
2886 // that we specify wrap=true so that search_frame never becomes NULL.
2887 search_frame
= options
.forward
?
2888 search_frame
->traverseNext(true) :
2889 search_frame
->traversePrevious(true);
2890 } while (!search_frame
->hasVisibleContent() &&
2891 search_frame
!= focused_frame
);
2893 // Make sure selection doesn't affect the search operation in new frame.
2894 search_frame
->executeCommand(WebString::fromUTF8("Unselect"),
2895 GetFocusedElement());
2897 // If we have multiple frames and we have wrapped back around to the
2898 // focused frame, we need to search it once more allowing wrap within
2899 // the frame, otherwise it will report 'no match' if the focused frame has
2900 // reported matches, but no frames after the focused_frame contain a
2901 // match for the search word(s).
2902 if (multi_frame
&& search_frame
== focused_frame
) {
2903 result
= search_frame
->find(
2904 request_id
, search_text
, options
, true, // Force wrapping.
2909 webview()->setFocusedFrame(search_frame
);
2910 } while (!result
&& search_frame
!= focused_frame
);
2912 if (options
.findNext
&& current_selection
.isNull()) {
2913 // Force the main_frame to report the actual count.
2914 main_frame
->increaseMatchCount(0, request_id
);
2916 // If nothing is found, set result to "0 of 0", otherwise, set it to
2917 // "-1 of 1" to indicate that we found at least one item, but we don't know
2918 // yet what is active.
2919 int ordinal
= result
? -1 : 0; // -1 here means, we might know more later.
2920 int match_count
= result
? 1 : 0; // 1 here means possibly more coming.
2922 // If we find no matches then this will be our last status update.
2923 // Otherwise the scoping effort will send more results.
2924 bool final_status_update
= !result
;
2926 SendFindReply(request_id
, match_count
, ordinal
, selection_rect
,
2927 final_status_update
);
2929 // Scoping effort begins, starting with the mainframe.
2930 search_frame
= main_frame
;
2932 main_frame
->resetMatchCount();
2935 // Cancel all old scoping requests before starting a new one.
2936 search_frame
->cancelPendingScopingEffort();
2938 // We don't start another scoping effort unless at least one match has
2941 // Start new scoping request. If the scoping function determines that it
2942 // needs to scope, it will defer until later.
2943 search_frame
->scopeStringMatches(request_id
,
2946 true); // reset the tickmarks
2949 // Iterate to the next frame. The frame will not necessarily scope, for
2950 // example if it is not visible.
2951 search_frame
= search_frame
->traverseNext(true);
2952 } while (search_frame
!= main_frame
);
2956 void RenderViewImpl::OnStopFinding(StopFindAction action
) {
2957 WebView
* view
= webview();
2961 blink::WebPlugin
* plugin
= GetWebPluginForFind();
2967 bool clear_selection
= action
== STOP_FIND_ACTION_CLEAR_SELECTION
;
2968 if (clear_selection
) {
2969 view
->focusedFrame()->executeCommand(WebString::fromUTF8("Unselect"),
2970 GetFocusedElement());
2973 WebFrame
* frame
= view
->mainFrame();
2975 frame
->stopFinding(clear_selection
);
2976 frame
= frame
->traverseNext(false);
2979 if (action
== STOP_FIND_ACTION_ACTIVATE_SELECTION
) {
2980 WebFrame
* focused_frame
= view
->focusedFrame();
2981 if (focused_frame
) {
2982 WebDocument doc
= focused_frame
->document();
2983 if (!doc
.isNull()) {
2984 WebElement element
= doc
.focusedElement();
2985 if (!element
.isNull())
2986 element
.simulateClick();
2992 #if defined(OS_ANDROID)
2993 void RenderViewImpl::OnActivateNearestFindResult(int request_id
,
2998 WebFrame
* main_frame
= webview()->mainFrame();
2999 WebRect selection_rect
;
3000 int ordinal
= main_frame
->selectNearestFindMatch(WebFloatPoint(x
, y
),
3002 if (ordinal
== -1) {
3003 // Something went wrong, so send a no-op reply (force the main_frame to
3004 // report the current match count) in case the host is waiting for a
3005 // response due to rate-limiting).
3006 main_frame
->increaseMatchCount(0, request_id
);
3010 SendFindReply(request_id
,
3011 -1 /* number_of_matches */,
3014 true /* final_update */);
3017 void RenderViewImpl::OnFindMatchRects(int current_version
) {
3021 WebFrame
* main_frame
= webview()->mainFrame();
3022 std::vector
<gfx::RectF
> match_rects
;
3024 int rects_version
= main_frame
->findMatchMarkersVersion();
3025 if (current_version
!= rects_version
) {
3026 WebVector
<WebFloatRect
> web_match_rects
;
3027 main_frame
->findMatchRects(web_match_rects
);
3028 match_rects
.reserve(web_match_rects
.size());
3029 for (size_t i
= 0; i
< web_match_rects
.size(); ++i
)
3030 match_rects
.push_back(gfx::RectF(web_match_rects
[i
]));
3033 gfx::RectF active_rect
= main_frame
->activeFindMatchRect();
3034 Send(new ViewHostMsg_FindMatchRects_Reply(routing_id_
,
3041 void RenderViewImpl::OnZoom(PageZoom zoom
) {
3042 if (!webview()) // Not sure if this can happen, but no harm in being safe.
3045 webview()->hidePopups();
3047 double old_zoom_level
= webview()->zoomLevel();
3049 if (zoom
== PAGE_ZOOM_RESET
) {
3051 } else if (static_cast<int>(old_zoom_level
) == old_zoom_level
) {
3052 // Previous zoom level is a whole number, so just increment/decrement.
3053 zoom_level
= old_zoom_level
+ zoom
;
3055 // Either the user hit the zoom factor limit and thus the zoom level is now
3056 // not a whole number, or a plugin changed it to a custom value. We want
3057 // to go to the next whole number so that the user can always get back to
3058 // 100% with the keyboard/menu.
3059 if ((old_zoom_level
> 1 && zoom
> 0) ||
3060 (old_zoom_level
< 1 && zoom
< 0)) {
3061 zoom_level
= static_cast<int>(old_zoom_level
+ zoom
);
3063 // We're going towards 100%, so first go to the next whole number.
3064 zoom_level
= static_cast<int>(old_zoom_level
);
3067 webview()->setZoomLevel(zoom_level
);
3071 void RenderViewImpl::OnSetZoomLevel(double zoom_level
) {
3072 webview()->hidePopups();
3073 webview()->setZoomLevel(zoom_level
);
3077 void RenderViewImpl::OnSetZoomLevelForLoadingURL(const GURL
& url
,
3078 double zoom_level
) {
3079 #if !defined(OS_ANDROID)
3080 // On Android, page zoom isn't used, and in case of WebView, text zoom is used
3081 // for legacy WebView text scaling emulation. Thus, the code that resets
3082 // the zoom level from this map will be effectively resetting text zoom level.
3083 host_zoom_levels_
[url
] = zoom_level
;
3087 void RenderViewImpl::OnSetPageEncoding(const std::string
& encoding_name
) {
3088 webview()->setPageEncoding(WebString::fromUTF8(encoding_name
));
3091 void RenderViewImpl::OnResetPageEncodingToDefault() {
3092 WebString no_encoding
;
3093 webview()->setPageEncoding(no_encoding
);
3096 void RenderViewImpl::OnPostMessageEvent(
3097 const ViewMsg_PostMessage_Params
& params
) {
3098 // TODO(nasko): Support sending to subframes.
3099 WebFrame
* frame
= webview()->mainFrame();
3101 // Find the source frame if it exists.
3102 WebFrame
* source_frame
= NULL
;
3103 if (params
.source_routing_id
!= MSG_ROUTING_NONE
) {
3104 RenderViewImpl
* source_view
= FromRoutingID(params
.source_routing_id
);
3106 source_frame
= source_view
->webview()->mainFrame();
3109 // If the message contained MessagePorts, create the corresponding endpoints.
3110 DCHECK_EQ(params
.message_port_ids
.size(), params
.new_routing_ids
.size());
3111 blink::WebMessagePortChannelArray
channels(params
.message_port_ids
.size());
3113 i
< params
.message_port_ids
.size() && i
< params
.new_routing_ids
.size();
3116 new WebMessagePortChannelImpl(params
.new_routing_ids
[i
],
3117 params
.message_port_ids
[i
],
3118 base::MessageLoopProxy::current().get());
3121 // Create an event with the message. The final parameter to initMessageEvent
3122 // is the last event ID, which is not used with postMessage.
3123 WebDOMEvent event
= frame
->document().createEvent("MessageEvent");
3124 WebDOMMessageEvent msg_event
= event
.to
<WebDOMMessageEvent
>();
3125 msg_event
.initMessageEvent("message",
3126 // |canBubble| and |cancellable| are always false
3128 WebSerializedScriptValue::fromString(params
.data
),
3129 params
.source_origin
, source_frame
, "", channels
);
3131 // We must pass in the target_origin to do the security check on this side,
3132 // since it may have changed since the original postMessage call was made.
3133 WebSecurityOrigin target_origin
;
3134 if (!params
.target_origin
.empty()) {
3136 WebSecurityOrigin::createFromString(WebString(params
.target_origin
));
3138 frame
->dispatchMessageEventWithOriginCheck(target_origin
, msg_event
);
3141 void RenderViewImpl::OnAllowBindings(int enabled_bindings_flags
) {
3142 if ((enabled_bindings_flags
& BINDINGS_POLICY_WEB_UI
) &&
3143 !(enabled_bindings_
& BINDINGS_POLICY_WEB_UI
)) {
3144 // WebUIExtensionData deletes itself when we're destroyed.
3145 new WebUIExtensionData(this);
3146 // WebUIMojo deletes itself when we're destroyed.
3147 new WebUIMojo(this);
3150 enabled_bindings_
|= enabled_bindings_flags
;
3152 // Keep track of the total bindings accumulated in this process.
3153 RenderProcess::current()->AddBindings(enabled_bindings_flags
);
3156 void RenderViewImpl::OnDragTargetDragEnter(const DropData
& drop_data
,
3157 const gfx::Point
& client_point
,
3158 const gfx::Point
& screen_point
,
3159 WebDragOperationsMask ops
,
3160 int key_modifiers
) {
3161 WebDragOperation operation
= webview()->dragTargetDragEnter(
3162 DropDataToWebDragData(drop_data
),
3168 Send(new DragHostMsg_UpdateDragCursor(routing_id_
, operation
));
3171 void RenderViewImpl::OnDragTargetDragOver(const gfx::Point
& client_point
,
3172 const gfx::Point
& screen_point
,
3173 WebDragOperationsMask ops
,
3174 int key_modifiers
) {
3175 WebDragOperation operation
= webview()->dragTargetDragOver(
3181 Send(new DragHostMsg_UpdateDragCursor(routing_id_
, operation
));
3184 void RenderViewImpl::OnDragTargetDragLeave() {
3185 webview()->dragTargetDragLeave();
3188 void RenderViewImpl::OnDragTargetDrop(const gfx::Point
& client_point
,
3189 const gfx::Point
& screen_point
,
3190 int key_modifiers
) {
3191 webview()->dragTargetDrop(client_point
, screen_point
, key_modifiers
);
3193 Send(new DragHostMsg_TargetDrop_ACK(routing_id_
));
3196 void RenderViewImpl::OnDragSourceEnded(const gfx::Point
& client_point
,
3197 const gfx::Point
& screen_point
,
3198 WebDragOperation op
) {
3199 webview()->dragSourceEndedAt(client_point
, screen_point
, op
);
3202 void RenderViewImpl::OnDragSourceSystemDragEnded() {
3203 webview()->dragSourceSystemDragEnded();
3206 void RenderViewImpl::OnUpdateWebPreferences(const WebPreferences
& prefs
) {
3207 webkit_preferences_
= prefs
;
3208 ApplyWebPreferences(webkit_preferences_
, webview());
3211 void RenderViewImpl::OnEnumerateDirectoryResponse(
3213 const std::vector
<base::FilePath
>& paths
) {
3214 if (!enumeration_completions_
[id
])
3217 WebVector
<WebString
> ws_file_names(paths
.size());
3218 for (size_t i
= 0; i
< paths
.size(); ++i
)
3219 ws_file_names
[i
] = paths
[i
].AsUTF16Unsafe();
3221 enumeration_completions_
[id
]->didChooseFile(ws_file_names
);
3222 enumeration_completions_
.erase(id
);
3225 void RenderViewImpl::OnFileChooserResponse(
3226 const std::vector
<ui::SelectedFileInfo
>& files
) {
3227 // This could happen if we navigated to a different page before the user
3228 // closed the chooser.
3229 if (file_chooser_completions_
.empty())
3232 // Convert Chrome's SelectedFileInfo list to WebKit's.
3233 WebVector
<WebFileChooserCompletion::SelectedFileInfo
> selected_files(
3235 for (size_t i
= 0; i
< files
.size(); ++i
) {
3236 WebFileChooserCompletion::SelectedFileInfo selected_file
;
3237 selected_file
.path
= files
[i
].local_path
.AsUTF16Unsafe();
3238 selected_file
.displayName
=
3239 base::FilePath(files
[i
].display_name
).AsUTF16Unsafe();
3240 selected_files
[i
] = selected_file
;
3243 if (file_chooser_completions_
.front()->completion
)
3244 file_chooser_completions_
.front()->completion
->didChooseFile(
3246 file_chooser_completions_
.pop_front();
3248 // If there are more pending file chooser requests, schedule one now.
3249 if (!file_chooser_completions_
.empty()) {
3250 Send(new ViewHostMsg_RunFileChooser(routing_id_
,
3251 file_chooser_completions_
.front()->params
));
3255 void RenderViewImpl::OnEnableAutoResize(const gfx::Size
& min_size
,
3256 const gfx::Size
& max_size
) {
3257 DCHECK(disable_scrollbars_size_limit_
.IsEmpty());
3260 auto_resize_mode_
= true;
3261 webview()->enableAutoResizeMode(min_size
, max_size
);
3264 void RenderViewImpl::OnDisableAutoResize(const gfx::Size
& new_size
) {
3265 DCHECK(disable_scrollbars_size_limit_
.IsEmpty());
3268 auto_resize_mode_
= false;
3269 webview()->disableAutoResizeMode();
3271 if (!new_size
.IsEmpty()) {
3273 physical_backing_size_
,
3274 overdraw_bottom_height_
,
3281 void RenderViewImpl::OnEnablePreferredSizeChangedMode() {
3282 if (send_preferred_size_changes_
)
3284 send_preferred_size_changes_
= true;
3286 // Start off with an initial preferred size notification (in case
3287 // |didUpdateLayout| was already called).
3291 void RenderViewImpl::OnDisableScrollbarsForSmallWindows(
3292 const gfx::Size
& disable_scrollbar_size_limit
) {
3293 disable_scrollbars_size_limit_
= disable_scrollbar_size_limit
;
3296 void RenderViewImpl::OnSetRendererPrefs(
3297 const RendererPreferences
& renderer_prefs
) {
3298 double old_zoom_level
= renderer_preferences_
.default_zoom_level
;
3299 renderer_preferences_
= renderer_prefs
;
3300 UpdateFontRenderingFromRendererPrefs();
3302 #if defined(USE_DEFAULT_RENDER_THEME)
3303 if (renderer_prefs
.use_custom_colors
) {
3304 WebColorName name
= blink::WebColorWebkitFocusRingColor
;
3305 blink::setNamedColors(&name
, &renderer_prefs
.focus_ring_color
, 1);
3306 blink::setCaretBlinkInterval(renderer_prefs
.caret_blink_interval
);
3309 webview()->setSelectionColors(
3310 renderer_prefs
.active_selection_bg_color
,
3311 renderer_prefs
.active_selection_fg_color
,
3312 renderer_prefs
.inactive_selection_bg_color
,
3313 renderer_prefs
.inactive_selection_fg_color
);
3314 webview()->themeChanged();
3317 #endif // defined(USE_DEFAULT_RENDER_THEME)
3319 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
3320 RenderThreadImpl::current()->SetFlingCurveParameters(
3321 renderer_prefs
.touchpad_fling_profile
,
3322 renderer_prefs
.touchscreen_fling_profile
);
3324 // If the zoom level for this page matches the old zoom default, and this
3325 // is not a plugin, update the zoom level to match the new default.
3326 if (webview() && !webview()->mainFrame()->document().isPluginDocument() &&
3327 !ZoomValuesEqual(old_zoom_level
,
3328 renderer_preferences_
.default_zoom_level
) &&
3329 ZoomValuesEqual(webview()->zoomLevel(), old_zoom_level
)) {
3330 webview()->setZoomLevel(renderer_preferences_
.default_zoom_level
);
3335 void RenderViewImpl::OnMediaPlayerActionAt(const gfx::Point
& location
,
3336 const WebMediaPlayerAction
& action
) {
3338 webview()->performMediaPlayerAction(action
, location
);
3341 void RenderViewImpl::OnOrientationChangeEvent(int orientation
) {
3342 // Screen has rotated. 0 = default (portrait), 90 = one turn right, and so on.
3343 FOR_EACH_OBSERVER(RenderViewObserver
,
3345 OrientationChangeEvent(orientation
));
3346 webview()->mainFrame()->sendOrientationChangeEvent(orientation
);
3349 void RenderViewImpl::OnPluginActionAt(const gfx::Point
& location
,
3350 const WebPluginAction
& action
) {
3352 webview()->performPluginAction(action
, location
);
3355 void RenderViewImpl::OnGetAllSavableResourceLinksForCurrentPage(
3356 const GURL
& page_url
) {
3357 // Prepare list to storage all savable resource links.
3358 std::vector
<GURL
> resources_list
;
3359 std::vector
<GURL
> referrer_urls_list
;
3360 std::vector
<blink::WebReferrerPolicy
> referrer_policies_list
;
3361 std::vector
<GURL
> frames_list
;
3362 SavableResourcesResult
result(&resources_list
,
3363 &referrer_urls_list
,
3364 &referrer_policies_list
,
3367 // webkit/ doesn't know about Referrer.
3368 if (!GetAllSavableResourceLinksForCurrentPage(
3372 const_cast<const char**>(GetSavableSchemes()))) {
3373 // If something is wrong when collecting all savable resource links,
3374 // send empty list to embedder(browser) to tell it failed.
3375 referrer_urls_list
.clear();
3376 referrer_policies_list
.clear();
3377 resources_list
.clear();
3378 frames_list
.clear();
3381 std::vector
<Referrer
> referrers_list
;
3382 CHECK_EQ(referrer_urls_list
.size(), referrer_policies_list
.size());
3383 for (unsigned i
= 0; i
< referrer_urls_list
.size(); ++i
) {
3384 referrers_list
.push_back(
3385 Referrer(referrer_urls_list
[i
], referrer_policies_list
[i
]));
3388 // Send result of all savable resource links to embedder.
3389 Send(new ViewHostMsg_SendCurrentPageAllSavableResourceLinks(routing_id(),
3395 void RenderViewImpl::OnGetSerializedHtmlDataForCurrentPageWithLocalLinks(
3396 const std::vector
<GURL
>& links
,
3397 const std::vector
<base::FilePath
>& local_paths
,
3398 const base::FilePath
& local_directory_name
) {
3400 // Convert std::vector of GURLs to WebVector<WebURL>
3401 WebVector
<WebURL
> weburl_links(links
);
3403 // Convert std::vector of base::FilePath to WebVector<WebString>
3404 WebVector
<WebString
> webstring_paths(local_paths
.size());
3405 for (size_t i
= 0; i
< local_paths
.size(); i
++)
3406 webstring_paths
[i
] = local_paths
[i
].AsUTF16Unsafe();
3408 WebPageSerializer::serialize(webview()->mainFrame()->toWebLocalFrame(),
3413 local_directory_name
.AsUTF16Unsafe());
3416 void RenderViewImpl::OnSuppressDialogsUntilSwapOut() {
3417 // Don't show any more dialogs until we finish OnSwapOut.
3418 suppress_dialogs_until_swap_out_
= true;
3421 void RenderViewImpl::NavigateToSwappedOutURL(blink::WebFrame
* frame
) {
3422 // We use loadRequest instead of loadHTMLString because the former commits
3423 // synchronously. Otherwise a new navigation can interrupt the navigation
3424 // to kSwappedOutURL. If that happens to be to the page we had been
3425 // showing, then WebKit will never send a commit and we'll be left spinning.
3426 // TODO(creis): Until we move this to RenderFrame, we may call this from a
3427 // swapped out RenderFrame while our own is_swapped_out_ is false.
3428 RenderFrameImpl
* rf
= RenderFrameImpl::FromWebFrame(frame
);
3429 CHECK(is_swapped_out_
|| rf
->is_swapped_out());
3430 GURL
swappedOutURL(kSwappedOutURL
);
3431 WebURLRequest
request(swappedOutURL
);
3432 frame
->loadRequest(request
);
3435 void RenderViewImpl::OnClosePage() {
3436 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, ClosePage());
3437 // TODO(creis): We'd rather use webview()->Close() here, but that currently
3438 // sets the WebView's delegate_ to NULL, preventing any JavaScript dialogs
3439 // in the onunload handler from appearing. For now, we're bypassing that and
3440 // calling the FrameLoader's CloseURL method directly. This should be
3441 // revisited to avoid having two ways to close a page. Having a single way
3442 // to close that can run onunload is also useful for fixing
3443 // http://b/issue?id=753080.
3444 webview()->mainFrame()->dispatchUnloadEvent();
3446 Send(new ViewHostMsg_ClosePage_ACK(routing_id_
));
3449 void RenderViewImpl::OnThemeChanged() {
3450 #if defined(USE_AURA)
3451 // Aura doesn't care if we switch themes.
3452 #elif defined(OS_WIN)
3453 ui::NativeThemeWin::instance()->CloseHandles();
3455 webview()->themeChanged();
3456 #else // defined(OS_WIN)
3457 // TODO(port): we don't support theming on non-Windows platforms yet
3462 void RenderViewImpl::OnMoveOrResizeStarted() {
3464 webview()->hidePopups();
3467 void RenderViewImpl::OnResize(const ViewMsg_Resize_Params
& params
) {
3469 webview()->hidePopups();
3470 if (send_preferred_size_changes_
) {
3471 webview()->mainFrame()->setCanHaveScrollbars(
3472 ShouldDisplayScrollbars(params
.new_size
.width(),
3473 params
.new_size
.height()));
3475 UpdateScrollState(webview()->mainFrame());
3478 RenderWidget::OnResize(params
);
3481 void RenderViewImpl::DidInitiatePaint() {
3482 #if defined(ENABLE_PLUGINS)
3483 // Notify all instances that we painted. The same caveats apply as for
3484 // ViewFlushedPaint regarding instances closing themselves, so we take
3485 // similar precautions.
3486 PepperPluginSet plugins
= active_pepper_instances_
;
3487 for (PepperPluginSet::iterator i
= plugins
.begin(); i
!= plugins
.end(); ++i
) {
3488 if (active_pepper_instances_
.find(*i
) != active_pepper_instances_
.end())
3489 (*i
)->ViewInitiatedPaint();
3494 void RenderViewImpl::DidFlushPaint() {
3495 #if defined(ENABLE_PLUGINS)
3496 // Notify all instances that we flushed. This will call into the plugin, and
3497 // we it may ask to close itself as a result. This will, in turn, modify our
3498 // set, possibly invalidating the iterator. So we iterate on a copy that
3499 // won't change out from under us.
3500 PepperPluginSet plugins
= active_pepper_instances_
;
3501 for (PepperPluginSet::iterator i
= plugins
.begin(); i
!= plugins
.end(); ++i
) {
3502 // The copy above makes sure our iterator is never invalid if some plugins
3503 // are destroyed. But some plugin may decide to close all of its views in
3504 // response to a paint in one of them, so we need to make sure each one is
3505 // still "current" before using it.
3507 // It's possible that a plugin was destroyed, but another one was created
3508 // with the same address. In this case, we'll call ViewFlushedPaint on that
3509 // new plugin. But that's OK for this particular case since we're just
3510 // notifying all of our instances that the view flushed, and the new one is
3511 // one of our instances.
3513 // What about the case where a new one is created in a callback at a new
3514 // address and we don't issue the callback? We're still OK since this
3515 // callback is used for flush callbacks and we could not have possibly
3516 // started a new paint for the new plugin while processing a previous paint
3517 // for an existing one.
3518 if (active_pepper_instances_
.find(*i
) != active_pepper_instances_
.end())
3519 (*i
)->ViewFlushedPaint();
3523 // If the RenderWidget is closing down then early-exit, otherwise we'll crash.
3524 // See crbug.com/112921.
3528 WebFrame
* main_frame
= webview()->mainFrame();
3530 // If we have a provisional frame we are between the start and commit stages
3531 // of loading and we don't want to save stats.
3532 if (!main_frame
->provisionalDataSource()) {
3533 WebDataSource
* ds
= main_frame
->dataSource();
3534 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3535 InternalDocumentStateData
* data
=
3536 InternalDocumentStateData::FromDocumentState(document_state
);
3537 if (data
->did_first_visually_non_empty_layout() &&
3538 !data
->did_first_visually_non_empty_paint()) {
3539 data
->set_did_first_visually_non_empty_paint(true);
3540 Send(new ViewHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_
,
3544 // TODO(jar): The following code should all be inside a method, probably in
3546 Time now
= Time::Now();
3547 if (document_state
->first_paint_time().is_null()) {
3548 document_state
->set_first_paint_time(now
);
3550 if (document_state
->first_paint_after_load_time().is_null() &&
3551 !document_state
->finish_load_time().is_null()) {
3552 document_state
->set_first_paint_after_load_time(now
);
3557 gfx::Vector2d
RenderViewImpl::GetScrollOffset() {
3558 WebSize scroll_offset
= webview()->mainFrame()->scrollOffset();
3559 return gfx::Vector2d(scroll_offset
.width
, scroll_offset
.height
);
3562 void RenderViewImpl::OnClearFocusedElement() {
3564 webview()->clearFocusedElement();
3567 void RenderViewImpl::OnSetBackground(const SkBitmap
& background
) {
3569 webview()->setIsTransparent(!background
.empty());
3571 compositor_
->setHasTransparentBackground(!background
.empty());
3573 SetBackground(background
);
3576 void RenderViewImpl::OnSetAccessibilityMode(AccessibilityMode new_mode
) {
3577 if (accessibility_mode_
== new_mode
)
3579 accessibility_mode_
= new_mode
;
3580 if (renderer_accessibility_
) {
3581 delete renderer_accessibility_
;
3582 renderer_accessibility_
= NULL
;
3584 if (accessibility_mode_
== AccessibilityModeOff
)
3587 if (accessibility_mode_
& AccessibilityModeFlagFullTree
)
3588 renderer_accessibility_
= new RendererAccessibilityComplete(this);
3589 #if !defined(OS_ANDROID)
3591 renderer_accessibility_
= new RendererAccessibilityFocusOnly(this);
3595 void RenderViewImpl::OnSetActive(bool active
) {
3597 webview()->setIsActive(active
);
3599 #if defined(ENABLE_PLUGINS) && defined(OS_MACOSX)
3600 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
3601 for (plugin_it
= plugin_delegates_
.begin();
3602 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
3603 (*plugin_it
)->SetWindowFocus(active
);
3608 #if defined(OS_MACOSX)
3609 void RenderViewImpl::OnSetWindowVisibility(bool visible
) {
3610 #if defined(ENABLE_PLUGINS)
3611 // Inform plugins that their container has changed visibility.
3612 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
3613 for (plugin_it
= plugin_delegates_
.begin();
3614 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
3615 (*plugin_it
)->SetContainerVisibility(visible
);
3620 void RenderViewImpl::OnWindowFrameChanged(const gfx::Rect
& window_frame
,
3621 const gfx::Rect
& view_frame
) {
3622 #if defined(ENABLE_PLUGINS)
3623 // Inform plugins that their window's frame has changed.
3624 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
3625 for (plugin_it
= plugin_delegates_
.begin();
3626 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
3627 (*plugin_it
)->WindowFrameChanged(window_frame
, view_frame
);
3632 void RenderViewImpl::OnPluginImeCompositionCompleted(const base::string16
& text
,
3634 // WebPluginDelegateProxy is responsible for figuring out if this event
3635 // applies to it or not, so inform all the delegates.
3636 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
3637 for (plugin_it
= plugin_delegates_
.begin();
3638 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
3639 (*plugin_it
)->ImeCompositionCompleted(text
, plugin_id
);
3644 void RenderViewImpl::Close() {
3645 // We need to grab a pointer to the doomed WebView before we destroy it.
3646 WebView
* doomed
= webview();
3647 RenderWidget::Close();
3648 g_view_map
.Get().erase(doomed
);
3649 g_routing_id_view_map
.Get().erase(routing_id_
);
3652 void RenderViewImpl::DidHandleKeyEvent() {
3653 ClearEditCommands();
3656 void RenderViewImpl::WillProcessUserGesture() {
3658 RenderViewObserver
, observers_
, WillProcessUserGesture());
3661 bool RenderViewImpl::WillHandleMouseEvent(const blink::WebMouseEvent
& event
) {
3662 possible_drag_event_info_
.event_source
=
3663 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE
;
3664 possible_drag_event_info_
.event_location
=
3665 gfx::Point(event
.globalX
, event
.globalY
);
3667 #if defined(ENABLE_PLUGINS)
3668 // This method is called for every mouse event that the render view receives.
3669 // And then the mouse event is forwarded to WebKit, which dispatches it to the
3670 // event target. Potentially a Pepper plugin will receive the event.
3671 // In order to tell whether a plugin gets the last mouse event and which it
3672 // is, we set |pepper_last_mouse_event_target_| to NULL here. If a plugin gets
3673 // the event, it will notify us via DidReceiveMouseEvent() and set itself as
3674 // |pepper_last_mouse_event_target_|.
3675 pepper_last_mouse_event_target_
= NULL
;
3678 // If the mouse is locked, only the current owner of the mouse lock can
3679 // process mouse events.
3680 return mouse_lock_dispatcher_
->WillHandleMouseEvent(event
);
3683 bool RenderViewImpl::WillHandleGestureEvent(
3684 const blink::WebGestureEvent
& event
) {
3685 possible_drag_event_info_
.event_source
=
3686 ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH
;
3687 possible_drag_event_info_
.event_location
=
3688 gfx::Point(event
.globalX
, event
.globalY
);
3692 void RenderViewImpl::DidHandleMouseEvent(const WebMouseEvent
& event
) {
3693 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidHandleMouseEvent(event
));
3696 void RenderViewImpl::DidHandleTouchEvent(const WebTouchEvent
& event
) {
3697 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidHandleTouchEvent(event
));
3700 bool RenderViewImpl::HasTouchEventHandlersAt(const gfx::Point
& point
) const {
3703 return webview()->hasTouchEventHandlersAt(point
);
3706 void RenderViewImpl::OnWasHidden() {
3707 RenderWidget::OnWasHidden();
3709 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3710 RenderThreadImpl::current()->video_capture_impl_manager()->
3711 SuspendDevices(true);
3715 webview()->setVisibilityState(visibilityState(), false);
3717 #if defined(ENABLE_PLUGINS)
3718 for (PepperPluginSet::iterator i
= active_pepper_instances_
.begin();
3719 i
!= active_pepper_instances_
.end(); ++i
)
3720 (*i
)->PageVisibilityChanged(false);
3722 #if defined(OS_MACOSX)
3723 // Inform NPAPI plugins that their container is no longer visible.
3724 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
3725 for (plugin_it
= plugin_delegates_
.begin();
3726 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
3727 (*plugin_it
)->SetContainerVisibility(false);
3730 #endif // ENABLE_PLUGINS
3733 void RenderViewImpl::OnWasShown(bool needs_repainting
) {
3734 RenderWidget::OnWasShown(needs_repainting
);
3736 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3737 RenderThreadImpl::current()->video_capture_impl_manager()->
3738 SuspendDevices(false);
3742 webview()->setVisibilityState(visibilityState(), false);
3744 #if defined(ENABLE_PLUGINS)
3745 for (PepperPluginSet::iterator i
= active_pepper_instances_
.begin();
3746 i
!= active_pepper_instances_
.end(); ++i
)
3747 (*i
)->PageVisibilityChanged(true);
3749 #if defined(OS_MACOSX)
3750 // Inform NPAPI plugins that their container is now visible.
3751 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
3752 for (plugin_it
= plugin_delegates_
.begin();
3753 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
3754 (*plugin_it
)->SetContainerVisibility(true);
3757 #endif // ENABLE_PLUGINS
3760 GURL
RenderViewImpl::GetURLForGraphicsContext3D() {
3762 if (webview()->mainFrame())
3763 return GURL(webview()->mainFrame()->document().url());
3765 return GURL("chrome://gpu/RenderViewImpl::CreateGraphicsContext3D");
3768 bool RenderViewImpl::ForceCompositingModeEnabled() {
3769 return webkit_preferences_
.force_compositing_mode
;
3772 void RenderViewImpl::OnSetFocus(bool enable
) {
3773 RenderWidget::OnSetFocus(enable
);
3775 #if defined(ENABLE_PLUGINS)
3776 if (webview() && webview()->isActive()) {
3777 // Notify all NPAPI plugins.
3778 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
3779 for (plugin_it
= plugin_delegates_
.begin();
3780 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
3781 #if defined(OS_MACOSX)
3782 // RenderWidget's call to setFocus can cause the underlying webview's
3783 // activation state to change just like a call to setIsActive.
3785 (*plugin_it
)->SetWindowFocus(true);
3787 (*plugin_it
)->SetContentAreaFocus(enable
);
3790 // Notify all Pepper plugins.
3791 for (PepperPluginSet::iterator i
= active_pepper_instances_
.begin();
3792 i
!= active_pepper_instances_
.end(); ++i
)
3793 (*i
)->SetContentAreaFocus(enable
);
3795 // Notify all BrowserPlugins of the RenderView's focus state.
3796 if (browser_plugin_manager_
.get())
3797 browser_plugin_manager_
->UpdateFocusState();
3800 void RenderViewImpl::OnImeSetComposition(
3801 const base::string16
& text
,
3802 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
3803 int selection_start
,
3804 int selection_end
) {
3805 #if defined(ENABLE_PLUGINS)
3806 if (focused_pepper_plugin_
) {
3807 focused_pepper_plugin_
->render_frame()->OnImeSetComposition(
3808 text
, underlines
, selection_start
, selection_end
);
3813 // When a plug-in has focus, we create platform-specific IME data used by
3814 // our IME emulator and send it directly to the focused plug-in, i.e. we
3815 // bypass WebKit. (WebPluginDelegate dispatches this IME data only when its
3816 // instance ID is the same one as the specified ID.)
3817 if (focused_plugin_id_
>= 0) {
3818 std::vector
<int> clauses
;
3819 std::vector
<int> target
;
3820 for (size_t i
= 0; i
< underlines
.size(); ++i
) {
3821 clauses
.push_back(underlines
[i
].startOffset
);
3822 clauses
.push_back(underlines
[i
].endOffset
);
3823 if (underlines
[i
].thick
) {
3825 target
.push_back(underlines
[i
].startOffset
);
3826 target
.push_back(underlines
[i
].endOffset
);
3829 std::set
<WebPluginDelegateProxy
*>::iterator it
;
3830 for (it
= plugin_delegates_
.begin(); it
!= plugin_delegates_
.end(); ++it
) {
3831 (*it
)->ImeCompositionUpdated(text
, clauses
, target
, selection_end
,
3832 focused_plugin_id_
);
3837 #endif // ENABLE_PLUGINS
3838 RenderWidget::OnImeSetComposition(text
,
3844 void RenderViewImpl::OnImeConfirmComposition(
3845 const base::string16
& text
,
3846 const gfx::Range
& replacement_range
,
3847 bool keep_selection
) {
3848 #if defined(ENABLE_PLUGINS)
3849 if (focused_pepper_plugin_
) {
3850 focused_pepper_plugin_
->render_frame()->OnImeConfirmComposition(
3851 text
, replacement_range
, keep_selection
);
3855 // Same as OnImeSetComposition(), we send the text from IMEs directly to
3856 // plug-ins. When we send IME text directly to plug-ins, we should not send
3857 // it to WebKit to prevent WebKit from controlling IMEs.
3858 // TODO(thakis): Honor |replacement_range| for plugins?
3859 if (focused_plugin_id_
>= 0) {
3860 std::set
<WebPluginDelegateProxy
*>::iterator it
;
3861 for (it
= plugin_delegates_
.begin();
3862 it
!= plugin_delegates_
.end(); ++it
) {
3863 (*it
)->ImeCompositionCompleted(text
, focused_plugin_id_
);
3868 #endif // ENABLE_PLUGINS
3869 if (replacement_range
.IsValid() && webview()) {
3870 // Select the text in |replacement_range|, it will then be replaced by
3871 // text added by the call to RenderWidget::OnImeConfirmComposition().
3872 if (WebLocalFrame
* frame
= webview()->focusedFrame()->toWebLocalFrame()) {
3873 WebRange webrange
= WebRange::fromDocumentRange(
3874 frame
, replacement_range
.start(), replacement_range
.length());
3875 if (!webrange
.isNull())
3876 frame
->selectRange(webrange
);
3879 RenderWidget::OnImeConfirmComposition(text
,
3884 void RenderViewImpl::SetDeviceScaleFactor(float device_scale_factor
) {
3885 RenderWidget::SetDeviceScaleFactor(device_scale_factor
);
3887 webview()->setDeviceScaleFactor(device_scale_factor
);
3888 webview()->settings()->setAcceleratedCompositingForFixedPositionEnabled(
3889 ShouldUseFixedPositionCompositing(device_scale_factor_
));
3890 webview()->settings()->setAcceleratedCompositingForOverflowScrollEnabled(
3891 ShouldUseAcceleratedCompositingForOverflowScroll(device_scale_factor_
));
3892 webview()->settings()->setAcceleratedCompositingForTransitionEnabled(
3893 ShouldUseTransitionCompositing(device_scale_factor_
));
3894 webview()->settings()->
3895 setAcceleratedCompositingForFixedRootBackgroundEnabled(
3896 ShouldUseAcceleratedFixedRootBackground(device_scale_factor_
));
3897 webview()->settings()->setCompositedScrollingForFramesEnabled(
3898 ShouldUseCompositedScrollingForFrames(device_scale_factor_
));
3900 if (auto_resize_mode_
)
3901 AutoResizeCompositor();
3903 if (browser_plugin_manager_
.get())
3904 browser_plugin_manager_
->UpdateDeviceScaleFactor(device_scale_factor_
);
3907 ui::TextInputType
RenderViewImpl::GetTextInputType() {
3908 #if defined(ENABLE_PLUGINS)
3909 if (focused_pepper_plugin_
)
3910 return focused_pepper_plugin_
->text_input_type();
3912 return RenderWidget::GetTextInputType();
3915 void RenderViewImpl::GetSelectionBounds(gfx::Rect
* start
, gfx::Rect
* end
) {
3916 #if defined(ENABLE_PLUGINS)
3917 if (focused_pepper_plugin_
) {
3918 // TODO(kinaba) http://crbug.com/101101
3919 // Current Pepper IME API does not handle selection bounds. So we simply
3920 // use the caret position as an empty range for now. It will be updated
3921 // after Pepper API equips features related to surrounding text retrieval.
3922 gfx::Rect caret
= focused_pepper_plugin_
->GetCaretBounds();
3928 RenderWidget::GetSelectionBounds(start
, end
);
3931 #if defined(OS_MACOSX) || defined(USE_AURA)
3932 void RenderViewImpl::GetCompositionCharacterBounds(
3933 std::vector
<gfx::Rect
>* bounds
) {
3937 #if defined(ENABLE_PLUGINS)
3938 if (focused_pepper_plugin_
) {
3945 size_t start_offset
= 0;
3946 size_t character_count
= 0;
3947 if (!webview()->compositionRange(&start_offset
, &character_count
))
3949 if (character_count
== 0)
3952 blink::WebFrame
* frame
= webview()->focusedFrame();
3956 bounds
->reserve(character_count
);
3957 blink::WebRect webrect
;
3958 for (size_t i
= 0; i
< character_count
; ++i
) {
3959 if (!frame
->firstRectForCharacterRange(start_offset
+ i
, 1, webrect
)) {
3960 DLOG(ERROR
) << "Could not retrieve character rectangle at " << i
;
3964 bounds
->push_back(webrect
);
3968 void RenderViewImpl::GetCompositionRange(gfx::Range
* range
) {
3969 #if defined(ENABLE_PLUGINS)
3970 if (focused_pepper_plugin_
) {
3974 RenderWidget::GetCompositionRange(range
);
3978 bool RenderViewImpl::CanComposeInline() {
3979 #if defined(ENABLE_PLUGINS)
3980 if (focused_pepper_plugin_
)
3981 return focused_pepper_plugin_
->IsPluginAcceptingCompositionEvents();
3986 void RenderViewImpl::InstrumentWillBeginFrame(int frame_id
) {
3989 if (!webview()->devToolsAgent())
3991 webview()->devToolsAgent()->didBeginFrame(frame_id
);
3994 void RenderViewImpl::InstrumentDidBeginFrame() {
3997 if (!webview()->devToolsAgent())
3999 // TODO(jamesr/caseq): Decide if this needs to be renamed.
4000 webview()->devToolsAgent()->didComposite();
4003 void RenderViewImpl::InstrumentDidCancelFrame() {
4006 if (!webview()->devToolsAgent())
4008 webview()->devToolsAgent()->didCancelFrame();
4011 void RenderViewImpl::InstrumentWillComposite() {
4014 if (!webview()->devToolsAgent())
4016 webview()->devToolsAgent()->willComposite();
4019 void RenderViewImpl::SetScreenMetricsEmulationParameters(
4020 float device_scale_factor
,
4021 const gfx::Point
& root_layer_offset
,
4022 float root_layer_scale
) {
4024 webview()->setCompositorDeviceScaleFactorOverride(device_scale_factor
);
4025 webview()->setRootLayerTransform(
4026 blink::WebSize(root_layer_offset
.x(), root_layer_offset
.y()),
4031 bool RenderViewImpl::ScheduleFileChooser(
4032 const FileChooserParams
& params
,
4033 WebFileChooserCompletion
* completion
) {
4034 static const size_t kMaximumPendingFileChooseRequests
= 4;
4035 if (file_chooser_completions_
.size() > kMaximumPendingFileChooseRequests
) {
4036 // This sanity check prevents too many file choose requests from getting
4037 // queued which could DoS the user. Getting these is most likely a
4038 // programming error (there are many ways to DoS the user so it's not
4039 // considered a "real" security check), either in JS requesting many file
4040 // choosers to pop up, or in a plugin.
4042 // TODO(brettw) we might possibly want to require a user gesture to open
4043 // a file picker, which will address this issue in a better way.
4047 file_chooser_completions_
.push_back(linked_ptr
<PendingFileChooser
>(
4048 new PendingFileChooser(params
, completion
)));
4049 if (file_chooser_completions_
.size() == 1) {
4050 // Actually show the browse dialog when this is the first request.
4051 Send(new ViewHostMsg_RunFileChooser(routing_id_
, params
));
4056 blink::WebGeolocationClient
* RenderViewImpl::geolocationClient() {
4057 if (!geolocation_dispatcher_
)
4058 geolocation_dispatcher_
= new GeolocationDispatcher(this);
4059 return geolocation_dispatcher_
;
4062 blink::WebSpeechInputController
* RenderViewImpl::speechInputController(
4063 blink::WebSpeechInputListener
* listener
) {
4064 #if defined(ENABLE_INPUT_SPEECH)
4065 if (!input_tag_speech_dispatcher_
)
4066 input_tag_speech_dispatcher_
=
4067 new InputTagSpeechDispatcher(this, listener
);
4069 return input_tag_speech_dispatcher_
;
4072 blink::WebSpeechRecognizer
* RenderViewImpl::speechRecognizer() {
4073 if (!speech_recognition_dispatcher_
)
4074 speech_recognition_dispatcher_
= new SpeechRecognitionDispatcher(this);
4075 return speech_recognition_dispatcher_
;
4078 void RenderViewImpl::zoomLimitsChanged(double minimum_level
,
4079 double maximum_level
) {
4080 // For now, don't remember plugin zoom values. We don't want to mix them with
4081 // normal web content (i.e. a fixed layout plugin would usually want them
4083 bool remember
= !webview()->mainFrame()->document().isPluginDocument();
4085 int minimum_percent
= static_cast<int>(
4086 ZoomLevelToZoomFactor(minimum_level
) * 100);
4087 int maximum_percent
= static_cast<int>(
4088 ZoomLevelToZoomFactor(maximum_level
) * 100);
4090 Send(new ViewHostMsg_UpdateZoomLimits(
4091 routing_id_
, minimum_percent
, maximum_percent
, remember
));
4094 void RenderViewImpl::zoomLevelChanged() {
4095 bool remember
= !webview()->mainFrame()->document().isPluginDocument();
4096 float zoom_level
= webview()->zoomLevel();
4098 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, ZoomLevelChanged());
4100 // Tell the browser which url got zoomed so it can update the menu and the
4101 // saved values if necessary
4102 Send(new ViewHostMsg_DidZoomURL(
4103 routing_id_
, zoom_level
, remember
,
4104 GURL(webview()->mainFrame()->document().url())));
4107 double RenderViewImpl::zoomLevelToZoomFactor(double zoom_level
) const {
4108 return ZoomLevelToZoomFactor(zoom_level
);
4111 double RenderViewImpl::zoomFactorToZoomLevel(double factor
) const {
4112 return ZoomFactorToZoomLevel(factor
);
4115 void RenderViewImpl::registerProtocolHandler(const WebString
& scheme
,
4116 const WebURL
& base_url
,
4118 const WebString
& title
) {
4119 bool user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
4120 GURL
base(base_url
);
4121 GURL absolute_url
= base
.Resolve(base::UTF16ToUTF8(url
.string()));
4122 if (base
.GetOrigin() != absolute_url
.GetOrigin()) {
4125 Send(new ViewHostMsg_RegisterProtocolHandler(routing_id_
,
4126 base::UTF16ToUTF8(scheme
),
4132 blink::WebPageVisibilityState
RenderViewImpl::visibilityState() const {
4133 blink::WebPageVisibilityState current_state
= is_hidden() ?
4134 blink::WebPageVisibilityStateHidden
:
4135 blink::WebPageVisibilityStateVisible
;
4136 blink::WebPageVisibilityState override_state
= current_state
;
4137 // TODO(jam): move this method to WebFrameClient.
4138 if (GetContentClient()->renderer()->
4139 ShouldOverridePageVisibilityState(main_render_frame_
.get(),
4141 return override_state
;
4142 return current_state
;
4145 blink::WebUserMediaClient
* RenderViewImpl::userMediaClient() {
4146 // This can happen in tests, in which case it's OK to return NULL.
4147 if (!InitializeMediaStreamClient())
4150 return web_user_media_client_
;
4153 blink::WebMIDIClient
* RenderViewImpl::webMIDIClient() {
4154 if (!midi_dispatcher_
)
4155 midi_dispatcher_
= new MidiDispatcher(this);
4156 return midi_dispatcher_
;
4159 blink::WebPushClient
* RenderViewImpl::webPushClient() {
4160 if (!push_messaging_dispatcher_
)
4161 push_messaging_dispatcher_
= new PushMessagingDispatcher(this);
4162 return push_messaging_dispatcher_
;
4165 void RenderViewImpl::draggableRegionsChanged() {
4169 DraggableRegionsChanged(webview()->mainFrame()));
4172 WebMediaPlayer
* RenderViewImpl::CreateWebMediaPlayerForMediaStream(
4174 const blink::WebURL
& url
,
4175 WebMediaPlayerClient
* client
) {
4176 #if defined(ENABLE_WEBRTC)
4177 if (!InitializeMediaStreamClient()) {
4178 LOG(ERROR
) << "Failed to initialize MediaStreamClient";
4181 if (media_stream_client_
->IsMediaStream(url
)) {
4182 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4184 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON
) != 0;
4185 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon
);
4186 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4187 return new WebMediaPlayerMS(frame
, client
, AsWeakPtr(),
4188 media_stream_client_
, new RenderMediaLog());
4190 #endif // defined(ENABLE_WEBRTC)
4194 #if defined(OS_ANDROID)
4195 WebContentDetectionResult
RenderViewImpl::detectContentAround(
4196 const WebHitTestResult
& touch_hit
) {
4197 DCHECK(!touch_hit
.isNull());
4198 DCHECK(!touch_hit
.node().isNull());
4199 DCHECK(touch_hit
.node().isTextNode());
4201 // Process the position with all the registered content detectors until
4202 // a match is found. Priority is provided by their relative order.
4203 for (ContentDetectorList::const_iterator it
= content_detectors_
.begin();
4204 it
!= content_detectors_
.end(); ++it
) {
4205 ContentDetector::Result content
= (*it
)->FindTappedContent(touch_hit
);
4206 if (content
.valid
) {
4207 return WebContentDetectionResult(content
.content_boundaries
,
4208 base::UTF8ToUTF16(content
.text
), content
.intent_url
);
4211 return WebContentDetectionResult();
4214 void RenderViewImpl::scheduleContentIntent(const WebURL
& intent
) {
4215 // Introduce a short delay so that the user can notice the content.
4216 base::MessageLoop::current()->PostDelayedTask(
4218 base::Bind(&RenderViewImpl::LaunchAndroidContentIntent
,
4221 expected_content_intent_id_
),
4222 base::TimeDelta::FromMilliseconds(kContentIntentDelayMilliseconds
));
4225 void RenderViewImpl::cancelScheduledContentIntents() {
4226 ++expected_content_intent_id_
;
4229 void RenderViewImpl::LaunchAndroidContentIntent(const GURL
& intent
,
4230 size_t request_id
) {
4231 if (request_id
!= expected_content_intent_id_
)
4234 // Remove the content highlighting if any.
4235 scheduleComposite();
4237 if (!intent
.is_empty())
4238 Send(new ViewHostMsg_StartContentIntent(routing_id_
, intent
));
4241 bool RenderViewImpl::openDateTimeChooser(
4242 const blink::WebDateTimeChooserParams
& params
,
4243 blink::WebDateTimeChooserCompletion
* completion
) {
4244 // JavaScript may try to open a date time chooser while one is already open.
4245 if (date_time_picker_client_
)
4247 date_time_picker_client_
.reset(
4248 new RendererDateTimePicker(this, params
, completion
));
4249 return date_time_picker_client_
->Open();
4252 void RenderViewImpl::DismissDateTimeDialog() {
4253 DCHECK(date_time_picker_client_
);
4254 date_time_picker_client_
.reset(NULL
);
4257 WebMediaPlayer
* RenderViewImpl::CreateAndroidWebMediaPlayer(
4259 const blink::WebURL
& url
,
4260 WebMediaPlayerClient
* client
) {
4261 GpuChannelHost
* gpu_channel_host
=
4262 RenderThreadImpl::current()->EstablishGpuChannelSync(
4263 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE
);
4264 if (!gpu_channel_host
) {
4265 LOG(ERROR
) << "Failed to establish GPU channel for media player";
4269 scoped_refptr
<StreamTextureFactory
> stream_texture_factory
;
4270 if (UsingSynchronousRendererCompositor()) {
4271 SynchronousCompositorFactory
* factory
=
4272 SynchronousCompositorFactory::GetInstance();
4273 stream_texture_factory
= factory
->CreateStreamTextureFactory(routing_id_
);
4275 scoped_refptr
<webkit::gpu::ContextProviderWebContext
> context_provider
=
4276 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4278 if (!context_provider
.get()) {
4279 LOG(ERROR
) << "Failed to get context3d for media player";
4283 stream_texture_factory
= StreamTextureFactoryImpl::Create(
4284 context_provider
, gpu_channel_host
, routing_id_
);
4287 return new WebMediaPlayerAndroid(
4291 media_player_manager_
,
4292 stream_texture_factory
,
4293 RenderThreadImpl::current()->GetMediaThreadMessageLoopProxy(),
4294 new RenderMediaLog());
4297 #endif // defined(OS_ANDROID)
4299 #if defined(OS_MACOSX)
4300 void RenderViewImpl::OnSelectPopupMenuItem(int selected_index
) {
4301 if (external_popup_menu_
== NULL
)
4303 external_popup_menu_
->DidSelectItem(selected_index
);
4304 external_popup_menu_
.reset();
4308 #if defined(OS_ANDROID)
4309 void RenderViewImpl::OnSelectPopupMenuItems(
4311 const std::vector
<int>& selected_indices
) {
4312 // It is possible to receive more than one of these calls if the user presses
4313 // a select faster than it takes for the show-select-popup IPC message to make
4314 // it to the browser UI thread. Ignore the extra-messages.
4315 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
4316 if (!external_popup_menu_
)
4319 external_popup_menu_
->DidSelectItems(canceled
, selected_indices
);
4320 external_popup_menu_
.reset();
4324 #if defined(OS_MACOSX) || defined(OS_ANDROID)
4325 void RenderViewImpl::DidHideExternalPopupMenu() {
4326 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
4327 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
4328 external_popup_menu_
.reset();
4332 void RenderViewImpl::OnShowContextMenu(const gfx::Point
& location
) {
4333 context_menu_source_type_
= ui::MENU_SOURCE_TOUCH_EDIT_MENU
;
4334 touch_editing_context_menu_location_
= location
;
4336 webview()->showContextMenu();
4339 void RenderViewImpl::OnEnableViewSourceMode() {
4342 WebFrame
* main_frame
= webview()->mainFrame();
4345 main_frame
->enableViewSourceMode(true);
4348 void RenderViewImpl::OnDisownOpener() {
4352 WebFrame
* main_frame
= webview()->mainFrame();
4353 if (main_frame
&& main_frame
->opener())
4354 main_frame
->setOpener(NULL
);
4357 #if defined(OS_ANDROID)
4358 bool RenderViewImpl::didTapMultipleTargets(
4359 const blink::WebGestureEvent
& event
,
4360 const WebVector
<WebRect
>& target_rects
) {
4361 // Never show a disambiguation popup when accessibility is enabled,
4362 // as this interferes with "touch exploration".
4363 bool matchesAccessibilityModeComplete
=
4364 (accessibility_mode_
& AccessibilityModeComplete
) ==
4365 AccessibilityModeComplete
;
4366 if (matchesAccessibilityModeComplete
)
4369 gfx::Rect
finger_rect(
4370 event
.x
- event
.data
.tap
.width
/ 2, event
.y
- event
.data
.tap
.height
/ 2,
4371 event
.data
.tap
.width
, event
.data
.tap
.height
);
4372 gfx::Rect zoom_rect
;
4373 float new_total_scale
=
4374 DisambiguationPopupHelper::ComputeZoomAreaAndScaleFactor(
4375 finger_rect
, target_rects
, GetSize(),
4376 gfx::Rect(webview()->mainFrame()->visibleContentRect()).size(),
4377 device_scale_factor_
* webview()->pageScaleFactor(), &zoom_rect
);
4378 if (!new_total_scale
)
4381 bool handled
= false;
4382 switch (renderer_preferences_
.tap_multiple_targets_strategy
) {
4383 case TAP_MULTIPLE_TARGETS_STRATEGY_ZOOM
:
4384 handled
= webview()->zoomToMultipleTargetsRect(zoom_rect
);
4386 case TAP_MULTIPLE_TARGETS_STRATEGY_POPUP
: {
4387 gfx::Size canvas_size
=
4388 gfx::ToCeiledSize(gfx::ScaleSize(zoom_rect
.size(), new_total_scale
));
4389 TransportDIB
* transport_dib
= NULL
;
4391 scoped_ptr
<skia::PlatformCanvas
> canvas(
4392 RenderProcess::current()->GetDrawingCanvas(&transport_dib
,
4393 gfx::Rect(canvas_size
)));
4399 // TODO(trchen): Cleanup the device scale factor mess.
4400 // device scale will be applied in WebKit
4401 // --> zoom_rect doesn't include device scale,
4402 // but WebKit will still draw on zoom_rect * device_scale_factor_
4403 canvas
->scale(new_total_scale
/ device_scale_factor_
,
4404 new_total_scale
/ device_scale_factor_
);
4405 canvas
->translate(-zoom_rect
.x() * device_scale_factor_
,
4406 -zoom_rect
.y() * device_scale_factor_
);
4411 WebWidget::ForceSoftwareRenderingAndIgnoreGPUResidentContent
);
4414 gfx::Rect physical_window_zoom_rect
= gfx::ToEnclosingRect(
4415 ClientRectToPhysicalWindowRect(gfx::RectF(zoom_rect
)));
4416 Send(new ViewHostMsg_ShowDisambiguationPopup(routing_id_
,
4417 physical_window_zoom_rect
,
4419 transport_dib
->id()));
4423 case TAP_MULTIPLE_TARGETS_STRATEGY_NONE
:
4432 unsigned RenderViewImpl::GetLocalSessionHistoryLengthForTesting() const {
4433 return history_list_length_
;
4436 void RenderViewImpl::SetFocusAndActivateForTesting(bool enable
) {
4450 void RenderViewImpl::SetDeviceScaleFactorForTesting(float factor
) {
4451 ViewMsg_Resize_Params params
;
4452 params
.screen_info
= screen_info_
;
4453 params
.screen_info
.deviceScaleFactor
= factor
;
4454 params
.new_size
= size();
4455 params
.physical_backing_size
=
4456 gfx::ToCeiledSize(gfx::ScaleSize(size(), factor
));
4457 params
.overdraw_bottom_height
= 0.f
;
4458 params
.resizer_rect
= WebRect();
4459 params
.is_fullscreen
= is_fullscreen();
4463 void RenderViewImpl::ForceResizeForTesting(const gfx::Size
& new_size
) {
4464 gfx::Rect
new_position(rootWindowRect().x
,
4468 ResizeSynchronously(new_position
);
4471 void RenderViewImpl::UseSynchronousResizeModeForTesting(bool enable
) {
4472 resizing_mode_selector_
->set_is_synchronous_mode(enable
);
4475 void RenderViewImpl::EnableAutoResizeForTesting(const gfx::Size
& min_size
,
4476 const gfx::Size
& max_size
) {
4477 OnEnableAutoResize(min_size
, max_size
);
4480 void RenderViewImpl::DisableAutoResizeForTesting(const gfx::Size
& new_size
) {
4481 OnDisableAutoResize(new_size
);
4484 void RenderViewImpl::SetMediaStreamClientForTesting(
4485 MediaStreamClient
* media_stream_client
) {
4486 DCHECK(!media_stream_client_
);
4487 DCHECK(!web_user_media_client_
);
4488 media_stream_client_
= media_stream_client
;
4491 void RenderViewImpl::OnReleaseDisambiguationPopupDIB(
4492 TransportDIB::Handle dib_handle
) {
4493 TransportDIB
* dib
= TransportDIB::CreateWithHandle(dib_handle
);
4494 RenderProcess::current()->ReleaseTransportDIB(dib
);
4497 void RenderViewImpl::DidCommitCompositorFrame() {
4498 RenderWidget::DidCommitCompositorFrame();
4499 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidCommitCompositorFrame());
4502 void RenderViewImpl::SendUpdateFaviconURL(const std::vector
<FaviconURL
>& urls
) {
4504 Send(new ViewHostMsg_UpdateFaviconURL(routing_id_
, page_id_
, urls
));
4507 void RenderViewImpl::DidStopLoadingIcons() {
4508 int icon_types
= WebIconURL::TypeFavicon
;
4510 icon_types
|= WebIconURL::TypeTouchPrecomposed
| WebIconURL::TypeTouch
;
4512 WebVector
<WebIconURL
> icon_urls
=
4513 webview()->mainFrame()->iconURLs(icon_types
);
4515 std::vector
<FaviconURL
> urls
;
4516 for (size_t i
= 0; i
< icon_urls
.size(); i
++) {
4517 WebURL url
= icon_urls
[i
].iconURL();
4518 std::vector
<gfx::Size
> sizes
;
4519 ConvertToFaviconSizes(icon_urls
[i
].sizes(), &sizes
);
4522 FaviconURL(url
, ToFaviconType(icon_urls
[i
].iconType()), sizes
));
4524 SendUpdateFaviconURL(urls
);
4527 } // namespace content