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/clipboard_messages.h"
42 #include "content/common/database_messages.h"
43 #include "content/common/dom_storage/dom_storage_types.h"
44 #include "content/common/drag_messages.h"
45 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
46 #include "content/common/input_messages.h"
47 #include "content/common/java_bridge_messages.h"
48 #include "content/common/pepper_messages.h"
49 #include "content/common/socket_stream_handle_data.h"
50 #include "content/common/ssl_status_serialization.h"
51 #include "content/common/view_messages.h"
52 #include "content/public/common/bindings_policy.h"
53 #include "content/public/common/content_client.h"
54 #include "content/public/common/content_constants.h"
55 #include "content/public/common/content_switches.h"
56 #include "content/public/common/context_menu_params.h"
57 #include "content/public/common/drop_data.h"
58 #include "content/public/common/favicon_url.h"
59 #include "content/public/common/file_chooser_params.h"
60 #include "content/public/common/page_zoom.h"
61 #include "content/public/common/ssl_status.h"
62 #include "content/public/common/three_d_api_types.h"
63 #include "content/public/common/url_constants.h"
64 #include "content/public/common/url_utils.h"
65 #include "content/public/renderer/content_renderer_client.h"
66 #include "content/public/renderer/context_menu_client.h"
67 #include "content/public/renderer/document_state.h"
68 #include "content/public/renderer/history_item_serialization.h"
69 #include "content/public/renderer/navigation_state.h"
70 #include "content/public/renderer/render_view_observer.h"
71 #include "content/public/renderer/render_view_visitor.h"
72 #include "content/public/renderer/web_preferences.h"
73 #include "content/renderer/accessibility/renderer_accessibility.h"
74 #include "content/renderer/accessibility/renderer_accessibility_complete.h"
75 #include "content/renderer/accessibility/renderer_accessibility_focus_only.h"
76 #include "content/renderer/browser_plugin/browser_plugin.h"
77 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
78 #include "content/renderer/browser_plugin/browser_plugin_manager_impl.h"
79 #include "content/renderer/context_menu_params_builder.h"
80 #include "content/renderer/devtools/devtools_agent.h"
81 #include "content/renderer/disambiguation_popup_helper.h"
82 #include "content/renderer/dom_automation_controller.h"
83 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
84 #include "content/renderer/drop_data_builder.h"
85 #include "content/renderer/external_popup_menu.h"
86 #include "content/renderer/fetchers/alt_error_page_resource_fetcher.h"
87 #include "content/renderer/geolocation_dispatcher.h"
88 #include "content/renderer/gpu/render_widget_compositor.h"
89 #include "content/renderer/idle_user_detector.h"
90 #include "content/renderer/image_loading_helper.h"
91 #include "content/renderer/ime_event_guard.h"
92 #include "content/renderer/input/input_handler_manager.h"
93 #include "content/renderer/input_tag_speech_dispatcher.h"
94 #include "content/renderer/internal_document_state_data.h"
95 #include "content/renderer/java/java_bridge_dispatcher.h"
96 #include "content/renderer/load_progress_tracker.h"
97 #include "content/renderer/media/audio_device_factory.h"
98 #include "content/renderer/media/audio_renderer_mixer_manager.h"
99 #include "content/renderer/media/media_stream_dependency_factory.h"
100 #include "content/renderer/media/media_stream_dispatcher.h"
101 #include "content/renderer/media/media_stream_impl.h"
102 #include "content/renderer/media/midi_dispatcher.h"
103 #include "content/renderer/media/render_media_log.h"
104 #include "content/renderer/media/video_capture_impl_manager.h"
105 #include "content/renderer/media/webmediaplayer_impl.h"
106 #include "content/renderer/media/webmediaplayer_ms.h"
107 #include "content/renderer/media/webmediaplayer_params.h"
108 #include "content/renderer/mhtml_generator.h"
109 #include "content/renderer/notification_provider.h"
110 #include "content/renderer/render_frame_impl.h"
111 #include "content/renderer/render_process.h"
112 #include "content/renderer/render_thread_impl.h"
113 #include "content/renderer/render_view_impl_params.h"
114 #include "content/renderer/render_view_mouse_lock_dispatcher.h"
115 #include "content/renderer/render_widget_fullscreen_pepper.h"
116 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
117 #include "content/renderer/renderer_webcolorchooser_impl.h"
118 #include "content/renderer/resizing_mode_selector.h"
119 #include "content/renderer/savable_resources.h"
120 #include "content/renderer/speech_recognition_dispatcher.h"
121 #include "content/renderer/stats_collection_controller.h"
122 #include "content/renderer/stats_collection_observer.h"
123 #include "content/renderer/text_input_client_observer.h"
124 #include "content/renderer/v8_value_converter_impl.h"
125 #include "content/renderer/web_ui_extension.h"
126 #include "content/renderer/web_ui_extension_data.h"
127 #include "content/renderer/websharedworker_proxy.h"
128 #include "media/audio/audio_output_device.h"
129 #include "media/base/audio_renderer_mixer_input.h"
130 #include "media/base/filter_collection.h"
131 #include "media/base/media_switches.h"
132 #include "media/filters/audio_renderer_impl.h"
133 #include "media/filters/gpu_video_accelerator_factories.h"
134 #include "net/base/data_url.h"
135 #include "net/base/escape.h"
136 #include "net/base/net_errors.h"
137 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
138 #include "net/http/http_util.h"
139 #include "third_party/WebKit/public/platform/WebCString.h"
140 #include "third_party/WebKit/public/platform/WebDragData.h"
141 #include "third_party/WebKit/public/platform/WebHTTPBody.h"
142 #include "third_party/WebKit/public/platform/WebImage.h"
143 #include "third_party/WebKit/public/platform/WebMessagePortChannel.h"
144 #include "third_party/WebKit/public/platform/WebPoint.h"
145 #include "third_party/WebKit/public/platform/WebRect.h"
146 #include "third_party/WebKit/public/platform/WebSize.h"
147 #include "third_party/WebKit/public/platform/WebSocketStreamHandle.h"
148 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
149 #include "third_party/WebKit/public/platform/WebString.h"
150 #include "third_party/WebKit/public/platform/WebURL.h"
151 #include "third_party/WebKit/public/platform/WebURLError.h"
152 #include "third_party/WebKit/public/platform/WebURLRequest.h"
153 #include "third_party/WebKit/public/platform/WebURLResponse.h"
154 #include "third_party/WebKit/public/platform/WebVector.h"
155 #include "third_party/WebKit/public/web/WebAXObject.h"
156 #include "third_party/WebKit/public/web/WebColorName.h"
157 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
158 #include "third_party/WebKit/public/web/WebDOMEvent.h"
159 #include "third_party/WebKit/public/web/WebDOMMessageEvent.h"
160 #include "third_party/WebKit/public/web/WebDataSource.h"
161 #include "third_party/WebKit/public/web/WebDateTimeChooserCompletion.h"
162 #include "third_party/WebKit/public/web/WebDateTimeChooserParams.h"
163 #include "third_party/WebKit/public/web/WebDevToolsAgent.h"
164 #include "third_party/WebKit/public/web/WebDocument.h"
165 #include "third_party/WebKit/public/web/WebElement.h"
166 #include "third_party/WebKit/public/web/WebFileChooserParams.h"
167 #include "third_party/WebKit/public/web/WebFindOptions.h"
168 #include "third_party/WebKit/public/web/WebFormControlElement.h"
169 #include "third_party/WebKit/public/web/WebFormElement.h"
170 #include "third_party/WebKit/public/web/WebFrame.h"
171 #include "third_party/WebKit/public/web/WebGlyphCache.h"
172 #include "third_party/WebKit/public/web/WebHelperPlugin.h"
173 #include "third_party/WebKit/public/web/WebHistoryItem.h"
174 #include "third_party/WebKit/public/web/WebInputElement.h"
175 #include "third_party/WebKit/public/web/WebInputEvent.h"
176 #include "third_party/WebKit/public/web/WebMediaPlayerAction.h"
177 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
178 #include "third_party/WebKit/public/web/WebNodeList.h"
179 #include "third_party/WebKit/public/web/WebPageSerializer.h"
180 #include "third_party/WebKit/public/web/WebPlugin.h"
181 #include "third_party/WebKit/public/web/WebPluginAction.h"
182 #include "third_party/WebKit/public/web/WebPluginContainer.h"
183 #include "third_party/WebKit/public/web/WebPluginDocument.h"
184 #include "third_party/WebKit/public/web/WebRange.h"
185 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
186 #include "third_party/WebKit/public/web/WebScriptSource.h"
187 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
188 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
189 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
190 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
191 #include "third_party/WebKit/public/web/WebSettings.h"
192 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
193 #include "third_party/WebKit/public/web/WebUserMediaClient.h"
194 #include "third_party/WebKit/public/web/WebView.h"
195 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
196 #include "third_party/WebKit/public/web/default/WebRenderTheme.h"
197 #include "ui/base/ui_base_switches_util.h"
198 #include "ui/events/latency_info.h"
199 #include "ui/gfx/native_widget_types.h"
200 #include "ui/gfx/point.h"
201 #include "ui/gfx/rect.h"
202 #include "ui/gfx/rect_conversions.h"
203 #include "ui/gfx/size_conversions.h"
204 #include "ui/shell_dialogs/selected_file_info.h"
205 #include "v8/include/v8.h"
206 #include "webkit/child/weburlresponse_extradata_impl.h"
208 #if defined(OS_ANDROID)
209 #include <cpu-features.h>
211 #include "content/common/android/device_telephony_info.h"
212 #include "content/common/gpu/client/context_provider_command_buffer.h"
213 #include "content/renderer/android/address_detector.h"
214 #include "content/renderer/android/content_detector.h"
215 #include "content/renderer/android/email_detector.h"
216 #include "content/renderer/android/phone_number_detector.h"
217 #include "content/renderer/android/synchronous_compositor_factory.h"
218 #include "content/renderer/media/android/renderer_media_player_manager.h"
219 #include "content/renderer/media/android/stream_texture_factory_android_impl.h"
220 #include "content/renderer/media/android/webmediaplayer_android.h"
221 #include "skia/ext/platform_canvas.h"
222 #include "third_party/WebKit/public/platform/WebFloatPoint.h"
223 #include "third_party/WebKit/public/platform/WebFloatRect.h"
224 #include "third_party/WebKit/public/web/WebHitTestResult.h"
225 #include "ui/gfx/rect_f.h"
227 #if defined(GOOGLE_TV)
228 #include "content/renderer/media/rtc_video_decoder_bridge_tv.h"
229 #include "content/renderer/media/rtc_video_decoder_factory_tv.h"
232 #elif defined(OS_WIN)
233 // TODO(port): these files are currently Windows only because they concern:
235 #include "ui/native_theme/native_theme_win.h"
236 #elif defined(USE_X11)
237 #include "ui/native_theme/native_theme.h"
238 #elif defined(OS_MACOSX)
239 #include "skia/ext/skia_utils_mac.h"
242 #if defined(ENABLE_PLUGINS)
243 #include "content/renderer/npapi/webplugin_delegate_proxy.h"
244 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
245 #include "content/renderer/pepper/pepper_plugin_registry.h"
248 #if defined(ENABLE_WEBRTC)
249 #include "content/renderer/media/rtc_peer_connection_handler.h"
252 using blink::WebAXObject
;
253 using blink::WebApplicationCacheHost
;
254 using blink::WebApplicationCacheHostClient
;
255 using blink::WebCString
;
256 using blink::WebColor
;
257 using blink::WebColorName
;
258 using blink::WebConsoleMessage
;
259 using blink::WebContextMenuData
;
260 using blink::WebData
;
261 using blink::WebDataSource
;
262 using blink::WebDocument
;
263 using blink::WebDOMEvent
;
264 using blink::WebDOMMessageEvent
;
265 using blink::WebDragData
;
266 using blink::WebDragOperation
;
267 using blink::WebDragOperationsMask
;
268 using blink::WebElement
;
269 using blink::WebExternalPopupMenu
;
270 using blink::WebExternalPopupMenuClient
;
271 using blink::WebFileChooserCompletion
;
272 using blink::WebFindOptions
;
273 using blink::WebFormControlElement
;
274 using blink::WebFormElement
;
275 using blink::WebFrame
;
276 using blink::WebGestureEvent
;
277 using blink::WebHistoryItem
;
278 using blink::WebHTTPBody
;
279 using blink::WebIconURL
;
280 using blink::WebImage
;
281 using blink::WebInputElement
;
282 using blink::WebInputEvent
;
283 using blink::WebMediaPlayer
;
284 using blink::WebMediaPlayerAction
;
285 using blink::WebMediaPlayerClient
;
286 using blink::WebMouseEvent
;
287 using blink::WebNavigationPolicy
;
288 using blink::WebNavigationType
;
289 using blink::WebNode
;
290 using blink::WebPageSerializer
;
291 using blink::WebPageSerializerClient
;
292 using blink::WebPeerConnection00Handler
;
293 using blink::WebPeerConnection00HandlerClient
;
294 using blink::WebPeerConnectionHandler
;
295 using blink::WebPeerConnectionHandlerClient
;
296 using blink::WebPluginAction
;
297 using blink::WebPluginContainer
;
298 using blink::WebPluginDocument
;
299 using blink::WebPoint
;
300 using blink::WebPopupMenuInfo
;
301 using blink::WebRange
;
302 using blink::WebRect
;
303 using blink::WebReferrerPolicy
;
304 using blink::WebRuntimeFeatures
;
305 using blink::WebScriptSource
;
306 using blink::WebSearchableFormData
;
307 using blink::WebSecurityOrigin
;
308 using blink::WebSecurityPolicy
;
309 using blink::WebSerializedScriptValue
;
310 using blink::WebSettings
;
311 using blink::WebSize
;
312 using blink::WebSocketStreamHandle
;
313 using blink::WebStorageNamespace
;
314 using blink::WebStorageQuotaCallbacks
;
315 using blink::WebStorageQuotaError
;
316 using blink::WebStorageQuotaType
;
317 using blink::WebString
;
318 using blink::WebTextAffinity
;
319 using blink::WebTextDirection
;
320 using blink::WebTouchEvent
;
322 using blink::WebURLError
;
323 using blink::WebURLRequest
;
324 using blink::WebURLResponse
;
325 using blink::WebUserGestureIndicator
;
326 using blink::WebVector
;
327 using blink::WebView
;
328 using blink::WebWidget
;
329 using blink::WebWindowFeatures
;
331 using base::TimeDelta
;
332 using webkit_glue::WebURLResponseExtraDataImpl
;
334 #if defined(OS_ANDROID)
335 using blink::WebContentDetectionResult
;
336 using blink::WebFloatPoint
;
337 using blink::WebFloatRect
;
338 using blink::WebHitTestResult
;
343 //-----------------------------------------------------------------------------
345 typedef std::map
<blink::WebView
*, RenderViewImpl
*> ViewMap
;
346 static base::LazyInstance
<ViewMap
> g_view_map
= LAZY_INSTANCE_INITIALIZER
;
347 typedef std::map
<int32
, RenderViewImpl
*> RoutingIDViewMap
;
348 static base::LazyInstance
<RoutingIDViewMap
> g_routing_id_view_map
=
349 LAZY_INSTANCE_INITIALIZER
;
351 // Time, in seconds, we delay before sending content state changes (such as form
352 // state and scroll position) to the browser. We delay sending changes to avoid
353 // spamming the browser.
354 // To avoid having tab/session restore require sending a message to get the
355 // current content state during tab closing we use a shorter timeout for the
356 // foreground renderer. This means there is a small window of time from which
357 // content state is modified and not sent to session restore, but this is
358 // better than having to wake up all renderers during shutdown.
359 const int kDelaySecondsForContentStateSyncHidden
= 5;
360 const int kDelaySecondsForContentStateSync
= 1;
362 const size_t kExtraCharsBeforeAndAfterSelection
= 100;
364 const float kScalingIncrementForGesture
= 0.01f
;
366 #if defined(OS_ANDROID)
367 // Delay between tapping in content and launching the associated android intent.
368 // Used to allow users see what has been recognized as content.
369 const size_t kContentIntentDelayMilliseconds
= 700;
372 static RenderViewImpl
* (*g_create_render_view_impl
)(RenderViewImplParams
*) =
375 static void GetRedirectChain(WebDataSource
* ds
, std::vector
<GURL
>* result
) {
376 // Replace any occurrences of swappedout:// with about:blank.
377 const WebURL
& blank_url
= GURL(kAboutBlankURL
);
378 WebVector
<WebURL
> urls
;
379 ds
->redirectChain(urls
);
380 result
->reserve(urls
.size());
381 for (size_t i
= 0; i
< urls
.size(); ++i
) {
382 if (urls
[i
] != GURL(kSwappedOutURL
))
383 result
->push_back(urls
[i
]);
385 result
->push_back(blank_url
);
389 // If |data_source| is non-null and has an InternalDocumentStateData associated
390 // with it, the AltErrorPageResourceFetcher is reset.
391 static void StopAltErrorPageFetcher(WebDataSource
* data_source
) {
393 InternalDocumentStateData
* internal_data
=
394 InternalDocumentStateData::FromDataSource(data_source
);
396 internal_data
->set_alt_error_page_fetcher(NULL
);
400 static bool IsReload(const ViewMsg_Navigate_Params
& params
) {
402 params
.navigation_type
== ViewMsg_Navigate_Type::RELOAD
||
403 params
.navigation_type
== ViewMsg_Navigate_Type::RELOAD_IGNORING_CACHE
||
404 params
.navigation_type
==
405 ViewMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
;
409 WebReferrerPolicy
RenderViewImpl::GetReferrerPolicyFromRequest(
411 const WebURLRequest
& request
) {
412 return request
.extraData() ?
413 static_cast<RequestExtraData
*>(request
.extraData())->referrer_policy() :
414 frame
->document().referrerPolicy();
418 Referrer
RenderViewImpl::GetReferrerFromRequest(
420 const WebURLRequest
& request
) {
421 return Referrer(GURL(request
.httpHeaderField(WebString::fromUTF8("Referer"))),
422 GetReferrerPolicyFromRequest(frame
, request
));
426 WebURLResponseExtraDataImpl
* RenderViewImpl::GetExtraDataFromResponse(
427 const WebURLResponse
& response
) {
428 return static_cast<WebURLResponseExtraDataImpl
*>(
429 response
.extraData());
432 NOINLINE
static void CrashIntentionally() {
433 // NOTE(shess): Crash directly rather than using NOTREACHED() so
434 // that the signature is easier to triage in crash reports.
435 volatile int* zero
= NULL
;
439 #if defined(ADDRESS_SANITIZER)
440 NOINLINE
static void MaybeTriggerAsanError(const GURL
& url
) {
441 // NOTE(rogerm): We intentionally perform an invalid heap access here in
442 // order to trigger an Address Sanitizer (ASAN) error report.
443 static const char kCrashDomain
[] = "crash";
444 static const char kHeapOverflow
[] = "/heap-overflow";
445 static const char kHeapUnderflow
[] = "/heap-underflow";
446 static const char kUseAfterFree
[] = "/use-after-free";
447 static const int kArraySize
= 5;
449 if (!url
.DomainIs(kCrashDomain
, sizeof(kCrashDomain
) - 1))
455 scoped_ptr
<int[]> array(new int[kArraySize
]);
456 std::string
crash_type(url
.path());
458 if (crash_type
== kHeapOverflow
) {
459 dummy
= array
[kArraySize
];
460 } else if (crash_type
== kHeapUnderflow
) {
462 } else if (crash_type
== kUseAfterFree
) {
463 int* dangling
= array
.get();
465 dummy
= dangling
[kArraySize
/ 2];
468 // Make sure the assignments to the dummy value aren't optimized away.
469 base::debug::Alias(&dummy
);
471 #endif // ADDRESS_SANITIZER
473 static void MaybeHandleDebugURL(const GURL
& url
) {
474 if (!url
.SchemeIs(chrome::kChromeUIScheme
))
476 if (url
== GURL(kChromeUICrashURL
)) {
477 CrashIntentionally();
478 } else if (url
== GURL(kChromeUIKillURL
)) {
479 base::KillProcess(base::GetCurrentProcessHandle(), 1, false);
480 } else if (url
== GURL(kChromeUIHangURL
)) {
482 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
484 } else if (url
== GURL(kChromeUIShorthangURL
)) {
485 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
488 #if defined(ADDRESS_SANITIZER)
489 MaybeTriggerAsanError(url
);
490 #endif // ADDRESS_SANITIZER
493 // Returns false unless this is a top-level navigation.
494 static bool IsTopLevelNavigation(WebFrame
* frame
) {
495 return frame
->parent() == NULL
;
498 // Returns false unless this is a top-level navigation that crosses origins.
499 static bool IsNonLocalTopLevelNavigation(const GURL
& url
,
501 WebNavigationType type
,
503 if (!IsTopLevelNavigation(frame
))
506 // Navigations initiated within Webkit are not sent out to the external host
507 // in the following cases.
508 // 1. The url scheme is not http/https
509 // 2. The origin of the url and the opener is the same in which case the
510 // opener relationship is maintained.
511 // 3. Reloads/form submits/back forward navigations
512 if (!url
.SchemeIs(kHttpScheme
) && !url
.SchemeIs(kHttpsScheme
))
515 if (type
!= blink::WebNavigationTypeReload
&&
516 type
!= blink::WebNavigationTypeBackForward
&& !is_form_post
) {
517 // The opener relationship between the new window and the parent allows the
518 // new window to script the parent and vice versa. This is not allowed if
519 // the origins of the two domains are different. This can be treated as a
520 // top level navigation and routed back to the host.
521 blink::WebFrame
* opener
= frame
->opener();
525 if (url
.GetOrigin() != GURL(opener
->document().url()).GetOrigin())
531 static void NotifyTimezoneChange(blink::WebFrame
* frame
) {
532 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
533 v8::Context::Scope
context_scope(frame
->mainWorldScriptContext());
534 v8::Date::DateTimeConfigurationChangeNotification(v8::Isolate::GetCurrent());
535 blink::WebFrame
* child
= frame
->firstChild();
536 for (; child
; child
= child
->nextSibling())
537 NotifyTimezoneChange(child
);
540 static WindowOpenDisposition
NavigationPolicyToDisposition(
541 WebNavigationPolicy policy
) {
543 case blink::WebNavigationPolicyIgnore
:
544 return IGNORE_ACTION
;
545 case blink::WebNavigationPolicyDownload
:
547 case blink::WebNavigationPolicyCurrentTab
:
549 case blink::WebNavigationPolicyNewBackgroundTab
:
550 return NEW_BACKGROUND_TAB
;
551 case blink::WebNavigationPolicyNewForegroundTab
:
552 return NEW_FOREGROUND_TAB
;
553 case blink::WebNavigationPolicyNewWindow
:
555 case blink::WebNavigationPolicyNewPopup
:
558 NOTREACHED() << "Unexpected WebNavigationPolicy";
559 return IGNORE_ACTION
;
563 // Returns true if the device scale is high enough that losing subpixel
564 // antialiasing won't have a noticeable effect on text quality.
565 static bool DeviceScaleEnsuresTextQuality(float device_scale_factor
) {
566 #if defined(OS_ANDROID)
567 // On Android, we never have subpixel antialiasing.
570 return device_scale_factor
> 1.5f
;
575 static bool ShouldUseFixedPositionCompositing(float device_scale_factor
) {
576 // Compositing for fixed-position elements is dependent on
577 // device_scale_factor if no flag is set. http://crbug.com/172738
578 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
580 if (command_line
.HasSwitch(switches::kDisableCompositingForFixedPosition
))
583 if (command_line
.HasSwitch(switches::kEnableCompositingForFixedPosition
))
586 return DeviceScaleEnsuresTextQuality(device_scale_factor
);
589 static bool ShouldUseAcceleratedCompositingForOverflowScroll(
590 float device_scale_factor
) {
591 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
593 if (command_line
.HasSwitch(switches::kDisableAcceleratedOverflowScroll
))
596 if (command_line
.HasSwitch(switches::kEnableAcceleratedOverflowScroll
))
599 return DeviceScaleEnsuresTextQuality(device_scale_factor
);
602 static bool ShouldUseAcceleratedCompositingForScrollableFrames(
603 float device_scale_factor
) {
604 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
606 if (command_line
.HasSwitch(switches::kDisableAcceleratedScrollableFrames
))
609 if (command_line
.HasSwitch(switches::kEnableAcceleratedScrollableFrames
))
612 if (!cc::switches::IsLCDTextEnabled())
615 return DeviceScaleEnsuresTextQuality(device_scale_factor
);
618 static bool ShouldUseCompositedScrollingForFrames(
619 float device_scale_factor
) {
620 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
622 if (command_line
.HasSwitch(switches::kDisableCompositedScrollingForFrames
))
625 if (command_line
.HasSwitch(switches::kEnableCompositedScrollingForFrames
))
628 if (!cc::switches::IsLCDTextEnabled())
631 return DeviceScaleEnsuresTextQuality(device_scale_factor
);
634 static bool ShouldUseUniversalAcceleratedCompositingForOverflowScroll() {
635 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
637 if (command_line
.HasSwitch(
638 switches::kDisableUniversalAcceleratedOverflowScroll
))
641 if (command_line
.HasSwitch(
642 switches::kEnableUniversalAcceleratedOverflowScroll
))
648 static bool ShouldUseTransitionCompositing(float device_scale_factor
) {
649 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
651 if (command_line
.HasSwitch(switches::kDisableCompositingForTransition
))
654 if (command_line
.HasSwitch(switches::kEnableCompositingForTransition
))
657 // TODO(ajuma): Re-enable this by default for high-DPI once the problem
658 // of excessive layer promotion caused by overlap has been addressed.
659 // http://crbug.com/178119.
663 static bool ShouldUseAcceleratedFixedRootBackground(float device_scale_factor
) {
664 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
666 if (command_line
.HasSwitch(switches::kDisableAcceleratedFixedRootBackground
))
669 if (command_line
.HasSwitch(switches::kEnableAcceleratedFixedRootBackground
))
672 return DeviceScaleEnsuresTextQuality(device_scale_factor
);
675 static FaviconURL::IconType
ToFaviconType(blink::WebIconURL::Type type
) {
677 case blink::WebIconURL::TypeFavicon
:
678 return FaviconURL::FAVICON
;
679 case blink::WebIconURL::TypeTouch
:
680 return FaviconURL::TOUCH_ICON
;
681 case blink::WebIconURL::TypeTouchPrecomposed
:
682 return FaviconURL::TOUCH_PRECOMPOSED_ICON
;
683 case blink::WebIconURL::TypeInvalid
:
684 return FaviconURL::INVALID_ICON
;
686 return FaviconURL::INVALID_ICON
;
689 ///////////////////////////////////////////////////////////////////////////////
691 struct RenderViewImpl::PendingFileChooser
{
692 PendingFileChooser(const FileChooserParams
& p
, WebFileChooserCompletion
* c
)
696 FileChooserParams params
;
697 WebFileChooserCompletion
* completion
; // MAY BE NULL to skip callback.
702 class WebWidgetLockTarget
: public MouseLockDispatcher::LockTarget
{
704 explicit WebWidgetLockTarget(blink::WebWidget
* webwidget
)
705 : webwidget_(webwidget
) {}
707 virtual void OnLockMouseACK(bool succeeded
) OVERRIDE
{
709 webwidget_
->didAcquirePointerLock();
711 webwidget_
->didNotAcquirePointerLock();
714 virtual void OnMouseLockLost() OVERRIDE
{
715 webwidget_
->didLosePointerLock();
718 virtual bool HandleMouseLockedInputEvent(
719 const blink::WebMouseEvent
&event
) OVERRIDE
{
720 // The WebWidget handles mouse lock in WebKit's handleInputEvent().
725 blink::WebWidget
* webwidget_
;
728 int64
ExtractPostId(const WebHistoryItem
& item
) {
732 if (item
.httpBody().isNull())
735 return item
.httpBody().identifier();
738 bool TouchEnabled() {
739 // Based on the definition of chrome::kEnableTouchIcon.
740 #if defined(OS_ANDROID)
747 WebDragData
DropDataToWebDragData(const DropData
& drop_data
) {
748 std::vector
<WebDragData::Item
> item_list
;
750 // These fields are currently unused when dragging into WebKit.
751 DCHECK(drop_data
.download_metadata
.empty());
752 DCHECK(drop_data
.file_contents
.empty());
753 DCHECK(drop_data
.file_description_filename
.empty());
755 if (!drop_data
.text
.is_null()) {
756 WebDragData::Item item
;
757 item
.storageType
= WebDragData::Item::StorageTypeString
;
758 item
.stringType
= WebString::fromUTF8(ui::Clipboard::kMimeTypeText
);
759 item
.stringData
= drop_data
.text
.string();
760 item_list
.push_back(item
);
763 // TODO(dcheng): Do we need to distinguish between null and empty URLs? Is it
764 // meaningful to write an empty URL to the clipboard?
765 if (!drop_data
.url
.is_empty()) {
766 WebDragData::Item item
;
767 item
.storageType
= WebDragData::Item::StorageTypeString
;
768 item
.stringType
= WebString::fromUTF8(ui::Clipboard::kMimeTypeURIList
);
769 item
.stringData
= WebString::fromUTF8(drop_data
.url
.spec());
770 item
.title
= drop_data
.url_title
;
771 item_list
.push_back(item
);
774 if (!drop_data
.html
.is_null()) {
775 WebDragData::Item item
;
776 item
.storageType
= WebDragData::Item::StorageTypeString
;
777 item
.stringType
= WebString::fromUTF8(ui::Clipboard::kMimeTypeHTML
);
778 item
.stringData
= drop_data
.html
.string();
779 item
.baseURL
= drop_data
.html_base_url
;
780 item_list
.push_back(item
);
783 for (std::vector
<DropData::FileInfo
>::const_iterator it
=
784 drop_data
.filenames
.begin();
785 it
!= drop_data
.filenames
.end();
787 WebDragData::Item item
;
788 item
.storageType
= WebDragData::Item::StorageTypeFilename
;
789 item
.filenameData
= it
->path
;
790 item
.displayNameData
= it
->display_name
;
791 item_list
.push_back(item
);
794 for (std::map
<base::string16
, base::string16
>::const_iterator it
=
795 drop_data
.custom_data
.begin();
796 it
!= drop_data
.custom_data
.end();
798 WebDragData::Item item
;
799 item
.storageType
= WebDragData::Item::StorageTypeString
;
800 item
.stringType
= it
->first
;
801 item
.stringData
= it
->second
;
802 item_list
.push_back(item
);
807 result
.setItems(item_list
);
808 result
.setFilesystemId(drop_data
.filesystem_id
);
814 RenderViewImpl::RenderViewImpl(RenderViewImplParams
* params
)
815 : RenderWidget(blink::WebPopupTypeNone
,
819 webkit_preferences_(params
->webkit_prefs
),
820 send_content_state_immediately_(false),
821 enabled_bindings_(0),
822 send_preferred_size_changes_(false),
824 navigation_gesture_(NavigationGestureUnknown
),
825 opened_by_user_gesture_(true),
826 opener_suppressed_(false),
827 suppress_dialogs_until_swap_out_(false),
829 last_page_id_sent_to_browser_(-1),
830 next_page_id_(params
->next_page_id
),
831 history_list_offset_(-1),
832 history_list_length_(0),
833 target_url_status_(TARGET_NONE
),
834 selection_text_offset_(0),
835 selection_range_(gfx::Range::InvalidRange()),
836 #if defined(OS_ANDROID)
837 top_controls_constraints_(cc::BOTH
),
839 cached_is_main_frame_pinned_to_left_(false),
840 cached_is_main_frame_pinned_to_right_(false),
841 cached_has_main_frame_horizontal_scrollbar_(false),
842 cached_has_main_frame_vertical_scrollbar_(false),
843 notification_provider_(NULL
),
844 geolocation_dispatcher_(NULL
),
845 input_tag_speech_dispatcher_(NULL
),
846 speech_recognition_dispatcher_(NULL
),
847 media_stream_dispatcher_(NULL
),
848 browser_plugin_manager_(NULL
),
849 media_stream_client_(NULL
),
850 web_user_media_client_(NULL
),
851 midi_dispatcher_(NULL
),
852 devtools_agent_(NULL
),
853 accessibility_mode_(AccessibilityModeOff
),
854 renderer_accessibility_(NULL
),
855 mouse_lock_dispatcher_(NULL
),
856 #if defined(OS_ANDROID)
857 body_background_color_(SK_ColorWHITE
),
858 expected_content_intent_id_(0),
859 media_player_manager_(NULL
),
862 focused_plugin_id_(-1),
864 #if defined(ENABLE_PLUGINS)
865 focused_pepper_plugin_(NULL
),
866 pepper_last_mouse_event_target_(NULL
),
868 enumeration_completion_id_(0),
869 load_progress_tracker_(new LoadProgressTracker(this)),
870 session_storage_namespace_id_(params
->session_storage_namespace_id
),
871 handling_select_range_(false),
872 next_snapshot_id_(0),
873 allow_partial_swap_(params
->allow_partial_swap
),
874 context_menu_source_type_(ui::MENU_SOURCE_MOUSE
) {
877 void RenderViewImpl::Initialize(RenderViewImplParams
* params
) {
878 routing_id_
= params
->routing_id
;
879 surface_id_
= params
->surface_id
;
880 if (params
->opener_id
!= MSG_ROUTING_NONE
&& params
->is_renderer_created
)
881 opener_id_
= params
->opener_id
;
883 // Ensure we start with a valid next_page_id_ from the browser.
884 DCHECK_GE(next_page_id_
, 0);
886 #if defined(ENABLE_NOTIFICATIONS)
887 notification_provider_
= new NotificationProvider(this);
889 notification_provider_
= NULL
;
892 webwidget_
= WebView::create(this);
893 webwidget_mouse_lock_target_
.reset(new WebWidgetLockTarget(webwidget_
));
895 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
897 if (command_line
.HasSwitch(switches::kStatsCollectionController
))
898 stats_collection_observer_
.reset(new StatsCollectionObserver(this));
900 #if defined(OS_ANDROID)
901 content::DeviceTelephonyInfo device_info
;
903 const std::string region_code
=
904 command_line
.HasSwitch(switches::kNetworkCountryIso
)
905 ? command_line
.GetSwitchValueASCII(switches::kNetworkCountryIso
)
906 : device_info
.GetNetworkCountryIso();
907 content_detectors_
.push_back(linked_ptr
<ContentDetector
>(
908 new AddressDetector()));
909 content_detectors_
.push_back(linked_ptr
<ContentDetector
>(
910 new PhoneNumberDetector(region_code
)));
911 content_detectors_
.push_back(linked_ptr
<ContentDetector
>(
912 new EmailDetector()));
915 RenderThread::Get()->AddRoute(routing_id_
, this);
916 // Take a reference on behalf of the RenderThread. This will be balanced
917 // when we receive ViewMsg_ClosePage.
919 if (RenderThreadImpl::current()) {
920 RenderThreadImpl::current()->WidgetCreated();
922 RenderThreadImpl::current()->WidgetHidden();
925 // If this is a popup, we must wait for the CreatingNew_ACK message before
926 // completing initialization. Otherwise, we can finish it now.
927 if (opener_id_
== MSG_ROUTING_NONE
) {
932 g_view_map
.Get().insert(std::make_pair(webview(), this));
933 g_routing_id_view_map
.Get().insert(std::make_pair(routing_id_
, this));
934 webview()->setDeviceScaleFactor(device_scale_factor_
);
935 webview()->settings()->setAcceleratedCompositingForFixedPositionEnabled(
936 ShouldUseFixedPositionCompositing(device_scale_factor_
));
937 webview()->settings()->setAcceleratedCompositingForOverflowScrollEnabled(
938 ShouldUseAcceleratedCompositingForOverflowScroll(device_scale_factor_
));
939 webview()->settings()->setCompositorDrivenAcceleratedScrollingEnabled(
940 ShouldUseUniversalAcceleratedCompositingForOverflowScroll());
941 webview()->settings()->setAcceleratedCompositingForTransitionEnabled(
942 ShouldUseTransitionCompositing(device_scale_factor_
));
943 webview()->settings()->setAcceleratedCompositingForFixedRootBackgroundEnabled(
944 ShouldUseAcceleratedFixedRootBackground(device_scale_factor_
));
945 webview()->settings()->setAcceleratedCompositingForScrollableFramesEnabled(
946 ShouldUseAcceleratedCompositingForScrollableFrames(device_scale_factor_
));
947 webview()->settings()->setCompositedScrollingForFramesEnabled(
948 ShouldUseCompositedScrollingForFrames(device_scale_factor_
));
950 ApplyWebPreferences(webkit_preferences_
, webview());
952 main_render_frame_
.reset(
953 RenderFrameImpl::Create(this, params
->main_frame_routing_id
));
954 // The main frame WebFrame object is closed by
955 // RenderFrameImpl::frameDetached().
956 webview()->setMainFrame(WebFrame::create(main_render_frame_
.get()));
957 main_render_frame_
->MainWebFrameCreated(webview()->mainFrame());
958 main_render_frame_
->SetWebFrame(webview()->mainFrame());
960 if (switches::IsTouchDragDropEnabled())
961 webview()->settings()->setTouchDragDropEnabled(true);
963 if (switches::IsTouchEditingEnabled())
964 webview()->settings()->setTouchEditingEnabled(true);
966 if (!params
->frame_name
.empty())
967 webview()->mainFrame()->setName(params
->frame_name
);
969 OnSetRendererPrefs(params
->renderer_prefs
);
971 #if defined(ENABLE_WEBRTC)
972 if (!media_stream_dispatcher_
)
973 media_stream_dispatcher_
= new MediaStreamDispatcher(this);
976 new MHTMLGenerator(this);
977 #if defined(OS_MACOSX)
978 new TextInputClientObserver(this);
979 #endif // defined(OS_MACOSX)
981 #if defined(OS_ANDROID)
982 media_player_manager_
= new RendererMediaPlayerManager(this);
983 new JavaBridgeDispatcher(this);
986 // The next group of objects all implement RenderViewObserver, so are deleted
987 // along with the RenderView automatically.
988 devtools_agent_
= new DevToolsAgent(this);
989 if (RenderWidgetCompositor
* rwc
= compositor()) {
990 webview()->devToolsAgent()->setLayerTreeId(rwc
->GetLayerTreeId());
992 mouse_lock_dispatcher_
= new RenderViewMouseLockDispatcher(this);
993 new ImageLoadingHelper(this);
995 // Create renderer_accessibility_ if needed.
996 OnSetAccessibilityMode(params
->accessibility_mode
);
998 new IdleUserDetector(this);
1000 if (command_line
.HasSwitch(switches::kDomAutomationController
))
1001 enabled_bindings_
|= BINDINGS_POLICY_DOM_AUTOMATION
;
1002 if (command_line
.HasSwitch(switches::kStatsCollectionController
))
1003 enabled_bindings_
|= BINDINGS_POLICY_STATS_COLLECTION
;
1005 ProcessViewLayoutFlags(command_line
);
1007 GetContentClient()->renderer()->RenderViewCreated(this);
1009 // If we have an opener_id but we weren't created by a renderer, then
1010 // it's the browser asking us to set our opener to another RenderView.
1011 if (params
->opener_id
!= MSG_ROUTING_NONE
&& !params
->is_renderer_created
) {
1012 RenderViewImpl
* opener_view
= FromRoutingID(params
->opener_id
);
1014 webview()->mainFrame()->setOpener(opener_view
->webview()->mainFrame());
1017 // If we are initially swapped out, navigate to kSwappedOutURL.
1018 // This ensures we are in a unique origin that others cannot script.
1019 if (is_swapped_out_
)
1020 NavigateToSwappedOutURL(webview()->mainFrame());
1023 RenderViewImpl::~RenderViewImpl() {
1024 history_page_ids_
.clear();
1026 base::debug::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_
);
1028 // If file chooser is still waiting for answer, dispatch empty answer.
1029 while (!file_chooser_completions_
.empty()) {
1030 if (file_chooser_completions_
.front()->completion
) {
1031 file_chooser_completions_
.front()->completion
->didChooseFile(
1032 WebVector
<WebString
>());
1034 file_chooser_completions_
.pop_front();
1037 #if defined(OS_ANDROID)
1038 // The date/time picker client is both a scoped_ptr member of this class and
1039 // a RenderViewObserver. Reset it to prevent double deletion.
1040 date_time_picker_client_
.reset();
1044 // Make sure we are no longer referenced by the ViewMap or RoutingIDViewMap.
1045 ViewMap
* views
= g_view_map
.Pointer();
1046 for (ViewMap::iterator it
= views
->begin(); it
!= views
->end(); ++it
)
1047 DCHECK_NE(this, it
->second
) << "Failed to call Close?";
1048 RoutingIDViewMap
* routing_id_views
= g_routing_id_view_map
.Pointer();
1049 for (RoutingIDViewMap::iterator it
= routing_id_views
->begin();
1050 it
!= routing_id_views
->end(); ++it
)
1051 DCHECK_NE(this, it
->second
) << "Failed to call Close?";
1054 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, RenderViewGone());
1055 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, OnDestruct());
1059 RenderViewImpl
* RenderViewImpl::FromWebView(WebView
* webview
) {
1060 ViewMap
* views
= g_view_map
.Pointer();
1061 ViewMap::iterator it
= views
->find(webview
);
1062 return it
== views
->end() ? NULL
: it
->second
;
1066 RenderView
* RenderView::FromWebView(blink::WebView
* webview
) {
1067 return RenderViewImpl::FromWebView(webview
);
1071 RenderViewImpl
* RenderViewImpl::FromRoutingID(int32 routing_id
) {
1072 RoutingIDViewMap
* views
= g_routing_id_view_map
.Pointer();
1073 RoutingIDViewMap::iterator it
= views
->find(routing_id
);
1074 return it
== views
->end() ? NULL
: it
->second
;
1078 RenderView
* RenderView::FromRoutingID(int routing_id
) {
1079 return RenderViewImpl::FromRoutingID(routing_id
);
1083 void RenderView::ForEach(RenderViewVisitor
* visitor
) {
1084 ViewMap
* views
= g_view_map
.Pointer();
1085 for (ViewMap::iterator it
= views
->begin(); it
!= views
->end(); ++it
) {
1086 if (!visitor
->Visit(it
->second
))
1092 RenderViewImpl
* RenderViewImpl::Create(
1094 const RendererPreferences
& renderer_prefs
,
1095 const WebPreferences
& webkit_prefs
,
1097 int32 main_frame_routing_id
,
1099 int64 session_storage_namespace_id
,
1100 const base::string16
& frame_name
,
1101 bool is_renderer_created
,
1105 const blink::WebScreenInfo
& screen_info
,
1106 AccessibilityMode accessibility_mode
,
1107 bool allow_partial_swap
) {
1108 DCHECK(routing_id
!= MSG_ROUTING_NONE
);
1109 RenderViewImplParams
params(
1114 main_frame_routing_id
,
1116 session_storage_namespace_id
,
1118 is_renderer_created
,
1124 allow_partial_swap
);
1125 RenderViewImpl
* render_view
= NULL
;
1126 if (g_create_render_view_impl
)
1127 render_view
= g_create_render_view_impl(¶ms
);
1129 render_view
= new RenderViewImpl(¶ms
);
1130 render_view
->Initialize(¶ms
);
1135 void RenderViewImpl::InstallCreateHook(
1136 RenderViewImpl
* (*create_render_view_impl
)(RenderViewImplParams
*)) {
1137 CHECK(!g_create_render_view_impl
);
1138 g_create_render_view_impl
= create_render_view_impl
;
1141 void RenderViewImpl::AddObserver(RenderViewObserver
* observer
) {
1142 observers_
.AddObserver(observer
);
1145 void RenderViewImpl::RemoveObserver(RenderViewObserver
* observer
) {
1146 observer
->RenderViewGone();
1147 observers_
.RemoveObserver(observer
);
1150 blink::WebView
* RenderViewImpl::webview() const {
1151 return static_cast<blink::WebView
*>(webwidget());
1154 #if defined(ENABLE_PLUGINS)
1155 void RenderViewImpl::RegisterPluginDelegate(WebPluginDelegateProxy
* delegate
) {
1156 plugin_delegates_
.insert(delegate
);
1157 // If the renderer is visible, set initial visibility and focus state.
1159 #if defined(OS_MACOSX)
1160 delegate
->SetContainerVisibility(true);
1161 if (webview() && webview()->isActive())
1162 delegate
->SetWindowFocus(true);
1165 // Plugins start assuming the content has focus (so that they work in
1166 // environments where RenderView isn't hosting them), so we always have to
1167 // set the initial state. See webplugin_delegate_impl.h for details.
1168 delegate
->SetContentAreaFocus(has_focus());
1171 void RenderViewImpl::UnregisterPluginDelegate(
1172 WebPluginDelegateProxy
* delegate
) {
1173 plugin_delegates_
.erase(delegate
);
1177 void RenderViewImpl::PluginFocusChanged(bool focused
, int plugin_id
) {
1179 focused_plugin_id_
= plugin_id
;
1181 focused_plugin_id_
= -1;
1185 #if defined(OS_MACOSX)
1186 void RenderViewImpl::PluginFocusChanged(bool focused
, int plugin_id
) {
1187 Send(new ViewHostMsg_PluginFocusChanged(routing_id(), focused
, plugin_id
));
1190 void RenderViewImpl::StartPluginIme() {
1191 IPC::Message
* msg
= new ViewHostMsg_StartPluginIme(routing_id());
1192 // This message can be sent during event-handling, and needs to be delivered
1193 // within that context.
1194 msg
->set_unblock(true);
1197 #endif // defined(OS_MACOSX)
1199 #endif // ENABLE_PLUGINS
1201 void RenderViewImpl::TransferActiveWheelFlingAnimation(
1202 const blink::WebActiveWheelFlingParameters
& params
) {
1204 webview()->transferActiveWheelFlingAnimation(params
);
1207 bool RenderViewImpl::HasIMETextFocus() {
1208 return GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE
;
1211 bool RenderViewImpl::OnMessageReceived(const IPC::Message
& message
) {
1212 WebFrame
* main_frame
= webview() ? webview()->mainFrame() : NULL
;
1214 GetContentClient()->SetActiveURL(main_frame
->document().url());
1216 ObserverListBase
<RenderViewObserver
>::Iterator
it(observers_
);
1217 RenderViewObserver
* observer
;
1218 while ((observer
= it
.GetNext()) != NULL
)
1219 if (observer
->OnMessageReceived(message
))
1222 bool handled
= true;
1223 bool msg_is_ok
= true;
1224 IPC_BEGIN_MESSAGE_MAP_EX(RenderViewImpl
, message
, msg_is_ok
)
1225 IPC_MESSAGE_HANDLER(InputMsg_Copy
, OnCopy
)
1226 IPC_MESSAGE_HANDLER(InputMsg_Cut
, OnCut
)
1227 IPC_MESSAGE_HANDLER(InputMsg_Delete
, OnDelete
)
1228 IPC_MESSAGE_HANDLER(InputMsg_ExecuteEditCommand
, OnExecuteEditCommand
)
1229 IPC_MESSAGE_HANDLER(InputMsg_MoveCaret
, OnMoveCaret
)
1230 IPC_MESSAGE_HANDLER(InputMsg_Paste
, OnPaste
)
1231 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle
, OnPasteAndMatchStyle
)
1232 IPC_MESSAGE_HANDLER(InputMsg_Redo
, OnRedo
)
1233 IPC_MESSAGE_HANDLER(InputMsg_Replace
, OnReplace
)
1234 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling
, OnReplaceMisspelling
)
1235 IPC_MESSAGE_HANDLER(InputMsg_ScrollFocusedEditableNodeIntoRect
,
1236 OnScrollFocusedEditableNodeIntoRect
)
1237 IPC_MESSAGE_HANDLER(InputMsg_SelectAll
, OnSelectAll
)
1238 IPC_MESSAGE_HANDLER(InputMsg_SelectRange
, OnSelectRange
)
1239 IPC_MESSAGE_HANDLER(InputMsg_SetEditCommandsForNextKeyEvent
,
1240 OnSetEditCommandsForNextKeyEvent
)
1241 IPC_MESSAGE_HANDLER(InputMsg_Undo
, OnUndo
)
1242 IPC_MESSAGE_HANDLER(InputMsg_Unselect
, OnUnselect
)
1243 IPC_MESSAGE_HANDLER(ViewMsg_Navigate
, OnNavigate
)
1244 IPC_MESSAGE_HANDLER(ViewMsg_Stop
, OnStop
)
1245 IPC_MESSAGE_HANDLER(ViewMsg_ReloadFrame
, OnReloadFrame
)
1246 IPC_MESSAGE_HANDLER(ViewMsg_SetName
, OnSetName
)
1247 IPC_MESSAGE_HANDLER(ViewMsg_SetEditableSelectionOffsets
,
1248 OnSetEditableSelectionOffsets
)
1249 IPC_MESSAGE_HANDLER(ViewMsg_SetCompositionFromExistingText
,
1250 OnSetCompositionFromExistingText
)
1251 IPC_MESSAGE_HANDLER(ViewMsg_ExtendSelectionAndDelete
,
1252 OnExtendSelectionAndDelete
)
1253 IPC_MESSAGE_HANDLER(ViewMsg_CopyImageAt
, OnCopyImageAt
)
1254 IPC_MESSAGE_HANDLER(ViewMsg_Find
, OnFind
)
1255 IPC_MESSAGE_HANDLER(ViewMsg_StopFinding
, OnStopFinding
)
1256 IPC_MESSAGE_HANDLER(ViewMsg_Zoom
, OnZoom
)
1257 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevel
, OnSetZoomLevel
)
1258 IPC_MESSAGE_HANDLER(ViewMsg_ZoomFactor
, OnZoomFactor
)
1259 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForLoadingURL
,
1260 OnSetZoomLevelForLoadingURL
)
1261 IPC_MESSAGE_HANDLER(ViewMsg_SetPageEncoding
, OnSetPageEncoding
)
1262 IPC_MESSAGE_HANDLER(ViewMsg_ResetPageEncodingToDefault
,
1263 OnResetPageEncodingToDefault
)
1264 IPC_MESSAGE_HANDLER(ViewMsg_ScriptEvalRequest
, OnScriptEvalRequest
)
1265 IPC_MESSAGE_HANDLER(ViewMsg_PostMessageEvent
, OnPostMessageEvent
)
1266 IPC_MESSAGE_HANDLER(ViewMsg_CSSInsertRequest
, OnCSSInsertRequest
)
1267 IPC_MESSAGE_HANDLER(DragMsg_TargetDragEnter
, OnDragTargetDragEnter
)
1268 IPC_MESSAGE_HANDLER(DragMsg_TargetDragOver
, OnDragTargetDragOver
)
1269 IPC_MESSAGE_HANDLER(DragMsg_TargetDragLeave
, OnDragTargetDragLeave
)
1270 IPC_MESSAGE_HANDLER(DragMsg_TargetDrop
, OnDragTargetDrop
)
1271 IPC_MESSAGE_HANDLER(DragMsg_SourceEndedOrMoved
, OnDragSourceEndedOrMoved
)
1272 IPC_MESSAGE_HANDLER(DragMsg_SourceSystemDragEnded
,
1273 OnDragSourceSystemDragEnded
)
1274 IPC_MESSAGE_HANDLER(ViewMsg_AllowBindings
, OnAllowBindings
)
1275 IPC_MESSAGE_HANDLER(ViewMsg_SetInitialFocus
, OnSetInitialFocus
)
1276 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTargetURL_ACK
, OnUpdateTargetURLAck
)
1277 IPC_MESSAGE_HANDLER(ViewMsg_UpdateWebPreferences
, OnUpdateWebPreferences
)
1278 IPC_MESSAGE_HANDLER(ViewMsg_TimezoneChange
, OnUpdateTimezone
)
1279 IPC_MESSAGE_HANDLER(ViewMsg_SetAltErrorPageURL
, OnSetAltErrorPageURL
)
1280 IPC_MESSAGE_HANDLER(ViewMsg_EnumerateDirectoryResponse
,
1281 OnEnumerateDirectoryResponse
)
1282 IPC_MESSAGE_HANDLER(ViewMsg_RunFileChooserResponse
, OnFileChooserResponse
)
1283 IPC_MESSAGE_HANDLER(ViewMsg_ShouldClose
, OnShouldClose
)
1284 IPC_MESSAGE_HANDLER(ViewMsg_SuppressDialogsUntilSwapOut
,
1285 OnSuppressDialogsUntilSwapOut
)
1286 IPC_MESSAGE_HANDLER(ViewMsg_SwapOut
, OnSwapOut
)
1287 IPC_MESSAGE_HANDLER(ViewMsg_ClosePage
, OnClosePage
)
1288 IPC_MESSAGE_HANDLER(ViewMsg_ThemeChanged
, OnThemeChanged
)
1289 IPC_MESSAGE_HANDLER(ViewMsg_MoveOrResizeStarted
, OnMoveOrResizeStarted
)
1290 IPC_MESSAGE_HANDLER(ViewMsg_ClearFocusedNode
, OnClearFocusedNode
)
1291 IPC_MESSAGE_HANDLER(ViewMsg_SetBackground
, OnSetBackground
)
1292 IPC_MESSAGE_HANDLER(ViewMsg_EnablePreferredSizeChangedMode
,
1293 OnEnablePreferredSizeChangedMode
)
1294 IPC_MESSAGE_HANDLER(ViewMsg_EnableAutoResize
, OnEnableAutoResize
)
1295 IPC_MESSAGE_HANDLER(ViewMsg_DisableAutoResize
, OnDisableAutoResize
)
1296 IPC_MESSAGE_HANDLER(ViewMsg_DisableScrollbarsForSmallWindows
,
1297 OnDisableScrollbarsForSmallWindows
)
1298 IPC_MESSAGE_HANDLER(ViewMsg_SetRendererPrefs
, OnSetRendererPrefs
)
1299 IPC_MESSAGE_HANDLER(ViewMsg_MediaPlayerActionAt
, OnMediaPlayerActionAt
)
1300 IPC_MESSAGE_HANDLER(ViewMsg_OrientationChangeEvent
,
1301 OnOrientationChangeEvent
)
1302 IPC_MESSAGE_HANDLER(ViewMsg_PluginActionAt
, OnPluginActionAt
)
1303 IPC_MESSAGE_HANDLER(ViewMsg_SetActive
, OnSetActive
)
1304 IPC_MESSAGE_HANDLER(ViewMsg_CustomContextMenuAction
,
1305 OnCustomContextMenuAction
)
1306 IPC_MESSAGE_HANDLER(ViewMsg_GetAllSavableResourceLinksForCurrentPage
,
1307 OnGetAllSavableResourceLinksForCurrentPage
)
1308 IPC_MESSAGE_HANDLER(
1309 ViewMsg_GetSerializedHtmlDataForCurrentPageWithLocalLinks
,
1310 OnGetSerializedHtmlDataForCurrentPageWithLocalLinks
)
1311 IPC_MESSAGE_HANDLER(ViewMsg_ContextMenuClosed
, OnContextMenuClosed
)
1312 IPC_MESSAGE_HANDLER(ViewMsg_ShowContextMenu
, OnShowContextMenu
)
1313 // TODO(viettrungluu): Move to a separate message filter.
1314 IPC_MESSAGE_HANDLER(ViewMsg_SetHistoryLengthAndPrune
,
1315 OnSetHistoryLengthAndPrune
)
1316 IPC_MESSAGE_HANDLER(ViewMsg_EnableViewSourceMode
, OnEnableViewSourceMode
)
1317 IPC_MESSAGE_HANDLER(ViewMsg_SetAccessibilityMode
, OnSetAccessibilityMode
)
1318 IPC_MESSAGE_HANDLER(ViewMsg_DisownOpener
, OnDisownOpener
)
1319 IPC_MESSAGE_HANDLER(ViewMsg_ReleaseDisambiguationPopupDIB
,
1320 OnReleaseDisambiguationPopupDIB
)
1321 IPC_MESSAGE_HANDLER(ViewMsg_WindowSnapshotCompleted
,
1322 OnWindowSnapshotCompleted
)
1323 #if defined(OS_ANDROID)
1324 IPC_MESSAGE_HANDLER(InputMsg_ActivateNearestFindResult
,
1325 OnActivateNearestFindResult
)
1326 IPC_MESSAGE_HANDLER(ViewMsg_FindMatchRects
, OnFindMatchRects
)
1327 IPC_MESSAGE_HANDLER(ViewMsg_SelectPopupMenuItems
, OnSelectPopupMenuItems
)
1328 IPC_MESSAGE_HANDLER(ViewMsg_UndoScrollFocusedEditableNodeIntoView
,
1329 OnUndoScrollFocusedEditableNodeIntoRect
)
1330 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTopControlsState
,
1331 OnUpdateTopControlsState
)
1332 IPC_MESSAGE_HANDLER(ViewMsg_PauseVideo
, OnPauseVideo
)
1333 IPC_MESSAGE_HANDLER(ViewMsg_ExtractSmartClipData
, OnExtractSmartClipData
)
1334 #elif defined(OS_MACOSX)
1335 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard
, OnCopyToFindPboard
)
1336 IPC_MESSAGE_HANDLER(ViewMsg_PluginImeCompositionCompleted
,
1337 OnPluginImeCompositionCompleted
)
1338 IPC_MESSAGE_HANDLER(ViewMsg_SelectPopupMenuItem
, OnSelectPopupMenuItem
)
1339 IPC_MESSAGE_HANDLER(ViewMsg_SetInLiveResize
, OnSetInLiveResize
)
1340 IPC_MESSAGE_HANDLER(ViewMsg_SetWindowVisibility
, OnSetWindowVisibility
)
1341 IPC_MESSAGE_HANDLER(ViewMsg_WindowFrameChanged
, OnWindowFrameChanged
)
1343 // Adding a new message? Add platform independent ones first, then put the
1344 // platform specific ones at the end.
1346 // Have the super handle all other messages.
1347 IPC_MESSAGE_UNHANDLED(handled
= RenderWidget::OnMessageReceived(message
))
1348 IPC_END_MESSAGE_MAP()
1351 // The message had a handler, but its deserialization failed.
1352 // Kill the renderer to avoid potential spoofing attacks.
1353 CHECK(false) << "Unable to deserialize message in RenderViewImpl.";
1359 void RenderViewImpl::OnNavigate(const ViewMsg_Navigate_Params
& params
) {
1360 MaybeHandleDebugURL(params
.url
);
1364 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, Navigate(params
.url
));
1366 bool is_reload
= IsReload(params
);
1367 WebURLRequest::CachePolicy cache_policy
=
1368 WebURLRequest::UseProtocolCachePolicy
;
1370 // If this is a stale back/forward (due to a recent navigation the browser
1371 // didn't know about), ignore it.
1372 if (IsBackForwardToStaleEntry(params
, is_reload
))
1375 // Swap this renderer back in if necessary.
1376 if (is_swapped_out_
) {
1377 // We marked the view as hidden when swapping the view out, so be sure to
1378 // reset the visibility state before navigating to the new URL.
1379 webview()->setVisibilityState(visibilityState(), false);
1381 // If this is an attempt to reload while we are swapped out, we should not
1382 // reload swappedout://, but the previous page, which is stored in
1383 // params.state. Setting is_reload to false will treat this like a back
1384 // navigation to accomplish that.
1386 cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
1388 // We refresh timezone when a view is swapped in since timezone
1389 // can get out of sync when the system timezone is updated while
1390 // the view is swapped out.
1391 NotifyTimezoneChange(webview()->mainFrame());
1393 SetSwappedOut(false);
1396 if (params
.should_clear_history_list
) {
1397 CHECK_EQ(params
.pending_history_list_offset
, -1);
1398 CHECK_EQ(params
.current_history_list_offset
, -1);
1399 CHECK_EQ(params
.current_history_list_length
, 0);
1401 history_list_offset_
= params
.current_history_list_offset
;
1402 history_list_length_
= params
.current_history_list_length
;
1403 if (history_list_length_
>= 0)
1404 history_page_ids_
.resize(history_list_length_
, -1);
1405 if (params
.pending_history_list_offset
>= 0 &&
1406 params
.pending_history_list_offset
< history_list_length_
)
1407 history_page_ids_
[params
.pending_history_list_offset
] = params
.page_id
;
1409 GetContentClient()->SetActiveURL(params
.url
);
1411 WebFrame
* frame
= webview()->mainFrame();
1412 if (!params
.frame_to_navigate
.empty()) {
1413 frame
= webview()->findFrameByName(
1414 WebString::fromUTF8(params
.frame_to_navigate
));
1415 CHECK(frame
) << "Invalid frame name passed: " << params
.frame_to_navigate
;
1418 if (is_reload
&& frame
->currentHistoryItem().isNull()) {
1419 // We cannot reload if we do not have any history state. This happens, for
1420 // example, when recovering from a crash.
1422 cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
1425 pending_navigation_params_
.reset(new ViewMsg_Navigate_Params(params
));
1427 // If we are reloading, then WebKit will use the history state of the current
1428 // page, so we should just ignore any given history state. Otherwise, if we
1429 // have history state, then we need to navigate to it, which corresponds to a
1430 // back/forward navigation event.
1432 bool reload_original_url
=
1433 (params
.navigation_type
==
1434 ViewMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
);
1435 bool ignore_cache
= (params
.navigation_type
==
1436 ViewMsg_Navigate_Type::RELOAD_IGNORING_CACHE
);
1438 if (reload_original_url
)
1439 frame
->reloadWithOverrideURL(params
.url
, true);
1441 frame
->reload(ignore_cache
);
1442 } else if (params
.page_state
.IsValid()) {
1443 // We must know the page ID of the page we are navigating back to.
1444 DCHECK_NE(params
.page_id
, -1);
1445 WebHistoryItem item
= PageStateToHistoryItem(params
.page_state
);
1446 if (!item
.isNull()) {
1447 // Ensure we didn't save the swapped out URL in UpdateState, since the
1448 // browser should never be telling us to navigate to swappedout://.
1449 CHECK(item
.urlString() != WebString::fromUTF8(kSwappedOutURL
));
1450 frame
->loadHistoryItem(item
, cache_policy
);
1452 } else if (!params
.base_url_for_data_url
.is_empty()) {
1453 // A loadData request with a specified base URL.
1454 std::string mime_type
, charset
, data
;
1455 if (net::DataURL::Parse(params
.url
, &mime_type
, &charset
, &data
)) {
1457 WebData(data
.c_str(), data
.length()),
1458 WebString::fromUTF8(mime_type
),
1459 WebString::fromUTF8(charset
),
1460 params
.base_url_for_data_url
,
1461 params
.history_url_for_data_url
,
1465 "Invalid URL passed: " << params
.url
.possibly_invalid_spec();
1468 // Navigate to the given URL.
1469 WebURLRequest
request(params
.url
);
1471 // A session history navigation should have been accompanied by state.
1472 CHECK_EQ(params
.page_id
, -1);
1474 if (frame
->isViewSourceModeEnabled())
1475 request
.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad
);
1477 if (params
.referrer
.url
.is_valid()) {
1478 WebString referrer
= WebSecurityPolicy::generateReferrerHeader(
1479 params
.referrer
.policy
,
1481 WebString::fromUTF8(params
.referrer
.url
.spec()));
1482 if (!referrer
.isEmpty())
1483 request
.setHTTPHeaderField(WebString::fromUTF8("Referer"), referrer
);
1486 if (!params
.extra_headers
.empty()) {
1487 for (net::HttpUtil::HeadersIterator
i(params
.extra_headers
.begin(),
1488 params
.extra_headers
.end(), "\n");
1490 request
.addHTTPHeaderField(WebString::fromUTF8(i
.name()),
1491 WebString::fromUTF8(i
.values()));
1495 if (params
.is_post
) {
1496 request
.setHTTPMethod(WebString::fromUTF8("POST"));
1499 WebHTTPBody http_body
;
1500 http_body
.initialize();
1501 const char* data
= NULL
;
1502 if (params
.browser_initiated_post_data
.size()) {
1503 data
= reinterpret_cast<const char*>(
1504 ¶ms
.browser_initiated_post_data
.front());
1506 http_body
.appendData(
1507 WebData(data
, params
.browser_initiated_post_data
.size()));
1508 request
.setHTTPBody(http_body
);
1511 frame
->loadRequest(request
);
1513 // If this is a cross-process navigation, the browser process will send
1514 // along the proper navigation start value.
1515 if (!params
.browser_navigation_start
.is_null() &&
1516 frame
->provisionalDataSource()) {
1517 // browser_navigation_start is likely before this process existed, so we
1518 // can't use InterProcessTimeTicksConverter. Instead, the best we can do
1519 // is just ensure we don't report a bogus value in the future.
1520 base::TimeTicks navigation_start
= std::min(
1521 base::TimeTicks::Now(), params
.browser_navigation_start
);
1522 double navigation_start_seconds
=
1523 (navigation_start
- base::TimeTicks()).InSecondsF();
1524 frame
->provisionalDataSource()->setNavigationStartTime(
1525 navigation_start_seconds
);
1529 // In case LoadRequest failed before DidCreateDataSource was called.
1530 pending_navigation_params_
.reset();
1533 bool RenderViewImpl::IsBackForwardToStaleEntry(
1534 const ViewMsg_Navigate_Params
& params
,
1536 // Make sure this isn't a back/forward to an entry we have already cropped
1537 // or replaced from our history, before the browser knew about it. If so,
1538 // a new navigation has committed in the mean time, and we can ignore this.
1539 bool is_back_forward
= !is_reload
&& params
.page_state
.IsValid();
1541 // Note: if the history_list_length_ is 0 for a back/forward, we must be
1542 // restoring from a previous session. We'll update our state in OnNavigate.
1543 if (!is_back_forward
|| history_list_length_
<= 0)
1546 DCHECK_EQ(static_cast<int>(history_page_ids_
.size()), history_list_length_
);
1548 // Check for whether the forward history has been cropped due to a recent
1549 // navigation the browser didn't know about.
1550 if (params
.pending_history_list_offset
>= history_list_length_
)
1553 // Check for whether this entry has been replaced with a new one.
1554 int expected_page_id
=
1555 history_page_ids_
[params
.pending_history_list_offset
];
1556 if (expected_page_id
> 0 && params
.page_id
!= expected_page_id
) {
1557 if (params
.page_id
< expected_page_id
)
1560 // Otherwise we've removed an earlier entry and should have shifted all
1561 // entries left. For now, it's ok to lazily update the list.
1562 // TODO(creis): Notify all live renderers when we remove entries from
1563 // the front of the list, so that we don't hit this case.
1564 history_page_ids_
[params
.pending_history_list_offset
] = params
.page_id
;
1570 // Stop loading the current page
1571 void RenderViewImpl::OnStop() {
1573 WebFrame
* main_frame
= webview()->mainFrame();
1574 // Stop the alt error page fetcher. If we let it continue it may complete
1575 // and cause RenderFrameHostManager to swap to this RenderView, even though
1576 // it may no longer be active.
1577 StopAltErrorPageFetcher(main_frame
->provisionalDataSource());
1578 StopAltErrorPageFetcher(main_frame
->dataSource());
1579 main_frame
->stopLoading();
1583 // Reload current focused frame.
1584 // E.g. called by right-clicking on the frame and picking "reload this frame".
1585 void RenderViewImpl::OnReloadFrame() {
1586 if (webview() && webview()->focusedFrame()) {
1587 // We always obey the cache (ignore_cache=false) here.
1588 // TODO(evanm): perhaps we could allow shift-clicking the menu item to do
1589 // a cache-ignoring reload of the frame.
1590 webview()->focusedFrame()->reload(false);
1594 void RenderViewImpl::OnCopyImageAt(int x
, int y
) {
1595 webview()->copyImageAt(WebPoint(x
, y
));
1598 void RenderViewImpl::OnUpdateTargetURLAck() {
1599 // Check if there is a targeturl waiting to be sent.
1600 if (target_url_status_
== TARGET_PENDING
) {
1601 Send(new ViewHostMsg_UpdateTargetURL(routing_id_
, page_id_
,
1602 pending_target_url_
));
1605 target_url_status_
= TARGET_NONE
;
1608 void RenderViewImpl::OnCopy() {
1612 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1613 WebNode current_node
= context_menu_node_
.isNull() ?
1614 GetFocusedNode() : context_menu_node_
;
1615 webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Copy"),
1619 void RenderViewImpl::OnCut() {
1623 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1624 webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Cut"),
1628 void RenderViewImpl::OnDelete() {
1632 webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Delete"),
1636 void RenderViewImpl::OnExecuteEditCommand(const std::string
& name
,
1637 const std::string
& value
) {
1638 if (!webview() || !webview()->focusedFrame())
1641 webview()->focusedFrame()->executeCommand(
1642 WebString::fromUTF8(name
), WebString::fromUTF8(value
));
1645 void RenderViewImpl::OnMoveCaret(const gfx::Point
& point
) {
1649 Send(new ViewHostMsg_MoveCaret_ACK(routing_id_
));
1651 webview()->focusedFrame()->moveCaretSelection(point
);
1654 void RenderViewImpl::OnPaste() {
1658 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1659 webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Paste"),
1663 void RenderViewImpl::OnPasteAndMatchStyle() {
1667 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1668 webview()->focusedFrame()->executeCommand(
1669 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedNode());
1672 void RenderViewImpl::OnRedo() {
1676 webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Redo"),
1680 void RenderViewImpl::OnReplace(const base::string16
& text
) {
1684 WebFrame
* frame
= webview()->focusedFrame();
1685 if (!frame
->hasSelection())
1686 frame
->selectWordAroundCaret();
1688 frame
->replaceSelection(text
);
1691 void RenderViewImpl::OnReplaceMisspelling(const base::string16
& text
) {
1695 WebFrame
* frame
= webview()->focusedFrame();
1696 if (!frame
->hasSelection())
1699 frame
->replaceMisspelledRange(text
);
1702 void RenderViewImpl::OnScrollFocusedEditableNodeIntoRect(
1703 const gfx::Rect
& rect
) {
1704 blink::WebNode node
= GetFocusedNode();
1705 if (!node
.isNull()) {
1706 if (IsEditableNode(node
)) {
1707 webview()->saveScrollAndScaleState();
1708 webview()->scrollFocusedNodeIntoRect(rect
);
1713 void RenderViewImpl::OnSelectAll() {
1717 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1718 webview()->focusedFrame()->executeCommand(
1719 WebString::fromUTF8("SelectAll"), GetFocusedNode());
1722 void RenderViewImpl::OnSelectRange(const gfx::Point
& start
,
1723 const gfx::Point
& end
) {
1727 Send(new ViewHostMsg_SelectRange_ACK(routing_id_
));
1729 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1730 webview()->focusedFrame()->selectRange(start
, end
);
1733 void RenderViewImpl::OnSetEditCommandsForNextKeyEvent(
1734 const EditCommands
& edit_commands
) {
1735 edit_commands_
= edit_commands
;
1738 void RenderViewImpl::OnUndo() {
1742 webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Undo"),
1746 void RenderViewImpl::OnUnselect() {
1750 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1751 webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Unselect"),
1755 #if defined(OS_MACOSX)
1756 void RenderViewImpl::OnCopyToFindPboard() {
1760 // Since the find pasteboard supports only plain text, this can be simpler
1761 // than the |OnCopy()| case.
1762 WebFrame
* frame
= webview()->focusedFrame();
1763 if (frame
->hasSelection()) {
1764 base::string16 selection
= frame
->selectionAsText();
1765 RenderThread::Get()->Send(
1766 new ClipboardHostMsg_FindPboardWriteStringAsync(selection
));
1771 void RenderViewImpl::OnSetName(const std::string
& name
) {
1775 webview()->mainFrame()->setName(WebString::fromUTF8(name
));
1778 void RenderViewImpl::OnSetEditableSelectionOffsets(int start
, int end
) {
1779 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1780 if (!ShouldHandleImeEvent())
1782 ImeEventGuard
guard(this);
1783 webview()->setEditableSelectionOffsets(start
, end
);
1786 void RenderViewImpl::OnSetCompositionFromExistingText(
1788 const std::vector
<blink::WebCompositionUnderline
>& underlines
) {
1789 if (!ShouldHandleImeEvent())
1791 ImeEventGuard
guard(this);
1792 webview()->setCompositionFromExistingText(start
, end
, underlines
);
1795 void RenderViewImpl::OnExtendSelectionAndDelete(int before
, int after
) {
1796 if (!ShouldHandleImeEvent())
1798 ImeEventGuard
guard(this);
1799 webview()->extendSelectionAndDelete(before
, after
);
1802 void RenderViewImpl::OnSetHistoryLengthAndPrune(int history_length
,
1803 int32 minimum_page_id
) {
1804 DCHECK_GE(history_length
, 0);
1805 DCHECK(history_list_offset_
== history_list_length_
- 1);
1806 DCHECK_GE(minimum_page_id
, -1);
1808 // Generate the new list.
1809 std::vector
<int32
> new_history_page_ids(history_length
, -1);
1810 for (size_t i
= 0; i
< history_page_ids_
.size(); ++i
) {
1811 if (minimum_page_id
>= 0 && history_page_ids_
[i
] < minimum_page_id
)
1813 new_history_page_ids
.push_back(history_page_ids_
[i
]);
1815 new_history_page_ids
.swap(history_page_ids_
);
1818 history_list_length_
= history_page_ids_
.size();
1819 history_list_offset_
= history_list_length_
- 1;
1823 void RenderViewImpl::OnSetInitialFocus(bool reverse
) {
1826 webview()->setInitialFocus(reverse
);
1829 #if defined(OS_MACOSX)
1830 void RenderViewImpl::OnSetInLiveResize(bool in_live_resize
) {
1834 webview()->willStartLiveResize();
1836 webview()->willEndLiveResize();
1840 #if defined(OS_ANDROID)
1841 void RenderViewImpl::OnUndoScrollFocusedEditableNodeIntoRect() {
1842 const WebNode node
= GetFocusedNode();
1843 if (!node
.isNull() && IsEditableNode(node
))
1844 webview()->restoreScrollAndScaleState();
1847 void RenderViewImpl::OnPauseVideo() {
1848 // Inform RendererMediaPlayerManager to release all video player resources.
1849 // If something is in progress the resource will not be freed, it will
1850 // only be freed once the tab is destroyed or if the user navigates away
1851 // via WebMediaPlayerAndroid::Destroy.
1852 media_player_manager_
->ReleaseVideoResources();
1856 ///////////////////////////////////////////////////////////////////////////////
1858 // Tell the embedding application that the URL of the active page has changed
1859 void RenderViewImpl::UpdateURL(WebFrame
* frame
) {
1860 WebDataSource
* ds
= frame
->dataSource();
1863 const WebURLRequest
& request
= ds
->request();
1864 const WebURLRequest
& original_request
= ds
->originalRequest();
1865 const WebURLResponse
& response
= ds
->response();
1867 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
1868 NavigationState
* navigation_state
= document_state
->navigation_state();
1869 InternalDocumentStateData
* internal_data
=
1870 InternalDocumentStateData::FromDocumentState(document_state
);
1872 ViewHostMsg_FrameNavigate_Params params
;
1873 params
.http_status_code
= response
.httpStatusCode();
1874 params
.is_post
= false;
1875 params
.post_id
= -1;
1876 params
.page_id
= page_id_
;
1877 params
.frame_id
= frame
->identifier();
1878 params
.frame_unique_name
= frame
->uniqueName();
1879 params
.socket_address
.set_host(response
.remoteIPAddress().utf8());
1880 params
.socket_address
.set_port(response
.remotePort());
1881 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
1883 params
.was_fetched_via_proxy
= extra_data
->was_fetched_via_proxy();
1885 params
.was_within_same_page
= navigation_state
->was_within_same_page();
1886 params
.security_info
= response
.securityInfo();
1888 // Set the URL to be displayed in the browser UI to the user.
1889 params
.url
= GetLoadingUrl(frame
);
1890 DCHECK(!is_swapped_out_
|| params
.url
== GURL(kSwappedOutURL
));
1892 if (frame
->document().baseURL() != params
.url
)
1893 params
.base_url
= frame
->document().baseURL();
1895 GetRedirectChain(ds
, ¶ms
.redirects
);
1896 params
.should_update_history
= !ds
->hasUnreachableURL() &&
1897 !response
.isMultipartPayload() && (response
.httpStatusCode() != 404);
1899 params
.searchable_form_url
= internal_data
->searchable_form_url();
1900 params
.searchable_form_encoding
= internal_data
->searchable_form_encoding();
1902 params
.gesture
= navigation_gesture_
;
1903 navigation_gesture_
= NavigationGestureUnknown
;
1905 // Make navigation state a part of the FrameNavigate message so that commited
1906 // entry had it at all times.
1907 WebHistoryItem item
= frame
->currentHistoryItem();
1908 if (item
.isNull()) {
1910 item
.setURLString(request
.url().spec().utf16());
1912 params
.page_state
= HistoryItemToPageState(item
);
1914 if (!frame
->parent()) {
1915 // Top-level navigation.
1917 // Reset the zoom limits in case a plugin had changed them previously. This
1918 // will also call us back which will cause us to send a message to
1919 // update WebContentsImpl.
1920 webview()->zoomLimitsChanged(ZoomFactorToZoomLevel(kMinimumZoomFactor
),
1921 ZoomFactorToZoomLevel(kMaximumZoomFactor
));
1923 // Set zoom level, but don't do it for full-page plugin since they don't use
1924 // the same zoom settings.
1925 HostZoomLevels::iterator host_zoom
=
1926 host_zoom_levels_
.find(GURL(request
.url()));
1927 if (webview()->mainFrame()->document().isPluginDocument()) {
1928 // Reset the zoom levels for plugins.
1929 webview()->setZoomLevel(0);
1931 if (host_zoom
!= host_zoom_levels_
.end())
1932 webview()->setZoomLevel(host_zoom
->second
);
1935 if (host_zoom
!= host_zoom_levels_
.end()) {
1936 // This zoom level was merely recorded transiently for this load. We can
1937 // erase it now. If at some point we reload this page, the browser will
1938 // send us a new, up-to-date zoom level.
1939 host_zoom_levels_
.erase(host_zoom
);
1942 // Update contents MIME type for main frame.
1943 params
.contents_mime_type
= ds
->response().mimeType().utf8();
1945 params
.transition
= navigation_state
->transition_type();
1946 if (!PageTransitionIsMainFrame(params
.transition
)) {
1947 // If the main frame does a load, it should not be reported as a subframe
1948 // navigation. This can occur in the following case:
1949 // 1. You're on a site with frames.
1950 // 2. You do a subframe navigation. This is stored with transition type
1952 // 3. You navigate to some non-frame site, say, google.com.
1953 // 4. You navigate back to the page from step 2. Since it was initially
1954 // MANUAL_SUBFRAME, it will be that same transition type here.
1955 // We don't want that, because any navigation that changes the toplevel
1956 // frame should be tracked as a toplevel navigation (this allows us to
1957 // update the URL bar, etc).
1958 params
.transition
= PAGE_TRANSITION_LINK
;
1961 // If the page contained a client redirect (meta refresh, document.loc...),
1962 // set the referrer and transition appropriately.
1963 if (ds
->isClientRedirect()) {
1964 params
.referrer
= Referrer(params
.redirects
[0],
1965 GetReferrerPolicyFromRequest(frame
, ds
->request()));
1966 params
.transition
= static_cast<PageTransition
>(
1967 params
.transition
| PAGE_TRANSITION_CLIENT_REDIRECT
);
1969 params
.referrer
= GetReferrerFromRequest(frame
, ds
->request());
1972 base::string16 method
= request
.httpMethod();
1973 if (EqualsASCII(method
, "POST")) {
1974 params
.is_post
= true;
1975 params
.post_id
= ExtractPostId(item
);
1978 // Send the user agent override back.
1979 params
.is_overriding_user_agent
= internal_data
->is_overriding_user_agent();
1981 // Track the URL of the original request. We use the first entry of the
1982 // redirect chain if it exists because the chain may have started in another
1984 if (params
.redirects
.size() > 0)
1985 params
.original_request_url
= params
.redirects
.at(0);
1987 params
.original_request_url
= original_request
.url();
1989 params
.history_list_was_cleared
=
1990 navigation_state
->history_list_was_cleared();
1992 // Save some histogram data so we can compute the average memory used per
1993 // page load of the glyphs.
1994 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
1995 blink::WebGlyphCache::pageCount());
1997 // This message needs to be sent before any of allowScripts(),
1998 // allowImages(), allowPlugins() is called for the new page, so that when
1999 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
2000 // after the ViewHostMsg_FrameNavigate message.
2001 Send(new ViewHostMsg_FrameNavigate(routing_id_
, params
));
2003 // Subframe navigation: the type depends on whether this navigation
2004 // generated a new session history entry. When they do generate a session
2005 // history entry, it means the user initiated the navigation and we should
2006 // mark it as such. This test checks if this is the first time UpdateURL
2007 // has been called since WillNavigateToURL was called to initiate the load.
2008 if (page_id_
> last_page_id_sent_to_browser_
)
2009 params
.transition
= PAGE_TRANSITION_MANUAL_SUBFRAME
;
2011 params
.transition
= PAGE_TRANSITION_AUTO_SUBFRAME
;
2013 DCHECK(!navigation_state
->history_list_was_cleared());
2014 params
.history_list_was_cleared
= false;
2016 // Don't send this message while the subframe is swapped out.
2017 // TODO(creis): This whole method should move to RenderFrame.
2018 RenderFrameImpl
* rf
= RenderFrameImpl::FindByWebFrame(frame
);
2019 if (!rf
|| !rf
->is_swapped_out())
2020 Send(new ViewHostMsg_FrameNavigate(routing_id_
, params
));
2023 last_page_id_sent_to_browser_
=
2024 std::max(last_page_id_sent_to_browser_
, page_id_
);
2026 // If we end up reusing this WebRequest (for example, due to a #ref click),
2027 // we don't want the transition type to persist. Just clear it.
2028 navigation_state
->set_transition_type(PAGE_TRANSITION_LINK
);
2031 // Tell the embedding application that the title of the active page has changed
2032 void RenderViewImpl::UpdateTitle(WebFrame
* frame
,
2033 const base::string16
& title
,
2034 WebTextDirection title_direction
) {
2035 // Ignore all but top level navigations.
2036 if (frame
->parent())
2039 base::debug::TraceLog::GetInstance()->UpdateProcessLabel(
2040 routing_id_
, base::UTF16ToUTF8(title
));
2042 base::string16 shortened_title
= title
.substr(0, kMaxTitleChars
);
2043 Send(new ViewHostMsg_UpdateTitle(routing_id_
, page_id_
, shortened_title
,
2047 void RenderViewImpl::UpdateEncoding(WebFrame
* frame
,
2048 const std::string
& encoding_name
) {
2049 // Only update main frame's encoding_name.
2050 if (webview()->mainFrame() == frame
&&
2051 last_encoding_name_
!= encoding_name
) {
2052 // Save the encoding name for later comparing.
2053 last_encoding_name_
= encoding_name
;
2055 Send(new ViewHostMsg_UpdateEncoding(routing_id_
, last_encoding_name_
));
2059 // Sends the last committed session history state to the browser so it will be
2060 // saved before we navigate to a new page. This must be called *before* the
2061 // page ID has been updated so we know what it was.
2062 void RenderViewImpl::UpdateSessionHistory(WebFrame
* frame
) {
2063 // If we have a valid page ID at this point, then it corresponds to the page
2064 // we are navigating away from. Otherwise, this is the first navigation, so
2065 // there is no past session history to record.
2069 const WebHistoryItem
& item
=
2070 webview()->mainFrame()->previousHistoryItem();
2071 SendUpdateState(item
);
2074 void RenderViewImpl::SendUpdateState(const WebHistoryItem
& item
) {
2078 // Don't send state updates for kSwappedOutURL.
2079 if (item
.urlString() == WebString::fromUTF8(kSwappedOutURL
))
2082 Send(new ViewHostMsg_UpdateState(
2083 routing_id_
, page_id_
, HistoryItemToPageState(item
)));
2086 void RenderViewImpl::OpenURL(WebFrame
* frame
,
2088 const Referrer
& referrer
,
2089 WebNavigationPolicy policy
) {
2090 ViewHostMsg_OpenURL_Params params
;
2092 params
.referrer
= referrer
;
2093 params
.disposition
= NavigationPolicyToDisposition(policy
);
2094 params
.frame_id
= frame
->identifier();
2095 WebDataSource
* ds
= frame
->provisionalDataSource();
2097 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2098 NavigationState
* navigation_state
= document_state
->navigation_state();
2099 if (navigation_state
->is_content_initiated()) {
2100 params
.should_replace_current_entry
= ds
->replacesCurrentHistoryItem();
2102 // This is necessary to preserve the should_replace_current_entry value on
2103 // cross-process redirects, in the event it was set by a previous process.
2105 // TODO(davidben): Avoid this awkward duplication of state. See comment on
2106 // NavigationState::should_replace_current_entry().
2107 params
.should_replace_current_entry
=
2108 navigation_state
->should_replace_current_entry();
2111 params
.should_replace_current_entry
= false;
2113 params
.user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
2114 if (GetContentClient()->renderer()->AllowPopup())
2115 params
.user_gesture
= true;
2117 if (policy
== blink::WebNavigationPolicyNewBackgroundTab
||
2118 policy
== blink::WebNavigationPolicyNewForegroundTab
||
2119 policy
== blink::WebNavigationPolicyNewWindow
||
2120 policy
== blink::WebNavigationPolicyNewPopup
) {
2121 WebUserGestureIndicator::consumeUserGesture();
2124 Send(new ViewHostMsg_OpenURL(routing_id_
, params
));
2127 // WebViewDelegate ------------------------------------------------------------
2129 void RenderViewImpl::LoadNavigationErrorPage(
2131 const WebURLRequest
& failed_request
,
2132 const WebURLError
& error
,
2133 const std::string
& html
,
2135 std::string alt_html
;
2136 const std::string
* error_html
;
2138 if (!html
.empty()) {
2141 GetContentClient()->renderer()->GetNavigationErrorStrings(
2142 frame
, failed_request
, error
, renderer_preferences_
.accept_languages
,
2144 error_html
= &alt_html
;
2147 frame
->loadHTMLString(*error_html
,
2148 GURL(kUnreachableWebDataURL
),
2149 error
.unreachableURL
,
2153 bool RenderViewImpl::RunJavaScriptMessage(JavaScriptMessageType type
,
2154 const base::string16
& message
,
2155 const base::string16
& default_value
,
2156 const GURL
& frame_url
,
2157 base::string16
* result
) {
2158 // Don't allow further dialogs if we are waiting to swap out, since the
2159 // PageGroupLoadDeferrer in our stack prevents it.
2160 if (suppress_dialogs_until_swap_out_
)
2163 bool success
= false;
2164 base::string16 result_temp
;
2166 result
= &result_temp
;
2168 SendAndRunNestedMessageLoop(new ViewHostMsg_RunJavaScriptMessage(
2169 routing_id_
, message
, default_value
, frame_url
, type
, &success
, result
));
2173 bool RenderViewImpl::SendAndRunNestedMessageLoop(IPC::SyncMessage
* message
) {
2174 // Before WebKit asks us to show an alert (etc.), it takes care of doing the
2175 // equivalent of WebView::willEnterModalLoop. In the case of showModalDialog
2176 // it is particularly important that we do not call willEnterModalLoop as
2177 // that would defer resource loads for the dialog itself.
2178 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
2179 RenderThreadImpl::current()->DoNotNotifyWebKitOfModalLoop();
2181 message
->EnableMessagePumping(); // Runs a nested message loop.
2182 return Send(message
);
2185 void RenderViewImpl::GetWindowSnapshot(const WindowSnapshotCallback
& callback
) {
2186 int id
= next_snapshot_id_
++;
2187 pending_snapshots_
.insert(std::make_pair(id
, callback
));
2188 ui::LatencyInfo latency_info
;
2189 latency_info
.AddLatencyNumber(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT
,
2190 GetLatencyComponentId(),
2192 scoped_ptr
<cc::SwapPromiseMonitor
> latency_info_swap_promise_monitor
;
2193 if (RenderWidgetCompositor
* rwc
= compositor()) {
2194 latency_info_swap_promise_monitor
=
2195 rwc
->CreateLatencyInfoSwapPromiseMonitor(&latency_info
).Pass();
2197 latency_info_
.push_back(latency_info
);
2199 ScheduleCompositeWithForcedRedraw();
2202 void RenderViewImpl::OnWindowSnapshotCompleted(const int snapshot_id
,
2203 const gfx::Size
& size
, const std::vector
<unsigned char>& png
) {
2205 // Any pending snapshots with a lower ID than the one received are considered
2206 // to be implicitly complete, and returned the same snapshot data.
2207 PendingSnapshotMap::iterator it
= pending_snapshots_
.begin();
2208 while(it
!= pending_snapshots_
.end()) {
2209 if (it
->first
<= snapshot_id
) {
2210 it
->second
.Run(size
, png
);
2211 pending_snapshots_
.erase(it
++);
2218 // blink::WebViewClient ------------------------------------------------------
2220 WebView
* RenderViewImpl::createView(
2222 const WebURLRequest
& request
,
2223 const WebWindowFeatures
& features
,
2224 const WebString
& frame_name
,
2225 WebNavigationPolicy policy
,
2226 bool suppress_opener
) {
2227 ViewHostMsg_CreateWindow_Params params
;
2228 params
.opener_id
= routing_id_
;
2229 params
.user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
2230 if (GetContentClient()->renderer()->AllowPopup())
2231 params
.user_gesture
= true;
2232 params
.window_container_type
= WindowFeaturesToContainerType(features
);
2233 params
.session_storage_namespace_id
= session_storage_namespace_id_
;
2234 if (frame_name
!= "_blank")
2235 params
.frame_name
= frame_name
;
2236 params
.opener_frame_id
= creator
->identifier();
2237 params
.opener_url
= creator
->document().url();
2238 params
.opener_top_level_frame_url
= creator
->top()->document().url();
2239 GURL
security_url(creator
->document().securityOrigin().toString().utf8());
2240 if (!security_url
.is_valid())
2241 security_url
= GURL();
2242 params
.opener_security_origin
= security_url
;
2243 params
.opener_suppressed
= suppress_opener
;
2244 params
.disposition
= NavigationPolicyToDisposition(policy
);
2245 if (!request
.isNull()) {
2246 params
.target_url
= request
.url();
2247 params
.referrer
= GetReferrerFromRequest(creator
, request
);
2249 params
.features
= features
;
2251 for (size_t i
= 0; i
< features
.additionalFeatures
.size(); ++i
)
2252 params
.additional_features
.push_back(features
.additionalFeatures
[i
]);
2254 int32 routing_id
= MSG_ROUTING_NONE
;
2255 int32 main_frame_routing_id
= MSG_ROUTING_NONE
;
2256 int32 surface_id
= 0;
2257 int64 cloned_session_storage_namespace_id
;
2259 RenderThread::Get()->Send(
2260 new ViewHostMsg_CreateWindow(params
,
2262 &main_frame_routing_id
,
2264 &cloned_session_storage_namespace_id
));
2265 if (routing_id
== MSG_ROUTING_NONE
)
2268 WebUserGestureIndicator::consumeUserGesture();
2270 WebPreferences transferred_preferences
= webkit_preferences_
;
2272 // Unless accelerated compositing has been explicitly disabled from the
2273 // command line (e.g. via the blacklist or about:flags) re-enable it for
2274 // new views that get spawned by this view. This gets around the issue that
2275 // background extension pages disable accelerated compositing via web prefs
2276 // but can themselves spawn a visible render view which should be allowed
2277 // use gpu acceleration.
2278 if (!webkit_preferences_
.accelerated_compositing_enabled
) {
2279 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
2280 if (!command_line
.HasSwitch(switches::kDisableAcceleratedCompositing
))
2281 transferred_preferences
.accelerated_compositing_enabled
= true;
2284 // The initial hidden state for the RenderViewImpl here has to match what the
2285 // browser will eventually decide for the given disposition. Since we have to
2286 // return from this call synchronously, we just have to make our best guess
2287 // and rely on the browser sending a WasHidden / WasShown message if it
2289 RenderViewImpl
* view
= RenderViewImpl::Create(
2291 renderer_preferences_
,
2292 transferred_preferences
,
2294 main_frame_routing_id
,
2296 cloned_session_storage_namespace_id
,
2297 base::string16(), // WebCore will take care of setting the correct name.
2298 true, // is_renderer_created
2299 false, // swapped_out
2300 params
.disposition
== NEW_BACKGROUND_TAB
, // hidden
2303 accessibility_mode_
,
2304 allow_partial_swap_
);
2305 view
->opened_by_user_gesture_
= params
.user_gesture
;
2307 // Record whether the creator frame is trying to suppress the opener field.
2308 view
->opener_suppressed_
= params
.opener_suppressed
;
2310 // Copy over the alternate error page URL so we can have alt error pages in
2311 // the new render view (we don't need the browser to send the URL back down).
2312 view
->alternate_error_page_url_
= alternate_error_page_url_
;
2314 return view
->webview();
2317 WebWidget
* RenderViewImpl::createPopupMenu(blink::WebPopupType popup_type
) {
2318 RenderWidget
* widget
=
2319 RenderWidget::Create(routing_id_
, popup_type
, screen_info_
);
2320 if (screen_metrics_emulator_
) {
2321 widget
->SetPopupOriginAdjustmentsForEmulation(
2322 screen_metrics_emulator_
.get());
2324 return widget
->webwidget();
2327 WebExternalPopupMenu
* RenderViewImpl::createExternalPopupMenu(
2328 const WebPopupMenuInfo
& popup_menu_info
,
2329 WebExternalPopupMenuClient
* popup_menu_client
) {
2330 // An IPC message is sent to the browser to build and display the actual
2331 // popup. The user could have time to click a different select by the time
2332 // the popup is shown. In that case external_popup_menu_ is non NULL.
2333 // By returning NULL in that case, we instruct WebKit to cancel that new
2334 // popup. So from the user perspective, only the first one will show, and
2335 // will have to close the first one before another one can be shown.
2336 if (external_popup_menu_
)
2338 external_popup_menu_
.reset(
2339 new ExternalPopupMenu(this, popup_menu_info
, popup_menu_client
));
2340 if (screen_metrics_emulator_
) {
2341 SetExternalPopupOriginAdjustmentsForEmulation(
2342 external_popup_menu_
.get(), screen_metrics_emulator_
.get());
2344 return external_popup_menu_
.get();
2347 WebStorageNamespace
* RenderViewImpl::createSessionStorageNamespace() {
2348 CHECK(session_storage_namespace_id_
!= kInvalidSessionStorageNamespaceId
);
2349 return new WebStorageNamespaceImpl(session_storage_namespace_id_
);
2352 bool RenderViewImpl::shouldReportDetailedMessageForSource(
2353 const WebString
& source
) {
2354 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2358 void RenderViewImpl::didAddMessageToConsole(
2359 const WebConsoleMessage
& message
, const WebString
& source_name
,
2360 unsigned source_line
, const WebString
& stack_trace
) {
2361 logging::LogSeverity log_severity
= logging::LOG_VERBOSE
;
2362 switch (message
.level
) {
2363 case WebConsoleMessage::LevelDebug
:
2364 log_severity
= logging::LOG_VERBOSE
;
2366 case WebConsoleMessage::LevelLog
:
2367 case WebConsoleMessage::LevelInfo
:
2368 log_severity
= logging::LOG_INFO
;
2370 case WebConsoleMessage::LevelWarning
:
2371 log_severity
= logging::LOG_WARNING
;
2373 case WebConsoleMessage::LevelError
:
2374 log_severity
= logging::LOG_ERROR
;
2380 if (shouldReportDetailedMessageForSource(source_name
)) {
2384 DetailedConsoleMessageAdded(message
.text
,
2388 static_cast<int32
>(log_severity
)));
2391 Send(new ViewHostMsg_AddMessageToConsole(routing_id_
,
2392 static_cast<int32
>(log_severity
),
2394 static_cast<int32
>(source_line
),
2398 void RenderViewImpl::printPage(WebFrame
* frame
) {
2399 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
,
2400 PrintPage(frame
, handling_input_event_
));
2403 blink::WebNotificationPresenter
* RenderViewImpl::notificationPresenter() {
2404 return notification_provider_
;
2407 bool RenderViewImpl::enumerateChosenDirectory(
2408 const WebString
& path
,
2409 WebFileChooserCompletion
* chooser_completion
) {
2410 int id
= enumeration_completion_id_
++;
2411 enumeration_completions_
[id
] = chooser_completion
;
2412 return Send(new ViewHostMsg_EnumerateDirectory(
2415 base::FilePath::FromUTF16Unsafe(path
)));
2418 void RenderViewImpl::initializeHelperPluginWebFrame(
2419 blink::WebHelperPlugin
* plugin
) {
2420 plugin
->initializeFrame(main_render_frame_
.get());
2423 void RenderViewImpl::didStartLoading(bool to_different_document
) {
2427 void RenderViewImpl::didStartLoading() {
2429 DVLOG(1) << "didStartLoading called while loading";
2435 Send(new ViewHostMsg_DidStartLoading(routing_id_
));
2437 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidStartLoading());
2440 void RenderViewImpl::didStopLoading() {
2442 DVLOG(1) << "DidStopLoading called while not loading";
2446 is_loading_
= false;
2448 // NOTE: For now we're doing the safest thing, and sending out notification
2449 // when done loading. This currently isn't an issue as the favicon is only
2450 // displayed when done loading. Ideally we would send notification when
2451 // finished parsing the head, but webkit doesn't support that yet.
2452 // The feed discovery code would also benefit from access to the head.
2453 Send(new ViewHostMsg_DidStopLoading(routing_id_
));
2455 if (load_progress_tracker_
!= NULL
)
2456 load_progress_tracker_
->DidStopLoading();
2458 DidStopLoadingIcons();
2460 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidStopLoading());
2463 void RenderViewImpl::didChangeLoadProgress(WebFrame
* frame
,
2464 double load_progress
) {
2465 if (load_progress_tracker_
!= NULL
)
2466 load_progress_tracker_
->DidChangeLoadProgress(frame
, load_progress
);
2469 void RenderViewImpl::didCancelCompositionOnSelectionChange() {
2470 Send(new ViewHostMsg_ImeCancelComposition(routing_id()));
2473 void RenderViewImpl::didChangeSelection(bool is_empty_selection
) {
2474 if (!handling_input_event_
&& !handling_select_range_
)
2477 if (is_empty_selection
)
2478 selection_text_
.clear();
2480 // UpdateTextInputType should be called before SyncSelectionIfRequired.
2481 // UpdateTextInputType may send TextInputTypeChanged to notify the focus
2482 // was changed, and SyncSelectionIfRequired may send SelectionChanged
2483 // to notify the selection was changed. Focus change should be notified
2484 // before selection change.
2485 UpdateTextInputType();
2486 SyncSelectionIfRequired();
2487 #if defined(OS_ANDROID)
2488 UpdateTextInputState(false, true);
2492 void RenderViewImpl::didExecuteCommand(const WebString
& command_name
) {
2493 const std::string
& name
= base::UTF16ToUTF8(command_name
);
2494 if (StartsWithASCII(name
, "Move", true) ||
2495 StartsWithASCII(name
, "Insert", true) ||
2496 StartsWithASCII(name
, "Delete", true))
2498 RenderThreadImpl::current()->RecordComputedAction(name
);
2501 bool RenderViewImpl::handleCurrentKeyboardEvent() {
2502 if (edit_commands_
.empty())
2505 WebFrame
* frame
= webview()->focusedFrame();
2509 EditCommands::iterator it
= edit_commands_
.begin();
2510 EditCommands::iterator end
= edit_commands_
.end();
2512 bool did_execute_command
= false;
2513 for (; it
!= end
; ++it
) {
2514 // In gtk and cocoa, it's possible to bind multiple edit commands to one
2515 // key (but it's the exception). Once one edit command is not executed, it
2516 // seems safest to not execute the rest.
2517 if (!frame
->executeCommand(WebString::fromUTF8(it
->name
),
2518 WebString::fromUTF8(it
->value
),
2521 did_execute_command
= true;
2524 return did_execute_command
;
2527 blink::WebColorChooser
* RenderViewImpl::createColorChooser(
2528 blink::WebColorChooserClient
* client
,
2529 const blink::WebColor
& initial_color
,
2530 const blink::WebVector
<blink::WebColorSuggestion
>& suggestions
) {
2531 RendererWebColorChooserImpl
* color_chooser
=
2532 new RendererWebColorChooserImpl(this, client
);
2533 std::vector
<content::ColorSuggestion
> color_suggestions
;
2534 for (size_t i
= 0; i
< suggestions
.size(); i
++) {
2535 color_suggestions
.push_back(content::ColorSuggestion(suggestions
[i
]));
2537 color_chooser
->Open(static_cast<SkColor
>(initial_color
), color_suggestions
);
2538 return color_chooser
;
2541 bool RenderViewImpl::runFileChooser(
2542 const blink::WebFileChooserParams
& params
,
2543 WebFileChooserCompletion
* chooser_completion
) {
2544 // Do not open the file dialog in a hidden RenderView.
2547 FileChooserParams ipc_params
;
2548 if (params
.directory
)
2549 ipc_params
.mode
= FileChooserParams::UploadFolder
;
2550 else if (params
.multiSelect
)
2551 ipc_params
.mode
= FileChooserParams::OpenMultiple
;
2552 else if (params
.saveAs
)
2553 ipc_params
.mode
= FileChooserParams::Save
;
2555 ipc_params
.mode
= FileChooserParams::Open
;
2556 ipc_params
.title
= params
.title
;
2557 ipc_params
.default_file_name
=
2558 base::FilePath::FromUTF16Unsafe(params
.initialValue
);
2559 ipc_params
.accept_types
.reserve(params
.acceptTypes
.size());
2560 for (size_t i
= 0; i
< params
.acceptTypes
.size(); ++i
)
2561 ipc_params
.accept_types
.push_back(params
.acceptTypes
[i
]);
2562 #if defined(OS_ANDROID)
2563 ipc_params
.capture
= params
.useMediaCapture
;
2566 return ScheduleFileChooser(ipc_params
, chooser_completion
);
2569 void RenderViewImpl::runModalAlertDialog(WebFrame
* frame
,
2570 const WebString
& message
) {
2571 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT
,
2574 frame
->document().url(),
2578 bool RenderViewImpl::runModalConfirmDialog(WebFrame
* frame
,
2579 const WebString
& message
) {
2580 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM
,
2583 frame
->document().url(),
2587 bool RenderViewImpl::runModalPromptDialog(WebFrame
* frame
,
2588 const WebString
& message
,
2589 const WebString
& default_value
,
2590 WebString
* actual_value
) {
2591 base::string16 result
;
2592 bool ok
= RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT
,
2595 frame
->document().url(),
2598 actual_value
->assign(result
);
2602 bool RenderViewImpl::runModalBeforeUnloadDialog(
2603 WebFrame
* frame
, const WebString
& message
) {
2604 bool is_reload
= false;
2605 WebDataSource
* ds
= frame
->provisionalDataSource();
2607 is_reload
= (ds
->navigationType() == blink::WebNavigationTypeReload
);
2608 return runModalBeforeUnloadDialog(frame
, is_reload
, message
);
2611 bool RenderViewImpl::runModalBeforeUnloadDialog(
2612 WebFrame
* frame
, bool is_reload
, const WebString
& message
) {
2613 // If we are swapping out, we have already run the beforeunload handler.
2614 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
2615 // at all, to avoid running it twice.
2616 if (is_swapped_out_
)
2619 // Don't allow further dialogs if we are waiting to swap out, since the
2620 // PageGroupLoadDeferrer in our stack prevents it.
2621 if (suppress_dialogs_until_swap_out_
)
2624 bool success
= false;
2625 // This is an ignored return value, but is included so we can accept the same
2626 // response as RunJavaScriptMessage.
2627 base::string16 ignored_result
;
2628 SendAndRunNestedMessageLoop(new ViewHostMsg_RunBeforeUnloadConfirm(
2629 routing_id_
, frame
->document().url(), message
, is_reload
,
2630 &success
, &ignored_result
));
2634 void RenderViewImpl::showValidationMessage(
2635 const blink::WebRect
& anchor_in_root_view
,
2636 const blink::WebString
& main_text
,
2637 const blink::WebString
& sub_text
,
2638 blink::WebTextDirection hint
) {
2639 base::string16 wrapped_main_text
= main_text
;
2640 base::string16 wrapped_sub_text
= sub_text
;
2641 if (hint
== blink::WebTextDirectionLeftToRight
) {
2643 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_main_text
);
2644 if (!wrapped_sub_text
.empty()) {
2646 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_sub_text
);
2648 } else if (hint
== blink::WebTextDirectionRightToLeft
2649 && !base::i18n::IsRTL()) {
2650 base::i18n::WrapStringWithRTLFormatting(&wrapped_main_text
);
2651 if (!wrapped_sub_text
.empty()) {
2652 base::i18n::WrapStringWithRTLFormatting(&wrapped_sub_text
);
2655 Send(new ViewHostMsg_ShowValidationMessage(
2656 routing_id(), anchor_in_root_view
, wrapped_main_text
, wrapped_sub_text
));
2659 void RenderViewImpl::hideValidationMessage() {
2660 Send(new ViewHostMsg_HideValidationMessage(routing_id()));
2663 void RenderViewImpl::moveValidationMessage(
2664 const blink::WebRect
& anchor_in_root_view
) {
2665 Send(new ViewHostMsg_MoveValidationMessage(routing_id(),
2666 anchor_in_root_view
));
2669 void RenderViewImpl::showContextMenu(
2670 WebFrame
* frame
, const WebContextMenuData
& data
) {
2671 ContextMenuParams params
= ContextMenuParamsBuilder::Build(data
);
2672 params
.source_type
= context_menu_source_type_
;
2673 if (context_menu_source_type_
== ui::MENU_SOURCE_TOUCH_EDIT_MENU
) {
2674 params
.x
= touch_editing_context_menu_location_
.x();
2675 params
.y
= touch_editing_context_menu_location_
.y();
2677 OnShowHostContextMenu(¶ms
);
2679 // Plugins, e.g. PDF, don't currently update the render view when their
2680 // selected text changes, but the context menu params do contain the updated
2681 // selection. If that's the case, update the render view's state just prior
2682 // to showing the context menu.
2683 // TODO(asvitkine): http://crbug.com/152432
2684 if (ShouldUpdateSelectionTextFromContextMenuParams(selection_text_
,
2685 selection_text_offset_
,
2688 selection_text_
= params
.selection_text
;
2689 // TODO(asvitkine): Text offset and range is not available in this case.
2690 selection_text_offset_
= 0;
2691 selection_range_
= gfx::Range(0, selection_text_
.length());
2692 Send(new ViewHostMsg_SelectionChanged(routing_id_
,
2694 selection_text_offset_
,
2698 // frame is NULL if invoked by BlockedPlugin.
2700 params
.frame_id
= frame
->identifier();
2702 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
2703 // it. We replace it with an empty GURL so the appropriate items are disabled
2704 // in the context menu.
2705 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
2706 // data encoded images. We should have a way to save them.
2707 if (params
.src_url
.spec().size() > GetMaxURLChars())
2708 params
.src_url
= GURL();
2709 context_menu_node_
= data
.node
;
2711 #if defined(OS_ANDROID)
2712 gfx::Rect start_rect
;
2714 GetSelectionBounds(&start_rect
, &end_rect
);
2715 params
.selection_start
= gfx::Point(start_rect
.x(), start_rect
.bottom());
2716 params
.selection_end
= gfx::Point(end_rect
.right(), end_rect
.bottom());
2719 Send(new ViewHostMsg_ContextMenu(routing_id_
, params
));
2722 RenderViewObserver
, observers_
, DidRequestShowContextMenu(frame
, data
));
2725 void RenderViewImpl::clearContextMenu() {
2726 context_menu_node_
.reset();
2729 void RenderViewImpl::setStatusText(const WebString
& text
) {
2732 void RenderViewImpl::UpdateTargetURL(const GURL
& url
,
2733 const GURL
& fallback_url
) {
2734 GURL latest_url
= url
.is_empty() ? fallback_url
: url
;
2735 if (latest_url
== target_url_
)
2738 // Tell the browser to display a destination link.
2739 if (target_url_status_
== TARGET_INFLIGHT
||
2740 target_url_status_
== TARGET_PENDING
) {
2741 // If we have a request in-flight, save the URL to be sent when we
2742 // receive an ACK to the in-flight request. We can happily overwrite
2743 // any existing pending sends.
2744 pending_target_url_
= latest_url
;
2745 target_url_status_
= TARGET_PENDING
;
2747 // URLs larger than |MaxURLChars()| cannot be sent through IPC -
2748 // see |ParamTraits<GURL>|.
2749 if (latest_url
.possibly_invalid_spec().size() > GetMaxURLChars())
2750 latest_url
= GURL();
2751 Send(new ViewHostMsg_UpdateTargetURL(routing_id_
, page_id_
, latest_url
));
2752 target_url_
= latest_url
;
2753 target_url_status_
= TARGET_INFLIGHT
;
2757 gfx::RectF
RenderViewImpl::ClientRectToPhysicalWindowRect(
2758 const gfx::RectF
& rect
) const {
2759 gfx::RectF window_rect
= rect
;
2760 window_rect
.Scale(device_scale_factor_
* webview()->pageScaleFactor());
2764 int64
RenderViewImpl::GetLatencyComponentId() {
2765 // Note: this must match the logic in RenderWidgetHostImpl.
2766 return GetRoutingID() | (static_cast<int64
>(
2767 RenderThreadImpl::current()->renderer_process_id()) << 32);
2770 void RenderViewImpl::StartNavStateSyncTimerIfNecessary() {
2771 // No need to update state if no page has committed yet.
2776 if (send_content_state_immediately_
)
2778 else if (is_hidden())
2779 delay
= kDelaySecondsForContentStateSyncHidden
;
2781 delay
= kDelaySecondsForContentStateSync
;
2783 if (nav_state_sync_timer_
.IsRunning()) {
2784 // The timer is already running. If the delay of the timer maches the amount
2785 // we want to delay by, then return. Otherwise stop the timer so that it
2786 // gets started with the right delay.
2787 if (nav_state_sync_timer_
.GetCurrentDelay().InSeconds() == delay
)
2789 nav_state_sync_timer_
.Stop();
2792 nav_state_sync_timer_
.Start(FROM_HERE
, TimeDelta::FromSeconds(delay
), this,
2793 &RenderViewImpl::SyncNavigationState
);
2796 void RenderViewImpl::setMouseOverURL(const WebURL
& url
) {
2797 mouse_over_url_
= GURL(url
);
2798 UpdateTargetURL(mouse_over_url_
, focus_url_
);
2801 void RenderViewImpl::setKeyboardFocusURL(const WebURL
& url
) {
2802 focus_url_
= GURL(url
);
2803 UpdateTargetURL(focus_url_
, mouse_over_url_
);
2806 void RenderViewImpl::startDragging(WebFrame
* frame
,
2807 const WebDragData
& data
,
2808 WebDragOperationsMask mask
,
2809 const WebImage
& image
,
2810 const WebPoint
& webImageOffset
) {
2811 DropData
drop_data(DropDataBuilder::Build(data
));
2812 drop_data
.referrer_policy
= frame
->document().referrerPolicy();
2813 gfx::Vector2d
imageOffset(webImageOffset
.x
, webImageOffset
.y
);
2814 Send(new DragHostMsg_StartDragging(routing_id_
,
2817 image
.getSkBitmap(),
2819 possible_drag_event_info_
));
2822 bool RenderViewImpl::acceptsLoadDrops() {
2823 return renderer_preferences_
.can_accept_load_drops
;
2826 void RenderViewImpl::focusNext() {
2827 Send(new ViewHostMsg_TakeFocus(routing_id_
, false));
2830 void RenderViewImpl::focusPrevious() {
2831 Send(new ViewHostMsg_TakeFocus(routing_id_
, true));
2834 void RenderViewImpl::focusedNodeChanged(const WebNode
& node
) {
2835 Send(new ViewHostMsg_FocusedNodeChanged(routing_id_
, IsEditableNode(node
)));
2837 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, FocusedNodeChanged(node
));
2840 void RenderViewImpl::numberOfWheelEventHandlersChanged(unsigned num_handlers
) {
2841 Send(new ViewHostMsg_DidChangeNumWheelEvents(routing_id_
, num_handlers
));
2844 void RenderViewImpl::didUpdateLayout() {
2845 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidUpdateLayout());
2847 // We don't always want to set up a timer, only if we've been put in that
2848 // mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
2850 if (!send_preferred_size_changes_
|| !webview())
2853 if (check_preferred_size_timer_
.IsRunning())
2855 check_preferred_size_timer_
.Start(FROM_HERE
,
2856 TimeDelta::FromMilliseconds(0), this,
2857 &RenderViewImpl::CheckPreferredSize
);
2860 void RenderViewImpl::navigateBackForwardSoon(int offset
) {
2861 Send(new ViewHostMsg_GoToEntryAtOffset(routing_id_
, offset
));
2864 int RenderViewImpl::historyBackListCount() {
2865 return history_list_offset_
< 0 ? 0 : history_list_offset_
;
2868 int RenderViewImpl::historyForwardListCount() {
2869 return history_list_length_
- historyBackListCount() - 1;
2872 void RenderViewImpl::postAccessibilityEvent(
2873 const WebAXObject
& obj
, blink::WebAXEvent event
) {
2874 if (renderer_accessibility_
) {
2875 renderer_accessibility_
->HandleWebAccessibilityEvent(obj
, event
);
2879 void RenderViewImpl::didUpdateInspectorSetting(const WebString
& key
,
2880 const WebString
& value
) {
2881 Send(new ViewHostMsg_UpdateInspectorSetting(routing_id_
,
2886 // blink::WebWidgetClient ----------------------------------------------------
2888 void RenderViewImpl::didFocus() {
2889 // TODO(jcivelli): when https://bugs.webkit.org/show_bug.cgi?id=33389 is fixed
2890 // we won't have to test for user gesture anymore and we can
2891 // move that code back to render_widget.cc
2892 if (WebUserGestureIndicator::isProcessingUserGesture() &&
2893 !RenderThreadImpl::current()->layout_test_mode()) {
2894 Send(new ViewHostMsg_Focus(routing_id_
));
2898 void RenderViewImpl::didBlur() {
2899 // TODO(jcivelli): see TODO above in didFocus().
2900 if (WebUserGestureIndicator::isProcessingUserGesture() &&
2901 !RenderThreadImpl::current()->layout_test_mode()) {
2902 Send(new ViewHostMsg_Blur(routing_id_
));
2906 // We are supposed to get a single call to Show for a newly created RenderView
2907 // that was created via RenderViewImpl::CreateWebView. So, we wait until this
2908 // point to dispatch the ShowView message.
2910 // This method provides us with the information about how to display the newly
2911 // created RenderView (i.e., as a blocked popup or as a new tab).
2913 void RenderViewImpl::show(WebNavigationPolicy policy
) {
2915 // When supports_multiple_windows is disabled, popups are reusing
2916 // the same view. In some scenarios, this makes WebKit to call show() twice.
2917 if (webkit_preferences_
.supports_multiple_windows
)
2918 NOTREACHED() << "received extraneous Show call";
2923 DCHECK(opener_id_
!= MSG_ROUTING_NONE
);
2925 // Force new windows to a popup if they were not opened with a user gesture.
2926 if (!opened_by_user_gesture_
) {
2927 // We exempt background tabs for compat with older versions of Chrome.
2928 // TODO(darin): This seems bogus. These should have a user gesture, so
2929 // we probably don't need this check.
2930 if (policy
!= blink::WebNavigationPolicyNewBackgroundTab
)
2931 policy
= blink::WebNavigationPolicyNewPopup
;
2934 // NOTE: initial_pos_ may still have its default values at this point, but
2935 // that's okay. It'll be ignored if disposition is not NEW_POPUP, or the
2936 // browser process will impose a default position otherwise.
2937 Send(new ViewHostMsg_ShowView(opener_id_
, routing_id_
,
2938 NavigationPolicyToDisposition(policy
), initial_pos_
,
2939 opened_by_user_gesture_
));
2940 SetPendingWindowRect(initial_pos_
);
2943 void RenderViewImpl::runModal() {
2944 DCHECK(did_show_
) << "should already have shown the view";
2946 // Don't allow further dialogs if we are waiting to swap out, since the
2947 // PageGroupLoadDeferrer in our stack prevents it.
2948 if (suppress_dialogs_until_swap_out_
)
2951 // We must keep WebKit's shared timer running in this case in order to allow
2952 // showModalDialog to function properly.
2954 // TODO(darin): WebKit should really be smarter about suppressing events and
2955 // timers so that we do not need to manage the shared timer in such a heavy
2958 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
2959 RenderThreadImpl::current()->DoNotSuspendWebKitSharedTimer();
2961 SendAndRunNestedMessageLoop(new ViewHostMsg_RunModal(
2962 routing_id_
, opener_id_
));
2965 bool RenderViewImpl::enterFullScreen() {
2966 Send(new ViewHostMsg_ToggleFullscreen(routing_id_
, true));
2970 void RenderViewImpl::exitFullScreen() {
2971 Send(new ViewHostMsg_ToggleFullscreen(routing_id_
, false));
2974 bool RenderViewImpl::requestPointerLock() {
2975 return mouse_lock_dispatcher_
->LockMouse(webwidget_mouse_lock_target_
.get());
2978 void RenderViewImpl::requestPointerUnlock() {
2979 mouse_lock_dispatcher_
->UnlockMouse(webwidget_mouse_lock_target_
.get());
2982 bool RenderViewImpl::isPointerLocked() {
2983 return mouse_lock_dispatcher_
->IsMouseLockedTo(
2984 webwidget_mouse_lock_target_
.get());
2987 void RenderViewImpl::didActivateCompositor(int input_handler_identifier
) {
2988 #if !defined(OS_MACOSX) // many events are unhandled - http://crbug.com/138003
2989 InputHandlerManager
* input_handler_manager
=
2990 RenderThreadImpl::current()->input_handler_manager();
2991 if (input_handler_manager
) {
2992 input_handler_manager
->AddInputHandler(
2994 compositor_
->GetInputHandler(),
2999 RenderWidget::didActivateCompositor(input_handler_identifier
);
3002 void RenderViewImpl::didHandleGestureEvent(
3003 const WebGestureEvent
& event
,
3004 bool event_cancelled
) {
3005 RenderWidget::didHandleGestureEvent(event
, event_cancelled
);
3007 if (event
.type
!= blink::WebGestureEvent::GestureTap
)
3010 blink::WebTextInputType text_input_type
=
3011 GetWebView()->textInputInfo().type
;
3013 Send(new ViewHostMsg_FocusedNodeTouched(
3014 routing_id(), text_input_type
!= blink::WebTextInputTypeNone
));
3017 void RenderViewImpl::initializeLayerTreeView() {
3018 RenderWidget::initializeLayerTreeView();
3019 RenderWidgetCompositor
* rwc
= compositor();
3020 if (!rwc
|| !webview() || !webview()->devToolsAgent())
3022 webview()->devToolsAgent()->setLayerTreeId(rwc
->GetLayerTreeId());
3025 // blink::WebFrameClient -----------------------------------------------------
3027 WebMediaPlayer
* RenderViewImpl::createMediaPlayer(
3028 WebFrame
* frame
, const blink::WebURL
& url
, WebMediaPlayerClient
* client
) {
3033 blink::WebMediaPlayer
* RenderViewImpl::CreateMediaPlayer(
3034 RenderFrame
* render_frame
,
3035 blink::WebFrame
* frame
,
3036 const blink::WebURL
& url
,
3037 blink::WebMediaPlayerClient
* client
) {
3039 RenderViewObserver
, observers_
, WillCreateMediaPlayer(frame
, client
));
3041 WebMediaPlayer
* player
= CreateWebMediaPlayerForMediaStream(frame
, url
,
3046 #if defined(OS_ANDROID)
3047 return CreateAndroidWebMediaPlayer(frame
, url
, client
);
3049 scoped_refptr
<media::AudioRendererSink
> sink
;
3050 if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableAudio
)) {
3051 sink
= RenderThreadImpl::current()->GetAudioRendererMixerManager()->
3052 CreateInput(routing_id_
);
3053 DVLOG(1) << "Using AudioRendererMixerManager-provided sink: " << sink
.get();
3056 WebMediaPlayerParams
params(
3057 base::Bind(&ContentRendererClient::DeferMediaLoad
,
3058 base::Unretained(GetContentClient()->renderer()),
3059 static_cast<RenderFrame
*>(render_frame
)),
3061 return new WebMediaPlayerImpl(this, frame
, client
, AsWeakPtr(), params
);
3062 #endif // defined(OS_ANDROID)
3065 void RenderViewImpl::didAccessInitialDocument(WebFrame
* frame
) {
3066 // Notify the browser process that it is no longer safe to show the pending
3067 // URL of the main frame, since a URL spoof is now possible.
3068 if (!frame
->parent() && page_id_
== -1)
3069 Send(new ViewHostMsg_DidAccessInitialDocument(routing_id_
));
3072 void RenderViewImpl::didDisownOpener(blink::WebFrame
* frame
) {
3073 // We only need to notify the browser if the active, top-level frame clears
3074 // its opener. We can ignore cases where a swapped out frame clears its
3075 // opener after hearing about it from the browser, and the browser does not
3076 // (yet) care about subframe openers.
3077 if (is_swapped_out_
|| frame
->parent())
3080 // Notify WebContents and all its swapped out RenderViews.
3081 Send(new ViewHostMsg_DidDisownOpener(routing_id_
));
3084 void RenderViewImpl::frameDetached(WebFrame
* frame
) {
3085 // NOTE: We may get here for either the main frame or for subframes. The
3086 // RenderFrameImpl will be deleted immediately after this call for subframes
3087 // but not for the main frame, which is owned by |main_render_frame_|.
3089 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, FrameDetached(frame
));
3092 void RenderViewImpl::willClose(WebFrame
* frame
) {
3093 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, FrameWillClose(frame
));
3096 void RenderViewImpl::didMatchCSS(
3098 const WebVector
<WebString
>& newly_matching_selectors
,
3099 const WebVector
<WebString
>& stopped_matching_selectors
) {
3101 RenderViewObserver
, observers_
,
3102 DidMatchCSS(frame
, newly_matching_selectors
, stopped_matching_selectors
));
3105 void RenderViewImpl::Repaint(const gfx::Size
& size
) {
3109 void RenderViewImpl::SetEditCommandForNextKeyEvent(const std::string
& name
,
3110 const std::string
& value
) {
3111 EditCommands edit_commands
;
3112 edit_commands
.push_back(EditCommand(name
, value
));
3113 OnSetEditCommandsForNextKeyEvent(edit_commands
);
3116 void RenderViewImpl::ClearEditCommands() {
3117 edit_commands_
.clear();
3120 SSLStatus
RenderViewImpl::GetSSLStatusOfFrame(blink::WebFrame
* frame
) const {
3121 std::string security_info
;
3122 if (frame
&& frame
->dataSource())
3123 security_info
= frame
->dataSource()->response().securityInfo();
3125 SSLStatus ssl_status
;
3126 DeserializeSecurityInfo(security_info
,
3127 &ssl_status
.cert_id
,
3128 &ssl_status
.cert_status
,
3129 &ssl_status
.security_bits
,
3130 &ssl_status
.connection_status
,
3131 &ssl_status
.signed_certificate_timestamp_ids
);
3135 const std::string
& RenderViewImpl::GetAcceptLanguages() const {
3136 return renderer_preferences_
.accept_languages
;
3139 WebNavigationPolicy
RenderViewImpl::DecidePolicyForNavigation(
3140 RenderFrame
* render_frame
, WebFrame
* frame
,
3141 WebDataSource::ExtraData
* extraData
, const WebURLRequest
& request
,
3142 WebNavigationType type
, WebNavigationPolicy default_policy
,
3145 // The handlenavigation API is deprecated and will be removed once
3146 // crbug.com/325351 is resolved.
3147 if (request
.url() != GURL(kSwappedOutURL
) &&
3148 GetContentClient()->renderer()->HandleNavigation(
3150 static_cast<DocumentState
*>(extraData
),
3157 return blink::WebNavigationPolicyIgnore
;
3161 Referrer
referrer(GetReferrerFromRequest(frame
, request
));
3163 if (is_swapped_out_
) {
3164 if (request
.url() != GURL(kSwappedOutURL
)) {
3165 // Targeted links may try to navigate a swapped out frame. Allow the
3166 // browser process to navigate the tab instead. Note that it is also
3167 // possible for non-targeted navigations (from this view) to arrive
3168 // here just after we are swapped out. It's ok to send them to the
3169 // browser, as long as they're for the top level frame.
3170 // TODO(creis): Ensure this supports targeted form submissions when
3171 // fixing http://crbug.com/101395.
3172 if (frame
->parent() == NULL
) {
3173 OpenURL(frame
, request
.url(), referrer
, default_policy
);
3174 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
3177 // We should otherwise ignore in-process iframe navigations, if they
3178 // arrive just after we are swapped out.
3179 return blink::WebNavigationPolicyIgnore
;
3182 // Allow kSwappedOutURL to complete.
3183 return default_policy
;
3186 // Webkit is asking whether to navigate to a new URL.
3187 // This is fine normally, except if we're showing UI from one security
3188 // context and they're trying to navigate to a different context.
3189 const GURL
& url
= request
.url();
3191 // A content initiated navigation may have originated from a link-click,
3192 // script, drag-n-drop operation, etc.
3193 bool is_content_initiated
= static_cast<DocumentState
*>(extraData
)->
3194 navigation_state()->is_content_initiated();
3197 // If --enable-strict-site-isolation or --site-per-process is enabled, send
3198 // all top-level navigations to the browser to let it swap processes when
3199 // crossing site boundaries. This is currently expected to break some script
3200 // calls and navigations, such as form submissions.
3201 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
3202 bool force_swap_due_to_flag
=
3203 command_line
.HasSwitch(switches::kEnableStrictSiteIsolation
) ||
3204 command_line
.HasSwitch(switches::kSitePerProcess
);
3205 if (force_swap_due_to_flag
&&
3206 !frame
->parent() && (is_content_initiated
|| is_redirect
)) {
3207 WebString origin_str
= frame
->document().securityOrigin().toString();
3208 GURL
frame_url(origin_str
.utf8().data());
3209 // TODO(cevans): revisit whether this site check is still necessary once
3210 // crbug.com/101395 is fixed.
3211 bool same_domain_or_host
=
3212 net::registry_controlled_domains::SameDomainOrHost(
3215 net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES
);
3216 if (!same_domain_or_host
|| frame_url
.scheme() != url
.scheme()) {
3217 OpenURL(frame
, url
, referrer
, default_policy
);
3218 return blink::WebNavigationPolicyIgnore
;
3222 // If the browser is interested, then give it a chance to look at the request.
3223 if (is_content_initiated
) {
3224 bool is_form_post
= ((type
== blink::WebNavigationTypeFormSubmitted
) ||
3225 (type
== blink::WebNavigationTypeFormResubmitted
)) &&
3226 EqualsASCII(request
.httpMethod(), "POST");
3227 bool browser_handles_request
=
3228 renderer_preferences_
.browser_handles_non_local_top_level_requests
&&
3229 IsNonLocalTopLevelNavigation(url
, frame
, type
, is_form_post
);
3230 if (!browser_handles_request
) {
3231 browser_handles_request
= IsTopLevelNavigation(frame
) &&
3232 renderer_preferences_
.browser_handles_all_top_level_requests
;
3235 if (browser_handles_request
) {
3236 // Reset these counters as the RenderView could be reused for the next
3239 last_page_id_sent_to_browser_
= -1;
3240 OpenURL(frame
, url
, referrer
, default_policy
);
3241 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
3245 // Use the frame's original request's URL rather than the document's URL for
3246 // subsequent checks. For a popup, the document's URL may become the opener
3247 // window's URL if the opener has called document.write().
3248 // See http://crbug.com/93517.
3249 GURL
old_url(frame
->dataSource()->request().url());
3251 // Detect when we're crossing a permission-based boundary (e.g. into or out of
3252 // an extension or app origin, leaving a WebUI page, etc). We only care about
3253 // top-level navigations (not iframes). But we sometimes navigate to
3254 // about:blank to clear a tab, and we want to still allow that.
3256 // Note: this is known to break POST submissions when crossing process
3257 // boundaries until http://crbug.com/101395 is fixed. This is better for
3258 // security than loading a WebUI, extension or app page in the wrong process.
3259 // POST requests don't work because this mechanism does not preserve form
3260 // POST data. We will need to send the request's httpBody data up to the
3261 // browser process, and issue a special POST navigation in WebKit (via
3262 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
3263 // for examples of how to send the httpBody data.
3264 if (!frame
->parent() && is_content_initiated
&&
3265 !url
.SchemeIs(chrome::kAboutScheme
)) {
3266 bool send_referrer
= false;
3268 // All navigations to or from WebUI URLs or within WebUI-enabled
3269 // RenderProcesses must be handled by the browser process so that the
3270 // correct bindings and data sources can be registered.
3271 // Similarly, navigations to view-source URLs or within ViewSource mode
3272 // must be handled by the browser process (except for reloads - those are
3273 // safe to leave within the renderer).
3274 // Lastly, access to file:// URLs from non-file:// URL pages must be
3275 // handled by the browser so that ordinary renderer processes don't get
3276 // blessed with file permissions.
3277 int cumulative_bindings
= RenderProcess::current()->GetEnabledBindings();
3278 bool is_initial_navigation
= page_id_
== -1;
3279 bool should_fork
= HasWebUIScheme(url
) || HasWebUIScheme(old_url
) ||
3280 (cumulative_bindings
& BINDINGS_POLICY_WEB_UI
) ||
3281 url
.SchemeIs(kViewSourceScheme
) ||
3282 (frame
->isViewSourceModeEnabled() &&
3283 type
!= blink::WebNavigationTypeReload
);
3285 if (!should_fork
&& url
.SchemeIs(kFileScheme
)) {
3286 // Fork non-file to file opens. Check the opener URL if this is the
3287 // initial navigation in a newly opened window.
3288 GURL
source_url(old_url
);
3289 if (is_initial_navigation
&& source_url
.is_empty() && frame
->opener())
3290 source_url
= frame
->opener()->top()->document().url();
3291 DCHECK(!source_url
.is_empty());
3292 should_fork
= !source_url
.SchemeIs(kFileScheme
);
3296 // Give the embedder a chance.
3297 should_fork
= GetContentClient()->renderer()->ShouldFork(
3298 frame
, url
, request
.httpMethod().utf8(), is_initial_navigation
,
3299 is_redirect
, &send_referrer
);
3304 frame
, url
, send_referrer
? referrer
: Referrer(), default_policy
);
3305 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
3309 // Detect when a page is "forking" a new tab that can be safely rendered in
3310 // its own process. This is done by sites like Gmail that try to open links
3311 // in new windows without script connections back to the original page. We
3312 // treat such cases as browser navigations (in which we will create a new
3313 // renderer for a cross-site navigation), rather than WebKit navigations.
3315 // We use the following heuristic to decide whether to fork a new page in its
3317 // The parent page must open a new tab to about:blank, set the new tab's
3318 // window.opener to null, and then redirect the tab to a cross-site URL using
3321 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
3324 // Must start from a tab showing about:blank, which is later redirected.
3325 old_url
== GURL(kAboutBlankURL
) &&
3326 // Must be the first real navigation of the tab.
3327 historyBackListCount() < 1 &&
3328 historyForwardListCount() < 1 &&
3329 // The parent page must have set the child's window.opener to null before
3330 // redirecting to the desired URL.
3331 frame
->opener() == NULL
&&
3332 // Must be a top-level frame.
3333 frame
->parent() == NULL
&&
3334 // Must not have issued the request from this page.
3335 is_content_initiated
&&
3336 // Must be targeted at the current tab.
3337 default_policy
== blink::WebNavigationPolicyCurrentTab
&&
3338 // Must be a JavaScript navigation, which appears as "other".
3339 type
== blink::WebNavigationTypeOther
;
3342 // Open the URL via the browser, not via WebKit.
3343 OpenURL(frame
, url
, Referrer(), default_policy
);
3344 return blink::WebNavigationPolicyIgnore
;
3347 return default_policy
;
3350 void RenderViewImpl::willSendSubmitEvent(blink::WebFrame
* frame
,
3351 const blink::WebFormElement
& form
) {
3353 RenderViewObserver
, observers_
, WillSendSubmitEvent(frame
, form
));
3356 void RenderViewImpl::willSubmitForm(WebFrame
* frame
,
3357 const WebFormElement
& form
) {
3359 RenderViewObserver
, observers_
, WillSubmitForm(frame
, form
));
3362 void RenderViewImpl::didCreateDataSource(WebFrame
* frame
, WebDataSource
* ds
) {
3363 bool content_initiated
= !pending_navigation_params_
.get();
3365 // Make sure any previous redirect URLs end up in our new data source.
3366 if (pending_navigation_params_
.get()) {
3367 for (std::vector
<GURL
>::const_iterator i
=
3368 pending_navigation_params_
->redirects
.begin();
3369 i
!= pending_navigation_params_
->redirects
.end(); ++i
) {
3370 ds
->appendRedirect(*i
);
3374 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3375 if (!document_state
) {
3376 document_state
= new DocumentState
;
3377 ds
->setExtraData(document_state
);
3378 if (!content_initiated
)
3379 PopulateDocumentStateFromPending(document_state
);
3382 // Carry over the user agent override flag, if it exists.
3383 if (content_initiated
&& webview() && webview()->mainFrame() &&
3384 webview()->mainFrame()->dataSource()) {
3385 DocumentState
* old_document_state
=
3386 DocumentState::FromDataSource(webview()->mainFrame()->dataSource());
3387 if (old_document_state
) {
3388 InternalDocumentStateData
* internal_data
=
3389 InternalDocumentStateData::FromDocumentState(document_state
);
3390 InternalDocumentStateData
* old_internal_data
=
3391 InternalDocumentStateData::FromDocumentState(old_document_state
);
3392 internal_data
->set_is_overriding_user_agent(
3393 old_internal_data
->is_overriding_user_agent());
3397 // The rest of RenderView assumes that a WebDataSource will always have a
3398 // non-null NavigationState.
3399 if (content_initiated
) {
3400 document_state
->set_navigation_state(
3401 NavigationState::CreateContentInitiated());
3403 document_state
->set_navigation_state(CreateNavigationStateFromPending());
3404 pending_navigation_params_
.reset();
3407 // DocumentState::referred_by_prefetcher_ is true if we are
3408 // navigating from a page that used prefetching using a link on that
3409 // page. We are early enough in the request process here that we
3410 // can still see the DocumentState of the previous page and set
3411 // this value appropriately.
3412 // TODO(gavinp): catch the important case of navigation in a new
3413 // renderer process.
3415 if (WebFrame
* old_frame
= webview()->mainFrame()) {
3416 const WebURLRequest
& original_request
= ds
->originalRequest();
3417 const GURL
referrer(
3418 original_request
.httpHeaderField(WebString::fromUTF8("Referer")));
3419 if (!referrer
.is_empty() &&
3420 DocumentState::FromDataSource(
3421 old_frame
->dataSource())->was_prefetcher()) {
3422 for (; old_frame
; old_frame
= old_frame
->traverseNext(false)) {
3423 WebDataSource
* old_frame_ds
= old_frame
->dataSource();
3424 if (old_frame_ds
&& referrer
== GURL(old_frame_ds
->request().url())) {
3425 document_state
->set_was_referred_by_prefetcher(true);
3433 if (content_initiated
) {
3434 const WebURLRequest
& request
= ds
->request();
3435 switch (request
.cachePolicy()) {
3436 case WebURLRequest::UseProtocolCachePolicy
: // normal load.
3437 document_state
->set_load_type(DocumentState::LINK_LOAD_NORMAL
);
3439 case WebURLRequest::ReloadIgnoringCacheData
: // reload.
3440 document_state
->set_load_type(DocumentState::LINK_LOAD_RELOAD
);
3442 case WebURLRequest::ReturnCacheDataElseLoad
: // allow stale data.
3443 document_state
->set_load_type(
3444 DocumentState::LINK_LOAD_CACHE_STALE_OK
);
3446 case WebURLRequest::ReturnCacheDataDontLoad
: // Don't re-post.
3447 document_state
->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY
);
3453 RenderViewObserver
, observers_
, DidCreateDataSource(frame
, ds
));
3456 void RenderViewImpl::PopulateDocumentStateFromPending(
3457 DocumentState
* document_state
) {
3458 const ViewMsg_Navigate_Params
& params
= *pending_navigation_params_
.get();
3459 document_state
->set_request_time(params
.request_time
);
3461 InternalDocumentStateData
* internal_data
=
3462 InternalDocumentStateData::FromDocumentState(document_state
);
3464 if (!params
.url
.SchemeIs(kJavaScriptScheme
) &&
3465 params
.navigation_type
== ViewMsg_Navigate_Type::RESTORE
) {
3466 // We're doing a load of a page that was restored from the last session. By
3467 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
3468 // can result in stale data for pages that are set to expire. We explicitly
3469 // override that by setting the policy here so that as necessary we load
3470 // from the network.
3472 // TODO(davidben): Remove this in favor of passing a cache policy to the
3473 // loadHistoryItem call in OnNavigate. That requires not overloading
3474 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
3475 // policy based on load type, etc".
3476 internal_data
->set_cache_policy_override(
3477 WebURLRequest::UseProtocolCachePolicy
);
3480 if (IsReload(params
))
3481 document_state
->set_load_type(DocumentState::RELOAD
);
3482 else if (params
.page_state
.IsValid())
3483 document_state
->set_load_type(DocumentState::HISTORY_LOAD
);
3485 document_state
->set_load_type(DocumentState::NORMAL_LOAD
);
3487 internal_data
->set_referrer_policy(params
.referrer
.policy
);
3488 internal_data
->set_is_overriding_user_agent(params
.is_overriding_user_agent
);
3489 internal_data
->set_must_reset_scroll_and_scale_state(
3490 params
.navigation_type
==
3491 ViewMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
);
3492 document_state
->set_can_load_local_resources(params
.can_load_local_resources
);
3495 NavigationState
* RenderViewImpl::CreateNavigationStateFromPending() {
3496 const ViewMsg_Navigate_Params
& params
= *pending_navigation_params_
.get();
3497 NavigationState
* navigation_state
= NULL
;
3499 // A navigation resulting from loading a javascript URL should not be treated
3500 // as a browser initiated event. Instead, we want it to look as if the page
3501 // initiated any load resulting from JS execution.
3502 if (!params
.url
.SchemeIs(kJavaScriptScheme
)) {
3503 navigation_state
= NavigationState::CreateBrowserInitiated(
3505 params
.pending_history_list_offset
,
3506 params
.should_clear_history_list
,
3508 navigation_state
->set_should_replace_current_entry(
3509 params
.should_replace_current_entry
);
3510 navigation_state
->set_transferred_request_child_id(
3511 params
.transferred_request_child_id
);
3512 navigation_state
->set_transferred_request_request_id(
3513 params
.transferred_request_request_id
);
3514 navigation_state
->set_allow_download(params
.allow_download
);
3515 navigation_state
->set_extra_headers(params
.extra_headers
);
3517 navigation_state
= NavigationState::CreateContentInitiated();
3519 return navigation_state
;
3522 void RenderViewImpl::ProcessViewLayoutFlags(const CommandLine
& command_line
) {
3523 bool enable_viewport
=
3524 command_line
.HasSwitch(switches::kEnableViewport
) ||
3525 command_line
.HasSwitch(switches::kEnableViewportMeta
);
3527 // If viewport tag is enabled, then the WebKit side will take care
3528 // of setting the fixed layout size and page scale limits.
3529 if (enable_viewport
)
3532 // When navigating to a new page, reset the page scale factor to be 1.0.
3533 webview()->setInitialPageScaleOverride(1.f
);
3535 float maxPageScaleFactor
=
3536 command_line
.HasSwitch(switches::kEnablePinch
) ? 4.f
: 1.f
;
3537 webview()->setPageScaleFactorLimits(1, maxPageScaleFactor
);
3540 // TODO(nasko): Remove this method once WebTestProxy in Blink is fixed.
3541 void RenderViewImpl::didStartProvisionalLoad(WebFrame
* frame
) {
3544 void RenderViewImpl::didReceiveServerRedirectForProvisionalLoad(
3546 if (frame
->parent())
3548 // Received a redirect on the main frame.
3549 WebDataSource
* data_source
= frame
->provisionalDataSource();
3551 // Should only be invoked when we have a data source.
3555 std::vector
<GURL
> redirects
;
3556 GetRedirectChain(data_source
, &redirects
);
3557 if (redirects
.size() >= 2) {
3558 Send(new ViewHostMsg_DidRedirectProvisionalLoad(routing_id_
, page_id_
,
3559 redirects
[redirects
.size() - 2], redirects
.back()));
3563 void RenderViewImpl::didFailProvisionalLoad(WebFrame
* frame
,
3564 const WebURLError
& error
) {
3565 // Notify the browser that we failed a provisional load with an error.
3567 // Note: It is important this notification occur before DidStopLoading so the
3568 // SSL manager can react to the provisional load failure before being
3569 // notified the load stopped.
3572 RenderViewObserver
, observers_
, DidFailProvisionalLoad(frame
, error
));
3575 void RenderViewImpl::didCommitProvisionalLoad(WebFrame
* frame
,
3576 bool is_new_navigation
) {
3577 DocumentState
* document_state
=
3578 DocumentState::FromDataSource(frame
->dataSource());
3579 NavigationState
* navigation_state
= document_state
->navigation_state();
3580 InternalDocumentStateData
* internal_data
=
3581 InternalDocumentStateData::FromDocumentState(document_state
);
3583 if (document_state
->commit_load_time().is_null())
3584 document_state
->set_commit_load_time(Time::Now());
3586 if (internal_data
->must_reset_scroll_and_scale_state()) {
3587 webview()->resetScrollAndScaleState();
3588 internal_data
->set_must_reset_scroll_and_scale_state(false);
3590 internal_data
->set_use_error_page(false);
3591 internal_data
->clear_referrer_policy();
3593 if (is_new_navigation
) {
3594 // When we perform a new navigation, we need to update the last committed
3595 // session history entry with state for the page we are leaving.
3596 UpdateSessionHistory(frame
);
3598 // We bump our Page ID to correspond with the new session history entry.
3599 page_id_
= next_page_id_
++;
3601 // Don't update history_page_ids_ (etc) for kSwappedOutURL, since
3602 // we don't want to forget the entry that was there, and since we will
3603 // never come back to kSwappedOutURL. Note that we have to call
3604 // UpdateSessionHistory and update page_id_ even in this case, so that
3605 // the current entry gets a state update and so that we don't send a
3606 // state update to the wrong entry when we swap back in.
3607 if (GetLoadingUrl(frame
) != GURL(kSwappedOutURL
)) {
3608 // Advance our offset in session history, applying the length limit.
3609 // There is now no forward history.
3610 history_list_offset_
++;
3611 if (history_list_offset_
>= kMaxSessionHistoryEntries
)
3612 history_list_offset_
= kMaxSessionHistoryEntries
- 1;
3613 history_list_length_
= history_list_offset_
+ 1;
3614 history_page_ids_
.resize(history_list_length_
, -1);
3615 history_page_ids_
[history_list_offset_
] = page_id_
;
3618 // Inspect the navigation_state on this frame to see if the navigation
3619 // corresponds to a session history navigation... Note: |frame| may or
3620 // may not be the toplevel frame, but for the case of capturing session
3621 // history, the first committed frame suffices. We keep track of whether
3622 // we've seen this commit before so that only capture session history once
3625 // Note that we need to check if the page ID changed. In the case of a
3626 // reload, the page ID doesn't change, and UpdateSessionHistory gets the
3627 // previous URL and the current page ID, which would be wrong.
3628 if (navigation_state
->pending_page_id() != -1 &&
3629 navigation_state
->pending_page_id() != page_id_
&&
3630 !navigation_state
->request_committed()) {
3631 // This is a successful session history navigation!
3632 UpdateSessionHistory(frame
);
3633 page_id_
= navigation_state
->pending_page_id();
3635 history_list_offset_
= navigation_state
->pending_history_list_offset();
3637 // If the history list is valid, our list of page IDs should be correct.
3638 DCHECK(history_list_length_
<= 0 ||
3639 history_list_offset_
< 0 ||
3640 history_list_offset_
>= history_list_length_
||
3641 history_page_ids_
[history_list_offset_
] == page_id_
);
3645 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
,
3646 DidCommitProvisionalLoad(frame
, is_new_navigation
));
3648 // Remember that we've already processed this request, so we don't update
3649 // the session history again. We do this regardless of whether this is
3650 // a session history navigation, because if we attempted a session history
3651 // navigation without valid HistoryItem state, WebCore will think it is a
3653 navigation_state
->set_request_committed(true);
3657 // Check whether we have new encoding name.
3658 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
3660 if (!frame
->parent()) { // Only for top frames.
3661 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
3662 if (render_thread_impl
) { // Can be NULL in tests.
3663 render_thread_impl
->histogram_customizer()->
3664 RenderViewNavigatedToHost(GURL(GetLoadingUrl(frame
)).host(),
3665 g_view_map
.Get().size());
3670 void RenderViewImpl::didClearWindowObject(WebFrame
* frame
) {
3671 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
,
3672 DidClearWindowObject(frame
));
3674 if (enabled_bindings_
& BINDINGS_POLICY_DOM_AUTOMATION
) {
3675 if (!dom_automation_controller_
)
3676 dom_automation_controller_
.reset(new DomAutomationController());
3677 dom_automation_controller_
->set_message_sender(
3678 static_cast<RenderView
*>(this));
3679 dom_automation_controller_
->set_routing_id(routing_id());
3680 dom_automation_controller_
->BindToJavascript(frame
,
3681 "domAutomationController");
3684 if (enabled_bindings_
& BINDINGS_POLICY_STATS_COLLECTION
)
3685 StatsCollectionController::Install(frame
);
3688 void RenderViewImpl::didCreateDocumentElement(WebFrame
* frame
) {
3689 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
,
3690 DidCreateDocumentElement(frame
));
3693 void RenderViewImpl::didReceiveTitle(WebFrame
* frame
, const WebString
& title
,
3694 WebTextDirection direction
) {
3695 UpdateTitle(frame
, title
, direction
);
3697 // Also check whether we have new encoding name.
3698 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
3701 void RenderViewImpl::didChangeIcon(WebFrame
* frame
,
3702 WebIconURL::Type icon_type
) {
3703 if (frame
->parent())
3706 if (!TouchEnabled() && icon_type
!= WebIconURL::TypeFavicon
)
3709 WebVector
<WebIconURL
> icon_urls
= frame
->iconURLs(icon_type
);
3710 std::vector
<FaviconURL
> urls
;
3711 for (size_t i
= 0; i
< icon_urls
.size(); i
++) {
3712 urls
.push_back(FaviconURL(icon_urls
[i
].iconURL(),
3713 ToFaviconType(icon_urls
[i
].iconType())));
3715 SendUpdateFaviconURL(urls
);
3718 void RenderViewImpl::didFinishDocumentLoad(WebFrame
* frame
) {
3719 WebDataSource
* ds
= frame
->dataSource();
3720 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3721 document_state
->set_finish_document_load_time(Time::Now());
3723 Send(new ViewHostMsg_DocumentLoadedInFrame(routing_id_
, frame
->identifier()));
3725 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
,
3726 DidFinishDocumentLoad(frame
));
3728 // Check whether we have new encoding name.
3729 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
3732 void RenderViewImpl::didHandleOnloadEvents(WebFrame
* frame
) {
3733 if (webview()->mainFrame() == frame
) {
3734 Send(new ViewHostMsg_DocumentOnLoadCompletedInMainFrame(routing_id_
,
3739 void RenderViewImpl::didFailLoad(WebFrame
* frame
, const WebURLError
& error
) {
3740 WebDataSource
* ds
= frame
->dataSource();
3744 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidFailLoad(frame
, error
));
3746 const WebURLRequest
& failed_request
= ds
->request();
3747 base::string16 error_description
;
3748 GetContentClient()->renderer()->GetNavigationErrorStrings(
3752 renderer_preferences_
.accept_languages
,
3754 &error_description
);
3755 Send(new ViewHostMsg_DidFailLoadWithError(routing_id_
,
3756 frame
->identifier(),
3757 failed_request
.url(),
3760 error_description
));
3763 void RenderViewImpl::didFinishLoad(WebFrame
* frame
) {
3764 WebDataSource
* ds
= frame
->dataSource();
3765 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3766 if (document_state
->finish_load_time().is_null()) {
3767 if (!frame
->parent()) {
3768 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
3769 TRACE_EVENT_SCOPE_PROCESS
);
3771 document_state
->set_finish_load_time(Time::Now());
3774 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidFinishLoad(frame
));
3776 // Don't send this message while the subframe is swapped out.
3777 // TODO(creis): This whole method should move to RenderFrame.
3778 RenderFrameImpl
* rf
= RenderFrameImpl::FindByWebFrame(frame
);
3779 if (rf
&& rf
->is_swapped_out())
3782 Send(new ViewHostMsg_DidFinishLoad(routing_id_
,
3783 frame
->identifier(),
3784 ds
->request().url(),
3788 void RenderViewImpl::didNavigateWithinPage(
3789 WebFrame
* frame
, bool is_new_navigation
) {
3790 // If this was a reference fragment navigation that we initiated, then we
3791 // could end up having a non-null pending navigation params. We just need to
3792 // update the ExtraData on the datasource so that others who read the
3793 // ExtraData will get the new NavigationState. Similarly, if we did not
3794 // initiate this navigation, then we need to take care to reset any pre-
3795 // existing navigation state to a content-initiated navigation state.
3796 // DidCreateDataSource conveniently takes care of this for us.
3797 didCreateDataSource(frame
, frame
->dataSource());
3799 DocumentState
* document_state
=
3800 DocumentState::FromDataSource(frame
->dataSource());
3801 NavigationState
* new_state
= document_state
->navigation_state();
3802 new_state
->set_was_within_same_page(true);
3804 didCommitProvisionalLoad(frame
, is_new_navigation
);
3807 void RenderViewImpl::didUpdateCurrentHistoryItem(WebFrame
* frame
) {
3808 StartNavStateSyncTimerIfNecessary();
3811 void RenderViewImpl::willSendRequest(WebFrame
* frame
,
3812 unsigned identifier
,
3813 WebURLRequest
& request
,
3814 const WebURLResponse
& redirect_response
) {
3818 void RenderViewImpl::didReceiveResponse(
3819 WebFrame
* frame
, unsigned identifier
, const WebURLResponse
& response
) {
3823 void RenderViewImpl::didFinishResourceLoad(
3824 WebFrame
* frame
, unsigned identifier
) {
3825 InternalDocumentStateData
* internal_data
=
3826 InternalDocumentStateData::FromDataSource(frame
->dataSource());
3827 if (!internal_data
->use_error_page())
3830 // Do not show error page when DevTools is attached.
3831 if (devtools_agent_
->IsAttached())
3834 // Display error page, if appropriate.
3835 int http_status_code
= internal_data
->http_status_code();
3836 if (http_status_code
== 404) {
3837 // On 404s, try a remote search page as a fallback.
3838 const GURL
& document_url
= frame
->document().url();
3840 const GURL
& error_page_url
=
3841 GetAlternateErrorPageURL(document_url
, HTTP_404
);
3842 if (error_page_url
.is_valid()) {
3843 WebURLError original_error
;
3844 original_error
.domain
= "http";
3845 original_error
.reason
= 404;
3846 original_error
.unreachableURL
= document_url
;
3848 internal_data
->set_alt_error_page_fetcher(
3849 new AltErrorPageResourceFetcher(
3850 error_page_url
, frame
, frame
->dataSource()->request(),
3852 base::Bind(&RenderViewImpl::AltErrorPageFinished
,
3853 base::Unretained(this))));
3858 std::string error_domain
;
3859 if (GetContentClient()->renderer()->HasErrorPage(
3860 http_status_code
, &error_domain
)) {
3862 error
.unreachableURL
= frame
->document().url();
3863 error
.domain
= WebString::fromUTF8(error_domain
);
3864 error
.reason
= http_status_code
;
3866 LoadNavigationErrorPage(
3867 frame
, frame
->dataSource()->request(), error
, std::string(), true);
3871 void RenderViewImpl::didLoadResourceFromMemoryCache(
3872 WebFrame
* frame
, const WebURLRequest
& request
,
3873 const WebURLResponse
& response
) {
3877 void RenderViewImpl::didDisplayInsecureContent(WebFrame
* frame
) {
3881 void RenderViewImpl::didRunInsecureContent(
3882 WebFrame
* frame
, const WebSecurityOrigin
& origin
, const WebURL
& target
) {
3886 void RenderViewImpl::didExhaustMemoryAvailableForScript(WebFrame
* frame
) {
3890 void RenderViewImpl::didCreateScriptContext(WebFrame
* frame
,
3891 v8::Handle
<v8::Context
> context
,
3892 int extension_group
,
3897 void RenderViewImpl::willReleaseScriptContext(WebFrame
* frame
,
3898 v8::Handle
<v8::Context
> context
,
3903 void RenderViewImpl::CheckPreferredSize() {
3904 // We don't always want to send the change messages over IPC, only if we've
3905 // been put in that mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
3907 if (!send_preferred_size_changes_
|| !webview())
3910 gfx::Size size
= webview()->contentsPreferredMinimumSize();
3912 // In the presence of zoom, these sizes are still reported as if unzoomed,
3913 // so we need to adjust.
3914 double zoom_factor
= ZoomLevelToZoomFactor(webview()->zoomLevel());
3915 size
.set_width(static_cast<int>(size
.width() * zoom_factor
));
3916 size
.set_height(static_cast<int>(size
.height() * zoom_factor
));
3918 if (size
== preferred_size_
)
3921 preferred_size_
= size
;
3922 Send(new ViewHostMsg_DidContentsPreferredSizeChange(routing_id_
,
3926 BrowserPluginManager
* RenderViewImpl::GetBrowserPluginManager() {
3927 if (!browser_plugin_manager_
.get())
3928 browser_plugin_manager_
= BrowserPluginManager::Create(this);
3929 return browser_plugin_manager_
.get();
3932 bool RenderViewImpl::InitializeMediaStreamClient() {
3933 if (media_stream_client_
)
3936 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
3939 #if defined(OS_ANDROID)
3940 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableWebRTC
))
3944 #if defined(ENABLE_WEBRTC)
3945 if (!media_stream_dispatcher_
)
3946 media_stream_dispatcher_
= new MediaStreamDispatcher(this);
3948 MediaStreamImpl
* media_stream_impl
= new MediaStreamImpl(
3950 media_stream_dispatcher_
,
3951 RenderThreadImpl::current()->GetMediaStreamDependencyFactory());
3952 media_stream_client_
= media_stream_impl
;
3953 web_user_media_client_
= media_stream_impl
;
3960 void RenderViewImpl::didChangeContentsSize(WebFrame
* frame
,
3961 const WebSize
& size
) {
3962 if (webview()->mainFrame() != frame
)
3964 WebView
* frameView
= frame
->view();
3968 bool has_horizontal_scrollbar
= frame
->hasHorizontalScrollbar();
3969 bool has_vertical_scrollbar
= frame
->hasVerticalScrollbar();
3971 if (has_horizontal_scrollbar
!= cached_has_main_frame_horizontal_scrollbar_
||
3972 has_vertical_scrollbar
!= cached_has_main_frame_vertical_scrollbar_
) {
3973 Send(new ViewHostMsg_DidChangeScrollbarsForMainFrame(
3974 routing_id_
, has_horizontal_scrollbar
, has_vertical_scrollbar
));
3976 cached_has_main_frame_horizontal_scrollbar_
= has_horizontal_scrollbar
;
3977 cached_has_main_frame_vertical_scrollbar_
= has_vertical_scrollbar
;
3981 void RenderViewImpl::UpdateScrollState(WebFrame
* frame
) {
3982 WebSize offset
= frame
->scrollOffset();
3983 WebSize minimum_offset
= frame
->minimumScrollOffset();
3984 WebSize maximum_offset
= frame
->maximumScrollOffset();
3986 bool is_pinned_to_left
= offset
.width
<= minimum_offset
.width
;
3987 bool is_pinned_to_right
= offset
.width
>= maximum_offset
.width
;
3989 if (is_pinned_to_left
!= cached_is_main_frame_pinned_to_left_
||
3990 is_pinned_to_right
!= cached_is_main_frame_pinned_to_right_
) {
3991 Send(new ViewHostMsg_DidChangeScrollOffsetPinningForMainFrame(
3992 routing_id_
, is_pinned_to_left
, is_pinned_to_right
));
3994 cached_is_main_frame_pinned_to_left_
= is_pinned_to_left
;
3995 cached_is_main_frame_pinned_to_right_
= is_pinned_to_right
;
3998 Send(new ViewHostMsg_DidChangeScrollOffset(routing_id_
));
4001 void RenderViewImpl::didChangeScrollOffset(WebFrame
* frame
) {
4002 StartNavStateSyncTimerIfNecessary();
4004 if (webview()->mainFrame() == frame
)
4005 UpdateScrollState(frame
);
4008 RenderViewObserver
, observers_
, DidChangeScrollOffset(frame
));
4011 void RenderViewImpl::willInsertBody(blink::WebFrame
* frame
) {
4015 void RenderViewImpl::didFirstVisuallyNonEmptyLayout(WebFrame
* frame
) {
4016 if (frame
!= webview()->mainFrame())
4019 InternalDocumentStateData
* data
=
4020 InternalDocumentStateData::FromDataSource(frame
->dataSource());
4021 data
->set_did_first_visually_non_empty_layout(true);
4023 #if defined(OS_ANDROID)
4024 // Update body background color if necessary.
4025 SkColor bg_color
= webwidget_
->backgroundColor();
4027 // If not initialized, default to white. Note that 0 is different from black
4028 // as black still has alpha 0xFF.
4030 bg_color
= SK_ColorWHITE
;
4032 if (bg_color
!= body_background_color_
) {
4033 body_background_color_
= bg_color
;
4034 Send(new ViewHostMsg_DidChangeBodyBackgroundColor(
4035 GetRoutingID(), bg_color
));
4040 void RenderViewImpl::SendFindReply(int request_id
,
4043 const WebRect
& selection_rect
,
4044 bool final_status_update
) {
4045 Send(new ViewHostMsg_Find_Reply(routing_id_
,
4050 final_status_update
));
4054 bool RenderViewImpl::ShouldUpdateSelectionTextFromContextMenuParams(
4055 const base::string16
& selection_text
,
4056 size_t selection_text_offset
,
4057 const gfx::Range
& selection_range
,
4058 const ContextMenuParams
& params
) {
4059 base::string16 trimmed_selection_text
;
4060 if (!selection_text
.empty() && !selection_range
.is_empty()) {
4061 const int start
= selection_range
.GetMin() - selection_text_offset
;
4062 const size_t length
= selection_range
.length();
4063 if (start
>= 0 && start
+ length
<= selection_text
.length()) {
4064 TrimWhitespace(selection_text
.substr(start
, length
), TRIM_ALL
,
4065 &trimmed_selection_text
);
4068 base::string16 trimmed_params_text
;
4069 TrimWhitespace(params
.selection_text
, TRIM_ALL
, &trimmed_params_text
);
4070 return trimmed_params_text
!= trimmed_selection_text
;
4073 void RenderViewImpl::reportFindInPageMatchCount(int request_id
,
4075 bool final_update
) {
4079 void RenderViewImpl::reportFindInPageSelection(int request_id
,
4080 int active_match_ordinal
,
4081 const WebRect
& selection_rect
) {
4085 void RenderViewImpl::requestStorageQuota(
4087 WebStorageQuotaType type
,
4088 unsigned long long requested_size
,
4089 WebStorageQuotaCallbacks
* callbacks
) {
4093 bool RenderViewImpl::willCheckAndDispatchMessageEvent(
4094 blink::WebFrame
* sourceFrame
,
4095 blink::WebFrame
* targetFrame
,
4096 blink::WebSecurityOrigin target_origin
,
4097 blink::WebDOMMessageEvent event
) {
4098 if (!is_swapped_out_
)
4101 ViewMsg_PostMessage_Params params
;
4102 params
.data
= event
.data().toString();
4103 params
.source_origin
= event
.origin();
4104 if (!target_origin
.isNull())
4105 params
.target_origin
= target_origin
.toString();
4107 blink::WebMessagePortChannelArray channels
= event
.releaseChannels();
4108 if (!channels
.isEmpty()) {
4109 std::vector
<int> message_port_ids(channels
.size());
4110 // Extract the port IDs from the channel array.
4111 for (size_t i
= 0; i
< channels
.size(); ++i
) {
4112 WebMessagePortChannelImpl
* webchannel
=
4113 static_cast<WebMessagePortChannelImpl
*>(channels
[i
]);
4114 message_port_ids
[i
] = webchannel
->message_port_id();
4115 webchannel
->QueueMessages();
4116 DCHECK_NE(message_port_ids
[i
], MSG_ROUTING_NONE
);
4118 params
.message_port_ids
= message_port_ids
;
4121 // Include the routing ID for the source frame (if one exists), which the
4122 // browser process will translate into the routing ID for the equivalent
4123 // frame in the target process.
4124 params
.source_routing_id
= MSG_ROUTING_NONE
;
4126 RenderViewImpl
* source_view
= FromWebView(sourceFrame
->view());
4128 params
.source_routing_id
= source_view
->routing_id();
4131 Send(new ViewHostMsg_RouteMessageEvent(routing_id_
, params
));
4135 void RenderViewImpl::willOpenSocketStream(
4136 WebSocketStreamHandle
* handle
) {
4140 void RenderViewImpl::willStartUsingPeerConnectionHandler(
4141 blink::WebFrame
* frame
, blink::WebRTCPeerConnectionHandler
* handler
) {
4145 blink::WebString
RenderViewImpl::acceptLanguages() {
4146 return WebString::fromUTF8(renderer_preferences_
.accept_languages
);
4149 blink::WebString
RenderViewImpl::userAgentOverride(
4150 blink::WebFrame
* frame
,
4151 const blink::WebURL
& url
) {
4153 return blink::WebString();
4156 WebString
RenderViewImpl::doNotTrackValue(WebFrame
* frame
) {
4158 return blink::WebString();
4161 bool RenderViewImpl::allowWebGL(WebFrame
* frame
, bool default_value
) {
4166 void RenderViewImpl::didLoseWebGLContext(
4167 blink::WebFrame
* frame
,
4168 int arb_robustness_status_code
) {
4172 // blink::WebPageSerializerClient implementation ------------------------------
4174 void RenderViewImpl::didSerializeDataForFrame(
4175 const WebURL
& frame_url
,
4176 const WebCString
& data
,
4177 WebPageSerializerClient::PageSerializationStatus status
) {
4178 Send(new ViewHostMsg_SendSerializedHtmlData(
4182 static_cast<int32
>(status
)));
4185 // RenderView implementation ---------------------------------------------------
4187 bool RenderViewImpl::Send(IPC::Message
* message
) {
4188 return RenderWidget::Send(message
);
4191 RenderFrame
* RenderViewImpl::GetMainRenderFrame() {
4192 return main_render_frame_
.get();
4195 int RenderViewImpl::GetRoutingID() const {
4199 int RenderViewImpl::GetPageId() const {
4203 gfx::Size
RenderViewImpl::GetSize() const {
4207 WebPreferences
& RenderViewImpl::GetWebkitPreferences() {
4208 return webkit_preferences_
;
4211 void RenderViewImpl::SetWebkitPreferences(const WebPreferences
& preferences
) {
4212 OnUpdateWebPreferences(preferences
);
4215 blink::WebView
* RenderViewImpl::GetWebView() {
4219 blink::WebNode
RenderViewImpl::GetFocusedNode() const {
4222 WebFrame
* focused_frame
= webview()->focusedFrame();
4223 if (focused_frame
) {
4224 WebDocument doc
= focused_frame
->document();
4226 return doc
.focusedNode();
4232 blink::WebNode
RenderViewImpl::GetContextMenuNode() const {
4233 return context_menu_node_
;
4236 bool RenderViewImpl::IsEditableNode(const WebNode
& node
) const {
4240 if (node
.isContentEditable())
4243 if (node
.isElementNode()) {
4244 const WebElement
& element
= node
.toConst
<WebElement
>();
4245 if (element
.isTextFormControlElement())
4248 // Also return true if it has an ARIA role of 'textbox'.
4249 for (unsigned i
= 0; i
< element
.attributeCount(); ++i
) {
4250 if (LowerCaseEqualsASCII(element
.attributeLocalName(i
), "role")) {
4251 if (LowerCaseEqualsASCII(element
.attributeValue(i
), "textbox"))
4261 void RenderViewImpl::EvaluateScript(const base::string16
& frame_xpath
,
4262 const base::string16
& jscript
,
4264 bool notify_result
) {
4265 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
4266 v8::Handle
<v8::Value
> result
;
4267 WebFrame
* web_frame
= GetChildFrame(frame_xpath
);
4269 result
= web_frame
->executeScriptAndReturnValue(WebScriptSource(jscript
));
4270 if (notify_result
) {
4271 base::ListValue list
;
4272 if (!result
.IsEmpty() && web_frame
) {
4273 v8::Local
<v8::Context
> context
= web_frame
->mainWorldScriptContext();
4274 v8::Context::Scope
context_scope(context
);
4275 V8ValueConverterImpl converter
;
4276 converter
.SetDateAllowed(true);
4277 converter
.SetRegExpAllowed(true);
4278 base::Value
* result_value
= converter
.FromV8Value(result
, context
);
4279 list
.Set(0, result_value
? result_value
: base::Value::CreateNullValue());
4281 list
.Set(0, base::Value::CreateNullValue());
4283 Send(new ViewHostMsg_ScriptEvalResponse(routing_id_
, id
, list
));
4287 bool RenderViewImpl::ShouldDisplayScrollbars(int width
, int height
) const {
4288 return (!send_preferred_size_changes_
||
4289 (disable_scrollbars_size_limit_
.width() <= width
||
4290 disable_scrollbars_size_limit_
.height() <= height
));
4293 int RenderViewImpl::GetEnabledBindings() const {
4294 return enabled_bindings_
;
4297 bool RenderViewImpl::GetContentStateImmediately() const {
4298 return send_content_state_immediately_
;
4301 float RenderViewImpl::GetFilteredTimePerFrame() const {
4302 return filtered_time_per_frame();
4305 int RenderViewImpl::ShowContextMenu(ContextMenuClient
* client
,
4306 const ContextMenuParams
& params
) {
4307 DCHECK(client
); // A null client means "internal" when we issue callbacks.
4308 ContextMenuParams
our_params(params
);
4309 our_params
.custom_context
.request_id
= pending_context_menus_
.Add(client
);
4310 Send(new ViewHostMsg_ContextMenu(routing_id_
, our_params
));
4311 return our_params
.custom_context
.request_id
;
4314 void RenderViewImpl::CancelContextMenu(int request_id
) {
4315 DCHECK(pending_context_menus_
.Lookup(request_id
));
4316 pending_context_menus_
.Remove(request_id
);
4319 blink::WebPageVisibilityState
RenderViewImpl::GetVisibilityState() const {
4320 return visibilityState();
4323 void RenderViewImpl::RunModalAlertDialog(blink::WebFrame
* frame
,
4324 const blink::WebString
& message
) {
4325 return runModalAlertDialog(frame
, message
);
4328 void RenderViewImpl::DidStartLoading() {
4332 void RenderViewImpl::DidStopLoading() {
4336 void RenderViewImpl::DidPlay(blink::WebMediaPlayer
* player
) {
4337 Send(new ViewHostMsg_MediaNotification(routing_id_
,
4338 reinterpret_cast<int64
>(player
),
4344 void RenderViewImpl::DidPause(blink::WebMediaPlayer
* player
) {
4345 Send(new ViewHostMsg_MediaNotification(routing_id_
,
4346 reinterpret_cast<int64
>(player
),
4352 void RenderViewImpl::PlayerGone(blink::WebMediaPlayer
* player
) {
4356 void RenderViewImpl::SyncNavigationState() {
4360 const WebHistoryItem
& item
= webview()->mainFrame()->currentHistoryItem();
4361 SendUpdateState(item
);
4364 void RenderViewImpl::SyncSelectionIfRequired() {
4365 WebFrame
* frame
= webview()->focusedFrame();
4369 base::string16 text
;
4372 #if defined(ENABLE_PLUGINS)
4373 if (focused_pepper_plugin_
) {
4374 focused_pepper_plugin_
->GetSurroundingText(&text
, &range
);
4375 offset
= 0; // Pepper API does not support offset reporting.
4376 // TODO(kinaba): cut as needed.
4380 size_t location
, length
;
4381 if (!webview()->caretOrSelectionRange(&location
, &length
))
4384 range
= gfx::Range(location
, location
+ length
);
4386 if (webview()->textInputInfo().type
!= blink::WebTextInputTypeNone
) {
4387 // If current focused element is editable, we will send 100 more chars
4388 // before and after selection. It is for input method surrounding text
4390 if (location
> kExtraCharsBeforeAndAfterSelection
)
4391 offset
= location
- kExtraCharsBeforeAndAfterSelection
;
4394 length
= location
+ length
- offset
+ kExtraCharsBeforeAndAfterSelection
;
4395 WebRange webrange
= WebRange::fromDocumentRange(frame
, offset
, length
);
4396 if (!webrange
.isNull())
4397 text
= WebRange::fromDocumentRange(frame
, offset
, length
).toPlainText();
4400 text
= frame
->selectionAsText();
4401 // http://crbug.com/101435
4402 // In some case, frame->selectionAsText() returned text's length is not
4403 // equal to the length returned from webview()->caretOrSelectionRange().
4404 // So we have to set the range according to text.length().
4405 range
.set_end(range
.start() + text
.length());
4409 // Sometimes we get repeated didChangeSelection calls from webkit when
4410 // the selection hasn't actually changed. We don't want to report these
4411 // because it will cause us to continually claim the X clipboard.
4412 if (selection_text_offset_
!= offset
||
4413 selection_range_
!= range
||
4414 selection_text_
!= text
) {
4415 selection_text_
= text
;
4416 selection_text_offset_
= offset
;
4417 selection_range_
= range
;
4418 Send(new ViewHostMsg_SelectionChanged(routing_id_
, text
, offset
, range
));
4420 UpdateSelectionBounds();
4423 GURL
RenderViewImpl::GetAlternateErrorPageURL(const GURL
& failed_url
,
4424 ErrorPageType error_type
) {
4425 if (failed_url
.SchemeIsSecure()) {
4426 // If the URL that failed was secure, then the embedding web page was not
4427 // expecting a network attacker to be able to manipulate its contents. As
4428 // we fetch alternate error pages over HTTP, we would be allowing a network
4429 // attacker to manipulate the contents of the response if we tried to use
4430 // the link doctor here.
4434 // Grab the base URL from the browser process.
4435 if (!alternate_error_page_url_
.is_valid())
4438 // Strip query params from the failed URL.
4439 GURL::Replacements remove_params
;
4440 remove_params
.ClearUsername();
4441 remove_params
.ClearPassword();
4442 remove_params
.ClearQuery();
4443 remove_params
.ClearRef();
4444 const GURL url_to_send
= failed_url
.ReplaceComponents(remove_params
);
4445 // TODO(yuusuke): change to net::FormatUrl when link doctor
4446 // becomes unicode-capable.
4447 std::string spec_to_send
= url_to_send
.spec();
4448 // Notify link doctor of the url truncation by sending of "?" at the end.
4449 if (failed_url
.has_query())
4450 spec_to_send
.append("?");
4452 // Construct the query params to send to link doctor.
4453 std::string
params(alternate_error_page_url_
.query());
4454 params
.append("&url=");
4455 params
.append(net::EscapeQueryParamValue(spec_to_send
, true));
4456 params
.append("&sourceid=chrome");
4457 params
.append("&error=");
4458 switch (error_type
) {
4460 params
.append("dnserror");
4464 params
.append("http404");
4467 case CONNECTION_ERROR
:
4468 params
.append("connectionfailure");
4472 NOTREACHED() << "unknown ErrorPageType";
4475 // OK, build the final url to return.
4476 GURL::Replacements link_doctor_params
;
4477 link_doctor_params
.SetQueryStr(params
);
4478 GURL url
= alternate_error_page_url_
.ReplaceComponents(link_doctor_params
);
4482 GURL
RenderViewImpl::GetLoadingUrl(blink::WebFrame
* frame
) const {
4483 WebDataSource
* ds
= frame
->dataSource();
4484 if (ds
->hasUnreachableURL())
4485 return ds
->unreachableURL();
4487 const WebURLRequest
& request
= ds
->request();
4488 return request
.url();
4491 blink::WebPlugin
* RenderViewImpl::GetWebPluginFromPluginDocument() {
4492 return webview()->mainFrame()->document().to
<WebPluginDocument
>().plugin();
4495 void RenderViewImpl::OnFind(int request_id
,
4496 const base::string16
& search_text
,
4497 const WebFindOptions
& options
) {
4498 WebFrame
* main_frame
= webview()->mainFrame();
4500 // Check if the plugin still exists in the document.
4501 if (main_frame
->document().isPluginDocument() &&
4502 GetWebPluginFromPluginDocument()) {
4503 if (options
.findNext
) {
4504 // Just navigate back/forward.
4505 GetWebPluginFromPluginDocument()->selectFindResult(options
.forward
);
4507 if (!GetWebPluginFromPluginDocument()->startFind(
4508 search_text
, options
.matchCase
, request_id
)) {
4509 // Send "no results".
4510 SendFindReply(request_id
, 0, 0, gfx::Rect(), true);
4516 WebFrame
* frame_after_main
= main_frame
->traverseNext(true);
4517 WebFrame
* focused_frame
= webview()->focusedFrame();
4518 WebFrame
* search_frame
= focused_frame
; // start searching focused frame.
4520 bool multi_frame
= (frame_after_main
!= main_frame
);
4522 // If we have multiple frames, we don't want to wrap the search within the
4523 // frame, so we check here if we only have main_frame in the chain.
4524 bool wrap_within_frame
= !multi_frame
;
4526 WebRect selection_rect
;
4527 bool result
= false;
4529 // If something is selected when we start searching it means we cannot just
4530 // increment the current match ordinal; we need to re-generate it.
4531 WebRange current_selection
= focused_frame
->selectionRange();
4534 result
= search_frame
->find(
4535 request_id
, search_text
, options
, wrap_within_frame
, &selection_rect
);
4538 // don't leave text selected as you move to the next frame.
4539 search_frame
->executeCommand(WebString::fromUTF8("Unselect"),
4542 // Find the next frame, but skip the invisible ones.
4544 // What is the next frame to search? (we might be going backwards). Note
4545 // that we specify wrap=true so that search_frame never becomes NULL.
4546 search_frame
= options
.forward
?
4547 search_frame
->traverseNext(true) :
4548 search_frame
->traversePrevious(true);
4549 } while (!search_frame
->hasVisibleContent() &&
4550 search_frame
!= focused_frame
);
4552 // Make sure selection doesn't affect the search operation in new frame.
4553 search_frame
->executeCommand(WebString::fromUTF8("Unselect"),
4556 // If we have multiple frames and we have wrapped back around to the
4557 // focused frame, we need to search it once more allowing wrap within
4558 // the frame, otherwise it will report 'no match' if the focused frame has
4559 // reported matches, but no frames after the focused_frame contain a
4560 // match for the search word(s).
4561 if (multi_frame
&& search_frame
== focused_frame
) {
4562 result
= search_frame
->find(
4563 request_id
, search_text
, options
, true, // Force wrapping.
4568 webview()->setFocusedFrame(search_frame
);
4569 } while (!result
&& search_frame
!= focused_frame
);
4571 if (options
.findNext
&& current_selection
.isNull()) {
4572 // Force the main_frame to report the actual count.
4573 main_frame
->increaseMatchCount(0, request_id
);
4575 // If nothing is found, set result to "0 of 0", otherwise, set it to
4576 // "-1 of 1" to indicate that we found at least one item, but we don't know
4577 // yet what is active.
4578 int ordinal
= result
? -1 : 0; // -1 here means, we might know more later.
4579 int match_count
= result
? 1 : 0; // 1 here means possibly more coming.
4581 // If we find no matches then this will be our last status update.
4582 // Otherwise the scoping effort will send more results.
4583 bool final_status_update
= !result
;
4585 SendFindReply(request_id
, match_count
, ordinal
, selection_rect
,
4586 final_status_update
);
4588 // Scoping effort begins, starting with the mainframe.
4589 search_frame
= main_frame
;
4591 main_frame
->resetMatchCount();
4594 // Cancel all old scoping requests before starting a new one.
4595 search_frame
->cancelPendingScopingEffort();
4597 // We don't start another scoping effort unless at least one match has
4600 // Start new scoping request. If the scoping function determines that it
4601 // needs to scope, it will defer until later.
4602 search_frame
->scopeStringMatches(request_id
,
4605 true); // reset the tickmarks
4608 // Iterate to the next frame. The frame will not necessarily scope, for
4609 // example if it is not visible.
4610 search_frame
= search_frame
->traverseNext(true);
4611 } while (search_frame
!= main_frame
);
4615 void RenderViewImpl::OnStopFinding(StopFindAction action
) {
4616 WebView
* view
= webview();
4620 WebDocument doc
= view
->mainFrame()->document();
4621 if (doc
.isPluginDocument() && GetWebPluginFromPluginDocument()) {
4622 GetWebPluginFromPluginDocument()->stopFind();
4626 bool clear_selection
= action
== STOP_FIND_ACTION_CLEAR_SELECTION
;
4627 if (clear_selection
) {
4628 view
->focusedFrame()->executeCommand(WebString::fromUTF8("Unselect"),
4632 WebFrame
* frame
= view
->mainFrame();
4634 frame
->stopFinding(clear_selection
);
4635 frame
= frame
->traverseNext(false);
4638 if (action
== STOP_FIND_ACTION_ACTIVATE_SELECTION
) {
4639 WebFrame
* focused_frame
= view
->focusedFrame();
4640 if (focused_frame
) {
4641 WebDocument doc
= focused_frame
->document();
4642 if (!doc
.isNull()) {
4643 WebNode node
= doc
.focusedNode();
4645 node
.simulateClick();
4651 #if defined(OS_ANDROID)
4652 void RenderViewImpl::OnActivateNearestFindResult(int request_id
,
4657 WebFrame
* main_frame
= webview()->mainFrame();
4658 WebRect selection_rect
;
4659 int ordinal
= main_frame
->selectNearestFindMatch(WebFloatPoint(x
, y
),
4661 if (ordinal
== -1) {
4662 // Something went wrong, so send a no-op reply (force the main_frame to
4663 // report the current match count) in case the host is waiting for a
4664 // response due to rate-limiting).
4665 main_frame
->increaseMatchCount(0, request_id
);
4669 SendFindReply(request_id
,
4670 -1 /* number_of_matches */,
4673 true /* final_update */);
4676 void RenderViewImpl::OnFindMatchRects(int current_version
) {
4680 WebFrame
* main_frame
= webview()->mainFrame();
4681 std::vector
<gfx::RectF
> match_rects
;
4683 int rects_version
= main_frame
->findMatchMarkersVersion();
4684 if (current_version
!= rects_version
) {
4685 WebVector
<WebFloatRect
> web_match_rects
;
4686 main_frame
->findMatchRects(web_match_rects
);
4687 match_rects
.reserve(web_match_rects
.size());
4688 for (size_t i
= 0; i
< web_match_rects
.size(); ++i
)
4689 match_rects
.push_back(gfx::RectF(web_match_rects
[i
]));
4692 gfx::RectF active_rect
= main_frame
->activeFindMatchRect();
4693 Send(new ViewHostMsg_FindMatchRects_Reply(routing_id_
,
4700 void RenderViewImpl::OnZoom(PageZoom zoom
) {
4701 if (!webview()) // Not sure if this can happen, but no harm in being safe.
4704 webview()->hidePopups();
4706 double old_zoom_level
= webview()->zoomLevel();
4708 if (zoom
== PAGE_ZOOM_RESET
) {
4710 } else if (static_cast<int>(old_zoom_level
) == old_zoom_level
) {
4711 // Previous zoom level is a whole number, so just increment/decrement.
4712 zoom_level
= old_zoom_level
+ zoom
;
4714 // Either the user hit the zoom factor limit and thus the zoom level is now
4715 // not a whole number, or a plugin changed it to a custom value. We want
4716 // to go to the next whole number so that the user can always get back to
4717 // 100% with the keyboard/menu.
4718 if ((old_zoom_level
> 1 && zoom
> 0) ||
4719 (old_zoom_level
< 1 && zoom
< 0)) {
4720 zoom_level
= static_cast<int>(old_zoom_level
+ zoom
);
4722 // We're going towards 100%, so first go to the next whole number.
4723 zoom_level
= static_cast<int>(old_zoom_level
);
4726 webview()->setZoomLevel(zoom_level
);
4730 void RenderViewImpl::OnZoomFactor(PageZoom zoom
, int zoom_center_x
,
4731 int zoom_center_y
) {
4732 ZoomFactorHelper(zoom
, zoom_center_x
, zoom_center_y
,
4733 kScalingIncrementForGesture
);
4736 void RenderViewImpl::ZoomFactorHelper(PageZoom zoom
,
4739 float scaling_increment
) {
4740 if (!webview()) // Not sure if this can happen, but no harm in being safe.
4743 double old_page_scale_factor
= webview()->pageScaleFactor();
4744 double page_scale_factor
;
4745 if (zoom
== PAGE_ZOOM_RESET
) {
4746 page_scale_factor
= 1.0;
4748 page_scale_factor
= old_page_scale_factor
+
4749 (zoom
> 0 ? scaling_increment
: -scaling_increment
);
4751 if (page_scale_factor
> 0) {
4752 webview()->setPageScaleFactor(page_scale_factor
,
4753 WebPoint(zoom_center_x
, zoom_center_y
));
4757 void RenderViewImpl::OnSetZoomLevel(double zoom_level
) {
4758 webview()->hidePopups();
4759 webview()->setZoomLevel(zoom_level
);
4763 void RenderViewImpl::OnSetZoomLevelForLoadingURL(const GURL
& url
,
4764 double zoom_level
) {
4765 #if !defined(OS_ANDROID)
4766 // On Android, page zoom isn't used, and in case of WebView, text zoom is used
4767 // for legacy WebView text scaling emulation. Thus, the code that resets
4768 // the zoom level from this map will be effectively resetting text zoom level.
4769 host_zoom_levels_
[url
] = zoom_level
;
4773 void RenderViewImpl::OnSetPageEncoding(const std::string
& encoding_name
) {
4774 webview()->setPageEncoding(WebString::fromUTF8(encoding_name
));
4777 void RenderViewImpl::OnResetPageEncodingToDefault() {
4778 WebString no_encoding
;
4779 webview()->setPageEncoding(no_encoding
);
4782 WebFrame
* RenderViewImpl::GetChildFrame(const base::string16
& xpath
) const {
4784 return webview()->mainFrame();
4786 // xpath string can represent a frame deep down the tree (across multiple
4788 // Example, /html/body/table/tbody/tr/td/iframe\n/frameset/frame[0]
4789 // should break into 2 xpaths
4790 // /html/body/table/tbody/tr/td/iframe & /frameset/frame[0]
4791 std::vector
<base::string16
> xpaths
;
4792 base::SplitString(xpath
, '\n', &xpaths
);
4794 WebFrame
* frame
= webview()->mainFrame();
4795 for (std::vector
<base::string16
>::const_iterator i
= xpaths
.begin();
4796 frame
&& i
!= xpaths
.end(); ++i
) {
4797 frame
= frame
->findChildByExpression(*i
);
4803 void RenderViewImpl::OnScriptEvalRequest(const base::string16
& frame_xpath
,
4804 const base::string16
& jscript
,
4806 bool notify_result
) {
4807 TRACE_EVENT_INSTANT0("test_tracing", "OnScriptEvalRequest",
4808 TRACE_EVENT_SCOPE_THREAD
);
4809 EvaluateScript(frame_xpath
, jscript
, id
, notify_result
);
4812 void RenderViewImpl::OnPostMessageEvent(
4813 const ViewMsg_PostMessage_Params
& params
) {
4814 // TODO(nasko): Support sending to subframes.
4815 WebFrame
* frame
= webview()->mainFrame();
4817 // Find the source frame if it exists.
4818 WebFrame
* source_frame
= NULL
;
4819 if (params
.source_routing_id
!= MSG_ROUTING_NONE
) {
4820 RenderViewImpl
* source_view
= FromRoutingID(params
.source_routing_id
);
4822 source_frame
= source_view
->webview()->mainFrame();
4825 // If the message contained MessagePorts, create the corresponding endpoints.
4826 DCHECK_EQ(params
.message_port_ids
.size(), params
.new_routing_ids
.size());
4827 blink::WebMessagePortChannelArray
channels(params
.message_port_ids
.size());
4829 i
< params
.message_port_ids
.size() && i
< params
.new_routing_ids
.size();
4832 new WebMessagePortChannelImpl(params
.new_routing_ids
[i
],
4833 params
.message_port_ids
[i
],
4834 base::MessageLoopProxy::current().get());
4837 // Create an event with the message. The final parameter to initMessageEvent
4838 // is the last event ID, which is not used with postMessage.
4839 WebDOMEvent event
= frame
->document().createEvent("MessageEvent");
4840 WebDOMMessageEvent msg_event
= event
.to
<WebDOMMessageEvent
>();
4841 msg_event
.initMessageEvent("message",
4842 // |canBubble| and |cancellable| are always false
4844 WebSerializedScriptValue::fromString(params
.data
),
4845 params
.source_origin
, source_frame
, "", channels
);
4847 // We must pass in the target_origin to do the security check on this side,
4848 // since it may have changed since the original postMessage call was made.
4849 WebSecurityOrigin target_origin
;
4850 if (!params
.target_origin
.empty()) {
4852 WebSecurityOrigin::createFromString(WebString(params
.target_origin
));
4854 frame
->dispatchMessageEventWithOriginCheck(target_origin
, msg_event
);
4857 void RenderViewImpl::OnCSSInsertRequest(const base::string16
& frame_xpath
,
4858 const std::string
& css
) {
4859 WebFrame
* frame
= GetChildFrame(frame_xpath
);
4863 frame
->document().insertUserStyleSheet(
4864 WebString::fromUTF8(css
),
4865 WebDocument::UserStyleAuthorLevel
);
4868 void RenderViewImpl::OnAllowBindings(int enabled_bindings_flags
) {
4869 if ((enabled_bindings_flags
& BINDINGS_POLICY_WEB_UI
) &&
4870 !(enabled_bindings_
& BINDINGS_POLICY_WEB_UI
)) {
4871 // WebUI uses <dialog> which is not yet enabled by default in Chrome.
4872 WebRuntimeFeatures::enableDialogElement(true);
4874 RenderThread::Get()->RegisterExtension(WebUIExtension::Get());
4875 new WebUIExtensionData(this);
4878 enabled_bindings_
|= enabled_bindings_flags
;
4880 // Keep track of the total bindings accumulated in this process.
4881 RenderProcess::current()->AddBindings(enabled_bindings_flags
);
4884 void RenderViewImpl::OnDragTargetDragEnter(const DropData
& drop_data
,
4885 const gfx::Point
& client_point
,
4886 const gfx::Point
& screen_point
,
4887 WebDragOperationsMask ops
,
4888 int key_modifiers
) {
4889 WebDragOperation operation
= webview()->dragTargetDragEnter(
4890 DropDataToWebDragData(drop_data
),
4896 Send(new DragHostMsg_UpdateDragCursor(routing_id_
, operation
));
4899 void RenderViewImpl::OnDragTargetDragOver(const gfx::Point
& client_point
,
4900 const gfx::Point
& screen_point
,
4901 WebDragOperationsMask ops
,
4902 int key_modifiers
) {
4903 WebDragOperation operation
= webview()->dragTargetDragOver(
4909 Send(new DragHostMsg_UpdateDragCursor(routing_id_
, operation
));
4912 void RenderViewImpl::OnDragTargetDragLeave() {
4913 webview()->dragTargetDragLeave();
4916 void RenderViewImpl::OnDragTargetDrop(const gfx::Point
& client_point
,
4917 const gfx::Point
& screen_point
,
4918 int key_modifiers
) {
4919 webview()->dragTargetDrop(client_point
, screen_point
, key_modifiers
);
4921 Send(new DragHostMsg_TargetDrop_ACK(routing_id_
));
4924 void RenderViewImpl::OnDragSourceEndedOrMoved(const gfx::Point
& client_point
,
4925 const gfx::Point
& screen_point
,
4927 WebDragOperation op
) {
4929 webview()->dragSourceEndedAt(client_point
, screen_point
, op
);
4931 webview()->dragSourceMovedTo(client_point
, screen_point
, op
);
4935 void RenderViewImpl::OnDragSourceSystemDragEnded() {
4936 webview()->dragSourceSystemDragEnded();
4939 void RenderViewImpl::OnUpdateWebPreferences(const WebPreferences
& prefs
) {
4940 webkit_preferences_
= prefs
;
4941 ApplyWebPreferences(webkit_preferences_
, webview());
4944 void RenderViewImpl::OnUpdateTimezone() {
4946 NotifyTimezoneChange(webview()->mainFrame());
4949 void RenderViewImpl::OnSetAltErrorPageURL(const GURL
& url
) {
4950 alternate_error_page_url_
= url
;
4953 void RenderViewImpl::OnCustomContextMenuAction(
4954 const CustomContextMenuContext
& custom_context
,
4956 if (custom_context
.request_id
) {
4957 // External context menu request, look in our map.
4958 ContextMenuClient
* client
=
4959 pending_context_menus_
.Lookup(custom_context
.request_id
);
4961 client
->OnMenuAction(custom_context
.request_id
, action
);
4963 // Internal request, forward to WebKit.
4964 webview()->performCustomContextMenuAction(action
);
4968 void RenderViewImpl::OnEnumerateDirectoryResponse(
4970 const std::vector
<base::FilePath
>& paths
) {
4971 if (!enumeration_completions_
[id
])
4974 WebVector
<WebString
> ws_file_names(paths
.size());
4975 for (size_t i
= 0; i
< paths
.size(); ++i
)
4976 ws_file_names
[i
] = paths
[i
].AsUTF16Unsafe();
4978 enumeration_completions_
[id
]->didChooseFile(ws_file_names
);
4979 enumeration_completions_
.erase(id
);
4982 void RenderViewImpl::OnFileChooserResponse(
4983 const std::vector
<ui::SelectedFileInfo
>& files
) {
4984 // This could happen if we navigated to a different page before the user
4985 // closed the chooser.
4986 if (file_chooser_completions_
.empty())
4989 // Convert Chrome's SelectedFileInfo list to WebKit's.
4990 WebVector
<WebFileChooserCompletion::SelectedFileInfo
> selected_files(
4992 for (size_t i
= 0; i
< files
.size(); ++i
) {
4993 WebFileChooserCompletion::SelectedFileInfo selected_file
;
4994 selected_file
.path
= files
[i
].local_path
.AsUTF16Unsafe();
4995 selected_file
.displayName
=
4996 base::FilePath(files
[i
].display_name
).AsUTF16Unsafe();
4997 selected_files
[i
] = selected_file
;
5000 if (file_chooser_completions_
.front()->completion
)
5001 file_chooser_completions_
.front()->completion
->didChooseFile(
5003 file_chooser_completions_
.pop_front();
5005 // If there are more pending file chooser requests, schedule one now.
5006 if (!file_chooser_completions_
.empty()) {
5007 Send(new ViewHostMsg_RunFileChooser(routing_id_
,
5008 file_chooser_completions_
.front()->params
));
5012 void RenderViewImpl::OnEnableAutoResize(const gfx::Size
& min_size
,
5013 const gfx::Size
& max_size
) {
5014 DCHECK(disable_scrollbars_size_limit_
.IsEmpty());
5017 auto_resize_mode_
= true;
5018 webview()->enableAutoResizeMode(min_size
, max_size
);
5021 void RenderViewImpl::OnDisableAutoResize(const gfx::Size
& new_size
) {
5022 DCHECK(disable_scrollbars_size_limit_
.IsEmpty());
5025 auto_resize_mode_
= false;
5026 webview()->disableAutoResizeMode();
5028 if (!new_size
.IsEmpty()) {
5030 physical_backing_size_
,
5031 overdraw_bottom_height_
,
5038 void RenderViewImpl::OnEnablePreferredSizeChangedMode() {
5039 if (send_preferred_size_changes_
)
5041 send_preferred_size_changes_
= true;
5043 // Start off with an initial preferred size notification (in case
5044 // |didUpdateLayout| was already called).
5048 void RenderViewImpl::OnDisableScrollbarsForSmallWindows(
5049 const gfx::Size
& disable_scrollbar_size_limit
) {
5050 disable_scrollbars_size_limit_
= disable_scrollbar_size_limit
;
5053 void RenderViewImpl::OnSetRendererPrefs(
5054 const RendererPreferences
& renderer_prefs
) {
5055 double old_zoom_level
= renderer_preferences_
.default_zoom_level
;
5056 renderer_preferences_
= renderer_prefs
;
5057 UpdateFontRenderingFromRendererPrefs();
5059 #if defined(USE_DEFAULT_RENDER_THEME) || defined(TOOLKIT_GTK)
5060 if (renderer_prefs
.use_custom_colors
) {
5061 WebColorName name
= blink::WebColorWebkitFocusRingColor
;
5062 blink::setNamedColors(&name
, &renderer_prefs
.focus_ring_color
, 1);
5063 blink::setCaretBlinkInterval(renderer_prefs
.caret_blink_interval
);
5064 #if defined(TOOLKIT_GTK)
5065 ui::NativeTheme::instance()->SetScrollbarColors(
5066 renderer_prefs
.thumb_inactive_color
,
5067 renderer_prefs
.thumb_active_color
,
5068 renderer_prefs
.track_color
);
5069 #endif // defined(TOOLKIT_GTK)
5072 webview()->setSelectionColors(
5073 renderer_prefs
.active_selection_bg_color
,
5074 renderer_prefs
.active_selection_fg_color
,
5075 renderer_prefs
.inactive_selection_bg_color
,
5076 renderer_prefs
.inactive_selection_fg_color
);
5077 webview()->themeChanged();
5080 #endif // defined(USE_DEFAULT_RENDER_THEME) || defined(TOOLKIT_GTK)
5082 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
5083 RenderThreadImpl::current()->SetFlingCurveParameters(
5084 renderer_prefs
.touchpad_fling_profile
,
5085 renderer_prefs
.touchscreen_fling_profile
);
5087 // If the zoom level for this page matches the old zoom default, and this
5088 // is not a plugin, update the zoom level to match the new default.
5089 if (webview() && !webview()->mainFrame()->document().isPluginDocument() &&
5090 !ZoomValuesEqual(old_zoom_level
,
5091 renderer_preferences_
.default_zoom_level
) &&
5092 ZoomValuesEqual(webview()->zoomLevel(), old_zoom_level
)) {
5093 webview()->setZoomLevel(renderer_preferences_
.default_zoom_level
);
5098 void RenderViewImpl::OnMediaPlayerActionAt(const gfx::Point
& location
,
5099 const WebMediaPlayerAction
& action
) {
5101 webview()->performMediaPlayerAction(action
, location
);
5104 void RenderViewImpl::OnOrientationChangeEvent(int orientation
) {
5105 // Screen has rotated. 0 = default (portrait), 90 = one turn right, and so on.
5106 FOR_EACH_OBSERVER(RenderViewObserver
,
5108 OrientationChangeEvent(orientation
));
5109 webview()->mainFrame()->sendOrientationChangeEvent(orientation
);
5112 void RenderViewImpl::OnPluginActionAt(const gfx::Point
& location
,
5113 const WebPluginAction
& action
) {
5115 webview()->performPluginAction(action
, location
);
5118 void RenderViewImpl::OnGetAllSavableResourceLinksForCurrentPage(
5119 const GURL
& page_url
) {
5120 // Prepare list to storage all savable resource links.
5121 std::vector
<GURL
> resources_list
;
5122 std::vector
<GURL
> referrer_urls_list
;
5123 std::vector
<blink::WebReferrerPolicy
> referrer_policies_list
;
5124 std::vector
<GURL
> frames_list
;
5125 SavableResourcesResult
result(&resources_list
,
5126 &referrer_urls_list
,
5127 &referrer_policies_list
,
5130 // webkit/ doesn't know about Referrer.
5131 if (!GetAllSavableResourceLinksForCurrentPage(
5135 const_cast<const char**>(GetSavableSchemes()))) {
5136 // If something is wrong when collecting all savable resource links,
5137 // send empty list to embedder(browser) to tell it failed.
5138 referrer_urls_list
.clear();
5139 referrer_policies_list
.clear();
5140 resources_list
.clear();
5141 frames_list
.clear();
5144 std::vector
<Referrer
> referrers_list
;
5145 CHECK_EQ(referrer_urls_list
.size(), referrer_policies_list
.size());
5146 for (unsigned i
= 0; i
< referrer_urls_list
.size(); ++i
) {
5147 referrers_list
.push_back(
5148 Referrer(referrer_urls_list
[i
], referrer_policies_list
[i
]));
5151 // Send result of all savable resource links to embedder.
5152 Send(new ViewHostMsg_SendCurrentPageAllSavableResourceLinks(routing_id(),
5158 void RenderViewImpl::OnGetSerializedHtmlDataForCurrentPageWithLocalLinks(
5159 const std::vector
<GURL
>& links
,
5160 const std::vector
<base::FilePath
>& local_paths
,
5161 const base::FilePath
& local_directory_name
) {
5163 // Convert std::vector of GURLs to WebVector<WebURL>
5164 WebVector
<WebURL
> weburl_links(links
);
5166 // Convert std::vector of base::FilePath to WebVector<WebString>
5167 WebVector
<WebString
> webstring_paths(local_paths
.size());
5168 for (size_t i
= 0; i
< local_paths
.size(); i
++)
5169 webstring_paths
[i
] = local_paths
[i
].AsUTF16Unsafe();
5171 WebPageSerializer::serialize(webview()->mainFrame(), true, this, weburl_links
,
5173 local_directory_name
.AsUTF16Unsafe());
5176 void RenderViewImpl::OnShouldClose() {
5177 base::TimeTicks before_unload_start_time
= base::TimeTicks::Now();
5178 bool should_close
= webview()->dispatchBeforeUnloadEvent();
5179 base::TimeTicks before_unload_end_time
= base::TimeTicks::Now();
5180 Send(new ViewHostMsg_ShouldClose_ACK(routing_id_
, should_close
,
5181 before_unload_start_time
,
5182 before_unload_end_time
));
5185 void RenderViewImpl::OnSuppressDialogsUntilSwapOut() {
5186 // Don't show any more dialogs until we finish OnSwapOut.
5187 suppress_dialogs_until_swap_out_
= true;
5190 void RenderViewImpl::OnSwapOut() {
5191 // Only run unload if we're not swapped out yet, but send the ack either way.
5192 if (!is_swapped_out_
) {
5193 // Swap this RenderView out so the tab can navigate to a page rendered by a
5194 // different process. This involves running the unload handler and clearing
5195 // the page. Once WasSwappedOut is called, we also allow this process to
5196 // exit if there are no other active RenderViews in it.
5198 // Send an UpdateState message before we get swapped out.
5199 SyncNavigationState();
5201 // Synchronously run the unload handler before sending the ACK.
5202 webview()->dispatchUnloadEvent();
5204 // Swap out and stop sending any IPC messages that are not ACKs.
5205 SetSwappedOut(true);
5207 // Now that we're swapped out and filtering IPC messages, stop loading to
5208 // ensure that no other in-progress navigation continues. We do this here
5209 // to avoid sending a DidStopLoading message to the browser process.
5212 // Replace the page with a blank dummy URL. The unload handler will not be
5213 // run a second time, thanks to a check in FrameLoader::stopLoading.
5214 // TODO(creis): Need to add a better way to do this that avoids running the
5215 // beforeunload handler. For now, we just run it a second time silently.
5216 NavigateToSwappedOutURL(webview()->mainFrame());
5218 // Let WebKit know that this view is hidden so it can drop resources and
5219 // stop compositing.
5220 webview()->setVisibilityState(blink::WebPageVisibilityStateHidden
, false);
5223 // It is now safe to show modal dialogs again.
5224 suppress_dialogs_until_swap_out_
= false;
5226 Send(new ViewHostMsg_SwapOut_ACK(routing_id_
));
5229 void RenderViewImpl::NavigateToSwappedOutURL(blink::WebFrame
* frame
) {
5230 // We use loadRequest instead of loadHTMLString because the former commits
5231 // synchronously. Otherwise a new navigation can interrupt the navigation
5232 // to kSwappedOutURL. If that happens to be to the page we had been
5233 // showing, then WebKit will never send a commit and we'll be left spinning.
5234 // TODO(creis): Until we move this to RenderFrame, we may call this from a
5235 // swapped out RenderFrame while our own is_swapped_out_ is false.
5236 RenderFrameImpl
* rf
= RenderFrameImpl::FindByWebFrame(frame
);
5237 CHECK(is_swapped_out_
|| rf
->is_swapped_out());
5238 GURL
swappedOutURL(kSwappedOutURL
);
5239 WebURLRequest
request(swappedOutURL
);
5240 frame
->loadRequest(request
);
5243 void RenderViewImpl::OnClosePage() {
5244 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, ClosePage());
5245 // TODO(creis): We'd rather use webview()->Close() here, but that currently
5246 // sets the WebView's delegate_ to NULL, preventing any JavaScript dialogs
5247 // in the onunload handler from appearing. For now, we're bypassing that and
5248 // calling the FrameLoader's CloseURL method directly. This should be
5249 // revisited to avoid having two ways to close a page. Having a single way
5250 // to close that can run onunload is also useful for fixing
5251 // http://b/issue?id=753080.
5252 webview()->dispatchUnloadEvent();
5254 Send(new ViewHostMsg_ClosePage_ACK(routing_id_
));
5257 void RenderViewImpl::OnThemeChanged() {
5258 #if defined(USE_AURA)
5259 // Aura doesn't care if we switch themes.
5260 #elif defined(OS_WIN)
5261 ui::NativeThemeWin::instance()->CloseHandles();
5263 webview()->themeChanged();
5264 #else // defined(OS_WIN)
5265 // TODO(port): we don't support theming on non-Windows platforms yet
5270 bool RenderViewImpl::MaybeLoadAlternateErrorPage(WebFrame
* frame
,
5271 const WebURLError
& error
,
5273 // We only show alternate error pages in the main frame. They are
5274 // intended to assist the user when navigating, so there is not much
5275 // value in showing them for failed subframes. Ideally, we would be
5276 // able to use the TYPED transition type for this, but that flag is
5277 // not preserved across page reloads.
5278 if (frame
->parent())
5281 // Use the alternate error page service if this is a DNS failure or
5282 // connection failure.
5283 int ec
= error
.reason
;
5284 if (ec
!= net::ERR_NAME_NOT_RESOLVED
&&
5285 ec
!= net::ERR_CONNECTION_FAILED
&&
5286 ec
!= net::ERR_CONNECTION_REFUSED
&&
5287 ec
!= net::ERR_ADDRESS_UNREACHABLE
&&
5288 ec
!= net::ERR_CONNECTION_TIMED_OUT
) {
5292 const GURL
& error_page_url
= GetAlternateErrorPageURL(error
.unreachableURL
,
5293 ec
== net::ERR_NAME_NOT_RESOLVED
? DNS_ERROR
: CONNECTION_ERROR
);
5294 if (!error_page_url
.is_valid())
5297 WebDataSource
* ds
= frame
->provisionalDataSource();
5298 const WebURLRequest
& failed_request
= ds
->request();
5300 // Load an empty page first so there is an immediate response to the error,
5301 // and then kick off a request for the alternate error page.
5302 frame
->loadHTMLString(std::string(),
5303 GURL(kUnreachableWebDataURL
),
5304 error
.unreachableURL
,
5307 // Now, create a fetcher for the error page and associate it with the data
5308 // source we just created via the LoadHTMLString call. That way if another
5309 // navigation occurs, the fetcher will get destroyed.
5310 InternalDocumentStateData
* internal_data
=
5311 InternalDocumentStateData::FromDataSource(frame
->provisionalDataSource());
5312 internal_data
->set_alt_error_page_fetcher(
5313 new AltErrorPageResourceFetcher(
5314 error_page_url
, frame
, failed_request
, error
,
5315 base::Bind(&RenderViewImpl::AltErrorPageFinished
,
5316 base::Unretained(this))));
5320 void RenderViewImpl::AltErrorPageFinished(WebFrame
* frame
,
5321 const WebURLRequest
& original_request
,
5322 const WebURLError
& original_error
,
5323 const std::string
& html
) {
5324 // Here, we replace the blank page we loaded previously.
5325 // If we failed to download the alternate error page, LoadNavigationErrorPage
5326 // will simply display a default error page.
5327 LoadNavigationErrorPage(frame
, original_request
, original_error
, html
, true);
5330 void RenderViewImpl::OnMoveOrResizeStarted() {
5332 webview()->hidePopups();
5335 void RenderViewImpl::OnResize(const ViewMsg_Resize_Params
& params
) {
5337 webview()->hidePopups();
5338 if (send_preferred_size_changes_
) {
5339 webview()->mainFrame()->setCanHaveScrollbars(
5340 ShouldDisplayScrollbars(params
.new_size
.width(),
5341 params
.new_size
.height()));
5343 UpdateScrollState(webview()->mainFrame());
5346 RenderWidget::OnResize(params
);
5349 void RenderViewImpl::DidInitiatePaint() {
5350 #if defined(ENABLE_PLUGINS)
5351 main_render_frame_
->DidInitiatePaint();
5355 void RenderViewImpl::DidFlushPaint() {
5356 #if defined(ENABLE_PLUGINS)
5357 main_render_frame_
->DidFlushPaint();
5360 // If the RenderWidget is closing down then early-exit, otherwise we'll crash.
5361 // See crbug.com/112921.
5365 WebFrame
* main_frame
= webview()->mainFrame();
5367 // If we have a provisional frame we are between the start and commit stages
5368 // of loading and we don't want to save stats.
5369 if (!main_frame
->provisionalDataSource()) {
5370 WebDataSource
* ds
= main_frame
->dataSource();
5371 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
5372 InternalDocumentStateData
* data
=
5373 InternalDocumentStateData::FromDocumentState(document_state
);
5374 if (data
->did_first_visually_non_empty_layout() &&
5375 !data
->did_first_visually_non_empty_paint()) {
5376 data
->set_did_first_visually_non_empty_paint(true);
5377 Send(new ViewHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_
,
5381 // TODO(jar): The following code should all be inside a method, probably in
5383 Time now
= Time::Now();
5384 if (document_state
->first_paint_time().is_null()) {
5385 document_state
->set_first_paint_time(now
);
5387 if (document_state
->first_paint_after_load_time().is_null() &&
5388 !document_state
->finish_load_time().is_null()) {
5389 document_state
->set_first_paint_after_load_time(now
);
5394 PepperPluginInstanceImpl
* RenderViewImpl::GetBitmapForOptimizedPluginPaint(
5395 const gfx::Rect
& paint_bounds
,
5397 gfx::Rect
* location
,
5399 float* scale_factor
) {
5400 #if defined(ENABLE_PLUGINS)
5401 return main_render_frame_
->GetBitmapForOptimizedPluginPaint(
5402 paint_bounds
, dib
, location
, clip
, scale_factor
);
5407 gfx::Vector2d
RenderViewImpl::GetScrollOffset() {
5408 WebSize scroll_offset
= webview()->mainFrame()->scrollOffset();
5409 return gfx::Vector2d(scroll_offset
.width
, scroll_offset
.height
);
5412 void RenderViewImpl::OnClearFocusedNode() {
5414 webview()->clearFocusedNode();
5417 void RenderViewImpl::OnSetBackground(const SkBitmap
& background
) {
5419 webview()->setIsTransparent(!background
.empty());
5421 compositor_
->setHasTransparentBackground(!background
.empty());
5423 SetBackground(background
);
5426 void RenderViewImpl::OnSetAccessibilityMode(AccessibilityMode new_mode
) {
5427 if (accessibility_mode_
== new_mode
)
5429 accessibility_mode_
= new_mode
;
5430 if (renderer_accessibility_
) {
5431 delete renderer_accessibility_
;
5432 renderer_accessibility_
= NULL
;
5434 if (accessibility_mode_
== AccessibilityModeComplete
)
5435 renderer_accessibility_
= new RendererAccessibilityComplete(this);
5436 #if !defined(OS_ANDROID)
5437 else if (accessibility_mode_
== AccessibilityModeEditableTextOnly
)
5438 renderer_accessibility_
= new RendererAccessibilityFocusOnly(this);
5442 void RenderViewImpl::OnSetActive(bool active
) {
5444 webview()->setIsActive(active
);
5446 #if defined(ENABLE_PLUGINS) && defined(OS_MACOSX)
5447 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
5448 for (plugin_it
= plugin_delegates_
.begin();
5449 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
5450 (*plugin_it
)->SetWindowFocus(active
);
5455 #if defined(OS_MACOSX)
5456 void RenderViewImpl::OnSetWindowVisibility(bool visible
) {
5457 #if defined(ENABLE_PLUGINS)
5458 // Inform plugins that their container has changed visibility.
5459 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
5460 for (plugin_it
= plugin_delegates_
.begin();
5461 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
5462 (*plugin_it
)->SetContainerVisibility(visible
);
5467 void RenderViewImpl::OnWindowFrameChanged(const gfx::Rect
& window_frame
,
5468 const gfx::Rect
& view_frame
) {
5469 #if defined(ENABLE_PLUGINS)
5470 // Inform plugins that their window's frame has changed.
5471 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
5472 for (plugin_it
= plugin_delegates_
.begin();
5473 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
5474 (*plugin_it
)->WindowFrameChanged(window_frame
, view_frame
);
5479 void RenderViewImpl::OnPluginImeCompositionCompleted(const base::string16
& text
,
5481 // WebPluginDelegateProxy is responsible for figuring out if this event
5482 // applies to it or not, so inform all the delegates.
5483 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
5484 for (plugin_it
= plugin_delegates_
.begin();
5485 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
5486 (*plugin_it
)->ImeCompositionCompleted(text
, plugin_id
);
5491 void RenderViewImpl::Close() {
5492 // We need to grab a pointer to the doomed WebView before we destroy it.
5493 WebView
* doomed
= webview();
5494 RenderWidget::Close();
5495 g_view_map
.Get().erase(doomed
);
5496 g_routing_id_view_map
.Get().erase(routing_id_
);
5499 void RenderViewImpl::DidHandleKeyEvent() {
5500 ClearEditCommands();
5503 bool RenderViewImpl::WillHandleMouseEvent(const blink::WebMouseEvent
& event
) {
5504 context_menu_source_type_
= ui::MENU_SOURCE_MOUSE
;
5505 possible_drag_event_info_
.event_source
=
5506 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE
;
5507 possible_drag_event_info_
.event_location
=
5508 gfx::Point(event
.globalX
, event
.globalY
);
5510 #if defined(ENABLE_PLUGINS)
5511 main_render_frame_
->WillHandleMouseEvent(event
);
5514 // If the mouse is locked, only the current owner of the mouse lock can
5515 // process mouse events.
5516 return mouse_lock_dispatcher_
->WillHandleMouseEvent(event
);
5519 bool RenderViewImpl::WillHandleKeyEvent(const blink::WebKeyboardEvent
& event
) {
5520 context_menu_source_type_
= ui::MENU_SOURCE_KEYBOARD
;
5524 bool RenderViewImpl::WillHandleGestureEvent(
5525 const blink::WebGestureEvent
& event
) {
5526 context_menu_source_type_
= ui::MENU_SOURCE_TOUCH
;
5527 possible_drag_event_info_
.event_source
=
5528 ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH
;
5529 possible_drag_event_info_
.event_location
=
5530 gfx::Point(event
.globalX
, event
.globalY
);
5534 void RenderViewImpl::DidHandleMouseEvent(const WebMouseEvent
& event
) {
5535 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidHandleMouseEvent(event
));
5538 void RenderViewImpl::DidHandleTouchEvent(const WebTouchEvent
& event
) {
5539 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidHandleTouchEvent(event
));
5542 bool RenderViewImpl::HasTouchEventHandlersAt(const gfx::Point
& point
) const {
5545 return webview()->hasTouchEventHandlersAt(point
);
5548 void RenderViewImpl::OnWasHidden() {
5549 RenderWidget::OnWasHidden();
5551 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
5552 RenderThreadImpl::current()->video_capture_impl_manager()->
5553 SuspendDevices(true);
5557 webview()->setVisibilityState(visibilityState(), false);
5559 #if defined(ENABLE_PLUGINS)
5560 main_render_frame_
->PageVisibilityChanged(false);
5562 #if defined(OS_MACOSX)
5563 // Inform NPAPI plugins that their container is no longer visible.
5564 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
5565 for (plugin_it
= plugin_delegates_
.begin();
5566 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
5567 (*plugin_it
)->SetContainerVisibility(false);
5570 #endif // ENABLE_PLUGINS
5573 void RenderViewImpl::OnWasShown(bool needs_repainting
) {
5574 RenderWidget::OnWasShown(needs_repainting
);
5576 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
5577 RenderThreadImpl::current()->video_capture_impl_manager()->
5578 SuspendDevices(false);
5582 webview()->setVisibilityState(visibilityState(), false);
5584 #if defined(ENABLE_PLUGINS)
5585 main_render_frame_
->PageVisibilityChanged(true);
5587 #if defined(OS_MACOSX)
5588 // Inform NPAPI plugins that their container is now visible.
5589 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
5590 for (plugin_it
= plugin_delegates_
.begin();
5591 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
5592 (*plugin_it
)->SetContainerVisibility(true);
5595 #endif // ENABLE_PLUGINS
5598 GURL
RenderViewImpl::GetURLForGraphicsContext3D() {
5600 if (webview()->mainFrame())
5601 return GURL(webview()->mainFrame()->document().url());
5603 return GURL("chrome://gpu/RenderViewImpl::CreateGraphicsContext3D");
5606 bool RenderViewImpl::ForceCompositingModeEnabled() {
5607 return webkit_preferences_
.force_compositing_mode
;
5610 void RenderViewImpl::OnSetFocus(bool enable
) {
5611 RenderWidget::OnSetFocus(enable
);
5613 #if defined(ENABLE_PLUGINS)
5614 if (webview() && webview()->isActive()) {
5615 // Notify all NPAPI plugins.
5616 std::set
<WebPluginDelegateProxy
*>::iterator plugin_it
;
5617 for (plugin_it
= plugin_delegates_
.begin();
5618 plugin_it
!= plugin_delegates_
.end(); ++plugin_it
) {
5619 #if defined(OS_MACOSX)
5620 // RenderWidget's call to setFocus can cause the underlying webview's
5621 // activation state to change just like a call to setIsActive.
5623 (*plugin_it
)->SetWindowFocus(true);
5625 (*plugin_it
)->SetContentAreaFocus(enable
);
5628 main_render_frame_
->OnSetFocus(enable
);
5630 // Notify all BrowserPlugins of the RenderView's focus state.
5631 if (browser_plugin_manager_
.get())
5632 browser_plugin_manager_
->UpdateFocusState();
5635 void RenderViewImpl::OnImeSetComposition(
5636 const base::string16
& text
,
5637 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
5638 int selection_start
,
5639 int selection_end
) {
5640 #if defined(ENABLE_PLUGINS)
5641 if (focused_pepper_plugin_
) {
5642 focused_pepper_plugin_
->render_frame()->OnImeSetComposition(
5643 text
, underlines
, selection_start
, selection_end
);
5648 // When a plug-in has focus, we create platform-specific IME data used by
5649 // our IME emulator and send it directly to the focused plug-in, i.e. we
5650 // bypass WebKit. (WebPluginDelegate dispatches this IME data only when its
5651 // instance ID is the same one as the specified ID.)
5652 if (focused_plugin_id_
>= 0) {
5653 std::vector
<int> clauses
;
5654 std::vector
<int> target
;
5655 for (size_t i
= 0; i
< underlines
.size(); ++i
) {
5656 clauses
.push_back(underlines
[i
].startOffset
);
5657 clauses
.push_back(underlines
[i
].endOffset
);
5658 if (underlines
[i
].thick
) {
5660 target
.push_back(underlines
[i
].startOffset
);
5661 target
.push_back(underlines
[i
].endOffset
);
5664 std::set
<WebPluginDelegateProxy
*>::iterator it
;
5665 for (it
= plugin_delegates_
.begin(); it
!= plugin_delegates_
.end(); ++it
) {
5666 (*it
)->ImeCompositionUpdated(text
, clauses
, target
, selection_end
,
5667 focused_plugin_id_
);
5672 #endif // ENABLE_PLUGINS
5673 RenderWidget::OnImeSetComposition(text
,
5679 void RenderViewImpl::OnImeConfirmComposition(
5680 const base::string16
& text
,
5681 const gfx::Range
& replacement_range
,
5682 bool keep_selection
) {
5683 #if defined(ENABLE_PLUGINS)
5684 if (focused_pepper_plugin_
) {
5685 focused_pepper_plugin_
->render_frame()->OnImeConfirmComposition(
5686 text
, replacement_range
, keep_selection
);
5690 // Same as OnImeSetComposition(), we send the text from IMEs directly to
5691 // plug-ins. When we send IME text directly to plug-ins, we should not send
5692 // it to WebKit to prevent WebKit from controlling IMEs.
5693 // TODO(thakis): Honor |replacement_range| for plugins?
5694 if (focused_plugin_id_
>= 0) {
5695 std::set
<WebPluginDelegateProxy
*>::iterator it
;
5696 for (it
= plugin_delegates_
.begin();
5697 it
!= plugin_delegates_
.end(); ++it
) {
5698 (*it
)->ImeCompositionCompleted(text
, focused_plugin_id_
);
5703 #endif // ENABLE_PLUGINS
5704 if (replacement_range
.IsValid() && webview()) {
5705 // Select the text in |replacement_range|, it will then be replaced by
5706 // text added by the call to RenderWidget::OnImeConfirmComposition().
5707 if (WebFrame
* frame
= webview()->focusedFrame()) {
5708 WebRange webrange
= WebRange::fromDocumentRange(
5709 frame
, replacement_range
.start(), replacement_range
.length());
5710 if (!webrange
.isNull())
5711 frame
->selectRange(webrange
);
5714 RenderWidget::OnImeConfirmComposition(text
,
5719 void RenderViewImpl::SetDeviceScaleFactor(float device_scale_factor
) {
5720 RenderWidget::SetDeviceScaleFactor(device_scale_factor
);
5722 webview()->setDeviceScaleFactor(device_scale_factor
);
5723 webview()->settings()->setAcceleratedCompositingForFixedPositionEnabled(
5724 ShouldUseFixedPositionCompositing(device_scale_factor_
));
5725 webview()->settings()->setAcceleratedCompositingForOverflowScrollEnabled(
5726 ShouldUseAcceleratedCompositingForOverflowScroll(device_scale_factor_
));
5727 webview()->settings()->setAcceleratedCompositingForTransitionEnabled(
5728 ShouldUseTransitionCompositing(device_scale_factor_
));
5729 webview()->settings()->
5730 setAcceleratedCompositingForFixedRootBackgroundEnabled(
5731 ShouldUseAcceleratedFixedRootBackground(device_scale_factor_
));
5732 webview()->settings()->setAcceleratedCompositingForScrollableFramesEnabled(
5733 ShouldUseAcceleratedCompositingForScrollableFrames(
5734 device_scale_factor_
));
5735 webview()->settings()->setCompositedScrollingForFramesEnabled(
5736 ShouldUseCompositedScrollingForFrames(device_scale_factor_
));
5738 if (auto_resize_mode_
)
5739 AutoResizeCompositor();
5741 if (browser_plugin_manager_
.get())
5742 browser_plugin_manager_
->UpdateDeviceScaleFactor(device_scale_factor_
);
5745 ui::TextInputType
RenderViewImpl::GetTextInputType() {
5746 #if defined(ENABLE_PLUGINS)
5747 if (focused_pepper_plugin_
)
5748 return focused_pepper_plugin_
->text_input_type();
5750 return RenderWidget::GetTextInputType();
5753 void RenderViewImpl::GetSelectionBounds(gfx::Rect
* start
, gfx::Rect
* end
) {
5754 #if defined(ENABLE_PLUGINS)
5755 if (focused_pepper_plugin_
) {
5756 // TODO(kinaba) http://crbug.com/101101
5757 // Current Pepper IME API does not handle selection bounds. So we simply
5758 // use the caret position as an empty range for now. It will be updated
5759 // after Pepper API equips features related to surrounding text retrieval.
5760 gfx::Rect caret
= focused_pepper_plugin_
->GetCaretBounds();
5766 RenderWidget::GetSelectionBounds(start
, end
);
5769 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(USE_AURA)
5770 void RenderViewImpl::GetCompositionCharacterBounds(
5771 std::vector
<gfx::Rect
>* bounds
) {
5775 #if defined(ENABLE_PLUGINS)
5776 if (focused_pepper_plugin_
) {
5783 size_t start_offset
= 0;
5784 size_t character_count
= 0;
5785 if (!webview()->compositionRange(&start_offset
, &character_count
))
5787 if (character_count
== 0)
5790 blink::WebFrame
* frame
= webview()->focusedFrame();
5794 bounds
->reserve(character_count
);
5795 blink::WebRect webrect
;
5796 for (size_t i
= 0; i
< character_count
; ++i
) {
5797 if (!frame
->firstRectForCharacterRange(start_offset
+ i
, 1, webrect
)) {
5798 DLOG(ERROR
) << "Could not retrieve character rectangle at " << i
;
5802 bounds
->push_back(webrect
);
5806 void RenderViewImpl::GetCompositionRange(gfx::Range
* range
) {
5807 #if defined(ENABLE_PLUGINS)
5808 if (focused_pepper_plugin_
) {
5812 RenderWidget::GetCompositionRange(range
);
5816 bool RenderViewImpl::CanComposeInline() {
5817 #if defined(ENABLE_PLUGINS)
5818 if (focused_pepper_plugin_
)
5819 return focused_pepper_plugin_
->IsPluginAcceptingCompositionEvents();
5824 void RenderViewImpl::InstrumentWillBeginFrame(int frame_id
) {
5827 if (!webview()->devToolsAgent())
5829 webview()->devToolsAgent()->didBeginFrame(frame_id
);
5832 void RenderViewImpl::InstrumentDidBeginFrame() {
5835 if (!webview()->devToolsAgent())
5837 // TODO(jamesr/caseq): Decide if this needs to be renamed.
5838 webview()->devToolsAgent()->didComposite();
5841 void RenderViewImpl::InstrumentDidCancelFrame() {
5844 if (!webview()->devToolsAgent())
5846 webview()->devToolsAgent()->didCancelFrame();
5849 void RenderViewImpl::InstrumentWillComposite() {
5852 if (!webview()->devToolsAgent())
5854 webview()->devToolsAgent()->willComposite();
5857 bool RenderViewImpl::AllowPartialSwap() const {
5858 return allow_partial_swap_
;
5861 void RenderViewImpl::SetScreenMetricsEmulationParameters(
5862 float device_scale_factor
,
5863 const gfx::Point
& root_layer_offset
,
5864 float root_layer_scale
) {
5866 webview()->setCompositorDeviceScaleFactorOverride(device_scale_factor
);
5867 webview()->setRootLayerTransform(
5868 blink::WebSize(root_layer_offset
.x(), root_layer_offset
.y()),
5873 bool RenderViewImpl::ScheduleFileChooser(
5874 const FileChooserParams
& params
,
5875 WebFileChooserCompletion
* completion
) {
5876 static const size_t kMaximumPendingFileChooseRequests
= 4;
5877 if (file_chooser_completions_
.size() > kMaximumPendingFileChooseRequests
) {
5878 // This sanity check prevents too many file choose requests from getting
5879 // queued which could DoS the user. Getting these is most likely a
5880 // programming error (there are many ways to DoS the user so it's not
5881 // considered a "real" security check), either in JS requesting many file
5882 // choosers to pop up, or in a plugin.
5884 // TODO(brettw) we might possibly want to require a user gesture to open
5885 // a file picker, which will address this issue in a better way.
5889 file_chooser_completions_
.push_back(linked_ptr
<PendingFileChooser
>(
5890 new PendingFileChooser(params
, completion
)));
5891 if (file_chooser_completions_
.size() == 1) {
5892 // Actually show the browse dialog when this is the first request.
5893 Send(new ViewHostMsg_RunFileChooser(routing_id_
, params
));
5898 blink::WebGeolocationClient
* RenderViewImpl::geolocationClient() {
5899 if (!geolocation_dispatcher_
)
5900 geolocation_dispatcher_
= new GeolocationDispatcher(this);
5901 return geolocation_dispatcher_
;
5904 blink::WebSpeechInputController
* RenderViewImpl::speechInputController(
5905 blink::WebSpeechInputListener
* listener
) {
5906 #if defined(ENABLE_INPUT_SPEECH)
5907 if (!input_tag_speech_dispatcher_
)
5908 input_tag_speech_dispatcher_
=
5909 new InputTagSpeechDispatcher(this, listener
);
5911 return input_tag_speech_dispatcher_
;
5914 blink::WebSpeechRecognizer
* RenderViewImpl::speechRecognizer() {
5915 if (!speech_recognition_dispatcher_
)
5916 speech_recognition_dispatcher_
= new SpeechRecognitionDispatcher(this);
5917 return speech_recognition_dispatcher_
;
5920 void RenderViewImpl::zoomLimitsChanged(double minimum_level
,
5921 double maximum_level
) {
5922 // For now, don't remember plugin zoom values. We don't want to mix them with
5923 // normal web content (i.e. a fixed layout plugin would usually want them
5925 bool remember
= !webview()->mainFrame()->document().isPluginDocument();
5927 int minimum_percent
= static_cast<int>(
5928 ZoomLevelToZoomFactor(minimum_level
) * 100);
5929 int maximum_percent
= static_cast<int>(
5930 ZoomLevelToZoomFactor(maximum_level
) * 100);
5932 Send(new ViewHostMsg_UpdateZoomLimits(
5933 routing_id_
, minimum_percent
, maximum_percent
, remember
));
5936 void RenderViewImpl::zoomLevelChanged() {
5937 bool remember
= !webview()->mainFrame()->document().isPluginDocument();
5938 float zoom_level
= webview()->zoomLevel();
5940 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, ZoomLevelChanged());
5942 // Tell the browser which url got zoomed so it can update the menu and the
5943 // saved values if necessary
5944 Send(new ViewHostMsg_DidZoomURL(
5945 routing_id_
, zoom_level
, remember
,
5946 GURL(webview()->mainFrame()->document().url())));
5949 double RenderViewImpl::zoomLevelToZoomFactor(double zoom_level
) const {
5950 return ZoomLevelToZoomFactor(zoom_level
);
5953 double RenderViewImpl::zoomFactorToZoomLevel(double factor
) const {
5954 return ZoomFactorToZoomLevel(factor
);
5957 void RenderViewImpl::registerProtocolHandler(const WebString
& scheme
,
5958 const WebString
& base_url
,
5959 const WebString
& url
,
5960 const WebString
& title
) {
5961 bool user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
5962 GURL
base(base_url
);
5963 GURL absolute_url
= base
.Resolve(base::UTF16ToUTF8(url
));
5964 if (base
.GetOrigin() != absolute_url
.GetOrigin()) {
5967 Send(new ViewHostMsg_RegisterProtocolHandler(routing_id_
,
5968 base::UTF16ToUTF8(scheme
),
5974 blink::WebPageVisibilityState
RenderViewImpl::visibilityState() const {
5975 blink::WebPageVisibilityState current_state
= is_hidden() ?
5976 blink::WebPageVisibilityStateHidden
:
5977 blink::WebPageVisibilityStateVisible
;
5978 blink::WebPageVisibilityState override_state
= current_state
;
5979 // TODO(jam): move this method to WebFrameClient.
5980 if (GetContentClient()->renderer()->
5981 ShouldOverridePageVisibilityState(main_render_frame_
.get(),
5983 return override_state
;
5984 return current_state
;
5987 blink::WebUserMediaClient
* RenderViewImpl::userMediaClient() {
5988 // This can happen in tests, in which case it's OK to return NULL.
5989 if (!InitializeMediaStreamClient())
5992 return web_user_media_client_
;
5995 blink::WebMIDIClient
* RenderViewImpl::webMIDIClient() {
5996 if (!midi_dispatcher_
)
5997 midi_dispatcher_
= new MIDIDispatcher(this);
5998 return midi_dispatcher_
;
6001 void RenderViewImpl::draggableRegionsChanged() {
6005 DraggableRegionsChanged(webview()->mainFrame()));
6008 WebMediaPlayer
* RenderViewImpl::CreateWebMediaPlayerForMediaStream(
6010 const blink::WebURL
& url
,
6011 WebMediaPlayerClient
* client
) {
6012 #if defined(ENABLE_WEBRTC)
6013 if (!InitializeMediaStreamClient()) {
6014 LOG(ERROR
) << "Failed to initialize MediaStreamClient";
6017 #if !defined(GOOGLE_TV)
6018 if (media_stream_client_
->IsMediaStream(url
)) {
6019 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
6021 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON
) != 0;
6022 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon
);
6023 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
6024 return new WebMediaPlayerMS(frame
, client
, AsWeakPtr(),
6025 media_stream_client_
, new RenderMediaLog());
6027 #endif // !defined(GOOGLE_TV)
6028 #endif // defined(ENABLE_WEBRTC)
6032 #if defined(OS_ANDROID)
6033 WebContentDetectionResult
RenderViewImpl::detectContentAround(
6034 const WebHitTestResult
& touch_hit
) {
6035 DCHECK(!touch_hit
.isNull());
6036 DCHECK(!touch_hit
.node().isNull());
6037 DCHECK(touch_hit
.node().isTextNode());
6039 // Process the position with all the registered content detectors until
6040 // a match is found. Priority is provided by their relative order.
6041 for (ContentDetectorList::const_iterator it
= content_detectors_
.begin();
6042 it
!= content_detectors_
.end(); ++it
) {
6043 ContentDetector::Result content
= (*it
)->FindTappedContent(touch_hit
);
6044 if (content
.valid
) {
6045 return WebContentDetectionResult(content
.content_boundaries
,
6046 base::UTF8ToUTF16(content
.text
), content
.intent_url
);
6049 return WebContentDetectionResult();
6052 void RenderViewImpl::scheduleContentIntent(const WebURL
& intent
) {
6053 // Introduce a short delay so that the user can notice the content.
6054 base::MessageLoop::current()->PostDelayedTask(
6056 base::Bind(&RenderViewImpl::LaunchAndroidContentIntent
,
6059 expected_content_intent_id_
),
6060 base::TimeDelta::FromMilliseconds(kContentIntentDelayMilliseconds
));
6063 void RenderViewImpl::cancelScheduledContentIntents() {
6064 ++expected_content_intent_id_
;
6067 void RenderViewImpl::LaunchAndroidContentIntent(const GURL
& intent
,
6068 size_t request_id
) {
6069 if (request_id
!= expected_content_intent_id_
)
6072 // Remove the content highlighting if any.
6073 scheduleComposite();
6075 if (!intent
.is_empty())
6076 Send(new ViewHostMsg_StartContentIntent(routing_id_
, intent
));
6079 bool RenderViewImpl::openDateTimeChooser(
6080 const blink::WebDateTimeChooserParams
& params
,
6081 blink::WebDateTimeChooserCompletion
* completion
) {
6082 // JavaScript may try to open a date time chooser while one is already open.
6083 if (date_time_picker_client_
)
6085 date_time_picker_client_
.reset(
6086 new RendererDateTimePicker(this, params
, completion
));
6087 return date_time_picker_client_
->Open();
6090 #if defined(OS_ANDROID)
6091 void RenderViewImpl::DismissDateTimeDialog() {
6092 DCHECK(date_time_picker_client_
);
6093 date_time_picker_client_
.reset(NULL
);
6097 WebMediaPlayer
* RenderViewImpl::CreateAndroidWebMediaPlayer(
6099 const blink::WebURL
& url
,
6100 WebMediaPlayerClient
* client
) {
6101 GpuChannelHost
* gpu_channel_host
=
6102 RenderThreadImpl::current()->EstablishGpuChannelSync(
6103 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE
);
6104 if (!gpu_channel_host
) {
6105 LOG(ERROR
) << "Failed to establish GPU channel for media player";
6109 scoped_ptr
<StreamTextureFactory
> stream_texture_factory
;
6110 if (UsingSynchronousRendererCompositor()) {
6111 SynchronousCompositorFactory
* factory
=
6112 SynchronousCompositorFactory::GetInstance();
6113 stream_texture_factory
= factory
->CreateStreamTextureFactory(routing_id_
);
6115 scoped_refptr
<cc::ContextProvider
> context_provider
=
6116 RenderThreadImpl::current()->SharedMainThreadContextProvider();
6118 if (!context_provider
.get()) {
6119 LOG(ERROR
) << "Failed to get context3d for media player";
6123 stream_texture_factory
.reset(new StreamTextureFactoryImpl(
6124 context_provider
->Context3d(), gpu_channel_host
, routing_id_
));
6127 scoped_ptr
<WebMediaPlayerAndroid
> web_media_player_android(
6128 new WebMediaPlayerAndroid(
6132 media_player_manager_
,
6133 stream_texture_factory
.release(),
6134 RenderThreadImpl::current()->GetMediaThreadMessageLoopProxy(),
6135 new RenderMediaLog()));
6136 #if defined(ENABLE_WEBRTC) && defined(GOOGLE_TV)
6137 if (media_stream_client_
&& media_stream_client_
->IsMediaStream(url
)) {
6138 RTCVideoDecoderFactoryTv
* factory
= RenderThreadImpl::current()
6139 ->GetMediaStreamDependencyFactory()->decoder_factory_tv();
6140 // |media_stream_client| and |factory| outlives |web_media_player_android|.
6141 if (!factory
->AcquireDemuxer() ||
6142 !web_media_player_android
->InjectMediaStream(
6143 media_stream_client_
,
6146 base::IgnoreResult(&RTCVideoDecoderFactoryTv::ReleaseDemuxer
),
6147 base::Unretained(factory
)))) {
6148 LOG(ERROR
) << "Failed to inject media stream.";
6152 #endif // defined(ENABLE_WEBRTC) && defined(GOOGLE_TV)
6153 return web_media_player_android
.release();
6156 #endif // defined(OS_ANDROID)
6158 #if defined(OS_MACOSX)
6159 void RenderViewImpl::OnSelectPopupMenuItem(int selected_index
) {
6160 if (external_popup_menu_
== NULL
) {
6161 // Crash reports from the field indicate that we can be notified with a
6162 // NULL external popup menu (we probably get notified twice).
6163 // If you hit this please file a bug against jcivelli and include the page
6164 // and steps to repro.
6168 external_popup_menu_
->DidSelectItem(selected_index
);
6169 external_popup_menu_
.reset();
6173 #if defined(OS_ANDROID)
6174 void RenderViewImpl::OnSelectPopupMenuItems(
6176 const std::vector
<int>& selected_indices
) {
6177 // It is possible to receive more than one of these calls if the user presses
6178 // a select faster than it takes for the show-select-popup IPC message to make
6179 // it to the browser UI thread. Ignore the extra-messages.
6180 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
6181 if (!external_popup_menu_
)
6184 external_popup_menu_
->DidSelectItems(canceled
, selected_indices
);
6185 external_popup_menu_
.reset();
6189 void RenderViewImpl::OnContextMenuClosed(
6190 const CustomContextMenuContext
& custom_context
) {
6191 if (custom_context
.request_id
) {
6192 // External request, should be in our map.
6193 ContextMenuClient
* client
=
6194 pending_context_menus_
.Lookup(custom_context
.request_id
);
6196 client
->OnMenuClosed(custom_context
.request_id
);
6197 pending_context_menus_
.Remove(custom_context
.request_id
);
6200 // Internal request, forward to WebKit.
6201 context_menu_node_
.reset();
6205 void RenderViewImpl::OnShowContextMenu(const gfx::Point
& location
) {
6206 context_menu_source_type_
= ui::MENU_SOURCE_TOUCH_EDIT_MENU
;
6207 touch_editing_context_menu_location_
= location
;
6209 webview()->showContextMenu();
6212 void RenderViewImpl::OnEnableViewSourceMode() {
6215 WebFrame
* main_frame
= webview()->mainFrame();
6218 main_frame
->enableViewSourceMode(true);
6221 void RenderViewImpl::OnDisownOpener() {
6225 WebFrame
* main_frame
= webview()->mainFrame();
6226 if (main_frame
&& main_frame
->opener())
6227 main_frame
->setOpener(NULL
);
6230 #if defined(OS_ANDROID)
6231 bool RenderViewImpl::didTapMultipleTargets(
6232 const blink::WebGestureEvent
& event
,
6233 const WebVector
<WebRect
>& target_rects
) {
6234 // Never show a disambiguation popup when accessibility is enabled,
6235 // as this interferes with "touch exploration".
6236 if (accessibility_mode_
== AccessibilityModeComplete
)
6239 gfx::Rect
finger_rect(
6240 event
.x
- event
.data
.tap
.width
/ 2, event
.y
- event
.data
.tap
.height
/ 2,
6241 event
.data
.tap
.width
, event
.data
.tap
.height
);
6242 gfx::Rect zoom_rect
;
6243 float new_total_scale
=
6244 DisambiguationPopupHelper::ComputeZoomAreaAndScaleFactor(
6245 finger_rect
, target_rects
, GetSize(),
6246 gfx::Rect(webview()->mainFrame()->visibleContentRect()).size(),
6247 device_scale_factor_
* webview()->pageScaleFactor(), &zoom_rect
);
6248 if (!new_total_scale
)
6251 bool handled
= false;
6252 switch (renderer_preferences_
.tap_multiple_targets_strategy
) {
6253 case TAP_MULTIPLE_TARGETS_STRATEGY_ZOOM
:
6254 handled
= webview()->zoomToMultipleTargetsRect(zoom_rect
);
6256 case TAP_MULTIPLE_TARGETS_STRATEGY_POPUP
: {
6257 gfx::Size canvas_size
=
6258 gfx::ToCeiledSize(gfx::ScaleSize(zoom_rect
.size(), new_total_scale
));
6259 TransportDIB
* transport_dib
= NULL
;
6261 scoped_ptr
<skia::PlatformCanvas
> canvas(
6262 RenderProcess::current()->GetDrawingCanvas(&transport_dib
,
6263 gfx::Rect(canvas_size
)));
6269 // TODO(trchen): Cleanup the device scale factor mess.
6270 // device scale will be applied in WebKit
6271 // --> zoom_rect doesn't include device scale,
6272 // but WebKit will still draw on zoom_rect * device_scale_factor_
6273 canvas
->scale(new_total_scale
/ device_scale_factor_
,
6274 new_total_scale
/ device_scale_factor_
);
6275 canvas
->translate(-zoom_rect
.x() * device_scale_factor_
,
6276 -zoom_rect
.y() * device_scale_factor_
);
6281 WebWidget::ForceSoftwareRenderingAndIgnoreGPUResidentContent
);
6284 gfx::Rect physical_window_zoom_rect
= gfx::ToEnclosingRect(
6285 ClientRectToPhysicalWindowRect(gfx::RectF(zoom_rect
)));
6286 Send(new ViewHostMsg_ShowDisambiguationPopup(routing_id_
,
6287 physical_window_zoom_rect
,
6289 transport_dib
->id()));
6293 case TAP_MULTIPLE_TARGETS_STRATEGY_NONE
:
6302 unsigned RenderViewImpl::GetLocalSessionHistoryLengthForTesting() const {
6303 return history_list_length_
;
6306 void RenderViewImpl::SetFocusAndActivateForTesting(bool enable
) {
6320 void RenderViewImpl::SetDeviceScaleFactorForTesting(float factor
) {
6321 ViewMsg_Resize_Params params
;
6322 params
.screen_info
= screen_info_
;
6323 params
.screen_info
.deviceScaleFactor
= factor
;
6324 params
.new_size
= size();
6325 params
.physical_backing_size
=
6326 gfx::ToCeiledSize(gfx::ScaleSize(size(), factor
));
6327 params
.overdraw_bottom_height
= 0.f
;
6328 params
.resizer_rect
= WebRect();
6329 params
.is_fullscreen
= is_fullscreen();
6333 void RenderViewImpl::ForceResizeForTesting(const gfx::Size
& new_size
) {
6334 gfx::Rect
new_position(rootWindowRect().x
,
6338 ResizeSynchronously(new_position
);
6341 void RenderViewImpl::UseSynchronousResizeModeForTesting(bool enable
) {
6342 resizing_mode_selector_
->set_is_synchronous_mode(enable
);
6345 void RenderViewImpl::EnableAutoResizeForTesting(const gfx::Size
& min_size
,
6346 const gfx::Size
& max_size
) {
6347 OnEnableAutoResize(min_size
, max_size
);
6350 void RenderViewImpl::DisableAutoResizeForTesting(const gfx::Size
& new_size
) {
6351 OnDisableAutoResize(new_size
);
6354 void RenderViewImpl::SetMediaStreamClientForTesting(
6355 MediaStreamClient
* media_stream_client
) {
6356 DCHECK(!media_stream_client_
);
6357 DCHECK(!web_user_media_client_
);
6358 media_stream_client_
= media_stream_client
;
6361 void RenderViewImpl::OnReleaseDisambiguationPopupDIB(
6362 TransportDIB::Handle dib_handle
) {
6363 TransportDIB
* dib
= TransportDIB::CreateWithHandle(dib_handle
);
6364 RenderProcess::current()->ReleaseTransportDIB(dib
);
6367 void RenderViewImpl::DidCommitCompositorFrame() {
6368 RenderWidget::DidCommitCompositorFrame();
6369 FOR_EACH_OBSERVER(RenderViewObserver
, observers_
, DidCommitCompositorFrame());
6372 void RenderViewImpl::SendUpdateFaviconURL(const std::vector
<FaviconURL
>& urls
) {
6374 Send(new ViewHostMsg_UpdateFaviconURL(routing_id_
, page_id_
, urls
));
6377 void RenderViewImpl::DidStopLoadingIcons() {
6378 int icon_types
= WebIconURL::TypeFavicon
;
6380 icon_types
|= WebIconURL::TypeTouchPrecomposed
| WebIconURL::TypeTouch
;
6382 WebVector
<WebIconURL
> icon_urls
=
6383 webview()->mainFrame()->iconURLs(icon_types
);
6385 std::vector
<FaviconURL
> urls
;
6386 for (size_t i
= 0; i
< icon_urls
.size(); i
++) {
6387 WebURL url
= icon_urls
[i
].iconURL();
6389 urls
.push_back(FaviconURL(url
,
6390 ToFaviconType(icon_urls
[i
].iconType())));
6392 SendUpdateFaviconURL(urls
);
6395 } // namespace content