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/frame_messages.h"
46 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
47 #include "content/common/input_messages.h"
48 #include "content/common/java_bridge_messages.h"
49 #include "content/common/pepper_messages.h"
50 #include "content/common/socket_stream_handle_data.h"
51 #include "content/common/ssl_status_serialization.h"
52 #include "content/common/view_messages.h"
53 #include "content/public/common/bindings_policy.h"
54 #include "content/public/common/content_client.h"
55 #include "content/public/common/content_constants.h"
56 #include "content/public/common/content_switches.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/document_state.h"
67 #include "content/public/renderer/history_item_serialization.h"
68 #include "content/public/renderer/navigation_state.h"
69 #include "content/public/renderer/render_view_observer.h"
70 #include "content/public/renderer/render_view_visitor.h"
71 #include "content/public/renderer/web_preferences.h"
72 #include "content/renderer/accessibility/renderer_accessibility.h"
73 #include "content/renderer/accessibility/renderer_accessibility_complete.h"
74 #include "content/renderer/accessibility/renderer_accessibility_focus_only.h"
75 #include "content/renderer/browser_plugin/browser_plugin.h"
76 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
77 #include "content/renderer/browser_plugin/browser_plugin_manager_impl.h"
78 #include "content/renderer/devtools/devtools_agent.h"
79 #include "content/renderer/disambiguation_popup_helper.h"
80 #include "content/renderer/dom_automation_controller.h"
81 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
82 #include "content/renderer/drop_data_builder.h"
83 #include "content/renderer/external_popup_menu.h"
84 #include "content/renderer/geolocation_dispatcher.h"
85 #include "content/renderer/gpu/render_widget_compositor.h"
86 #include "content/renderer/idle_user_detector.h"
87 #include "content/renderer/image_loading_helper.h"
88 #include "content/renderer/ime_event_guard.h"
89 #include "content/renderer/input/input_handler_manager.h"
90 #include "content/renderer/input_tag_speech_dispatcher.h"
91 #include "content/renderer/internal_document_state_data.h"
92 #include "content/renderer/java/java_bridge_dispatcher.h"
93 #include "content/renderer/load_progress_tracker.h"
94 #include "content/renderer/media/audio_device_factory.h"
95 #include "content/renderer/media/audio_renderer_mixer_manager.h"
96 #include "content/renderer/media/media_stream_dependency_factory.h"
97 #include "content/renderer/media/media_stream_dispatcher.h"
98 #include "content/renderer/media/media_stream_impl.h"
99 #include "content/renderer/media/midi_dispatcher.h"
100 #include "content/renderer/media/render_media_log.h"
101 #include "content/renderer/media/video_capture_impl_manager.h"
102 #include "content/renderer/media/webmediaplayer_impl.h"
103 #include "content/renderer/media/webmediaplayer_ms.h"
104 #include "content/renderer/media/webmediaplayer_params.h"
105 #include "content/renderer/memory_benchmarking_extension.h"
106 #include "content/renderer/mhtml_generator.h"
107 #include "content/renderer/notification_provider.h"
108 #include "content/renderer/render_frame_impl.h"
109 #include "content/renderer/render_process.h"
110 #include "content/renderer/render_thread_impl.h"
111 #include "content/renderer/render_view_impl_params.h"
112 #include "content/renderer/render_view_mouse_lock_dispatcher.h"
113 #include "content/renderer/render_widget_fullscreen_pepper.h"
114 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
115 #include "content/renderer/renderer_webcolorchooser_impl.h"
116 #include "content/renderer/resizing_mode_selector.h"
117 #include "content/renderer/savable_resources.h"
118 #include "content/renderer/skia_benchmarking_extension.h"
119 #include "content/renderer/speech_recognition_dispatcher.h"
120 #include "content/renderer/stats_collection_controller.h"
121 #include "content/renderer/stats_collection_observer.h"
122 #include "content/renderer/text_input_client_observer.h"
123 #include "content/renderer/v8_value_converter_impl.h"
124 #include "content/renderer/web_ui_extension.h"
125 #include "content/renderer/web_ui_extension_data.h"
126 #include "content/renderer/websharedworker_proxy.h"
127 #include "media/audio/audio_output_device.h"
128 #include "media/base/audio_renderer_mixer_input.h"
129 #include "media/base/filter_collection.h"
130 #include "media/base/media_switches.h"
131 #include "media/filters/audio_renderer_impl.h"
132 #include "media/filters/gpu_video_accelerator_factories.h"
133 #include "net/base/data_url.h"
134 #include "net/base/escape.h"
135 #include "net/base/net_errors.h"
136 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
137 #include "net/http/http_util.h"
138 #include "third_party/WebKit/public/platform/WebCString.h"
139 #include "third_party/WebKit/public/platform/WebDragData.h"
140 #include "third_party/WebKit/public/platform/WebHTTPBody.h"
141 #include "third_party/WebKit/public/platform/WebImage.h"
142 #include "third_party/WebKit/public/platform/WebMessagePortChannel.h"
143 #include "third_party/WebKit/public/platform/WebPoint.h"
144 #include "third_party/WebKit/public/platform/WebRect.h"
145 #include "third_party/WebKit/public/platform/WebSize.h"
146 #include "third_party/WebKit/public/platform/WebSocketStreamHandle.h"
147 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
148 #include "third_party/WebKit/public/platform/WebString.h"
149 #include "third_party/WebKit/public/platform/WebURL.h"
150 #include "third_party/WebKit/public/platform/WebURLError.h"
151 #include "third_party/WebKit/public/platform/WebURLRequest.h"
152 #include "third_party/WebKit/public/platform/WebURLResponse.h"
153 #include "third_party/WebKit/public/platform/WebVector.h"
154 #include "third_party/WebKit/public/web/WebAXObject.h"
155 #include "third_party/WebKit/public/web/WebColorName.h"
156 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
157 #include "third_party/WebKit/public/web/WebDOMEvent.h"
158 #include "third_party/WebKit/public/web/WebDOMMessageEvent.h"
159 #include "third_party/WebKit/public/web/WebDataSource.h"
160 #include "third_party/WebKit/public/web/WebDateTimeChooserCompletion.h"
161 #include "third_party/WebKit/public/web/WebDateTimeChooserParams.h"
162 #include "third_party/WebKit/public/web/WebDevToolsAgent.h"
163 #include "third_party/WebKit/public/web/WebDocument.h"
164 #include "third_party/WebKit/public/web/WebElement.h"
165 #include "third_party/WebKit/public/web/WebFileChooserParams.h"
166 #include "third_party/WebKit/public/web/WebFindOptions.h"
167 #include "third_party/WebKit/public/web/WebFormControlElement.h"
168 #include "third_party/WebKit/public/web/WebFormElement.h"
169 #include "third_party/WebKit/public/web/WebFrame.h"
170 #include "third_party/WebKit/public/web/WebGlyphCache.h"
171 #include "third_party/WebKit/public/web/WebHelperPlugin.h"
172 #include "third_party/WebKit/public/web/WebHistoryItem.h"
173 #include "third_party/WebKit/public/web/WebInputElement.h"
174 #include "third_party/WebKit/public/web/WebInputEvent.h"
175 #include "third_party/WebKit/public/web/WebMediaPlayerAction.h"
176 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
177 #include "third_party/WebKit/public/web/WebNodeList.h"
178 #include "third_party/WebKit/public/web/WebPageSerializer.h"
179 #include "third_party/WebKit/public/web/WebPlugin.h"
180 #include "third_party/WebKit/public/web/WebPluginAction.h"
181 #include "third_party/WebKit/public/web/WebPluginContainer.h"
182 #include "third_party/WebKit/public/web/WebPluginDocument.h"
183 #include "third_party/WebKit/public/web/WebRange.h"
184 #include "third_party/WebKit/public/web/WebScriptSource.h"
185 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
186 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
187 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
188 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
189 #include "third_party/WebKit/public/web/WebSettings.h"
190 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
191 #include "third_party/WebKit/public/web/WebUserMediaClient.h"
192 #include "third_party/WebKit/public/web/WebView.h"
193 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
194 #include "third_party/WebKit/public/web/default/WebRenderTheme.h"
195 #include "ui/base/ui_base_switches_util.h"
196 #include "ui/events/latency_info.h"
197 #include "ui/gfx/native_widget_types.h"
198 #include "ui/gfx/point.h"
199 #include "ui/gfx/rect.h"
200 #include "ui/gfx/rect_conversions.h"
201 #include "ui/gfx/size_conversions.h"
202 #include "ui/shell_dialogs/selected_file_info.h"
203 #include "v8/include/v8.h"
204 #include "webkit/child/weburlresponse_extradata_impl.h"
206 #if defined(OS_ANDROID)
207 #include <cpu-features.h>
209 #include "content/common/android/device_telephony_info.h"
210 #include "content/common/gpu/client/context_provider_command_buffer.h"
211 #include "content/renderer/android/address_detector.h"
212 #include "content/renderer/android/content_detector.h"
213 #include "content/renderer/android/email_detector.h"
214 #include "content/renderer/android/phone_number_detector.h"
215 #include "content/renderer/android/synchronous_compositor_factory.h"
216 #include "content/renderer/media/android/renderer_media_player_manager.h"
217 #include "content/renderer/media/android/stream_texture_factory_android_impl.h"
218 #include "content/renderer/media/android/webmediaplayer_android.h"
219 #include "skia/ext/platform_canvas.h"
220 #include "third_party/WebKit/public/platform/WebFloatPoint.h"
221 #include "third_party/WebKit/public/platform/WebFloatRect.h"
222 #include "third_party/WebKit/public/web/WebHitTestResult.h"
223 #include "ui/gfx/rect_f.h"
225 #elif defined(OS_WIN)
226 // TODO(port): these files are currently Windows only because they concern:
228 #include "ui/native_theme/native_theme_win.h"
229 #elif defined(USE_X11)
230 #include "ui/native_theme/native_theme.h"
231 #elif defined(OS_MACOSX)
232 #include "skia/ext/skia_utils_mac.h"
235 #if defined(ENABLE_PLUGINS)
236 #include "content/renderer/npapi/webplugin_delegate_proxy.h"
237 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
238 #include "content/renderer/pepper/pepper_plugin_registry.h"
241 #if defined(ENABLE_WEBRTC)
242 #include "content/renderer/media/rtc_peer_connection_handler.h"
245 using blink::WebAXObject;
246 using blink::WebApplicationCacheHost;
247 using blink::WebApplicationCacheHostClient;
248 using blink::WebCString;
249 using blink::WebColor;
250 using blink::WebColorName;
251 using blink::WebConsoleMessage;
252 using blink::WebData;
253 using blink::WebDataSource;
254 using blink::WebDocument;
255 using blink::WebDOMEvent;
256 using blink::WebDOMMessageEvent;
257 using blink::WebDragData;
258 using blink::WebDragOperation;
259 using blink::WebDragOperationsMask;
260 using blink::WebElement;
261 using blink::WebExternalPopupMenu;
262 using blink::WebExternalPopupMenuClient;
263 using blink::WebFileChooserCompletion;
264 using blink::WebFindOptions;
265 using blink::WebFormControlElement;
266 using blink::WebFormElement;
267 using blink::WebFrame;
268 using blink::WebGestureEvent;
269 using blink::WebHistoryItem;
270 using blink::WebHTTPBody;
271 using blink::WebIconURL;
272 using blink::WebImage;
273 using blink::WebInputElement;
274 using blink::WebInputEvent;
275 using blink::WebMediaPlayer;
276 using blink::WebMediaPlayerAction;
277 using blink::WebMediaPlayerClient;
278 using blink::WebMouseEvent;
279 using blink::WebNavigationPolicy;
280 using blink::WebNavigationType;
281 using blink::WebNode;
282 using blink::WebPageSerializer;
283 using blink::WebPageSerializerClient;
284 using blink::WebPeerConnection00Handler;
285 using blink::WebPeerConnection00HandlerClient;
286 using blink::WebPeerConnectionHandler;
287 using blink::WebPeerConnectionHandlerClient;
288 using blink::WebPluginAction;
289 using blink::WebPluginContainer;
290 using blink::WebPluginDocument;
291 using blink::WebPoint;
292 using blink::WebPopupMenuInfo;
293 using blink::WebRange;
294 using blink::WebRect;
295 using blink::WebReferrerPolicy;
296 using blink::WebScriptSource;
297 using blink::WebSearchableFormData;
298 using blink::WebSecurityOrigin;
299 using blink::WebSecurityPolicy;
300 using blink::WebSerializedScriptValue;
301 using blink::WebSettings;
302 using blink::WebSize;
303 using blink::WebSocketStreamHandle;
304 using blink::WebStorageNamespace;
305 using blink::WebStorageQuotaCallbacks;
306 using blink::WebStorageQuotaError;
307 using blink::WebStorageQuotaType;
308 using blink::WebString;
309 using blink::WebTextAffinity;
310 using blink::WebTextDirection;
311 using blink::WebTouchEvent;
313 using blink::WebURLError;
314 using blink::WebURLRequest;
315 using blink::WebURLResponse;
316 using blink::WebUserGestureIndicator;
317 using blink::WebVector;
318 using blink::WebView;
319 using blink::WebWidget;
320 using blink::WebWindowFeatures;
322 using base::TimeDelta;
323 using webkit_glue::WebURLResponseExtraDataImpl;
325 #if defined(OS_ANDROID)
326 using blink::WebContentDetectionResult;
327 using blink::WebFloatPoint;
328 using blink::WebFloatRect;
329 using blink::WebHitTestResult;
334 //-----------------------------------------------------------------------------
336 typedef std::map<blink::WebView*, RenderViewImpl*> ViewMap;
337 static base::LazyInstance<ViewMap> g_view_map = LAZY_INSTANCE_INITIALIZER;
338 typedef std::map<int32, RenderViewImpl*> RoutingIDViewMap;
339 static base::LazyInstance<RoutingIDViewMap> g_routing_id_view_map =
340 LAZY_INSTANCE_INITIALIZER;
342 // Time, in seconds, we delay before sending content state changes (such as form
343 // state and scroll position) to the browser. We delay sending changes to avoid
344 // spamming the browser.
345 // To avoid having tab/session restore require sending a message to get the
346 // current content state during tab closing we use a shorter timeout for the
347 // foreground renderer. This means there is a small window of time from which
348 // content state is modified and not sent to session restore, but this is
349 // better than having to wake up all renderers during shutdown.
350 const int kDelaySecondsForContentStateSyncHidden = 5;
351 const int kDelaySecondsForContentStateSync = 1;
353 const size_t kExtraCharsBeforeAndAfterSelection = 100;
355 const float kScalingIncrementForGesture = 0.01f;
357 #if defined(OS_ANDROID)
358 // Delay between tapping in content and launching the associated android intent.
359 // Used to allow users see what has been recognized as content.
360 const size_t kContentIntentDelayMilliseconds = 700;
363 static RenderViewImpl* (*g_create_render_view_impl)(RenderViewImplParams*) =
367 bool RenderViewImpl::IsReload(const FrameMsg_Navigate_Params& params) {
369 params.navigation_type == FrameMsg_Navigate_Type::RELOAD ||
370 params.navigation_type == FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE ||
371 params.navigation_type ==
372 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL;
376 Referrer RenderViewImpl::GetReferrerFromRequest(
378 const WebURLRequest& request) {
379 return Referrer(GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
380 request.referrerPolicy());
383 // Returns false unless this is a top-level navigation.
384 static bool IsTopLevelNavigation(WebFrame* frame) {
385 return frame->parent() == NULL;
388 // Returns false unless this is a top-level navigation that crosses origins.
389 static bool IsNonLocalTopLevelNavigation(const GURL& url,
391 WebNavigationType type,
393 if (!IsTopLevelNavigation(frame))
396 // Navigations initiated within Webkit are not sent out to the external host
397 // in the following cases.
398 // 1. The url scheme is not http/https
399 // 2. The origin of the url and the opener is the same in which case the
400 // opener relationship is maintained.
401 // 3. Reloads/form submits/back forward navigations
402 if (!url.SchemeIs(kHttpScheme) && !url.SchemeIs(kHttpsScheme))
405 if (type != blink::WebNavigationTypeReload &&
406 type != blink::WebNavigationTypeBackForward && !is_form_post) {
407 // The opener relationship between the new window and the parent allows the
408 // new window to script the parent and vice versa. This is not allowed if
409 // the origins of the two domains are different. This can be treated as a
410 // top level navigation and routed back to the host.
411 blink::WebFrame* opener = frame->opener();
415 if (url.GetOrigin() != GURL(opener->document().url()).GetOrigin())
422 void RenderViewImpl::NotifyTimezoneChange(blink::WebFrame* frame) {
423 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
424 v8::Context::Scope context_scope(frame->mainWorldScriptContext());
425 v8::Date::DateTimeConfigurationChangeNotification(v8::Isolate::GetCurrent());
426 blink::WebFrame* child = frame->firstChild();
427 for (; child; child = child->nextSibling())
428 NotifyTimezoneChange(child);
431 static WindowOpenDisposition NavigationPolicyToDisposition(
432 WebNavigationPolicy policy) {
434 case blink::WebNavigationPolicyIgnore:
435 return IGNORE_ACTION;
436 case blink::WebNavigationPolicyDownload:
438 case blink::WebNavigationPolicyCurrentTab:
440 case blink::WebNavigationPolicyNewBackgroundTab:
441 return NEW_BACKGROUND_TAB;
442 case blink::WebNavigationPolicyNewForegroundTab:
443 return NEW_FOREGROUND_TAB;
444 case blink::WebNavigationPolicyNewWindow:
446 case blink::WebNavigationPolicyNewPopup:
449 NOTREACHED() << "Unexpected WebNavigationPolicy";
450 return IGNORE_ACTION;
454 // Returns true if the device scale is high enough that losing subpixel
455 // antialiasing won't have a noticeable effect on text quality.
456 static bool DeviceScaleEnsuresTextQuality(float device_scale_factor) {
457 #if defined(OS_ANDROID)
458 // On Android, we never have subpixel antialiasing.
461 return device_scale_factor > 1.5f;
466 static bool ShouldUseFixedPositionCompositing(float device_scale_factor) {
467 // Compositing for fixed-position elements is dependent on
468 // device_scale_factor if no flag is set. http://crbug.com/172738
469 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
471 if (command_line.HasSwitch(switches::kDisableCompositingForFixedPosition))
474 if (command_line.HasSwitch(switches::kEnableCompositingForFixedPosition))
477 return DeviceScaleEnsuresTextQuality(device_scale_factor);
480 static bool ShouldUseAcceleratedCompositingForOverflowScroll(
481 float device_scale_factor) {
482 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
484 if (command_line.HasSwitch(switches::kDisableAcceleratedOverflowScroll))
487 if (command_line.HasSwitch(switches::kEnableAcceleratedOverflowScroll))
490 return DeviceScaleEnsuresTextQuality(device_scale_factor);
493 static bool ShouldUseAcceleratedCompositingForScrollableFrames(
494 float device_scale_factor) {
495 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
497 if (command_line.HasSwitch(switches::kDisableAcceleratedScrollableFrames))
500 if (command_line.HasSwitch(switches::kEnableAcceleratedScrollableFrames))
503 if (!cc::switches::IsLCDTextEnabled())
506 return DeviceScaleEnsuresTextQuality(device_scale_factor);
509 static bool ShouldUseCompositedScrollingForFrames(
510 float device_scale_factor) {
511 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
513 if (command_line.HasSwitch(switches::kDisableCompositedScrollingForFrames))
516 if (command_line.HasSwitch(switches::kEnableCompositedScrollingForFrames))
519 if (!cc::switches::IsLCDTextEnabled())
522 return DeviceScaleEnsuresTextQuality(device_scale_factor);
525 static bool ShouldUseUniversalAcceleratedCompositingForOverflowScroll() {
526 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
528 if (command_line.HasSwitch(
529 switches::kDisableUniversalAcceleratedOverflowScroll))
532 if (command_line.HasSwitch(
533 switches::kEnableUniversalAcceleratedOverflowScroll))
539 static bool ShouldUseTransitionCompositing(float device_scale_factor) {
540 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
542 if (command_line.HasSwitch(switches::kDisableCompositingForTransition))
545 if (command_line.HasSwitch(switches::kEnableCompositingForTransition))
548 // TODO(ajuma): Re-enable this by default for high-DPI once the problem
549 // of excessive layer promotion caused by overlap has been addressed.
550 // http://crbug.com/178119.
554 static bool ShouldUseAcceleratedFixedRootBackground(float device_scale_factor) {
555 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
557 if (command_line.HasSwitch(switches::kDisableAcceleratedFixedRootBackground))
560 if (command_line.HasSwitch(switches::kEnableAcceleratedFixedRootBackground))
563 return DeviceScaleEnsuresTextQuality(device_scale_factor);
566 static FaviconURL::IconType ToFaviconType(blink::WebIconURL::Type type) {
568 case blink::WebIconURL::TypeFavicon:
569 return FaviconURL::FAVICON;
570 case blink::WebIconURL::TypeTouch:
571 return FaviconURL::TOUCH_ICON;
572 case blink::WebIconURL::TypeTouchPrecomposed:
573 return FaviconURL::TOUCH_PRECOMPOSED_ICON;
574 case blink::WebIconURL::TypeInvalid:
575 return FaviconURL::INVALID_ICON;
577 return FaviconURL::INVALID_ICON;
580 ///////////////////////////////////////////////////////////////////////////////
582 struct RenderViewImpl::PendingFileChooser {
583 PendingFileChooser(const FileChooserParams& p, WebFileChooserCompletion* c)
587 FileChooserParams params;
588 WebFileChooserCompletion* completion; // MAY BE NULL to skip callback.
593 class WebWidgetLockTarget : public MouseLockDispatcher::LockTarget {
595 explicit WebWidgetLockTarget(blink::WebWidget* webwidget)
596 : webwidget_(webwidget) {}
598 virtual void OnLockMouseACK(bool succeeded) OVERRIDE {
600 webwidget_->didAcquirePointerLock();
602 webwidget_->didNotAcquirePointerLock();
605 virtual void OnMouseLockLost() OVERRIDE {
606 webwidget_->didLosePointerLock();
609 virtual bool HandleMouseLockedInputEvent(
610 const blink::WebMouseEvent &event) OVERRIDE {
611 // The WebWidget handles mouse lock in WebKit's handleInputEvent().
616 blink::WebWidget* webwidget_;
619 bool TouchEnabled() {
620 // Based on the definition of chrome::kEnableTouchIcon.
621 #if defined(OS_ANDROID)
628 WebDragData DropDataToWebDragData(const DropData& drop_data) {
629 std::vector<WebDragData::Item> item_list;
631 // These fields are currently unused when dragging into WebKit.
632 DCHECK(drop_data.download_metadata.empty());
633 DCHECK(drop_data.file_contents.empty());
634 DCHECK(drop_data.file_description_filename.empty());
636 if (!drop_data.text.is_null()) {
637 WebDragData::Item item;
638 item.storageType = WebDragData::Item::StorageTypeString;
639 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeText);
640 item.stringData = drop_data.text.string();
641 item_list.push_back(item);
644 // TODO(dcheng): Do we need to distinguish between null and empty URLs? Is it
645 // meaningful to write an empty URL to the clipboard?
646 if (!drop_data.url.is_empty()) {
647 WebDragData::Item item;
648 item.storageType = WebDragData::Item::StorageTypeString;
649 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeURIList);
650 item.stringData = WebString::fromUTF8(drop_data.url.spec());
651 item.title = drop_data.url_title;
652 item_list.push_back(item);
655 if (!drop_data.html.is_null()) {
656 WebDragData::Item item;
657 item.storageType = WebDragData::Item::StorageTypeString;
658 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeHTML);
659 item.stringData = drop_data.html.string();
660 item.baseURL = drop_data.html_base_url;
661 item_list.push_back(item);
664 for (std::vector<DropData::FileInfo>::const_iterator it =
665 drop_data.filenames.begin();
666 it != drop_data.filenames.end();
668 WebDragData::Item item;
669 item.storageType = WebDragData::Item::StorageTypeFilename;
670 item.filenameData = it->path;
671 item.displayNameData = it->display_name;
672 item_list.push_back(item);
675 for (std::map<base::string16, base::string16>::const_iterator it =
676 drop_data.custom_data.begin();
677 it != drop_data.custom_data.end();
679 WebDragData::Item item;
680 item.storageType = WebDragData::Item::StorageTypeString;
681 item.stringType = it->first;
682 item.stringData = it->second;
683 item_list.push_back(item);
688 result.setItems(item_list);
689 result.setFilesystemId(drop_data.filesystem_id);
695 RenderViewImpl::RenderViewImpl(RenderViewImplParams* params)
696 : RenderWidget(blink::WebPopupTypeNone,
700 webkit_preferences_(params->webkit_prefs),
701 send_content_state_immediately_(false),
702 enabled_bindings_(0),
703 send_preferred_size_changes_(false),
705 navigation_gesture_(NavigationGestureUnknown),
706 opened_by_user_gesture_(true),
707 opener_suppressed_(false),
708 suppress_dialogs_until_swap_out_(false),
710 last_page_id_sent_to_browser_(-1),
711 next_page_id_(params->next_page_id),
712 history_list_offset_(-1),
713 history_list_length_(0),
714 target_url_status_(TARGET_NONE),
715 selection_text_offset_(0),
716 selection_range_(gfx::Range::InvalidRange()),
717 #if defined(OS_ANDROID)
718 top_controls_constraints_(cc::BOTH),
720 cached_is_main_frame_pinned_to_left_(false),
721 cached_is_main_frame_pinned_to_right_(false),
722 cached_has_main_frame_horizontal_scrollbar_(false),
723 cached_has_main_frame_vertical_scrollbar_(false),
724 notification_provider_(NULL),
725 geolocation_dispatcher_(NULL),
726 input_tag_speech_dispatcher_(NULL),
727 speech_recognition_dispatcher_(NULL),
728 media_stream_dispatcher_(NULL),
729 browser_plugin_manager_(NULL),
730 media_stream_client_(NULL),
731 web_user_media_client_(NULL),
732 midi_dispatcher_(NULL),
733 devtools_agent_(NULL),
734 accessibility_mode_(AccessibilityModeOff),
735 renderer_accessibility_(NULL),
736 mouse_lock_dispatcher_(NULL),
737 #if defined(OS_ANDROID)
738 body_background_color_(SK_ColorWHITE),
739 expected_content_intent_id_(0),
740 media_player_manager_(NULL),
743 focused_plugin_id_(-1),
745 #if defined(ENABLE_PLUGINS)
746 focused_pepper_plugin_(NULL),
747 pepper_last_mouse_event_target_(NULL),
749 enumeration_completion_id_(0),
750 load_progress_tracker_(new LoadProgressTracker(this)),
751 session_storage_namespace_id_(params->session_storage_namespace_id),
752 handling_select_range_(false),
753 next_snapshot_id_(0),
754 allow_partial_swap_(params->allow_partial_swap) {
757 void RenderViewImpl::Initialize(RenderViewImplParams* params) {
758 routing_id_ = params->routing_id;
759 surface_id_ = params->surface_id;
760 if (params->opener_id != MSG_ROUTING_NONE && params->is_renderer_created)
761 opener_id_ = params->opener_id;
763 // Ensure we start with a valid next_page_id_ from the browser.
764 DCHECK_GE(next_page_id_, 0);
766 #if defined(ENABLE_NOTIFICATIONS)
767 notification_provider_ = new NotificationProvider(this);
769 notification_provider_ = NULL;
772 webwidget_ = WebView::create(this);
773 webwidget_mouse_lock_target_.reset(new WebWidgetLockTarget(webwidget_));
775 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
777 if (command_line.HasSwitch(switches::kStatsCollectionController))
778 stats_collection_observer_.reset(new StatsCollectionObserver(this));
780 #if defined(OS_ANDROID)
781 content::DeviceTelephonyInfo device_info;
783 const std::string region_code =
784 command_line.HasSwitch(switches::kNetworkCountryIso)
785 ? command_line.GetSwitchValueASCII(switches::kNetworkCountryIso)
786 : device_info.GetNetworkCountryIso();
787 content_detectors_.push_back(linked_ptr<ContentDetector>(
788 new AddressDetector()));
789 content_detectors_.push_back(linked_ptr<ContentDetector>(
790 new PhoneNumberDetector(region_code)));
791 content_detectors_.push_back(linked_ptr<ContentDetector>(
792 new EmailDetector()));
795 RenderThread::Get()->AddRoute(routing_id_, this);
796 // Take a reference on behalf of the RenderThread. This will be balanced
797 // when we receive ViewMsg_ClosePage.
799 if (RenderThreadImpl::current()) {
800 RenderThreadImpl::current()->WidgetCreated();
802 RenderThreadImpl::current()->WidgetHidden();
805 // If this is a popup, we must wait for the CreatingNew_ACK message before
806 // completing initialization. Otherwise, we can finish it now.
807 if (opener_id_ == MSG_ROUTING_NONE) {
812 g_view_map.Get().insert(std::make_pair(webview(), this));
813 g_routing_id_view_map.Get().insert(std::make_pair(routing_id_, this));
814 webview()->setDeviceScaleFactor(device_scale_factor_);
815 webview()->settings()->setAcceleratedCompositingForFixedPositionEnabled(
816 ShouldUseFixedPositionCompositing(device_scale_factor_));
817 webview()->settings()->setAcceleratedCompositingForOverflowScrollEnabled(
818 ShouldUseAcceleratedCompositingForOverflowScroll(device_scale_factor_));
819 webview()->settings()->setCompositorDrivenAcceleratedScrollingEnabled(
820 ShouldUseUniversalAcceleratedCompositingForOverflowScroll());
821 webview()->settings()->setAcceleratedCompositingForTransitionEnabled(
822 ShouldUseTransitionCompositing(device_scale_factor_));
823 webview()->settings()->setAcceleratedCompositingForFixedRootBackgroundEnabled(
824 ShouldUseAcceleratedFixedRootBackground(device_scale_factor_));
825 webview()->settings()->setAcceleratedCompositingForScrollableFramesEnabled(
826 ShouldUseAcceleratedCompositingForScrollableFrames(device_scale_factor_));
827 webview()->settings()->setCompositedScrollingForFramesEnabled(
828 ShouldUseCompositedScrollingForFrames(device_scale_factor_));
830 ApplyWebPreferences(webkit_preferences_, webview());
832 main_render_frame_.reset(
833 RenderFrameImpl::Create(this, params->main_frame_routing_id));
834 // The main frame WebFrame object is closed by
835 // RenderFrameImpl::frameDetached().
836 webview()->setMainFrame(WebFrame::create(main_render_frame_.get()));
837 main_render_frame_->SetWebFrame(webview()->mainFrame());
839 if (switches::IsTouchDragDropEnabled())
840 webview()->settings()->setTouchDragDropEnabled(true);
842 if (switches::IsTouchEditingEnabled())
843 webview()->settings()->setTouchEditingEnabled(true);
845 if (!params->frame_name.empty())
846 webview()->mainFrame()->setName(params->frame_name);
848 OnSetRendererPrefs(params->renderer_prefs);
850 #if defined(ENABLE_WEBRTC)
851 if (!media_stream_dispatcher_)
852 media_stream_dispatcher_ = new MediaStreamDispatcher(this);
855 new MHTMLGenerator(this);
856 #if defined(OS_MACOSX)
857 new TextInputClientObserver(this);
858 #endif // defined(OS_MACOSX)
860 #if defined(OS_ANDROID)
861 media_player_manager_ = new RendererMediaPlayerManager(this);
862 new JavaBridgeDispatcher(this);
865 // The next group of objects all implement RenderViewObserver, so are deleted
866 // along with the RenderView automatically.
867 devtools_agent_ = new DevToolsAgent(this);
868 if (RenderWidgetCompositor* rwc = compositor()) {
869 webview()->devToolsAgent()->setLayerTreeId(rwc->GetLayerTreeId());
871 mouse_lock_dispatcher_ = new RenderViewMouseLockDispatcher(this);
872 new ImageLoadingHelper(this);
874 // Create renderer_accessibility_ if needed.
875 OnSetAccessibilityMode(params->accessibility_mode);
877 new IdleUserDetector(this);
879 if (command_line.HasSwitch(switches::kDomAutomationController))
880 enabled_bindings_ |= BINDINGS_POLICY_DOM_AUTOMATION;
881 if (command_line.HasSwitch(switches::kStatsCollectionController))
882 enabled_bindings_ |= BINDINGS_POLICY_STATS_COLLECTION;
884 ProcessViewLayoutFlags(command_line);
886 GetContentClient()->renderer()->RenderViewCreated(this);
888 // If we have an opener_id but we weren't created by a renderer, then
889 // it's the browser asking us to set our opener to another RenderView.
890 if (params->opener_id != MSG_ROUTING_NONE && !params->is_renderer_created) {
891 RenderViewImpl* opener_view = FromRoutingID(params->opener_id);
893 webview()->mainFrame()->setOpener(opener_view->webview()->mainFrame());
896 // If we are initially swapped out, navigate to kSwappedOutURL.
897 // This ensures we are in a unique origin that others cannot script.
899 NavigateToSwappedOutURL(webview()->mainFrame());
902 RenderViewImpl::~RenderViewImpl() {
903 history_page_ids_.clear();
905 base::debug::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_);
907 // If file chooser is still waiting for answer, dispatch empty answer.
908 while (!file_chooser_completions_.empty()) {
909 if (file_chooser_completions_.front()->completion) {
910 file_chooser_completions_.front()->completion->didChooseFile(
911 WebVector<WebString>());
913 file_chooser_completions_.pop_front();
916 #if defined(OS_ANDROID)
917 // The date/time picker client is both a scoped_ptr member of this class and
918 // a RenderViewObserver. Reset it to prevent double deletion.
919 date_time_picker_client_.reset();
923 // Make sure we are no longer referenced by the ViewMap or RoutingIDViewMap.
924 ViewMap* views = g_view_map.Pointer();
925 for (ViewMap::iterator it = views->begin(); it != views->end(); ++it)
926 DCHECK_NE(this, it->second) << "Failed to call Close?";
927 RoutingIDViewMap* routing_id_views = g_routing_id_view_map.Pointer();
928 for (RoutingIDViewMap::iterator it = routing_id_views->begin();
929 it != routing_id_views->end(); ++it)
930 DCHECK_NE(this, it->second) << "Failed to call Close?";
933 FOR_EACH_OBSERVER(RenderViewObserver, observers_, RenderViewGone());
934 FOR_EACH_OBSERVER(RenderViewObserver, observers_, OnDestruct());
938 RenderViewImpl* RenderViewImpl::FromWebView(WebView* webview) {
939 ViewMap* views = g_view_map.Pointer();
940 ViewMap::iterator it = views->find(webview);
941 return it == views->end() ? NULL : it->second;
945 RenderView* RenderView::FromWebView(blink::WebView* webview) {
946 return RenderViewImpl::FromWebView(webview);
950 RenderViewImpl* RenderViewImpl::FromRoutingID(int32 routing_id) {
951 RoutingIDViewMap* views = g_routing_id_view_map.Pointer();
952 RoutingIDViewMap::iterator it = views->find(routing_id);
953 return it == views->end() ? NULL : it->second;
957 RenderView* RenderView::FromRoutingID(int routing_id) {
958 return RenderViewImpl::FromRoutingID(routing_id);
962 void RenderView::ForEach(RenderViewVisitor* visitor) {
963 ViewMap* views = g_view_map.Pointer();
964 for (ViewMap::iterator it = views->begin(); it != views->end(); ++it) {
965 if (!visitor->Visit(it->second))
971 RenderViewImpl* RenderViewImpl::Create(
973 const RendererPreferences& renderer_prefs,
974 const WebPreferences& webkit_prefs,
976 int32 main_frame_routing_id,
978 int64 session_storage_namespace_id,
979 const base::string16& frame_name,
980 bool is_renderer_created,
984 const blink::WebScreenInfo& screen_info,
985 unsigned int accessibility_mode,
986 bool allow_partial_swap) {
987 DCHECK(routing_id != MSG_ROUTING_NONE);
988 RenderViewImplParams params(
993 main_frame_routing_id,
995 session_storage_namespace_id,
1003 allow_partial_swap);
1004 RenderViewImpl* render_view = NULL;
1005 if (g_create_render_view_impl)
1006 render_view = g_create_render_view_impl(¶ms);
1008 render_view = new RenderViewImpl(¶ms);
1009 render_view->Initialize(¶ms);
1014 void RenderViewImpl::InstallCreateHook(
1015 RenderViewImpl* (*create_render_view_impl)(RenderViewImplParams*)) {
1016 CHECK(!g_create_render_view_impl);
1017 g_create_render_view_impl = create_render_view_impl;
1020 void RenderViewImpl::AddObserver(RenderViewObserver* observer) {
1021 observers_.AddObserver(observer);
1024 void RenderViewImpl::RemoveObserver(RenderViewObserver* observer) {
1025 observer->RenderViewGone();
1026 observers_.RemoveObserver(observer);
1029 blink::WebView* RenderViewImpl::webview() const {
1030 return static_cast<blink::WebView*>(webwidget());
1033 #if defined(ENABLE_PLUGINS)
1034 void RenderViewImpl::PepperInstanceCreated(
1035 PepperPluginInstanceImpl* instance) {
1036 active_pepper_instances_.insert(instance);
1039 void RenderViewImpl::PepperInstanceDeleted(
1040 PepperPluginInstanceImpl* instance) {
1041 active_pepper_instances_.erase(instance);
1043 if (pepper_last_mouse_event_target_ == instance)
1044 pepper_last_mouse_event_target_ = NULL;
1045 if (focused_pepper_plugin_ == instance)
1046 PepperFocusChanged(instance, false);
1049 void RenderViewImpl::PepperFocusChanged(PepperPluginInstanceImpl* instance,
1052 focused_pepper_plugin_ = instance;
1053 else if (focused_pepper_plugin_ == instance)
1054 focused_pepper_plugin_ = NULL;
1056 UpdateTextInputType();
1057 UpdateSelectionBounds();
1060 void RenderViewImpl::RegisterPluginDelegate(WebPluginDelegateProxy* delegate) {
1061 plugin_delegates_.insert(delegate);
1062 // If the renderer is visible, set initial visibility and focus state.
1064 #if defined(OS_MACOSX)
1065 delegate->SetContainerVisibility(true);
1066 if (webview() && webview()->isActive())
1067 delegate->SetWindowFocus(true);
1070 // Plugins start assuming the content has focus (so that they work in
1071 // environments where RenderView isn't hosting them), so we always have to
1072 // set the initial state. See webplugin_delegate_impl.h for details.
1073 delegate->SetContentAreaFocus(has_focus());
1076 void RenderViewImpl::UnregisterPluginDelegate(
1077 WebPluginDelegateProxy* delegate) {
1078 plugin_delegates_.erase(delegate);
1082 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1084 focused_plugin_id_ = plugin_id;
1086 focused_plugin_id_ = -1;
1090 #if defined(OS_MACOSX)
1091 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1092 Send(new ViewHostMsg_PluginFocusChanged(routing_id(), focused, plugin_id));
1095 void RenderViewImpl::StartPluginIme() {
1096 IPC::Message* msg = new ViewHostMsg_StartPluginIme(routing_id());
1097 // This message can be sent during event-handling, and needs to be delivered
1098 // within that context.
1099 msg->set_unblock(true);
1102 #endif // defined(OS_MACOSX)
1104 #endif // ENABLE_PLUGINS
1106 void RenderViewImpl::TransferActiveWheelFlingAnimation(
1107 const blink::WebActiveWheelFlingParameters& params) {
1109 webview()->transferActiveWheelFlingAnimation(params);
1112 bool RenderViewImpl::HasIMETextFocus() {
1113 return GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE;
1116 bool RenderViewImpl::OnMessageReceived(const IPC::Message& message) {
1117 WebFrame* main_frame = webview() ? webview()->mainFrame() : NULL;
1119 GetContentClient()->SetActiveURL(main_frame->document().url());
1121 ObserverListBase<RenderViewObserver>::Iterator it(observers_);
1122 RenderViewObserver* observer;
1123 while ((observer = it.GetNext()) != NULL)
1124 if (observer->OnMessageReceived(message))
1127 bool handled = true;
1128 bool msg_is_ok = true;
1129 IPC_BEGIN_MESSAGE_MAP_EX(RenderViewImpl, message, msg_is_ok)
1130 IPC_MESSAGE_HANDLER(InputMsg_Copy, OnCopy)
1131 IPC_MESSAGE_HANDLER(InputMsg_Cut, OnCut)
1132 IPC_MESSAGE_HANDLER(InputMsg_Delete, OnDelete)
1133 IPC_MESSAGE_HANDLER(InputMsg_ExecuteEditCommand, OnExecuteEditCommand)
1134 IPC_MESSAGE_HANDLER(InputMsg_MoveCaret, OnMoveCaret)
1135 IPC_MESSAGE_HANDLER(InputMsg_Paste, OnPaste)
1136 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle, OnPasteAndMatchStyle)
1137 IPC_MESSAGE_HANDLER(InputMsg_Redo, OnRedo)
1138 IPC_MESSAGE_HANDLER(InputMsg_Replace, OnReplace)
1139 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling, OnReplaceMisspelling)
1140 IPC_MESSAGE_HANDLER(InputMsg_ScrollFocusedEditableNodeIntoRect,
1141 OnScrollFocusedEditableNodeIntoRect)
1142 IPC_MESSAGE_HANDLER(InputMsg_SelectAll, OnSelectAll)
1143 IPC_MESSAGE_HANDLER(InputMsg_SelectRange, OnSelectRange)
1144 IPC_MESSAGE_HANDLER(InputMsg_SetEditCommandsForNextKeyEvent,
1145 OnSetEditCommandsForNextKeyEvent)
1146 IPC_MESSAGE_HANDLER(InputMsg_Undo, OnUndo)
1147 IPC_MESSAGE_HANDLER(InputMsg_Unselect, OnUnselect)
1148 IPC_MESSAGE_HANDLER(FrameMsg_Navigate, OnNavigate)
1149 IPC_MESSAGE_HANDLER(ViewMsg_Stop, OnStop)
1150 IPC_MESSAGE_HANDLER(ViewMsg_ReloadFrame, OnReloadFrame)
1151 IPC_MESSAGE_HANDLER(ViewMsg_SetName, OnSetName)
1152 IPC_MESSAGE_HANDLER(ViewMsg_SetEditableSelectionOffsets,
1153 OnSetEditableSelectionOffsets)
1154 IPC_MESSAGE_HANDLER(ViewMsg_SetCompositionFromExistingText,
1155 OnSetCompositionFromExistingText)
1156 IPC_MESSAGE_HANDLER(ViewMsg_ExtendSelectionAndDelete,
1157 OnExtendSelectionAndDelete)
1158 IPC_MESSAGE_HANDLER(ViewMsg_CopyImageAt, OnCopyImageAt)
1159 IPC_MESSAGE_HANDLER(ViewMsg_Find, OnFind)
1160 IPC_MESSAGE_HANDLER(ViewMsg_StopFinding, OnStopFinding)
1161 IPC_MESSAGE_HANDLER(ViewMsg_Zoom, OnZoom)
1162 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevel, OnSetZoomLevel)
1163 IPC_MESSAGE_HANDLER(ViewMsg_ZoomFactor, OnZoomFactor)
1164 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForLoadingURL,
1165 OnSetZoomLevelForLoadingURL)
1166 IPC_MESSAGE_HANDLER(ViewMsg_SetPageEncoding, OnSetPageEncoding)
1167 IPC_MESSAGE_HANDLER(ViewMsg_ResetPageEncodingToDefault,
1168 OnResetPageEncodingToDefault)
1169 IPC_MESSAGE_HANDLER(ViewMsg_ScriptEvalRequest, OnScriptEvalRequest)
1170 IPC_MESSAGE_HANDLER(ViewMsg_PostMessageEvent, OnPostMessageEvent)
1171 IPC_MESSAGE_HANDLER(ViewMsg_CSSInsertRequest, OnCSSInsertRequest)
1172 IPC_MESSAGE_HANDLER(DragMsg_TargetDragEnter, OnDragTargetDragEnter)
1173 IPC_MESSAGE_HANDLER(DragMsg_TargetDragOver, OnDragTargetDragOver)
1174 IPC_MESSAGE_HANDLER(DragMsg_TargetDragLeave, OnDragTargetDragLeave)
1175 IPC_MESSAGE_HANDLER(DragMsg_TargetDrop, OnDragTargetDrop)
1176 IPC_MESSAGE_HANDLER(DragMsg_SourceEndedOrMoved, OnDragSourceEndedOrMoved)
1177 IPC_MESSAGE_HANDLER(DragMsg_SourceSystemDragEnded,
1178 OnDragSourceSystemDragEnded)
1179 IPC_MESSAGE_HANDLER(ViewMsg_AllowBindings, OnAllowBindings)
1180 IPC_MESSAGE_HANDLER(ViewMsg_SetInitialFocus, OnSetInitialFocus)
1181 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTargetURL_ACK, OnUpdateTargetURLAck)
1182 IPC_MESSAGE_HANDLER(ViewMsg_UpdateWebPreferences, OnUpdateWebPreferences)
1183 IPC_MESSAGE_HANDLER(ViewMsg_TimezoneChange, OnUpdateTimezone)
1184 IPC_MESSAGE_HANDLER(ViewMsg_EnumerateDirectoryResponse,
1185 OnEnumerateDirectoryResponse)
1186 IPC_MESSAGE_HANDLER(ViewMsg_RunFileChooserResponse, OnFileChooserResponse)
1187 IPC_MESSAGE_HANDLER(ViewMsg_ShouldClose, OnShouldClose)
1188 IPC_MESSAGE_HANDLER(ViewMsg_SuppressDialogsUntilSwapOut,
1189 OnSuppressDialogsUntilSwapOut)
1190 IPC_MESSAGE_HANDLER(ViewMsg_SwapOut, OnSwapOut)
1191 IPC_MESSAGE_HANDLER(ViewMsg_ClosePage, OnClosePage)
1192 IPC_MESSAGE_HANDLER(ViewMsg_ThemeChanged, OnThemeChanged)
1193 IPC_MESSAGE_HANDLER(ViewMsg_MoveOrResizeStarted, OnMoveOrResizeStarted)
1194 IPC_MESSAGE_HANDLER(ViewMsg_ClearFocusedNode, OnClearFocusedNode)
1195 IPC_MESSAGE_HANDLER(ViewMsg_SetBackground, OnSetBackground)
1196 IPC_MESSAGE_HANDLER(ViewMsg_EnablePreferredSizeChangedMode,
1197 OnEnablePreferredSizeChangedMode)
1198 IPC_MESSAGE_HANDLER(ViewMsg_EnableAutoResize, OnEnableAutoResize)
1199 IPC_MESSAGE_HANDLER(ViewMsg_DisableAutoResize, OnDisableAutoResize)
1200 IPC_MESSAGE_HANDLER(ViewMsg_DisableScrollbarsForSmallWindows,
1201 OnDisableScrollbarsForSmallWindows)
1202 IPC_MESSAGE_HANDLER(ViewMsg_SetRendererPrefs, OnSetRendererPrefs)
1203 IPC_MESSAGE_HANDLER(ViewMsg_MediaPlayerActionAt, OnMediaPlayerActionAt)
1204 IPC_MESSAGE_HANDLER(ViewMsg_OrientationChangeEvent,
1205 OnOrientationChangeEvent)
1206 IPC_MESSAGE_HANDLER(ViewMsg_PluginActionAt, OnPluginActionAt)
1207 IPC_MESSAGE_HANDLER(ViewMsg_SetActive, OnSetActive)
1208 IPC_MESSAGE_HANDLER(ViewMsg_GetAllSavableResourceLinksForCurrentPage,
1209 OnGetAllSavableResourceLinksForCurrentPage)
1210 IPC_MESSAGE_HANDLER(
1211 ViewMsg_GetSerializedHtmlDataForCurrentPageWithLocalLinks,
1212 OnGetSerializedHtmlDataForCurrentPageWithLocalLinks)
1213 IPC_MESSAGE_HANDLER(ViewMsg_ShowContextMenu, OnShowContextMenu)
1214 // TODO(viettrungluu): Move to a separate message filter.
1215 IPC_MESSAGE_HANDLER(ViewMsg_SetHistoryLengthAndPrune,
1216 OnSetHistoryLengthAndPrune)
1217 IPC_MESSAGE_HANDLER(ViewMsg_EnableViewSourceMode, OnEnableViewSourceMode)
1218 IPC_MESSAGE_HANDLER(ViewMsg_SetAccessibilityMode, OnSetAccessibilityMode)
1219 IPC_MESSAGE_HANDLER(ViewMsg_DisownOpener, OnDisownOpener)
1220 IPC_MESSAGE_HANDLER(ViewMsg_ReleaseDisambiguationPopupDIB,
1221 OnReleaseDisambiguationPopupDIB)
1222 IPC_MESSAGE_HANDLER(ViewMsg_WindowSnapshotCompleted,
1223 OnWindowSnapshotCompleted)
1224 #if defined(OS_ANDROID)
1225 IPC_MESSAGE_HANDLER(InputMsg_ActivateNearestFindResult,
1226 OnActivateNearestFindResult)
1227 IPC_MESSAGE_HANDLER(ViewMsg_FindMatchRects, OnFindMatchRects)
1228 IPC_MESSAGE_HANDLER(ViewMsg_SelectPopupMenuItems, OnSelectPopupMenuItems)
1229 IPC_MESSAGE_HANDLER(ViewMsg_UndoScrollFocusedEditableNodeIntoView,
1230 OnUndoScrollFocusedEditableNodeIntoRect)
1231 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTopControlsState,
1232 OnUpdateTopControlsState)
1233 IPC_MESSAGE_HANDLER(ViewMsg_PauseVideo, OnPauseVideo)
1234 IPC_MESSAGE_HANDLER(ViewMsg_ExtractSmartClipData, OnExtractSmartClipData)
1235 #elif defined(OS_MACOSX)
1236 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard, OnCopyToFindPboard)
1237 IPC_MESSAGE_HANDLER(ViewMsg_PluginImeCompositionCompleted,
1238 OnPluginImeCompositionCompleted)
1239 IPC_MESSAGE_HANDLER(ViewMsg_SelectPopupMenuItem, OnSelectPopupMenuItem)
1240 IPC_MESSAGE_HANDLER(ViewMsg_SetInLiveResize, OnSetInLiveResize)
1241 IPC_MESSAGE_HANDLER(ViewMsg_SetWindowVisibility, OnSetWindowVisibility)
1242 IPC_MESSAGE_HANDLER(ViewMsg_WindowFrameChanged, OnWindowFrameChanged)
1244 // Adding a new message? Add platform independent ones first, then put the
1245 // platform specific ones at the end.
1247 // Have the super handle all other messages.
1248 IPC_MESSAGE_UNHANDLED(handled = RenderWidget::OnMessageReceived(message))
1249 IPC_END_MESSAGE_MAP()
1252 // The message had a handler, but its deserialization failed.
1253 // Kill the renderer to avoid potential spoofing attacks.
1254 CHECK(false) << "Unable to deserialize message in RenderViewImpl.";
1260 void RenderViewImpl::OnNavigate(const FrameMsg_Navigate_Params& params) {
1261 FOR_EACH_OBSERVER(RenderViewObserver, observers_, Navigate(params.url));
1264 bool RenderViewImpl::IsBackForwardToStaleEntry(
1265 const FrameMsg_Navigate_Params& params,
1267 // Make sure this isn't a back/forward to an entry we have already cropped
1268 // or replaced from our history, before the browser knew about it. If so,
1269 // a new navigation has committed in the mean time, and we can ignore this.
1270 bool is_back_forward = !is_reload && params.page_state.IsValid();
1272 // Note: if the history_list_length_ is 0 for a back/forward, we must be
1273 // restoring from a previous session. We'll update our state in OnNavigate.
1274 if (!is_back_forward || history_list_length_ <= 0)
1277 DCHECK_EQ(static_cast<int>(history_page_ids_.size()), history_list_length_);
1279 // Check for whether the forward history has been cropped due to a recent
1280 // navigation the browser didn't know about.
1281 if (params.pending_history_list_offset >= history_list_length_)
1284 // Check for whether this entry has been replaced with a new one.
1285 int expected_page_id =
1286 history_page_ids_[params.pending_history_list_offset];
1287 if (expected_page_id > 0 && params.page_id != expected_page_id) {
1288 if (params.page_id < expected_page_id)
1291 // Otherwise we've removed an earlier entry and should have shifted all
1292 // entries left. For now, it's ok to lazily update the list.
1293 // TODO(creis): Notify all live renderers when we remove entries from
1294 // the front of the list, so that we don't hit this case.
1295 history_page_ids_[params.pending_history_list_offset] = params.page_id;
1301 // Stop loading the current page.
1302 void RenderViewImpl::OnStop() {
1304 webview()->mainFrame()->stopLoading();
1305 FOR_EACH_OBSERVER(RenderViewObserver, observers_, OnStop());
1306 main_render_frame_->OnStop();
1309 // Reload current focused frame.
1310 // E.g. called by right-clicking on the frame and picking "reload this frame".
1311 void RenderViewImpl::OnReloadFrame() {
1312 if (webview() && webview()->focusedFrame()) {
1313 // We always obey the cache (ignore_cache=false) here.
1314 // TODO(evanm): perhaps we could allow shift-clicking the menu item to do
1315 // a cache-ignoring reload of the frame.
1316 webview()->focusedFrame()->reload(false);
1320 void RenderViewImpl::OnCopyImageAt(int x, int y) {
1321 webview()->copyImageAt(WebPoint(x, y));
1324 void RenderViewImpl::OnUpdateTargetURLAck() {
1325 // Check if there is a targeturl waiting to be sent.
1326 if (target_url_status_ == TARGET_PENDING) {
1327 Send(new ViewHostMsg_UpdateTargetURL(routing_id_, page_id_,
1328 pending_target_url_));
1331 target_url_status_ = TARGET_NONE;
1334 void RenderViewImpl::OnCopy() {
1338 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1339 WebNode current_node = context_menu_node_.isNull() ?
1340 GetFocusedNode() : context_menu_node_;
1341 webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Copy"),
1345 void RenderViewImpl::OnCut() {
1349 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1350 webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Cut"),
1354 void RenderViewImpl::OnDelete() {
1358 webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Delete"),
1362 void RenderViewImpl::OnExecuteEditCommand(const std::string& name,
1363 const std::string& value) {
1364 if (!webview() || !webview()->focusedFrame())
1367 webview()->focusedFrame()->executeCommand(
1368 WebString::fromUTF8(name), WebString::fromUTF8(value));
1371 void RenderViewImpl::OnMoveCaret(const gfx::Point& point) {
1375 Send(new ViewHostMsg_MoveCaret_ACK(routing_id_));
1377 webview()->focusedFrame()->moveCaretSelection(point);
1380 void RenderViewImpl::OnPaste() {
1384 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1385 webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Paste"),
1389 void RenderViewImpl::OnPasteAndMatchStyle() {
1393 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1394 webview()->focusedFrame()->executeCommand(
1395 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedNode());
1398 void RenderViewImpl::OnRedo() {
1402 webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Redo"),
1406 void RenderViewImpl::OnReplace(const base::string16& text) {
1410 WebFrame* frame = webview()->focusedFrame();
1411 if (!frame->hasSelection())
1412 frame->selectWordAroundCaret();
1414 frame->replaceSelection(text);
1417 void RenderViewImpl::OnReplaceMisspelling(const base::string16& text) {
1421 WebFrame* frame = webview()->focusedFrame();
1422 if (!frame->hasSelection())
1425 frame->replaceMisspelledRange(text);
1428 void RenderViewImpl::OnScrollFocusedEditableNodeIntoRect(
1429 const gfx::Rect& rect) {
1430 blink::WebNode node = GetFocusedNode();
1431 if (!node.isNull()) {
1432 if (IsEditableNode(node)) {
1433 webview()->saveScrollAndScaleState();
1434 webview()->scrollFocusedNodeIntoRect(rect);
1439 void RenderViewImpl::OnSelectAll() {
1443 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1444 webview()->focusedFrame()->executeCommand(
1445 WebString::fromUTF8("SelectAll"), GetFocusedNode());
1448 void RenderViewImpl::OnSelectRange(const gfx::Point& start,
1449 const gfx::Point& end) {
1453 Send(new ViewHostMsg_SelectRange_ACK(routing_id_));
1455 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1456 webview()->focusedFrame()->selectRange(start, end);
1459 void RenderViewImpl::OnSetEditCommandsForNextKeyEvent(
1460 const EditCommands& edit_commands) {
1461 edit_commands_ = edit_commands;
1464 void RenderViewImpl::OnUndo() {
1468 webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Undo"),
1472 void RenderViewImpl::OnUnselect() {
1476 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1477 webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Unselect"),
1481 #if defined(OS_MACOSX)
1482 void RenderViewImpl::OnCopyToFindPboard() {
1486 // Since the find pasteboard supports only plain text, this can be simpler
1487 // than the |OnCopy()| case.
1488 WebFrame* frame = webview()->focusedFrame();
1489 if (frame->hasSelection()) {
1490 base::string16 selection = frame->selectionAsText();
1491 RenderThread::Get()->Send(
1492 new ClipboardHostMsg_FindPboardWriteStringAsync(selection));
1497 void RenderViewImpl::OnSetName(const std::string& name) {
1501 webview()->mainFrame()->setName(WebString::fromUTF8(name));
1504 void RenderViewImpl::OnSetEditableSelectionOffsets(int start, int end) {
1505 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1506 if (!ShouldHandleImeEvent())
1508 ImeEventGuard guard(this);
1509 webview()->setEditableSelectionOffsets(start, end);
1512 void RenderViewImpl::OnSetCompositionFromExistingText(
1514 const std::vector<blink::WebCompositionUnderline>& underlines) {
1515 if (!ShouldHandleImeEvent())
1517 ImeEventGuard guard(this);
1518 webview()->setCompositionFromExistingText(start, end, underlines);
1521 void RenderViewImpl::OnExtendSelectionAndDelete(int before, int after) {
1522 if (!ShouldHandleImeEvent())
1524 ImeEventGuard guard(this);
1525 webview()->extendSelectionAndDelete(before, after);
1528 void RenderViewImpl::OnSetHistoryLengthAndPrune(int history_length,
1529 int32 minimum_page_id) {
1530 DCHECK_GE(history_length, 0);
1531 DCHECK(history_list_offset_ == history_list_length_ - 1);
1532 DCHECK_GE(minimum_page_id, -1);
1534 // Generate the new list.
1535 std::vector<int32> new_history_page_ids(history_length, -1);
1536 for (size_t i = 0; i < history_page_ids_.size(); ++i) {
1537 if (minimum_page_id >= 0 && history_page_ids_[i] < minimum_page_id)
1539 new_history_page_ids.push_back(history_page_ids_[i]);
1541 new_history_page_ids.swap(history_page_ids_);
1544 history_list_length_ = history_page_ids_.size();
1545 history_list_offset_ = history_list_length_ - 1;
1549 void RenderViewImpl::OnSetInitialFocus(bool reverse) {
1552 webview()->setInitialFocus(reverse);
1555 #if defined(OS_MACOSX)
1556 void RenderViewImpl::OnSetInLiveResize(bool in_live_resize) {
1560 webview()->willStartLiveResize();
1562 webview()->willEndLiveResize();
1566 #if defined(OS_ANDROID)
1567 void RenderViewImpl::OnUndoScrollFocusedEditableNodeIntoRect() {
1568 const WebNode node = GetFocusedNode();
1569 if (!node.isNull() && IsEditableNode(node))
1570 webview()->restoreScrollAndScaleState();
1573 void RenderViewImpl::OnPauseVideo() {
1574 // Inform RendererMediaPlayerManager to release all video player resources.
1575 // If something is in progress the resource will not be freed, it will
1576 // only be freed once the tab is destroyed or if the user navigates away
1577 // via WebMediaPlayerAndroid::Destroy.
1578 media_player_manager_->ReleaseVideoResources();
1582 ///////////////////////////////////////////////////////////////////////////////
1584 // Tell the embedding application that the title of the active page has changed
1585 void RenderViewImpl::UpdateTitle(WebFrame* frame,
1586 const base::string16& title,
1587 WebTextDirection title_direction) {
1588 // Ignore all but top level navigations.
1589 if (frame->parent())
1592 base::debug::TraceLog::GetInstance()->UpdateProcessLabel(
1593 routing_id_, base::UTF16ToUTF8(title));
1595 base::string16 shortened_title = title.substr(0, kMaxTitleChars);
1596 Send(new ViewHostMsg_UpdateTitle(routing_id_, page_id_, shortened_title,
1600 void RenderViewImpl::UpdateEncoding(WebFrame* frame,
1601 const std::string& encoding_name) {
1602 // Only update main frame's encoding_name.
1603 if (webview()->mainFrame() == frame &&
1604 last_encoding_name_ != encoding_name) {
1605 // Save the encoding name for later comparing.
1606 last_encoding_name_ = encoding_name;
1608 Send(new ViewHostMsg_UpdateEncoding(routing_id_, last_encoding_name_));
1612 // Sends the last committed session history state to the browser so it will be
1613 // saved before we navigate to a new page. This must be called *before* the
1614 // page ID has been updated so we know what it was.
1615 void RenderViewImpl::UpdateSessionHistory(WebFrame* frame) {
1616 // If we have a valid page ID at this point, then it corresponds to the page
1617 // we are navigating away from. Otherwise, this is the first navigation, so
1618 // there is no past session history to record.
1622 const WebHistoryItem& item =
1623 webview()->mainFrame()->previousHistoryItem();
1624 SendUpdateState(item);
1627 void RenderViewImpl::SendUpdateState(const WebHistoryItem& item) {
1631 // Don't send state updates for kSwappedOutURL.
1632 if (item.urlString() == WebString::fromUTF8(kSwappedOutURL))
1635 Send(new ViewHostMsg_UpdateState(
1636 routing_id_, page_id_, HistoryItemToPageState(item)));
1639 void RenderViewImpl::OpenURL(WebFrame* frame,
1641 const Referrer& referrer,
1642 WebNavigationPolicy policy) {
1643 ViewHostMsg_OpenURL_Params params;
1645 params.referrer = referrer;
1646 params.disposition = NavigationPolicyToDisposition(policy);
1647 params.frame_id = frame->identifier();
1648 WebDataSource* ds = frame->provisionalDataSource();
1650 DocumentState* document_state = DocumentState::FromDataSource(ds);
1651 NavigationState* navigation_state = document_state->navigation_state();
1652 if (navigation_state->is_content_initiated()) {
1653 params.should_replace_current_entry = ds->replacesCurrentHistoryItem();
1655 // This is necessary to preserve the should_replace_current_entry value on
1656 // cross-process redirects, in the event it was set by a previous process.
1658 // TODO(davidben): Avoid this awkward duplication of state. See comment on
1659 // NavigationState::should_replace_current_entry().
1660 params.should_replace_current_entry =
1661 navigation_state->should_replace_current_entry();
1664 params.should_replace_current_entry = false;
1666 params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
1667 if (GetContentClient()->renderer()->AllowPopup())
1668 params.user_gesture = true;
1670 if (policy == blink::WebNavigationPolicyNewBackgroundTab ||
1671 policy == blink::WebNavigationPolicyNewForegroundTab ||
1672 policy == blink::WebNavigationPolicyNewWindow ||
1673 policy == blink::WebNavigationPolicyNewPopup) {
1674 WebUserGestureIndicator::consumeUserGesture();
1677 Send(new ViewHostMsg_OpenURL(routing_id_, params));
1680 // WebViewDelegate ------------------------------------------------------------
1682 void RenderViewImpl::LoadNavigationErrorPage(
1684 const WebURLRequest& failed_request,
1685 const WebURLError& error,
1687 std::string error_html;
1688 GetContentClient()->renderer()->GetNavigationErrorStrings(
1689 this, frame, failed_request, error, &error_html, NULL);
1691 frame->loadHTMLString(error_html,
1692 GURL(kUnreachableWebDataURL),
1693 error.unreachableURL,
1697 bool RenderViewImpl::RunJavaScriptMessage(JavaScriptMessageType type,
1698 const base::string16& message,
1699 const base::string16& default_value,
1700 const GURL& frame_url,
1701 base::string16* result) {
1702 // Don't allow further dialogs if we are waiting to swap out, since the
1703 // PageGroupLoadDeferrer in our stack prevents it.
1704 if (suppress_dialogs_until_swap_out_)
1707 bool success = false;
1708 base::string16 result_temp;
1710 result = &result_temp;
1712 SendAndRunNestedMessageLoop(new ViewHostMsg_RunJavaScriptMessage(
1713 routing_id_, message, default_value, frame_url, type, &success, result));
1717 bool RenderViewImpl::SendAndRunNestedMessageLoop(IPC::SyncMessage* message) {
1718 // Before WebKit asks us to show an alert (etc.), it takes care of doing the
1719 // equivalent of WebView::willEnterModalLoop. In the case of showModalDialog
1720 // it is particularly important that we do not call willEnterModalLoop as
1721 // that would defer resource loads for the dialog itself.
1722 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
1723 RenderThreadImpl::current()->DoNotNotifyWebKitOfModalLoop();
1725 message->EnableMessagePumping(); // Runs a nested message loop.
1726 return Send(message);
1729 void RenderViewImpl::GetWindowSnapshot(const WindowSnapshotCallback& callback) {
1730 int id = next_snapshot_id_++;
1731 pending_snapshots_.insert(std::make_pair(id, callback));
1732 ui::LatencyInfo latency_info;
1733 latency_info.AddLatencyNumber(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
1736 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1737 if (RenderWidgetCompositor* rwc = compositor()) {
1738 latency_info_swap_promise_monitor =
1739 rwc->CreateLatencyInfoSwapPromiseMonitor(&latency_info).Pass();
1741 latency_info_.push_back(latency_info);
1743 ScheduleCompositeWithForcedRedraw();
1746 void RenderViewImpl::OnWindowSnapshotCompleted(const int snapshot_id,
1747 const gfx::Size& size, const std::vector<unsigned char>& png) {
1749 // Any pending snapshots with a lower ID than the one received are considered
1750 // to be implicitly complete, and returned the same snapshot data.
1751 PendingSnapshotMap::iterator it = pending_snapshots_.begin();
1752 while(it != pending_snapshots_.end()) {
1753 if (it->first <= snapshot_id) {
1754 it->second.Run(size, png);
1755 pending_snapshots_.erase(it++);
1762 // blink::WebViewClient ------------------------------------------------------
1764 WebView* RenderViewImpl::createView(
1766 const WebURLRequest& request,
1767 const WebWindowFeatures& features,
1768 const WebString& frame_name,
1769 WebNavigationPolicy policy,
1770 bool suppress_opener) {
1771 ViewHostMsg_CreateWindow_Params params;
1772 params.opener_id = routing_id_;
1773 params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
1774 if (GetContentClient()->renderer()->AllowPopup())
1775 params.user_gesture = true;
1776 params.window_container_type = WindowFeaturesToContainerType(features);
1777 params.session_storage_namespace_id = session_storage_namespace_id_;
1778 if (frame_name != "_blank")
1779 params.frame_name = frame_name;
1780 params.opener_frame_id = creator->identifier();
1781 params.opener_url = creator->document().url();
1782 params.opener_top_level_frame_url = creator->top()->document().url();
1783 GURL security_url(creator->document().securityOrigin().toString().utf8());
1784 if (!security_url.is_valid())
1785 security_url = GURL();
1786 params.opener_security_origin = security_url;
1787 params.opener_suppressed = suppress_opener;
1788 params.disposition = NavigationPolicyToDisposition(policy);
1789 if (!request.isNull()) {
1790 params.target_url = request.url();
1791 params.referrer = GetReferrerFromRequest(creator, request);
1793 params.features = features;
1795 for (size_t i = 0; i < features.additionalFeatures.size(); ++i)
1796 params.additional_features.push_back(features.additionalFeatures[i]);
1798 int32 routing_id = MSG_ROUTING_NONE;
1799 int32 main_frame_routing_id = MSG_ROUTING_NONE;
1800 int32 surface_id = 0;
1801 int64 cloned_session_storage_namespace_id;
1803 RenderThread::Get()->Send(
1804 new ViewHostMsg_CreateWindow(params,
1806 &main_frame_routing_id,
1808 &cloned_session_storage_namespace_id));
1809 if (routing_id == MSG_ROUTING_NONE)
1812 WebUserGestureIndicator::consumeUserGesture();
1814 WebPreferences transferred_preferences = webkit_preferences_;
1816 // Unless accelerated compositing has been explicitly disabled from the
1817 // command line (e.g. via the blacklist or about:flags) re-enable it for
1818 // new views that get spawned by this view. This gets around the issue that
1819 // background extension pages disable accelerated compositing via web prefs
1820 // but can themselves spawn a visible render view which should be allowed
1821 // use gpu acceleration.
1822 if (!webkit_preferences_.accelerated_compositing_enabled) {
1823 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1824 if (!command_line.HasSwitch(switches::kDisableAcceleratedCompositing))
1825 transferred_preferences.accelerated_compositing_enabled = true;
1828 // The initial hidden state for the RenderViewImpl here has to match what the
1829 // browser will eventually decide for the given disposition. Since we have to
1830 // return from this call synchronously, we just have to make our best guess
1831 // and rely on the browser sending a WasHidden / WasShown message if it
1833 RenderViewImpl* view = RenderViewImpl::Create(
1835 renderer_preferences_,
1836 transferred_preferences,
1838 main_frame_routing_id,
1840 cloned_session_storage_namespace_id,
1841 base::string16(), // WebCore will take care of setting the correct name.
1842 true, // is_renderer_created
1843 false, // swapped_out
1844 params.disposition == NEW_BACKGROUND_TAB, // hidden
1847 accessibility_mode_,
1848 allow_partial_swap_);
1849 view->opened_by_user_gesture_ = params.user_gesture;
1851 // Record whether the creator frame is trying to suppress the opener field.
1852 view->opener_suppressed_ = params.opener_suppressed;
1854 return view->webview();
1857 WebWidget* RenderViewImpl::createPopupMenu(blink::WebPopupType popup_type) {
1858 RenderWidget* widget =
1859 RenderWidget::Create(routing_id_, popup_type, screen_info_);
1860 if (screen_metrics_emulator_) {
1861 widget->SetPopupOriginAdjustmentsForEmulation(
1862 screen_metrics_emulator_.get());
1864 return widget->webwidget();
1867 WebExternalPopupMenu* RenderViewImpl::createExternalPopupMenu(
1868 const WebPopupMenuInfo& popup_menu_info,
1869 WebExternalPopupMenuClient* popup_menu_client) {
1870 // An IPC message is sent to the browser to build and display the actual
1871 // popup. The user could have time to click a different select by the time
1872 // the popup is shown. In that case external_popup_menu_ is non NULL.
1873 // By returning NULL in that case, we instruct WebKit to cancel that new
1874 // popup. So from the user perspective, only the first one will show, and
1875 // will have to close the first one before another one can be shown.
1876 if (external_popup_menu_)
1878 external_popup_menu_.reset(
1879 new ExternalPopupMenu(this, popup_menu_info, popup_menu_client));
1880 if (screen_metrics_emulator_) {
1881 SetExternalPopupOriginAdjustmentsForEmulation(
1882 external_popup_menu_.get(), screen_metrics_emulator_.get());
1884 return external_popup_menu_.get();
1887 WebStorageNamespace* RenderViewImpl::createSessionStorageNamespace() {
1888 CHECK(session_storage_namespace_id_ != kInvalidSessionStorageNamespaceId);
1889 return new WebStorageNamespaceImpl(session_storage_namespace_id_);
1892 bool RenderViewImpl::shouldReportDetailedMessageForSource(
1893 const WebString& source) {
1894 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
1898 void RenderViewImpl::didAddMessageToConsole(
1899 const WebConsoleMessage& message, const WebString& source_name,
1900 unsigned source_line, const WebString& stack_trace) {
1901 logging::LogSeverity log_severity = logging::LOG_VERBOSE;
1902 switch (message.level) {
1903 case WebConsoleMessage::LevelDebug:
1904 log_severity = logging::LOG_VERBOSE;
1906 case WebConsoleMessage::LevelLog:
1907 case WebConsoleMessage::LevelInfo:
1908 log_severity = logging::LOG_INFO;
1910 case WebConsoleMessage::LevelWarning:
1911 log_severity = logging::LOG_WARNING;
1913 case WebConsoleMessage::LevelError:
1914 log_severity = logging::LOG_ERROR;
1920 if (shouldReportDetailedMessageForSource(source_name)) {
1924 DetailedConsoleMessageAdded(message.text,
1928 static_cast<int32>(log_severity)));
1931 Send(new ViewHostMsg_AddMessageToConsole(routing_id_,
1932 static_cast<int32>(log_severity),
1934 static_cast<int32>(source_line),
1938 void RenderViewImpl::printPage(WebFrame* frame) {
1939 FOR_EACH_OBSERVER(RenderViewObserver, observers_,
1940 PrintPage(frame, handling_input_event_));
1943 blink::WebNotificationPresenter* RenderViewImpl::notificationPresenter() {
1944 return notification_provider_;
1947 bool RenderViewImpl::enumerateChosenDirectory(
1948 const WebString& path,
1949 WebFileChooserCompletion* chooser_completion) {
1950 int id = enumeration_completion_id_++;
1951 enumeration_completions_[id] = chooser_completion;
1952 return Send(new ViewHostMsg_EnumerateDirectory(
1955 base::FilePath::FromUTF16Unsafe(path)));
1958 void RenderViewImpl::initializeHelperPluginWebFrame(
1959 blink::WebHelperPlugin* plugin) {
1960 plugin->initializeFrame(main_render_frame_.get());
1963 void RenderViewImpl::didStartLoading(bool to_different_document) {
1967 void RenderViewImpl::didStartLoading() {
1969 DVLOG(1) << "didStartLoading called while loading";
1975 // Send the IPC message through the top-level frame.
1976 main_render_frame_->didStartLoading();
1978 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStartLoading());
1981 void RenderViewImpl::didStopLoading() {
1983 DVLOG(1) << "DidStopLoading called while not loading";
1987 is_loading_ = false;
1989 // NOTE: For now we're doing the safest thing, and sending out notification
1990 // when done loading. This currently isn't an issue as the favicon is only
1991 // displayed when done loading. Ideally we would send notification when
1992 // finished parsing the head, but webkit doesn't support that yet.
1993 // The feed discovery code would also benefit from access to the head.
1994 // NOTE: Sending of the IPC message happens through the top-level frame.
1995 main_render_frame_->didStopLoading();
1997 if (load_progress_tracker_ != NULL)
1998 load_progress_tracker_->DidStopLoading();
2000 DidStopLoadingIcons();
2002 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStopLoading());
2005 void RenderViewImpl::didChangeLoadProgress(WebFrame* frame,
2006 double load_progress) {
2007 if (load_progress_tracker_ != NULL)
2008 load_progress_tracker_->DidChangeLoadProgress(frame, load_progress);
2011 void RenderViewImpl::didCancelCompositionOnSelectionChange() {
2012 Send(new ViewHostMsg_ImeCancelComposition(routing_id()));
2015 void RenderViewImpl::didChangeSelection(bool is_empty_selection) {
2016 if (!handling_input_event_ && !handling_select_range_)
2019 if (is_empty_selection)
2020 selection_text_.clear();
2022 // UpdateTextInputType should be called before SyncSelectionIfRequired.
2023 // UpdateTextInputType may send TextInputTypeChanged to notify the focus
2024 // was changed, and SyncSelectionIfRequired may send SelectionChanged
2025 // to notify the selection was changed. Focus change should be notified
2026 // before selection change.
2027 UpdateTextInputType();
2028 SyncSelectionIfRequired();
2029 #if defined(OS_ANDROID)
2030 UpdateTextInputState(false, true);
2034 void RenderViewImpl::didExecuteCommand(const WebString& command_name) {
2035 const std::string& name = base::UTF16ToUTF8(command_name);
2036 if (StartsWithASCII(name, "Move", true) ||
2037 StartsWithASCII(name, "Insert", true) ||
2038 StartsWithASCII(name, "Delete", true))
2040 RenderThreadImpl::current()->RecordComputedAction(name);
2043 bool RenderViewImpl::handleCurrentKeyboardEvent() {
2044 if (edit_commands_.empty())
2047 WebFrame* frame = webview()->focusedFrame();
2051 EditCommands::iterator it = edit_commands_.begin();
2052 EditCommands::iterator end = edit_commands_.end();
2054 bool did_execute_command = false;
2055 for (; it != end; ++it) {
2056 // In gtk and cocoa, it's possible to bind multiple edit commands to one
2057 // key (but it's the exception). Once one edit command is not executed, it
2058 // seems safest to not execute the rest.
2059 if (!frame->executeCommand(WebString::fromUTF8(it->name),
2060 WebString::fromUTF8(it->value),
2063 did_execute_command = true;
2066 return did_execute_command;
2069 blink::WebColorChooser* RenderViewImpl::createColorChooser(
2070 blink::WebColorChooserClient* client,
2071 const blink::WebColor& initial_color,
2072 const blink::WebVector<blink::WebColorSuggestion>& suggestions) {
2073 RendererWebColorChooserImpl* color_chooser =
2074 new RendererWebColorChooserImpl(this, client);
2075 std::vector<content::ColorSuggestion> color_suggestions;
2076 for (size_t i = 0; i < suggestions.size(); i++) {
2077 color_suggestions.push_back(content::ColorSuggestion(suggestions[i]));
2079 color_chooser->Open(static_cast<SkColor>(initial_color), color_suggestions);
2080 return color_chooser;
2083 bool RenderViewImpl::runFileChooser(
2084 const blink::WebFileChooserParams& params,
2085 WebFileChooserCompletion* chooser_completion) {
2086 // Do not open the file dialog in a hidden RenderView.
2089 FileChooserParams ipc_params;
2090 if (params.directory)
2091 ipc_params.mode = FileChooserParams::UploadFolder;
2092 else if (params.multiSelect)
2093 ipc_params.mode = FileChooserParams::OpenMultiple;
2094 else if (params.saveAs)
2095 ipc_params.mode = FileChooserParams::Save;
2097 ipc_params.mode = FileChooserParams::Open;
2098 ipc_params.title = params.title;
2099 ipc_params.default_file_name =
2100 base::FilePath::FromUTF16Unsafe(params.initialValue);
2101 ipc_params.accept_types.reserve(params.acceptTypes.size());
2102 for (size_t i = 0; i < params.acceptTypes.size(); ++i)
2103 ipc_params.accept_types.push_back(params.acceptTypes[i]);
2104 #if defined(OS_ANDROID)
2105 ipc_params.capture = params.useMediaCapture;
2108 return ScheduleFileChooser(ipc_params, chooser_completion);
2111 void RenderViewImpl::runModalAlertDialog(WebFrame* frame,
2112 const WebString& message) {
2113 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT,
2116 frame->document().url(),
2120 bool RenderViewImpl::runModalConfirmDialog(WebFrame* frame,
2121 const WebString& message) {
2122 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM,
2125 frame->document().url(),
2129 bool RenderViewImpl::runModalPromptDialog(WebFrame* frame,
2130 const WebString& message,
2131 const WebString& default_value,
2132 WebString* actual_value) {
2133 base::string16 result;
2134 bool ok = RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT,
2137 frame->document().url(),
2140 actual_value->assign(result);
2144 bool RenderViewImpl::runModalBeforeUnloadDialog(
2145 WebFrame* frame, const WebString& message) {
2146 bool is_reload = false;
2147 WebDataSource* ds = frame->provisionalDataSource();
2149 is_reload = (ds->navigationType() == blink::WebNavigationTypeReload);
2150 return runModalBeforeUnloadDialog(frame, is_reload, message);
2153 bool RenderViewImpl::runModalBeforeUnloadDialog(
2154 WebFrame* frame, bool is_reload, const WebString& message) {
2155 // If we are swapping out, we have already run the beforeunload handler.
2156 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
2157 // at all, to avoid running it twice.
2158 if (is_swapped_out_)
2161 // Don't allow further dialogs if we are waiting to swap out, since the
2162 // PageGroupLoadDeferrer in our stack prevents it.
2163 if (suppress_dialogs_until_swap_out_)
2166 bool success = false;
2167 // This is an ignored return value, but is included so we can accept the same
2168 // response as RunJavaScriptMessage.
2169 base::string16 ignored_result;
2170 SendAndRunNestedMessageLoop(new ViewHostMsg_RunBeforeUnloadConfirm(
2171 routing_id_, frame->document().url(), message, is_reload,
2172 &success, &ignored_result));
2176 void RenderViewImpl::showValidationMessage(
2177 const blink::WebRect& anchor_in_root_view,
2178 const blink::WebString& main_text,
2179 const blink::WebString& sub_text,
2180 blink::WebTextDirection hint) {
2181 base::string16 wrapped_main_text = main_text;
2182 base::string16 wrapped_sub_text = sub_text;
2183 if (hint == blink::WebTextDirectionLeftToRight) {
2185 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_main_text);
2186 if (!wrapped_sub_text.empty()) {
2188 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_sub_text);
2190 } else if (hint == blink::WebTextDirectionRightToLeft
2191 && !base::i18n::IsRTL()) {
2192 base::i18n::WrapStringWithRTLFormatting(&wrapped_main_text);
2193 if (!wrapped_sub_text.empty()) {
2194 base::i18n::WrapStringWithRTLFormatting(&wrapped_sub_text);
2197 Send(new ViewHostMsg_ShowValidationMessage(
2198 routing_id(), anchor_in_root_view, wrapped_main_text, wrapped_sub_text));
2201 void RenderViewImpl::hideValidationMessage() {
2202 Send(new ViewHostMsg_HideValidationMessage(routing_id()));
2205 void RenderViewImpl::moveValidationMessage(
2206 const blink::WebRect& anchor_in_root_view) {
2207 Send(new ViewHostMsg_MoveValidationMessage(routing_id(),
2208 anchor_in_root_view));
2211 void RenderViewImpl::showContextMenu(
2212 WebFrame* frame, const blink::WebContextMenuData& data) {
2213 // TODO(jam): move this method to WebFrameClient.
2214 RenderFrameImpl* render_frame = RenderFrameImpl::FromWebFrame(frame);
2215 render_frame->showContextMenu(data);
2218 void RenderViewImpl::clearContextMenu() {
2219 context_menu_node_.reset();
2222 void RenderViewImpl::setStatusText(const WebString& text) {
2225 void RenderViewImpl::UpdateTargetURL(const GURL& url,
2226 const GURL& fallback_url) {
2227 GURL latest_url = url.is_empty() ? fallback_url : url;
2228 if (latest_url == target_url_)
2231 // Tell the browser to display a destination link.
2232 if (target_url_status_ == TARGET_INFLIGHT ||
2233 target_url_status_ == TARGET_PENDING) {
2234 // If we have a request in-flight, save the URL to be sent when we
2235 // receive an ACK to the in-flight request. We can happily overwrite
2236 // any existing pending sends.
2237 pending_target_url_ = latest_url;
2238 target_url_status_ = TARGET_PENDING;
2240 // URLs larger than |MaxURLChars()| cannot be sent through IPC -
2241 // see |ParamTraits<GURL>|.
2242 if (latest_url.possibly_invalid_spec().size() > GetMaxURLChars())
2243 latest_url = GURL();
2244 Send(new ViewHostMsg_UpdateTargetURL(routing_id_, page_id_, latest_url));
2245 target_url_ = latest_url;
2246 target_url_status_ = TARGET_INFLIGHT;
2250 gfx::RectF RenderViewImpl::ClientRectToPhysicalWindowRect(
2251 const gfx::RectF& rect) const {
2252 gfx::RectF window_rect = rect;
2253 window_rect.Scale(device_scale_factor_ * webview()->pageScaleFactor());
2257 void RenderViewImpl::StartNavStateSyncTimerIfNecessary() {
2258 // No need to update state if no page has committed yet.
2263 if (send_content_state_immediately_)
2265 else if (is_hidden())
2266 delay = kDelaySecondsForContentStateSyncHidden;
2268 delay = kDelaySecondsForContentStateSync;
2270 if (nav_state_sync_timer_.IsRunning()) {
2271 // The timer is already running. If the delay of the timer maches the amount
2272 // we want to delay by, then return. Otherwise stop the timer so that it
2273 // gets started with the right delay.
2274 if (nav_state_sync_timer_.GetCurrentDelay().InSeconds() == delay)
2276 nav_state_sync_timer_.Stop();
2279 nav_state_sync_timer_.Start(FROM_HERE, TimeDelta::FromSeconds(delay), this,
2280 &RenderViewImpl::SyncNavigationState);
2283 void RenderViewImpl::setMouseOverURL(const WebURL& url) {
2284 mouse_over_url_ = GURL(url);
2285 UpdateTargetURL(mouse_over_url_, focus_url_);
2288 void RenderViewImpl::setKeyboardFocusURL(const WebURL& url) {
2289 focus_url_ = GURL(url);
2290 UpdateTargetURL(focus_url_, mouse_over_url_);
2293 void RenderViewImpl::startDragging(WebFrame* frame,
2294 const WebDragData& data,
2295 WebDragOperationsMask mask,
2296 const WebImage& image,
2297 const WebPoint& webImageOffset) {
2298 DropData drop_data(DropDataBuilder::Build(data));
2299 drop_data.referrer_policy = frame->document().referrerPolicy();
2300 gfx::Vector2d imageOffset(webImageOffset.x, webImageOffset.y);
2301 Send(new DragHostMsg_StartDragging(routing_id_,
2304 image.getSkBitmap(),
2306 possible_drag_event_info_));
2309 bool RenderViewImpl::acceptsLoadDrops() {
2310 return renderer_preferences_.can_accept_load_drops;
2313 void RenderViewImpl::focusNext() {
2314 Send(new ViewHostMsg_TakeFocus(routing_id_, false));
2317 void RenderViewImpl::focusPrevious() {
2318 Send(new ViewHostMsg_TakeFocus(routing_id_, true));
2321 void RenderViewImpl::focusedNodeChanged(const WebNode& node) {
2322 Send(new ViewHostMsg_FocusedNodeChanged(routing_id_, IsEditableNode(node)));
2324 FOR_EACH_OBSERVER(RenderViewObserver, observers_, FocusedNodeChanged(node));
2327 void RenderViewImpl::numberOfWheelEventHandlersChanged(unsigned num_handlers) {
2328 Send(new ViewHostMsg_DidChangeNumWheelEvents(routing_id_, num_handlers));
2331 void RenderViewImpl::didUpdateLayout() {
2332 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidUpdateLayout());
2334 // We don't always want to set up a timer, only if we've been put in that
2335 // mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
2337 if (!send_preferred_size_changes_ || !webview())
2340 if (check_preferred_size_timer_.IsRunning())
2342 check_preferred_size_timer_.Start(FROM_HERE,
2343 TimeDelta::FromMilliseconds(0), this,
2344 &RenderViewImpl::CheckPreferredSize);
2347 void RenderViewImpl::navigateBackForwardSoon(int offset) {
2348 Send(new ViewHostMsg_GoToEntryAtOffset(routing_id_, offset));
2351 int RenderViewImpl::historyBackListCount() {
2352 return history_list_offset_ < 0 ? 0 : history_list_offset_;
2355 int RenderViewImpl::historyForwardListCount() {
2356 return history_list_length_ - historyBackListCount() - 1;
2359 void RenderViewImpl::postAccessibilityEvent(
2360 const WebAXObject& obj, blink::WebAXEvent event) {
2361 if (renderer_accessibility_) {
2362 renderer_accessibility_->HandleWebAccessibilityEvent(obj, event);
2366 void RenderViewImpl::didUpdateInspectorSetting(const WebString& key,
2367 const WebString& value) {
2368 Send(new ViewHostMsg_UpdateInspectorSetting(routing_id_,
2373 // blink::WebWidgetClient ----------------------------------------------------
2375 void RenderViewImpl::didFocus() {
2376 // TODO(jcivelli): when https://bugs.webkit.org/show_bug.cgi?id=33389 is fixed
2377 // we won't have to test for user gesture anymore and we can
2378 // move that code back to render_widget.cc
2379 if (WebUserGestureIndicator::isProcessingUserGesture() &&
2380 !RenderThreadImpl::current()->layout_test_mode()) {
2381 Send(new ViewHostMsg_Focus(routing_id_));
2385 void RenderViewImpl::didBlur() {
2386 // TODO(jcivelli): see TODO above in didFocus().
2387 if (WebUserGestureIndicator::isProcessingUserGesture() &&
2388 !RenderThreadImpl::current()->layout_test_mode()) {
2389 Send(new ViewHostMsg_Blur(routing_id_));
2393 // We are supposed to get a single call to Show for a newly created RenderView
2394 // that was created via RenderViewImpl::CreateWebView. So, we wait until this
2395 // point to dispatch the ShowView message.
2397 // This method provides us with the information about how to display the newly
2398 // created RenderView (i.e., as a blocked popup or as a new tab).
2400 void RenderViewImpl::show(WebNavigationPolicy policy) {
2402 // When supports_multiple_windows is disabled, popups are reusing
2403 // the same view. In some scenarios, this makes WebKit to call show() twice.
2404 if (webkit_preferences_.supports_multiple_windows)
2405 NOTREACHED() << "received extraneous Show call";
2410 DCHECK(opener_id_ != MSG_ROUTING_NONE);
2412 // Force new windows to a popup if they were not opened with a user gesture.
2413 if (!opened_by_user_gesture_) {
2414 // We exempt background tabs for compat with older versions of Chrome.
2415 // TODO(darin): This seems bogus. These should have a user gesture, so
2416 // we probably don't need this check.
2417 if (policy != blink::WebNavigationPolicyNewBackgroundTab)
2418 policy = blink::WebNavigationPolicyNewPopup;
2421 // NOTE: initial_pos_ may still have its default values at this point, but
2422 // that's okay. It'll be ignored if disposition is not NEW_POPUP, or the
2423 // browser process will impose a default position otherwise.
2424 Send(new ViewHostMsg_ShowView(opener_id_, routing_id_,
2425 NavigationPolicyToDisposition(policy), initial_pos_,
2426 opened_by_user_gesture_));
2427 SetPendingWindowRect(initial_pos_);
2430 void RenderViewImpl::runModal() {
2431 DCHECK(did_show_) << "should already have shown the view";
2433 // Don't allow further dialogs if we are waiting to swap out, since the
2434 // PageGroupLoadDeferrer in our stack prevents it.
2435 if (suppress_dialogs_until_swap_out_)
2438 // We must keep WebKit's shared timer running in this case in order to allow
2439 // showModalDialog to function properly.
2441 // TODO(darin): WebKit should really be smarter about suppressing events and
2442 // timers so that we do not need to manage the shared timer in such a heavy
2445 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
2446 RenderThreadImpl::current()->DoNotSuspendWebKitSharedTimer();
2448 SendAndRunNestedMessageLoop(new ViewHostMsg_RunModal(
2449 routing_id_, opener_id_));
2452 bool RenderViewImpl::enterFullScreen() {
2453 Send(new ViewHostMsg_ToggleFullscreen(routing_id_, true));
2457 void RenderViewImpl::exitFullScreen() {
2458 Send(new ViewHostMsg_ToggleFullscreen(routing_id_, false));
2461 bool RenderViewImpl::requestPointerLock() {
2462 return mouse_lock_dispatcher_->LockMouse(webwidget_mouse_lock_target_.get());
2465 void RenderViewImpl::requestPointerUnlock() {
2466 mouse_lock_dispatcher_->UnlockMouse(webwidget_mouse_lock_target_.get());
2469 bool RenderViewImpl::isPointerLocked() {
2470 return mouse_lock_dispatcher_->IsMouseLockedTo(
2471 webwidget_mouse_lock_target_.get());
2474 void RenderViewImpl::didActivateCompositor(int input_handler_identifier) {
2475 #if !defined(OS_MACOSX) // many events are unhandled - http://crbug.com/138003
2476 InputHandlerManager* input_handler_manager =
2477 RenderThreadImpl::current()->input_handler_manager();
2478 if (input_handler_manager) {
2479 input_handler_manager->AddInputHandler(
2481 compositor_->GetInputHandler(),
2486 RenderWidget::didActivateCompositor(input_handler_identifier);
2489 void RenderViewImpl::didHandleGestureEvent(
2490 const WebGestureEvent& event,
2491 bool event_cancelled) {
2492 RenderWidget::didHandleGestureEvent(event, event_cancelled);
2494 if (event.type != blink::WebGestureEvent::GestureTap)
2497 blink::WebTextInputType text_input_type =
2498 GetWebView()->textInputInfo().type;
2500 Send(new ViewHostMsg_FocusedNodeTouched(
2501 routing_id(), text_input_type != blink::WebTextInputTypeNone));
2504 void RenderViewImpl::initializeLayerTreeView() {
2505 RenderWidget::initializeLayerTreeView();
2506 RenderWidgetCompositor* rwc = compositor();
2507 if (!rwc || !webview() || !webview()->devToolsAgent())
2509 webview()->devToolsAgent()->setLayerTreeId(rwc->GetLayerTreeId());
2512 // blink::WebFrameClient -----------------------------------------------------
2514 WebMediaPlayer* RenderViewImpl::createMediaPlayer(
2515 WebFrame* frame, const blink::WebURL& url, WebMediaPlayerClient* client) {
2520 blink::WebMediaPlayer* RenderViewImpl::CreateMediaPlayer(
2521 RenderFrame* render_frame,
2522 blink::WebFrame* frame,
2523 const blink::WebURL& url,
2524 blink::WebMediaPlayerClient* client) {
2526 RenderViewObserver, observers_, WillCreateMediaPlayer(frame, client));
2528 WebMediaPlayer* player = CreateWebMediaPlayerForMediaStream(frame, url,
2533 #if defined(OS_ANDROID)
2534 return CreateAndroidWebMediaPlayer(frame, url, client);
2536 scoped_refptr<media::AudioRendererSink> sink;
2537 if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableAudio)) {
2538 sink = RenderThreadImpl::current()->GetAudioRendererMixerManager()->
2539 CreateInput(routing_id_, render_frame->GetRoutingID());
2540 DVLOG(1) << "Using AudioRendererMixerManager-provided sink: " << sink.get();
2543 WebMediaPlayerParams params(
2544 base::Bind(&ContentRendererClient::DeferMediaLoad,
2545 base::Unretained(GetContentClient()->renderer()),
2546 static_cast<RenderFrame*>(render_frame)),
2548 return new WebMediaPlayerImpl(frame, client, AsWeakPtr(), params);
2549 #endif // defined(OS_ANDROID)
2552 void RenderViewImpl::didAccessInitialDocument(WebFrame* frame) {
2553 // Notify the browser process that it is no longer safe to show the pending
2554 // URL of the main frame, since a URL spoof is now possible.
2555 if (!frame->parent() && page_id_ == -1)
2556 Send(new ViewHostMsg_DidAccessInitialDocument(routing_id_));
2559 void RenderViewImpl::didDisownOpener(blink::WebFrame* frame) {
2560 // We only need to notify the browser if the active, top-level frame clears
2561 // its opener. We can ignore cases where a swapped out frame clears its
2562 // opener after hearing about it from the browser, and the browser does not
2563 // (yet) care about subframe openers.
2564 if (is_swapped_out_ || frame->parent())
2567 // Notify WebContents and all its swapped out RenderViews.
2568 Send(new ViewHostMsg_DidDisownOpener(routing_id_));
2571 void RenderViewImpl::frameDetached(WebFrame* frame) {
2572 // NOTE: We may get here for either the main frame or for subframes. The
2573 // RenderFrameImpl will be deleted immediately after this call for subframes
2574 // but not for the main frame, which is owned by |main_render_frame_|.
2576 FOR_EACH_OBSERVER(RenderViewObserver, observers_, FrameDetached(frame));
2579 void RenderViewImpl::willClose(WebFrame* frame) {
2580 FOR_EACH_OBSERVER(RenderViewObserver, observers_, FrameWillClose(frame));
2583 void RenderViewImpl::didMatchCSS(
2585 const WebVector<WebString>& newly_matching_selectors,
2586 const WebVector<WebString>& stopped_matching_selectors) {
2588 RenderViewObserver, observers_,
2589 DidMatchCSS(frame, newly_matching_selectors, stopped_matching_selectors));
2592 void RenderViewImpl::Repaint(const gfx::Size& size) {
2596 void RenderViewImpl::SetEditCommandForNextKeyEvent(const std::string& name,
2597 const std::string& value) {
2598 EditCommands edit_commands;
2599 edit_commands.push_back(EditCommand(name, value));
2600 OnSetEditCommandsForNextKeyEvent(edit_commands);
2603 void RenderViewImpl::ClearEditCommands() {
2604 edit_commands_.clear();
2607 SSLStatus RenderViewImpl::GetSSLStatusOfFrame(blink::WebFrame* frame) const {
2608 std::string security_info;
2609 if (frame && frame->dataSource())
2610 security_info = frame->dataSource()->response().securityInfo();
2612 SSLStatus ssl_status;
2613 DeserializeSecurityInfo(security_info,
2614 &ssl_status.cert_id,
2615 &ssl_status.cert_status,
2616 &ssl_status.security_bits,
2617 &ssl_status.connection_status,
2618 &ssl_status.signed_certificate_timestamp_ids);
2622 const std::string& RenderViewImpl::GetAcceptLanguages() const {
2623 return renderer_preferences_.accept_languages;
2626 WebNavigationPolicy RenderViewImpl::DecidePolicyForNavigation(
2627 RenderFrame* render_frame, WebFrame* frame,
2628 WebDataSource::ExtraData* extraData, const WebURLRequest& request,
2629 WebNavigationType type, WebNavigationPolicy default_policy,
2632 // The handlenavigation API is deprecated and will be removed once
2633 // crbug.com/325351 is resolved.
2634 if (request.url() != GURL(kSwappedOutURL) &&
2635 GetContentClient()->renderer()->HandleNavigation(
2637 static_cast<DocumentState*>(extraData),
2644 return blink::WebNavigationPolicyIgnore;
2648 Referrer referrer(GetReferrerFromRequest(frame, request));
2650 if (is_swapped_out_) {
2651 if (request.url() != GURL(kSwappedOutURL)) {
2652 // Targeted links may try to navigate a swapped out frame. Allow the
2653 // browser process to navigate the tab instead. Note that it is also
2654 // possible for non-targeted navigations (from this view) to arrive
2655 // here just after we are swapped out. It's ok to send them to the
2656 // browser, as long as they're for the top level frame.
2657 // TODO(creis): Ensure this supports targeted form submissions when
2658 // fixing http://crbug.com/101395.
2659 if (frame->parent() == NULL) {
2660 OpenURL(frame, request.url(), referrer, default_policy);
2661 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
2664 // We should otherwise ignore in-process iframe navigations, if they
2665 // arrive just after we are swapped out.
2666 return blink::WebNavigationPolicyIgnore;
2669 // Allow kSwappedOutURL to complete.
2670 return default_policy;
2673 // Webkit is asking whether to navigate to a new URL.
2674 // This is fine normally, except if we're showing UI from one security
2675 // context and they're trying to navigate to a different context.
2676 const GURL& url = request.url();
2678 // A content initiated navigation may have originated from a link-click,
2679 // script, drag-n-drop operation, etc.
2680 bool is_content_initiated = static_cast<DocumentState*>(extraData)->
2681 navigation_state()->is_content_initiated();
2684 // If --enable-strict-site-isolation or --site-per-process is enabled, send
2685 // all top-level navigations to the browser to let it swap processes when
2686 // crossing site boundaries. This is currently expected to break some script
2687 // calls and navigations, such as form submissions.
2688 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
2689 bool force_swap_due_to_flag =
2690 command_line.HasSwitch(switches::kEnableStrictSiteIsolation) ||
2691 command_line.HasSwitch(switches::kSitePerProcess);
2692 if (force_swap_due_to_flag &&
2693 !frame->parent() && (is_content_initiated || is_redirect)) {
2694 WebString origin_str = frame->document().securityOrigin().toString();
2695 GURL frame_url(origin_str.utf8().data());
2696 // TODO(cevans): revisit whether this site check is still necessary once
2697 // crbug.com/101395 is fixed.
2698 bool same_domain_or_host =
2699 net::registry_controlled_domains::SameDomainOrHost(
2702 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
2703 if (!same_domain_or_host || frame_url.scheme() != url.scheme()) {
2704 OpenURL(frame, url, referrer, default_policy);
2705 return blink::WebNavigationPolicyIgnore;
2709 // If the browser is interested, then give it a chance to look at the request.
2710 if (is_content_initiated) {
2711 bool is_form_post = ((type == blink::WebNavigationTypeFormSubmitted) ||
2712 (type == blink::WebNavigationTypeFormResubmitted)) &&
2713 EqualsASCII(request.httpMethod(), "POST");
2714 bool browser_handles_request =
2715 renderer_preferences_.browser_handles_non_local_top_level_requests &&
2716 IsNonLocalTopLevelNavigation(url, frame, type, is_form_post);
2717 if (!browser_handles_request) {
2718 browser_handles_request = IsTopLevelNavigation(frame) &&
2719 renderer_preferences_.browser_handles_all_top_level_requests;
2722 if (browser_handles_request) {
2723 // Reset these counters as the RenderView could be reused for the next
2726 last_page_id_sent_to_browser_ = -1;
2727 OpenURL(frame, url, referrer, default_policy);
2728 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
2732 // Use the frame's original request's URL rather than the document's URL for
2733 // subsequent checks. For a popup, the document's URL may become the opener
2734 // window's URL if the opener has called document.write().
2735 // See http://crbug.com/93517.
2736 GURL old_url(frame->dataSource()->request().url());
2738 // Detect when we're crossing a permission-based boundary (e.g. into or out of
2739 // an extension or app origin, leaving a WebUI page, etc). We only care about
2740 // top-level navigations (not iframes). But we sometimes navigate to
2741 // about:blank to clear a tab, and we want to still allow that.
2743 // Note: this is known to break POST submissions when crossing process
2744 // boundaries until http://crbug.com/101395 is fixed. This is better for
2745 // security than loading a WebUI, extension or app page in the wrong process.
2746 // POST requests don't work because this mechanism does not preserve form
2747 // POST data. We will need to send the request's httpBody data up to the
2748 // browser process, and issue a special POST navigation in WebKit (via
2749 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
2750 // for examples of how to send the httpBody data.
2751 if (!frame->parent() && is_content_initiated &&
2752 !url.SchemeIs(chrome::kAboutScheme)) {
2753 bool send_referrer = false;
2755 // All navigations to or from WebUI URLs or within WebUI-enabled
2756 // RenderProcesses must be handled by the browser process so that the
2757 // correct bindings and data sources can be registered.
2758 // Similarly, navigations to view-source URLs or within ViewSource mode
2759 // must be handled by the browser process (except for reloads - those are
2760 // safe to leave within the renderer).
2761 // Lastly, access to file:// URLs from non-file:// URL pages must be
2762 // handled by the browser so that ordinary renderer processes don't get
2763 // blessed with file permissions.
2764 int cumulative_bindings = RenderProcess::current()->GetEnabledBindings();
2765 bool is_initial_navigation = page_id_ == -1;
2766 bool should_fork = HasWebUIScheme(url) || HasWebUIScheme(old_url) ||
2767 (cumulative_bindings & BINDINGS_POLICY_WEB_UI) ||
2768 url.SchemeIs(kViewSourceScheme) ||
2769 (frame->isViewSourceModeEnabled() &&
2770 type != blink::WebNavigationTypeReload);
2772 if (!should_fork && url.SchemeIs(kFileScheme)) {
2773 // Fork non-file to file opens. Check the opener URL if this is the
2774 // initial navigation in a newly opened window.
2775 GURL source_url(old_url);
2776 if (is_initial_navigation && source_url.is_empty() && frame->opener())
2777 source_url = frame->opener()->top()->document().url();
2778 DCHECK(!source_url.is_empty());
2779 should_fork = !source_url.SchemeIs(kFileScheme);
2783 // Give the embedder a chance.
2784 should_fork = GetContentClient()->renderer()->ShouldFork(
2785 frame, url, request.httpMethod().utf8(), is_initial_navigation,
2786 is_redirect, &send_referrer);
2791 frame, url, send_referrer ? referrer : Referrer(), default_policy);
2792 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
2796 // Detect when a page is "forking" a new tab that can be safely rendered in
2797 // its own process. This is done by sites like Gmail that try to open links
2798 // in new windows without script connections back to the original page. We
2799 // treat such cases as browser navigations (in which we will create a new
2800 // renderer for a cross-site navigation), rather than WebKit navigations.
2802 // We use the following heuristic to decide whether to fork a new page in its
2804 // The parent page must open a new tab to about:blank, set the new tab's
2805 // window.opener to null, and then redirect the tab to a cross-site URL using
2808 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
2811 // Must start from a tab showing about:blank, which is later redirected.
2812 old_url == GURL(kAboutBlankURL) &&
2813 // Must be the first real navigation of the tab.
2814 historyBackListCount() < 1 &&
2815 historyForwardListCount() < 1 &&
2816 // The parent page must have set the child's window.opener to null before
2817 // redirecting to the desired URL.
2818 frame->opener() == NULL &&
2819 // Must be a top-level frame.
2820 frame->parent() == NULL &&
2821 // Must not have issued the request from this page.
2822 is_content_initiated &&
2823 // Must be targeted at the current tab.
2824 default_policy == blink::WebNavigationPolicyCurrentTab &&
2825 // Must be a JavaScript navigation, which appears as "other".
2826 type == blink::WebNavigationTypeOther;
2829 // Open the URL via the browser, not via WebKit.
2830 OpenURL(frame, url, Referrer(), default_policy);
2831 return blink::WebNavigationPolicyIgnore;
2834 return default_policy;
2837 void RenderViewImpl::willSendSubmitEvent(blink::WebFrame* frame,
2838 const blink::WebFormElement& form) {
2840 RenderViewObserver, observers_, WillSendSubmitEvent(frame, form));
2843 void RenderViewImpl::willSubmitForm(WebFrame* frame,
2844 const WebFormElement& form) {
2846 RenderViewObserver, observers_, WillSubmitForm(frame, form));
2849 void RenderViewImpl::didCreateDataSource(WebFrame* frame, WebDataSource* ds) {
2850 bool content_initiated = !pending_navigation_params_.get();
2852 // Make sure any previous redirect URLs end up in our new data source.
2853 if (pending_navigation_params_.get()) {
2854 for (std::vector<GURL>::const_iterator i =
2855 pending_navigation_params_->redirects.begin();
2856 i != pending_navigation_params_->redirects.end(); ++i) {
2857 ds->appendRedirect(*i);
2861 DocumentState* document_state = DocumentState::FromDataSource(ds);
2862 if (!document_state) {
2863 document_state = new DocumentState;
2864 ds->setExtraData(document_state);
2865 if (!content_initiated)
2866 PopulateDocumentStateFromPending(document_state);
2869 // Carry over the user agent override flag, if it exists.
2870 if (content_initiated && webview() && webview()->mainFrame() &&
2871 webview()->mainFrame()->dataSource()) {
2872 DocumentState* old_document_state =
2873 DocumentState::FromDataSource(webview()->mainFrame()->dataSource());
2874 if (old_document_state) {
2875 InternalDocumentStateData* internal_data =
2876 InternalDocumentStateData::FromDocumentState(document_state);
2877 InternalDocumentStateData* old_internal_data =
2878 InternalDocumentStateData::FromDocumentState(old_document_state);
2879 internal_data->set_is_overriding_user_agent(
2880 old_internal_data->is_overriding_user_agent());
2884 // The rest of RenderView assumes that a WebDataSource will always have a
2885 // non-null NavigationState.
2886 if (content_initiated) {
2887 document_state->set_navigation_state(
2888 NavigationState::CreateContentInitiated());
2890 document_state->set_navigation_state(CreateNavigationStateFromPending());
2891 pending_navigation_params_.reset();
2894 // DocumentState::referred_by_prefetcher_ is true if we are
2895 // navigating from a page that used prefetching using a link on that
2896 // page. We are early enough in the request process here that we
2897 // can still see the DocumentState of the previous page and set
2898 // this value appropriately.
2899 // TODO(gavinp): catch the important case of navigation in a new
2900 // renderer process.
2902 if (WebFrame* old_frame = webview()->mainFrame()) {
2903 const WebURLRequest& original_request = ds->originalRequest();
2904 const GURL referrer(
2905 original_request.httpHeaderField(WebString::fromUTF8("Referer")));
2906 if (!referrer.is_empty() &&
2907 DocumentState::FromDataSource(
2908 old_frame->dataSource())->was_prefetcher()) {
2909 for (; old_frame; old_frame = old_frame->traverseNext(false)) {
2910 WebDataSource* old_frame_ds = old_frame->dataSource();
2911 if (old_frame_ds && referrer == GURL(old_frame_ds->request().url())) {
2912 document_state->set_was_referred_by_prefetcher(true);
2920 if (content_initiated) {
2921 const WebURLRequest& request = ds->request();
2922 switch (request.cachePolicy()) {
2923 case WebURLRequest::UseProtocolCachePolicy: // normal load.
2924 document_state->set_load_type(DocumentState::LINK_LOAD_NORMAL);
2926 case WebURLRequest::ReloadIgnoringCacheData: // reload.
2927 document_state->set_load_type(DocumentState::LINK_LOAD_RELOAD);
2929 case WebURLRequest::ReturnCacheDataElseLoad: // allow stale data.
2930 document_state->set_load_type(
2931 DocumentState::LINK_LOAD_CACHE_STALE_OK);
2933 case WebURLRequest::ReturnCacheDataDontLoad: // Don't re-post.
2934 document_state->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY);
2940 RenderViewObserver, observers_, DidCreateDataSource(frame, ds));
2943 void RenderViewImpl::PopulateDocumentStateFromPending(
2944 DocumentState* document_state) {
2945 const FrameMsg_Navigate_Params& params = *pending_navigation_params_.get();
2946 document_state->set_request_time(params.request_time);
2948 InternalDocumentStateData* internal_data =
2949 InternalDocumentStateData::FromDocumentState(document_state);
2951 if (!params.url.SchemeIs(kJavaScriptScheme) &&
2952 params.navigation_type == FrameMsg_Navigate_Type::RESTORE) {
2953 // We're doing a load of a page that was restored from the last session. By
2954 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
2955 // can result in stale data for pages that are set to expire. We explicitly
2956 // override that by setting the policy here so that as necessary we load
2957 // from the network.
2959 // TODO(davidben): Remove this in favor of passing a cache policy to the
2960 // loadHistoryItem call in OnNavigate. That requires not overloading
2961 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
2962 // policy based on load type, etc".
2963 internal_data->set_cache_policy_override(
2964 WebURLRequest::UseProtocolCachePolicy);
2967 if (IsReload(params))
2968 document_state->set_load_type(DocumentState::RELOAD);
2969 else if (params.page_state.IsValid())
2970 document_state->set_load_type(DocumentState::HISTORY_LOAD);
2972 document_state->set_load_type(DocumentState::NORMAL_LOAD);
2974 internal_data->set_is_overriding_user_agent(params.is_overriding_user_agent);
2975 internal_data->set_must_reset_scroll_and_scale_state(
2976 params.navigation_type ==
2977 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
2978 document_state->set_can_load_local_resources(params.can_load_local_resources);
2981 NavigationState* RenderViewImpl::CreateNavigationStateFromPending() {
2982 const FrameMsg_Navigate_Params& params = *pending_navigation_params_.get();
2983 NavigationState* navigation_state = NULL;
2985 // A navigation resulting from loading a javascript URL should not be treated
2986 // as a browser initiated event. Instead, we want it to look as if the page
2987 // initiated any load resulting from JS execution.
2988 if (!params.url.SchemeIs(kJavaScriptScheme)) {
2989 navigation_state = NavigationState::CreateBrowserInitiated(
2991 params.pending_history_list_offset,
2992 params.should_clear_history_list,
2994 navigation_state->set_should_replace_current_entry(
2995 params.should_replace_current_entry);
2996 navigation_state->set_transferred_request_child_id(
2997 params.transferred_request_child_id);
2998 navigation_state->set_transferred_request_request_id(
2999 params.transferred_request_request_id);
3000 navigation_state->set_allow_download(params.allow_download);
3001 navigation_state->set_extra_headers(params.extra_headers);
3003 navigation_state = NavigationState::CreateContentInitiated();
3005 return navigation_state;
3008 void RenderViewImpl::ProcessViewLayoutFlags(const CommandLine& command_line) {
3009 bool enable_viewport =
3010 command_line.HasSwitch(switches::kEnableViewport) ||
3011 command_line.HasSwitch(switches::kEnableViewportMeta);
3013 // If viewport tag is enabled, then the WebKit side will take care
3014 // of setting the fixed layout size and page scale limits.
3015 if (enable_viewport)
3018 // When navigating to a new page, reset the page scale factor to be 1.0.
3019 webview()->setInitialPageScaleOverride(1.f);
3021 float maxPageScaleFactor =
3022 command_line.HasSwitch(switches::kEnablePinch) ? 4.f : 1.f ;
3023 webview()->setPageScaleFactorLimits(1, maxPageScaleFactor);
3026 // TODO(nasko): Remove this method once WebTestProxy in Blink is fixed.
3027 void RenderViewImpl::didStartProvisionalLoad(WebFrame* frame) {
3030 void RenderViewImpl::didFailProvisionalLoad(WebFrame* frame,
3031 const WebURLError& error) {
3032 // Notify the browser that we failed a provisional load with an error.
3034 // Note: It is important this notification occur before DidStopLoading so the
3035 // SSL manager can react to the provisional load failure before being
3036 // notified the load stopped.
3039 RenderViewObserver, observers_, DidFailProvisionalLoad(frame, error));
3042 void RenderViewImpl::didCommitProvisionalLoad(WebFrame* frame,
3043 bool is_new_navigation) {
3044 FOR_EACH_OBSERVER(RenderViewObserver, observers_,
3045 DidCommitProvisionalLoad(frame, is_new_navigation));
3047 // TODO(nasko): Transition this code to RenderFrameImpl, since g_view_map is
3048 // not accessible from there.
3049 if (!frame->parent()) { // Only for top frames.
3050 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
3051 if (render_thread_impl) { // Can be NULL in tests.
3052 render_thread_impl->histogram_customizer()->
3053 RenderViewNavigatedToHost(GURL(GetLoadingUrl(frame)).host(),
3054 g_view_map.Get().size());
3059 void RenderViewImpl::didClearWindowObject(WebFrame* frame, int world_id) {
3060 FOR_EACH_OBSERVER(RenderViewObserver, observers_,
3061 DidClearWindowObject(frame, world_id));
3063 // Only install controllers into the main world.
3067 if (enabled_bindings_& BINDINGS_POLICY_WEB_UI)
3068 WebUIExtension::Install(frame);
3070 if (enabled_bindings_ & BINDINGS_POLICY_DOM_AUTOMATION)
3071 DomAutomationController::Install(this, frame);
3073 if (enabled_bindings_ & BINDINGS_POLICY_STATS_COLLECTION)
3074 StatsCollectionController::Install(frame);
3076 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
3078 if (command_line.HasSwitch(switches::kEnableSkiaBenchmarking))
3079 SkiaBenchmarking::Install(frame);
3081 if (command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
3082 MemoryBenchmarkingExtension::Install(frame);
3085 void RenderViewImpl::didCreateDocumentElement(WebFrame* frame) {
3086 FOR_EACH_OBSERVER(RenderViewObserver, observers_,
3087 DidCreateDocumentElement(frame));
3090 void RenderViewImpl::didReceiveTitle(WebFrame* frame, const WebString& title,
3091 WebTextDirection direction) {
3092 UpdateTitle(frame, title, direction);
3094 // Also check whether we have new encoding name.
3095 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
3098 void RenderViewImpl::didChangeIcon(WebFrame* frame,
3099 WebIconURL::Type icon_type) {
3100 if (frame->parent())
3103 if (!TouchEnabled() && icon_type != WebIconURL::TypeFavicon)
3106 WebVector<WebIconURL> icon_urls = frame->iconURLs(icon_type);
3107 std::vector<FaviconURL> urls;
3108 for (size_t i = 0; i < icon_urls.size(); i++) {
3109 urls.push_back(FaviconURL(icon_urls[i].iconURL(),
3110 ToFaviconType(icon_urls[i].iconType())));
3112 SendUpdateFaviconURL(urls);
3115 void RenderViewImpl::didFinishDocumentLoad(WebFrame* frame) {
3116 FOR_EACH_OBSERVER(RenderViewObserver, observers_,
3117 DidFinishDocumentLoad(frame));
3120 void RenderViewImpl::didHandleOnloadEvents(WebFrame* frame) {
3121 if (webview()->mainFrame() == frame) {
3122 Send(new ViewHostMsg_DocumentOnLoadCompletedInMainFrame(routing_id_,
3127 void RenderViewImpl::didFailLoad(WebFrame* frame, const WebURLError& error) {
3128 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidFailLoad(frame, error));
3131 void RenderViewImpl::didFinishLoad(WebFrame* frame) {
3132 WebDataSource* ds = frame->dataSource();
3133 DocumentState* document_state = DocumentState::FromDataSource(ds);
3134 if (document_state->finish_load_time().is_null()) {
3135 if (!frame->parent()) {
3136 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
3137 TRACE_EVENT_SCOPE_PROCESS);
3139 document_state->set_finish_load_time(Time::Now());
3142 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidFinishLoad(frame));
3144 // Don't send this message while the subframe is swapped out.
3145 // TODO(creis): This whole method should move to RenderFrame.
3146 RenderFrameImpl* rf = RenderFrameImpl::FromWebFrame(frame);
3147 if (rf && rf->is_swapped_out())
3150 Send(new ViewHostMsg_DidFinishLoad(routing_id_,
3151 frame->identifier(),
3152 ds->request().url(),
3156 void RenderViewImpl::didNavigateWithinPage(
3158 bool is_new_navigation) {
3159 // TODO(nasko): Forward calls to the main RenderFrameImpl until all
3160 // callers of this method on RenderView are removed.
3161 main_render_frame_->didNavigateWithinPage(frame, is_new_navigation);
3164 void RenderViewImpl::didUpdateCurrentHistoryItem(WebFrame* frame) {
3165 StartNavStateSyncTimerIfNecessary();
3168 void RenderViewImpl::willSendRequest(WebFrame* frame,
3169 unsigned identifier,
3170 WebURLRequest& request,
3171 const WebURLResponse& redirect_response) {
3175 void RenderViewImpl::didReceiveResponse(
3176 WebFrame* frame, unsigned identifier, const WebURLResponse& response) {
3180 void RenderViewImpl::didFinishResourceLoad(
3181 WebFrame* frame, unsigned identifier) {
3182 InternalDocumentStateData* internal_data =
3183 InternalDocumentStateData::FromDataSource(frame->dataSource());
3184 if (!internal_data->use_error_page())
3187 // Do not show error page when DevTools is attached.
3188 if (devtools_agent_->IsAttached())
3191 // Display error page, if appropriate.
3192 std::string error_domain = "http";
3193 int http_status_code = internal_data->http_status_code();
3194 if (GetContentClient()->renderer()->HasErrorPage(
3195 http_status_code, &error_domain)) {
3197 error.unreachableURL = frame->document().url();
3198 error.domain = WebString::fromUTF8(error_domain);
3199 error.reason = http_status_code;
3200 LoadNavigationErrorPage(frame, frame->dataSource()->request(), error, true);
3204 void RenderViewImpl::didLoadResourceFromMemoryCache(
3205 WebFrame* frame, const WebURLRequest& request,
3206 const WebURLResponse& response) {
3210 void RenderViewImpl::didDisplayInsecureContent(WebFrame* frame) {
3214 void RenderViewImpl::didRunInsecureContent(
3215 WebFrame* frame, const WebSecurityOrigin& origin, const WebURL& target) {
3219 void RenderViewImpl::didExhaustMemoryAvailableForScript(WebFrame* frame) {
3223 void RenderViewImpl::didCreateScriptContext(WebFrame* frame,
3224 v8::Handle<v8::Context> context,
3225 int extension_group,
3230 void RenderViewImpl::willReleaseScriptContext(WebFrame* frame,
3231 v8::Handle<v8::Context> context,
3236 void RenderViewImpl::CheckPreferredSize() {
3237 // We don't always want to send the change messages over IPC, only if we've
3238 // been put in that mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
3240 if (!send_preferred_size_changes_ || !webview())
3243 gfx::Size size = webview()->contentsPreferredMinimumSize();
3245 // In the presence of zoom, these sizes are still reported as if unzoomed,
3246 // so we need to adjust.
3247 double zoom_factor = ZoomLevelToZoomFactor(webview()->zoomLevel());
3248 size.set_width(static_cast<int>(size.width() * zoom_factor));
3249 size.set_height(static_cast<int>(size.height() * zoom_factor));
3251 if (size == preferred_size_)
3254 preferred_size_ = size;
3255 Send(new ViewHostMsg_DidContentsPreferredSizeChange(routing_id_,
3259 BrowserPluginManager* RenderViewImpl::GetBrowserPluginManager() {
3260 if (!browser_plugin_manager_.get())
3261 browser_plugin_manager_ = BrowserPluginManager::Create(this);
3262 return browser_plugin_manager_.get();
3265 bool RenderViewImpl::InitializeMediaStreamClient() {
3266 if (media_stream_client_)
3269 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
3272 #if defined(OS_ANDROID)
3273 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableWebRTC))
3277 #if defined(ENABLE_WEBRTC)
3278 if (!media_stream_dispatcher_)
3279 media_stream_dispatcher_ = new MediaStreamDispatcher(this);
3281 MediaStreamImpl* media_stream_impl = new MediaStreamImpl(
3283 media_stream_dispatcher_,
3284 RenderThreadImpl::current()->GetMediaStreamDependencyFactory());
3285 media_stream_client_ = media_stream_impl;
3286 web_user_media_client_ = media_stream_impl;
3293 void RenderViewImpl::didChangeContentsSize(WebFrame* frame,
3294 const WebSize& size) {
3295 if (webview()->mainFrame() != frame)
3297 WebView* frameView = frame->view();
3301 bool has_horizontal_scrollbar = frame->hasHorizontalScrollbar();
3302 bool has_vertical_scrollbar = frame->hasVerticalScrollbar();
3304 if (has_horizontal_scrollbar != cached_has_main_frame_horizontal_scrollbar_ ||
3305 has_vertical_scrollbar != cached_has_main_frame_vertical_scrollbar_) {
3306 Send(new ViewHostMsg_DidChangeScrollbarsForMainFrame(
3307 routing_id_, has_horizontal_scrollbar, has_vertical_scrollbar));
3309 cached_has_main_frame_horizontal_scrollbar_ = has_horizontal_scrollbar;
3310 cached_has_main_frame_vertical_scrollbar_ = has_vertical_scrollbar;
3314 void RenderViewImpl::UpdateScrollState(WebFrame* frame) {
3315 WebSize offset = frame->scrollOffset();
3316 WebSize minimum_offset = frame->minimumScrollOffset();
3317 WebSize maximum_offset = frame->maximumScrollOffset();
3319 bool is_pinned_to_left = offset.width <= minimum_offset.width;
3320 bool is_pinned_to_right = offset.width >= maximum_offset.width;
3322 if (is_pinned_to_left != cached_is_main_frame_pinned_to_left_ ||
3323 is_pinned_to_right != cached_is_main_frame_pinned_to_right_) {
3324 Send(new ViewHostMsg_DidChangeScrollOffsetPinningForMainFrame(
3325 routing_id_, is_pinned_to_left, is_pinned_to_right));
3327 cached_is_main_frame_pinned_to_left_ = is_pinned_to_left;
3328 cached_is_main_frame_pinned_to_right_ = is_pinned_to_right;
3331 Send(new ViewHostMsg_DidChangeScrollOffset(routing_id_));
3334 void RenderViewImpl::didChangeScrollOffset(WebFrame* frame) {
3335 StartNavStateSyncTimerIfNecessary();
3337 if (webview()->mainFrame() == frame)
3338 UpdateScrollState(frame);
3341 RenderViewObserver, observers_, DidChangeScrollOffset(frame));
3344 void RenderViewImpl::willInsertBody(blink::WebFrame* frame) {
3348 void RenderViewImpl::didFirstVisuallyNonEmptyLayout(WebFrame* frame) {
3349 if (frame != webview()->mainFrame())
3352 InternalDocumentStateData* data =
3353 InternalDocumentStateData::FromDataSource(frame->dataSource());
3354 data->set_did_first_visually_non_empty_layout(true);
3356 #if defined(OS_ANDROID)
3357 // Update body background color if necessary.
3358 SkColor bg_color = webwidget_->backgroundColor();
3360 // If not initialized, default to white. Note that 0 is different from black
3361 // as black still has alpha 0xFF.
3363 bg_color = SK_ColorWHITE;
3365 if (bg_color != body_background_color_) {
3366 body_background_color_ = bg_color;
3367 Send(new ViewHostMsg_DidChangeBodyBackgroundColor(
3368 GetRoutingID(), bg_color));
3373 void RenderViewImpl::SendFindReply(int request_id,
3376 const WebRect& selection_rect,
3377 bool final_status_update) {
3378 Send(new ViewHostMsg_Find_Reply(routing_id_,
3383 final_status_update));
3386 void RenderViewImpl::reportFindInPageMatchCount(int request_id,
3388 bool final_update) {
3392 void RenderViewImpl::reportFindInPageSelection(int request_id,
3393 int active_match_ordinal,
3394 const WebRect& selection_rect) {
3398 void RenderViewImpl::requestStorageQuota(
3400 WebStorageQuotaType type,
3401 unsigned long long requested_size,
3402 blink::WebStorageQuotaCallbacks callbacks) {
3406 bool RenderViewImpl::willCheckAndDispatchMessageEvent(
3407 blink::WebFrame* sourceFrame,
3408 blink::WebFrame* targetFrame,
3409 blink::WebSecurityOrigin target_origin,
3410 blink::WebDOMMessageEvent event) {
3411 if (!is_swapped_out_)
3414 ViewMsg_PostMessage_Params params;
3415 params.data = event.data().toString();
3416 params.source_origin = event.origin();
3417 if (!target_origin.isNull())
3418 params.target_origin = target_origin.toString();
3420 blink::WebMessagePortChannelArray channels = event.releaseChannels();
3421 if (!channels.isEmpty()) {
3422 std::vector<int> message_port_ids(channels.size());
3423 // Extract the port IDs from the channel array.
3424 for (size_t i = 0; i < channels.size(); ++i) {
3425 WebMessagePortChannelImpl* webchannel =
3426 static_cast<WebMessagePortChannelImpl*>(channels[i]);
3427 message_port_ids[i] = webchannel->message_port_id();
3428 webchannel->QueueMessages();
3429 DCHECK_NE(message_port_ids[i], MSG_ROUTING_NONE);
3431 params.message_port_ids = message_port_ids;
3434 // Include the routing ID for the source frame (if one exists), which the
3435 // browser process will translate into the routing ID for the equivalent
3436 // frame in the target process.
3437 params.source_routing_id = MSG_ROUTING_NONE;
3439 RenderViewImpl* source_view = FromWebView(sourceFrame->view());
3441 params.source_routing_id = source_view->routing_id();
3444 Send(new ViewHostMsg_RouteMessageEvent(routing_id_, params));
3448 void RenderViewImpl::willOpenSocketStream(
3449 WebSocketStreamHandle* handle) {
3453 void RenderViewImpl::willStartUsingPeerConnectionHandler(
3454 blink::WebFrame* frame, blink::WebRTCPeerConnectionHandler* handler) {
3458 blink::WebString RenderViewImpl::acceptLanguages() {
3459 return WebString::fromUTF8(renderer_preferences_.accept_languages);
3462 blink::WebString RenderViewImpl::userAgentOverride(
3463 blink::WebFrame* frame,
3464 const blink::WebURL& url) {
3466 return blink::WebString();
3469 WebString RenderViewImpl::doNotTrackValue(WebFrame* frame) {
3471 return blink::WebString();
3474 bool RenderViewImpl::allowWebGL(WebFrame* frame, bool default_value) {
3479 void RenderViewImpl::didLoseWebGLContext(
3480 blink::WebFrame* frame,
3481 int arb_robustness_status_code) {
3485 // blink::WebPageSerializerClient implementation ------------------------------
3487 void RenderViewImpl::didSerializeDataForFrame(
3488 const WebURL& frame_url,
3489 const WebCString& data,
3490 WebPageSerializerClient::PageSerializationStatus status) {
3491 Send(new ViewHostMsg_SendSerializedHtmlData(
3495 static_cast<int32>(status)));
3498 // RenderView implementation ---------------------------------------------------
3500 bool RenderViewImpl::Send(IPC::Message* message) {
3501 return RenderWidget::Send(message);
3504 RenderFrame* RenderViewImpl::GetMainRenderFrame() {
3505 return main_render_frame_.get();
3508 int RenderViewImpl::GetRoutingID() const {
3512 int RenderViewImpl::GetPageId() const {
3516 gfx::Size RenderViewImpl::GetSize() const {
3520 WebPreferences& RenderViewImpl::GetWebkitPreferences() {
3521 return webkit_preferences_;
3524 void RenderViewImpl::SetWebkitPreferences(const WebPreferences& preferences) {
3525 OnUpdateWebPreferences(preferences);
3528 blink::WebView* RenderViewImpl::GetWebView() {
3532 blink::WebNode RenderViewImpl::GetFocusedNode() const {
3535 WebFrame* focused_frame = webview()->focusedFrame();
3536 if (focused_frame) {
3537 WebDocument doc = focused_frame->document();
3539 return doc.focusedNode();
3545 blink::WebNode RenderViewImpl::GetContextMenuNode() const {
3546 return context_menu_node_;
3549 bool RenderViewImpl::IsEditableNode(const WebNode& node) const {
3553 if (node.isContentEditable())
3556 if (node.isElementNode()) {
3557 const WebElement& element = node.toConst<WebElement>();
3558 if (element.isTextFormControlElement())
3561 // Also return true if it has an ARIA role of 'textbox'.
3562 for (unsigned i = 0; i < element.attributeCount(); ++i) {
3563 if (LowerCaseEqualsASCII(element.attributeLocalName(i), "role")) {
3564 if (LowerCaseEqualsASCII(element.attributeValue(i), "textbox"))
3574 void RenderViewImpl::EvaluateScript(const base::string16& frame_xpath,
3575 const base::string16& jscript,
3577 bool notify_result) {
3578 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
3579 v8::Handle<v8::Value> result;
3580 WebFrame* web_frame = GetChildFrame(frame_xpath);
3582 result = web_frame->executeScriptAndReturnValue(WebScriptSource(jscript));
3583 if (notify_result) {
3584 base::ListValue list;
3585 if (!result.IsEmpty() && web_frame) {
3586 v8::Local<v8::Context> context = web_frame->mainWorldScriptContext();
3587 v8::Context::Scope context_scope(context);
3588 V8ValueConverterImpl converter;
3589 converter.SetDateAllowed(true);
3590 converter.SetRegExpAllowed(true);
3591 base::Value* result_value = converter.FromV8Value(result, context);
3592 list.Set(0, result_value ? result_value : base::Value::CreateNullValue());
3594 list.Set(0, base::Value::CreateNullValue());
3596 Send(new ViewHostMsg_ScriptEvalResponse(routing_id_, id, list));
3600 bool RenderViewImpl::ShouldDisplayScrollbars(int width, int height) const {
3601 return (!send_preferred_size_changes_ ||
3602 (disable_scrollbars_size_limit_.width() <= width ||
3603 disable_scrollbars_size_limit_.height() <= height));
3606 int RenderViewImpl::GetEnabledBindings() const {
3607 return enabled_bindings_;
3610 bool RenderViewImpl::GetContentStateImmediately() const {
3611 return send_content_state_immediately_;
3614 float RenderViewImpl::GetFilteredTimePerFrame() const {
3615 return filtered_time_per_frame();
3618 blink::WebPageVisibilityState RenderViewImpl::GetVisibilityState() const {
3619 return visibilityState();
3622 void RenderViewImpl::RunModalAlertDialog(blink::WebFrame* frame,
3623 const blink::WebString& message) {
3624 return runModalAlertDialog(frame, message);
3627 void RenderViewImpl::DidStartLoading() {
3631 void RenderViewImpl::DidStopLoading() {
3635 void RenderViewImpl::DidPlay(blink::WebMediaPlayer* player) {
3636 Send(new ViewHostMsg_MediaPlayingNotification(routing_id_,
3637 reinterpret_cast<int64>(player),
3639 player->hasAudio()));
3642 void RenderViewImpl::DidPause(blink::WebMediaPlayer* player) {
3643 Send(new ViewHostMsg_MediaPausedNotification(
3644 routing_id_, reinterpret_cast<int64>(player)));
3647 void RenderViewImpl::PlayerGone(blink::WebMediaPlayer* player) {
3651 void RenderViewImpl::SyncNavigationState() {
3655 const WebHistoryItem& item = webview()->mainFrame()->currentHistoryItem();
3656 SendUpdateState(item);
3659 void RenderViewImpl::SyncSelectionIfRequired() {
3660 WebFrame* frame = webview()->focusedFrame();
3664 base::string16 text;
3667 #if defined(ENABLE_PLUGINS)
3668 if (focused_pepper_plugin_) {
3669 focused_pepper_plugin_->GetSurroundingText(&text, &range);
3670 offset = 0; // Pepper API does not support offset reporting.
3671 // TODO(kinaba): cut as needed.
3675 size_t location, length;
3676 if (!webview()->caretOrSelectionRange(&location, &length))
3679 range = gfx::Range(location, location + length);
3681 if (webview()->textInputInfo().type != blink::WebTextInputTypeNone) {
3682 // If current focused element is editable, we will send 100 more chars
3683 // before and after selection. It is for input method surrounding text
3685 if (location > kExtraCharsBeforeAndAfterSelection)
3686 offset = location - kExtraCharsBeforeAndAfterSelection;
3689 length = location + length - offset + kExtraCharsBeforeAndAfterSelection;
3690 WebRange webrange = WebRange::fromDocumentRange(frame, offset, length);
3691 if (!webrange.isNull())
3692 text = WebRange::fromDocumentRange(frame, offset, length).toPlainText();
3695 text = frame->selectionAsText();
3696 // http://crbug.com/101435
3697 // In some case, frame->selectionAsText() returned text's length is not
3698 // equal to the length returned from webview()->caretOrSelectionRange().
3699 // So we have to set the range according to text.length().
3700 range.set_end(range.start() + text.length());
3704 // Sometimes we get repeated didChangeSelection calls from webkit when
3705 // the selection hasn't actually changed. We don't want to report these
3706 // because it will cause us to continually claim the X clipboard.
3707 if (selection_text_offset_ != offset ||
3708 selection_range_ != range ||
3709 selection_text_ != text) {
3710 selection_text_ = text;
3711 selection_text_offset_ = offset;
3712 selection_range_ = range;
3713 Send(new ViewHostMsg_SelectionChanged(routing_id_, text, offset, range));
3715 UpdateSelectionBounds();
3718 GURL RenderViewImpl::GetLoadingUrl(blink::WebFrame* frame) const {
3719 WebDataSource* ds = frame->dataSource();
3720 if (ds->hasUnreachableURL())
3721 return ds->unreachableURL();
3723 const WebURLRequest& request = ds->request();
3724 return request.url();
3727 blink::WebPlugin* RenderViewImpl::GetWebPluginFromPluginDocument() {
3728 return webview()->mainFrame()->document().to<WebPluginDocument>().plugin();
3731 void RenderViewImpl::OnFind(int request_id,
3732 const base::string16& search_text,
3733 const WebFindOptions& options) {
3734 WebFrame* main_frame = webview()->mainFrame();
3736 // Check if the plugin still exists in the document.
3737 if (main_frame->document().isPluginDocument() &&
3738 GetWebPluginFromPluginDocument()) {
3739 if (options.findNext) {
3740 // Just navigate back/forward.
3741 GetWebPluginFromPluginDocument()->selectFindResult(options.forward);
3743 if (!GetWebPluginFromPluginDocument()->startFind(
3744 search_text, options.matchCase, request_id)) {
3745 // Send "no results".
3746 SendFindReply(request_id, 0, 0, gfx::Rect(), true);
3752 WebFrame* frame_after_main = main_frame->traverseNext(true);
3753 WebFrame* focused_frame = webview()->focusedFrame();
3754 WebFrame* search_frame = focused_frame; // start searching focused frame.
3756 bool multi_frame = (frame_after_main != main_frame);
3758 // If we have multiple frames, we don't want to wrap the search within the
3759 // frame, so we check here if we only have main_frame in the chain.
3760 bool wrap_within_frame = !multi_frame;
3762 WebRect selection_rect;
3763 bool result = false;
3765 // If something is selected when we start searching it means we cannot just
3766 // increment the current match ordinal; we need to re-generate it.
3767 WebRange current_selection = focused_frame->selectionRange();
3770 result = search_frame->find(
3771 request_id, search_text, options, wrap_within_frame, &selection_rect);
3774 // don't leave text selected as you move to the next frame.
3775 search_frame->executeCommand(WebString::fromUTF8("Unselect"),
3778 // Find the next frame, but skip the invisible ones.
3780 // What is the next frame to search? (we might be going backwards). Note
3781 // that we specify wrap=true so that search_frame never becomes NULL.
3782 search_frame = options.forward ?
3783 search_frame->traverseNext(true) :
3784 search_frame->traversePrevious(true);
3785 } while (!search_frame->hasVisibleContent() &&
3786 search_frame != focused_frame);
3788 // Make sure selection doesn't affect the search operation in new frame.
3789 search_frame->executeCommand(WebString::fromUTF8("Unselect"),
3792 // If we have multiple frames and we have wrapped back around to the
3793 // focused frame, we need to search it once more allowing wrap within
3794 // the frame, otherwise it will report 'no match' if the focused frame has
3795 // reported matches, but no frames after the focused_frame contain a
3796 // match for the search word(s).
3797 if (multi_frame && search_frame == focused_frame) {
3798 result = search_frame->find(
3799 request_id, search_text, options, true, // Force wrapping.
3804 webview()->setFocusedFrame(search_frame);
3805 } while (!result && search_frame != focused_frame);
3807 if (options.findNext && current_selection.isNull()) {
3808 // Force the main_frame to report the actual count.
3809 main_frame->increaseMatchCount(0, request_id);
3811 // If nothing is found, set result to "0 of 0", otherwise, set it to
3812 // "-1 of 1" to indicate that we found at least one item, but we don't know
3813 // yet what is active.
3814 int ordinal = result ? -1 : 0; // -1 here means, we might know more later.
3815 int match_count = result ? 1 : 0; // 1 here means possibly more coming.
3817 // If we find no matches then this will be our last status update.
3818 // Otherwise the scoping effort will send more results.
3819 bool final_status_update = !result;
3821 SendFindReply(request_id, match_count, ordinal, selection_rect,
3822 final_status_update);
3824 // Scoping effort begins, starting with the mainframe.
3825 search_frame = main_frame;
3827 main_frame->resetMatchCount();
3830 // Cancel all old scoping requests before starting a new one.
3831 search_frame->cancelPendingScopingEffort();
3833 // We don't start another scoping effort unless at least one match has
3836 // Start new scoping request. If the scoping function determines that it
3837 // needs to scope, it will defer until later.
3838 search_frame->scopeStringMatches(request_id,
3841 true); // reset the tickmarks
3844 // Iterate to the next frame. The frame will not necessarily scope, for
3845 // example if it is not visible.
3846 search_frame = search_frame->traverseNext(true);
3847 } while (search_frame != main_frame);
3851 void RenderViewImpl::OnStopFinding(StopFindAction action) {
3852 WebView* view = webview();
3856 WebDocument doc = view->mainFrame()->document();
3857 if (doc.isPluginDocument() && GetWebPluginFromPluginDocument()) {
3858 GetWebPluginFromPluginDocument()->stopFind();
3862 bool clear_selection = action == STOP_FIND_ACTION_CLEAR_SELECTION;
3863 if (clear_selection) {
3864 view->focusedFrame()->executeCommand(WebString::fromUTF8("Unselect"),
3868 WebFrame* frame = view->mainFrame();
3870 frame->stopFinding(clear_selection);
3871 frame = frame->traverseNext(false);
3874 if (action == STOP_FIND_ACTION_ACTIVATE_SELECTION) {
3875 WebFrame* focused_frame = view->focusedFrame();
3876 if (focused_frame) {
3877 WebDocument doc = focused_frame->document();
3878 if (!doc.isNull()) {
3879 WebNode node = doc.focusedNode();
3881 node.simulateClick();
3887 #if defined(OS_ANDROID)
3888 void RenderViewImpl::OnActivateNearestFindResult(int request_id,
3893 WebFrame* main_frame = webview()->mainFrame();
3894 WebRect selection_rect;
3895 int ordinal = main_frame->selectNearestFindMatch(WebFloatPoint(x, y),
3897 if (ordinal == -1) {
3898 // Something went wrong, so send a no-op reply (force the main_frame to
3899 // report the current match count) in case the host is waiting for a
3900 // response due to rate-limiting).
3901 main_frame->increaseMatchCount(0, request_id);
3905 SendFindReply(request_id,
3906 -1 /* number_of_matches */,
3909 true /* final_update */);
3912 void RenderViewImpl::OnFindMatchRects(int current_version) {
3916 WebFrame* main_frame = webview()->mainFrame();
3917 std::vector<gfx::RectF> match_rects;
3919 int rects_version = main_frame->findMatchMarkersVersion();
3920 if (current_version != rects_version) {
3921 WebVector<WebFloatRect> web_match_rects;
3922 main_frame->findMatchRects(web_match_rects);
3923 match_rects.reserve(web_match_rects.size());
3924 for (size_t i = 0; i < web_match_rects.size(); ++i)
3925 match_rects.push_back(gfx::RectF(web_match_rects[i]));
3928 gfx::RectF active_rect = main_frame->activeFindMatchRect();
3929 Send(new ViewHostMsg_FindMatchRects_Reply(routing_id_,
3936 void RenderViewImpl::OnZoom(PageZoom zoom) {
3937 if (!webview()) // Not sure if this can happen, but no harm in being safe.
3940 webview()->hidePopups();
3942 double old_zoom_level = webview()->zoomLevel();
3944 if (zoom == PAGE_ZOOM_RESET) {
3946 } else if (static_cast<int>(old_zoom_level) == old_zoom_level) {
3947 // Previous zoom level is a whole number, so just increment/decrement.
3948 zoom_level = old_zoom_level + zoom;
3950 // Either the user hit the zoom factor limit and thus the zoom level is now
3951 // not a whole number, or a plugin changed it to a custom value. We want
3952 // to go to the next whole number so that the user can always get back to
3953 // 100% with the keyboard/menu.
3954 if ((old_zoom_level > 1 && zoom > 0) ||
3955 (old_zoom_level < 1 && zoom < 0)) {
3956 zoom_level = static_cast<int>(old_zoom_level + zoom);
3958 // We're going towards 100%, so first go to the next whole number.
3959 zoom_level = static_cast<int>(old_zoom_level);
3962 webview()->setZoomLevel(zoom_level);
3966 void RenderViewImpl::OnZoomFactor(PageZoom zoom, int zoom_center_x,
3967 int zoom_center_y) {
3968 ZoomFactorHelper(zoom, zoom_center_x, zoom_center_y,
3969 kScalingIncrementForGesture);
3972 void RenderViewImpl::ZoomFactorHelper(PageZoom zoom,
3975 float scaling_increment) {
3976 if (!webview()) // Not sure if this can happen, but no harm in being safe.
3979 double old_page_scale_factor = webview()->pageScaleFactor();
3980 double page_scale_factor;
3981 if (zoom == PAGE_ZOOM_RESET) {
3982 page_scale_factor = 1.0;
3984 page_scale_factor = old_page_scale_factor +
3985 (zoom > 0 ? scaling_increment : -scaling_increment);
3987 if (page_scale_factor > 0) {
3988 webview()->setPageScaleFactor(page_scale_factor,
3989 WebPoint(zoom_center_x, zoom_center_y));
3993 void RenderViewImpl::OnSetZoomLevel(double zoom_level) {
3994 webview()->hidePopups();
3995 webview()->setZoomLevel(zoom_level);
3999 void RenderViewImpl::OnSetZoomLevelForLoadingURL(const GURL& url,
4000 double zoom_level) {
4001 #if !defined(OS_ANDROID)
4002 // On Android, page zoom isn't used, and in case of WebView, text zoom is used
4003 // for legacy WebView text scaling emulation. Thus, the code that resets
4004 // the zoom level from this map will be effectively resetting text zoom level.
4005 host_zoom_levels_[url] = zoom_level;
4009 void RenderViewImpl::OnSetPageEncoding(const std::string& encoding_name) {
4010 webview()->setPageEncoding(WebString::fromUTF8(encoding_name));
4013 void RenderViewImpl::OnResetPageEncodingToDefault() {
4014 WebString no_encoding;
4015 webview()->setPageEncoding(no_encoding);
4018 WebFrame* RenderViewImpl::GetChildFrame(const base::string16& xpath) const {
4020 return webview()->mainFrame();
4022 // xpath string can represent a frame deep down the tree (across multiple
4024 // Example, /html/body/table/tbody/tr/td/iframe\n/frameset/frame[0]
4025 // should break into 2 xpaths
4026 // /html/body/table/tbody/tr/td/iframe & /frameset/frame[0]
4027 std::vector<base::string16> xpaths;
4028 base::SplitString(xpath, '\n', &xpaths);
4030 WebFrame* frame = webview()->mainFrame();
4031 for (std::vector<base::string16>::const_iterator i = xpaths.begin();
4032 frame && i != xpaths.end(); ++i) {
4033 frame = frame->findChildByExpression(*i);
4039 void RenderViewImpl::OnScriptEvalRequest(const base::string16& frame_xpath,
4040 const base::string16& jscript,
4042 bool notify_result) {
4043 TRACE_EVENT_INSTANT0("test_tracing", "OnScriptEvalRequest",
4044 TRACE_EVENT_SCOPE_THREAD);
4045 EvaluateScript(frame_xpath, jscript, id, notify_result);
4048 void RenderViewImpl::OnPostMessageEvent(
4049 const ViewMsg_PostMessage_Params& params) {
4050 // TODO(nasko): Support sending to subframes.
4051 WebFrame* frame = webview()->mainFrame();
4053 // Find the source frame if it exists.
4054 WebFrame* source_frame = NULL;
4055 if (params.source_routing_id != MSG_ROUTING_NONE) {
4056 RenderViewImpl* source_view = FromRoutingID(params.source_routing_id);
4058 source_frame = source_view->webview()->mainFrame();
4061 // If the message contained MessagePorts, create the corresponding endpoints.
4062 DCHECK_EQ(params.message_port_ids.size(), params.new_routing_ids.size());
4063 blink::WebMessagePortChannelArray channels(params.message_port_ids.size());
4065 i < params.message_port_ids.size() && i < params.new_routing_ids.size();
4068 new WebMessagePortChannelImpl(params.new_routing_ids[i],
4069 params.message_port_ids[i],
4070 base::MessageLoopProxy::current().get());
4073 // Create an event with the message. The final parameter to initMessageEvent
4074 // is the last event ID, which is not used with postMessage.
4075 WebDOMEvent event = frame->document().createEvent("MessageEvent");
4076 WebDOMMessageEvent msg_event = event.to<WebDOMMessageEvent>();
4077 msg_event.initMessageEvent("message",
4078 // |canBubble| and |cancellable| are always false
4080 WebSerializedScriptValue::fromString(params.data),
4081 params.source_origin, source_frame, "", channels);
4083 // We must pass in the target_origin to do the security check on this side,
4084 // since it may have changed since the original postMessage call was made.
4085 WebSecurityOrigin target_origin;
4086 if (!params.target_origin.empty()) {
4088 WebSecurityOrigin::createFromString(WebString(params.target_origin));
4090 frame->dispatchMessageEventWithOriginCheck(target_origin, msg_event);
4093 void RenderViewImpl::OnCSSInsertRequest(const base::string16& frame_xpath,
4094 const std::string& css) {
4095 WebFrame* frame = GetChildFrame(frame_xpath);
4099 frame->document().insertStyleSheet(WebString::fromUTF8(css));
4102 void RenderViewImpl::OnAllowBindings(int enabled_bindings_flags) {
4103 if ((enabled_bindings_flags & BINDINGS_POLICY_WEB_UI) &&
4104 !(enabled_bindings_ & BINDINGS_POLICY_WEB_UI)) {
4105 new WebUIExtensionData(this);
4108 enabled_bindings_ |= enabled_bindings_flags;
4110 // Keep track of the total bindings accumulated in this process.
4111 RenderProcess::current()->AddBindings(enabled_bindings_flags);
4114 void RenderViewImpl::OnDragTargetDragEnter(const DropData& drop_data,
4115 const gfx::Point& client_point,
4116 const gfx::Point& screen_point,
4117 WebDragOperationsMask ops,
4118 int key_modifiers) {
4119 WebDragOperation operation = webview()->dragTargetDragEnter(
4120 DropDataToWebDragData(drop_data),
4126 Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
4129 void RenderViewImpl::OnDragTargetDragOver(const gfx::Point& client_point,
4130 const gfx::Point& screen_point,
4131 WebDragOperationsMask ops,
4132 int key_modifiers) {
4133 WebDragOperation operation = webview()->dragTargetDragOver(
4139 Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
4142 void RenderViewImpl::OnDragTargetDragLeave() {
4143 webview()->dragTargetDragLeave();
4146 void RenderViewImpl::OnDragTargetDrop(const gfx::Point& client_point,
4147 const gfx::Point& screen_point,
4148 int key_modifiers) {
4149 webview()->dragTargetDrop(client_point, screen_point, key_modifiers);
4151 Send(new DragHostMsg_TargetDrop_ACK(routing_id_));
4154 void RenderViewImpl::OnDragSourceEndedOrMoved(const gfx::Point& client_point,
4155 const gfx::Point& screen_point,
4157 WebDragOperation op) {
4159 webview()->dragSourceEndedAt(client_point, screen_point, op);
4161 webview()->dragSourceMovedTo(client_point, screen_point, op);
4165 void RenderViewImpl::OnDragSourceSystemDragEnded() {
4166 webview()->dragSourceSystemDragEnded();
4169 void RenderViewImpl::OnUpdateWebPreferences(const WebPreferences& prefs) {
4170 webkit_preferences_ = prefs;
4171 ApplyWebPreferences(webkit_preferences_, webview());
4174 void RenderViewImpl::OnUpdateTimezone() {
4176 NotifyTimezoneChange(webview()->mainFrame());
4179 void RenderViewImpl::OnEnumerateDirectoryResponse(
4181 const std::vector<base::FilePath>& paths) {
4182 if (!enumeration_completions_[id])
4185 WebVector<WebString> ws_file_names(paths.size());
4186 for (size_t i = 0; i < paths.size(); ++i)
4187 ws_file_names[i] = paths[i].AsUTF16Unsafe();
4189 enumeration_completions_[id]->didChooseFile(ws_file_names);
4190 enumeration_completions_.erase(id);
4193 void RenderViewImpl::OnFileChooserResponse(
4194 const std::vector<ui::SelectedFileInfo>& files) {
4195 // This could happen if we navigated to a different page before the user
4196 // closed the chooser.
4197 if (file_chooser_completions_.empty())
4200 // Convert Chrome's SelectedFileInfo list to WebKit's.
4201 WebVector<WebFileChooserCompletion::SelectedFileInfo> selected_files(
4203 for (size_t i = 0; i < files.size(); ++i) {
4204 WebFileChooserCompletion::SelectedFileInfo selected_file;
4205 selected_file.path = files[i].local_path.AsUTF16Unsafe();
4206 selected_file.displayName =
4207 base::FilePath(files[i].display_name).AsUTF16Unsafe();
4208 selected_files[i] = selected_file;
4211 if (file_chooser_completions_.front()->completion)
4212 file_chooser_completions_.front()->completion->didChooseFile(
4214 file_chooser_completions_.pop_front();
4216 // If there are more pending file chooser requests, schedule one now.
4217 if (!file_chooser_completions_.empty()) {
4218 Send(new ViewHostMsg_RunFileChooser(routing_id_,
4219 file_chooser_completions_.front()->params));
4223 void RenderViewImpl::OnEnableAutoResize(const gfx::Size& min_size,
4224 const gfx::Size& max_size) {
4225 DCHECK(disable_scrollbars_size_limit_.IsEmpty());
4228 auto_resize_mode_ = true;
4229 webview()->enableAutoResizeMode(min_size, max_size);
4232 void RenderViewImpl::OnDisableAutoResize(const gfx::Size& new_size) {
4233 DCHECK(disable_scrollbars_size_limit_.IsEmpty());
4236 auto_resize_mode_ = false;
4237 webview()->disableAutoResizeMode();
4239 if (!new_size.IsEmpty()) {
4241 physical_backing_size_,
4242 overdraw_bottom_height_,
4249 void RenderViewImpl::OnEnablePreferredSizeChangedMode() {
4250 if (send_preferred_size_changes_)
4252 send_preferred_size_changes_ = true;
4254 // Start off with an initial preferred size notification (in case
4255 // |didUpdateLayout| was already called).
4259 void RenderViewImpl::OnDisableScrollbarsForSmallWindows(
4260 const gfx::Size& disable_scrollbar_size_limit) {
4261 disable_scrollbars_size_limit_ = disable_scrollbar_size_limit;
4264 void RenderViewImpl::OnSetRendererPrefs(
4265 const RendererPreferences& renderer_prefs) {
4266 double old_zoom_level = renderer_preferences_.default_zoom_level;
4267 renderer_preferences_ = renderer_prefs;
4268 UpdateFontRenderingFromRendererPrefs();
4270 #if defined(USE_DEFAULT_RENDER_THEME) || defined(TOOLKIT_GTK)
4271 if (renderer_prefs.use_custom_colors) {
4272 WebColorName name = blink::WebColorWebkitFocusRingColor;
4273 blink::setNamedColors(&name, &renderer_prefs.focus_ring_color, 1);
4274 blink::setCaretBlinkInterval(renderer_prefs.caret_blink_interval);
4275 #if defined(TOOLKIT_GTK)
4276 ui::NativeTheme::instance()->SetScrollbarColors(
4277 renderer_prefs.thumb_inactive_color,
4278 renderer_prefs.thumb_active_color,
4279 renderer_prefs.track_color);
4280 #endif // defined(TOOLKIT_GTK)
4283 webview()->setSelectionColors(
4284 renderer_prefs.active_selection_bg_color,
4285 renderer_prefs.active_selection_fg_color,
4286 renderer_prefs.inactive_selection_bg_color,
4287 renderer_prefs.inactive_selection_fg_color);
4288 webview()->themeChanged();
4291 #endif // defined(USE_DEFAULT_RENDER_THEME) || defined(TOOLKIT_GTK)
4293 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
4294 RenderThreadImpl::current()->SetFlingCurveParameters(
4295 renderer_prefs.touchpad_fling_profile,
4296 renderer_prefs.touchscreen_fling_profile);
4298 // If the zoom level for this page matches the old zoom default, and this
4299 // is not a plugin, update the zoom level to match the new default.
4300 if (webview() && !webview()->mainFrame()->document().isPluginDocument() &&
4301 !ZoomValuesEqual(old_zoom_level,
4302 renderer_preferences_.default_zoom_level) &&
4303 ZoomValuesEqual(webview()->zoomLevel(), old_zoom_level)) {
4304 webview()->setZoomLevel(renderer_preferences_.default_zoom_level);
4309 void RenderViewImpl::OnMediaPlayerActionAt(const gfx::Point& location,
4310 const WebMediaPlayerAction& action) {
4312 webview()->performMediaPlayerAction(action, location);
4315 void RenderViewImpl::OnOrientationChangeEvent(int orientation) {
4316 // Screen has rotated. 0 = default (portrait), 90 = one turn right, and so on.
4317 FOR_EACH_OBSERVER(RenderViewObserver,
4319 OrientationChangeEvent(orientation));
4320 webview()->mainFrame()->sendOrientationChangeEvent(orientation);
4323 void RenderViewImpl::OnPluginActionAt(const gfx::Point& location,
4324 const WebPluginAction& action) {
4326 webview()->performPluginAction(action, location);
4329 void RenderViewImpl::OnGetAllSavableResourceLinksForCurrentPage(
4330 const GURL& page_url) {
4331 // Prepare list to storage all savable resource links.
4332 std::vector<GURL> resources_list;
4333 std::vector<GURL> referrer_urls_list;
4334 std::vector<blink::WebReferrerPolicy> referrer_policies_list;
4335 std::vector<GURL> frames_list;
4336 SavableResourcesResult result(&resources_list,
4337 &referrer_urls_list,
4338 &referrer_policies_list,
4341 // webkit/ doesn't know about Referrer.
4342 if (!GetAllSavableResourceLinksForCurrentPage(
4346 const_cast<const char**>(GetSavableSchemes()))) {
4347 // If something is wrong when collecting all savable resource links,
4348 // send empty list to embedder(browser) to tell it failed.
4349 referrer_urls_list.clear();
4350 referrer_policies_list.clear();
4351 resources_list.clear();
4352 frames_list.clear();
4355 std::vector<Referrer> referrers_list;
4356 CHECK_EQ(referrer_urls_list.size(), referrer_policies_list.size());
4357 for (unsigned i = 0; i < referrer_urls_list.size(); ++i) {
4358 referrers_list.push_back(
4359 Referrer(referrer_urls_list[i], referrer_policies_list[i]));
4362 // Send result of all savable resource links to embedder.
4363 Send(new ViewHostMsg_SendCurrentPageAllSavableResourceLinks(routing_id(),
4369 void RenderViewImpl::OnGetSerializedHtmlDataForCurrentPageWithLocalLinks(
4370 const std::vector<GURL>& links,
4371 const std::vector<base::FilePath>& local_paths,
4372 const base::FilePath& local_directory_name) {
4374 // Convert std::vector of GURLs to WebVector<WebURL>
4375 WebVector<WebURL> weburl_links(links);
4377 // Convert std::vector of base::FilePath to WebVector<WebString>
4378 WebVector<WebString> webstring_paths(local_paths.size());
4379 for (size_t i = 0; i < local_paths.size(); i++)
4380 webstring_paths[i] = local_paths[i].AsUTF16Unsafe();
4382 WebPageSerializer::serialize(webview()->mainFrame(), true, this, weburl_links,
4384 local_directory_name.AsUTF16Unsafe());
4387 void RenderViewImpl::OnShouldClose() {
4388 base::TimeTicks before_unload_start_time = base::TimeTicks::Now();
4389 bool should_close = webview()->dispatchBeforeUnloadEvent();
4390 base::TimeTicks before_unload_end_time = base::TimeTicks::Now();
4391 Send(new ViewHostMsg_ShouldClose_ACK(routing_id_, should_close,
4392 before_unload_start_time,
4393 before_unload_end_time));
4396 void RenderViewImpl::OnSuppressDialogsUntilSwapOut() {
4397 // Don't show any more dialogs until we finish OnSwapOut.
4398 suppress_dialogs_until_swap_out_ = true;
4401 void RenderViewImpl::OnSwapOut() {
4402 // Only run unload if we're not swapped out yet, but send the ack either way.
4403 if (!is_swapped_out_) {
4404 // Swap this RenderView out so the tab can navigate to a page rendered by a
4405 // different process. This involves running the unload handler and clearing
4406 // the page. Once WasSwappedOut is called, we also allow this process to
4407 // exit if there are no other active RenderViews in it.
4409 // Send an UpdateState message before we get swapped out.
4410 SyncNavigationState();
4412 // Synchronously run the unload handler before sending the ACK.
4413 webview()->dispatchUnloadEvent();
4415 // Swap out and stop sending any IPC messages that are not ACKs.
4416 SetSwappedOut(true);
4418 // Now that we're swapped out and filtering IPC messages, stop loading to
4419 // ensure that no other in-progress navigation continues. We do this here
4420 // to avoid sending a DidStopLoading message to the browser process.
4423 // Replace the page with a blank dummy URL. The unload handler will not be
4424 // run a second time, thanks to a check in FrameLoader::stopLoading.
4425 // TODO(creis): Need to add a better way to do this that avoids running the
4426 // beforeunload handler. For now, we just run it a second time silently.
4427 NavigateToSwappedOutURL(webview()->mainFrame());
4429 // Let WebKit know that this view is hidden so it can drop resources and
4430 // stop compositing.
4431 webview()->setVisibilityState(blink::WebPageVisibilityStateHidden, false);
4434 // It is now safe to show modal dialogs again.
4435 suppress_dialogs_until_swap_out_ = false;
4437 Send(new ViewHostMsg_SwapOut_ACK(routing_id_));
4440 void RenderViewImpl::NavigateToSwappedOutURL(blink::WebFrame* frame) {
4441 // We use loadRequest instead of loadHTMLString because the former commits
4442 // synchronously. Otherwise a new navigation can interrupt the navigation
4443 // to kSwappedOutURL. If that happens to be to the page we had been
4444 // showing, then WebKit will never send a commit and we'll be left spinning.
4445 // TODO(creis): Until we move this to RenderFrame, we may call this from a
4446 // swapped out RenderFrame while our own is_swapped_out_ is false.
4447 RenderFrameImpl* rf = RenderFrameImpl::FromWebFrame(frame);
4448 CHECK(is_swapped_out_ || rf->is_swapped_out());
4449 GURL swappedOutURL(kSwappedOutURL);
4450 WebURLRequest request(swappedOutURL);
4451 frame->loadRequest(request);
4454 void RenderViewImpl::OnClosePage() {
4455 FOR_EACH_OBSERVER(RenderViewObserver, observers_, ClosePage());
4456 // TODO(creis): We'd rather use webview()->Close() here, but that currently
4457 // sets the WebView's delegate_ to NULL, preventing any JavaScript dialogs
4458 // in the onunload handler from appearing. For now, we're bypassing that and
4459 // calling the FrameLoader's CloseURL method directly. This should be
4460 // revisited to avoid having two ways to close a page. Having a single way
4461 // to close that can run onunload is also useful for fixing
4462 // http://b/issue?id=753080.
4463 webview()->dispatchUnloadEvent();
4465 Send(new ViewHostMsg_ClosePage_ACK(routing_id_));
4468 void RenderViewImpl::OnThemeChanged() {
4469 #if defined(USE_AURA)
4470 // Aura doesn't care if we switch themes.
4471 #elif defined(OS_WIN)
4472 ui::NativeThemeWin::instance()->CloseHandles();
4474 webview()->themeChanged();
4475 #else // defined(OS_WIN)
4476 // TODO(port): we don't support theming on non-Windows platforms yet
4481 void RenderViewImpl::OnMoveOrResizeStarted() {
4483 webview()->hidePopups();
4486 void RenderViewImpl::OnResize(const ViewMsg_Resize_Params& params) {
4488 webview()->hidePopups();
4489 if (send_preferred_size_changes_) {
4490 webview()->mainFrame()->setCanHaveScrollbars(
4491 ShouldDisplayScrollbars(params.new_size.width(),
4492 params.new_size.height()));
4494 UpdateScrollState(webview()->mainFrame());
4497 RenderWidget::OnResize(params);
4500 void RenderViewImpl::DidInitiatePaint() {
4501 #if defined(ENABLE_PLUGINS)
4502 // Notify all instances that we painted. The same caveats apply as for
4503 // ViewFlushedPaint regarding instances closing themselves, so we take
4504 // similar precautions.
4505 PepperPluginSet plugins = active_pepper_instances_;
4506 for (PepperPluginSet::iterator i = plugins.begin(); i != plugins.end(); ++i) {
4507 if (active_pepper_instances_.find(*i) != active_pepper_instances_.end())
4508 (*i)->ViewInitiatedPaint();
4513 void RenderViewImpl::DidFlushPaint() {
4514 #if defined(ENABLE_PLUGINS)
4515 // Notify all instances that we flushed. This will call into the plugin, and
4516 // we it may ask to close itself as a result. This will, in turn, modify our
4517 // set, possibly invalidating the iterator. So we iterate on a copy that
4518 // won't change out from under us.
4519 PepperPluginSet plugins = active_pepper_instances_;
4520 for (PepperPluginSet::iterator i = plugins.begin(); i != plugins.end(); ++i) {
4521 // The copy above makes sure our iterator is never invalid if some plugins
4522 // are destroyed. But some plugin may decide to close all of its views in
4523 // response to a paint in one of them, so we need to make sure each one is
4524 // still "current" before using it.
4526 // It's possible that a plugin was destroyed, but another one was created
4527 // with the same address. In this case, we'll call ViewFlushedPaint on that
4528 // new plugin. But that's OK for this particular case since we're just
4529 // notifying all of our instances that the view flushed, and the new one is
4530 // one of our instances.
4532 // What about the case where a new one is created in a callback at a new
4533 // address and we don't issue the callback? We're still OK since this
4534 // callback is used for flush callbacks and we could not have possibly
4535 // started a new paint for the new plugin while processing a previous paint
4536 // for an existing one.
4537 if (active_pepper_instances_.find(*i) != active_pepper_instances_.end())
4538 (*i)->ViewFlushedPaint();
4542 // If the RenderWidget is closing down then early-exit, otherwise we'll crash.
4543 // See crbug.com/112921.
4547 WebFrame* main_frame = webview()->mainFrame();
4549 // If we have a provisional frame we are between the start and commit stages
4550 // of loading and we don't want to save stats.
4551 if (!main_frame->provisionalDataSource()) {
4552 WebDataSource* ds = main_frame->dataSource();
4553 DocumentState* document_state = DocumentState::FromDataSource(ds);
4554 InternalDocumentStateData* data =
4555 InternalDocumentStateData::FromDocumentState(document_state);
4556 if (data->did_first_visually_non_empty_layout() &&
4557 !data->did_first_visually_non_empty_paint()) {
4558 data->set_did_first_visually_non_empty_paint(true);
4559 Send(new ViewHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_,
4563 // TODO(jar): The following code should all be inside a method, probably in
4565 Time now = Time::Now();
4566 if (document_state->first_paint_time().is_null()) {
4567 document_state->set_first_paint_time(now);
4569 if (document_state->first_paint_after_load_time().is_null() &&
4570 !document_state->finish_load_time().is_null()) {
4571 document_state->set_first_paint_after_load_time(now);
4576 PepperPluginInstanceImpl* RenderViewImpl::GetBitmapForOptimizedPluginPaint(
4577 const gfx::Rect& paint_bounds,
4579 gfx::Rect* location,
4581 float* scale_factor) {
4582 #if defined(ENABLE_PLUGINS)
4583 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
4584 i != active_pepper_instances_.end(); ++i) {
4585 PepperPluginInstanceImpl* instance = *i;
4586 // In Flash fullscreen , the plugin contents should be painted onto the
4587 // fullscreen widget instead of the web page.
4588 if (!instance->FlashIsFullscreenOrPending() &&
4589 instance->GetBitmapForOptimizedPluginPaint(paint_bounds, dib, location,
4590 clip, scale_factor))
4597 gfx::Vector2d RenderViewImpl::GetScrollOffset() {
4598 WebSize scroll_offset = webview()->mainFrame()->scrollOffset();
4599 return gfx::Vector2d(scroll_offset.width, scroll_offset.height);
4602 void RenderViewImpl::OnClearFocusedNode() {
4604 webview()->clearFocusedNode();
4607 void RenderViewImpl::OnSetBackground(const SkBitmap& background) {
4609 webview()->setIsTransparent(!background.empty());
4611 compositor_->setHasTransparentBackground(!background.empty());
4613 SetBackground(background);
4616 void RenderViewImpl::OnSetAccessibilityMode(unsigned int new_mode) {
4617 if (accessibility_mode_ == new_mode)
4619 accessibility_mode_ = new_mode;
4620 if (renderer_accessibility_) {
4621 delete renderer_accessibility_;
4622 renderer_accessibility_ = NULL;
4624 if (accessibility_mode_ == AccessibilityModeOff)
4627 if (accessibility_mode_ & AccessibilityModeFlagPlatformFullTree)
4628 renderer_accessibility_ = new RendererAccessibilityComplete(this);
4629 #if !defined(OS_ANDROID)
4631 renderer_accessibility_ = new RendererAccessibilityFocusOnly(this);
4635 void RenderViewImpl::OnSetActive(bool active) {
4637 webview()->setIsActive(active);
4639 #if defined(ENABLE_PLUGINS) && defined(OS_MACOSX)
4640 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
4641 for (plugin_it = plugin_delegates_.begin();
4642 plugin_it != plugin_delegates_.end(); ++plugin_it) {
4643 (*plugin_it)->SetWindowFocus(active);
4648 #if defined(OS_MACOSX)
4649 void RenderViewImpl::OnSetWindowVisibility(bool visible) {
4650 #if defined(ENABLE_PLUGINS)
4651 // Inform plugins that their container has changed visibility.
4652 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
4653 for (plugin_it = plugin_delegates_.begin();
4654 plugin_it != plugin_delegates_.end(); ++plugin_it) {
4655 (*plugin_it)->SetContainerVisibility(visible);
4660 void RenderViewImpl::OnWindowFrameChanged(const gfx::Rect& window_frame,
4661 const gfx::Rect& view_frame) {
4662 #if defined(ENABLE_PLUGINS)
4663 // Inform plugins that their window's frame has changed.
4664 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
4665 for (plugin_it = plugin_delegates_.begin();
4666 plugin_it != plugin_delegates_.end(); ++plugin_it) {
4667 (*plugin_it)->WindowFrameChanged(window_frame, view_frame);
4672 void RenderViewImpl::OnPluginImeCompositionCompleted(const base::string16& text,
4674 // WebPluginDelegateProxy is responsible for figuring out if this event
4675 // applies to it or not, so inform all the delegates.
4676 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
4677 for (plugin_it = plugin_delegates_.begin();
4678 plugin_it != plugin_delegates_.end(); ++plugin_it) {
4679 (*plugin_it)->ImeCompositionCompleted(text, plugin_id);
4684 void RenderViewImpl::Close() {
4685 // We need to grab a pointer to the doomed WebView before we destroy it.
4686 WebView* doomed = webview();
4687 RenderWidget::Close();
4688 g_view_map.Get().erase(doomed);
4689 g_routing_id_view_map.Get().erase(routing_id_);
4692 void RenderViewImpl::DidHandleKeyEvent() {
4693 ClearEditCommands();
4696 bool RenderViewImpl::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
4697 possible_drag_event_info_.event_source =
4698 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE;
4699 possible_drag_event_info_.event_location =
4700 gfx::Point(event.globalX, event.globalY);
4702 #if defined(ENABLE_PLUGINS)
4703 // This method is called for every mouse event that the render view receives.
4704 // And then the mouse event is forwarded to WebKit, which dispatches it to the
4705 // event target. Potentially a Pepper plugin will receive the event.
4706 // In order to tell whether a plugin gets the last mouse event and which it
4707 // is, we set |pepper_last_mouse_event_target_| to NULL here. If a plugin gets
4708 // the event, it will notify us via DidReceiveMouseEvent() and set itself as
4709 // |pepper_last_mouse_event_target_|.
4710 pepper_last_mouse_event_target_ = NULL;
4713 // If the mouse is locked, only the current owner of the mouse lock can
4714 // process mouse events.
4715 return mouse_lock_dispatcher_->WillHandleMouseEvent(event);
4718 bool RenderViewImpl::WillHandleGestureEvent(
4719 const blink::WebGestureEvent& event) {
4720 possible_drag_event_info_.event_source =
4721 ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH;
4722 possible_drag_event_info_.event_location =
4723 gfx::Point(event.globalX, event.globalY);
4727 void RenderViewImpl::DidHandleMouseEvent(const WebMouseEvent& event) {
4728 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidHandleMouseEvent(event));
4731 void RenderViewImpl::DidHandleTouchEvent(const WebTouchEvent& event) {
4732 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidHandleTouchEvent(event));
4735 bool RenderViewImpl::HasTouchEventHandlersAt(const gfx::Point& point) const {
4738 return webview()->hasTouchEventHandlersAt(point);
4741 void RenderViewImpl::OnWasHidden() {
4742 RenderWidget::OnWasHidden();
4744 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
4745 RenderThreadImpl::current()->video_capture_impl_manager()->
4746 SuspendDevices(true);
4750 webview()->setVisibilityState(visibilityState(), false);
4752 #if defined(ENABLE_PLUGINS)
4753 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
4754 i != active_pepper_instances_.end(); ++i)
4755 (*i)->PageVisibilityChanged(false);
4757 #if defined(OS_MACOSX)
4758 // Inform NPAPI plugins that their container is no longer visible.
4759 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
4760 for (plugin_it = plugin_delegates_.begin();
4761 plugin_it != plugin_delegates_.end(); ++plugin_it) {
4762 (*plugin_it)->SetContainerVisibility(false);
4765 #endif // ENABLE_PLUGINS
4768 void RenderViewImpl::OnWasShown(bool needs_repainting) {
4769 RenderWidget::OnWasShown(needs_repainting);
4771 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
4772 RenderThreadImpl::current()->video_capture_impl_manager()->
4773 SuspendDevices(false);
4777 webview()->setVisibilityState(visibilityState(), false);
4779 #if defined(ENABLE_PLUGINS)
4780 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
4781 i != active_pepper_instances_.end(); ++i)
4782 (*i)->PageVisibilityChanged(true);
4784 #if defined(OS_MACOSX)
4785 // Inform NPAPI plugins that their container is now visible.
4786 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
4787 for (plugin_it = plugin_delegates_.begin();
4788 plugin_it != plugin_delegates_.end(); ++plugin_it) {
4789 (*plugin_it)->SetContainerVisibility(true);
4792 #endif // ENABLE_PLUGINS
4795 GURL RenderViewImpl::GetURLForGraphicsContext3D() {
4797 if (webview()->mainFrame())
4798 return GURL(webview()->mainFrame()->document().url());
4800 return GURL("chrome://gpu/RenderViewImpl::CreateGraphicsContext3D");
4803 bool RenderViewImpl::ForceCompositingModeEnabled() {
4804 return webkit_preferences_.force_compositing_mode;
4807 void RenderViewImpl::OnSetFocus(bool enable) {
4808 RenderWidget::OnSetFocus(enable);
4810 #if defined(ENABLE_PLUGINS)
4811 if (webview() && webview()->isActive()) {
4812 // Notify all NPAPI plugins.
4813 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
4814 for (plugin_it = plugin_delegates_.begin();
4815 plugin_it != plugin_delegates_.end(); ++plugin_it) {
4816 #if defined(OS_MACOSX)
4817 // RenderWidget's call to setFocus can cause the underlying webview's
4818 // activation state to change just like a call to setIsActive.
4820 (*plugin_it)->SetWindowFocus(true);
4822 (*plugin_it)->SetContentAreaFocus(enable);
4825 // Notify all Pepper plugins.
4826 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
4827 i != active_pepper_instances_.end(); ++i)
4828 (*i)->SetContentAreaFocus(enable);
4830 // Notify all BrowserPlugins of the RenderView's focus state.
4831 if (browser_plugin_manager_.get())
4832 browser_plugin_manager_->UpdateFocusState();
4835 void RenderViewImpl::OnImeSetComposition(
4836 const base::string16& text,
4837 const std::vector<blink::WebCompositionUnderline>& underlines,
4838 int selection_start,
4839 int selection_end) {
4840 #if defined(ENABLE_PLUGINS)
4841 if (focused_pepper_plugin_) {
4842 focused_pepper_plugin_->render_frame()->OnImeSetComposition(
4843 text, underlines, selection_start, selection_end);
4848 // When a plug-in has focus, we create platform-specific IME data used by
4849 // our IME emulator and send it directly to the focused plug-in, i.e. we
4850 // bypass WebKit. (WebPluginDelegate dispatches this IME data only when its
4851 // instance ID is the same one as the specified ID.)
4852 if (focused_plugin_id_ >= 0) {
4853 std::vector<int> clauses;
4854 std::vector<int> target;
4855 for (size_t i = 0; i < underlines.size(); ++i) {
4856 clauses.push_back(underlines[i].startOffset);
4857 clauses.push_back(underlines[i].endOffset);
4858 if (underlines[i].thick) {
4860 target.push_back(underlines[i].startOffset);
4861 target.push_back(underlines[i].endOffset);
4864 std::set<WebPluginDelegateProxy*>::iterator it;
4865 for (it = plugin_delegates_.begin(); it != plugin_delegates_.end(); ++it) {
4866 (*it)->ImeCompositionUpdated(text, clauses, target, selection_end,
4867 focused_plugin_id_);
4872 #endif // ENABLE_PLUGINS
4873 RenderWidget::OnImeSetComposition(text,
4879 void RenderViewImpl::OnImeConfirmComposition(
4880 const base::string16& text,
4881 const gfx::Range& replacement_range,
4882 bool keep_selection) {
4883 #if defined(ENABLE_PLUGINS)
4884 if (focused_pepper_plugin_) {
4885 focused_pepper_plugin_->render_frame()->OnImeConfirmComposition(
4886 text, replacement_range, keep_selection);
4890 // Same as OnImeSetComposition(), we send the text from IMEs directly to
4891 // plug-ins. When we send IME text directly to plug-ins, we should not send
4892 // it to WebKit to prevent WebKit from controlling IMEs.
4893 // TODO(thakis): Honor |replacement_range| for plugins?
4894 if (focused_plugin_id_ >= 0) {
4895 std::set<WebPluginDelegateProxy*>::iterator it;
4896 for (it = plugin_delegates_.begin();
4897 it != plugin_delegates_.end(); ++it) {
4898 (*it)->ImeCompositionCompleted(text, focused_plugin_id_);
4903 #endif // ENABLE_PLUGINS
4904 if (replacement_range.IsValid() && webview()) {
4905 // Select the text in |replacement_range|, it will then be replaced by
4906 // text added by the call to RenderWidget::OnImeConfirmComposition().
4907 if (WebFrame* frame = webview()->focusedFrame()) {
4908 WebRange webrange = WebRange::fromDocumentRange(
4909 frame, replacement_range.start(), replacement_range.length());
4910 if (!webrange.isNull())
4911 frame->selectRange(webrange);
4914 RenderWidget::OnImeConfirmComposition(text,
4919 void RenderViewImpl::SetDeviceScaleFactor(float device_scale_factor) {
4920 RenderWidget::SetDeviceScaleFactor(device_scale_factor);
4922 webview()->setDeviceScaleFactor(device_scale_factor);
4923 webview()->settings()->setAcceleratedCompositingForFixedPositionEnabled(
4924 ShouldUseFixedPositionCompositing(device_scale_factor_));
4925 webview()->settings()->setAcceleratedCompositingForOverflowScrollEnabled(
4926 ShouldUseAcceleratedCompositingForOverflowScroll(device_scale_factor_));
4927 webview()->settings()->setAcceleratedCompositingForTransitionEnabled(
4928 ShouldUseTransitionCompositing(device_scale_factor_));
4929 webview()->settings()->
4930 setAcceleratedCompositingForFixedRootBackgroundEnabled(
4931 ShouldUseAcceleratedFixedRootBackground(device_scale_factor_));
4932 webview()->settings()->setAcceleratedCompositingForScrollableFramesEnabled(
4933 ShouldUseAcceleratedCompositingForScrollableFrames(
4934 device_scale_factor_));
4935 webview()->settings()->setCompositedScrollingForFramesEnabled(
4936 ShouldUseCompositedScrollingForFrames(device_scale_factor_));
4938 if (auto_resize_mode_)
4939 AutoResizeCompositor();
4941 if (browser_plugin_manager_.get())
4942 browser_plugin_manager_->UpdateDeviceScaleFactor(device_scale_factor_);
4945 ui::TextInputType RenderViewImpl::GetTextInputType() {
4946 #if defined(ENABLE_PLUGINS)
4947 if (focused_pepper_plugin_)
4948 return focused_pepper_plugin_->text_input_type();
4950 return RenderWidget::GetTextInputType();
4953 void RenderViewImpl::GetSelectionBounds(gfx::Rect* start, gfx::Rect* end) {
4954 #if defined(ENABLE_PLUGINS)
4955 if (focused_pepper_plugin_) {
4956 // TODO(kinaba) http://crbug.com/101101
4957 // Current Pepper IME API does not handle selection bounds. So we simply
4958 // use the caret position as an empty range for now. It will be updated
4959 // after Pepper API equips features related to surrounding text retrieval.
4960 gfx::Rect caret = focused_pepper_plugin_->GetCaretBounds();
4966 RenderWidget::GetSelectionBounds(start, end);
4969 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(USE_AURA)
4970 void RenderViewImpl::GetCompositionCharacterBounds(
4971 std::vector<gfx::Rect>* bounds) {
4975 #if defined(ENABLE_PLUGINS)
4976 if (focused_pepper_plugin_) {
4983 size_t start_offset = 0;
4984 size_t character_count = 0;
4985 if (!webview()->compositionRange(&start_offset, &character_count))
4987 if (character_count == 0)
4990 blink::WebFrame* frame = webview()->focusedFrame();
4994 bounds->reserve(character_count);
4995 blink::WebRect webrect;
4996 for (size_t i = 0; i < character_count; ++i) {
4997 if (!frame->firstRectForCharacterRange(start_offset + i, 1, webrect)) {
4998 DLOG(ERROR) << "Could not retrieve character rectangle at " << i;
5002 bounds->push_back(webrect);
5006 void RenderViewImpl::GetCompositionRange(gfx::Range* range) {
5007 #if defined(ENABLE_PLUGINS)
5008 if (focused_pepper_plugin_) {
5012 RenderWidget::GetCompositionRange(range);
5016 bool RenderViewImpl::CanComposeInline() {
5017 #if defined(ENABLE_PLUGINS)
5018 if (focused_pepper_plugin_)
5019 return focused_pepper_plugin_->IsPluginAcceptingCompositionEvents();
5024 void RenderViewImpl::InstrumentWillBeginFrame(int frame_id) {
5027 if (!webview()->devToolsAgent())
5029 webview()->devToolsAgent()->didBeginFrame(frame_id);
5032 void RenderViewImpl::InstrumentDidBeginFrame() {
5035 if (!webview()->devToolsAgent())
5037 // TODO(jamesr/caseq): Decide if this needs to be renamed.
5038 webview()->devToolsAgent()->didComposite();
5041 void RenderViewImpl::InstrumentDidCancelFrame() {
5044 if (!webview()->devToolsAgent())
5046 webview()->devToolsAgent()->didCancelFrame();
5049 void RenderViewImpl::InstrumentWillComposite() {
5052 if (!webview()->devToolsAgent())
5054 webview()->devToolsAgent()->willComposite();
5057 bool RenderViewImpl::AllowPartialSwap() const {
5058 return allow_partial_swap_;
5061 void RenderViewImpl::SetScreenMetricsEmulationParameters(
5062 float device_scale_factor,
5063 const gfx::Point& root_layer_offset,
5064 float root_layer_scale) {
5066 webview()->setCompositorDeviceScaleFactorOverride(device_scale_factor);
5067 webview()->setRootLayerTransform(
5068 blink::WebSize(root_layer_offset.x(), root_layer_offset.y()),
5073 bool RenderViewImpl::ScheduleFileChooser(
5074 const FileChooserParams& params,
5075 WebFileChooserCompletion* completion) {
5076 static const size_t kMaximumPendingFileChooseRequests = 4;
5077 if (file_chooser_completions_.size() > kMaximumPendingFileChooseRequests) {
5078 // This sanity check prevents too many file choose requests from getting
5079 // queued which could DoS the user. Getting these is most likely a
5080 // programming error (there are many ways to DoS the user so it's not
5081 // considered a "real" security check), either in JS requesting many file
5082 // choosers to pop up, or in a plugin.
5084 // TODO(brettw) we might possibly want to require a user gesture to open
5085 // a file picker, which will address this issue in a better way.
5089 file_chooser_completions_.push_back(linked_ptr<PendingFileChooser>(
5090 new PendingFileChooser(params, completion)));
5091 if (file_chooser_completions_.size() == 1) {
5092 // Actually show the browse dialog when this is the first request.
5093 Send(new ViewHostMsg_RunFileChooser(routing_id_, params));
5098 blink::WebGeolocationClient* RenderViewImpl::geolocationClient() {
5099 if (!geolocation_dispatcher_)
5100 geolocation_dispatcher_ = new GeolocationDispatcher(this);
5101 return geolocation_dispatcher_;
5104 blink::WebSpeechInputController* RenderViewImpl::speechInputController(
5105 blink::WebSpeechInputListener* listener) {
5106 #if defined(ENABLE_INPUT_SPEECH)
5107 if (!input_tag_speech_dispatcher_)
5108 input_tag_speech_dispatcher_ =
5109 new InputTagSpeechDispatcher(this, listener);
5111 return input_tag_speech_dispatcher_;
5114 blink::WebSpeechRecognizer* RenderViewImpl::speechRecognizer() {
5115 if (!speech_recognition_dispatcher_)
5116 speech_recognition_dispatcher_ = new SpeechRecognitionDispatcher(this);
5117 return speech_recognition_dispatcher_;
5120 void RenderViewImpl::zoomLimitsChanged(double minimum_level,
5121 double maximum_level) {
5122 // For now, don't remember plugin zoom values. We don't want to mix them with
5123 // normal web content (i.e. a fixed layout plugin would usually want them
5125 bool remember = !webview()->mainFrame()->document().isPluginDocument();
5127 int minimum_percent = static_cast<int>(
5128 ZoomLevelToZoomFactor(minimum_level) * 100);
5129 int maximum_percent = static_cast<int>(
5130 ZoomLevelToZoomFactor(maximum_level) * 100);
5132 Send(new ViewHostMsg_UpdateZoomLimits(
5133 routing_id_, minimum_percent, maximum_percent, remember));
5136 void RenderViewImpl::zoomLevelChanged() {
5137 bool remember = !webview()->mainFrame()->document().isPluginDocument();
5138 float zoom_level = webview()->zoomLevel();
5140 FOR_EACH_OBSERVER(RenderViewObserver, observers_, ZoomLevelChanged());
5142 // Tell the browser which url got zoomed so it can update the menu and the
5143 // saved values if necessary
5144 Send(new ViewHostMsg_DidZoomURL(
5145 routing_id_, zoom_level, remember,
5146 GURL(webview()->mainFrame()->document().url())));
5149 double RenderViewImpl::zoomLevelToZoomFactor(double zoom_level) const {
5150 return ZoomLevelToZoomFactor(zoom_level);
5153 double RenderViewImpl::zoomFactorToZoomLevel(double factor) const {
5154 return ZoomFactorToZoomLevel(factor);
5157 void RenderViewImpl::registerProtocolHandler(const WebString& scheme,
5158 const WebURL& base_url,
5160 const WebString& title) {
5161 bool user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
5162 GURL base(base_url);
5163 GURL absolute_url = base.Resolve(base::UTF16ToUTF8(url.string()));
5164 if (base.GetOrigin() != absolute_url.GetOrigin()) {
5167 Send(new ViewHostMsg_RegisterProtocolHandler(routing_id_,
5168 base::UTF16ToUTF8(scheme),
5174 blink::WebPageVisibilityState RenderViewImpl::visibilityState() const {
5175 blink::WebPageVisibilityState current_state = is_hidden() ?
5176 blink::WebPageVisibilityStateHidden :
5177 blink::WebPageVisibilityStateVisible;
5178 blink::WebPageVisibilityState override_state = current_state;
5179 // TODO(jam): move this method to WebFrameClient.
5180 if (GetContentClient()->renderer()->
5181 ShouldOverridePageVisibilityState(main_render_frame_.get(),
5183 return override_state;
5184 return current_state;
5187 blink::WebUserMediaClient* RenderViewImpl::userMediaClient() {
5188 // This can happen in tests, in which case it's OK to return NULL.
5189 if (!InitializeMediaStreamClient())
5192 return web_user_media_client_;
5195 blink::WebMIDIClient* RenderViewImpl::webMIDIClient() {
5196 if (!midi_dispatcher_)
5197 midi_dispatcher_ = new MidiDispatcher(this);
5198 return midi_dispatcher_;
5201 void RenderViewImpl::draggableRegionsChanged() {
5205 DraggableRegionsChanged(webview()->mainFrame()));
5208 WebMediaPlayer* RenderViewImpl::CreateWebMediaPlayerForMediaStream(
5210 const blink::WebURL& url,
5211 WebMediaPlayerClient* client) {
5212 #if defined(ENABLE_WEBRTC)
5213 if (!InitializeMediaStreamClient()) {
5214 LOG(ERROR) << "Failed to initialize MediaStreamClient";
5217 if (media_stream_client_->IsMediaStream(url)) {
5218 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
5220 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0;
5221 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon);
5222 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
5223 return new WebMediaPlayerMS(frame, client, AsWeakPtr(),
5224 media_stream_client_, new RenderMediaLog());
5226 #endif // defined(ENABLE_WEBRTC)
5230 #if defined(OS_ANDROID)
5231 WebContentDetectionResult RenderViewImpl::detectContentAround(
5232 const WebHitTestResult& touch_hit) {
5233 DCHECK(!touch_hit.isNull());
5234 DCHECK(!touch_hit.node().isNull());
5235 DCHECK(touch_hit.node().isTextNode());
5237 // Process the position with all the registered content detectors until
5238 // a match is found. Priority is provided by their relative order.
5239 for (ContentDetectorList::const_iterator it = content_detectors_.begin();
5240 it != content_detectors_.end(); ++it) {
5241 ContentDetector::Result content = (*it)->FindTappedContent(touch_hit);
5242 if (content.valid) {
5243 return WebContentDetectionResult(content.content_boundaries,
5244 base::UTF8ToUTF16(content.text), content.intent_url);
5247 return WebContentDetectionResult();
5250 void RenderViewImpl::scheduleContentIntent(const WebURL& intent) {
5251 // Introduce a short delay so that the user can notice the content.
5252 base::MessageLoop::current()->PostDelayedTask(
5254 base::Bind(&RenderViewImpl::LaunchAndroidContentIntent,
5257 expected_content_intent_id_),
5258 base::TimeDelta::FromMilliseconds(kContentIntentDelayMilliseconds));
5261 void RenderViewImpl::cancelScheduledContentIntents() {
5262 ++expected_content_intent_id_;
5265 void RenderViewImpl::LaunchAndroidContentIntent(const GURL& intent,
5266 size_t request_id) {
5267 if (request_id != expected_content_intent_id_)
5270 // Remove the content highlighting if any.
5271 scheduleComposite();
5273 if (!intent.is_empty())
5274 Send(new ViewHostMsg_StartContentIntent(routing_id_, intent));
5277 bool RenderViewImpl::openDateTimeChooser(
5278 const blink::WebDateTimeChooserParams& params,
5279 blink::WebDateTimeChooserCompletion* completion) {
5280 // JavaScript may try to open a date time chooser while one is already open.
5281 if (date_time_picker_client_)
5283 date_time_picker_client_.reset(
5284 new RendererDateTimePicker(this, params, completion));
5285 return date_time_picker_client_->Open();
5288 void RenderViewImpl::DismissDateTimeDialog() {
5289 DCHECK(date_time_picker_client_);
5290 date_time_picker_client_.reset(NULL);
5293 WebMediaPlayer* RenderViewImpl::CreateAndroidWebMediaPlayer(
5295 const blink::WebURL& url,
5296 WebMediaPlayerClient* client) {
5297 GpuChannelHost* gpu_channel_host =
5298 RenderThreadImpl::current()->EstablishGpuChannelSync(
5299 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE);
5300 if (!gpu_channel_host) {
5301 LOG(ERROR) << "Failed to establish GPU channel for media player";
5305 scoped_ptr<StreamTextureFactory> stream_texture_factory;
5306 if (UsingSynchronousRendererCompositor()) {
5307 SynchronousCompositorFactory* factory =
5308 SynchronousCompositorFactory::GetInstance();
5309 stream_texture_factory = factory->CreateStreamTextureFactory(routing_id_);
5311 scoped_refptr<webkit::gpu::ContextProviderWebContext> context_provider =
5312 RenderThreadImpl::current()->SharedMainThreadContextProvider();
5314 if (!context_provider.get()) {
5315 LOG(ERROR) << "Failed to get context3d for media player";
5319 stream_texture_factory.reset(new StreamTextureFactoryImpl(
5320 context_provider, gpu_channel_host, routing_id_));
5323 return new WebMediaPlayerAndroid(
5327 media_player_manager_,
5328 stream_texture_factory.release(),
5329 RenderThreadImpl::current()->GetMediaThreadMessageLoopProxy(),
5330 new RenderMediaLog());
5333 #endif // defined(OS_ANDROID)
5335 #if defined(OS_MACOSX)
5336 void RenderViewImpl::OnSelectPopupMenuItem(int selected_index) {
5337 if (external_popup_menu_ == NULL) {
5338 // Crash reports from the field indicate that we can be notified with a
5339 // NULL external popup menu (we probably get notified twice).
5340 // If you hit this please file a bug against jcivelli and include the page
5341 // and steps to repro.
5345 external_popup_menu_->DidSelectItem(selected_index);
5346 external_popup_menu_.reset();
5350 #if defined(OS_ANDROID)
5351 void RenderViewImpl::OnSelectPopupMenuItems(
5353 const std::vector<int>& selected_indices) {
5354 // It is possible to receive more than one of these calls if the user presses
5355 // a select faster than it takes for the show-select-popup IPC message to make
5356 // it to the browser UI thread. Ignore the extra-messages.
5357 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
5358 if (!external_popup_menu_)
5361 external_popup_menu_->DidSelectItems(canceled, selected_indices);
5362 external_popup_menu_.reset();
5366 void RenderViewImpl::OnShowContextMenu(const gfx::Point& location) {
5367 context_menu_source_type_ = ui::MENU_SOURCE_TOUCH_EDIT_MENU;
5368 touch_editing_context_menu_location_ = location;
5370 webview()->showContextMenu();
5373 void RenderViewImpl::OnEnableViewSourceMode() {
5376 WebFrame* main_frame = webview()->mainFrame();
5379 main_frame->enableViewSourceMode(true);
5382 void RenderViewImpl::OnDisownOpener() {
5386 WebFrame* main_frame = webview()->mainFrame();
5387 if (main_frame && main_frame->opener())
5388 main_frame->setOpener(NULL);
5391 #if defined(OS_ANDROID)
5392 bool RenderViewImpl::didTapMultipleTargets(
5393 const blink::WebGestureEvent& event,
5394 const WebVector<WebRect>& target_rects) {
5395 // Never show a disambiguation popup when accessibility is enabled,
5396 // as this interferes with "touch exploration".
5397 bool matchesAccessibilityModeComplete =
5398 (accessibility_mode_ & AccessibilityModeComplete) ==
5399 AccessibilityModeComplete;
5400 if (matchesAccessibilityModeComplete)
5403 gfx::Rect finger_rect(
5404 event.x - event.data.tap.width / 2, event.y - event.data.tap.height / 2,
5405 event.data.tap.width, event.data.tap.height);
5406 gfx::Rect zoom_rect;
5407 float new_total_scale =
5408 DisambiguationPopupHelper::ComputeZoomAreaAndScaleFactor(
5409 finger_rect, target_rects, GetSize(),
5410 gfx::Rect(webview()->mainFrame()->visibleContentRect()).size(),
5411 device_scale_factor_ * webview()->pageScaleFactor(), &zoom_rect);
5412 if (!new_total_scale)
5415 bool handled = false;
5416 switch (renderer_preferences_.tap_multiple_targets_strategy) {
5417 case TAP_MULTIPLE_TARGETS_STRATEGY_ZOOM:
5418 handled = webview()->zoomToMultipleTargetsRect(zoom_rect);
5420 case TAP_MULTIPLE_TARGETS_STRATEGY_POPUP: {
5421 gfx::Size canvas_size =
5422 gfx::ToCeiledSize(gfx::ScaleSize(zoom_rect.size(), new_total_scale));
5423 TransportDIB* transport_dib = NULL;
5425 scoped_ptr<skia::PlatformCanvas> canvas(
5426 RenderProcess::current()->GetDrawingCanvas(&transport_dib,
5427 gfx::Rect(canvas_size)));
5433 // TODO(trchen): Cleanup the device scale factor mess.
5434 // device scale will be applied in WebKit
5435 // --> zoom_rect doesn't include device scale,
5436 // but WebKit will still draw on zoom_rect * device_scale_factor_
5437 canvas->scale(new_total_scale / device_scale_factor_,
5438 new_total_scale / device_scale_factor_);
5439 canvas->translate(-zoom_rect.x() * device_scale_factor_,
5440 -zoom_rect.y() * device_scale_factor_);
5445 WebWidget::ForceSoftwareRenderingAndIgnoreGPUResidentContent);
5448 gfx::Rect physical_window_zoom_rect = gfx::ToEnclosingRect(
5449 ClientRectToPhysicalWindowRect(gfx::RectF(zoom_rect)));
5450 Send(new ViewHostMsg_ShowDisambiguationPopup(routing_id_,
5451 physical_window_zoom_rect,
5453 transport_dib->id()));
5457 case TAP_MULTIPLE_TARGETS_STRATEGY_NONE:
5466 unsigned RenderViewImpl::GetLocalSessionHistoryLengthForTesting() const {
5467 return history_list_length_;
5470 void RenderViewImpl::SetFocusAndActivateForTesting(bool enable) {
5484 void RenderViewImpl::SetDeviceScaleFactorForTesting(float factor) {
5485 ViewMsg_Resize_Params params;
5486 params.screen_info = screen_info_;
5487 params.screen_info.deviceScaleFactor = factor;
5488 params.new_size = size();
5489 params.physical_backing_size =
5490 gfx::ToCeiledSize(gfx::ScaleSize(size(), factor));
5491 params.overdraw_bottom_height = 0.f;
5492 params.resizer_rect = WebRect();
5493 params.is_fullscreen = is_fullscreen();
5497 void RenderViewImpl::ForceResizeForTesting(const gfx::Size& new_size) {
5498 gfx::Rect new_position(rootWindowRect().x,
5502 ResizeSynchronously(new_position);
5505 void RenderViewImpl::UseSynchronousResizeModeForTesting(bool enable) {
5506 resizing_mode_selector_->set_is_synchronous_mode(enable);
5509 void RenderViewImpl::EnableAutoResizeForTesting(const gfx::Size& min_size,
5510 const gfx::Size& max_size) {
5511 OnEnableAutoResize(min_size, max_size);
5514 void RenderViewImpl::DisableAutoResizeForTesting(const gfx::Size& new_size) {
5515 OnDisableAutoResize(new_size);
5518 void RenderViewImpl::SetMediaStreamClientForTesting(
5519 MediaStreamClient* media_stream_client) {
5520 DCHECK(!media_stream_client_);
5521 DCHECK(!web_user_media_client_);
5522 media_stream_client_ = media_stream_client;
5525 void RenderViewImpl::OnReleaseDisambiguationPopupDIB(
5526 TransportDIB::Handle dib_handle) {
5527 TransportDIB* dib = TransportDIB::CreateWithHandle(dib_handle);
5528 RenderProcess::current()->ReleaseTransportDIB(dib);
5531 void RenderViewImpl::DidCommitCompositorFrame() {
5532 RenderWidget::DidCommitCompositorFrame();
5533 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidCommitCompositorFrame());
5536 void RenderViewImpl::SendUpdateFaviconURL(const std::vector<FaviconURL>& urls) {
5538 Send(new ViewHostMsg_UpdateFaviconURL(routing_id_, page_id_, urls));
5541 void RenderViewImpl::DidStopLoadingIcons() {
5542 int icon_types = WebIconURL::TypeFavicon;
5544 icon_types |= WebIconURL::TypeTouchPrecomposed | WebIconURL::TypeTouch;
5546 WebVector<WebIconURL> icon_urls =
5547 webview()->mainFrame()->iconURLs(icon_types);
5549 std::vector<FaviconURL> urls;
5550 for (size_t i = 0; i < icon_urls.size(); i++) {
5551 WebURL url = icon_urls[i].iconURL();
5553 urls.push_back(FaviconURL(url,
5554 ToFaviconType(icon_urls[i].iconType())));
5556 SendUpdateFaviconURL(urls);
5559 } // namespace content