Assume the foo_test_run depends on everything needed to run the test.
[chromium-blink-merge.git] / content / renderer / render_view_impl.cc
blobec7e834c46915952d0fcb11a705c748b270c1e5a
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"
7 #include <algorithm>
8 #include <cmath>
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_shared_bitmap_manager.h"
38 #include "content/child/child_thread.h"
39 #include "content/child/npapi/webplugin_delegate_impl.h"
40 #include "content/child/request_extra_data.h"
41 #include "content/child/webmessageportchannel_impl.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/pepper_messages.h"
49 #include "content/common/socket_stream_handle_data.h"
50 #include "content/common/ssl_status_serialization.h"
51 #include "content/common/view_messages.h"
52 #include "content/public/common/bindings_policy.h"
53 #include "content/public/common/content_client.h"
54 #include "content/public/common/content_constants.h"
55 #include "content/public/common/content_switches.h"
56 #include "content/public/common/drop_data.h"
57 #include "content/public/common/favicon_url.h"
58 #include "content/public/common/file_chooser_params.h"
59 #include "content/public/common/page_zoom.h"
60 #include "content/public/common/ssl_status.h"
61 #include "content/public/common/three_d_api_types.h"
62 #include "content/public/common/url_constants.h"
63 #include "content/public/common/url_utils.h"
64 #include "content/public/renderer/content_renderer_client.h"
65 #include "content/public/renderer/document_state.h"
66 #include "content/public/renderer/navigation_state.h"
67 #include "content/public/renderer/render_view_observer.h"
68 #include "content/public/renderer/render_view_visitor.h"
69 #include "content/public/renderer/web_preferences.h"
70 #include "content/renderer/accessibility/renderer_accessibility.h"
71 #include "content/renderer/accessibility/renderer_accessibility_complete.h"
72 #include "content/renderer/accessibility/renderer_accessibility_focus_only.h"
73 #include "content/renderer/browser_plugin/browser_plugin.h"
74 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
75 #include "content/renderer/browser_plugin/browser_plugin_manager_impl.h"
76 #include "content/renderer/devtools/devtools_agent.h"
77 #include "content/renderer/disambiguation_popup_helper.h"
78 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
79 #include "content/renderer/drop_data_builder.h"
80 #include "content/renderer/external_popup_menu.h"
81 #include "content/renderer/geolocation_dispatcher.h"
82 #include "content/renderer/gpu/render_widget_compositor.h"
83 #include "content/renderer/history_controller.h"
84 #include "content/renderer/history_serialization.h"
85 #include "content/renderer/idle_user_detector.h"
86 #include "content/renderer/ime_event_guard.h"
87 #include "content/renderer/input/input_handler_manager.h"
88 #include "content/renderer/internal_document_state_data.h"
89 #include "content/renderer/load_progress_tracker.h"
90 #include "content/renderer/media/audio_device_factory.h"
91 #include "content/renderer/media/media_stream_dependency_factory.h"
92 #include "content/renderer/media/media_stream_dispatcher.h"
93 #include "content/renderer/media/midi_dispatcher.h"
94 #include "content/renderer/media/video_capture_impl_manager.h"
95 #include "content/renderer/memory_benchmarking_extension.h"
96 #include "content/renderer/mhtml_generator.h"
97 #include "content/renderer/push_messaging_dispatcher.h"
98 #include "content/renderer/render_frame_impl.h"
99 #include "content/renderer/render_process.h"
100 #include "content/renderer/render_thread_impl.h"
101 #include "content/renderer/render_view_impl_params.h"
102 #include "content/renderer/render_view_mouse_lock_dispatcher.h"
103 #include "content/renderer/render_widget_fullscreen_pepper.h"
104 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
105 #include "content/renderer/resizing_mode_selector.h"
106 #include "content/renderer/savable_resources.h"
107 #include "content/renderer/skia_benchmarking_extension.h"
108 #include "content/renderer/speech_recognition_dispatcher.h"
109 #include "content/renderer/stats_collection_controller.h"
110 #include "content/renderer/stats_collection_observer.h"
111 #include "content/renderer/text_input_client_observer.h"
112 #include "content/renderer/v8_value_converter_impl.h"
113 #include "content/renderer/web_ui_extension.h"
114 #include "content/renderer/web_ui_extension_data.h"
115 #include "content/renderer/web_ui_mojo.h"
116 #include "content/renderer/websharedworker_proxy.h"
117 #include "media/audio/audio_output_device.h"
118 #include "media/base/filter_collection.h"
119 #include "media/base/media_switches.h"
120 #include "media/filters/audio_renderer_impl.h"
121 #include "media/filters/gpu_video_accelerator_factories.h"
122 #include "net/base/data_url.h"
123 #include "net/base/escape.h"
124 #include "net/base/net_errors.h"
125 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
126 #include "net/http/http_util.h"
127 #include "third_party/WebKit/public/platform/WebCString.h"
128 #include "third_party/WebKit/public/platform/WebDragData.h"
129 #include "third_party/WebKit/public/platform/WebHTTPBody.h"
130 #include "third_party/WebKit/public/platform/WebImage.h"
131 #include "third_party/WebKit/public/platform/WebMessagePortChannel.h"
132 #include "third_party/WebKit/public/platform/WebPoint.h"
133 #include "third_party/WebKit/public/platform/WebRect.h"
134 #include "third_party/WebKit/public/platform/WebSize.h"
135 #include "third_party/WebKit/public/platform/WebSocketStreamHandle.h"
136 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
137 #include "third_party/WebKit/public/platform/WebString.h"
138 #include "third_party/WebKit/public/platform/WebURL.h"
139 #include "third_party/WebKit/public/platform/WebURLError.h"
140 #include "third_party/WebKit/public/platform/WebURLRequest.h"
141 #include "third_party/WebKit/public/platform/WebURLResponse.h"
142 #include "third_party/WebKit/public/platform/WebVector.h"
143 #include "third_party/WebKit/public/web/WebAXObject.h"
144 #include "third_party/WebKit/public/web/WebColorName.h"
145 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
146 #include "third_party/WebKit/public/web/WebDOMEvent.h"
147 #include "third_party/WebKit/public/web/WebDOMMessageEvent.h"
148 #include "third_party/WebKit/public/web/WebDataSource.h"
149 #include "third_party/WebKit/public/web/WebDateTimeChooserCompletion.h"
150 #include "third_party/WebKit/public/web/WebDateTimeChooserParams.h"
151 #include "third_party/WebKit/public/web/WebDevToolsAgent.h"
152 #include "third_party/WebKit/public/web/WebDocument.h"
153 #include "third_party/WebKit/public/web/WebElement.h"
154 #include "third_party/WebKit/public/web/WebFileChooserParams.h"
155 #include "third_party/WebKit/public/web/WebFindOptions.h"
156 #include "third_party/WebKit/public/web/WebFormControlElement.h"
157 #include "third_party/WebKit/public/web/WebFormElement.h"
158 #include "third_party/WebKit/public/web/WebFrame.h"
159 #include "third_party/WebKit/public/web/WebGlyphCache.h"
160 #include "third_party/WebKit/public/web/WebHistoryItem.h"
161 #include "third_party/WebKit/public/web/WebInputElement.h"
162 #include "third_party/WebKit/public/web/WebInputEvent.h"
163 #include "third_party/WebKit/public/web/WebLocalFrame.h"
164 #include "third_party/WebKit/public/web/WebMediaPlayerAction.h"
165 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
166 #include "third_party/WebKit/public/web/WebNodeList.h"
167 #include "third_party/WebKit/public/web/WebPageSerializer.h"
168 #include "third_party/WebKit/public/web/WebPlugin.h"
169 #include "third_party/WebKit/public/web/WebPluginAction.h"
170 #include "third_party/WebKit/public/web/WebPluginContainer.h"
171 #include "third_party/WebKit/public/web/WebPluginDocument.h"
172 #include "third_party/WebKit/public/web/WebRange.h"
173 #include "third_party/WebKit/public/web/WebScriptSource.h"
174 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
175 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
176 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
177 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
178 #include "third_party/WebKit/public/web/WebSettings.h"
179 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
180 #include "third_party/WebKit/public/web/WebView.h"
181 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
182 #include "third_party/WebKit/public/web/default/WebRenderTheme.h"
183 #include "ui/base/clipboard/clipboard.h"
184 #include "ui/base/ui_base_switches_util.h"
185 #include "ui/events/latency_info.h"
186 #include "ui/gfx/native_widget_types.h"
187 #include "ui/gfx/point.h"
188 #include "ui/gfx/rect.h"
189 #include "ui/gfx/rect_conversions.h"
190 #include "ui/gfx/size_conversions.h"
191 #include "ui/shell_dialogs/selected_file_info.h"
192 #include "v8/include/v8.h"
193 #include "webkit/child/weburlresponse_extradata_impl.h"
195 #if defined(OS_ANDROID)
196 #include <cpu-features.h>
198 #include "content/renderer/android/address_detector.h"
199 #include "content/renderer/android/content_detector.h"
200 #include "content/renderer/android/email_detector.h"
201 #include "content/renderer/android/phone_number_detector.h"
202 #include "content/renderer/media/android/renderer_media_player_manager.h"
203 #include "net/android/network_library.h"
204 #include "skia/ext/platform_canvas.h"
205 #include "third_party/WebKit/public/platform/WebFloatPoint.h"
206 #include "third_party/WebKit/public/platform/WebFloatRect.h"
207 #include "third_party/WebKit/public/web/WebHitTestResult.h"
208 #include "ui/gfx/rect_f.h"
210 #elif defined(OS_WIN)
211 // TODO(port): these files are currently Windows only because they concern:
212 // * theming
213 #include "ui/native_theme/native_theme_win.h"
214 #elif defined(USE_X11)
215 #include "ui/native_theme/native_theme.h"
216 #elif defined(OS_MACOSX)
217 #include "skia/ext/skia_utils_mac.h"
218 #endif
220 #if defined(ENABLE_PLUGINS)
221 #include "content/renderer/npapi/webplugin_delegate_proxy.h"
222 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
223 #include "content/renderer/pepper/pepper_plugin_registry.h"
224 #endif
226 #if defined(ENABLE_WEBRTC)
227 #include "content/renderer/media/rtc_peer_connection_handler.h"
228 #endif
230 using blink::WebAXObject;
231 using blink::WebApplicationCacheHost;
232 using blink::WebApplicationCacheHostClient;
233 using blink::WebCString;
234 using blink::WebColor;
235 using blink::WebColorName;
236 using blink::WebConsoleMessage;
237 using blink::WebData;
238 using blink::WebDataSource;
239 using blink::WebDocument;
240 using blink::WebDOMEvent;
241 using blink::WebDOMMessageEvent;
242 using blink::WebDragData;
243 using blink::WebDragOperation;
244 using blink::WebDragOperationsMask;
245 using blink::WebElement;
246 using blink::WebExternalPopupMenu;
247 using blink::WebExternalPopupMenuClient;
248 using blink::WebFileChooserCompletion;
249 using blink::WebFindOptions;
250 using blink::WebFormControlElement;
251 using blink::WebFormElement;
252 using blink::WebFrame;
253 using blink::WebGestureEvent;
254 using blink::WebHistoryItem;
255 using blink::WebHTTPBody;
256 using blink::WebIconURL;
257 using blink::WebImage;
258 using blink::WebInputElement;
259 using blink::WebInputEvent;
260 using blink::WebLocalFrame;
261 using blink::WebMediaPlayerAction;
262 using blink::WebMouseEvent;
263 using blink::WebNavigationPolicy;
264 using blink::WebNavigationType;
265 using blink::WebNode;
266 using blink::WebPageSerializer;
267 using blink::WebPageSerializerClient;
268 using blink::WebPeerConnection00Handler;
269 using blink::WebPeerConnection00HandlerClient;
270 using blink::WebPeerConnectionHandler;
271 using blink::WebPeerConnectionHandlerClient;
272 using blink::WebPluginAction;
273 using blink::WebPluginContainer;
274 using blink::WebPluginDocument;
275 using blink::WebPoint;
276 using blink::WebPopupMenuInfo;
277 using blink::WebRange;
278 using blink::WebRect;
279 using blink::WebReferrerPolicy;
280 using blink::WebScriptSource;
281 using blink::WebSearchableFormData;
282 using blink::WebSecurityOrigin;
283 using blink::WebSecurityPolicy;
284 using blink::WebSerializedScriptValue;
285 using blink::WebSettings;
286 using blink::WebSize;
287 using blink::WebSocketStreamHandle;
288 using blink::WebStorageNamespace;
289 using blink::WebStorageQuotaCallbacks;
290 using blink::WebStorageQuotaError;
291 using blink::WebStorageQuotaType;
292 using blink::WebString;
293 using blink::WebTextAffinity;
294 using blink::WebTextDirection;
295 using blink::WebTouchEvent;
296 using blink::WebURL;
297 using blink::WebURLError;
298 using blink::WebURLRequest;
299 using blink::WebURLResponse;
300 using blink::WebUserGestureIndicator;
301 using blink::WebVector;
302 using blink::WebView;
303 using blink::WebWidget;
304 using blink::WebWindowFeatures;
305 using base::Time;
306 using base::TimeDelta;
307 using webkit_glue::WebURLResponseExtraDataImpl;
309 #if defined(OS_ANDROID)
310 using blink::WebContentDetectionResult;
311 using blink::WebFloatPoint;
312 using blink::WebFloatRect;
313 using blink::WebHitTestResult;
314 #endif
316 namespace content {
318 //-----------------------------------------------------------------------------
320 typedef std::map<blink::WebView*, RenderViewImpl*> ViewMap;
321 static base::LazyInstance<ViewMap> g_view_map = LAZY_INSTANCE_INITIALIZER;
322 typedef std::map<int32, RenderViewImpl*> RoutingIDViewMap;
323 static base::LazyInstance<RoutingIDViewMap> g_routing_id_view_map =
324 LAZY_INSTANCE_INITIALIZER;
326 // Time, in seconds, we delay before sending content state changes (such as form
327 // state and scroll position) to the browser. We delay sending changes to avoid
328 // spamming the browser.
329 // To avoid having tab/session restore require sending a message to get the
330 // current content state during tab closing we use a shorter timeout for the
331 // foreground renderer. This means there is a small window of time from which
332 // content state is modified and not sent to session restore, but this is
333 // better than having to wake up all renderers during shutdown.
334 const int kDelaySecondsForContentStateSyncHidden = 5;
335 const int kDelaySecondsForContentStateSync = 1;
337 #if defined(OS_ANDROID)
338 // Delay between tapping in content and launching the associated android intent.
339 // Used to allow users see what has been recognized as content.
340 const size_t kContentIntentDelayMilliseconds = 700;
341 #endif
343 static RenderViewImpl* (*g_create_render_view_impl)(RenderViewImplParams*) =
344 NULL;
346 // static
347 bool RenderViewImpl::IsReload(const FrameMsg_Navigate_Params& params) {
348 return
349 params.navigation_type == FrameMsg_Navigate_Type::RELOAD ||
350 params.navigation_type == FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE ||
351 params.navigation_type ==
352 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL;
355 // static
356 Referrer RenderViewImpl::GetReferrerFromRequest(
357 WebFrame* frame,
358 const WebURLRequest& request) {
359 return Referrer(GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
360 request.referrerPolicy());
363 // static
364 WindowOpenDisposition RenderViewImpl::NavigationPolicyToDisposition(
365 WebNavigationPolicy policy) {
366 switch (policy) {
367 case blink::WebNavigationPolicyIgnore:
368 return IGNORE_ACTION;
369 case blink::WebNavigationPolicyDownload:
370 return SAVE_TO_DISK;
371 case blink::WebNavigationPolicyCurrentTab:
372 return CURRENT_TAB;
373 case blink::WebNavigationPolicyNewBackgroundTab:
374 return NEW_BACKGROUND_TAB;
375 case blink::WebNavigationPolicyNewForegroundTab:
376 return NEW_FOREGROUND_TAB;
377 case blink::WebNavigationPolicyNewWindow:
378 return NEW_WINDOW;
379 case blink::WebNavigationPolicyNewPopup:
380 return NEW_POPUP;
381 default:
382 NOTREACHED() << "Unexpected WebNavigationPolicy";
383 return IGNORE_ACTION;
387 // Returns true if the device scale is high enough that losing subpixel
388 // antialiasing won't have a noticeable effect on text quality.
389 static bool DeviceScaleEnsuresTextQuality(float device_scale_factor) {
390 #if defined(OS_ANDROID)
391 // On Android, we never have subpixel antialiasing.
392 return true;
393 #else
394 return device_scale_factor > 1.5f;
395 #endif
399 static bool ShouldUseFixedPositionCompositing(float device_scale_factor) {
400 // Compositing for fixed-position elements is dependent on
401 // device_scale_factor if no flag is set. http://crbug.com/172738
402 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
404 if (command_line.HasSwitch(switches::kDisableCompositingForFixedPosition))
405 return false;
407 if (command_line.HasSwitch(switches::kEnableCompositingForFixedPosition))
408 return true;
410 return DeviceScaleEnsuresTextQuality(device_scale_factor);
413 static bool ShouldUseAcceleratedCompositingForOverflowScroll(
414 float device_scale_factor) {
415 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
417 if (command_line.HasSwitch(switches::kDisableAcceleratedOverflowScroll))
418 return false;
420 if (command_line.HasSwitch(switches::kEnableAcceleratedOverflowScroll))
421 return true;
423 return DeviceScaleEnsuresTextQuality(device_scale_factor);
426 static bool ShouldUseCompositedScrollingForFrames(
427 float device_scale_factor) {
428 if (RenderThreadImpl::current() &&
429 !RenderThreadImpl::current()->is_lcd_text_enabled())
430 return true;
432 return DeviceScaleEnsuresTextQuality(device_scale_factor);
435 static bool ShouldUseUniversalAcceleratedCompositingForOverflowScroll() {
436 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
438 if (command_line.HasSwitch(
439 switches::kDisableUniversalAcceleratedOverflowScroll))
440 return false;
442 if (command_line.HasSwitch(
443 switches::kEnableUniversalAcceleratedOverflowScroll))
444 return true;
446 return false;
449 static bool ShouldUseTransitionCompositing(float device_scale_factor) {
450 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
452 if (command_line.HasSwitch(switches::kDisableCompositingForTransition))
453 return false;
455 if (command_line.HasSwitch(switches::kEnableCompositingForTransition))
456 return true;
458 // TODO(ajuma): Re-enable this by default for high-DPI once the problem
459 // of excessive layer promotion caused by overlap has been addressed.
460 // http://crbug.com/178119.
461 return false;
464 static bool ShouldUseAcceleratedFixedRootBackground(float device_scale_factor) {
465 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
467 if (command_line.HasSwitch(switches::kDisableAcceleratedFixedRootBackground))
468 return false;
470 if (command_line.HasSwitch(switches::kEnableAcceleratedFixedRootBackground))
471 return true;
473 return DeviceScaleEnsuresTextQuality(device_scale_factor);
476 static FaviconURL::IconType ToFaviconType(blink::WebIconURL::Type type) {
477 switch (type) {
478 case blink::WebIconURL::TypeFavicon:
479 return FaviconURL::FAVICON;
480 case blink::WebIconURL::TypeTouch:
481 return FaviconURL::TOUCH_ICON;
482 case blink::WebIconURL::TypeTouchPrecomposed:
483 return FaviconURL::TOUCH_PRECOMPOSED_ICON;
484 case blink::WebIconURL::TypeInvalid:
485 return FaviconURL::INVALID_ICON;
487 return FaviconURL::INVALID_ICON;
490 static void ConvertToFaviconSizes(
491 const blink::WebVector<blink::WebSize>& web_sizes,
492 std::vector<gfx::Size>* sizes) {
493 DCHECK(sizes->empty());
494 sizes->reserve(web_sizes.size());
495 for (size_t i = 0; i < web_sizes.size(); ++i)
496 sizes->push_back(gfx::Size(web_sizes[i]));
499 ///////////////////////////////////////////////////////////////////////////////
501 struct RenderViewImpl::PendingFileChooser {
502 PendingFileChooser(const FileChooserParams& p, WebFileChooserCompletion* c)
503 : params(p),
504 completion(c) {
506 FileChooserParams params;
507 WebFileChooserCompletion* completion; // MAY BE NULL to skip callback.
510 namespace {
512 class WebWidgetLockTarget : public MouseLockDispatcher::LockTarget {
513 public:
514 explicit WebWidgetLockTarget(blink::WebWidget* webwidget)
515 : webwidget_(webwidget) {}
517 virtual void OnLockMouseACK(bool succeeded) OVERRIDE {
518 if (succeeded)
519 webwidget_->didAcquirePointerLock();
520 else
521 webwidget_->didNotAcquirePointerLock();
524 virtual void OnMouseLockLost() OVERRIDE {
525 webwidget_->didLosePointerLock();
528 virtual bool HandleMouseLockedInputEvent(
529 const blink::WebMouseEvent &event) OVERRIDE {
530 // The WebWidget handles mouse lock in WebKit's handleInputEvent().
531 return false;
534 private:
535 blink::WebWidget* webwidget_;
538 bool TouchEnabled() {
539 // Based on the definition of chrome::kEnableTouchIcon.
540 #if defined(OS_ANDROID)
541 return true;
542 #else
543 return false;
544 #endif
547 WebDragData DropDataToWebDragData(const DropData& drop_data) {
548 std::vector<WebDragData::Item> item_list;
550 // These fields are currently unused when dragging into WebKit.
551 DCHECK(drop_data.download_metadata.empty());
552 DCHECK(drop_data.file_contents.empty());
553 DCHECK(drop_data.file_description_filename.empty());
555 if (!drop_data.text.is_null()) {
556 WebDragData::Item item;
557 item.storageType = WebDragData::Item::StorageTypeString;
558 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeText);
559 item.stringData = drop_data.text.string();
560 item_list.push_back(item);
563 // TODO(dcheng): Do we need to distinguish between null and empty URLs? Is it
564 // meaningful to write an empty URL to the clipboard?
565 if (!drop_data.url.is_empty()) {
566 WebDragData::Item item;
567 item.storageType = WebDragData::Item::StorageTypeString;
568 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeURIList);
569 item.stringData = WebString::fromUTF8(drop_data.url.spec());
570 item.title = drop_data.url_title;
571 item_list.push_back(item);
574 if (!drop_data.html.is_null()) {
575 WebDragData::Item item;
576 item.storageType = WebDragData::Item::StorageTypeString;
577 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeHTML);
578 item.stringData = drop_data.html.string();
579 item.baseURL = drop_data.html_base_url;
580 item_list.push_back(item);
583 for (std::vector<ui::FileInfo>::const_iterator it =
584 drop_data.filenames.begin();
585 it != drop_data.filenames.end();
586 ++it) {
587 WebDragData::Item item;
588 item.storageType = WebDragData::Item::StorageTypeFilename;
589 item.filenameData = it->path.AsUTF16Unsafe();
590 item.displayNameData = it->display_name.AsUTF16Unsafe();
591 item_list.push_back(item);
594 for (std::vector<DropData::FileSystemFileInfo>::const_iterator it =
595 drop_data.file_system_files.begin();
596 it != drop_data.file_system_files.end();
597 ++it) {
598 WebDragData::Item item;
599 item.storageType = WebDragData::Item::StorageTypeFileSystemFile;
600 item.fileSystemURL = it->url;
601 item.fileSystemFileSize = it->size;
602 item_list.push_back(item);
605 for (std::map<base::string16, base::string16>::const_iterator it =
606 drop_data.custom_data.begin();
607 it != drop_data.custom_data.end();
608 ++it) {
609 WebDragData::Item item;
610 item.storageType = WebDragData::Item::StorageTypeString;
611 item.stringType = it->first;
612 item.stringData = it->second;
613 item_list.push_back(item);
616 WebDragData result;
617 result.initialize();
618 result.setItems(item_list);
619 result.setFilesystemId(drop_data.filesystem_id);
620 return result;
623 } // namespace
625 RenderViewImpl::RenderViewImpl(RenderViewImplParams* params)
626 : RenderWidget(blink::WebPopupTypeNone,
627 params->screen_info,
628 params->swapped_out,
629 params->hidden,
630 params->never_visible),
631 webkit_preferences_(params->webkit_prefs),
632 send_content_state_immediately_(false),
633 enabled_bindings_(0),
634 send_preferred_size_changes_(false),
635 navigation_gesture_(NavigationGestureUnknown),
636 opened_by_user_gesture_(true),
637 opener_suppressed_(false),
638 suppress_dialogs_until_swap_out_(false),
639 page_id_(-1),
640 last_page_id_sent_to_browser_(-1),
641 next_page_id_(params->next_page_id),
642 history_list_offset_(-1),
643 history_list_length_(0),
644 frames_in_progress_(0),
645 target_url_status_(TARGET_NONE),
646 #if defined(OS_ANDROID)
647 top_controls_constraints_(cc::BOTH),
648 #endif
649 cached_is_main_frame_pinned_to_left_(false),
650 cached_is_main_frame_pinned_to_right_(false),
651 has_scrolled_focused_editable_node_into_rect_(false),
652 push_messaging_dispatcher_(NULL),
653 geolocation_dispatcher_(NULL),
654 speech_recognition_dispatcher_(NULL),
655 media_stream_dispatcher_(NULL),
656 browser_plugin_manager_(NULL),
657 midi_dispatcher_(NULL),
658 devtools_agent_(NULL),
659 accessibility_mode_(AccessibilityModeOff),
660 renderer_accessibility_(NULL),
661 mouse_lock_dispatcher_(NULL),
662 #if defined(OS_ANDROID)
663 expected_content_intent_id_(0),
664 media_player_manager_(NULL),
665 #endif
666 #if defined(OS_WIN)
667 focused_plugin_id_(-1),
668 #endif
669 #if defined(ENABLE_PLUGINS)
670 plugin_find_handler_(NULL),
671 focused_pepper_plugin_(NULL),
672 pepper_last_mouse_event_target_(NULL),
673 #endif
674 enumeration_completion_id_(0),
675 load_progress_tracker_(new LoadProgressTracker(this)),
676 session_storage_namespace_id_(params->session_storage_namespace_id),
677 next_snapshot_id_(0) {
680 void RenderViewImpl::Initialize(RenderViewImplParams* params) {
681 routing_id_ = params->routing_id;
682 surface_id_ = params->surface_id;
683 if (params->opener_id != MSG_ROUTING_NONE && params->is_renderer_created)
684 opener_id_ = params->opener_id;
686 // Ensure we start with a valid next_page_id_ from the browser.
687 DCHECK_GE(next_page_id_, 0);
689 RenderFrameImpl* main_render_frame = RenderFrameImpl::Create(
690 this, params->main_frame_routing_id);
691 // The main frame WebLocalFrame object is closed by
692 // RenderFrameImpl::frameDetached().
693 WebLocalFrame* web_frame = WebLocalFrame::create(main_render_frame);
694 main_render_frame->SetWebFrame(web_frame);
696 webwidget_ = WebView::create(this);
697 webwidget_mouse_lock_target_.reset(new WebWidgetLockTarget(webwidget_));
699 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
701 if (command_line.HasSwitch(switches::kStatsCollectionController))
702 stats_collection_observer_.reset(new StatsCollectionObserver(this));
704 #if defined(OS_ANDROID)
705 const std::string region_code =
706 command_line.HasSwitch(switches::kNetworkCountryIso)
707 ? command_line.GetSwitchValueASCII(switches::kNetworkCountryIso)
708 : net::android::GetTelephonyNetworkOperator();
709 content_detectors_.push_back(linked_ptr<ContentDetector>(
710 new AddressDetector()));
711 content_detectors_.push_back(linked_ptr<ContentDetector>(
712 new PhoneNumberDetector(region_code)));
713 content_detectors_.push_back(linked_ptr<ContentDetector>(
714 new EmailDetector()));
715 #endif
717 RenderThread::Get()->AddRoute(routing_id_, this);
718 // Take a reference on behalf of the RenderThread. This will be balanced
719 // when we receive ViewMsg_ClosePage.
720 AddRef();
721 if (RenderThreadImpl::current()) {
722 RenderThreadImpl::current()->WidgetCreated();
723 if (is_hidden_)
724 RenderThreadImpl::current()->WidgetHidden();
727 // If this is a popup, we must wait for the CreatingNew_ACK message before
728 // completing initialization. Otherwise, we can finish it now.
729 if (opener_id_ == MSG_ROUTING_NONE) {
730 did_show_ = true;
731 CompleteInit();
734 g_view_map.Get().insert(std::make_pair(webview(), this));
735 g_routing_id_view_map.Get().insert(std::make_pair(routing_id_, this));
736 webview()->setDeviceScaleFactor(device_scale_factor_);
737 webview()->settings()->setAcceleratedCompositingForFixedPositionEnabled(
738 ShouldUseFixedPositionCompositing(device_scale_factor_));
739 webview()->settings()->setAcceleratedCompositingForOverflowScrollEnabled(
740 ShouldUseAcceleratedCompositingForOverflowScroll(device_scale_factor_));
741 webview()->settings()->setCompositorDrivenAcceleratedScrollingEnabled(
742 ShouldUseUniversalAcceleratedCompositingForOverflowScroll());
743 webview()->settings()->setAcceleratedCompositingForTransitionEnabled(
744 ShouldUseTransitionCompositing(device_scale_factor_));
745 webview()->settings()->setAcceleratedCompositingForFixedRootBackgroundEnabled(
746 ShouldUseAcceleratedFixedRootBackground(device_scale_factor_));
747 webview()->settings()->setCompositedScrollingForFramesEnabled(
748 ShouldUseCompositedScrollingForFrames(device_scale_factor_));
750 ApplyWebPreferences(webkit_preferences_, webview());
752 webview()->settings()->setAllowConnectingInsecureWebSocket(
753 command_line.HasSwitch(switches::kAllowInsecureWebSocketFromHttpsOrigin));
755 main_render_frame_.reset(main_render_frame);
756 webview()->setMainFrame(main_render_frame_->GetWebFrame());
757 main_render_frame_->Initialize();
759 if (switches::IsTouchDragDropEnabled())
760 webview()->settings()->setTouchDragDropEnabled(true);
762 if (switches::IsTouchEditingEnabled())
763 webview()->settings()->setTouchEditingEnabled(true);
765 if (!params->frame_name.empty())
766 webview()->mainFrame()->setName(params->frame_name);
768 // TODO(davidben): Move this state from Blink into content.
769 if (params->window_was_created_with_opener)
770 webview()->setOpenedByDOM();
772 OnSetRendererPrefs(params->renderer_prefs);
774 #if defined(ENABLE_WEBRTC)
775 if (!media_stream_dispatcher_)
776 media_stream_dispatcher_ = new MediaStreamDispatcher(this);
777 #endif
779 new MHTMLGenerator(this);
780 #if defined(OS_MACOSX)
781 new TextInputClientObserver(this);
782 #endif // defined(OS_MACOSX)
784 #if defined(OS_ANDROID)
785 media_player_manager_ = new RendererMediaPlayerManager(this);
786 #endif
788 // The next group of objects all implement RenderViewObserver, so are deleted
789 // along with the RenderView automatically.
790 devtools_agent_ = new DevToolsAgent(this);
791 if (RenderWidgetCompositor* rwc = compositor()) {
792 webview()->devToolsAgent()->setLayerTreeId(rwc->GetLayerTreeId());
794 mouse_lock_dispatcher_ = new RenderViewMouseLockDispatcher(this);
796 history_controller_.reset(new HistoryController(this));
798 // Create renderer_accessibility_ if needed.
799 OnSetAccessibilityMode(params->accessibility_mode);
801 new IdleUserDetector(this);
803 if (command_line.HasSwitch(switches::kDomAutomationController))
804 enabled_bindings_ |= BINDINGS_POLICY_DOM_AUTOMATION;
805 if (command_line.HasSwitch(switches::kStatsCollectionController))
806 enabled_bindings_ |= BINDINGS_POLICY_STATS_COLLECTION;
808 ProcessViewLayoutFlags(command_line);
810 GetContentClient()->renderer()->RenderViewCreated(this);
812 // If we have an opener_id but we weren't created by a renderer, then
813 // it's the browser asking us to set our opener to another RenderView.
814 if (params->opener_id != MSG_ROUTING_NONE && !params->is_renderer_created) {
815 RenderViewImpl* opener_view = FromRoutingID(params->opener_id);
816 if (opener_view)
817 webview()->mainFrame()->setOpener(opener_view->webview()->mainFrame());
820 // If we are initially swapped out, navigate to kSwappedOutURL.
821 // This ensures we are in a unique origin that others cannot script.
822 if (is_swapped_out_)
823 NavigateToSwappedOutURL(webview()->mainFrame());
826 RenderViewImpl::~RenderViewImpl() {
827 for (BitmapMap::iterator it = disambiguation_bitmaps_.begin();
828 it != disambiguation_bitmaps_.end();
829 ++it)
830 delete it->second;
831 history_page_ids_.clear();
833 base::debug::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_);
835 // If file chooser is still waiting for answer, dispatch empty answer.
836 while (!file_chooser_completions_.empty()) {
837 if (file_chooser_completions_.front()->completion) {
838 file_chooser_completions_.front()->completion->didChooseFile(
839 WebVector<WebString>());
841 file_chooser_completions_.pop_front();
844 #if defined(OS_ANDROID)
845 // The date/time picker client is both a scoped_ptr member of this class and
846 // a RenderViewObserver. Reset it to prevent double deletion.
847 date_time_picker_client_.reset();
848 #endif
850 #ifndef NDEBUG
851 // Make sure we are no longer referenced by the ViewMap or RoutingIDViewMap.
852 ViewMap* views = g_view_map.Pointer();
853 for (ViewMap::iterator it = views->begin(); it != views->end(); ++it)
854 DCHECK_NE(this, it->second) << "Failed to call Close?";
855 RoutingIDViewMap* routing_id_views = g_routing_id_view_map.Pointer();
856 for (RoutingIDViewMap::iterator it = routing_id_views->begin();
857 it != routing_id_views->end(); ++it)
858 DCHECK_NE(this, it->second) << "Failed to call Close?";
859 #endif
861 FOR_EACH_OBSERVER(RenderViewObserver, observers_, RenderViewGone());
862 FOR_EACH_OBSERVER(RenderViewObserver, observers_, OnDestruct());
865 /*static*/
866 RenderViewImpl* RenderViewImpl::FromWebView(WebView* webview) {
867 ViewMap* views = g_view_map.Pointer();
868 ViewMap::iterator it = views->find(webview);
869 return it == views->end() ? NULL : it->second;
872 /*static*/
873 RenderView* RenderView::FromWebView(blink::WebView* webview) {
874 return RenderViewImpl::FromWebView(webview);
877 /*static*/
878 RenderViewImpl* RenderViewImpl::FromRoutingID(int32 routing_id) {
879 RoutingIDViewMap* views = g_routing_id_view_map.Pointer();
880 RoutingIDViewMap::iterator it = views->find(routing_id);
881 return it == views->end() ? NULL : it->second;
884 /*static*/
885 RenderView* RenderView::FromRoutingID(int routing_id) {
886 return RenderViewImpl::FromRoutingID(routing_id);
889 /*static*/
890 void RenderView::ForEach(RenderViewVisitor* visitor) {
891 ViewMap* views = g_view_map.Pointer();
892 for (ViewMap::iterator it = views->begin(); it != views->end(); ++it) {
893 if (!visitor->Visit(it->second))
894 return;
898 /*static*/
899 RenderViewImpl* RenderViewImpl::Create(
900 int32 opener_id,
901 bool window_was_created_with_opener,
902 const RendererPreferences& renderer_prefs,
903 const WebPreferences& webkit_prefs,
904 int32 routing_id,
905 int32 main_frame_routing_id,
906 int32 surface_id,
907 int64 session_storage_namespace_id,
908 const base::string16& frame_name,
909 bool is_renderer_created,
910 bool swapped_out,
911 bool hidden,
912 bool never_visible,
913 int32 next_page_id,
914 const blink::WebScreenInfo& screen_info,
915 AccessibilityMode accessibility_mode) {
916 DCHECK(routing_id != MSG_ROUTING_NONE);
917 RenderViewImplParams params(opener_id,
918 window_was_created_with_opener,
919 renderer_prefs,
920 webkit_prefs,
921 routing_id,
922 main_frame_routing_id,
923 surface_id,
924 session_storage_namespace_id,
925 frame_name,
926 is_renderer_created,
927 swapped_out,
928 hidden,
929 never_visible,
930 next_page_id,
931 screen_info,
932 accessibility_mode);
933 RenderViewImpl* render_view = NULL;
934 if (g_create_render_view_impl)
935 render_view = g_create_render_view_impl(&params);
936 else
937 render_view = new RenderViewImpl(&params);
939 render_view->Initialize(&params);
940 return render_view;
943 // static
944 void RenderViewImpl::InstallCreateHook(
945 RenderViewImpl* (*create_render_view_impl)(RenderViewImplParams*)) {
946 CHECK(!g_create_render_view_impl);
947 g_create_render_view_impl = create_render_view_impl;
950 void RenderViewImpl::AddObserver(RenderViewObserver* observer) {
951 observers_.AddObserver(observer);
954 void RenderViewImpl::RemoveObserver(RenderViewObserver* observer) {
955 observer->RenderViewGone();
956 observers_.RemoveObserver(observer);
959 blink::WebView* RenderViewImpl::webview() const {
960 return static_cast<blink::WebView*>(webwidget());
963 #if defined(ENABLE_PLUGINS)
964 void RenderViewImpl::PepperInstanceCreated(
965 PepperPluginInstanceImpl* instance) {
966 active_pepper_instances_.insert(instance);
969 void RenderViewImpl::PepperInstanceDeleted(
970 PepperPluginInstanceImpl* instance) {
971 active_pepper_instances_.erase(instance);
973 if (pepper_last_mouse_event_target_ == instance)
974 pepper_last_mouse_event_target_ = NULL;
975 if (focused_pepper_plugin_ == instance)
976 PepperFocusChanged(instance, false);
979 void RenderViewImpl::PepperFocusChanged(PepperPluginInstanceImpl* instance,
980 bool focused) {
981 if (focused)
982 focused_pepper_plugin_ = instance;
983 else if (focused_pepper_plugin_ == instance)
984 focused_pepper_plugin_ = NULL;
986 UpdateTextInputType();
987 UpdateSelectionBounds();
990 void RenderViewImpl::RegisterPluginDelegate(WebPluginDelegateProxy* delegate) {
991 plugin_delegates_.insert(delegate);
992 // If the renderer is visible, set initial visibility and focus state.
993 if (!is_hidden()) {
994 #if defined(OS_MACOSX)
995 delegate->SetContainerVisibility(true);
996 if (webview() && webview()->isActive())
997 delegate->SetWindowFocus(true);
998 #endif
1000 // Plugins start assuming the content has focus (so that they work in
1001 // environments where RenderView isn't hosting them), so we always have to
1002 // set the initial state. See webplugin_delegate_impl.h for details.
1003 delegate->SetContentAreaFocus(has_focus());
1006 void RenderViewImpl::UnregisterPluginDelegate(
1007 WebPluginDelegateProxy* delegate) {
1008 plugin_delegates_.erase(delegate);
1011 #if defined(OS_WIN)
1012 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1013 if (focused)
1014 focused_plugin_id_ = plugin_id;
1015 else
1016 focused_plugin_id_ = -1;
1018 #endif
1020 #if defined(OS_MACOSX)
1021 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1022 Send(new ViewHostMsg_PluginFocusChanged(routing_id(), focused, plugin_id));
1025 void RenderViewImpl::StartPluginIme() {
1026 IPC::Message* msg = new ViewHostMsg_StartPluginIme(routing_id());
1027 // This message can be sent during event-handling, and needs to be delivered
1028 // within that context.
1029 msg->set_unblock(true);
1030 Send(msg);
1032 #endif // defined(OS_MACOSX)
1034 #endif // ENABLE_PLUGINS
1036 void RenderViewImpl::TransferActiveWheelFlingAnimation(
1037 const blink::WebActiveWheelFlingParameters& params) {
1038 if (webview())
1039 webview()->transferActiveWheelFlingAnimation(params);
1042 bool RenderViewImpl::HasIMETextFocus() {
1043 return GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE;
1046 bool RenderViewImpl::OnMessageReceived(const IPC::Message& message) {
1047 WebFrame* main_frame = webview() ? webview()->mainFrame() : NULL;
1048 if (main_frame)
1049 GetContentClient()->SetActiveURL(main_frame->document().url());
1051 ObserverListBase<RenderViewObserver>::Iterator it(observers_);
1052 RenderViewObserver* observer;
1053 while ((observer = it.GetNext()) != NULL)
1054 if (observer->OnMessageReceived(message))
1055 return true;
1057 bool handled = true;
1058 bool msg_is_ok = true;
1059 IPC_BEGIN_MESSAGE_MAP_EX(RenderViewImpl, message, msg_is_ok)
1060 IPC_MESSAGE_HANDLER(InputMsg_ExecuteEditCommand, OnExecuteEditCommand)
1061 IPC_MESSAGE_HANDLER(InputMsg_MoveCaret, OnMoveCaret)
1062 IPC_MESSAGE_HANDLER(InputMsg_ScrollFocusedEditableNodeIntoRect,
1063 OnScrollFocusedEditableNodeIntoRect)
1064 IPC_MESSAGE_HANDLER(InputMsg_SetEditCommandsForNextKeyEvent,
1065 OnSetEditCommandsForNextKeyEvent)
1066 IPC_MESSAGE_HANDLER(FrameMsg_Navigate, OnNavigate)
1067 IPC_MESSAGE_HANDLER(ViewMsg_Stop, OnStop)
1068 IPC_MESSAGE_HANDLER(ViewMsg_SetName, OnSetName)
1069 IPC_MESSAGE_HANDLER(ViewMsg_CopyImageAt, OnCopyImageAt)
1070 IPC_MESSAGE_HANDLER(ViewMsg_Find, OnFind)
1071 IPC_MESSAGE_HANDLER(ViewMsg_StopFinding, OnStopFinding)
1072 IPC_MESSAGE_HANDLER(ViewMsg_Zoom, OnZoom)
1073 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevel, OnSetZoomLevel)
1074 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForLoadingURL,
1075 OnSetZoomLevelForLoadingURL)
1076 IPC_MESSAGE_HANDLER(ViewMsg_SetPageEncoding, OnSetPageEncoding)
1077 IPC_MESSAGE_HANDLER(ViewMsg_ResetPageEncodingToDefault,
1078 OnResetPageEncodingToDefault)
1079 IPC_MESSAGE_HANDLER(ViewMsg_PostMessageEvent, OnPostMessageEvent)
1080 IPC_MESSAGE_HANDLER(DragMsg_TargetDragEnter, OnDragTargetDragEnter)
1081 IPC_MESSAGE_HANDLER(DragMsg_TargetDragOver, OnDragTargetDragOver)
1082 IPC_MESSAGE_HANDLER(DragMsg_TargetDragLeave, OnDragTargetDragLeave)
1083 IPC_MESSAGE_HANDLER(DragMsg_TargetDrop, OnDragTargetDrop)
1084 IPC_MESSAGE_HANDLER(DragMsg_SourceEnded, OnDragSourceEnded)
1085 IPC_MESSAGE_HANDLER(DragMsg_SourceSystemDragEnded,
1086 OnDragSourceSystemDragEnded)
1087 IPC_MESSAGE_HANDLER(ViewMsg_AllowBindings, OnAllowBindings)
1088 IPC_MESSAGE_HANDLER(ViewMsg_SetInitialFocus, OnSetInitialFocus)
1089 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTargetURL_ACK, OnUpdateTargetURLAck)
1090 IPC_MESSAGE_HANDLER(ViewMsg_UpdateWebPreferences, OnUpdateWebPreferences)
1091 IPC_MESSAGE_HANDLER(ViewMsg_EnumerateDirectoryResponse,
1092 OnEnumerateDirectoryResponse)
1093 IPC_MESSAGE_HANDLER(ViewMsg_RunFileChooserResponse, OnFileChooserResponse)
1094 IPC_MESSAGE_HANDLER(ViewMsg_SuppressDialogsUntilSwapOut,
1095 OnSuppressDialogsUntilSwapOut)
1096 IPC_MESSAGE_HANDLER(ViewMsg_ClosePage, OnClosePage)
1097 IPC_MESSAGE_HANDLER(ViewMsg_ThemeChanged, OnThemeChanged)
1098 IPC_MESSAGE_HANDLER(ViewMsg_MoveOrResizeStarted, OnMoveOrResizeStarted)
1099 IPC_MESSAGE_HANDLER(ViewMsg_ClearFocusedElement, OnClearFocusedElement)
1100 IPC_MESSAGE_HANDLER(ViewMsg_SetBackground, OnSetBackground)
1101 IPC_MESSAGE_HANDLER(ViewMsg_EnablePreferredSizeChangedMode,
1102 OnEnablePreferredSizeChangedMode)
1103 IPC_MESSAGE_HANDLER(ViewMsg_EnableAutoResize, OnEnableAutoResize)
1104 IPC_MESSAGE_HANDLER(ViewMsg_DisableAutoResize, OnDisableAutoResize)
1105 IPC_MESSAGE_HANDLER(ViewMsg_DisableScrollbarsForSmallWindows,
1106 OnDisableScrollbarsForSmallWindows)
1107 IPC_MESSAGE_HANDLER(ViewMsg_SetRendererPrefs, OnSetRendererPrefs)
1108 IPC_MESSAGE_HANDLER(ViewMsg_MediaPlayerActionAt, OnMediaPlayerActionAt)
1109 IPC_MESSAGE_HANDLER(ViewMsg_OrientationChangeEvent,
1110 OnOrientationChangeEvent)
1111 IPC_MESSAGE_HANDLER(ViewMsg_PluginActionAt, OnPluginActionAt)
1112 IPC_MESSAGE_HANDLER(ViewMsg_SetActive, OnSetActive)
1113 IPC_MESSAGE_HANDLER(ViewMsg_GetAllSavableResourceLinksForCurrentPage,
1114 OnGetAllSavableResourceLinksForCurrentPage)
1115 IPC_MESSAGE_HANDLER(
1116 ViewMsg_GetSerializedHtmlDataForCurrentPageWithLocalLinks,
1117 OnGetSerializedHtmlDataForCurrentPageWithLocalLinks)
1118 IPC_MESSAGE_HANDLER(ViewMsg_ShowContextMenu, OnShowContextMenu)
1119 // TODO(viettrungluu): Move to a separate message filter.
1120 IPC_MESSAGE_HANDLER(ViewMsg_SetHistoryLengthAndPrune,
1121 OnSetHistoryLengthAndPrune)
1122 IPC_MESSAGE_HANDLER(ViewMsg_EnableViewSourceMode, OnEnableViewSourceMode)
1123 IPC_MESSAGE_HANDLER(ViewMsg_SetAccessibilityMode, OnSetAccessibilityMode)
1124 IPC_MESSAGE_HANDLER(ViewMsg_DisownOpener, OnDisownOpener)
1125 IPC_MESSAGE_HANDLER(ViewMsg_ReleaseDisambiguationPopupBitmap,
1126 OnReleaseDisambiguationPopupBitmap)
1127 IPC_MESSAGE_HANDLER(ViewMsg_WindowSnapshotCompleted,
1128 OnWindowSnapshotCompleted)
1129 #if defined(OS_ANDROID)
1130 IPC_MESSAGE_HANDLER(InputMsg_ActivateNearestFindResult,
1131 OnActivateNearestFindResult)
1132 IPC_MESSAGE_HANDLER(ViewMsg_FindMatchRects, OnFindMatchRects)
1133 IPC_MESSAGE_HANDLER(ViewMsg_SelectPopupMenuItems, OnSelectPopupMenuItems)
1134 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTopControlsState,
1135 OnUpdateTopControlsState)
1136 IPC_MESSAGE_HANDLER(ViewMsg_PauseVideo, OnPauseVideo)
1137 IPC_MESSAGE_HANDLER(ViewMsg_ExtractSmartClipData, OnExtractSmartClipData)
1138 #elif defined(OS_MACOSX)
1139 IPC_MESSAGE_HANDLER(ViewMsg_PluginImeCompositionCompleted,
1140 OnPluginImeCompositionCompleted)
1141 IPC_MESSAGE_HANDLER(ViewMsg_SelectPopupMenuItem, OnSelectPopupMenuItem)
1142 IPC_MESSAGE_HANDLER(ViewMsg_SetInLiveResize, OnSetInLiveResize)
1143 IPC_MESSAGE_HANDLER(ViewMsg_SetWindowVisibility, OnSetWindowVisibility)
1144 IPC_MESSAGE_HANDLER(ViewMsg_WindowFrameChanged, OnWindowFrameChanged)
1145 #endif
1146 // Adding a new message? Add platform independent ones first, then put the
1147 // platform specific ones at the end.
1149 // Have the super handle all other messages.
1150 IPC_MESSAGE_UNHANDLED(handled = RenderWidget::OnMessageReceived(message))
1151 IPC_END_MESSAGE_MAP()
1153 if (!msg_is_ok) {
1154 // The message had a handler, but its deserialization failed.
1155 // Kill the renderer to avoid potential spoofing attacks.
1156 CHECK(false) << "Unable to deserialize message in RenderViewImpl.";
1159 return handled;
1162 void RenderViewImpl::OnNavigate(const FrameMsg_Navigate_Params& params) {
1163 FOR_EACH_OBSERVER(RenderViewObserver, observers_, Navigate(params.url));
1166 bool RenderViewImpl::IsBackForwardToStaleEntry(
1167 const FrameMsg_Navigate_Params& params,
1168 bool is_reload) {
1169 // Make sure this isn't a back/forward to an entry we have already cropped
1170 // or replaced from our history, before the browser knew about it. If so,
1171 // a new navigation has committed in the mean time, and we can ignore this.
1172 bool is_back_forward = !is_reload && params.page_state.IsValid();
1174 // Note: if the history_list_length_ is 0 for a back/forward, we must be
1175 // restoring from a previous session. We'll update our state in OnNavigate.
1176 if (!is_back_forward || history_list_length_ <= 0)
1177 return false;
1179 DCHECK_EQ(static_cast<int>(history_page_ids_.size()), history_list_length_);
1181 // Check for whether the forward history has been cropped due to a recent
1182 // navigation the browser didn't know about.
1183 if (params.pending_history_list_offset >= history_list_length_)
1184 return true;
1186 // Check for whether this entry has been replaced with a new one.
1187 int expected_page_id =
1188 history_page_ids_[params.pending_history_list_offset];
1189 if (expected_page_id > 0 && params.page_id != expected_page_id) {
1190 if (params.page_id < expected_page_id)
1191 return true;
1193 // Otherwise we've removed an earlier entry and should have shifted all
1194 // entries left. For now, it's ok to lazily update the list.
1195 // TODO(creis): Notify all live renderers when we remove entries from
1196 // the front of the list, so that we don't hit this case.
1197 history_page_ids_[params.pending_history_list_offset] = params.page_id;
1200 return false;
1203 // Stop loading the current page.
1204 void RenderViewImpl::OnStop() {
1205 if (webview())
1206 webview()->mainFrame()->stopLoading();
1207 FOR_EACH_OBSERVER(RenderViewObserver, observers_, OnStop());
1208 main_render_frame_->OnStop();
1211 void RenderViewImpl::OnCopyImageAt(int x, int y) {
1212 webview()->copyImageAt(WebPoint(x, y));
1215 void RenderViewImpl::OnUpdateTargetURLAck() {
1216 // Check if there is a targeturl waiting to be sent.
1217 if (target_url_status_ == TARGET_PENDING) {
1218 Send(new ViewHostMsg_UpdateTargetURL(routing_id_, page_id_,
1219 pending_target_url_));
1222 target_url_status_ = TARGET_NONE;
1225 void RenderViewImpl::OnExecuteEditCommand(const std::string& name,
1226 const std::string& value) {
1227 if (!webview() || !webview()->focusedFrame())
1228 return;
1230 webview()->focusedFrame()->executeCommand(
1231 WebString::fromUTF8(name), WebString::fromUTF8(value));
1234 void RenderViewImpl::OnMoveCaret(const gfx::Point& point) {
1235 if (!webview())
1236 return;
1238 Send(new ViewHostMsg_MoveCaret_ACK(routing_id_));
1240 webview()->focusedFrame()->moveCaretSelection(point);
1243 void RenderViewImpl::OnScrollFocusedEditableNodeIntoRect(
1244 const gfx::Rect& rect) {
1245 if (has_scrolled_focused_editable_node_into_rect_ &&
1246 rect == rect_for_scrolled_focused_editable_node_) {
1247 return;
1250 blink::WebElement element = GetFocusedElement();
1251 if (!element.isNull() && IsEditableNode(element)) {
1252 rect_for_scrolled_focused_editable_node_ = rect;
1253 has_scrolled_focused_editable_node_into_rect_ = true;
1254 webview()->scrollFocusedNodeIntoRect(rect);
1258 void RenderViewImpl::OnSetEditCommandsForNextKeyEvent(
1259 const EditCommands& edit_commands) {
1260 edit_commands_ = edit_commands;
1263 void RenderViewImpl::OnSetName(const std::string& name) {
1264 if (!webview())
1265 return;
1267 webview()->mainFrame()->setName(WebString::fromUTF8(name));
1270 void RenderViewImpl::OnSetHistoryLengthAndPrune(int history_length,
1271 int32 minimum_page_id) {
1272 DCHECK_GE(history_length, 0);
1273 DCHECK(history_list_offset_ == history_list_length_ - 1);
1274 DCHECK_GE(minimum_page_id, -1);
1276 // Generate the new list.
1277 std::vector<int32> new_history_page_ids(history_length, -1);
1278 for (size_t i = 0; i < history_page_ids_.size(); ++i) {
1279 if (minimum_page_id >= 0 && history_page_ids_[i] < minimum_page_id)
1280 continue;
1281 new_history_page_ids.push_back(history_page_ids_[i]);
1283 new_history_page_ids.swap(history_page_ids_);
1285 // Update indexes.
1286 history_list_length_ = history_page_ids_.size();
1287 history_list_offset_ = history_list_length_ - 1;
1291 void RenderViewImpl::OnSetInitialFocus(bool reverse) {
1292 if (!webview())
1293 return;
1294 webview()->setInitialFocus(reverse);
1297 #if defined(OS_MACOSX)
1298 void RenderViewImpl::OnSetInLiveResize(bool in_live_resize) {
1299 if (!webview())
1300 return;
1301 if (in_live_resize)
1302 webview()->willStartLiveResize();
1303 else
1304 webview()->willEndLiveResize();
1306 #endif
1308 #if defined(OS_ANDROID)
1309 void RenderViewImpl::OnPauseVideo() {
1310 // Inform RendererMediaPlayerManager to release all video player resources.
1311 // If something is in progress the resource will not be freed, it will
1312 // only be freed once the tab is destroyed or if the user navigates away
1313 // via WebMediaPlayerAndroid::Destroy.
1314 media_player_manager_->ReleaseVideoResources();
1316 #endif
1318 ///////////////////////////////////////////////////////////////////////////////
1320 // Tell the embedding application that the title of the active page has changed
1321 void RenderViewImpl::UpdateTitle(WebFrame* frame,
1322 const base::string16& title,
1323 WebTextDirection title_direction) {
1324 // Ignore all but top level navigations.
1325 if (frame->parent())
1326 return;
1328 base::debug::TraceLog::GetInstance()->UpdateProcessLabel(
1329 routing_id_, base::UTF16ToUTF8(title));
1331 base::string16 shortened_title = title.substr(0, kMaxTitleChars);
1332 Send(new ViewHostMsg_UpdateTitle(routing_id_, page_id_, shortened_title,
1333 title_direction));
1336 void RenderViewImpl::UpdateEncoding(WebFrame* frame,
1337 const std::string& encoding_name) {
1338 // Only update main frame's encoding_name.
1339 if (webview()->mainFrame() == frame &&
1340 last_encoding_name_ != encoding_name) {
1341 // Save the encoding name for later comparing.
1342 last_encoding_name_ = encoding_name;
1344 Send(new ViewHostMsg_UpdateEncoding(routing_id_, last_encoding_name_));
1348 // Sends the last committed session history state to the browser so it will be
1349 // saved before we navigate to a new page. This must be called *before* the
1350 // page ID has been updated so we know what it was.
1351 void RenderViewImpl::UpdateSessionHistory(WebFrame* frame) {
1352 // If we have a valid page ID at this point, then it corresponds to the page
1353 // we are navigating away from. Otherwise, this is the first navigation, so
1354 // there is no past session history to record.
1355 if (page_id_ == -1)
1356 return;
1357 SendUpdateState(history_controller_->GetPreviousEntry());
1360 void RenderViewImpl::SendUpdateState(HistoryEntry* entry) {
1361 if (!entry)
1362 return;
1364 // Don't send state updates for kSwappedOutURL.
1365 if (entry->root().urlString() == WebString::fromUTF8(kSwappedOutURL))
1366 return;
1368 Send(new ViewHostMsg_UpdateState(
1369 routing_id_, page_id_, HistoryEntryToPageState(entry)));
1372 bool RenderViewImpl::SendAndRunNestedMessageLoop(IPC::SyncMessage* message) {
1373 // Before WebKit asks us to show an alert (etc.), it takes care of doing the
1374 // equivalent of WebView::willEnterModalLoop. In the case of showModalDialog
1375 // it is particularly important that we do not call willEnterModalLoop as
1376 // that would defer resource loads for the dialog itself.
1377 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
1378 RenderThreadImpl::current()->DoNotNotifyWebKitOfModalLoop();
1380 message->EnableMessagePumping(); // Runs a nested message loop.
1381 return Send(message);
1384 void RenderViewImpl::GetWindowSnapshot(const WindowSnapshotCallback& callback) {
1385 int id = next_snapshot_id_++;
1386 pending_snapshots_.insert(std::make_pair(id, callback));
1387 ui::LatencyInfo latency_info;
1388 latency_info.AddLatencyNumber(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
1390 id);
1391 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1392 if (RenderWidgetCompositor* rwc = compositor()) {
1393 latency_info_swap_promise_monitor =
1394 rwc->CreateLatencyInfoSwapPromiseMonitor(&latency_info).Pass();
1396 ScheduleCompositeWithForcedRedraw();
1399 void RenderViewImpl::OnWindowSnapshotCompleted(const int snapshot_id,
1400 const gfx::Size& size, const std::vector<unsigned char>& png) {
1402 // Any pending snapshots with a lower ID than the one received are considered
1403 // to be implicitly complete, and returned the same snapshot data.
1404 PendingSnapshotMap::iterator it = pending_snapshots_.begin();
1405 while(it != pending_snapshots_.end()) {
1406 if (it->first <= snapshot_id) {
1407 it->second.Run(size, png);
1408 pending_snapshots_.erase(it++);
1409 } else {
1410 ++it;
1415 // blink::WebViewClient ------------------------------------------------------
1417 WebView* RenderViewImpl::createView(WebLocalFrame* creator,
1418 const WebURLRequest& request,
1419 const WebWindowFeatures& features,
1420 const WebString& frame_name,
1421 WebNavigationPolicy policy,
1422 bool suppress_opener) {
1423 ViewHostMsg_CreateWindow_Params params;
1424 params.opener_id = routing_id_;
1425 params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
1426 if (GetContentClient()->renderer()->AllowPopup())
1427 params.user_gesture = true;
1428 params.window_container_type = WindowFeaturesToContainerType(features);
1429 params.session_storage_namespace_id = session_storage_namespace_id_;
1430 if (frame_name != "_blank")
1431 params.frame_name = frame_name;
1432 params.opener_render_frame_id =
1433 RenderFrameImpl::FromWebFrame(creator)->GetRoutingID();
1434 params.opener_url = creator->document().url();
1435 params.opener_top_level_frame_url = creator->top()->document().url();
1436 GURL security_url(creator->document().securityOrigin().toString());
1437 if (!security_url.is_valid())
1438 security_url = GURL();
1439 params.opener_security_origin = security_url;
1440 params.opener_suppressed = suppress_opener;
1441 params.disposition = NavigationPolicyToDisposition(policy);
1442 if (!request.isNull()) {
1443 params.target_url = request.url();
1444 params.referrer = GetReferrerFromRequest(creator, request);
1446 params.features = features;
1448 for (size_t i = 0; i < features.additionalFeatures.size(); ++i)
1449 params.additional_features.push_back(features.additionalFeatures[i]);
1451 int32 routing_id = MSG_ROUTING_NONE;
1452 int32 main_frame_routing_id = MSG_ROUTING_NONE;
1453 int32 surface_id = 0;
1454 int64 cloned_session_storage_namespace_id;
1456 RenderThread::Get()->Send(
1457 new ViewHostMsg_CreateWindow(params,
1458 &routing_id,
1459 &main_frame_routing_id,
1460 &surface_id,
1461 &cloned_session_storage_namespace_id));
1462 if (routing_id == MSG_ROUTING_NONE)
1463 return NULL;
1465 WebUserGestureIndicator::consumeUserGesture();
1467 // While this view may be a background extension page, it can spawn a visible
1468 // render view. So we just assume that the new one is not another background
1469 // page instead of passing on our own value.
1470 // TODO(vangelis): Can we tell if the new view will be a background page?
1471 bool never_visible = false;
1473 // The initial hidden state for the RenderViewImpl here has to match what the
1474 // browser will eventually decide for the given disposition. Since we have to
1475 // return from this call synchronously, we just have to make our best guess
1476 // and rely on the browser sending a WasHidden / WasShown message if it
1477 // disagrees.
1478 RenderViewImpl* view = RenderViewImpl::Create(
1479 routing_id_,
1480 true, // window_was_created_with_opener
1481 renderer_preferences_,
1482 webkit_preferences_,
1483 routing_id,
1484 main_frame_routing_id,
1485 surface_id,
1486 cloned_session_storage_namespace_id,
1487 base::string16(), // WebCore will take care of setting the correct name.
1488 true, // is_renderer_created
1489 false, // swapped_out
1490 params.disposition == NEW_BACKGROUND_TAB, // hidden
1491 never_visible,
1492 1, // next_page_id
1493 screen_info_,
1494 accessibility_mode_);
1495 view->opened_by_user_gesture_ = params.user_gesture;
1497 // Record whether the creator frame is trying to suppress the opener field.
1498 view->opener_suppressed_ = params.opener_suppressed;
1500 return view->webview();
1503 WebWidget* RenderViewImpl::createPopupMenu(blink::WebPopupType popup_type) {
1504 RenderWidget* widget =
1505 RenderWidget::Create(routing_id_, popup_type, screen_info_);
1506 if (!widget)
1507 return NULL;
1508 if (screen_metrics_emulator_) {
1509 widget->SetPopupOriginAdjustmentsForEmulation(
1510 screen_metrics_emulator_.get());
1512 return widget->webwidget();
1515 WebExternalPopupMenu* RenderViewImpl::createExternalPopupMenu(
1516 const WebPopupMenuInfo& popup_menu_info,
1517 WebExternalPopupMenuClient* popup_menu_client) {
1518 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1519 // An IPC message is sent to the browser to build and display the actual
1520 // popup. The user could have time to click a different select by the time
1521 // the popup is shown. In that case external_popup_menu_ is non NULL.
1522 // By returning NULL in that case, we instruct WebKit to cancel that new
1523 // popup. So from the user perspective, only the first one will show, and
1524 // will have to close the first one before another one can be shown.
1525 if (external_popup_menu_)
1526 return NULL;
1527 external_popup_menu_.reset(
1528 new ExternalPopupMenu(this, popup_menu_info, popup_menu_client));
1529 if (screen_metrics_emulator_) {
1530 SetExternalPopupOriginAdjustmentsForEmulation(
1531 external_popup_menu_.get(), screen_metrics_emulator_.get());
1533 return external_popup_menu_.get();
1534 #else
1535 return NULL;
1536 #endif
1539 WebStorageNamespace* RenderViewImpl::createSessionStorageNamespace() {
1540 CHECK(session_storage_namespace_id_ != kInvalidSessionStorageNamespaceId);
1541 return new WebStorageNamespaceImpl(session_storage_namespace_id_);
1544 void RenderViewImpl::printPage(WebLocalFrame* frame) {
1545 FOR_EACH_OBSERVER(RenderViewObserver, observers_,
1546 PrintPage(frame, handling_input_event_));
1549 bool RenderViewImpl::enumerateChosenDirectory(
1550 const WebString& path,
1551 WebFileChooserCompletion* chooser_completion) {
1552 int id = enumeration_completion_id_++;
1553 enumeration_completions_[id] = chooser_completion;
1554 return Send(new ViewHostMsg_EnumerateDirectory(
1555 routing_id_,
1557 base::FilePath::FromUTF16Unsafe(path)));
1560 void RenderViewImpl::FrameDidStartLoading(WebFrame* frame) {
1561 if (load_progress_tracker_ != NULL) {
1562 load_progress_tracker_->DidStartLoading(
1563 RenderFrameImpl::FromWebFrame(frame)->GetRoutingID());
1565 DCHECK_GE(frames_in_progress_, 0);
1566 if (frames_in_progress_ == 0)
1567 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStartLoading());
1568 frames_in_progress_++;
1571 void RenderViewImpl::FrameDidStopLoading(WebFrame* frame) {
1572 if (load_progress_tracker_ != NULL) {
1573 load_progress_tracker_->DidStopLoading(
1574 RenderFrameImpl::FromWebFrame(frame)->GetRoutingID());
1576 // TODO(japhet): This should be a DCHECK, but the pdf plugin sometimes
1577 // calls DidStopLoading() without a matching DidStartLoading().
1578 if (frames_in_progress_ == 0)
1579 return;
1580 frames_in_progress_--;
1581 if (frames_in_progress_ == 0) {
1582 DidStopLoadingIcons();
1583 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStopLoading());
1587 void RenderViewImpl::FrameDidChangeLoadProgress(WebFrame* frame,
1588 double load_progress) {
1589 if (load_progress_tracker_ != NULL) {
1590 load_progress_tracker_->DidChangeLoadProgress(
1591 RenderFrameImpl::FromWebFrame(frame)->GetRoutingID(), load_progress);
1595 void RenderViewImpl::didCancelCompositionOnSelectionChange() {
1596 Send(new ViewHostMsg_ImeCancelComposition(routing_id()));
1599 void RenderViewImpl::didExecuteCommand(const WebString& command_name) {
1600 const std::string& name = base::UTF16ToUTF8(command_name);
1601 if (StartsWithASCII(name, "Move", true) ||
1602 StartsWithASCII(name, "Insert", true) ||
1603 StartsWithASCII(name, "Delete", true))
1604 return;
1605 RenderThreadImpl::current()->RecordComputedAction(name);
1608 bool RenderViewImpl::handleCurrentKeyboardEvent() {
1609 if (edit_commands_.empty())
1610 return false;
1612 WebFrame* frame = webview()->focusedFrame();
1613 if (!frame)
1614 return false;
1616 EditCommands::iterator it = edit_commands_.begin();
1617 EditCommands::iterator end = edit_commands_.end();
1619 bool did_execute_command = false;
1620 for (; it != end; ++it) {
1621 // In gtk and cocoa, it's possible to bind multiple edit commands to one
1622 // key (but it's the exception). Once one edit command is not executed, it
1623 // seems safest to not execute the rest.
1624 if (!frame->executeCommand(WebString::fromUTF8(it->name),
1625 WebString::fromUTF8(it->value),
1626 GetFocusedElement()))
1627 break;
1628 did_execute_command = true;
1631 return did_execute_command;
1634 bool RenderViewImpl::runFileChooser(
1635 const blink::WebFileChooserParams& params,
1636 WebFileChooserCompletion* chooser_completion) {
1637 // Do not open the file dialog in a hidden RenderView.
1638 if (is_hidden())
1639 return false;
1640 FileChooserParams ipc_params;
1641 if (params.directory)
1642 ipc_params.mode = FileChooserParams::UploadFolder;
1643 else if (params.multiSelect)
1644 ipc_params.mode = FileChooserParams::OpenMultiple;
1645 else if (params.saveAs)
1646 ipc_params.mode = FileChooserParams::Save;
1647 else
1648 ipc_params.mode = FileChooserParams::Open;
1649 ipc_params.title = params.title;
1650 ipc_params.default_file_name =
1651 base::FilePath::FromUTF16Unsafe(params.initialValue);
1652 ipc_params.accept_types.reserve(params.acceptTypes.size());
1653 for (size_t i = 0; i < params.acceptTypes.size(); ++i)
1654 ipc_params.accept_types.push_back(params.acceptTypes[i]);
1655 #if defined(OS_ANDROID)
1656 ipc_params.capture = params.useMediaCapture;
1657 #endif
1659 return ScheduleFileChooser(ipc_params, chooser_completion);
1662 void RenderViewImpl::showValidationMessage(
1663 const blink::WebRect& anchor_in_root_view,
1664 const blink::WebString& main_text,
1665 const blink::WebString& sub_text,
1666 blink::WebTextDirection hint) {
1667 base::string16 wrapped_main_text = main_text;
1668 base::string16 wrapped_sub_text = sub_text;
1669 if (hint == blink::WebTextDirectionLeftToRight) {
1670 wrapped_main_text =
1671 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_main_text);
1672 if (!wrapped_sub_text.empty()) {
1673 wrapped_sub_text =
1674 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_sub_text);
1676 } else if (hint == blink::WebTextDirectionRightToLeft
1677 && !base::i18n::IsRTL()) {
1678 base::i18n::WrapStringWithRTLFormatting(&wrapped_main_text);
1679 if (!wrapped_sub_text.empty()) {
1680 base::i18n::WrapStringWithRTLFormatting(&wrapped_sub_text);
1683 Send(new ViewHostMsg_ShowValidationMessage(
1684 routing_id(), anchor_in_root_view, wrapped_main_text, wrapped_sub_text));
1687 void RenderViewImpl::hideValidationMessage() {
1688 Send(new ViewHostMsg_HideValidationMessage(routing_id()));
1691 void RenderViewImpl::moveValidationMessage(
1692 const blink::WebRect& anchor_in_root_view) {
1693 Send(new ViewHostMsg_MoveValidationMessage(routing_id(),
1694 anchor_in_root_view));
1697 void RenderViewImpl::setStatusText(const WebString& text) {
1700 void RenderViewImpl::UpdateTargetURL(const GURL& url,
1701 const GURL& fallback_url) {
1702 GURL latest_url = url.is_empty() ? fallback_url : url;
1703 if (latest_url == target_url_)
1704 return;
1706 // Tell the browser to display a destination link.
1707 if (target_url_status_ == TARGET_INFLIGHT ||
1708 target_url_status_ == TARGET_PENDING) {
1709 // If we have a request in-flight, save the URL to be sent when we
1710 // receive an ACK to the in-flight request. We can happily overwrite
1711 // any existing pending sends.
1712 pending_target_url_ = latest_url;
1713 target_url_status_ = TARGET_PENDING;
1714 } else {
1715 // URLs larger than |MaxURLChars()| cannot be sent through IPC -
1716 // see |ParamTraits<GURL>|.
1717 if (latest_url.possibly_invalid_spec().size() > GetMaxURLChars())
1718 latest_url = GURL();
1719 Send(new ViewHostMsg_UpdateTargetURL(routing_id_, page_id_, latest_url));
1720 target_url_ = latest_url;
1721 target_url_status_ = TARGET_INFLIGHT;
1725 gfx::RectF RenderViewImpl::ClientRectToPhysicalWindowRect(
1726 const gfx::RectF& rect) const {
1727 gfx::RectF window_rect = rect;
1728 window_rect.Scale(device_scale_factor_ * webview()->pageScaleFactor());
1729 return window_rect;
1732 void RenderViewImpl::StartNavStateSyncTimerIfNecessary() {
1733 // No need to update state if no page has committed yet.
1734 if (page_id_ == -1)
1735 return;
1737 int delay;
1738 if (send_content_state_immediately_)
1739 delay = 0;
1740 else if (is_hidden())
1741 delay = kDelaySecondsForContentStateSyncHidden;
1742 else
1743 delay = kDelaySecondsForContentStateSync;
1745 if (nav_state_sync_timer_.IsRunning()) {
1746 // The timer is already running. If the delay of the timer maches the amount
1747 // we want to delay by, then return. Otherwise stop the timer so that it
1748 // gets started with the right delay.
1749 if (nav_state_sync_timer_.GetCurrentDelay().InSeconds() == delay)
1750 return;
1751 nav_state_sync_timer_.Stop();
1754 nav_state_sync_timer_.Start(FROM_HERE, TimeDelta::FromSeconds(delay), this,
1755 &RenderViewImpl::SyncNavigationState);
1758 void RenderViewImpl::setMouseOverURL(const WebURL& url) {
1759 mouse_over_url_ = GURL(url);
1760 UpdateTargetURL(mouse_over_url_, focus_url_);
1763 void RenderViewImpl::setKeyboardFocusURL(const WebURL& url) {
1764 focus_url_ = GURL(url);
1765 UpdateTargetURL(focus_url_, mouse_over_url_);
1768 void RenderViewImpl::startDragging(WebLocalFrame* frame,
1769 const WebDragData& data,
1770 WebDragOperationsMask mask,
1771 const WebImage& image,
1772 const WebPoint& webImageOffset) {
1773 DropData drop_data(DropDataBuilder::Build(data));
1774 drop_data.referrer_policy = frame->document().referrerPolicy();
1775 gfx::Vector2d imageOffset(webImageOffset.x, webImageOffset.y);
1776 Send(new DragHostMsg_StartDragging(routing_id_,
1777 drop_data,
1778 mask,
1779 image.getSkBitmap(),
1780 imageOffset,
1781 possible_drag_event_info_));
1784 bool RenderViewImpl::acceptsLoadDrops() {
1785 return renderer_preferences_.can_accept_load_drops;
1788 void RenderViewImpl::focusNext() {
1789 Send(new ViewHostMsg_TakeFocus(routing_id_, false));
1792 void RenderViewImpl::focusPrevious() {
1793 Send(new ViewHostMsg_TakeFocus(routing_id_, true));
1796 void RenderViewImpl::focusedNodeChanged(const WebNode& node) {
1797 has_scrolled_focused_editable_node_into_rect_ = false;
1799 Send(new ViewHostMsg_FocusedNodeChanged(routing_id_, IsEditableNode(node)));
1801 FOR_EACH_OBSERVER(RenderViewObserver, observers_, FocusedNodeChanged(node));
1804 void RenderViewImpl::numberOfWheelEventHandlersChanged(unsigned num_handlers) {
1805 Send(new ViewHostMsg_DidChangeNumWheelEvents(routing_id_, num_handlers));
1808 void RenderViewImpl::didUpdateLayout() {
1809 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidUpdateLayout());
1811 // We don't always want to set up a timer, only if we've been put in that
1812 // mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
1813 // message.
1814 if (!send_preferred_size_changes_ || !webview())
1815 return;
1817 if (check_preferred_size_timer_.IsRunning())
1818 return;
1819 check_preferred_size_timer_.Start(FROM_HERE,
1820 TimeDelta::FromMilliseconds(0), this,
1821 &RenderViewImpl::CheckPreferredSize);
1824 void RenderViewImpl::navigateBackForwardSoon(int offset) {
1825 Send(new ViewHostMsg_GoToEntryAtOffset(routing_id_, offset));
1828 int RenderViewImpl::historyBackListCount() {
1829 return history_list_offset_ < 0 ? 0 : history_list_offset_;
1832 int RenderViewImpl::historyForwardListCount() {
1833 return history_list_length_ - historyBackListCount() - 1;
1836 void RenderViewImpl::postAccessibilityEvent(
1837 const WebAXObject& obj, blink::WebAXEvent event) {
1838 if (renderer_accessibility_) {
1839 renderer_accessibility_->HandleWebAccessibilityEvent(obj, event);
1843 void RenderViewImpl::didUpdateInspectorSetting(const WebString& key,
1844 const WebString& value) {
1845 Send(new ViewHostMsg_UpdateInspectorSetting(routing_id_,
1846 key.utf8(),
1847 value.utf8()));
1850 // blink::WebWidgetClient ----------------------------------------------------
1852 void RenderViewImpl::didFocus() {
1853 // TODO(jcivelli): when https://bugs.webkit.org/show_bug.cgi?id=33389 is fixed
1854 // we won't have to test for user gesture anymore and we can
1855 // move that code back to render_widget.cc
1856 if (WebUserGestureIndicator::isProcessingUserGesture() &&
1857 !RenderThreadImpl::current()->layout_test_mode()) {
1858 Send(new ViewHostMsg_Focus(routing_id_));
1862 void RenderViewImpl::didBlur() {
1863 // TODO(jcivelli): see TODO above in didFocus().
1864 if (WebUserGestureIndicator::isProcessingUserGesture() &&
1865 !RenderThreadImpl::current()->layout_test_mode()) {
1866 Send(new ViewHostMsg_Blur(routing_id_));
1870 // We are supposed to get a single call to Show for a newly created RenderView
1871 // that was created via RenderViewImpl::CreateWebView. So, we wait until this
1872 // point to dispatch the ShowView message.
1874 // This method provides us with the information about how to display the newly
1875 // created RenderView (i.e., as a blocked popup or as a new tab).
1877 void RenderViewImpl::show(WebNavigationPolicy policy) {
1878 if (did_show_) {
1879 // When supports_multiple_windows is disabled, popups are reusing
1880 // the same view. In some scenarios, this makes WebKit to call show() twice.
1881 if (webkit_preferences_.supports_multiple_windows)
1882 NOTREACHED() << "received extraneous Show call";
1883 return;
1885 did_show_ = true;
1887 DCHECK(opener_id_ != MSG_ROUTING_NONE);
1889 // Force new windows to a popup if they were not opened with a user gesture.
1890 if (!opened_by_user_gesture_) {
1891 // We exempt background tabs for compat with older versions of Chrome.
1892 // TODO(darin): This seems bogus. These should have a user gesture, so
1893 // we probably don't need this check.
1894 if (policy != blink::WebNavigationPolicyNewBackgroundTab)
1895 policy = blink::WebNavigationPolicyNewPopup;
1898 // NOTE: initial_pos_ may still have its default values at this point, but
1899 // that's okay. It'll be ignored if disposition is not NEW_POPUP, or the
1900 // browser process will impose a default position otherwise.
1901 Send(new ViewHostMsg_ShowView(opener_id_, routing_id_,
1902 NavigationPolicyToDisposition(policy), initial_pos_,
1903 opened_by_user_gesture_));
1904 SetPendingWindowRect(initial_pos_);
1907 void RenderViewImpl::runModal() {
1908 DCHECK(did_show_) << "should already have shown the view";
1910 // Don't allow further dialogs if we are waiting to swap out, since the
1911 // PageGroupLoadDeferrer in our stack prevents it.
1912 if (suppress_dialogs_until_swap_out_)
1913 return;
1915 // We must keep WebKit's shared timer running in this case in order to allow
1916 // showModalDialog to function properly.
1918 // TODO(darin): WebKit should really be smarter about suppressing events and
1919 // timers so that we do not need to manage the shared timer in such a heavy
1920 // handed manner.
1922 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
1923 RenderThreadImpl::current()->DoNotSuspendWebKitSharedTimer();
1925 SendAndRunNestedMessageLoop(new ViewHostMsg_RunModal(
1926 routing_id_, opener_id_));
1929 bool RenderViewImpl::enterFullScreen() {
1930 Send(new ViewHostMsg_ToggleFullscreen(routing_id_, true));
1931 return true;
1934 void RenderViewImpl::exitFullScreen() {
1935 Send(new ViewHostMsg_ToggleFullscreen(routing_id_, false));
1938 bool RenderViewImpl::requestPointerLock() {
1939 return mouse_lock_dispatcher_->LockMouse(webwidget_mouse_lock_target_.get());
1942 void RenderViewImpl::requestPointerUnlock() {
1943 mouse_lock_dispatcher_->UnlockMouse(webwidget_mouse_lock_target_.get());
1946 bool RenderViewImpl::isPointerLocked() {
1947 return mouse_lock_dispatcher_->IsMouseLockedTo(
1948 webwidget_mouse_lock_target_.get());
1951 void RenderViewImpl::didActivateCompositor() {
1952 #if !defined(OS_MACOSX) // many events are unhandled - http://crbug.com/138003
1953 RenderThreadImpl* render_thread = RenderThreadImpl::current();
1954 // render_thread may be NULL in tests.
1955 InputHandlerManager* input_handler_manager =
1956 render_thread ? render_thread->input_handler_manager() : NULL;
1957 if (input_handler_manager) {
1958 input_handler_manager->AddInputHandler(
1959 routing_id_,
1960 compositor_->GetInputHandler(),
1961 AsWeakPtr());
1963 #endif
1965 RenderWidget::didActivateCompositor();
1968 void RenderViewImpl::didHandleGestureEvent(
1969 const WebGestureEvent& event,
1970 bool event_cancelled) {
1971 RenderWidget::didHandleGestureEvent(event, event_cancelled);
1973 if (event.type != blink::WebGestureEvent::GestureTap)
1974 return;
1976 blink::WebTextInputType text_input_type =
1977 GetWebView()->textInputInfo().type;
1979 Send(new ViewHostMsg_FocusedNodeTouched(
1980 routing_id(), text_input_type != blink::WebTextInputTypeNone));
1983 void RenderViewImpl::initializeLayerTreeView() {
1984 RenderWidget::initializeLayerTreeView();
1985 RenderWidgetCompositor* rwc = compositor();
1986 if (!rwc || !webview() || !webview()->devToolsAgent())
1987 return;
1988 webview()->devToolsAgent()->setLayerTreeId(rwc->GetLayerTreeId());
1991 // blink::WebFrameClient -----------------------------------------------------
1993 void RenderViewImpl::Repaint(const gfx::Size& size) {
1994 OnRepaint(size);
1997 void RenderViewImpl::SetEditCommandForNextKeyEvent(const std::string& name,
1998 const std::string& value) {
1999 EditCommands edit_commands;
2000 edit_commands.push_back(EditCommand(name, value));
2001 OnSetEditCommandsForNextKeyEvent(edit_commands);
2004 void RenderViewImpl::ClearEditCommands() {
2005 edit_commands_.clear();
2008 SSLStatus RenderViewImpl::GetSSLStatusOfFrame(blink::WebFrame* frame) const {
2009 std::string security_info;
2010 if (frame && frame->dataSource())
2011 security_info = frame->dataSource()->response().securityInfo();
2013 SSLStatus ssl_status;
2014 DeserializeSecurityInfo(security_info,
2015 &ssl_status.cert_id,
2016 &ssl_status.cert_status,
2017 &ssl_status.security_bits,
2018 &ssl_status.connection_status,
2019 &ssl_status.signed_certificate_timestamp_ids);
2020 return ssl_status;
2023 const std::string& RenderViewImpl::GetAcceptLanguages() const {
2024 return renderer_preferences_.accept_languages;
2027 void RenderViewImpl::didCreateDataSource(WebLocalFrame* frame,
2028 WebDataSource* ds) {
2029 bool content_initiated = !pending_navigation_params_.get();
2031 // Make sure any previous redirect URLs end up in our new data source.
2032 if (pending_navigation_params_.get()) {
2033 for (std::vector<GURL>::const_iterator i =
2034 pending_navigation_params_->redirects.begin();
2035 i != pending_navigation_params_->redirects.end(); ++i) {
2036 ds->appendRedirect(*i);
2040 DocumentState* document_state = DocumentState::FromDataSource(ds);
2041 if (!document_state) {
2042 document_state = new DocumentState;
2043 ds->setExtraData(document_state);
2044 if (!content_initiated)
2045 PopulateDocumentStateFromPending(document_state);
2048 // Carry over the user agent override flag, if it exists.
2049 if (content_initiated && webview() && webview()->mainFrame() &&
2050 webview()->mainFrame()->dataSource()) {
2051 DocumentState* old_document_state =
2052 DocumentState::FromDataSource(webview()->mainFrame()->dataSource());
2053 if (old_document_state) {
2054 InternalDocumentStateData* internal_data =
2055 InternalDocumentStateData::FromDocumentState(document_state);
2056 InternalDocumentStateData* old_internal_data =
2057 InternalDocumentStateData::FromDocumentState(old_document_state);
2058 internal_data->set_is_overriding_user_agent(
2059 old_internal_data->is_overriding_user_agent());
2063 // The rest of RenderView assumes that a WebDataSource will always have a
2064 // non-null NavigationState.
2065 if (content_initiated) {
2066 document_state->set_navigation_state(
2067 NavigationState::CreateContentInitiated());
2068 } else {
2069 document_state->set_navigation_state(CreateNavigationStateFromPending());
2070 pending_navigation_params_.reset();
2073 // DocumentState::referred_by_prefetcher_ is true if we are
2074 // navigating from a page that used prefetching using a link on that
2075 // page. We are early enough in the request process here that we
2076 // can still see the DocumentState of the previous page and set
2077 // this value appropriately.
2078 // TODO(gavinp): catch the important case of navigation in a new
2079 // renderer process.
2080 if (webview()) {
2081 if (WebFrame* old_frame = webview()->mainFrame()) {
2082 const WebURLRequest& original_request = ds->originalRequest();
2083 const GURL referrer(
2084 original_request.httpHeaderField(WebString::fromUTF8("Referer")));
2085 if (!referrer.is_empty() &&
2086 DocumentState::FromDataSource(
2087 old_frame->dataSource())->was_prefetcher()) {
2088 for (; old_frame; old_frame = old_frame->traverseNext(false)) {
2089 WebDataSource* old_frame_ds = old_frame->dataSource();
2090 if (old_frame_ds && referrer == GURL(old_frame_ds->request().url())) {
2091 document_state->set_was_referred_by_prefetcher(true);
2092 break;
2099 if (content_initiated) {
2100 const WebURLRequest& request = ds->request();
2101 switch (request.cachePolicy()) {
2102 case WebURLRequest::UseProtocolCachePolicy: // normal load.
2103 document_state->set_load_type(DocumentState::LINK_LOAD_NORMAL);
2104 break;
2105 case WebURLRequest::ReloadIgnoringCacheData: // reload.
2106 document_state->set_load_type(DocumentState::LINK_LOAD_RELOAD);
2107 break;
2108 case WebURLRequest::ReturnCacheDataElseLoad: // allow stale data.
2109 document_state->set_load_type(
2110 DocumentState::LINK_LOAD_CACHE_STALE_OK);
2111 break;
2112 case WebURLRequest::ReturnCacheDataDontLoad: // Don't re-post.
2113 document_state->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY);
2114 break;
2118 FOR_EACH_OBSERVER(
2119 RenderViewObserver, observers_, DidCreateDataSource(frame, ds));
2122 void RenderViewImpl::PopulateDocumentStateFromPending(
2123 DocumentState* document_state) {
2124 const FrameMsg_Navigate_Params& params = *pending_navigation_params_.get();
2125 document_state->set_request_time(params.request_time);
2127 InternalDocumentStateData* internal_data =
2128 InternalDocumentStateData::FromDocumentState(document_state);
2130 if (!params.url.SchemeIs(kJavaScriptScheme) &&
2131 params.navigation_type == FrameMsg_Navigate_Type::RESTORE) {
2132 // We're doing a load of a page that was restored from the last session. By
2133 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
2134 // can result in stale data for pages that are set to expire. We explicitly
2135 // override that by setting the policy here so that as necessary we load
2136 // from the network.
2138 // TODO(davidben): Remove this in favor of passing a cache policy to the
2139 // loadHistoryItem call in OnNavigate. That requires not overloading
2140 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
2141 // policy based on load type, etc".
2142 internal_data->set_cache_policy_override(
2143 WebURLRequest::UseProtocolCachePolicy);
2146 if (IsReload(params))
2147 document_state->set_load_type(DocumentState::RELOAD);
2148 else if (params.page_state.IsValid())
2149 document_state->set_load_type(DocumentState::HISTORY_LOAD);
2150 else
2151 document_state->set_load_type(DocumentState::NORMAL_LOAD);
2153 internal_data->set_is_overriding_user_agent(params.is_overriding_user_agent);
2154 internal_data->set_must_reset_scroll_and_scale_state(
2155 params.navigation_type ==
2156 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
2157 document_state->set_can_load_local_resources(params.can_load_local_resources);
2160 NavigationState* RenderViewImpl::CreateNavigationStateFromPending() {
2161 const FrameMsg_Navigate_Params& params = *pending_navigation_params_.get();
2162 NavigationState* navigation_state = NULL;
2164 // A navigation resulting from loading a javascript URL should not be treated
2165 // as a browser initiated event. Instead, we want it to look as if the page
2166 // initiated any load resulting from JS execution.
2167 if (!params.url.SchemeIs(kJavaScriptScheme)) {
2168 navigation_state = NavigationState::CreateBrowserInitiated(
2169 params.page_id,
2170 params.pending_history_list_offset,
2171 params.should_clear_history_list,
2172 params.transition);
2173 navigation_state->set_should_replace_current_entry(
2174 params.should_replace_current_entry);
2175 navigation_state->set_transferred_request_child_id(
2176 params.transferred_request_child_id);
2177 navigation_state->set_transferred_request_request_id(
2178 params.transferred_request_request_id);
2179 navigation_state->set_allow_download(params.allow_download);
2180 navigation_state->set_extra_headers(params.extra_headers);
2181 } else {
2182 navigation_state = NavigationState::CreateContentInitiated();
2184 return navigation_state;
2187 void RenderViewImpl::ProcessViewLayoutFlags(const CommandLine& command_line) {
2188 bool enable_viewport =
2189 command_line.HasSwitch(switches::kEnableViewport) ||
2190 command_line.HasSwitch(switches::kEnableViewportMeta);
2192 // If viewport tag is enabled, then the WebKit side will take care
2193 // of setting the fixed layout size and page scale limits.
2194 if (enable_viewport)
2195 return;
2197 // When navigating to a new page, reset the page scale factor to be 1.0.
2198 webview()->setInitialPageScaleOverride(1.f);
2200 float maxPageScaleFactor =
2201 command_line.HasSwitch(switches::kEnablePinch) ? 4.f : 1.f ;
2202 webview()->setPageScaleFactorLimits(1, maxPageScaleFactor);
2205 void RenderViewImpl::FrameDidCommitProvisionalLoad(WebLocalFrame* frame,
2206 bool is_new_navigation) {
2207 FOR_EACH_OBSERVER(RenderViewObserver, observers_,
2208 DidCommitProvisionalLoad(frame, is_new_navigation));
2210 // TODO(nasko): Transition this code to RenderFrameImpl, since g_view_map is
2211 // not accessible from there.
2212 if (!frame->parent()) { // Only for top frames.
2213 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
2214 if (render_thread_impl) { // Can be NULL in tests.
2215 render_thread_impl->histogram_customizer()->
2216 RenderViewNavigatedToHost(GURL(GetLoadingUrl(frame)).host(),
2217 g_view_map.Get().size());
2222 void RenderViewImpl::didClearWindowObject(WebLocalFrame* frame, int world_id) {
2223 FOR_EACH_OBSERVER(RenderViewObserver, observers_,
2224 DidClearWindowObject(frame, world_id));
2226 // Only install controllers into the main world.
2227 if (world_id)
2228 return;
2230 if (enabled_bindings_& BINDINGS_POLICY_WEB_UI)
2231 WebUIExtension::Install(frame);
2233 if (enabled_bindings_ & BINDINGS_POLICY_STATS_COLLECTION)
2234 StatsCollectionController::Install(frame);
2236 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
2238 if (command_line.HasSwitch(switches::kEnableSkiaBenchmarking))
2239 SkiaBenchmarking::Install(frame);
2241 if (command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
2242 MemoryBenchmarkingExtension::Install(frame);
2245 void RenderViewImpl::didReceiveTitle(WebLocalFrame* frame,
2246 const WebString& title,
2247 WebTextDirection direction) {
2248 UpdateTitle(frame, title, direction);
2250 // Also check whether we have new encoding name.
2251 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2254 void RenderViewImpl::didChangeIcon(WebLocalFrame* frame,
2255 WebIconURL::Type icon_type) {
2256 if (frame->parent())
2257 return;
2259 if (!TouchEnabled() && icon_type != WebIconURL::TypeFavicon)
2260 return;
2262 WebVector<WebIconURL> icon_urls = frame->iconURLs(icon_type);
2263 std::vector<FaviconURL> urls;
2264 for (size_t i = 0; i < icon_urls.size(); i++) {
2265 std::vector<gfx::Size> sizes;
2266 ConvertToFaviconSizes(icon_urls[i].sizes(), &sizes);
2267 urls.push_back(FaviconURL(
2268 icon_urls[i].iconURL(), ToFaviconType(icon_urls[i].iconType()), sizes));
2270 SendUpdateFaviconURL(urls);
2273 void RenderViewImpl::didUpdateCurrentHistoryItem(WebLocalFrame* frame) {
2274 StartNavStateSyncTimerIfNecessary();
2277 void RenderViewImpl::CheckPreferredSize() {
2278 // We don't always want to send the change messages over IPC, only if we've
2279 // been put in that mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
2280 // message.
2281 if (!send_preferred_size_changes_ || !webview())
2282 return;
2284 gfx::Size size = webview()->contentsPreferredMinimumSize();
2286 // In the presence of zoom, these sizes are still reported as if unzoomed,
2287 // so we need to adjust.
2288 double zoom_factor = ZoomLevelToZoomFactor(webview()->zoomLevel());
2289 size.set_width(static_cast<int>(size.width() * zoom_factor));
2290 size.set_height(static_cast<int>(size.height() * zoom_factor));
2292 if (size == preferred_size_)
2293 return;
2295 preferred_size_ = size;
2296 Send(new ViewHostMsg_DidContentsPreferredSizeChange(routing_id_,
2297 preferred_size_));
2300 BrowserPluginManager* RenderViewImpl::GetBrowserPluginManager() {
2301 if (!browser_plugin_manager_.get())
2302 browser_plugin_manager_ = BrowserPluginManager::Create(this);
2303 return browser_plugin_manager_.get();
2306 void RenderViewImpl::UpdateScrollState(WebFrame* frame) {
2307 WebSize offset = frame->scrollOffset();
2308 WebSize minimum_offset = frame->minimumScrollOffset();
2309 WebSize maximum_offset = frame->maximumScrollOffset();
2311 bool is_pinned_to_left = offset.width <= minimum_offset.width;
2312 bool is_pinned_to_right = offset.width >= maximum_offset.width;
2314 if (is_pinned_to_left != cached_is_main_frame_pinned_to_left_ ||
2315 is_pinned_to_right != cached_is_main_frame_pinned_to_right_) {
2316 Send(new ViewHostMsg_DidChangeScrollOffsetPinningForMainFrame(
2317 routing_id_, is_pinned_to_left, is_pinned_to_right));
2319 cached_is_main_frame_pinned_to_left_ = is_pinned_to_left;
2320 cached_is_main_frame_pinned_to_right_ = is_pinned_to_right;
2323 Send(new ViewHostMsg_DidChangeScrollOffset(routing_id_));
2326 void RenderViewImpl::didChangeScrollOffset(WebLocalFrame* frame) {
2327 StartNavStateSyncTimerIfNecessary();
2329 if (webview()->mainFrame() == frame)
2330 UpdateScrollState(frame);
2332 FOR_EACH_OBSERVER(
2333 RenderViewObserver, observers_, DidChangeScrollOffset(frame));
2336 void RenderViewImpl::SendFindReply(int request_id,
2337 int match_count,
2338 int ordinal,
2339 const WebRect& selection_rect,
2340 bool final_status_update) {
2341 Send(new ViewHostMsg_Find_Reply(routing_id_,
2342 request_id,
2343 match_count,
2344 selection_rect,
2345 ordinal,
2346 final_status_update));
2349 bool RenderViewImpl::willCheckAndDispatchMessageEvent(
2350 blink::WebLocalFrame* sourceFrame,
2351 blink::WebFrame* targetFrame,
2352 blink::WebSecurityOrigin target_origin,
2353 blink::WebDOMMessageEvent event) {
2354 if (!is_swapped_out_)
2355 return false;
2357 ViewMsg_PostMessage_Params params;
2358 params.data = event.data().toString();
2359 params.source_origin = event.origin();
2360 if (!target_origin.isNull())
2361 params.target_origin = target_origin.toString();
2363 blink::WebMessagePortChannelArray channels = event.releaseChannels();
2364 if (!channels.isEmpty()) {
2365 std::vector<int> message_port_ids(channels.size());
2366 // Extract the port IDs from the channel array.
2367 for (size_t i = 0; i < channels.size(); ++i) {
2368 WebMessagePortChannelImpl* webchannel =
2369 static_cast<WebMessagePortChannelImpl*>(channels[i]);
2370 message_port_ids[i] = webchannel->message_port_id();
2371 webchannel->QueueMessages();
2372 DCHECK_NE(message_port_ids[i], MSG_ROUTING_NONE);
2374 params.message_port_ids = message_port_ids;
2377 // Include the routing ID for the source frame (if one exists), which the
2378 // browser process will translate into the routing ID for the equivalent
2379 // frame in the target process.
2380 params.source_routing_id = MSG_ROUTING_NONE;
2381 if (sourceFrame) {
2382 RenderViewImpl* source_view = FromWebView(sourceFrame->view());
2383 if (source_view)
2384 params.source_routing_id = source_view->routing_id();
2387 Send(new ViewHostMsg_RouteMessageEvent(routing_id_, params));
2388 return true;
2391 blink::WebString RenderViewImpl::acceptLanguages() {
2392 return WebString::fromUTF8(renderer_preferences_.accept_languages);
2395 // blink::WebPageSerializerClient implementation ------------------------------
2397 void RenderViewImpl::didSerializeDataForFrame(
2398 const WebURL& frame_url,
2399 const WebCString& data,
2400 WebPageSerializerClient::PageSerializationStatus status) {
2401 Send(new ViewHostMsg_SendSerializedHtmlData(
2402 routing_id(),
2403 frame_url,
2404 data.data(),
2405 static_cast<int32>(status)));
2408 // RenderView implementation ---------------------------------------------------
2410 bool RenderViewImpl::Send(IPC::Message* message) {
2411 return RenderWidget::Send(message);
2414 RenderFrame* RenderViewImpl::GetMainRenderFrame() {
2415 return main_render_frame_.get();
2418 int RenderViewImpl::GetRoutingID() const {
2419 return routing_id_;
2422 int RenderViewImpl::GetPageId() const {
2423 return page_id_;
2426 gfx::Size RenderViewImpl::GetSize() const {
2427 return size();
2430 WebPreferences& RenderViewImpl::GetWebkitPreferences() {
2431 return webkit_preferences_;
2434 void RenderViewImpl::SetWebkitPreferences(const WebPreferences& preferences) {
2435 OnUpdateWebPreferences(preferences);
2438 blink::WebView* RenderViewImpl::GetWebView() {
2439 return webview();
2442 blink::WebElement RenderViewImpl::GetFocusedElement() const {
2443 if (!webview())
2444 return WebElement();
2445 WebFrame* focused_frame = webview()->focusedFrame();
2446 if (focused_frame) {
2447 WebDocument doc = focused_frame->document();
2448 if (!doc.isNull())
2449 return doc.focusedElement();
2452 return WebElement();
2455 bool RenderViewImpl::IsEditableNode(const WebNode& node) const {
2456 if (node.isNull())
2457 return false;
2459 if (node.isContentEditable())
2460 return true;
2462 if (node.isElementNode()) {
2463 const WebElement& element = node.toConst<WebElement>();
2464 if (element.isTextFormControlElement())
2465 return true;
2467 // Also return true if it has an ARIA role of 'textbox'.
2468 for (unsigned i = 0; i < element.attributeCount(); ++i) {
2469 if (LowerCaseEqualsASCII(element.attributeLocalName(i), "role")) {
2470 if (LowerCaseEqualsASCII(element.attributeValue(i), "textbox"))
2471 return true;
2472 break;
2477 return false;
2480 bool RenderViewImpl::ShouldDisplayScrollbars(int width, int height) const {
2481 return (!send_preferred_size_changes_ ||
2482 (disable_scrollbars_size_limit_.width() <= width ||
2483 disable_scrollbars_size_limit_.height() <= height));
2486 int RenderViewImpl::GetEnabledBindings() const {
2487 return enabled_bindings_;
2490 bool RenderViewImpl::GetContentStateImmediately() const {
2491 return send_content_state_immediately_;
2494 float RenderViewImpl::GetFilteredTimePerFrame() const {
2495 return 0.0f;
2498 blink::WebPageVisibilityState RenderViewImpl::GetVisibilityState() const {
2499 return visibilityState();
2502 void RenderViewImpl::DidStartLoading() {
2503 main_render_frame_->didStartLoading(true);
2506 void RenderViewImpl::DidStopLoading() {
2507 main_render_frame_->didStopLoading();
2510 void RenderViewImpl::SyncNavigationState() {
2511 if (!webview())
2512 return;
2513 SendUpdateState(history_controller_->GetCurrentEntry());
2516 GURL RenderViewImpl::GetLoadingUrl(blink::WebFrame* frame) const {
2517 WebDataSource* ds = frame->dataSource();
2518 if (ds->hasUnreachableURL())
2519 return ds->unreachableURL();
2521 const WebURLRequest& request = ds->request();
2522 return request.url();
2525 blink::WebPlugin* RenderViewImpl::GetWebPluginForFind() {
2526 if (!webview())
2527 return NULL;
2529 WebFrame* main_frame = webview()->mainFrame();
2530 if (main_frame->document().isPluginDocument())
2531 return webview()->mainFrame()->document().to<WebPluginDocument>().plugin();
2533 #if defined(ENABLE_PLUGINS)
2534 if (plugin_find_handler_)
2535 return plugin_find_handler_->container()->plugin();
2536 #endif
2538 return NULL;
2541 void RenderViewImpl::OnFind(int request_id,
2542 const base::string16& search_text,
2543 const WebFindOptions& options) {
2544 WebFrame* main_frame = webview()->mainFrame();
2545 blink::WebPlugin* plugin = GetWebPluginForFind();
2546 // Check if the plugin still exists in the document.
2547 if (plugin) {
2548 if (options.findNext) {
2549 // Just navigate back/forward.
2550 plugin->selectFindResult(options.forward);
2551 } else {
2552 if (!plugin->startFind(
2553 search_text, options.matchCase, request_id)) {
2554 // Send "no results".
2555 SendFindReply(request_id, 0, 0, gfx::Rect(), true);
2558 return;
2561 WebFrame* frame_after_main = main_frame->traverseNext(true);
2562 WebFrame* focused_frame = webview()->focusedFrame();
2563 WebFrame* search_frame = focused_frame; // start searching focused frame.
2565 bool multi_frame = (frame_after_main != main_frame);
2567 // If we have multiple frames, we don't want to wrap the search within the
2568 // frame, so we check here if we only have main_frame in the chain.
2569 bool wrap_within_frame = !multi_frame;
2571 WebRect selection_rect;
2572 bool result = false;
2574 // If something is selected when we start searching it means we cannot just
2575 // increment the current match ordinal; we need to re-generate it.
2576 WebRange current_selection = focused_frame->selectionRange();
2578 do {
2579 result = search_frame->find(
2580 request_id, search_text, options, wrap_within_frame, &selection_rect);
2582 if (!result) {
2583 // don't leave text selected as you move to the next frame.
2584 search_frame->executeCommand(WebString::fromUTF8("Unselect"),
2585 GetFocusedElement());
2587 // Find the next frame, but skip the invisible ones.
2588 do {
2589 // What is the next frame to search? (we might be going backwards). Note
2590 // that we specify wrap=true so that search_frame never becomes NULL.
2591 search_frame = options.forward ?
2592 search_frame->traverseNext(true) :
2593 search_frame->traversePrevious(true);
2594 } while (!search_frame->hasVisibleContent() &&
2595 search_frame != focused_frame);
2597 // Make sure selection doesn't affect the search operation in new frame.
2598 search_frame->executeCommand(WebString::fromUTF8("Unselect"),
2599 GetFocusedElement());
2601 // If we have multiple frames and we have wrapped back around to the
2602 // focused frame, we need to search it once more allowing wrap within
2603 // the frame, otherwise it will report 'no match' if the focused frame has
2604 // reported matches, but no frames after the focused_frame contain a
2605 // match for the search word(s).
2606 if (multi_frame && search_frame == focused_frame) {
2607 result = search_frame->find(
2608 request_id, search_text, options, true, // Force wrapping.
2609 &selection_rect);
2613 webview()->setFocusedFrame(search_frame);
2614 } while (!result && search_frame != focused_frame);
2616 if (options.findNext && current_selection.isNull()) {
2617 // Force the main_frame to report the actual count.
2618 main_frame->increaseMatchCount(0, request_id);
2619 } else {
2620 // If nothing is found, set result to "0 of 0", otherwise, set it to
2621 // "-1 of 1" to indicate that we found at least one item, but we don't know
2622 // yet what is active.
2623 int ordinal = result ? -1 : 0; // -1 here means, we might know more later.
2624 int match_count = result ? 1 : 0; // 1 here means possibly more coming.
2626 // If we find no matches then this will be our last status update.
2627 // Otherwise the scoping effort will send more results.
2628 bool final_status_update = !result;
2630 SendFindReply(request_id, match_count, ordinal, selection_rect,
2631 final_status_update);
2633 // Scoping effort begins, starting with the mainframe.
2634 search_frame = main_frame;
2636 main_frame->resetMatchCount();
2638 do {
2639 // Cancel all old scoping requests before starting a new one.
2640 search_frame->cancelPendingScopingEffort();
2642 // We don't start another scoping effort unless at least one match has
2643 // been found.
2644 if (result) {
2645 // Start new scoping request. If the scoping function determines that it
2646 // needs to scope, it will defer until later.
2647 search_frame->scopeStringMatches(request_id,
2648 search_text,
2649 options,
2650 true); // reset the tickmarks
2653 // Iterate to the next frame. The frame will not necessarily scope, for
2654 // example if it is not visible.
2655 search_frame = search_frame->traverseNext(true);
2656 } while (search_frame != main_frame);
2660 void RenderViewImpl::OnStopFinding(StopFindAction action) {
2661 WebView* view = webview();
2662 if (!view)
2663 return;
2665 blink::WebPlugin* plugin = GetWebPluginForFind();
2666 if (plugin) {
2667 plugin->stopFind();
2668 return;
2671 bool clear_selection = action == STOP_FIND_ACTION_CLEAR_SELECTION;
2672 if (clear_selection) {
2673 view->focusedFrame()->executeCommand(WebString::fromUTF8("Unselect"),
2674 GetFocusedElement());
2677 WebFrame* frame = view->mainFrame();
2678 while (frame) {
2679 frame->stopFinding(clear_selection);
2680 frame = frame->traverseNext(false);
2683 if (action == STOP_FIND_ACTION_ACTIVATE_SELECTION) {
2684 WebFrame* focused_frame = view->focusedFrame();
2685 if (focused_frame) {
2686 WebDocument doc = focused_frame->document();
2687 if (!doc.isNull()) {
2688 WebElement element = doc.focusedElement();
2689 if (!element.isNull())
2690 element.simulateClick();
2696 #if defined(OS_ANDROID)
2697 void RenderViewImpl::OnActivateNearestFindResult(int request_id,
2698 float x, float y) {
2699 if (!webview())
2700 return;
2702 WebFrame* main_frame = webview()->mainFrame();
2703 WebRect selection_rect;
2704 int ordinal = main_frame->selectNearestFindMatch(WebFloatPoint(x, y),
2705 &selection_rect);
2706 if (ordinal == -1) {
2707 // Something went wrong, so send a no-op reply (force the main_frame to
2708 // report the current match count) in case the host is waiting for a
2709 // response due to rate-limiting).
2710 main_frame->increaseMatchCount(0, request_id);
2711 return;
2714 SendFindReply(request_id,
2715 -1 /* number_of_matches */,
2716 ordinal,
2717 selection_rect,
2718 true /* final_update */);
2721 void RenderViewImpl::OnFindMatchRects(int current_version) {
2722 if (!webview())
2723 return;
2725 WebFrame* main_frame = webview()->mainFrame();
2726 std::vector<gfx::RectF> match_rects;
2728 int rects_version = main_frame->findMatchMarkersVersion();
2729 if (current_version != rects_version) {
2730 WebVector<WebFloatRect> web_match_rects;
2731 main_frame->findMatchRects(web_match_rects);
2732 match_rects.reserve(web_match_rects.size());
2733 for (size_t i = 0; i < web_match_rects.size(); ++i)
2734 match_rects.push_back(gfx::RectF(web_match_rects[i]));
2737 gfx::RectF active_rect = main_frame->activeFindMatchRect();
2738 Send(new ViewHostMsg_FindMatchRects_Reply(routing_id_,
2739 rects_version,
2740 match_rects,
2741 active_rect));
2743 #endif
2745 void RenderViewImpl::OnZoom(PageZoom zoom) {
2746 if (!webview()) // Not sure if this can happen, but no harm in being safe.
2747 return;
2749 webview()->hidePopups();
2751 double old_zoom_level = webview()->zoomLevel();
2752 double zoom_level;
2753 if (zoom == PAGE_ZOOM_RESET) {
2754 zoom_level = 0;
2755 } else if (static_cast<int>(old_zoom_level) == old_zoom_level) {
2756 // Previous zoom level is a whole number, so just increment/decrement.
2757 zoom_level = old_zoom_level + zoom;
2758 } else {
2759 // Either the user hit the zoom factor limit and thus the zoom level is now
2760 // not a whole number, or a plugin changed it to a custom value. We want
2761 // to go to the next whole number so that the user can always get back to
2762 // 100% with the keyboard/menu.
2763 if ((old_zoom_level > 1 && zoom > 0) ||
2764 (old_zoom_level < 1 && zoom < 0)) {
2765 zoom_level = static_cast<int>(old_zoom_level + zoom);
2766 } else {
2767 // We're going towards 100%, so first go to the next whole number.
2768 zoom_level = static_cast<int>(old_zoom_level);
2771 webview()->setZoomLevel(zoom_level);
2772 zoomLevelChanged();
2775 void RenderViewImpl::OnSetZoomLevel(double zoom_level) {
2776 webview()->hidePopups();
2777 webview()->setZoomLevel(zoom_level);
2778 zoomLevelChanged();
2781 void RenderViewImpl::OnSetZoomLevelForLoadingURL(const GURL& url,
2782 double zoom_level) {
2783 #if !defined(OS_ANDROID)
2784 // On Android, page zoom isn't used, and in case of WebView, text zoom is used
2785 // for legacy WebView text scaling emulation. Thus, the code that resets
2786 // the zoom level from this map will be effectively resetting text zoom level.
2787 host_zoom_levels_[url] = zoom_level;
2788 #endif
2791 void RenderViewImpl::OnSetPageEncoding(const std::string& encoding_name) {
2792 webview()->setPageEncoding(WebString::fromUTF8(encoding_name));
2795 void RenderViewImpl::OnResetPageEncodingToDefault() {
2796 WebString no_encoding;
2797 webview()->setPageEncoding(no_encoding);
2800 void RenderViewImpl::OnPostMessageEvent(
2801 const ViewMsg_PostMessage_Params& params) {
2802 // TODO(nasko): Support sending to subframes.
2803 WebFrame* frame = webview()->mainFrame();
2805 // Find the source frame if it exists.
2806 WebFrame* source_frame = NULL;
2807 if (params.source_routing_id != MSG_ROUTING_NONE) {
2808 RenderViewImpl* source_view = FromRoutingID(params.source_routing_id);
2809 if (source_view)
2810 source_frame = source_view->webview()->mainFrame();
2813 // If the message contained MessagePorts, create the corresponding endpoints.
2814 DCHECK_EQ(params.message_port_ids.size(), params.new_routing_ids.size());
2815 blink::WebMessagePortChannelArray channels(params.message_port_ids.size());
2816 for (size_t i = 0;
2817 i < params.message_port_ids.size() && i < params.new_routing_ids.size();
2818 ++i) {
2819 channels[i] =
2820 new WebMessagePortChannelImpl(params.new_routing_ids[i],
2821 params.message_port_ids[i],
2822 base::MessageLoopProxy::current().get());
2825 // Create an event with the message. The final parameter to initMessageEvent
2826 // is the last event ID, which is not used with postMessage.
2827 WebDOMEvent event = frame->document().createEvent("MessageEvent");
2828 WebDOMMessageEvent msg_event = event.to<WebDOMMessageEvent>();
2829 msg_event.initMessageEvent("message",
2830 // |canBubble| and |cancellable| are always false
2831 false, false,
2832 WebSerializedScriptValue::fromString(params.data),
2833 params.source_origin, source_frame, "", channels);
2835 // We must pass in the target_origin to do the security check on this side,
2836 // since it may have changed since the original postMessage call was made.
2837 WebSecurityOrigin target_origin;
2838 if (!params.target_origin.empty()) {
2839 target_origin =
2840 WebSecurityOrigin::createFromString(WebString(params.target_origin));
2842 frame->dispatchMessageEventWithOriginCheck(target_origin, msg_event);
2845 void RenderViewImpl::OnAllowBindings(int enabled_bindings_flags) {
2846 if ((enabled_bindings_flags & BINDINGS_POLICY_WEB_UI) &&
2847 !(enabled_bindings_ & BINDINGS_POLICY_WEB_UI)) {
2848 // WebUIExtensionData deletes itself when we're destroyed.
2849 new WebUIExtensionData(this);
2850 // WebUIMojo deletes itself when we're destroyed.
2851 new WebUIMojo(this);
2854 enabled_bindings_ |= enabled_bindings_flags;
2856 // Keep track of the total bindings accumulated in this process.
2857 RenderProcess::current()->AddBindings(enabled_bindings_flags);
2860 void RenderViewImpl::OnDragTargetDragEnter(const DropData& drop_data,
2861 const gfx::Point& client_point,
2862 const gfx::Point& screen_point,
2863 WebDragOperationsMask ops,
2864 int key_modifiers) {
2865 WebDragOperation operation = webview()->dragTargetDragEnter(
2866 DropDataToWebDragData(drop_data),
2867 client_point,
2868 screen_point,
2869 ops,
2870 key_modifiers);
2872 Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
2875 void RenderViewImpl::OnDragTargetDragOver(const gfx::Point& client_point,
2876 const gfx::Point& screen_point,
2877 WebDragOperationsMask ops,
2878 int key_modifiers) {
2879 WebDragOperation operation = webview()->dragTargetDragOver(
2880 client_point,
2881 screen_point,
2882 ops,
2883 key_modifiers);
2885 Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
2888 void RenderViewImpl::OnDragTargetDragLeave() {
2889 webview()->dragTargetDragLeave();
2892 void RenderViewImpl::OnDragTargetDrop(const gfx::Point& client_point,
2893 const gfx::Point& screen_point,
2894 int key_modifiers) {
2895 webview()->dragTargetDrop(client_point, screen_point, key_modifiers);
2897 Send(new DragHostMsg_TargetDrop_ACK(routing_id_));
2900 void RenderViewImpl::OnDragSourceEnded(const gfx::Point& client_point,
2901 const gfx::Point& screen_point,
2902 WebDragOperation op) {
2903 webview()->dragSourceEndedAt(client_point, screen_point, op);
2906 void RenderViewImpl::OnDragSourceSystemDragEnded() {
2907 webview()->dragSourceSystemDragEnded();
2910 void RenderViewImpl::OnUpdateWebPreferences(const WebPreferences& prefs) {
2911 webkit_preferences_ = prefs;
2912 ApplyWebPreferences(webkit_preferences_, webview());
2915 void RenderViewImpl::OnEnumerateDirectoryResponse(
2916 int id,
2917 const std::vector<base::FilePath>& paths) {
2918 if (!enumeration_completions_[id])
2919 return;
2921 WebVector<WebString> ws_file_names(paths.size());
2922 for (size_t i = 0; i < paths.size(); ++i)
2923 ws_file_names[i] = paths[i].AsUTF16Unsafe();
2925 enumeration_completions_[id]->didChooseFile(ws_file_names);
2926 enumeration_completions_.erase(id);
2929 void RenderViewImpl::OnFileChooserResponse(
2930 const std::vector<ui::SelectedFileInfo>& files) {
2931 // This could happen if we navigated to a different page before the user
2932 // closed the chooser.
2933 if (file_chooser_completions_.empty())
2934 return;
2936 // Convert Chrome's SelectedFileInfo list to WebKit's.
2937 WebVector<WebFileChooserCompletion::SelectedFileInfo> selected_files(
2938 files.size());
2939 for (size_t i = 0; i < files.size(); ++i) {
2940 WebFileChooserCompletion::SelectedFileInfo selected_file;
2941 selected_file.path = files[i].local_path.AsUTF16Unsafe();
2942 selected_file.displayName =
2943 base::FilePath(files[i].display_name).AsUTF16Unsafe();
2944 selected_files[i] = selected_file;
2947 if (file_chooser_completions_.front()->completion)
2948 file_chooser_completions_.front()->completion->didChooseFile(
2949 selected_files);
2950 file_chooser_completions_.pop_front();
2952 // If there are more pending file chooser requests, schedule one now.
2953 if (!file_chooser_completions_.empty()) {
2954 Send(new ViewHostMsg_RunFileChooser(routing_id_,
2955 file_chooser_completions_.front()->params));
2959 void RenderViewImpl::OnEnableAutoResize(const gfx::Size& min_size,
2960 const gfx::Size& max_size) {
2961 DCHECK(disable_scrollbars_size_limit_.IsEmpty());
2962 if (!webview())
2963 return;
2964 auto_resize_mode_ = true;
2965 webview()->enableAutoResizeMode(min_size, max_size);
2968 void RenderViewImpl::OnDisableAutoResize(const gfx::Size& new_size) {
2969 DCHECK(disable_scrollbars_size_limit_.IsEmpty());
2970 if (!webview())
2971 return;
2972 auto_resize_mode_ = false;
2973 webview()->disableAutoResizeMode();
2975 if (!new_size.IsEmpty()) {
2976 Resize(new_size,
2977 physical_backing_size_,
2978 overdraw_bottom_height_,
2979 visible_viewport_size_,
2980 resizer_rect_,
2981 is_fullscreen_,
2982 NO_RESIZE_ACK);
2986 void RenderViewImpl::OnEnablePreferredSizeChangedMode() {
2987 if (send_preferred_size_changes_)
2988 return;
2989 send_preferred_size_changes_ = true;
2991 // Start off with an initial preferred size notification (in case
2992 // |didUpdateLayout| was already called).
2993 didUpdateLayout();
2996 void RenderViewImpl::OnDisableScrollbarsForSmallWindows(
2997 const gfx::Size& disable_scrollbar_size_limit) {
2998 disable_scrollbars_size_limit_ = disable_scrollbar_size_limit;
3001 void RenderViewImpl::OnSetRendererPrefs(
3002 const RendererPreferences& renderer_prefs) {
3003 double old_zoom_level = renderer_preferences_.default_zoom_level;
3004 renderer_preferences_ = renderer_prefs;
3005 UpdateFontRenderingFromRendererPrefs();
3007 #if defined(USE_DEFAULT_RENDER_THEME)
3008 if (renderer_prefs.use_custom_colors) {
3009 WebColorName name = blink::WebColorWebkitFocusRingColor;
3010 blink::setNamedColors(&name, &renderer_prefs.focus_ring_color, 1);
3011 blink::setCaretBlinkInterval(renderer_prefs.caret_blink_interval);
3013 if (webview()) {
3014 webview()->setSelectionColors(
3015 renderer_prefs.active_selection_bg_color,
3016 renderer_prefs.active_selection_fg_color,
3017 renderer_prefs.inactive_selection_bg_color,
3018 renderer_prefs.inactive_selection_fg_color);
3019 webview()->themeChanged();
3022 #endif // defined(USE_DEFAULT_RENDER_THEME)
3024 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
3025 RenderThreadImpl::current()->SetFlingCurveParameters(
3026 renderer_prefs.touchpad_fling_profile,
3027 renderer_prefs.touchscreen_fling_profile);
3029 // If the zoom level for this page matches the old zoom default, and this
3030 // is not a plugin, update the zoom level to match the new default.
3031 if (webview() && !webview()->mainFrame()->document().isPluginDocument() &&
3032 !ZoomValuesEqual(old_zoom_level,
3033 renderer_preferences_.default_zoom_level) &&
3034 ZoomValuesEqual(webview()->zoomLevel(), old_zoom_level)) {
3035 webview()->setZoomLevel(renderer_preferences_.default_zoom_level);
3036 zoomLevelChanged();
3040 void RenderViewImpl::OnMediaPlayerActionAt(const gfx::Point& location,
3041 const WebMediaPlayerAction& action) {
3042 if (webview())
3043 webview()->performMediaPlayerAction(action, location);
3046 void RenderViewImpl::OnOrientationChangeEvent(int orientation) {
3047 // Screen has rotated. 0 = default (portrait), 90 = one turn right, and so on.
3048 FOR_EACH_OBSERVER(RenderViewObserver,
3049 observers_,
3050 OrientationChangeEvent(orientation));
3051 webview()->mainFrame()->sendOrientationChangeEvent(orientation);
3054 void RenderViewImpl::OnPluginActionAt(const gfx::Point& location,
3055 const WebPluginAction& action) {
3056 if (webview())
3057 webview()->performPluginAction(action, location);
3060 void RenderViewImpl::OnGetAllSavableResourceLinksForCurrentPage(
3061 const GURL& page_url) {
3062 // Prepare list to storage all savable resource links.
3063 std::vector<GURL> resources_list;
3064 std::vector<GURL> referrer_urls_list;
3065 std::vector<blink::WebReferrerPolicy> referrer_policies_list;
3066 std::vector<GURL> frames_list;
3067 SavableResourcesResult result(&resources_list,
3068 &referrer_urls_list,
3069 &referrer_policies_list,
3070 &frames_list);
3072 // webkit/ doesn't know about Referrer.
3073 if (!GetAllSavableResourceLinksForCurrentPage(
3074 webview(),
3075 page_url,
3076 &result,
3077 const_cast<const char**>(GetSavableSchemes()))) {
3078 // If something is wrong when collecting all savable resource links,
3079 // send empty list to embedder(browser) to tell it failed.
3080 referrer_urls_list.clear();
3081 referrer_policies_list.clear();
3082 resources_list.clear();
3083 frames_list.clear();
3086 std::vector<Referrer> referrers_list;
3087 CHECK_EQ(referrer_urls_list.size(), referrer_policies_list.size());
3088 for (unsigned i = 0; i < referrer_urls_list.size(); ++i) {
3089 referrers_list.push_back(
3090 Referrer(referrer_urls_list[i], referrer_policies_list[i]));
3093 // Send result of all savable resource links to embedder.
3094 Send(new ViewHostMsg_SendCurrentPageAllSavableResourceLinks(routing_id(),
3095 resources_list,
3096 referrers_list,
3097 frames_list));
3100 void RenderViewImpl::OnGetSerializedHtmlDataForCurrentPageWithLocalLinks(
3101 const std::vector<GURL>& links,
3102 const std::vector<base::FilePath>& local_paths,
3103 const base::FilePath& local_directory_name) {
3105 // Convert std::vector of GURLs to WebVector<WebURL>
3106 WebVector<WebURL> weburl_links(links);
3108 // Convert std::vector of base::FilePath to WebVector<WebString>
3109 WebVector<WebString> webstring_paths(local_paths.size());
3110 for (size_t i = 0; i < local_paths.size(); i++)
3111 webstring_paths[i] = local_paths[i].AsUTF16Unsafe();
3113 WebPageSerializer::serialize(webview()->mainFrame()->toWebLocalFrame(),
3114 true,
3115 this,
3116 weburl_links,
3117 webstring_paths,
3118 local_directory_name.AsUTF16Unsafe());
3121 void RenderViewImpl::OnSuppressDialogsUntilSwapOut() {
3122 // Don't show any more dialogs until we finish OnSwapOut.
3123 suppress_dialogs_until_swap_out_ = true;
3126 void RenderViewImpl::NavigateToSwappedOutURL(blink::WebFrame* frame) {
3127 // We use loadRequest instead of loadHTMLString because the former commits
3128 // synchronously. Otherwise a new navigation can interrupt the navigation
3129 // to kSwappedOutURL. If that happens to be to the page we had been
3130 // showing, then WebKit will never send a commit and we'll be left spinning.
3131 // TODO(creis): Until we move this to RenderFrame, we may call this from a
3132 // swapped out RenderFrame while our own is_swapped_out_ is false.
3133 RenderFrameImpl* rf = RenderFrameImpl::FromWebFrame(frame);
3134 CHECK(is_swapped_out_ || rf->is_swapped_out());
3135 GURL swappedOutURL(kSwappedOutURL);
3136 WebURLRequest request(swappedOutURL);
3137 frame->loadRequest(request);
3140 void RenderViewImpl::OnClosePage() {
3141 FOR_EACH_OBSERVER(RenderViewObserver, observers_, ClosePage());
3142 // TODO(creis): We'd rather use webview()->Close() here, but that currently
3143 // sets the WebView's delegate_ to NULL, preventing any JavaScript dialogs
3144 // in the onunload handler from appearing. For now, we're bypassing that and
3145 // calling the FrameLoader's CloseURL method directly. This should be
3146 // revisited to avoid having two ways to close a page. Having a single way
3147 // to close that can run onunload is also useful for fixing
3148 // http://b/issue?id=753080.
3149 webview()->mainFrame()->dispatchUnloadEvent();
3151 Send(new ViewHostMsg_ClosePage_ACK(routing_id_));
3154 void RenderViewImpl::OnThemeChanged() {
3155 #if defined(USE_AURA)
3156 // Aura doesn't care if we switch themes.
3157 #elif defined(OS_WIN)
3158 ui::NativeThemeWin::instance()->CloseHandles();
3159 if (webview())
3160 webview()->themeChanged();
3161 #else // defined(OS_WIN)
3162 // TODO(port): we don't support theming on non-Windows platforms yet
3163 NOTIMPLEMENTED();
3164 #endif
3167 void RenderViewImpl::OnMoveOrResizeStarted() {
3168 if (webview())
3169 webview()->hidePopups();
3172 void RenderViewImpl::OnResize(const ViewMsg_Resize_Params& params) {
3173 if (webview()) {
3174 webview()->hidePopups();
3175 if (send_preferred_size_changes_) {
3176 webview()->mainFrame()->setCanHaveScrollbars(
3177 ShouldDisplayScrollbars(params.new_size.width(),
3178 params.new_size.height()));
3180 UpdateScrollState(webview()->mainFrame());
3183 RenderWidget::OnResize(params);
3186 void RenderViewImpl::DidInitiatePaint() {
3187 #if defined(ENABLE_PLUGINS)
3188 // Notify all instances that we painted. The same caveats apply as for
3189 // ViewFlushedPaint regarding instances closing themselves, so we take
3190 // similar precautions.
3191 PepperPluginSet plugins = active_pepper_instances_;
3192 for (PepperPluginSet::iterator i = plugins.begin(); i != plugins.end(); ++i) {
3193 if (active_pepper_instances_.find(*i) != active_pepper_instances_.end())
3194 (*i)->ViewInitiatedPaint();
3196 #endif
3199 void RenderViewImpl::DidFlushPaint() {
3200 #if defined(ENABLE_PLUGINS)
3201 // Notify all instances that we flushed. This will call into the plugin, and
3202 // we it may ask to close itself as a result. This will, in turn, modify our
3203 // set, possibly invalidating the iterator. So we iterate on a copy that
3204 // won't change out from under us.
3205 PepperPluginSet plugins = active_pepper_instances_;
3206 for (PepperPluginSet::iterator i = plugins.begin(); i != plugins.end(); ++i) {
3207 // The copy above makes sure our iterator is never invalid if some plugins
3208 // are destroyed. But some plugin may decide to close all of its views in
3209 // response to a paint in one of them, so we need to make sure each one is
3210 // still "current" before using it.
3212 // It's possible that a plugin was destroyed, but another one was created
3213 // with the same address. In this case, we'll call ViewFlushedPaint on that
3214 // new plugin. But that's OK for this particular case since we're just
3215 // notifying all of our instances that the view flushed, and the new one is
3216 // one of our instances.
3218 // What about the case where a new one is created in a callback at a new
3219 // address and we don't issue the callback? We're still OK since this
3220 // callback is used for flush callbacks and we could not have possibly
3221 // started a new paint for the new plugin while processing a previous paint
3222 // for an existing one.
3223 if (active_pepper_instances_.find(*i) != active_pepper_instances_.end())
3224 (*i)->ViewFlushedPaint();
3226 #endif
3228 // If the RenderWidget is closing down then early-exit, otherwise we'll crash.
3229 // See crbug.com/112921.
3230 if (!webview())
3231 return;
3233 WebFrame* main_frame = webview()->mainFrame();
3235 // If we have a provisional frame we are between the start and commit stages
3236 // of loading and we don't want to save stats.
3237 if (!main_frame->provisionalDataSource()) {
3238 WebDataSource* ds = main_frame->dataSource();
3239 DocumentState* document_state = DocumentState::FromDataSource(ds);
3240 InternalDocumentStateData* data =
3241 InternalDocumentStateData::FromDocumentState(document_state);
3242 if (data->did_first_visually_non_empty_layout() &&
3243 !data->did_first_visually_non_empty_paint()) {
3244 data->set_did_first_visually_non_empty_paint(true);
3245 Send(new ViewHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_));
3248 // TODO(jar): The following code should all be inside a method, probably in
3249 // NavigatorState.
3250 Time now = Time::Now();
3251 if (document_state->first_paint_time().is_null()) {
3252 document_state->set_first_paint_time(now);
3254 if (document_state->first_paint_after_load_time().is_null() &&
3255 !document_state->finish_load_time().is_null()) {
3256 document_state->set_first_paint_after_load_time(now);
3261 gfx::Vector2d RenderViewImpl::GetScrollOffset() {
3262 WebSize scroll_offset = webview()->mainFrame()->scrollOffset();
3263 return gfx::Vector2d(scroll_offset.width, scroll_offset.height);
3266 void RenderViewImpl::OnClearFocusedElement() {
3267 if (webview())
3268 webview()->clearFocusedElement();
3271 void RenderViewImpl::OnSetBackground(const SkBitmap& background) {
3272 if (webview())
3273 webview()->setIsTransparent(!background.empty());
3274 if (compositor_)
3275 compositor_->setHasTransparentBackground(!background.empty());
3277 SetBackground(background);
3280 void RenderViewImpl::OnSetAccessibilityMode(AccessibilityMode new_mode) {
3281 if (accessibility_mode_ == new_mode)
3282 return;
3283 accessibility_mode_ = new_mode;
3284 if (renderer_accessibility_) {
3285 delete renderer_accessibility_;
3286 renderer_accessibility_ = NULL;
3288 if (accessibility_mode_ == AccessibilityModeOff)
3289 return;
3291 if (accessibility_mode_ & AccessibilityModeFlagFullTree)
3292 renderer_accessibility_ = new RendererAccessibilityComplete(this);
3293 #if !defined(OS_ANDROID)
3294 else
3295 renderer_accessibility_ = new RendererAccessibilityFocusOnly(this);
3296 #endif
3299 void RenderViewImpl::OnSetActive(bool active) {
3300 if (webview())
3301 webview()->setIsActive(active);
3303 #if defined(ENABLE_PLUGINS) && defined(OS_MACOSX)
3304 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3305 for (plugin_it = plugin_delegates_.begin();
3306 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3307 (*plugin_it)->SetWindowFocus(active);
3309 #endif
3312 #if defined(OS_MACOSX)
3313 void RenderViewImpl::OnSetWindowVisibility(bool visible) {
3314 #if defined(ENABLE_PLUGINS)
3315 // Inform plugins that their container has changed visibility.
3316 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3317 for (plugin_it = plugin_delegates_.begin();
3318 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3319 (*plugin_it)->SetContainerVisibility(visible);
3321 #endif
3324 void RenderViewImpl::OnWindowFrameChanged(const gfx::Rect& window_frame,
3325 const gfx::Rect& view_frame) {
3326 #if defined(ENABLE_PLUGINS)
3327 // Inform plugins that their window's frame has changed.
3328 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3329 for (plugin_it = plugin_delegates_.begin();
3330 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3331 (*plugin_it)->WindowFrameChanged(window_frame, view_frame);
3333 #endif
3336 void RenderViewImpl::OnPluginImeCompositionCompleted(const base::string16& text,
3337 int plugin_id) {
3338 // WebPluginDelegateProxy is responsible for figuring out if this event
3339 // applies to it or not, so inform all the delegates.
3340 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3341 for (plugin_it = plugin_delegates_.begin();
3342 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3343 (*plugin_it)->ImeCompositionCompleted(text, plugin_id);
3346 #endif // OS_MACOSX
3348 void RenderViewImpl::Close() {
3349 // We need to grab a pointer to the doomed WebView before we destroy it.
3350 WebView* doomed = webview();
3351 RenderWidget::Close();
3352 g_view_map.Get().erase(doomed);
3353 g_routing_id_view_map.Get().erase(routing_id_);
3356 void RenderViewImpl::DidHandleKeyEvent() {
3357 ClearEditCommands();
3360 bool RenderViewImpl::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
3361 possible_drag_event_info_.event_source =
3362 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE;
3363 possible_drag_event_info_.event_location =
3364 gfx::Point(event.globalX, event.globalY);
3366 #if defined(ENABLE_PLUGINS)
3367 // This method is called for every mouse event that the render view receives.
3368 // And then the mouse event is forwarded to WebKit, which dispatches it to the
3369 // event target. Potentially a Pepper plugin will receive the event.
3370 // In order to tell whether a plugin gets the last mouse event and which it
3371 // is, we set |pepper_last_mouse_event_target_| to NULL here. If a plugin gets
3372 // the event, it will notify us via DidReceiveMouseEvent() and set itself as
3373 // |pepper_last_mouse_event_target_|.
3374 pepper_last_mouse_event_target_ = NULL;
3375 #endif
3377 // If the mouse is locked, only the current owner of the mouse lock can
3378 // process mouse events.
3379 return mouse_lock_dispatcher_->WillHandleMouseEvent(event);
3382 bool RenderViewImpl::WillHandleGestureEvent(
3383 const blink::WebGestureEvent& event) {
3384 possible_drag_event_info_.event_source =
3385 ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH;
3386 possible_drag_event_info_.event_location =
3387 gfx::Point(event.globalX, event.globalY);
3388 return false;
3391 void RenderViewImpl::DidHandleMouseEvent(const WebMouseEvent& event) {
3392 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidHandleMouseEvent(event));
3395 void RenderViewImpl::DidHandleTouchEvent(const WebTouchEvent& event) {
3396 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidHandleTouchEvent(event));
3399 bool RenderViewImpl::HasTouchEventHandlersAt(const gfx::Point& point) const {
3400 if (!webview())
3401 return false;
3402 return webview()->hasTouchEventHandlersAt(point);
3405 void RenderViewImpl::OnWasHidden() {
3406 RenderWidget::OnWasHidden();
3408 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3409 RenderThreadImpl::current()->video_capture_impl_manager()->
3410 SuspendDevices(true);
3411 #endif
3413 if (webview())
3414 webview()->setVisibilityState(visibilityState(), false);
3416 #if defined(ENABLE_PLUGINS)
3417 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3418 i != active_pepper_instances_.end(); ++i)
3419 (*i)->PageVisibilityChanged(false);
3421 #if defined(OS_MACOSX)
3422 // Inform NPAPI plugins that their container is no longer visible.
3423 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3424 for (plugin_it = plugin_delegates_.begin();
3425 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3426 (*plugin_it)->SetContainerVisibility(false);
3428 #endif // OS_MACOSX
3429 #endif // ENABLE_PLUGINS
3432 void RenderViewImpl::OnWasShown(bool needs_repainting) {
3433 RenderWidget::OnWasShown(needs_repainting);
3435 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3436 RenderThreadImpl::current()->video_capture_impl_manager()->
3437 SuspendDevices(false);
3438 #endif
3440 if (webview())
3441 webview()->setVisibilityState(visibilityState(), false);
3443 #if defined(ENABLE_PLUGINS)
3444 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3445 i != active_pepper_instances_.end(); ++i)
3446 (*i)->PageVisibilityChanged(true);
3448 #if defined(OS_MACOSX)
3449 // Inform NPAPI plugins that their container is now visible.
3450 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3451 for (plugin_it = plugin_delegates_.begin();
3452 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3453 (*plugin_it)->SetContainerVisibility(true);
3455 #endif // OS_MACOSX
3456 #endif // ENABLE_PLUGINS
3459 GURL RenderViewImpl::GetURLForGraphicsContext3D() {
3460 DCHECK(webview());
3461 if (webview()->mainFrame())
3462 return GURL(webview()->mainFrame()->document().url());
3463 else
3464 return GURL("chrome://gpu/RenderViewImpl::CreateGraphicsContext3D");
3467 bool RenderViewImpl::ForceCompositingModeEnabled() {
3468 return webkit_preferences_.force_compositing_mode;
3471 void RenderViewImpl::OnSetFocus(bool enable) {
3472 RenderWidget::OnSetFocus(enable);
3474 #if defined(ENABLE_PLUGINS)
3475 if (webview() && webview()->isActive()) {
3476 // Notify all NPAPI plugins.
3477 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3478 for (plugin_it = plugin_delegates_.begin();
3479 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3480 #if defined(OS_MACOSX)
3481 // RenderWidget's call to setFocus can cause the underlying webview's
3482 // activation state to change just like a call to setIsActive.
3483 if (enable)
3484 (*plugin_it)->SetWindowFocus(true);
3485 #endif
3486 (*plugin_it)->SetContentAreaFocus(enable);
3489 // Notify all Pepper plugins.
3490 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3491 i != active_pepper_instances_.end(); ++i)
3492 (*i)->SetContentAreaFocus(enable);
3493 #endif
3494 // Notify all BrowserPlugins of the RenderView's focus state.
3495 if (browser_plugin_manager_.get())
3496 browser_plugin_manager_->UpdateFocusState();
3499 void RenderViewImpl::OnImeSetComposition(
3500 const base::string16& text,
3501 const std::vector<blink::WebCompositionUnderline>& underlines,
3502 int selection_start,
3503 int selection_end) {
3504 #if defined(ENABLE_PLUGINS)
3505 if (focused_pepper_plugin_) {
3506 focused_pepper_plugin_->render_frame()->OnImeSetComposition(
3507 text, underlines, selection_start, selection_end);
3508 return;
3511 #if defined(OS_WIN)
3512 // When a plug-in has focus, we create platform-specific IME data used by
3513 // our IME emulator and send it directly to the focused plug-in, i.e. we
3514 // bypass WebKit. (WebPluginDelegate dispatches this IME data only when its
3515 // instance ID is the same one as the specified ID.)
3516 if (focused_plugin_id_ >= 0) {
3517 std::vector<int> clauses;
3518 std::vector<int> target;
3519 for (size_t i = 0; i < underlines.size(); ++i) {
3520 clauses.push_back(underlines[i].startOffset);
3521 clauses.push_back(underlines[i].endOffset);
3522 if (underlines[i].thick) {
3523 target.clear();
3524 target.push_back(underlines[i].startOffset);
3525 target.push_back(underlines[i].endOffset);
3528 std::set<WebPluginDelegateProxy*>::iterator it;
3529 for (it = plugin_delegates_.begin(); it != plugin_delegates_.end(); ++it) {
3530 (*it)->ImeCompositionUpdated(text, clauses, target, selection_end,
3531 focused_plugin_id_);
3533 return;
3535 #endif // OS_WIN
3536 #endif // ENABLE_PLUGINS
3537 RenderWidget::OnImeSetComposition(text,
3538 underlines,
3539 selection_start,
3540 selection_end);
3543 void RenderViewImpl::OnImeConfirmComposition(
3544 const base::string16& text,
3545 const gfx::Range& replacement_range,
3546 bool keep_selection) {
3547 #if defined(ENABLE_PLUGINS)
3548 if (focused_pepper_plugin_) {
3549 focused_pepper_plugin_->render_frame()->OnImeConfirmComposition(
3550 text, replacement_range, keep_selection);
3551 return;
3553 #if defined(OS_WIN)
3554 // Same as OnImeSetComposition(), we send the text from IMEs directly to
3555 // plug-ins. When we send IME text directly to plug-ins, we should not send
3556 // it to WebKit to prevent WebKit from controlling IMEs.
3557 // TODO(thakis): Honor |replacement_range| for plugins?
3558 if (focused_plugin_id_ >= 0) {
3559 std::set<WebPluginDelegateProxy*>::iterator it;
3560 for (it = plugin_delegates_.begin();
3561 it != plugin_delegates_.end(); ++it) {
3562 (*it)->ImeCompositionCompleted(text, focused_plugin_id_);
3564 return;
3566 #endif // OS_WIN
3567 #endif // ENABLE_PLUGINS
3568 if (replacement_range.IsValid() && webview()) {
3569 // Select the text in |replacement_range|, it will then be replaced by
3570 // text added by the call to RenderWidget::OnImeConfirmComposition().
3571 if (WebLocalFrame* frame = webview()->focusedFrame()->toWebLocalFrame()) {
3572 WebRange webrange = WebRange::fromDocumentRange(
3573 frame, replacement_range.start(), replacement_range.length());
3574 if (!webrange.isNull())
3575 frame->selectRange(webrange);
3578 RenderWidget::OnImeConfirmComposition(text,
3579 replacement_range,
3580 keep_selection);
3583 void RenderViewImpl::SetDeviceScaleFactor(float device_scale_factor) {
3584 RenderWidget::SetDeviceScaleFactor(device_scale_factor);
3585 if (webview()) {
3586 webview()->setDeviceScaleFactor(device_scale_factor);
3587 webview()->settings()->setAcceleratedCompositingForFixedPositionEnabled(
3588 ShouldUseFixedPositionCompositing(device_scale_factor_));
3589 webview()->settings()->setAcceleratedCompositingForOverflowScrollEnabled(
3590 ShouldUseAcceleratedCompositingForOverflowScroll(device_scale_factor_));
3591 webview()->settings()->setAcceleratedCompositingForTransitionEnabled(
3592 ShouldUseTransitionCompositing(device_scale_factor_));
3593 webview()->settings()->
3594 setAcceleratedCompositingForFixedRootBackgroundEnabled(
3595 ShouldUseAcceleratedFixedRootBackground(device_scale_factor_));
3596 webview()->settings()->setCompositedScrollingForFramesEnabled(
3597 ShouldUseCompositedScrollingForFrames(device_scale_factor_));
3599 if (auto_resize_mode_)
3600 AutoResizeCompositor();
3602 if (browser_plugin_manager_.get())
3603 browser_plugin_manager_->UpdateDeviceScaleFactor(device_scale_factor_);
3606 ui::TextInputType RenderViewImpl::GetTextInputType() {
3607 #if defined(ENABLE_PLUGINS)
3608 if (focused_pepper_plugin_)
3609 return focused_pepper_plugin_->text_input_type();
3610 #endif
3611 return RenderWidget::GetTextInputType();
3614 void RenderViewImpl::GetSelectionBounds(gfx::Rect* start, gfx::Rect* end) {
3615 #if defined(ENABLE_PLUGINS)
3616 if (focused_pepper_plugin_) {
3617 // TODO(kinaba) http://crbug.com/101101
3618 // Current Pepper IME API does not handle selection bounds. So we simply
3619 // use the caret position as an empty range for now. It will be updated
3620 // after Pepper API equips features related to surrounding text retrieval.
3621 gfx::Rect caret = focused_pepper_plugin_->GetCaretBounds();
3622 *start = caret;
3623 *end = caret;
3624 return;
3626 #endif
3627 RenderWidget::GetSelectionBounds(start, end);
3630 #if defined(OS_MACOSX) || defined(USE_AURA)
3631 void RenderViewImpl::GetCompositionCharacterBounds(
3632 std::vector<gfx::Rect>* bounds) {
3633 DCHECK(bounds);
3634 bounds->clear();
3636 #if defined(ENABLE_PLUGINS)
3637 if (focused_pepper_plugin_) {
3638 return;
3640 #endif
3642 if (!webview())
3643 return;
3644 size_t start_offset = 0;
3645 size_t character_count = 0;
3646 if (!webview()->compositionRange(&start_offset, &character_count))
3647 return;
3648 if (character_count == 0)
3649 return;
3651 blink::WebFrame* frame = webview()->focusedFrame();
3652 if (!frame)
3653 return;
3655 bounds->reserve(character_count);
3656 blink::WebRect webrect;
3657 for (size_t i = 0; i < character_count; ++i) {
3658 if (!frame->firstRectForCharacterRange(start_offset + i, 1, webrect)) {
3659 DLOG(ERROR) << "Could not retrieve character rectangle at " << i;
3660 bounds->clear();
3661 return;
3663 bounds->push_back(webrect);
3667 void RenderViewImpl::GetCompositionRange(gfx::Range* range) {
3668 #if defined(ENABLE_PLUGINS)
3669 if (focused_pepper_plugin_) {
3670 return;
3672 #endif
3673 RenderWidget::GetCompositionRange(range);
3675 #endif
3677 bool RenderViewImpl::CanComposeInline() {
3678 #if defined(ENABLE_PLUGINS)
3679 if (focused_pepper_plugin_)
3680 return focused_pepper_plugin_->IsPluginAcceptingCompositionEvents();
3681 #endif
3682 return true;
3685 void RenderViewImpl::InstrumentWillBeginFrame(int frame_id) {
3686 if (!webview())
3687 return;
3688 if (!webview()->devToolsAgent())
3689 return;
3690 webview()->devToolsAgent()->didBeginFrame(frame_id);
3693 void RenderViewImpl::InstrumentDidBeginFrame() {
3694 if (!webview())
3695 return;
3696 if (!webview()->devToolsAgent())
3697 return;
3698 // TODO(jamesr/caseq): Decide if this needs to be renamed.
3699 webview()->devToolsAgent()->didComposite();
3702 void RenderViewImpl::InstrumentDidCancelFrame() {
3703 if (!webview())
3704 return;
3705 if (!webview()->devToolsAgent())
3706 return;
3707 webview()->devToolsAgent()->didCancelFrame();
3710 void RenderViewImpl::InstrumentWillComposite() {
3711 if (!webview())
3712 return;
3713 if (!webview()->devToolsAgent())
3714 return;
3715 webview()->devToolsAgent()->willComposite();
3718 void RenderViewImpl::SetScreenMetricsEmulationParameters(
3719 float device_scale_factor,
3720 const gfx::Point& root_layer_offset,
3721 float root_layer_scale) {
3722 if (webview()) {
3723 webview()->setCompositorDeviceScaleFactorOverride(device_scale_factor);
3724 webview()->setRootLayerTransform(
3725 blink::WebSize(root_layer_offset.x(), root_layer_offset.y()),
3726 root_layer_scale);
3730 bool RenderViewImpl::ScheduleFileChooser(
3731 const FileChooserParams& params,
3732 WebFileChooserCompletion* completion) {
3733 static const size_t kMaximumPendingFileChooseRequests = 4;
3734 if (file_chooser_completions_.size() > kMaximumPendingFileChooseRequests) {
3735 // This sanity check prevents too many file choose requests from getting
3736 // queued which could DoS the user. Getting these is most likely a
3737 // programming error (there are many ways to DoS the user so it's not
3738 // considered a "real" security check), either in JS requesting many file
3739 // choosers to pop up, or in a plugin.
3741 // TODO(brettw) we might possibly want to require a user gesture to open
3742 // a file picker, which will address this issue in a better way.
3743 return false;
3746 file_chooser_completions_.push_back(linked_ptr<PendingFileChooser>(
3747 new PendingFileChooser(params, completion)));
3748 if (file_chooser_completions_.size() == 1) {
3749 // Actually show the browse dialog when this is the first request.
3750 Send(new ViewHostMsg_RunFileChooser(routing_id_, params));
3752 return true;
3755 blink::WebGeolocationClient* RenderViewImpl::geolocationClient() {
3756 if (!geolocation_dispatcher_)
3757 geolocation_dispatcher_ = new GeolocationDispatcher(this);
3758 return geolocation_dispatcher_;
3761 blink::WebSpeechRecognizer* RenderViewImpl::speechRecognizer() {
3762 if (!speech_recognition_dispatcher_)
3763 speech_recognition_dispatcher_ = new SpeechRecognitionDispatcher(this);
3764 return speech_recognition_dispatcher_;
3767 void RenderViewImpl::zoomLimitsChanged(double minimum_level,
3768 double maximum_level) {
3769 // For now, don't remember plugin zoom values. We don't want to mix them with
3770 // normal web content (i.e. a fixed layout plugin would usually want them
3771 // different).
3772 bool remember = !webview()->mainFrame()->document().isPluginDocument();
3774 int minimum_percent = static_cast<int>(
3775 ZoomLevelToZoomFactor(minimum_level) * 100);
3776 int maximum_percent = static_cast<int>(
3777 ZoomLevelToZoomFactor(maximum_level) * 100);
3779 Send(new ViewHostMsg_UpdateZoomLimits(
3780 routing_id_, minimum_percent, maximum_percent, remember));
3783 void RenderViewImpl::zoomLevelChanged() {
3784 bool remember = !webview()->mainFrame()->document().isPluginDocument();
3785 double zoom_level = webview()->zoomLevel();
3787 FOR_EACH_OBSERVER(RenderViewObserver, observers_, ZoomLevelChanged());
3789 // Do not send empty URLs to the browser when we are just setting the default
3790 // zoom level (from RendererPreferences) before the first navigation.
3791 if (!webview()->mainFrame()->document().url().isEmpty()) {
3792 // Tell the browser which url got zoomed so it can update the menu and the
3793 // saved values if necessary
3794 Send(new ViewHostMsg_DidZoomURL(
3795 routing_id_, zoom_level, remember,
3796 GURL(webview()->mainFrame()->document().url())));
3800 double RenderViewImpl::zoomLevelToZoomFactor(double zoom_level) const {
3801 return ZoomLevelToZoomFactor(zoom_level);
3804 double RenderViewImpl::zoomFactorToZoomLevel(double factor) const {
3805 return ZoomFactorToZoomLevel(factor);
3808 void RenderViewImpl::registerProtocolHandler(const WebString& scheme,
3809 const WebURL& base_url,
3810 const WebURL& url,
3811 const WebString& title) {
3812 bool user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
3813 GURL base(base_url);
3814 GURL absolute_url = base.Resolve(base::UTF16ToUTF8(url.string()));
3815 if (base.GetOrigin() != absolute_url.GetOrigin()) {
3816 return;
3818 Send(new ViewHostMsg_RegisterProtocolHandler(routing_id_,
3819 base::UTF16ToUTF8(scheme),
3820 absolute_url,
3821 title,
3822 user_gesture));
3825 blink::WebPageVisibilityState RenderViewImpl::visibilityState() const {
3826 blink::WebPageVisibilityState current_state = is_hidden() ?
3827 blink::WebPageVisibilityStateHidden :
3828 blink::WebPageVisibilityStateVisible;
3829 blink::WebPageVisibilityState override_state = current_state;
3830 // TODO(jam): move this method to WebFrameClient.
3831 if (GetContentClient()->renderer()->
3832 ShouldOverridePageVisibilityState(main_render_frame_.get(),
3833 &override_state))
3834 return override_state;
3835 return current_state;
3838 blink::WebMIDIClient* RenderViewImpl::webMIDIClient() {
3839 if (!midi_dispatcher_)
3840 midi_dispatcher_ = new MidiDispatcher(this);
3841 return midi_dispatcher_;
3844 blink::WebPushClient* RenderViewImpl::webPushClient() {
3845 if (!push_messaging_dispatcher_)
3846 push_messaging_dispatcher_ = new PushMessagingDispatcher(this);
3847 return push_messaging_dispatcher_;
3850 void RenderViewImpl::draggableRegionsChanged() {
3851 FOR_EACH_OBSERVER(
3852 RenderViewObserver,
3853 observers_,
3854 DraggableRegionsChanged(webview()->mainFrame()));
3857 #if defined(OS_ANDROID)
3858 WebContentDetectionResult RenderViewImpl::detectContentAround(
3859 const WebHitTestResult& touch_hit) {
3860 DCHECK(!touch_hit.isNull());
3861 DCHECK(!touch_hit.node().isNull());
3862 DCHECK(touch_hit.node().isTextNode());
3864 // Process the position with all the registered content detectors until
3865 // a match is found. Priority is provided by their relative order.
3866 for (ContentDetectorList::const_iterator it = content_detectors_.begin();
3867 it != content_detectors_.end(); ++it) {
3868 ContentDetector::Result content = (*it)->FindTappedContent(touch_hit);
3869 if (content.valid) {
3870 return WebContentDetectionResult(content.content_boundaries,
3871 base::UTF8ToUTF16(content.text), content.intent_url);
3874 return WebContentDetectionResult();
3877 void RenderViewImpl::scheduleContentIntent(const WebURL& intent) {
3878 // Introduce a short delay so that the user can notice the content.
3879 base::MessageLoop::current()->PostDelayedTask(
3880 FROM_HERE,
3881 base::Bind(&RenderViewImpl::LaunchAndroidContentIntent,
3882 AsWeakPtr(),
3883 intent,
3884 expected_content_intent_id_),
3885 base::TimeDelta::FromMilliseconds(kContentIntentDelayMilliseconds));
3888 void RenderViewImpl::cancelScheduledContentIntents() {
3889 ++expected_content_intent_id_;
3892 void RenderViewImpl::LaunchAndroidContentIntent(const GURL& intent,
3893 size_t request_id) {
3894 if (request_id != expected_content_intent_id_)
3895 return;
3897 // Remove the content highlighting if any.
3898 scheduleComposite();
3900 if (!intent.is_empty())
3901 Send(new ViewHostMsg_StartContentIntent(routing_id_, intent));
3904 bool RenderViewImpl::openDateTimeChooser(
3905 const blink::WebDateTimeChooserParams& params,
3906 blink::WebDateTimeChooserCompletion* completion) {
3907 // JavaScript may try to open a date time chooser while one is already open.
3908 if (date_time_picker_client_)
3909 return false;
3910 date_time_picker_client_.reset(
3911 new RendererDateTimePicker(this, params, completion));
3912 return date_time_picker_client_->Open();
3915 void RenderViewImpl::DismissDateTimeDialog() {
3916 DCHECK(date_time_picker_client_);
3917 date_time_picker_client_.reset(NULL);
3920 #endif // defined(OS_ANDROID)
3922 #if defined(OS_MACOSX)
3923 void RenderViewImpl::OnSelectPopupMenuItem(int selected_index) {
3924 if (external_popup_menu_ == NULL)
3925 return;
3926 external_popup_menu_->DidSelectItem(selected_index);
3927 external_popup_menu_.reset();
3929 #endif
3931 #if defined(OS_ANDROID)
3932 void RenderViewImpl::OnSelectPopupMenuItems(
3933 bool canceled,
3934 const std::vector<int>& selected_indices) {
3935 // It is possible to receive more than one of these calls if the user presses
3936 // a select faster than it takes for the show-select-popup IPC message to make
3937 // it to the browser UI thread. Ignore the extra-messages.
3938 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
3939 if (!external_popup_menu_)
3940 return;
3942 external_popup_menu_->DidSelectItems(canceled, selected_indices);
3943 external_popup_menu_.reset();
3945 #endif
3947 #if defined(OS_MACOSX) || defined(OS_ANDROID)
3948 void RenderViewImpl::DidHideExternalPopupMenu() {
3949 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
3950 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
3951 external_popup_menu_.reset();
3953 #endif
3955 void RenderViewImpl::OnShowContextMenu(const gfx::Point& location) {
3956 context_menu_source_type_ = ui::MENU_SOURCE_TOUCH_EDIT_MENU;
3957 touch_editing_context_menu_location_ = location;
3958 if (webview())
3959 webview()->showContextMenu();
3962 void RenderViewImpl::OnEnableViewSourceMode() {
3963 if (!webview())
3964 return;
3965 WebFrame* main_frame = webview()->mainFrame();
3966 if (!main_frame)
3967 return;
3968 main_frame->enableViewSourceMode(true);
3971 void RenderViewImpl::OnDisownOpener() {
3972 if (!webview())
3973 return;
3975 WebFrame* main_frame = webview()->mainFrame();
3976 if (main_frame && main_frame->opener())
3977 main_frame->setOpener(NULL);
3980 #if defined(OS_ANDROID)
3981 bool RenderViewImpl::didTapMultipleTargets(
3982 const blink::WebGestureEvent& event,
3983 const WebVector<WebRect>& target_rects) {
3984 // Never show a disambiguation popup when accessibility is enabled,
3985 // as this interferes with "touch exploration".
3986 bool matchesAccessibilityModeComplete =
3987 (accessibility_mode_ & AccessibilityModeComplete) ==
3988 AccessibilityModeComplete;
3989 if (matchesAccessibilityModeComplete)
3990 return false;
3992 gfx::Rect finger_rect(
3993 event.x - event.data.tap.width / 2, event.y - event.data.tap.height / 2,
3994 event.data.tap.width, event.data.tap.height);
3995 gfx::Rect zoom_rect;
3996 float new_total_scale =
3997 DisambiguationPopupHelper::ComputeZoomAreaAndScaleFactor(
3998 finger_rect, target_rects, GetSize(),
3999 gfx::Rect(webview()->mainFrame()->visibleContentRect()).size(),
4000 device_scale_factor_ * webview()->pageScaleFactor(), &zoom_rect);
4001 if (!new_total_scale)
4002 return false;
4004 bool handled = false;
4005 switch (renderer_preferences_.tap_multiple_targets_strategy) {
4006 case TAP_MULTIPLE_TARGETS_STRATEGY_ZOOM:
4007 handled = webview()->zoomToMultipleTargetsRect(zoom_rect);
4008 break;
4009 case TAP_MULTIPLE_TARGETS_STRATEGY_POPUP: {
4010 gfx::Size canvas_size =
4011 gfx::ToCeiledSize(gfx::ScaleSize(zoom_rect.size(), new_total_scale));
4012 cc::SharedBitmapManager* manager =
4013 RenderThreadImpl::current()->shared_bitmap_manager();
4014 scoped_ptr<cc::SharedBitmap> shared_bitmap =
4015 manager->AllocateSharedBitmap(canvas_size);
4017 SkBitmap bitmap;
4018 SkImageInfo info = SkImageInfo::MakeN32Premul(canvas_size.width(),
4019 canvas_size.height());
4020 bitmap.installPixels(info, shared_bitmap->pixels(), info.minRowBytes());
4021 SkCanvas canvas(bitmap);
4023 // TODO(trchen): Cleanup the device scale factor mess.
4024 // device scale will be applied in WebKit
4025 // --> zoom_rect doesn't include device scale,
4026 // but WebKit will still draw on zoom_rect * device_scale_factor_
4027 canvas.scale(new_total_scale / device_scale_factor_,
4028 new_total_scale / device_scale_factor_);
4029 canvas.translate(-zoom_rect.x() * device_scale_factor_,
4030 -zoom_rect.y() * device_scale_factor_);
4032 DCHECK(webwidget_->isAcceleratedCompositingActive());
4033 // TODO(aelias): The disambiguation popup should be composited so we
4034 // don't have to call this method.
4035 webwidget_->paintCompositedDeprecated(&canvas, zoom_rect);
4038 gfx::Rect physical_window_zoom_rect = gfx::ToEnclosingRect(
4039 ClientRectToPhysicalWindowRect(gfx::RectF(zoom_rect)));
4040 Send(new ViewHostMsg_ShowDisambiguationPopup(routing_id_,
4041 physical_window_zoom_rect,
4042 canvas_size,
4043 shared_bitmap->id()));
4044 cc::SharedBitmapId id = shared_bitmap->id();
4045 disambiguation_bitmaps_[id] = shared_bitmap.release();
4046 handled = true;
4047 break;
4049 case TAP_MULTIPLE_TARGETS_STRATEGY_NONE:
4050 // No-op.
4051 break;
4054 return handled;
4056 #endif
4058 unsigned RenderViewImpl::GetLocalSessionHistoryLengthForTesting() const {
4059 return history_list_length_;
4062 void RenderViewImpl::SetFocusAndActivateForTesting(bool enable) {
4063 if (enable) {
4064 if (has_focus())
4065 return;
4066 OnSetActive(true);
4067 OnSetFocus(true);
4068 } else {
4069 if (!has_focus())
4070 return;
4071 OnSetFocus(false);
4072 OnSetActive(false);
4076 void RenderViewImpl::SetDeviceScaleFactorForTesting(float factor) {
4077 ViewMsg_Resize_Params params;
4078 params.screen_info = screen_info_;
4079 params.screen_info.deviceScaleFactor = factor;
4080 params.new_size = size();
4081 params.physical_backing_size =
4082 gfx::ToCeiledSize(gfx::ScaleSize(size(), factor));
4083 params.overdraw_bottom_height = 0.f;
4084 params.resizer_rect = WebRect();
4085 params.is_fullscreen = is_fullscreen();
4086 OnResize(params);
4089 void RenderViewImpl::ForceResizeForTesting(const gfx::Size& new_size) {
4090 gfx::Rect new_position(rootWindowRect().x,
4091 rootWindowRect().y,
4092 new_size.width(),
4093 new_size.height());
4094 ResizeSynchronously(new_position);
4097 void RenderViewImpl::UseSynchronousResizeModeForTesting(bool enable) {
4098 resizing_mode_selector_->set_is_synchronous_mode(enable);
4101 void RenderViewImpl::EnableAutoResizeForTesting(const gfx::Size& min_size,
4102 const gfx::Size& max_size) {
4103 OnEnableAutoResize(min_size, max_size);
4106 void RenderViewImpl::DisableAutoResizeForTesting(const gfx::Size& new_size) {
4107 OnDisableAutoResize(new_size);
4110 void RenderViewImpl::OnReleaseDisambiguationPopupBitmap(
4111 const cc::SharedBitmapId& id) {
4112 BitmapMap::iterator it = disambiguation_bitmaps_.find(id);
4113 DCHECK(it != disambiguation_bitmaps_.end());
4114 delete it->second;
4115 disambiguation_bitmaps_.erase(it);
4118 void RenderViewImpl::DidCommitCompositorFrame() {
4119 RenderWidget::DidCommitCompositorFrame();
4120 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidCommitCompositorFrame());
4123 void RenderViewImpl::SendUpdateFaviconURL(const std::vector<FaviconURL>& urls) {
4124 if (!urls.empty())
4125 Send(new ViewHostMsg_UpdateFaviconURL(routing_id_, urls));
4128 void RenderViewImpl::DidStopLoadingIcons() {
4129 int icon_types = WebIconURL::TypeFavicon;
4130 if (TouchEnabled())
4131 icon_types |= WebIconURL::TypeTouchPrecomposed | WebIconURL::TypeTouch;
4133 WebVector<WebIconURL> icon_urls =
4134 webview()->mainFrame()->iconURLs(icon_types);
4136 std::vector<FaviconURL> urls;
4137 for (size_t i = 0; i < icon_urls.size(); i++) {
4138 WebURL url = icon_urls[i].iconURL();
4139 std::vector<gfx::Size> sizes;
4140 ConvertToFaviconSizes(icon_urls[i].sizes(), &sizes);
4141 if (!url.isEmpty())
4142 urls.push_back(
4143 FaviconURL(url, ToFaviconType(icon_urls[i].iconType()), sizes));
4145 SendUpdateFaviconURL(urls);
4148 } // namespace content