Add non-native file support to the ViewMsg_RunFileChooserResponse message.
[chromium-blink-merge.git] / content / renderer / render_view_impl.cc
blob135719d822349a8a09dc40efc9b7091298c50cb1
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/field_trial.h"
24 #include "base/metrics/histogram.h"
25 #include "base/path_service.h"
26 #include "base/process/kill.h"
27 #include "base/process/process.h"
28 #include "base/strings/string_number_conversions.h"
29 #include "base/strings/string_piece.h"
30 #include "base/strings/string_split.h"
31 #include "base/strings/string_util.h"
32 #include "base/strings/sys_string_conversions.h"
33 #include "base/strings/utf_string_conversions.h"
34 #include "base/time/time.h"
35 #include "cc/base/switches.h"
36 #include "content/child/appcache/appcache_dispatcher.h"
37 #include "content/child/appcache/web_application_cache_host_impl.h"
38 #include "content/child/child_shared_bitmap_manager.h"
39 #include "content/child/child_thread.h"
40 #include "content/child/npapi/webplugin_delegate_impl.h"
41 #include "content/child/request_extra_data.h"
42 #include "content/child/webmessageportchannel_impl.h"
43 #include "content/common/content_constants_internal.h"
44 #include "content/common/database_messages.h"
45 #include "content/common/dom_storage/dom_storage_types.h"
46 #include "content/common/drag_messages.h"
47 #include "content/common/frame_messages.h"
48 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
49 #include "content/common/input_messages.h"
50 #include "content/common/pepper_messages.h"
51 #include "content/common/socket_stream_handle_data.h"
52 #include "content/common/ssl_status_serialization.h"
53 #include "content/common/view_messages.h"
54 #include "content/public/common/bindings_policy.h"
55 #include "content/public/common/content_client.h"
56 #include "content/public/common/content_constants.h"
57 #include "content/public/common/content_switches.h"
58 #include "content/public/common/drop_data.h"
59 #include "content/public/common/favicon_url.h"
60 #include "content/public/common/file_chooser_file_info.h"
61 #include "content/public/common/file_chooser_params.h"
62 #include "content/public/common/page_state.h"
63 #include "content/public/common/page_zoom.h"
64 #include "content/public/common/ssl_status.h"
65 #include "content/public/common/three_d_api_types.h"
66 #include "content/public/common/url_constants.h"
67 #include "content/public/common/url_utils.h"
68 #include "content/public/common/web_preferences.h"
69 #include "content/public/renderer/content_renderer_client.h"
70 #include "content/public/renderer/document_state.h"
71 #include "content/public/renderer/navigation_state.h"
72 #include "content/public/renderer/render_view_observer.h"
73 #include "content/public/renderer/render_view_visitor.h"
74 #include "content/renderer/accessibility/renderer_accessibility.h"
75 #include "content/renderer/accessibility/renderer_accessibility_complete.h"
76 #include "content/renderer/accessibility/renderer_accessibility_focus_only.h"
77 #include "content/renderer/browser_plugin/browser_plugin.h"
78 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
79 #include "content/renderer/devtools/devtools_agent.h"
80 #include "content/renderer/disambiguation_popup_helper.h"
81 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
82 #include "content/renderer/drop_data_builder.h"
83 #include "content/renderer/gpu/render_widget_compositor.h"
84 #include "content/renderer/history_controller.h"
85 #include "content/renderer/history_serialization.h"
86 #include "content/renderer/idle_user_detector.h"
87 #include "content/renderer/ime_event_guard.h"
88 #include "content/renderer/input/input_handler_manager.h"
89 #include "content/renderer/internal_document_state_data.h"
90 #include "content/renderer/media/audio_device_factory.h"
91 #include "content/renderer/media/video_capture_impl_manager.h"
92 #include "content/renderer/memory_benchmarking_extension.h"
93 #include "content/renderer/mhtml_generator.h"
94 #include "content/renderer/net_info_helper.h"
95 #include "content/renderer/render_frame_impl.h"
96 #include "content/renderer/render_frame_proxy.h"
97 #include "content/renderer/render_process.h"
98 #include "content/renderer/render_thread_impl.h"
99 #include "content/renderer/render_view_impl_params.h"
100 #include "content/renderer/render_view_mouse_lock_dispatcher.h"
101 #include "content/renderer/render_widget_fullscreen_pepper.h"
102 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
103 #include "content/renderer/resizing_mode_selector.h"
104 #include "content/renderer/savable_resources.h"
105 #include "content/renderer/skia_benchmarking_extension.h"
106 #include "content/renderer/speech_recognition_dispatcher.h"
107 #include "content/renderer/stats_collection_controller.h"
108 #include "content/renderer/stats_collection_observer.h"
109 #include "content/renderer/text_input_client_observer.h"
110 #include "content/renderer/v8_value_converter_impl.h"
111 #include "content/renderer/web_ui_extension.h"
112 #include "content/renderer/web_ui_extension_data.h"
113 #include "content/renderer/web_ui_mojo.h"
114 #include "content/renderer/websharedworker_proxy.h"
115 #include "media/audio/audio_output_device.h"
116 #include "media/base/media_switches.h"
117 #include "media/filters/audio_renderer_impl.h"
118 #include "media/filters/gpu_video_accelerator_factories.h"
119 #include "net/base/data_url.h"
120 #include "net/base/escape.h"
121 #include "net/base/net_errors.h"
122 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
123 #include "net/http/http_util.h"
124 #include "skia/ext/platform_canvas.h"
125 #include "third_party/WebKit/public/platform/WebCString.h"
126 #include "third_party/WebKit/public/platform/WebConnectionType.h"
127 #include "third_party/WebKit/public/platform/WebDragData.h"
128 #include "third_party/WebKit/public/platform/WebHTTPBody.h"
129 #include "third_party/WebKit/public/platform/WebImage.h"
130 #include "third_party/WebKit/public/platform/WebMessagePortChannel.h"
131 #include "third_party/WebKit/public/platform/WebPoint.h"
132 #include "third_party/WebKit/public/platform/WebRect.h"
133 #include "third_party/WebKit/public/platform/WebSize.h"
134 #include "third_party/WebKit/public/platform/WebSocketStreamHandle.h"
135 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
136 #include "third_party/WebKit/public/platform/WebString.h"
137 #include "third_party/WebKit/public/platform/WebURL.h"
138 #include "third_party/WebKit/public/platform/WebURLError.h"
139 #include "third_party/WebKit/public/platform/WebURLRequest.h"
140 #include "third_party/WebKit/public/platform/WebURLResponse.h"
141 #include "third_party/WebKit/public/platform/WebVector.h"
142 #include "third_party/WebKit/public/web/WebAXObject.h"
143 #include "third_party/WebKit/public/web/WebColorName.h"
144 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
145 #include "third_party/WebKit/public/web/WebDOMEvent.h"
146 #include "third_party/WebKit/public/web/WebDOMMessageEvent.h"
147 #include "third_party/WebKit/public/web/WebDataSource.h"
148 #include "third_party/WebKit/public/web/WebDateTimeChooserCompletion.h"
149 #include "third_party/WebKit/public/web/WebDateTimeChooserParams.h"
150 #include "third_party/WebKit/public/web/WebDevToolsAgent.h"
151 #include "third_party/WebKit/public/web/WebDocument.h"
152 #include "third_party/WebKit/public/web/WebElement.h"
153 #include "third_party/WebKit/public/web/WebFileChooserParams.h"
154 #include "third_party/WebKit/public/web/WebFindOptions.h"
155 #include "third_party/WebKit/public/web/WebFormControlElement.h"
156 #include "third_party/WebKit/public/web/WebFormElement.h"
157 #include "third_party/WebKit/public/web/WebFrame.h"
158 #include "third_party/WebKit/public/web/WebGlyphCache.h"
159 #include "third_party/WebKit/public/web/WebHistoryItem.h"
160 #include "third_party/WebKit/public/web/WebHitTestResult.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/WebKit.h"
164 #include "third_party/WebKit/public/web/WebLocalFrame.h"
165 #include "third_party/WebKit/public/web/WebMediaPlayerAction.h"
166 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
167 #include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
168 #include "third_party/WebKit/public/web/WebNodeList.h"
169 #include "third_party/WebKit/public/web/WebPageSerializer.h"
170 #include "third_party/WebKit/public/web/WebPlugin.h"
171 #include "third_party/WebKit/public/web/WebPluginAction.h"
172 #include "third_party/WebKit/public/web/WebPluginContainer.h"
173 #include "third_party/WebKit/public/web/WebPluginDocument.h"
174 #include "third_party/WebKit/public/web/WebRange.h"
175 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
176 #include "third_party/WebKit/public/web/WebScriptSource.h"
177 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
178 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
179 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
180 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
181 #include "third_party/WebKit/public/web/WebSettings.h"
182 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
183 #include "third_party/WebKit/public/web/WebView.h"
184 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
185 #include "third_party/WebKit/public/web/default/WebRenderTheme.h"
186 #include "third_party/icu/source/common/unicode/uchar.h"
187 #include "third_party/icu/source/common/unicode/uscript.h"
188 #include "ui/base/clipboard/clipboard.h"
189 #include "ui/base/ui_base_switches_util.h"
190 #include "ui/events/latency_info.h"
191 #include "ui/gfx/native_widget_types.h"
192 #include "ui/gfx/point.h"
193 #include "ui/gfx/rect.h"
194 #include "ui/gfx/rect_conversions.h"
195 #include "ui/gfx/size_conversions.h"
196 #include "v8/include/v8.h"
198 #if defined(OS_ANDROID)
199 #include <cpu-features.h>
201 #include "content/renderer/android/address_detector.h"
202 #include "content/renderer/android/content_detector.h"
203 #include "content/renderer/android/email_detector.h"
204 #include "content/renderer/android/phone_number_detector.h"
205 #include "net/android/network_library.h"
206 #include "third_party/WebKit/public/platform/WebFloatPoint.h"
207 #include "third_party/WebKit/public/platform/WebFloatRect.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 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
229 #endif
231 using blink::WebAXObject;
232 using blink::WebApplicationCacheHost;
233 using blink::WebApplicationCacheHostClient;
234 using blink::WebCString;
235 using blink::WebColor;
236 using blink::WebColorName;
237 using blink::WebConsoleMessage;
238 using blink::WebData;
239 using blink::WebDataSource;
240 using blink::WebDocument;
241 using blink::WebDOMEvent;
242 using blink::WebDOMMessageEvent;
243 using blink::WebDragData;
244 using blink::WebDragOperation;
245 using blink::WebDragOperationsMask;
246 using blink::WebElement;
247 using blink::WebFileChooserCompletion;
248 using blink::WebFindOptions;
249 using blink::WebFormControlElement;
250 using blink::WebFormElement;
251 using blink::WebFrame;
252 using blink::WebGestureEvent;
253 using blink::WebHistoryItem;
254 using blink::WebHTTPBody;
255 using blink::WebIconURL;
256 using blink::WebImage;
257 using blink::WebInputElement;
258 using blink::WebInputEvent;
259 using blink::WebLocalFrame;
260 using blink::WebMediaPlayerAction;
261 using blink::WebMouseEvent;
262 using blink::WebNavigationPolicy;
263 using blink::WebNavigationType;
264 using blink::WebNode;
265 using blink::WebPageSerializer;
266 using blink::WebPageSerializerClient;
267 using blink::WebPeerConnection00Handler;
268 using blink::WebPeerConnection00HandlerClient;
269 using blink::WebPeerConnectionHandler;
270 using blink::WebPeerConnectionHandlerClient;
271 using blink::WebPluginAction;
272 using blink::WebPluginContainer;
273 using blink::WebPluginDocument;
274 using blink::WebPoint;
275 using blink::WebRange;
276 using blink::WebRect;
277 using blink::WebReferrerPolicy;
278 using blink::WebScriptSource;
279 using blink::WebSearchableFormData;
280 using blink::WebSecurityOrigin;
281 using blink::WebSecurityPolicy;
282 using blink::WebSerializedScriptValue;
283 using blink::WebSettings;
284 using blink::WebSize;
285 using blink::WebSocketStreamHandle;
286 using blink::WebStorageNamespace;
287 using blink::WebStorageQuotaCallbacks;
288 using blink::WebStorageQuotaError;
289 using blink::WebStorageQuotaType;
290 using blink::WebString;
291 using blink::WebTextAffinity;
292 using blink::WebTextDirection;
293 using blink::WebTouchEvent;
294 using blink::WebURL;
295 using blink::WebURLError;
296 using blink::WebURLRequest;
297 using blink::WebURLResponse;
298 using blink::WebUserGestureIndicator;
299 using blink::WebVector;
300 using blink::WebView;
301 using blink::WebWidget;
302 using blink::WebWindowFeatures;
303 using blink::WebNetworkStateNotifier;
304 using blink::WebRuntimeFeatures;
305 using base::Time;
306 using base::TimeDelta;
308 #if defined(OS_ANDROID)
309 using blink::WebContentDetectionResult;
310 using blink::WebFloatPoint;
311 using blink::WebFloatRect;
312 using blink::WebHitTestResult;
313 #endif
315 namespace content {
317 //-----------------------------------------------------------------------------
319 typedef std::map<blink::WebView*, RenderViewImpl*> ViewMap;
320 static base::LazyInstance<ViewMap> g_view_map = LAZY_INSTANCE_INITIALIZER;
321 typedef std::map<int32, RenderViewImpl*> RoutingIDViewMap;
322 static base::LazyInstance<RoutingIDViewMap> g_routing_id_view_map =
323 LAZY_INSTANCE_INITIALIZER;
325 // Time, in seconds, we delay before sending content state changes (such as form
326 // state and scroll position) to the browser. We delay sending changes to avoid
327 // spamming the browser.
328 // To avoid having tab/session restore require sending a message to get the
329 // current content state during tab closing we use a shorter timeout for the
330 // foreground renderer. This means there is a small window of time from which
331 // content state is modified and not sent to session restore, but this is
332 // better than having to wake up all renderers during shutdown.
333 const int kDelaySecondsForContentStateSyncHidden = 5;
334 const int kDelaySecondsForContentStateSync = 1;
336 #if defined(OS_ANDROID)
337 // Delay between tapping in content and launching the associated android intent.
338 // Used to allow users see what has been recognized as content.
339 const size_t kContentIntentDelayMilliseconds = 700;
340 #endif
342 static RenderViewImpl* (*g_create_render_view_impl)(RenderViewImplParams*) =
343 NULL;
345 // static
346 bool RenderViewImpl::IsReload(FrameMsg_Navigate_Type::Value navigation_type) {
347 return navigation_type == FrameMsg_Navigate_Type::RELOAD ||
348 navigation_type == FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE ||
349 navigation_type == FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL;
352 // static
353 Referrer RenderViewImpl::GetReferrerFromRequest(
354 WebFrame* frame,
355 const WebURLRequest& request) {
356 return Referrer(GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
357 request.referrerPolicy());
360 // static
361 WindowOpenDisposition RenderViewImpl::NavigationPolicyToDisposition(
362 WebNavigationPolicy policy) {
363 switch (policy) {
364 case blink::WebNavigationPolicyIgnore:
365 return IGNORE_ACTION;
366 case blink::WebNavigationPolicyDownload:
367 return SAVE_TO_DISK;
368 case blink::WebNavigationPolicyCurrentTab:
369 return CURRENT_TAB;
370 case blink::WebNavigationPolicyNewBackgroundTab:
371 return NEW_BACKGROUND_TAB;
372 case blink::WebNavigationPolicyNewForegroundTab:
373 return NEW_FOREGROUND_TAB;
374 case blink::WebNavigationPolicyNewWindow:
375 return NEW_WINDOW;
376 case blink::WebNavigationPolicyNewPopup:
377 return NEW_POPUP;
378 default:
379 NOTREACHED() << "Unexpected WebNavigationPolicy";
380 return IGNORE_ACTION;
384 // Returns true if the device scale is high enough that losing subpixel
385 // antialiasing won't have a noticeable effect on text quality.
386 static bool DeviceScaleEnsuresTextQuality(float device_scale_factor) {
387 #if defined(OS_ANDROID)
388 // On Android, we never have subpixel antialiasing.
389 return true;
390 #else
391 return device_scale_factor > 1.5f;
392 #endif
396 static bool PreferCompositingToLCDText(float device_scale_factor) {
397 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
398 if (command_line.HasSwitch(switches::kDisablePreferCompositingToLCDText))
399 return false;
400 if (command_line.HasSwitch(switches::kEnablePreferCompositingToLCDText))
401 return true;
402 if (RenderThreadImpl::current() &&
403 !RenderThreadImpl::current()->is_lcd_text_enabled())
404 return true;
405 return DeviceScaleEnsuresTextQuality(device_scale_factor);
408 static bool ShouldUseTransitionCompositing(float device_scale_factor) {
409 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
411 if (command_line.HasSwitch(switches::kDisableCompositingForTransition))
412 return false;
414 if (command_line.HasSwitch(switches::kEnableCompositingForTransition))
415 return true;
417 // TODO(ajuma): Re-enable this by default for high-DPI once the problem
418 // of excessive layer promotion caused by overlap has been addressed.
419 // http://crbug.com/178119.
420 return false;
423 static FaviconURL::IconType ToFaviconType(blink::WebIconURL::Type type) {
424 switch (type) {
425 case blink::WebIconURL::TypeFavicon:
426 return FaviconURL::FAVICON;
427 case blink::WebIconURL::TypeTouch:
428 return FaviconURL::TOUCH_ICON;
429 case blink::WebIconURL::TypeTouchPrecomposed:
430 return FaviconURL::TOUCH_PRECOMPOSED_ICON;
431 case blink::WebIconURL::TypeInvalid:
432 return FaviconURL::INVALID_ICON;
434 return FaviconURL::INVALID_ICON;
437 static void ConvertToFaviconSizes(
438 const blink::WebVector<blink::WebSize>& web_sizes,
439 std::vector<gfx::Size>* sizes) {
440 DCHECK(sizes->empty());
441 sizes->reserve(web_sizes.size());
442 for (size_t i = 0; i < web_sizes.size(); ++i)
443 sizes->push_back(gfx::Size(web_sizes[i]));
446 ///////////////////////////////////////////////////////////////////////////////
448 struct RenderViewImpl::PendingFileChooser {
449 PendingFileChooser(const FileChooserParams& p, WebFileChooserCompletion* c)
450 : params(p),
451 completion(c) {
453 FileChooserParams params;
454 WebFileChooserCompletion* completion; // MAY BE NULL to skip callback.
457 namespace {
459 class WebWidgetLockTarget : public MouseLockDispatcher::LockTarget {
460 public:
461 explicit WebWidgetLockTarget(blink::WebWidget* webwidget)
462 : webwidget_(webwidget) {}
464 virtual void OnLockMouseACK(bool succeeded) override {
465 if (succeeded)
466 webwidget_->didAcquirePointerLock();
467 else
468 webwidget_->didNotAcquirePointerLock();
471 virtual void OnMouseLockLost() override {
472 webwidget_->didLosePointerLock();
475 virtual bool HandleMouseLockedInputEvent(
476 const blink::WebMouseEvent &event) override {
477 // The WebWidget handles mouse lock in WebKit's handleInputEvent().
478 return false;
481 private:
482 blink::WebWidget* webwidget_;
485 bool TouchEnabled() {
486 // Based on the definition of chrome::kEnableTouchIcon.
487 #if defined(OS_ANDROID)
488 return true;
489 #else
490 return false;
491 #endif
494 WebDragData DropDataToWebDragData(const DropData& drop_data) {
495 std::vector<WebDragData::Item> item_list;
497 // These fields are currently unused when dragging into WebKit.
498 DCHECK(drop_data.download_metadata.empty());
499 DCHECK(drop_data.file_contents.empty());
500 DCHECK(drop_data.file_description_filename.empty());
502 if (!drop_data.text.is_null()) {
503 WebDragData::Item item;
504 item.storageType = WebDragData::Item::StorageTypeString;
505 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeText);
506 item.stringData = drop_data.text.string();
507 item_list.push_back(item);
510 // TODO(dcheng): Do we need to distinguish between null and empty URLs? Is it
511 // meaningful to write an empty URL to the clipboard?
512 if (!drop_data.url.is_empty()) {
513 WebDragData::Item item;
514 item.storageType = WebDragData::Item::StorageTypeString;
515 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeURIList);
516 item.stringData = WebString::fromUTF8(drop_data.url.spec());
517 item.title = drop_data.url_title;
518 item_list.push_back(item);
521 if (!drop_data.html.is_null()) {
522 WebDragData::Item item;
523 item.storageType = WebDragData::Item::StorageTypeString;
524 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeHTML);
525 item.stringData = drop_data.html.string();
526 item.baseURL = drop_data.html_base_url;
527 item_list.push_back(item);
530 for (std::vector<ui::FileInfo>::const_iterator it =
531 drop_data.filenames.begin();
532 it != drop_data.filenames.end();
533 ++it) {
534 WebDragData::Item item;
535 item.storageType = WebDragData::Item::StorageTypeFilename;
536 item.filenameData = it->path.AsUTF16Unsafe();
537 item.displayNameData = it->display_name.AsUTF16Unsafe();
538 item_list.push_back(item);
541 for (std::vector<DropData::FileSystemFileInfo>::const_iterator it =
542 drop_data.file_system_files.begin();
543 it != drop_data.file_system_files.end();
544 ++it) {
545 WebDragData::Item item;
546 item.storageType = WebDragData::Item::StorageTypeFileSystemFile;
547 item.fileSystemURL = it->url;
548 item.fileSystemFileSize = it->size;
549 item_list.push_back(item);
552 for (std::map<base::string16, base::string16>::const_iterator it =
553 drop_data.custom_data.begin();
554 it != drop_data.custom_data.end();
555 ++it) {
556 WebDragData::Item item;
557 item.storageType = WebDragData::Item::StorageTypeString;
558 item.stringType = it->first;
559 item.stringData = it->second;
560 item_list.push_back(item);
563 WebDragData result;
564 result.initialize();
565 result.setItems(item_list);
566 result.setFilesystemId(drop_data.filesystem_id);
567 return result;
570 typedef void (*SetFontFamilyWrapper)(blink::WebSettings*,
571 const base::string16&,
572 UScriptCode);
574 void SetStandardFontFamilyWrapper(WebSettings* settings,
575 const base::string16& font,
576 UScriptCode script) {
577 settings->setStandardFontFamily(font, script);
580 void SetFixedFontFamilyWrapper(WebSettings* settings,
581 const base::string16& font,
582 UScriptCode script) {
583 settings->setFixedFontFamily(font, script);
586 void SetSerifFontFamilyWrapper(WebSettings* settings,
587 const base::string16& font,
588 UScriptCode script) {
589 settings->setSerifFontFamily(font, script);
592 void SetSansSerifFontFamilyWrapper(WebSettings* settings,
593 const base::string16& font,
594 UScriptCode script) {
595 settings->setSansSerifFontFamily(font, script);
598 void SetCursiveFontFamilyWrapper(WebSettings* settings,
599 const base::string16& font,
600 UScriptCode script) {
601 settings->setCursiveFontFamily(font, script);
604 void SetFantasyFontFamilyWrapper(WebSettings* settings,
605 const base::string16& font,
606 UScriptCode script) {
607 settings->setFantasyFontFamily(font, script);
610 void SetPictographFontFamilyWrapper(WebSettings* settings,
611 const base::string16& font,
612 UScriptCode script) {
613 settings->setPictographFontFamily(font, script);
616 // If |scriptCode| is a member of a family of "similar" script codes, returns
617 // the script code in that family that is used by WebKit for font selection
618 // purposes. For example, USCRIPT_KATAKANA_OR_HIRAGANA and USCRIPT_JAPANESE are
619 // considered equivalent for the purposes of font selection. WebKit uses the
620 // script code USCRIPT_KATAKANA_OR_HIRAGANA. So, if |scriptCode| is
621 // USCRIPT_JAPANESE, the function returns USCRIPT_KATAKANA_OR_HIRAGANA. WebKit
622 // uses different scripts than the ones in Chrome pref names because the version
623 // of ICU included on certain ports does not have some of the newer scripts. If
624 // |scriptCode| is not a member of such a family, returns |scriptCode|.
625 UScriptCode GetScriptForWebSettings(UScriptCode scriptCode) {
626 switch (scriptCode) {
627 case USCRIPT_HIRAGANA:
628 case USCRIPT_KATAKANA:
629 case USCRIPT_JAPANESE:
630 return USCRIPT_KATAKANA_OR_HIRAGANA;
631 case USCRIPT_KOREAN:
632 return USCRIPT_HANGUL;
633 default:
634 return scriptCode;
638 void ApplyFontsFromMap(const ScriptFontFamilyMap& map,
639 SetFontFamilyWrapper setter,
640 WebSettings* settings) {
641 for (ScriptFontFamilyMap::const_iterator it = map.begin(); it != map.end();
642 ++it) {
643 int32 script = u_getPropertyValueEnum(UCHAR_SCRIPT, (it->first).c_str());
644 if (script >= 0 && script < USCRIPT_CODE_LIMIT) {
645 UScriptCode code = static_cast<UScriptCode>(script);
646 (*setter)(settings, it->second, GetScriptForWebSettings(code));
651 } // namespace
653 RenderViewImpl::RenderViewImpl(RenderViewImplParams* params)
654 : RenderWidget(blink::WebPopupTypeNone,
655 params->screen_info,
656 params->swapped_out,
657 params->hidden,
658 params->never_visible),
659 webkit_preferences_(params->webkit_prefs),
660 send_content_state_immediately_(false),
661 enabled_bindings_(0),
662 send_preferred_size_changes_(false),
663 navigation_gesture_(NavigationGestureUnknown),
664 opened_by_user_gesture_(true),
665 opener_suppressed_(false),
666 suppress_dialogs_until_swap_out_(false),
667 page_id_(-1),
668 last_page_id_sent_to_browser_(-1),
669 next_page_id_(params->next_page_id),
670 history_list_offset_(-1),
671 history_list_length_(0),
672 frames_in_progress_(0),
673 target_url_status_(TARGET_NONE),
674 uses_temporary_zoom_level_(false),
675 #if defined(OS_ANDROID)
676 top_controls_constraints_(cc::BOTH),
677 #endif
678 has_scrolled_focused_editable_node_into_rect_(false),
679 speech_recognition_dispatcher_(NULL),
680 browser_plugin_manager_(NULL),
681 devtools_agent_(NULL),
682 mouse_lock_dispatcher_(NULL),
683 #if defined(OS_ANDROID)
684 expected_content_intent_id_(0),
685 #endif
686 #if defined(OS_WIN)
687 focused_plugin_id_(-1),
688 #endif
689 #if defined(ENABLE_PLUGINS)
690 plugin_find_handler_(NULL),
691 focused_pepper_plugin_(NULL),
692 pepper_last_mouse_event_target_(NULL),
693 #endif
694 enumeration_completion_id_(0),
695 session_storage_namespace_id_(params->session_storage_namespace_id),
696 next_snapshot_id_(0) {
699 void RenderViewImpl::Initialize(RenderViewImplParams* params) {
700 routing_id_ = params->routing_id;
701 surface_id_ = params->surface_id;
702 if (params->opener_id != MSG_ROUTING_NONE && params->is_renderer_created)
703 opener_id_ = params->opener_id;
705 // Ensure we start with a valid next_page_id_ from the browser.
706 DCHECK_GE(next_page_id_, 0);
708 main_render_frame_.reset(RenderFrameImpl::Create(
709 this, params->main_frame_routing_id));
710 // The main frame WebLocalFrame object is closed by
711 // RenderFrameImpl::frameDetached().
712 WebLocalFrame* web_frame = WebLocalFrame::create(main_render_frame_.get());
713 main_render_frame_->SetWebFrame(web_frame);
715 webwidget_ = WebView::create(this);
716 webwidget_mouse_lock_target_.reset(new WebWidgetLockTarget(webwidget_));
718 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
720 if (command_line.HasSwitch(switches::kStatsCollectionController))
721 stats_collection_observer_.reset(new StatsCollectionObserver(this));
723 #if defined(OS_ANDROID)
724 const std::string region_code =
725 command_line.HasSwitch(switches::kNetworkCountryIso)
726 ? command_line.GetSwitchValueASCII(switches::kNetworkCountryIso)
727 : net::android::GetTelephonyNetworkCountryIso();
728 content_detectors_.push_back(linked_ptr<ContentDetector>(
729 new AddressDetector()));
730 content_detectors_.push_back(linked_ptr<ContentDetector>(
731 new PhoneNumberDetector(region_code)));
732 content_detectors_.push_back(linked_ptr<ContentDetector>(
733 new EmailDetector()));
734 #endif
736 RenderThread::Get()->AddRoute(routing_id_, this);
737 // Take a reference on behalf of the RenderThread. This will be balanced
738 // when we receive ViewMsg_ClosePage.
739 AddRef();
740 if (RenderThreadImpl::current()) {
741 RenderThreadImpl::current()->WidgetCreated();
742 if (is_hidden_)
743 RenderThreadImpl::current()->WidgetHidden();
746 // If this is a popup, we must wait for the CreatingNew_ACK message before
747 // completing initialization. Otherwise, we can finish it now.
748 if (opener_id_ == MSG_ROUTING_NONE) {
749 did_show_ = true;
750 CompleteInit();
753 g_view_map.Get().insert(std::make_pair(webview(), this));
754 g_routing_id_view_map.Get().insert(std::make_pair(routing_id_, this));
755 webview()->setDeviceScaleFactor(device_scale_factor_);
756 webview()->settings()->setPreferCompositingToLCDTextEnabled(
757 PreferCompositingToLCDText(device_scale_factor_));
758 webview()->settings()->setAcceleratedCompositingForTransitionEnabled(
759 ShouldUseTransitionCompositing(device_scale_factor_));
760 webview()->settings()->setThreadedScrollingEnabled(
761 !command_line.HasSwitch(switches::kDisableThreadedScrolling));
763 ApplyWebPreferences(webkit_preferences_, webview());
765 webview()->settings()->setAllowConnectingInsecureWebSocket(
766 command_line.HasSwitch(switches::kAllowInsecureWebSocketFromHttpsOrigin));
768 RenderFrameProxy* proxy = NULL;
769 if (params->proxy_routing_id != MSG_ROUTING_NONE) {
770 CHECK(params->swapped_out);
771 proxy = RenderFrameProxy::CreateProxyToReplaceFrame(
772 main_render_frame_.get(), params->proxy_routing_id);
773 main_render_frame_->set_render_frame_proxy(proxy);
776 // In --site-per-process, just use the WebRemoteFrame as the main frame.
777 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess) &&
778 proxy) {
779 webview()->setMainFrame(proxy->web_frame());
780 } else {
781 webview()->setMainFrame(main_render_frame_->GetWebFrame());
783 main_render_frame_->Initialize();
785 if (switches::IsTouchDragDropEnabled())
786 webview()->settings()->setTouchDragDropEnabled(true);
788 if (switches::IsTouchEditingEnabled())
789 webview()->settings()->setTouchEditingEnabled(true);
791 if (!params->frame_name.empty())
792 webview()->mainFrame()->setName(params->frame_name);
794 // TODO(davidben): Move this state from Blink into content.
795 if (params->window_was_created_with_opener)
796 webview()->setOpenedByDOM();
798 OnSetRendererPrefs(params->renderer_prefs);
800 new MHTMLGenerator(this);
801 #if defined(OS_MACOSX)
802 new TextInputClientObserver(this);
803 #endif // defined(OS_MACOSX)
805 // The next group of objects all implement RenderViewObserver, so are deleted
806 // along with the RenderView automatically.
807 devtools_agent_ = new DevToolsAgent(this);
808 if (RenderWidgetCompositor* rwc = compositor()) {
809 webview()->devToolsAgent()->setLayerTreeId(rwc->GetLayerTreeId());
811 mouse_lock_dispatcher_ = new RenderViewMouseLockDispatcher(this);
813 history_controller_.reset(new HistoryController(this));
815 new IdleUserDetector(this);
817 if (command_line.HasSwitch(switches::kDomAutomationController))
818 enabled_bindings_ |= BINDINGS_POLICY_DOM_AUTOMATION;
819 if (command_line.HasSwitch(switches::kStatsCollectionController))
820 enabled_bindings_ |= BINDINGS_POLICY_STATS_COLLECTION;
822 ProcessViewLayoutFlags(command_line);
824 GetContentClient()->renderer()->RenderViewCreated(this);
826 // If we have an opener_id but we weren't created by a renderer, then
827 // it's the browser asking us to set our opener to another RenderView.
828 if (params->opener_id != MSG_ROUTING_NONE && !params->is_renderer_created) {
829 RenderViewImpl* opener_view = FromRoutingID(params->opener_id);
830 if (opener_view)
831 webview()->mainFrame()->setOpener(opener_view->webview()->mainFrame());
834 // If we are initially swapped out, navigate to kSwappedOutURL.
835 // This ensures we are in a unique origin that others cannot script.
836 if (is_swapped_out_ && webview()->mainFrame()->isWebLocalFrame())
837 NavigateToSwappedOutURL(webview()->mainFrame());
840 RenderViewImpl::~RenderViewImpl() {
841 for (BitmapMap::iterator it = disambiguation_bitmaps_.begin();
842 it != disambiguation_bitmaps_.end();
843 ++it)
844 delete it->second;
845 history_page_ids_.clear();
847 base::debug::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_);
849 // If file chooser is still waiting for answer, dispatch empty answer.
850 while (!file_chooser_completions_.empty()) {
851 if (file_chooser_completions_.front()->completion) {
852 file_chooser_completions_.front()->completion->didChooseFile(
853 WebVector<WebString>());
855 file_chooser_completions_.pop_front();
858 #if defined(OS_ANDROID)
859 // The date/time picker client is both a scoped_ptr member of this class and
860 // a RenderViewObserver. Reset it to prevent double deletion.
861 date_time_picker_client_.reset();
862 #endif
864 #ifndef NDEBUG
865 // Make sure we are no longer referenced by the ViewMap or RoutingIDViewMap.
866 ViewMap* views = g_view_map.Pointer();
867 for (ViewMap::iterator it = views->begin(); it != views->end(); ++it)
868 DCHECK_NE(this, it->second) << "Failed to call Close?";
869 RoutingIDViewMap* routing_id_views = g_routing_id_view_map.Pointer();
870 for (RoutingIDViewMap::iterator it = routing_id_views->begin();
871 it != routing_id_views->end(); ++it)
872 DCHECK_NE(this, it->second) << "Failed to call Close?";
873 #endif
875 FOR_EACH_OBSERVER(RenderViewObserver, observers_, RenderViewGone());
876 FOR_EACH_OBSERVER(RenderViewObserver, observers_, OnDestruct());
879 /*static*/
880 RenderViewImpl* RenderViewImpl::FromWebView(WebView* webview) {
881 ViewMap* views = g_view_map.Pointer();
882 ViewMap::iterator it = views->find(webview);
883 return it == views->end() ? NULL : it->second;
886 /*static*/
887 RenderView* RenderView::FromWebView(blink::WebView* webview) {
888 return RenderViewImpl::FromWebView(webview);
891 /*static*/
892 RenderViewImpl* RenderViewImpl::FromRoutingID(int32 routing_id) {
893 RoutingIDViewMap* views = g_routing_id_view_map.Pointer();
894 RoutingIDViewMap::iterator it = views->find(routing_id);
895 return it == views->end() ? NULL : it->second;
898 /*static*/
899 RenderView* RenderView::FromRoutingID(int routing_id) {
900 return RenderViewImpl::FromRoutingID(routing_id);
903 /* static */
904 size_t RenderViewImpl::GetRenderViewCount() {
905 return g_view_map.Get().size();
908 /*static*/
909 void RenderView::ForEach(RenderViewVisitor* visitor) {
910 ViewMap* views = g_view_map.Pointer();
911 for (ViewMap::iterator it = views->begin(); it != views->end(); ++it) {
912 if (!visitor->Visit(it->second))
913 return;
917 /*static*/
918 void RenderView::ApplyWebPreferences(const WebPreferences& prefs,
919 WebView* web_view) {
920 WebSettings* settings = web_view->settings();
921 ApplyFontsFromMap(prefs.standard_font_family_map,
922 SetStandardFontFamilyWrapper, settings);
923 ApplyFontsFromMap(prefs.fixed_font_family_map,
924 SetFixedFontFamilyWrapper, settings);
925 ApplyFontsFromMap(prefs.serif_font_family_map,
926 SetSerifFontFamilyWrapper, settings);
927 ApplyFontsFromMap(prefs.sans_serif_font_family_map,
928 SetSansSerifFontFamilyWrapper, settings);
929 ApplyFontsFromMap(prefs.cursive_font_family_map,
930 SetCursiveFontFamilyWrapper, settings);
931 ApplyFontsFromMap(prefs.fantasy_font_family_map,
932 SetFantasyFontFamilyWrapper, settings);
933 ApplyFontsFromMap(prefs.pictograph_font_family_map,
934 SetPictographFontFamilyWrapper, settings);
935 settings->setDefaultFontSize(prefs.default_font_size);
936 settings->setDefaultFixedFontSize(prefs.default_fixed_font_size);
937 settings->setMinimumFontSize(prefs.minimum_font_size);
938 settings->setMinimumLogicalFontSize(prefs.minimum_logical_font_size);
939 settings->setDefaultTextEncodingName(
940 base::ASCIIToUTF16(prefs.default_encoding));
941 settings->setJavaScriptEnabled(prefs.javascript_enabled);
942 settings->setWebSecurityEnabled(prefs.web_security_enabled);
943 settings->setJavaScriptCanOpenWindowsAutomatically(
944 prefs.javascript_can_open_windows_automatically);
945 settings->setLoadsImagesAutomatically(prefs.loads_images_automatically);
946 settings->setImagesEnabled(prefs.images_enabled);
947 settings->setPluginsEnabled(prefs.plugins_enabled);
948 settings->setDOMPasteAllowed(prefs.dom_paste_enabled);
949 settings->setShrinksStandaloneImagesToFit(
950 prefs.shrinks_standalone_images_to_fit);
951 settings->setUsesEncodingDetector(prefs.uses_universal_detector);
952 settings->setTextAreasAreResizable(prefs.text_areas_are_resizable);
953 settings->setAllowScriptsToCloseWindows(prefs.allow_scripts_to_close_windows);
954 settings->setDownloadableBinaryFontsEnabled(prefs.remote_fonts_enabled);
955 settings->setJavaScriptCanAccessClipboard(
956 prefs.javascript_can_access_clipboard);
957 WebRuntimeFeatures::enableXSLT(prefs.xslt_enabled);
958 settings->setXSSAuditorEnabled(prefs.xss_auditor_enabled);
959 settings->setDNSPrefetchingEnabled(prefs.dns_prefetching_enabled);
960 settings->setLocalStorageEnabled(prefs.local_storage_enabled);
961 settings->setSyncXHRInDocumentsEnabled(prefs.sync_xhr_in_documents_enabled);
962 WebRuntimeFeatures::enableDatabase(prefs.databases_enabled);
963 settings->setOfflineWebApplicationCacheEnabled(
964 prefs.application_cache_enabled);
965 settings->setCaretBrowsingEnabled(prefs.caret_browsing_enabled);
966 settings->setHyperlinkAuditingEnabled(prefs.hyperlink_auditing_enabled);
967 settings->setCookieEnabled(prefs.cookie_enabled);
968 settings->setNavigateOnDragDrop(prefs.navigate_on_drag_drop);
970 settings->setJavaEnabled(prefs.java_enabled);
972 // By default, allow_universal_access_from_file_urls is set to false and thus
973 // we mitigate attacks from local HTML files by not granting file:// URLs
974 // universal access. Only test shell will enable this.
975 settings->setAllowUniversalAccessFromFileURLs(
976 prefs.allow_universal_access_from_file_urls);
977 settings->setAllowFileAccessFromFileURLs(
978 prefs.allow_file_access_from_file_urls);
980 // Enable the web audio API if requested on the command line.
981 settings->setWebAudioEnabled(prefs.webaudio_enabled);
983 // Enable experimental WebGL support if requested on command line
984 // and support is compiled in.
985 settings->setExperimentalWebGLEnabled(prefs.experimental_webgl_enabled);
987 // Disable GL multisampling if requested on command line.
988 settings->setOpenGLMultisamplingEnabled(prefs.gl_multisampling_enabled);
990 // Enable WebGL errors to the JS console if requested.
991 settings->setWebGLErrorsToConsoleEnabled(
992 prefs.webgl_errors_to_console_enabled);
994 // Uses the mock theme engine for scrollbars.
995 settings->setMockScrollbarsEnabled(prefs.mock_scrollbars_enabled);
997 settings->setLayerSquashingEnabled(prefs.layer_squashing_enabled);
999 // Enable gpu-accelerated 2d canvas if requested on the command line.
1000 settings->setAccelerated2dCanvasEnabled(prefs.accelerated_2d_canvas_enabled);
1002 settings->setMinimumAccelerated2dCanvasSize(
1003 prefs.minimum_accelerated_2d_canvas_size);
1005 // Disable antialiasing for 2d canvas if requested on the command line.
1006 settings->setAntialiased2dCanvasEnabled(
1007 !prefs.antialiased_2d_canvas_disabled);
1009 // Set MSAA sample count for 2d canvas if requested on the command line (or
1010 // default value if not).
1011 settings->setAccelerated2dCanvasMSAASampleCount(
1012 prefs.accelerated_2d_canvas_msaa_sample_count);
1014 // Enable deferred filter rendering if requested on the command line.
1015 settings->setDeferredFiltersEnabled(prefs.deferred_filters_enabled);
1017 // Enable container culling if requested on the command line.
1018 settings->setContainerCullingEnabled(prefs.container_culling_enabled);
1020 WebRuntimeFeatures::enableTextBlobs(prefs.text_blobs_enabled);
1022 settings->setAsynchronousSpellCheckingEnabled(
1023 prefs.asynchronous_spell_checking_enabled);
1024 settings->setUnifiedTextCheckerEnabled(prefs.unified_textchecker_enabled);
1026 // Tabs to link is not part of the settings. WebCore calls
1027 // ChromeClient::tabsToLinks which is part of the glue code.
1028 web_view->setTabsToLinks(prefs.tabs_to_links);
1030 settings->setAllowDisplayOfInsecureContent(
1031 prefs.allow_displaying_insecure_content);
1032 settings->setAllowRunningOfInsecureContent(
1033 prefs.allow_running_insecure_content);
1034 settings->setPasswordEchoEnabled(prefs.password_echo_enabled);
1035 settings->setShouldPrintBackgrounds(prefs.should_print_backgrounds);
1036 settings->setShouldClearDocumentBackground(
1037 prefs.should_clear_document_background);
1038 settings->setEnableScrollAnimator(prefs.enable_scroll_animator);
1040 settings->setRegionBasedColumnsEnabled(prefs.region_based_columns_enabled);
1042 WebRuntimeFeatures::enableTouch(prefs.touch_enabled);
1043 settings->setMaxTouchPoints(prefs.pointer_events_max_touch_points);
1044 settings->setDeviceSupportsTouch(prefs.device_supports_touch);
1045 settings->setDeviceSupportsMouse(prefs.device_supports_mouse);
1046 settings->setEnableTouchAdjustment(prefs.touch_adjustment_enabled);
1048 settings->setDeferredImageDecodingEnabled(
1049 prefs.deferred_image_decoding_enabled);
1050 settings->setShouldRespectImageOrientation(
1051 prefs.should_respect_image_orientation);
1053 settings->setUnsafePluginPastingEnabled(false);
1054 settings->setEditingBehavior(
1055 static_cast<WebSettings::EditingBehavior>(prefs.editing_behavior));
1057 settings->setSupportsMultipleWindows(prefs.supports_multiple_windows);
1059 settings->setViewportEnabled(prefs.viewport_enabled);
1060 settings->setLoadWithOverviewMode(prefs.initialize_at_minimum_page_scale);
1061 settings->setViewportMetaEnabled(prefs.viewport_meta_enabled);
1062 settings->setMainFrameResizesAreOrientationChanges(
1063 prefs.main_frame_resizes_are_orientation_changes);
1065 settings->setSmartInsertDeleteEnabled(prefs.smart_insert_delete_enabled);
1067 settings->setSpatialNavigationEnabled(prefs.spatial_navigation_enabled);
1069 settings->setSelectionIncludesAltImageText(true);
1071 settings->setV8CacheOptions(
1072 static_cast<WebSettings::V8CacheOptions>(prefs.v8_cache_options));
1074 settings->setV8ScriptStreamingEnabled(prefs.v8_script_streaming_enabled);
1076 #if defined(OS_ANDROID)
1077 settings->setAllowCustomScrollbarInMainFrame(false);
1078 settings->setTextAutosizingEnabled(prefs.text_autosizing_enabled);
1079 settings->setAccessibilityFontScaleFactor(prefs.font_scale_factor);
1080 settings->setDeviceScaleAdjustment(prefs.device_scale_adjustment);
1081 settings->setDisallowFullscreenForNonMediaElements(
1082 prefs.disallow_fullscreen_for_non_media_elements);
1083 settings->setFullscreenSupported(prefs.fullscreen_supported);
1084 web_view->setIgnoreViewportTagScaleLimits(prefs.force_enable_zoom);
1085 settings->setAutoZoomFocusedNodeToLegibleScale(true);
1086 settings->setDoubleTapToZoomEnabled(prefs.double_tap_to_zoom_enabled);
1087 settings->setMediaControlsOverlayPlayButtonEnabled(true);
1088 settings->setMediaPlaybackRequiresUserGesture(
1089 prefs.user_gesture_required_for_media_playback);
1090 settings->setDefaultVideoPosterURL(
1091 base::ASCIIToUTF16(prefs.default_video_poster_url.spec()));
1092 settings->setSupportDeprecatedTargetDensityDPI(
1093 prefs.support_deprecated_target_density_dpi);
1094 settings->setUseLegacyBackgroundSizeShorthandBehavior(
1095 prefs.use_legacy_background_size_shorthand_behavior);
1096 settings->setWideViewportQuirkEnabled(prefs.wide_viewport_quirk);
1097 settings->setUseWideViewport(prefs.use_wide_viewport);
1098 settings->setForceZeroLayoutHeight(prefs.force_zero_layout_height);
1099 settings->setViewportMetaLayoutSizeQuirk(
1100 prefs.viewport_meta_layout_size_quirk);
1101 settings->setViewportMetaMergeContentQuirk(
1102 prefs.viewport_meta_merge_content_quirk);
1103 settings->setViewportMetaNonUserScalableQuirk(
1104 prefs.viewport_meta_non_user_scalable_quirk);
1105 settings->setViewportMetaZeroValuesQuirk(
1106 prefs.viewport_meta_zero_values_quirk);
1107 settings->setClobberUserAgentInitialScaleQuirk(
1108 prefs.clobber_user_agent_initial_scale_quirk);
1109 settings->setIgnoreMainFrameOverflowHiddenQuirk(
1110 prefs.ignore_main_frame_overflow_hidden_quirk);
1111 settings->setReportScreenSizeInPhysicalPixelsQuirk(
1112 prefs.report_screen_size_in_physical_pixels_quirk);
1113 settings->setMainFrameClipsContent(false);
1114 settings->setShrinksStandaloneImagesToFit(false);
1115 settings->setShrinksViewportContentToFit(true);
1116 #endif
1118 WebNetworkStateNotifier::setOnLine(prefs.is_online);
1119 WebNetworkStateNotifier::setWebConnectionType(
1120 NetConnectionTypeToWebConnectionType(prefs.connection_type));
1121 settings->setPinchVirtualViewportEnabled(
1122 prefs.pinch_virtual_viewport_enabled);
1124 settings->setPinchOverlayScrollbarThickness(
1125 prefs.pinch_overlay_scrollbar_thickness);
1126 settings->setUseSolidColorScrollbars(prefs.use_solid_color_scrollbars);
1129 /*static*/
1130 RenderViewImpl* RenderViewImpl::Create(
1131 int32 opener_id,
1132 bool window_was_created_with_opener,
1133 const RendererPreferences& renderer_prefs,
1134 const WebPreferences& webkit_prefs,
1135 int32 routing_id,
1136 int32 main_frame_routing_id,
1137 int32 surface_id,
1138 int64 session_storage_namespace_id,
1139 const base::string16& frame_name,
1140 bool is_renderer_created,
1141 bool swapped_out,
1142 int32 proxy_routing_id,
1143 bool hidden,
1144 bool never_visible,
1145 int32 next_page_id,
1146 const blink::WebScreenInfo& screen_info) {
1147 DCHECK(routing_id != MSG_ROUTING_NONE);
1148 RenderViewImplParams params(opener_id,
1149 window_was_created_with_opener,
1150 renderer_prefs,
1151 webkit_prefs,
1152 routing_id,
1153 main_frame_routing_id,
1154 surface_id,
1155 session_storage_namespace_id,
1156 frame_name,
1157 is_renderer_created,
1158 swapped_out,
1159 proxy_routing_id,
1160 hidden,
1161 never_visible,
1162 next_page_id,
1163 screen_info);
1164 RenderViewImpl* render_view = NULL;
1165 if (g_create_render_view_impl)
1166 render_view = g_create_render_view_impl(&params);
1167 else
1168 render_view = new RenderViewImpl(&params);
1170 render_view->Initialize(&params);
1171 return render_view;
1174 // static
1175 void RenderViewImpl::InstallCreateHook(
1176 RenderViewImpl* (*create_render_view_impl)(RenderViewImplParams*)) {
1177 CHECK(!g_create_render_view_impl);
1178 g_create_render_view_impl = create_render_view_impl;
1181 void RenderViewImpl::AddObserver(RenderViewObserver* observer) {
1182 observers_.AddObserver(observer);
1185 void RenderViewImpl::RemoveObserver(RenderViewObserver* observer) {
1186 observer->RenderViewGone();
1187 observers_.RemoveObserver(observer);
1190 blink::WebView* RenderViewImpl::webview() const {
1191 return static_cast<blink::WebView*>(webwidget());
1194 #if defined(ENABLE_PLUGINS)
1195 void RenderViewImpl::PepperInstanceCreated(
1196 PepperPluginInstanceImpl* instance) {
1197 active_pepper_instances_.insert(instance);
1200 void RenderViewImpl::PepperInstanceDeleted(
1201 PepperPluginInstanceImpl* instance) {
1202 active_pepper_instances_.erase(instance);
1204 if (pepper_last_mouse_event_target_ == instance)
1205 pepper_last_mouse_event_target_ = NULL;
1206 if (focused_pepper_plugin_ == instance)
1207 PepperFocusChanged(instance, false);
1210 void RenderViewImpl::PepperFocusChanged(PepperPluginInstanceImpl* instance,
1211 bool focused) {
1212 if (focused)
1213 focused_pepper_plugin_ = instance;
1214 else if (focused_pepper_plugin_ == instance)
1215 focused_pepper_plugin_ = NULL;
1217 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
1218 UpdateSelectionBounds();
1221 void RenderViewImpl::RegisterPluginDelegate(WebPluginDelegateProxy* delegate) {
1222 plugin_delegates_.insert(delegate);
1223 // If the renderer is visible, set initial visibility and focus state.
1224 if (!is_hidden()) {
1225 #if defined(OS_MACOSX)
1226 delegate->SetContainerVisibility(true);
1227 if (webview() && webview()->isActive())
1228 delegate->SetWindowFocus(true);
1229 #endif
1231 // Plugins start assuming the content has focus (so that they work in
1232 // environments where RenderView isn't hosting them), so we always have to
1233 // set the initial state. See webplugin_delegate_impl.h for details.
1234 delegate->SetContentAreaFocus(has_focus());
1237 void RenderViewImpl::UnregisterPluginDelegate(
1238 WebPluginDelegateProxy* delegate) {
1239 plugin_delegates_.erase(delegate);
1242 #if defined(OS_WIN)
1243 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1244 if (focused)
1245 focused_plugin_id_ = plugin_id;
1246 else
1247 focused_plugin_id_ = -1;
1249 #endif
1251 #if defined(OS_MACOSX)
1252 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1253 Send(new ViewHostMsg_PluginFocusChanged(routing_id(), focused, plugin_id));
1256 void RenderViewImpl::OnGetRenderedText() {
1257 if (!webview())
1258 return;
1259 // Get rendered text from WebLocalFrame.
1260 // TODO: Currently IPC truncates any data that has a
1261 // size > kMaximumMessageSize. May be split the text into smaller chunks and
1262 // send back using multiple IPC. See http://crbug.com/393444.
1263 static const size_t kMaximumMessageSize = 8 * 1024 * 1024;
1264 std::string text = webview()->mainFrame()->contentAsText(
1265 kMaximumMessageSize).utf8();
1267 Send(new ViewMsg_GetRenderedTextCompleted(routing_id(), text));
1270 void RenderViewImpl::StartPluginIme() {
1271 IPC::Message* msg = new ViewHostMsg_StartPluginIme(routing_id());
1272 // This message can be sent during event-handling, and needs to be delivered
1273 // within that context.
1274 msg->set_unblock(true);
1275 Send(msg);
1277 #endif // defined(OS_MACOSX)
1279 #endif // ENABLE_PLUGINS
1281 void RenderViewImpl::TransferActiveWheelFlingAnimation(
1282 const blink::WebActiveWheelFlingParameters& params) {
1283 if (webview())
1284 webview()->transferActiveWheelFlingAnimation(params);
1287 bool RenderViewImpl::HasIMETextFocus() {
1288 return GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE;
1291 bool RenderViewImpl::OnMessageReceived(const IPC::Message& message) {
1292 WebFrame* main_frame = webview() ? webview()->mainFrame() : NULL;
1293 if (main_frame && main_frame->isWebLocalFrame())
1294 GetContentClient()->SetActiveURL(main_frame->document().url());
1296 ObserverListBase<RenderViewObserver>::Iterator it(observers_);
1297 RenderViewObserver* observer;
1298 while ((observer = it.GetNext()) != NULL)
1299 if (observer->OnMessageReceived(message))
1300 return true;
1302 bool handled = true;
1303 IPC_BEGIN_MESSAGE_MAP(RenderViewImpl, message)
1304 IPC_MESSAGE_HANDLER(InputMsg_ExecuteEditCommand, OnExecuteEditCommand)
1305 IPC_MESSAGE_HANDLER(InputMsg_MoveCaret, OnMoveCaret)
1306 IPC_MESSAGE_HANDLER(InputMsg_ScrollFocusedEditableNodeIntoRect,
1307 OnScrollFocusedEditableNodeIntoRect)
1308 IPC_MESSAGE_HANDLER(InputMsg_SetEditCommandsForNextKeyEvent,
1309 OnSetEditCommandsForNextKeyEvent)
1310 IPC_MESSAGE_HANDLER(ViewMsg_CopyImageAt, OnCopyImageAt)
1311 IPC_MESSAGE_HANDLER(ViewMsg_SaveImageAt, OnSaveImageAt)
1312 IPC_MESSAGE_HANDLER(ViewMsg_Find, OnFind)
1313 IPC_MESSAGE_HANDLER(ViewMsg_StopFinding, OnStopFinding)
1314 IPC_MESSAGE_HANDLER(ViewMsg_Zoom, OnZoom)
1315 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForLoadingURL,
1316 OnSetZoomLevelForLoadingURL)
1317 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForView,
1318 OnSetZoomLevelForView)
1319 IPC_MESSAGE_HANDLER(ViewMsg_SetPageEncoding, OnSetPageEncoding)
1320 IPC_MESSAGE_HANDLER(ViewMsg_ResetPageEncodingToDefault,
1321 OnResetPageEncodingToDefault)
1322 IPC_MESSAGE_HANDLER(ViewMsg_PostMessageEvent, OnPostMessageEvent)
1323 IPC_MESSAGE_HANDLER(DragMsg_TargetDragEnter, OnDragTargetDragEnter)
1324 IPC_MESSAGE_HANDLER(DragMsg_TargetDragOver, OnDragTargetDragOver)
1325 IPC_MESSAGE_HANDLER(DragMsg_TargetDragLeave, OnDragTargetDragLeave)
1326 IPC_MESSAGE_HANDLER(DragMsg_TargetDrop, OnDragTargetDrop)
1327 IPC_MESSAGE_HANDLER(DragMsg_SourceEnded, OnDragSourceEnded)
1328 IPC_MESSAGE_HANDLER(DragMsg_SourceSystemDragEnded,
1329 OnDragSourceSystemDragEnded)
1330 IPC_MESSAGE_HANDLER(ViewMsg_AllowBindings, OnAllowBindings)
1331 IPC_MESSAGE_HANDLER(ViewMsg_SetInitialFocus, OnSetInitialFocus)
1332 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTargetURL_ACK, OnUpdateTargetURLAck)
1333 IPC_MESSAGE_HANDLER(ViewMsg_UpdateWebPreferences, OnUpdateWebPreferences)
1334 IPC_MESSAGE_HANDLER(ViewMsg_EnumerateDirectoryResponse,
1335 OnEnumerateDirectoryResponse)
1336 IPC_MESSAGE_HANDLER(ViewMsg_RunFileChooserResponse, OnFileChooserResponse)
1337 IPC_MESSAGE_HANDLER(ViewMsg_SuppressDialogsUntilSwapOut,
1338 OnSuppressDialogsUntilSwapOut)
1339 IPC_MESSAGE_HANDLER(ViewMsg_ClosePage, OnClosePage)
1340 IPC_MESSAGE_HANDLER(ViewMsg_ThemeChanged, OnThemeChanged)
1341 IPC_MESSAGE_HANDLER(ViewMsg_MoveOrResizeStarted, OnMoveOrResizeStarted)
1342 IPC_MESSAGE_HANDLER(ViewMsg_ClearFocusedElement, OnClearFocusedElement)
1343 IPC_MESSAGE_HANDLER(ViewMsg_SetBackgroundOpaque, OnSetBackgroundOpaque)
1344 IPC_MESSAGE_HANDLER(ViewMsg_EnablePreferredSizeChangedMode,
1345 OnEnablePreferredSizeChangedMode)
1346 IPC_MESSAGE_HANDLER(ViewMsg_EnableAutoResize, OnEnableAutoResize)
1347 IPC_MESSAGE_HANDLER(ViewMsg_DisableAutoResize, OnDisableAutoResize)
1348 IPC_MESSAGE_HANDLER(ViewMsg_DisableScrollbarsForSmallWindows,
1349 OnDisableScrollbarsForSmallWindows)
1350 IPC_MESSAGE_HANDLER(ViewMsg_SetRendererPrefs, OnSetRendererPrefs)
1351 IPC_MESSAGE_HANDLER(ViewMsg_MediaPlayerActionAt, OnMediaPlayerActionAt)
1352 IPC_MESSAGE_HANDLER(ViewMsg_PluginActionAt, OnPluginActionAt)
1353 IPC_MESSAGE_HANDLER(ViewMsg_SetActive, OnSetActive)
1354 IPC_MESSAGE_HANDLER(ViewMsg_GetAllSavableResourceLinksForCurrentPage,
1355 OnGetAllSavableResourceLinksForCurrentPage)
1356 IPC_MESSAGE_HANDLER(
1357 ViewMsg_GetSerializedHtmlDataForCurrentPageWithLocalLinks,
1358 OnGetSerializedHtmlDataForCurrentPageWithLocalLinks)
1359 IPC_MESSAGE_HANDLER(ViewMsg_ShowContextMenu, OnShowContextMenu)
1360 // TODO(viettrungluu): Move to a separate message filter.
1361 IPC_MESSAGE_HANDLER(ViewMsg_SetHistoryLengthAndPrune,
1362 OnSetHistoryLengthAndPrune)
1363 IPC_MESSAGE_HANDLER(ViewMsg_EnableViewSourceMode, OnEnableViewSourceMode)
1364 IPC_MESSAGE_HANDLER(ViewMsg_ReleaseDisambiguationPopupBitmap,
1365 OnReleaseDisambiguationPopupBitmap)
1366 IPC_MESSAGE_HANDLER(ViewMsg_WindowSnapshotCompleted,
1367 OnWindowSnapshotCompleted)
1368 IPC_MESSAGE_HANDLER(ViewMsg_ForceRedraw, OnForceRedraw)
1369 IPC_MESSAGE_HANDLER(ViewMsg_SelectWordAroundCaret, OnSelectWordAroundCaret)
1370 #if defined(OS_ANDROID)
1371 IPC_MESSAGE_HANDLER(InputMsg_ActivateNearestFindResult,
1372 OnActivateNearestFindResult)
1373 IPC_MESSAGE_HANDLER(ViewMsg_FindMatchRects, OnFindMatchRects)
1374 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTopControlsState,
1375 OnUpdateTopControlsState)
1376 IPC_MESSAGE_HANDLER(ViewMsg_ExtractSmartClipData, OnExtractSmartClipData)
1377 #elif defined(OS_MACOSX)
1378 IPC_MESSAGE_HANDLER(ViewMsg_GetRenderedText,
1379 OnGetRenderedText)
1380 IPC_MESSAGE_HANDLER(ViewMsg_PluginImeCompositionCompleted,
1381 OnPluginImeCompositionCompleted)
1382 IPC_MESSAGE_HANDLER(ViewMsg_SetInLiveResize, OnSetInLiveResize)
1383 IPC_MESSAGE_HANDLER(ViewMsg_SetWindowVisibility, OnSetWindowVisibility)
1384 IPC_MESSAGE_HANDLER(ViewMsg_WindowFrameChanged, OnWindowFrameChanged)
1385 #endif
1386 // Adding a new message? Add platform independent ones first, then put the
1387 // platform specific ones at the end.
1389 // Have the super handle all other messages.
1390 IPC_MESSAGE_UNHANDLED(handled = RenderWidget::OnMessageReceived(message))
1391 IPC_END_MESSAGE_MAP()
1393 return handled;
1396 void RenderViewImpl::OnSelectWordAroundCaret() {
1397 if (!webview())
1398 return;
1400 handling_input_event_ = true;
1401 webview()->focusedFrame()->selectWordAroundCaret();
1402 handling_input_event_ = false;
1405 bool RenderViewImpl::IsBackForwardToStaleEntry(const PageState& state,
1406 int pending_history_list_offset,
1407 int32 page_id,
1408 bool is_reload) {
1409 // Make sure this isn't a back/forward to an entry we have already cropped
1410 // or replaced from our history, before the browser knew about it. If so,
1411 // a new navigation has committed in the mean time, and we can ignore this.
1412 bool is_back_forward = !is_reload && state.IsValid();
1414 // Note: if the history_list_length_ is 0 for a back/forward, we must be
1415 // restoring from a previous session. We'll update our state in OnNavigate.
1416 if (!is_back_forward || history_list_length_ <= 0)
1417 return false;
1419 DCHECK_EQ(static_cast<int>(history_page_ids_.size()), history_list_length_);
1421 // Check for whether the forward history has been cropped due to a recent
1422 // navigation the browser didn't know about.
1423 if (pending_history_list_offset >= history_list_length_)
1424 return true;
1426 // Check for whether this entry has been replaced with a new one.
1427 int expected_page_id =
1428 history_page_ids_[pending_history_list_offset];
1429 if (expected_page_id > 0 && page_id != expected_page_id) {
1430 if (page_id < expected_page_id)
1431 return true;
1433 // Otherwise we've removed an earlier entry and should have shifted all
1434 // entries left. For now, it's ok to lazily update the list.
1435 // TODO(creis): Notify all live renderers when we remove entries from
1436 // the front of the list, so that we don't hit this case.
1437 history_page_ids_[pending_history_list_offset] = page_id;
1440 return false;
1443 void RenderViewImpl::OnCopyImageAt(int x, int y) {
1444 webview()->copyImageAt(WebPoint(x, y));
1447 void RenderViewImpl::OnSaveImageAt(int x, int y) {
1448 webview()->saveImageAt(WebPoint(x, y));
1451 void RenderViewImpl::OnUpdateTargetURLAck() {
1452 // Check if there is a targeturl waiting to be sent.
1453 if (target_url_status_ == TARGET_PENDING)
1454 Send(new ViewHostMsg_UpdateTargetURL(routing_id_, pending_target_url_));
1456 target_url_status_ = TARGET_NONE;
1459 void RenderViewImpl::OnExecuteEditCommand(const std::string& name,
1460 const std::string& value) {
1461 if (!webview() || !webview()->focusedFrame())
1462 return;
1464 webview()->focusedFrame()->executeCommand(
1465 WebString::fromUTF8(name), WebString::fromUTF8(value));
1468 void RenderViewImpl::OnMoveCaret(const gfx::Point& point) {
1469 if (!webview())
1470 return;
1472 Send(new ViewHostMsg_MoveCaret_ACK(routing_id_));
1474 webview()->focusedFrame()->moveCaretSelection(point);
1477 void RenderViewImpl::OnScrollFocusedEditableNodeIntoRect(
1478 const gfx::Rect& rect) {
1479 if (has_scrolled_focused_editable_node_into_rect_ &&
1480 rect == rect_for_scrolled_focused_editable_node_) {
1481 return;
1484 blink::WebElement element = GetFocusedElement();
1485 if (!element.isNull() && IsEditableNode(element)) {
1486 rect_for_scrolled_focused_editable_node_ = rect;
1487 has_scrolled_focused_editable_node_into_rect_ = true;
1488 webview()->scrollFocusedNodeIntoRect(rect);
1492 void RenderViewImpl::OnSetEditCommandsForNextKeyEvent(
1493 const EditCommands& edit_commands) {
1494 edit_commands_ = edit_commands;
1497 void RenderViewImpl::OnSetHistoryLengthAndPrune(int history_length,
1498 int32 minimum_page_id) {
1499 DCHECK_GE(history_length, 0);
1500 DCHECK(history_list_offset_ == history_list_length_ - 1);
1501 DCHECK_GE(minimum_page_id, -1);
1503 // Generate the new list.
1504 std::vector<int32> new_history_page_ids(history_length, -1);
1505 for (size_t i = 0; i < history_page_ids_.size(); ++i) {
1506 if (minimum_page_id >= 0 && history_page_ids_[i] < minimum_page_id)
1507 continue;
1508 new_history_page_ids.push_back(history_page_ids_[i]);
1510 new_history_page_ids.swap(history_page_ids_);
1512 // Update indexes.
1513 history_list_length_ = history_page_ids_.size();
1514 history_list_offset_ = history_list_length_ - 1;
1518 void RenderViewImpl::OnSetInitialFocus(bool reverse) {
1519 if (!webview())
1520 return;
1521 webview()->setInitialFocus(reverse);
1524 #if defined(OS_MACOSX)
1525 void RenderViewImpl::OnSetInLiveResize(bool in_live_resize) {
1526 if (!webview())
1527 return;
1528 if (in_live_resize)
1529 webview()->willStartLiveResize();
1530 else
1531 webview()->willEndLiveResize();
1533 #endif
1535 ///////////////////////////////////////////////////////////////////////////////
1537 // Sends the current history state to the browser so it will be saved before we
1538 // navigate to a new page.
1539 void RenderViewImpl::UpdateSessionHistory(WebFrame* frame) {
1540 // If we have a valid page ID at this point, then it corresponds to the page
1541 // we are navigating away from. Otherwise, this is the first navigation, so
1542 // there is no past session history to record.
1543 if (page_id_ == -1)
1544 return;
1545 SendUpdateState(history_controller_->GetCurrentEntry());
1548 void RenderViewImpl::SendUpdateState(HistoryEntry* entry) {
1549 if (!entry)
1550 return;
1552 // Don't send state updates for kSwappedOutURL.
1553 if (entry->root().urlString() == WebString::fromUTF8(kSwappedOutURL))
1554 return;
1556 Send(new ViewHostMsg_UpdateState(
1557 routing_id_, page_id_, HistoryEntryToPageState(entry)));
1560 bool RenderViewImpl::SendAndRunNestedMessageLoop(IPC::SyncMessage* message) {
1561 // Before WebKit asks us to show an alert (etc.), it takes care of doing the
1562 // equivalent of WebView::willEnterModalLoop. In the case of showModalDialog
1563 // it is particularly important that we do not call willEnterModalLoop as
1564 // that would defer resource loads for the dialog itself.
1565 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
1566 RenderThreadImpl::current()->DoNotNotifyWebKitOfModalLoop();
1568 message->EnableMessagePumping(); // Runs a nested message loop.
1569 return Send(message);
1572 void RenderViewImpl::GetWindowSnapshot(const WindowSnapshotCallback& callback) {
1573 int id = next_snapshot_id_++;
1574 pending_snapshots_.insert(std::make_pair(id, callback));
1575 ui::LatencyInfo latency_info;
1576 latency_info.AddLatencyNumber(ui::WINDOW_OLD_SNAPSHOT_FRAME_NUMBER_COMPONENT,
1578 id);
1579 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1580 if (RenderWidgetCompositor* rwc = compositor()) {
1581 latency_info_swap_promise_monitor =
1582 rwc->CreateLatencyInfoSwapPromiseMonitor(&latency_info).Pass();
1584 ScheduleCompositeWithForcedRedraw();
1587 void RenderViewImpl::OnForceRedraw(int id) {
1588 ui::LatencyInfo latency_info;
1589 if (id) {
1590 latency_info.AddLatencyNumber(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
1592 id);
1594 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1595 if (RenderWidgetCompositor* rwc = compositor()) {
1596 latency_info_swap_promise_monitor =
1597 rwc->CreateLatencyInfoSwapPromiseMonitor(&latency_info).Pass();
1599 ScheduleCompositeWithForcedRedraw();
1602 void RenderViewImpl::OnWindowSnapshotCompleted(const int snapshot_id,
1603 const gfx::Size& size, const std::vector<unsigned char>& png) {
1605 // Any pending snapshots with a lower ID than the one received are considered
1606 // to be implicitly complete, and returned the same snapshot data.
1607 PendingSnapshotMap::iterator it = pending_snapshots_.begin();
1608 while(it != pending_snapshots_.end()) {
1609 if (it->first <= snapshot_id) {
1610 it->second.Run(size, png);
1611 pending_snapshots_.erase(it++);
1612 } else {
1613 ++it;
1618 // blink::WebViewClient ------------------------------------------------------
1620 WebView* RenderViewImpl::createView(WebLocalFrame* creator,
1621 const WebURLRequest& request,
1622 const WebWindowFeatures& features,
1623 const WebString& frame_name,
1624 WebNavigationPolicy policy,
1625 bool suppress_opener) {
1626 ViewHostMsg_CreateWindow_Params params;
1627 params.opener_id = routing_id_;
1628 params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
1629 if (GetContentClient()->renderer()->AllowPopup())
1630 params.user_gesture = true;
1631 params.window_container_type = WindowFeaturesToContainerType(features);
1632 params.session_storage_namespace_id = session_storage_namespace_id_;
1633 if (frame_name != "_blank")
1634 params.frame_name = frame_name;
1635 params.opener_render_frame_id =
1636 RenderFrameImpl::FromWebFrame(creator)->GetRoutingID();
1637 params.opener_url = creator->document().url();
1638 params.opener_top_level_frame_url = creator->top()->document().url();
1639 GURL security_url(creator->document().securityOrigin().toString());
1640 if (!security_url.is_valid())
1641 security_url = GURL();
1642 params.opener_security_origin = security_url;
1643 params.opener_suppressed = suppress_opener;
1644 params.disposition = NavigationPolicyToDisposition(policy);
1645 if (!request.isNull()) {
1646 params.target_url = request.url();
1647 params.referrer = GetReferrerFromRequest(creator, request);
1649 params.features = features;
1651 for (size_t i = 0; i < features.additionalFeatures.size(); ++i)
1652 params.additional_features.push_back(features.additionalFeatures[i]);
1654 int32 routing_id = MSG_ROUTING_NONE;
1655 int32 main_frame_routing_id = MSG_ROUTING_NONE;
1656 int32 surface_id = 0;
1657 int64 cloned_session_storage_namespace_id = 0;
1659 RenderThread::Get()->Send(
1660 new ViewHostMsg_CreateWindow(params,
1661 &routing_id,
1662 &main_frame_routing_id,
1663 &surface_id,
1664 &cloned_session_storage_namespace_id));
1665 if (routing_id == MSG_ROUTING_NONE)
1666 return NULL;
1668 WebUserGestureIndicator::consumeUserGesture();
1670 // While this view may be a background extension page, it can spawn a visible
1671 // render view. So we just assume that the new one is not another background
1672 // page instead of passing on our own value.
1673 // TODO(vangelis): Can we tell if the new view will be a background page?
1674 bool never_visible = false;
1676 // The initial hidden state for the RenderViewImpl here has to match what the
1677 // browser will eventually decide for the given disposition. Since we have to
1678 // return from this call synchronously, we just have to make our best guess
1679 // and rely on the browser sending a WasHidden / WasShown message if it
1680 // disagrees.
1681 RenderViewImpl* view = RenderViewImpl::Create(
1682 routing_id_,
1683 true, // window_was_created_with_opener
1684 renderer_preferences_,
1685 webkit_preferences_,
1686 routing_id,
1687 main_frame_routing_id,
1688 surface_id,
1689 cloned_session_storage_namespace_id,
1690 base::string16(), // WebCore will take care of setting the correct name.
1691 true, // is_renderer_created
1692 false, // swapped_out
1693 MSG_ROUTING_NONE, // proxy_routing_id
1694 params.disposition == NEW_BACKGROUND_TAB, // hidden
1695 never_visible,
1696 1, // next_page_id
1697 screen_info_);
1698 view->opened_by_user_gesture_ = params.user_gesture;
1700 // Record whether the creator frame is trying to suppress the opener field.
1701 view->opener_suppressed_ = params.opener_suppressed;
1703 return view->webview();
1706 WebWidget* RenderViewImpl::createPopupMenu(blink::WebPopupType popup_type) {
1707 RenderWidget* widget =
1708 RenderWidget::Create(routing_id_, popup_type, screen_info_);
1709 if (!widget)
1710 return NULL;
1711 if (screen_metrics_emulator_) {
1712 widget->SetPopupOriginAdjustmentsForEmulation(
1713 screen_metrics_emulator_.get());
1715 return widget->webwidget();
1718 WebStorageNamespace* RenderViewImpl::createSessionStorageNamespace() {
1719 CHECK(session_storage_namespace_id_ != kInvalidSessionStorageNamespaceId);
1720 return new WebStorageNamespaceImpl(session_storage_namespace_id_);
1723 void RenderViewImpl::printPage(WebLocalFrame* frame) {
1724 FOR_EACH_OBSERVER(RenderViewObserver, observers_,
1725 PrintPage(frame, handling_input_event_));
1728 void RenderViewImpl::saveImageFromDataURL(const blink::WebString& data_url) {
1729 // Note: We should basically send GURL but we use size-limited string instead
1730 // in order to send a larger data url to save a image for <canvas> or <img>.
1731 if (data_url.length() < kMaxLengthOfDataURLString)
1732 Send(new ViewHostMsg_SaveImageFromDataURL(routing_id_, data_url.utf8()));
1735 bool RenderViewImpl::enumerateChosenDirectory(
1736 const WebString& path,
1737 WebFileChooserCompletion* chooser_completion) {
1738 int id = enumeration_completion_id_++;
1739 enumeration_completions_[id] = chooser_completion;
1740 return Send(new ViewHostMsg_EnumerateDirectory(
1741 routing_id_,
1743 base::FilePath::FromUTF16Unsafe(path)));
1746 void RenderViewImpl::FrameDidStartLoading(WebFrame* frame) {
1747 DCHECK_GE(frames_in_progress_, 0);
1748 if (frames_in_progress_ == 0)
1749 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStartLoading());
1750 frames_in_progress_++;
1753 void RenderViewImpl::FrameDidStopLoading(WebFrame* frame) {
1754 // TODO(japhet): This should be a DCHECK, but the pdf plugin sometimes
1755 // calls DidStopLoading() without a matching DidStartLoading().
1756 if (frames_in_progress_ == 0)
1757 return;
1758 frames_in_progress_--;
1759 if (frames_in_progress_ == 0) {
1760 DidStopLoadingIcons();
1761 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStopLoading());
1765 void RenderViewImpl::didCancelCompositionOnSelectionChange() {
1766 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
1769 bool RenderViewImpl::handleCurrentKeyboardEvent() {
1770 if (edit_commands_.empty())
1771 return false;
1773 WebFrame* frame = webview()->focusedFrame();
1774 if (!frame)
1775 return false;
1777 EditCommands::iterator it = edit_commands_.begin();
1778 EditCommands::iterator end = edit_commands_.end();
1780 bool did_execute_command = false;
1781 for (; it != end; ++it) {
1782 // In gtk and cocoa, it's possible to bind multiple edit commands to one
1783 // key (but it's the exception). Once one edit command is not executed, it
1784 // seems safest to not execute the rest.
1785 if (!frame->executeCommand(WebString::fromUTF8(it->name),
1786 WebString::fromUTF8(it->value),
1787 GetFocusedElement()))
1788 break;
1789 did_execute_command = true;
1792 return did_execute_command;
1795 bool RenderViewImpl::runFileChooser(
1796 const blink::WebFileChooserParams& params,
1797 WebFileChooserCompletion* chooser_completion) {
1798 // Do not open the file dialog in a hidden RenderView.
1799 if (is_hidden())
1800 return false;
1801 FileChooserParams ipc_params;
1802 if (params.directory)
1803 ipc_params.mode = FileChooserParams::UploadFolder;
1804 else if (params.multiSelect)
1805 ipc_params.mode = FileChooserParams::OpenMultiple;
1806 else if (params.saveAs)
1807 ipc_params.mode = FileChooserParams::Save;
1808 else
1809 ipc_params.mode = FileChooserParams::Open;
1810 ipc_params.title = params.title;
1811 ipc_params.default_file_name =
1812 base::FilePath::FromUTF16Unsafe(params.initialValue);
1813 ipc_params.accept_types.reserve(params.acceptTypes.size());
1814 for (size_t i = 0; i < params.acceptTypes.size(); ++i)
1815 ipc_params.accept_types.push_back(params.acceptTypes[i]);
1816 #if defined(OS_ANDROID)
1817 ipc_params.capture = params.useMediaCapture;
1818 #endif
1820 return ScheduleFileChooser(ipc_params, chooser_completion);
1823 void RenderViewImpl::SetValidationMessageDirection(
1824 base::string16* wrapped_main_text,
1825 blink::WebTextDirection main_text_hint,
1826 base::string16* wrapped_sub_text,
1827 blink::WebTextDirection sub_text_hint) {
1828 if (main_text_hint == blink::WebTextDirectionLeftToRight) {
1829 *wrapped_main_text =
1830 base::i18n::GetDisplayStringInLTRDirectionality(*wrapped_main_text);
1831 } else if (main_text_hint == blink::WebTextDirectionRightToLeft &&
1832 !base::i18n::IsRTL()) {
1833 base::i18n::WrapStringWithRTLFormatting(wrapped_main_text);
1836 if (!wrapped_sub_text->empty()) {
1837 if (sub_text_hint == blink::WebTextDirectionLeftToRight) {
1838 *wrapped_sub_text =
1839 base::i18n::GetDisplayStringInLTRDirectionality(*wrapped_sub_text);
1840 } else if (sub_text_hint == blink::WebTextDirectionRightToLeft) {
1841 base::i18n::WrapStringWithRTLFormatting(wrapped_sub_text);
1846 void RenderViewImpl::showValidationMessage(
1847 const blink::WebRect& anchor_in_root_view,
1848 const blink::WebString& main_text,
1849 blink::WebTextDirection main_text_hint,
1850 const blink::WebString& sub_text,
1851 blink::WebTextDirection sub_text_hint) {
1852 base::string16 wrapped_main_text = main_text;
1853 base::string16 wrapped_sub_text = sub_text;
1855 SetValidationMessageDirection(
1856 &wrapped_main_text, main_text_hint, &wrapped_sub_text, sub_text_hint);
1858 Send(new ViewHostMsg_ShowValidationMessage(
1859 routing_id(), AdjustValidationMessageAnchor(anchor_in_root_view),
1860 wrapped_main_text, wrapped_sub_text));
1863 void RenderViewImpl::hideValidationMessage() {
1864 Send(new ViewHostMsg_HideValidationMessage(routing_id()));
1867 void RenderViewImpl::moveValidationMessage(
1868 const blink::WebRect& anchor_in_root_view) {
1869 Send(new ViewHostMsg_MoveValidationMessage(
1870 routing_id(), AdjustValidationMessageAnchor(anchor_in_root_view)));
1873 void RenderViewImpl::setStatusText(const WebString& text) {
1876 void RenderViewImpl::UpdateTargetURL(const GURL& url,
1877 const GURL& fallback_url) {
1878 GURL latest_url = url.is_empty() ? fallback_url : url;
1879 if (latest_url == target_url_)
1880 return;
1882 // Tell the browser to display a destination link.
1883 if (target_url_status_ == TARGET_INFLIGHT ||
1884 target_url_status_ == TARGET_PENDING) {
1885 // If we have a request in-flight, save the URL to be sent when we
1886 // receive an ACK to the in-flight request. We can happily overwrite
1887 // any existing pending sends.
1888 pending_target_url_ = latest_url;
1889 target_url_status_ = TARGET_PENDING;
1890 } else {
1891 // URLs larger than |MaxURLChars()| cannot be sent through IPC -
1892 // see |ParamTraits<GURL>|.
1893 if (latest_url.possibly_invalid_spec().size() > GetMaxURLChars())
1894 latest_url = GURL();
1895 Send(new ViewHostMsg_UpdateTargetURL(routing_id_, latest_url));
1896 target_url_ = latest_url;
1897 target_url_status_ = TARGET_INFLIGHT;
1901 gfx::RectF RenderViewImpl::ClientRectToPhysicalWindowRect(
1902 const gfx::RectF& rect) const {
1903 gfx::RectF window_rect = rect;
1904 window_rect.Scale(device_scale_factor_ * webview()->pageScaleFactor());
1905 return window_rect;
1908 void RenderViewImpl::StartNavStateSyncTimerIfNecessary() {
1909 // No need to update state if no page has committed yet.
1910 if (page_id_ == -1)
1911 return;
1913 int delay;
1914 if (send_content_state_immediately_)
1915 delay = 0;
1916 else if (is_hidden())
1917 delay = kDelaySecondsForContentStateSyncHidden;
1918 else
1919 delay = kDelaySecondsForContentStateSync;
1921 if (nav_state_sync_timer_.IsRunning()) {
1922 // The timer is already running. If the delay of the timer maches the amount
1923 // we want to delay by, then return. Otherwise stop the timer so that it
1924 // gets started with the right delay.
1925 if (nav_state_sync_timer_.GetCurrentDelay().InSeconds() == delay)
1926 return;
1927 nav_state_sync_timer_.Stop();
1930 nav_state_sync_timer_.Start(FROM_HERE, TimeDelta::FromSeconds(delay), this,
1931 &RenderViewImpl::SyncNavigationState);
1934 void RenderViewImpl::setMouseOverURL(const WebURL& url) {
1935 mouse_over_url_ = GURL(url);
1936 UpdateTargetURL(mouse_over_url_, focus_url_);
1939 void RenderViewImpl::setKeyboardFocusURL(const WebURL& url) {
1940 focus_url_ = GURL(url);
1941 UpdateTargetURL(focus_url_, mouse_over_url_);
1944 void RenderViewImpl::startDragging(WebLocalFrame* frame,
1945 const WebDragData& data,
1946 WebDragOperationsMask mask,
1947 const WebImage& image,
1948 const WebPoint& webImageOffset) {
1949 DropData drop_data(DropDataBuilder::Build(data));
1950 drop_data.referrer_policy = frame->document().referrerPolicy();
1951 gfx::Vector2d imageOffset(webImageOffset.x, webImageOffset.y);
1952 Send(new DragHostMsg_StartDragging(routing_id_,
1953 drop_data,
1954 mask,
1955 image.getSkBitmap(),
1956 imageOffset,
1957 possible_drag_event_info_));
1960 bool RenderViewImpl::acceptsLoadDrops() {
1961 return renderer_preferences_.can_accept_load_drops;
1964 void RenderViewImpl::focusNext() {
1965 Send(new ViewHostMsg_TakeFocus(routing_id_, false));
1968 void RenderViewImpl::focusPrevious() {
1969 Send(new ViewHostMsg_TakeFocus(routing_id_, true));
1972 void RenderViewImpl::focusedNodeChanged(const WebNode& node) {
1973 has_scrolled_focused_editable_node_into_rect_ = false;
1975 Send(new ViewHostMsg_FocusedNodeChanged(routing_id_, IsEditableNode(node)));
1977 FOR_EACH_OBSERVER(RenderViewObserver, observers_, FocusedNodeChanged(node));
1979 // TODO(dmazzoni): this should be part of RenderFrameObserver.
1980 GetMainRenderFrame()->FocusedNodeChanged(node);
1983 void RenderViewImpl::didUpdateLayout() {
1984 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidUpdateLayout());
1986 // We don't always want to set up a timer, only if we've been put in that
1987 // mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
1988 // message.
1989 if (!send_preferred_size_changes_ || !webview())
1990 return;
1992 if (check_preferred_size_timer_.IsRunning())
1993 return;
1994 check_preferred_size_timer_.Start(FROM_HERE,
1995 TimeDelta::FromMilliseconds(0), this,
1996 &RenderViewImpl::CheckPreferredSize);
1999 void RenderViewImpl::navigateBackForwardSoon(int offset) {
2000 Send(new ViewHostMsg_GoToEntryAtOffset(routing_id_, offset));
2003 int RenderViewImpl::historyBackListCount() {
2004 return history_list_offset_ < 0 ? 0 : history_list_offset_;
2007 int RenderViewImpl::historyForwardListCount() {
2008 return history_list_length_ - historyBackListCount() - 1;
2011 // blink::WebWidgetClient ----------------------------------------------------
2013 void RenderViewImpl::didFocus() {
2014 // TODO(jcivelli): when https://bugs.webkit.org/show_bug.cgi?id=33389 is fixed
2015 // we won't have to test for user gesture anymore and we can
2016 // move that code back to render_widget.cc
2017 if (WebUserGestureIndicator::isProcessingUserGesture() &&
2018 !RenderThreadImpl::current()->layout_test_mode()) {
2019 Send(new ViewHostMsg_Focus(routing_id_));
2023 void RenderViewImpl::didBlur() {
2024 // TODO(jcivelli): see TODO above in didFocus().
2025 if (WebUserGestureIndicator::isProcessingUserGesture() &&
2026 !RenderThreadImpl::current()->layout_test_mode()) {
2027 Send(new ViewHostMsg_Blur(routing_id_));
2031 // We are supposed to get a single call to Show for a newly created RenderView
2032 // that was created via RenderViewImpl::CreateWebView. So, we wait until this
2033 // point to dispatch the ShowView message.
2035 // This method provides us with the information about how to display the newly
2036 // created RenderView (i.e., as a blocked popup or as a new tab).
2038 void RenderViewImpl::show(WebNavigationPolicy policy) {
2039 if (did_show_) {
2040 // When supports_multiple_windows is disabled, popups are reusing
2041 // the same view. In some scenarios, this makes WebKit to call show() twice.
2042 if (webkit_preferences_.supports_multiple_windows)
2043 NOTREACHED() << "received extraneous Show call";
2044 return;
2046 did_show_ = true;
2048 DCHECK(opener_id_ != MSG_ROUTING_NONE);
2050 // NOTE: initial_pos_ may still have its default values at this point, but
2051 // that's okay. It'll be ignored if disposition is not NEW_POPUP, or the
2052 // browser process will impose a default position otherwise.
2053 Send(new ViewHostMsg_ShowView(opener_id_, routing_id_,
2054 NavigationPolicyToDisposition(policy), initial_pos_,
2055 opened_by_user_gesture_));
2056 SetPendingWindowRect(initial_pos_);
2059 void RenderViewImpl::runModal() {
2060 DCHECK(did_show_) << "should already have shown the view";
2062 // Don't allow further dialogs if we are waiting to swap out, since the
2063 // PageGroupLoadDeferrer in our stack prevents it.
2064 if (suppress_dialogs_until_swap_out_)
2065 return;
2067 // We must keep WebKit's shared timer running in this case in order to allow
2068 // showModalDialog to function properly.
2070 // TODO(darin): WebKit should really be smarter about suppressing events and
2071 // timers so that we do not need to manage the shared timer in such a heavy
2072 // handed manner.
2074 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
2075 RenderThreadImpl::current()->DoNotSuspendWebKitSharedTimer();
2077 SendAndRunNestedMessageLoop(new ViewHostMsg_RunModal(
2078 routing_id_, opener_id_));
2081 bool RenderViewImpl::enterFullScreen() {
2082 Send(new ViewHostMsg_ToggleFullscreen(routing_id_, true));
2083 return true;
2086 void RenderViewImpl::exitFullScreen() {
2087 Send(new ViewHostMsg_ToggleFullscreen(routing_id_, false));
2090 bool RenderViewImpl::requestPointerLock() {
2091 return mouse_lock_dispatcher_->LockMouse(webwidget_mouse_lock_target_.get());
2094 void RenderViewImpl::requestPointerUnlock() {
2095 mouse_lock_dispatcher_->UnlockMouse(webwidget_mouse_lock_target_.get());
2098 bool RenderViewImpl::isPointerLocked() {
2099 return mouse_lock_dispatcher_->IsMouseLockedTo(
2100 webwidget_mouse_lock_target_.get());
2103 void RenderViewImpl::didHandleGestureEvent(
2104 const WebGestureEvent& event,
2105 bool event_cancelled) {
2106 RenderWidget::didHandleGestureEvent(event, event_cancelled);
2108 if (!event_cancelled) {
2109 FOR_EACH_OBSERVER(
2110 RenderViewObserver, observers_, DidHandleGestureEvent(event));
2113 // TODO(ananta): Piggyback off existing IPCs to communicate this information,
2114 // crbug/420130.
2115 #if defined(OS_WIN)
2116 if (event.type != blink::WebGestureEvent::GestureTap)
2117 return;
2119 // TODO(estade): hit test the event against focused node to make sure
2120 // the tap actually hit the focused node.
2121 blink::WebTextInputType text_input_type =
2122 GetWebView()->textInputInfo().type;
2124 Send(new ViewHostMsg_FocusedNodeTouched(
2125 routing_id(), text_input_type != blink::WebTextInputTypeNone));
2126 #endif
2129 void RenderViewImpl::initializeLayerTreeView() {
2130 RenderWidget::initializeLayerTreeView();
2131 RenderWidgetCompositor* rwc = compositor();
2132 if (!rwc)
2133 return;
2134 if (webview() && webview()->devToolsAgent())
2135 webview()->devToolsAgent()->setLayerTreeId(rwc->GetLayerTreeId());
2137 #if !defined(OS_MACOSX) // many events are unhandled - http://crbug.com/138003
2138 RenderThreadImpl* render_thread = RenderThreadImpl::current();
2139 // render_thread may be NULL in tests.
2140 InputHandlerManager* input_handler_manager =
2141 render_thread ? render_thread->input_handler_manager() : NULL;
2142 if (input_handler_manager) {
2143 input_handler_manager->AddInputHandler(
2144 routing_id_, rwc->GetInputHandler(), AsWeakPtr());
2146 #endif
2149 // blink::WebFrameClient -----------------------------------------------------
2151 void RenderViewImpl::Repaint(const gfx::Size& size) {
2152 OnRepaint(size);
2155 void RenderViewImpl::SetEditCommandForNextKeyEvent(const std::string& name,
2156 const std::string& value) {
2157 EditCommands edit_commands;
2158 edit_commands.push_back(EditCommand(name, value));
2159 OnSetEditCommandsForNextKeyEvent(edit_commands);
2162 void RenderViewImpl::ClearEditCommands() {
2163 edit_commands_.clear();
2166 SSLStatus RenderViewImpl::GetSSLStatusOfFrame(blink::WebFrame* frame) const {
2167 std::string security_info;
2168 if (frame && frame->dataSource())
2169 security_info = frame->dataSource()->response().securityInfo();
2171 SSLStatus ssl_status;
2172 DeserializeSecurityInfo(security_info,
2173 &ssl_status.cert_id,
2174 &ssl_status.cert_status,
2175 &ssl_status.security_bits,
2176 &ssl_status.connection_status,
2177 &ssl_status.signed_certificate_timestamp_ids);
2178 return ssl_status;
2181 const std::string& RenderViewImpl::GetAcceptLanguages() const {
2182 return renderer_preferences_.accept_languages;
2185 void RenderViewImpl::didCreateDataSource(WebLocalFrame* frame,
2186 WebDataSource* ds) {
2187 bool content_initiated = !pending_navigation_params_.get();
2189 // Make sure any previous redirect URLs end up in our new data source.
2190 if (pending_navigation_params_.get()) {
2191 for (std::vector<GURL>::const_iterator i =
2192 pending_navigation_params_->redirects.begin();
2193 i != pending_navigation_params_->redirects.end(); ++i) {
2194 ds->appendRedirect(*i);
2198 DocumentState* document_state = DocumentState::FromDataSource(ds);
2199 if (!document_state) {
2200 document_state = new DocumentState;
2201 ds->setExtraData(document_state);
2202 if (!content_initiated)
2203 PopulateDocumentStateFromPending(document_state);
2206 // Carry over the user agent override flag, if it exists.
2207 if (content_initiated && webview() && webview()->mainFrame() &&
2208 webview()->mainFrame()->isWebLocalFrame() &&
2209 webview()->mainFrame()->dataSource()) {
2210 DocumentState* old_document_state =
2211 DocumentState::FromDataSource(webview()->mainFrame()->dataSource());
2212 if (old_document_state) {
2213 InternalDocumentStateData* internal_data =
2214 InternalDocumentStateData::FromDocumentState(document_state);
2215 InternalDocumentStateData* old_internal_data =
2216 InternalDocumentStateData::FromDocumentState(old_document_state);
2217 internal_data->set_is_overriding_user_agent(
2218 old_internal_data->is_overriding_user_agent());
2222 // The rest of RenderView assumes that a WebDataSource will always have a
2223 // non-null NavigationState.
2224 if (content_initiated) {
2225 document_state->set_navigation_state(
2226 NavigationState::CreateContentInitiated());
2227 } else {
2228 document_state->set_navigation_state(CreateNavigationStateFromPending());
2229 pending_navigation_params_.reset();
2232 // DocumentState::referred_by_prefetcher_ is true if we are
2233 // navigating from a page that used prefetching using a link on that
2234 // page. We are early enough in the request process here that we
2235 // can still see the DocumentState of the previous page and set
2236 // this value appropriately.
2237 // TODO(gavinp): catch the important case of navigation in a new
2238 // renderer process.
2239 if (webview()) {
2240 if (WebFrame* old_frame = webview()->mainFrame()) {
2241 const WebURLRequest& original_request = ds->originalRequest();
2242 const GURL referrer(
2243 original_request.httpHeaderField(WebString::fromUTF8("Referer")));
2244 if (!referrer.is_empty() && old_frame->isWebLocalFrame() &&
2245 DocumentState::FromDataSource(old_frame->dataSource())
2246 ->was_prefetcher()) {
2247 for (; old_frame; old_frame = old_frame->traverseNext(false)) {
2248 WebDataSource* old_frame_ds = old_frame->dataSource();
2249 if (old_frame_ds && referrer == GURL(old_frame_ds->request().url())) {
2250 document_state->set_was_referred_by_prefetcher(true);
2251 break;
2258 if (content_initiated) {
2259 const WebURLRequest& request = ds->request();
2260 switch (request.cachePolicy()) {
2261 case WebURLRequest::UseProtocolCachePolicy: // normal load.
2262 document_state->set_load_type(DocumentState::LINK_LOAD_NORMAL);
2263 break;
2264 case WebURLRequest::ReloadIgnoringCacheData: // reload.
2265 case WebURLRequest::ReloadBypassingCache: // end-to-end reload.
2266 document_state->set_load_type(DocumentState::LINK_LOAD_RELOAD);
2267 break;
2268 case WebURLRequest::ReturnCacheDataElseLoad: // allow stale data.
2269 document_state->set_load_type(
2270 DocumentState::LINK_LOAD_CACHE_STALE_OK);
2271 break;
2272 case WebURLRequest::ReturnCacheDataDontLoad: // Don't re-post.
2273 document_state->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY);
2274 break;
2275 default:
2276 NOTREACHED();
2280 FOR_EACH_OBSERVER(
2281 RenderViewObserver, observers_, DidCreateDataSource(frame, ds));
2284 void RenderViewImpl::PopulateDocumentStateFromPending(
2285 DocumentState* document_state) {
2286 const FrameMsg_Navigate_Params& params = *pending_navigation_params_.get();
2287 document_state->set_request_time(params.request_time);
2289 InternalDocumentStateData* internal_data =
2290 InternalDocumentStateData::FromDocumentState(document_state);
2292 if (!params.common_params.url.SchemeIs(url::kJavaScriptScheme) &&
2293 params.common_params.navigation_type == FrameMsg_Navigate_Type::RESTORE) {
2294 // We're doing a load of a page that was restored from the last session. By
2295 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
2296 // can result in stale data for pages that are set to expire. We explicitly
2297 // override that by setting the policy here so that as necessary we load
2298 // from the network.
2300 // TODO(davidben): Remove this in favor of passing a cache policy to the
2301 // loadHistoryItem call in OnNavigate. That requires not overloading
2302 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
2303 // policy based on load type, etc".
2304 internal_data->set_cache_policy_override(
2305 WebURLRequest::UseProtocolCachePolicy);
2308 if (IsReload(params.common_params.navigation_type))
2309 document_state->set_load_type(DocumentState::RELOAD);
2310 else if (params.commit_params.page_state.IsValid())
2311 document_state->set_load_type(DocumentState::HISTORY_LOAD);
2312 else
2313 document_state->set_load_type(DocumentState::NORMAL_LOAD);
2315 internal_data->set_is_overriding_user_agent(
2316 params.commit_params.is_overriding_user_agent);
2317 internal_data->set_must_reset_scroll_and_scale_state(
2318 params.common_params.navigation_type ==
2319 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
2320 document_state->set_can_load_local_resources(params.can_load_local_resources);
2323 NavigationState* RenderViewImpl::CreateNavigationStateFromPending() {
2324 const FrameMsg_Navigate_Params& params = *pending_navigation_params_.get();
2325 NavigationState* navigation_state = NULL;
2327 // A navigation resulting from loading a javascript URL should not be treated
2328 // as a browser initiated event. Instead, we want it to look as if the page
2329 // initiated any load resulting from JS execution.
2330 if (!params.common_params.url.SchemeIs(url::kJavaScriptScheme)) {
2331 navigation_state = NavigationState::CreateBrowserInitiated(
2332 params.page_id,
2333 params.pending_history_list_offset,
2334 params.should_clear_history_list,
2335 params.common_params.transition);
2336 navigation_state->set_should_replace_current_entry(
2337 params.should_replace_current_entry);
2338 navigation_state->set_transferred_request_child_id(
2339 params.transferred_request_child_id);
2340 navigation_state->set_transferred_request_request_id(
2341 params.transferred_request_request_id);
2342 navigation_state->set_allow_download(params.common_params.allow_download);
2343 navigation_state->set_extra_headers(params.request_params.extra_headers);
2344 } else {
2345 navigation_state = NavigationState::CreateContentInitiated();
2347 return navigation_state;
2350 void RenderViewImpl::ProcessViewLayoutFlags(const CommandLine& command_line) {
2351 bool enable_viewport =
2352 command_line.HasSwitch(switches::kEnableViewport) ||
2353 command_line.HasSwitch(switches::kEnableViewportMeta);
2355 // If viewport tag is enabled, then the WebKit side will take care
2356 // of setting the fixed layout size and page scale limits.
2357 if (enable_viewport)
2358 return;
2360 // When navigating to a new page, reset the page scale factor to be 1.0.
2361 webview()->setInitialPageScaleOverride(1.f);
2363 float maxPageScaleFactor =
2364 command_line.HasSwitch(switches::kEnablePinch) ? 4.f : 1.f ;
2365 webview()->setPageScaleFactorLimits(1, maxPageScaleFactor);
2368 void RenderViewImpl::didClearWindowObject(WebLocalFrame* frame) {
2369 FOR_EACH_OBSERVER(
2370 RenderViewObserver, observers_, DidClearWindowObject(frame));
2372 if (enabled_bindings_& BINDINGS_POLICY_WEB_UI)
2373 WebUIExtension::Install(frame);
2375 if (enabled_bindings_ & BINDINGS_POLICY_STATS_COLLECTION)
2376 StatsCollectionController::Install(frame);
2378 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
2380 if (command_line.HasSwitch(switches::kEnableSkiaBenchmarking))
2381 SkiaBenchmarking::Install(frame);
2383 if (command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
2384 MemoryBenchmarkingExtension::Install(frame);
2387 void RenderViewImpl::didChangeIcon(WebLocalFrame* frame,
2388 WebIconURL::Type icon_type) {
2389 if (frame->parent())
2390 return;
2392 if (!TouchEnabled() && icon_type != WebIconURL::TypeFavicon)
2393 return;
2395 WebVector<WebIconURL> icon_urls = frame->iconURLs(icon_type);
2396 std::vector<FaviconURL> urls;
2397 for (size_t i = 0; i < icon_urls.size(); i++) {
2398 std::vector<gfx::Size> sizes;
2399 ConvertToFaviconSizes(icon_urls[i].sizes(), &sizes);
2400 urls.push_back(FaviconURL(
2401 icon_urls[i].iconURL(), ToFaviconType(icon_urls[i].iconType()), sizes));
2403 SendUpdateFaviconURL(urls);
2406 void RenderViewImpl::didUpdateCurrentHistoryItem(WebLocalFrame* frame) {
2407 StartNavStateSyncTimerIfNecessary();
2410 void RenderViewImpl::CheckPreferredSize() {
2411 // We don't always want to send the change messages over IPC, only if we've
2412 // been put in that mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
2413 // message.
2414 if (!send_preferred_size_changes_ || !webview())
2415 return;
2417 gfx::Size size = webview()->contentsPreferredMinimumSize();
2419 // In the presence of zoom, these sizes are still reported as if unzoomed,
2420 // so we need to adjust.
2421 double zoom_factor = ZoomLevelToZoomFactor(webview()->zoomLevel());
2422 size.set_width(static_cast<int>(size.width() * zoom_factor));
2423 size.set_height(static_cast<int>(size.height() * zoom_factor));
2425 if (size == preferred_size_)
2426 return;
2428 preferred_size_ = size;
2429 Send(new ViewHostMsg_DidContentsPreferredSizeChange(routing_id_,
2430 preferred_size_));
2433 BrowserPluginManager* RenderViewImpl::GetBrowserPluginManager() {
2434 if (!browser_plugin_manager_.get())
2435 browser_plugin_manager_ = BrowserPluginManager::Create(this);
2436 return browser_plugin_manager_.get();
2439 void RenderViewImpl::didChangeScrollOffset(WebLocalFrame* frame) {
2440 StartNavStateSyncTimerIfNecessary();
2442 FOR_EACH_OBSERVER(
2443 RenderViewObserver, observers_, DidChangeScrollOffset(frame));
2446 void RenderViewImpl::SendFindReply(int request_id,
2447 int match_count,
2448 int ordinal,
2449 const WebRect& selection_rect,
2450 bool final_status_update) {
2451 Send(new ViewHostMsg_Find_Reply(routing_id_,
2452 request_id,
2453 match_count,
2454 selection_rect,
2455 ordinal,
2456 final_status_update));
2459 blink::WebString RenderViewImpl::acceptLanguages() {
2460 return WebString::fromUTF8(renderer_preferences_.accept_languages);
2463 // blink::WebPageSerializerClient implementation ------------------------------
2465 void RenderViewImpl::didSerializeDataForFrame(
2466 const WebURL& frame_url,
2467 const WebCString& data,
2468 WebPageSerializerClient::PageSerializationStatus status) {
2469 Send(new ViewHostMsg_SendSerializedHtmlData(
2470 routing_id(),
2471 frame_url,
2472 data.data(),
2473 static_cast<int32>(status)));
2476 // RenderView implementation ---------------------------------------------------
2478 bool RenderViewImpl::Send(IPC::Message* message) {
2479 return RenderWidget::Send(message);
2482 RenderFrameImpl* RenderViewImpl::GetMainRenderFrame() {
2483 return main_render_frame_.get();
2486 int RenderViewImpl::GetRoutingID() const {
2487 return routing_id_;
2490 gfx::Size RenderViewImpl::GetSize() const {
2491 return size();
2494 WebPreferences& RenderViewImpl::GetWebkitPreferences() {
2495 return webkit_preferences_;
2498 void RenderViewImpl::SetWebkitPreferences(const WebPreferences& preferences) {
2499 OnUpdateWebPreferences(preferences);
2502 blink::WebView* RenderViewImpl::GetWebView() {
2503 return webview();
2506 blink::WebElement RenderViewImpl::GetFocusedElement() const {
2507 if (!webview())
2508 return WebElement();
2509 WebFrame* focused_frame = webview()->focusedFrame();
2510 if (focused_frame) {
2511 WebDocument doc = focused_frame->document();
2512 if (!doc.isNull())
2513 return doc.focusedElement();
2516 return WebElement();
2519 bool RenderViewImpl::IsEditableNode(const WebNode& node) const {
2520 if (node.isNull())
2521 return false;
2523 if (node.isContentEditable())
2524 return true;
2526 if (node.isElementNode()) {
2527 const WebElement& element = node.toConst<WebElement>();
2528 if (element.isTextFormControlElement())
2529 return true;
2531 // Also return true if it has an ARIA role of 'textbox'.
2532 for (unsigned i = 0; i < element.attributeCount(); ++i) {
2533 if (LowerCaseEqualsASCII(element.attributeLocalName(i), "role")) {
2534 if (LowerCaseEqualsASCII(element.attributeValue(i), "textbox"))
2535 return true;
2536 break;
2541 return false;
2544 bool RenderViewImpl::NodeContainsPoint(const WebNode& node,
2545 const gfx::Point& point) const {
2546 blink::WebHitTestResult hit_test =
2547 webview()->hitTestResultAt(WebPoint(point.x(), point.y()));
2548 return node.containsIncludingShadowDOM(hit_test.node());
2551 bool RenderViewImpl::ShouldDisplayScrollbars(int width, int height) const {
2552 return (!send_preferred_size_changes_ ||
2553 (disable_scrollbars_size_limit_.width() <= width ||
2554 disable_scrollbars_size_limit_.height() <= height));
2557 int RenderViewImpl::GetEnabledBindings() const {
2558 return enabled_bindings_;
2561 bool RenderViewImpl::GetContentStateImmediately() const {
2562 return send_content_state_immediately_;
2565 blink::WebPageVisibilityState RenderViewImpl::GetVisibilityState() const {
2566 return visibilityState();
2569 void RenderViewImpl::DidStartLoading() {
2570 main_render_frame_->didStartLoading(true);
2573 void RenderViewImpl::DidStopLoading() {
2574 main_render_frame_->didStopLoading();
2577 void RenderViewImpl::SyncNavigationState() {
2578 if (!webview())
2579 return;
2580 SendUpdateState(history_controller_->GetCurrentEntry());
2583 blink::WebPlugin* RenderViewImpl::GetWebPluginForFind() {
2584 if (!webview())
2585 return NULL;
2587 WebFrame* main_frame = webview()->mainFrame();
2588 if (main_frame->isWebLocalFrame() &&
2589 main_frame->document().isPluginDocument())
2590 return webview()->mainFrame()->document().to<WebPluginDocument>().plugin();
2592 #if defined(ENABLE_PLUGINS)
2593 if (plugin_find_handler_)
2594 return plugin_find_handler_->container()->plugin();
2595 #endif
2597 return NULL;
2600 void RenderViewImpl::OnFind(int request_id,
2601 const base::string16& search_text,
2602 const WebFindOptions& options) {
2603 WebFrame* main_frame = webview()->mainFrame();
2604 blink::WebPlugin* plugin = GetWebPluginForFind();
2605 // Check if the plugin still exists in the document.
2606 if (plugin) {
2607 if (options.findNext) {
2608 // Just navigate back/forward.
2609 plugin->selectFindResult(options.forward);
2610 } else {
2611 if (!plugin->startFind(
2612 search_text, options.matchCase, request_id)) {
2613 // Send "no results".
2614 SendFindReply(request_id, 0, 0, gfx::Rect(), true);
2617 return;
2620 WebFrame* frame_after_main = main_frame->traverseNext(true);
2621 WebFrame* focused_frame = webview()->focusedFrame();
2622 WebFrame* search_frame = focused_frame; // start searching focused frame.
2624 bool multi_frame = (frame_after_main != main_frame);
2626 // If we have multiple frames, we don't want to wrap the search within the
2627 // frame, so we check here if we only have main_frame in the chain.
2628 bool wrap_within_frame = !multi_frame;
2630 WebRect selection_rect;
2631 bool result = false;
2633 // If something is selected when we start searching it means we cannot just
2634 // increment the current match ordinal; we need to re-generate it.
2635 WebRange current_selection = focused_frame->selectionRange();
2637 do {
2638 result = search_frame->find(
2639 request_id, search_text, options, wrap_within_frame, &selection_rect);
2641 if (!result) {
2642 // don't leave text selected as you move to the next frame.
2643 search_frame->executeCommand(WebString::fromUTF8("Unselect"),
2644 GetFocusedElement());
2646 // Find the next frame, but skip the invisible ones.
2647 do {
2648 // What is the next frame to search? (we might be going backwards). Note
2649 // that we specify wrap=true so that search_frame never becomes NULL.
2650 search_frame = options.forward ?
2651 search_frame->traverseNext(true) :
2652 search_frame->traversePrevious(true);
2653 } while (!search_frame->hasVisibleContent() &&
2654 search_frame != focused_frame);
2656 // Make sure selection doesn't affect the search operation in new frame.
2657 search_frame->executeCommand(WebString::fromUTF8("Unselect"),
2658 GetFocusedElement());
2660 // If we have multiple frames and we have wrapped back around to the
2661 // focused frame, we need to search it once more allowing wrap within
2662 // the frame, otherwise it will report 'no match' if the focused frame has
2663 // reported matches, but no frames after the focused_frame contain a
2664 // match for the search word(s).
2665 if (multi_frame && search_frame == focused_frame) {
2666 result = search_frame->find(
2667 request_id, search_text, options, true, // Force wrapping.
2668 &selection_rect);
2672 webview()->setFocusedFrame(search_frame);
2673 } while (!result && search_frame != focused_frame);
2675 if (options.findNext && current_selection.isNull()) {
2676 // Force the main_frame to report the actual count.
2677 main_frame->increaseMatchCount(0, request_id);
2678 } else {
2679 // If nothing is found, set result to "0 of 0", otherwise, set it to
2680 // "-1 of 1" to indicate that we found at least one item, but we don't know
2681 // yet what is active.
2682 int ordinal = result ? -1 : 0; // -1 here means, we might know more later.
2683 int match_count = result ? 1 : 0; // 1 here means possibly more coming.
2685 // If we find no matches then this will be our last status update.
2686 // Otherwise the scoping effort will send more results.
2687 bool final_status_update = !result;
2689 SendFindReply(request_id, match_count, ordinal, selection_rect,
2690 final_status_update);
2692 // Scoping effort begins, starting with the mainframe.
2693 search_frame = main_frame;
2695 main_frame->resetMatchCount();
2697 do {
2698 // Cancel all old scoping requests before starting a new one.
2699 search_frame->cancelPendingScopingEffort();
2701 // We don't start another scoping effort unless at least one match has
2702 // been found.
2703 if (result) {
2704 // Start new scoping request. If the scoping function determines that it
2705 // needs to scope, it will defer until later.
2706 search_frame->scopeStringMatches(request_id,
2707 search_text,
2708 options,
2709 true); // reset the tickmarks
2712 // Iterate to the next frame. The frame will not necessarily scope, for
2713 // example if it is not visible.
2714 search_frame = search_frame->traverseNext(true);
2715 } while (search_frame != main_frame);
2719 void RenderViewImpl::OnStopFinding(StopFindAction action) {
2720 WebView* view = webview();
2721 if (!view)
2722 return;
2724 blink::WebPlugin* plugin = GetWebPluginForFind();
2725 if (plugin) {
2726 plugin->stopFind();
2727 return;
2730 bool clear_selection = action == STOP_FIND_ACTION_CLEAR_SELECTION;
2731 if (clear_selection) {
2732 view->focusedFrame()->executeCommand(WebString::fromUTF8("Unselect"),
2733 GetFocusedElement());
2736 WebFrame* frame = view->mainFrame();
2737 while (frame) {
2738 frame->stopFinding(clear_selection);
2739 frame = frame->traverseNext(false);
2742 if (action == STOP_FIND_ACTION_ACTIVATE_SELECTION) {
2743 WebFrame* focused_frame = view->focusedFrame();
2744 if (focused_frame) {
2745 WebDocument doc = focused_frame->document();
2746 if (!doc.isNull()) {
2747 WebElement element = doc.focusedElement();
2748 if (!element.isNull())
2749 element.simulateClick();
2755 #if defined(OS_ANDROID)
2756 void RenderViewImpl::OnActivateNearestFindResult(int request_id,
2757 float x, float y) {
2758 if (!webview())
2759 return;
2761 WebFrame* main_frame = webview()->mainFrame();
2762 WebRect selection_rect;
2763 int ordinal = main_frame->selectNearestFindMatch(WebFloatPoint(x, y),
2764 &selection_rect);
2765 if (ordinal == -1) {
2766 // Something went wrong, so send a no-op reply (force the main_frame to
2767 // report the current match count) in case the host is waiting for a
2768 // response due to rate-limiting).
2769 main_frame->increaseMatchCount(0, request_id);
2770 return;
2773 SendFindReply(request_id,
2774 -1 /* number_of_matches */,
2775 ordinal,
2776 selection_rect,
2777 true /* final_update */);
2780 void RenderViewImpl::OnFindMatchRects(int current_version) {
2781 if (!webview())
2782 return;
2784 WebFrame* main_frame = webview()->mainFrame();
2785 std::vector<gfx::RectF> match_rects;
2787 int rects_version = main_frame->findMatchMarkersVersion();
2788 if (current_version != rects_version) {
2789 WebVector<WebFloatRect> web_match_rects;
2790 main_frame->findMatchRects(web_match_rects);
2791 match_rects.reserve(web_match_rects.size());
2792 for (size_t i = 0; i < web_match_rects.size(); ++i)
2793 match_rects.push_back(gfx::RectF(web_match_rects[i]));
2796 gfx::RectF active_rect = main_frame->activeFindMatchRect();
2797 Send(new ViewHostMsg_FindMatchRects_Reply(routing_id_,
2798 rects_version,
2799 match_rects,
2800 active_rect));
2802 #endif
2804 void RenderViewImpl::OnZoom(PageZoom zoom) {
2805 if (!webview()) // Not sure if this can happen, but no harm in being safe.
2806 return;
2808 webview()->hidePopups();
2810 double old_zoom_level = webview()->zoomLevel();
2811 double zoom_level;
2812 if (zoom == PAGE_ZOOM_RESET) {
2813 zoom_level = 0;
2814 } else if (static_cast<int>(old_zoom_level) == old_zoom_level) {
2815 // Previous zoom level is a whole number, so just increment/decrement.
2816 zoom_level = old_zoom_level + zoom;
2817 } else {
2818 // Either the user hit the zoom factor limit and thus the zoom level is now
2819 // not a whole number, or a plugin changed it to a custom value. We want
2820 // to go to the next whole number so that the user can always get back to
2821 // 100% with the keyboard/menu.
2822 if ((old_zoom_level > 1 && zoom > 0) ||
2823 (old_zoom_level < 1 && zoom < 0)) {
2824 zoom_level = static_cast<int>(old_zoom_level + zoom);
2825 } else {
2826 // We're going towards 100%, so first go to the next whole number.
2827 zoom_level = static_cast<int>(old_zoom_level);
2830 webview()->setZoomLevel(zoom_level);
2831 zoomLevelChanged();
2834 void RenderViewImpl::OnSetZoomLevelForLoadingURL(const GURL& url,
2835 double zoom_level) {
2836 #if !defined(OS_ANDROID)
2837 // On Android, page zoom isn't used, and in case of WebView, text zoom is used
2838 // for legacy WebView text scaling emulation. Thus, the code that resets
2839 // the zoom level from this map will be effectively resetting text zoom level.
2840 host_zoom_levels_[url] = zoom_level;
2841 #endif
2844 void RenderViewImpl::OnSetZoomLevelForView(bool uses_temporary_zoom_level,
2845 double level) {
2846 uses_temporary_zoom_level_ = uses_temporary_zoom_level;
2848 webview()->hidePopups();
2849 webview()->setZoomLevel(level);
2852 void RenderViewImpl::OnSetPageEncoding(const std::string& encoding_name) {
2853 webview()->setPageEncoding(WebString::fromUTF8(encoding_name));
2856 void RenderViewImpl::OnResetPageEncodingToDefault() {
2857 WebString no_encoding;
2858 webview()->setPageEncoding(no_encoding);
2861 void RenderViewImpl::OnPostMessageEvent(
2862 const ViewMsg_PostMessage_Params& params) {
2863 // TODO(nasko): Support sending to subframes.
2864 WebFrame* frame = webview()->mainFrame();
2866 // Find the source frame if it exists.
2867 WebFrame* source_frame = NULL;
2868 if (params.source_routing_id != MSG_ROUTING_NONE) {
2869 RenderViewImpl* source_view = FromRoutingID(params.source_routing_id);
2870 if (source_view)
2871 source_frame = source_view->webview()->mainFrame();
2874 // If the message contained MessagePorts, create the corresponding endpoints.
2875 DCHECK_EQ(params.message_port_ids.size(), params.new_routing_ids.size());
2876 blink::WebMessagePortChannelArray channels(params.message_port_ids.size());
2877 for (size_t i = 0;
2878 i < params.message_port_ids.size() && i < params.new_routing_ids.size();
2879 ++i) {
2880 channels[i] =
2881 new WebMessagePortChannelImpl(params.new_routing_ids[i],
2882 params.message_port_ids[i],
2883 base::MessageLoopProxy::current().get());
2886 WebSerializedScriptValue serialized_script_value;
2887 if (params.is_data_raw_string) {
2888 v8::HandleScope handle_scope(blink::mainThreadIsolate());
2889 v8::Local<v8::Context> context = frame->mainWorldScriptContext();
2890 v8::Context::Scope context_scope(context);
2891 V8ValueConverterImpl converter;
2892 converter.SetDateAllowed(true);
2893 converter.SetRegExpAllowed(true);
2894 scoped_ptr<base::Value> value(new base::StringValue(params.data));
2895 v8::Handle<v8::Value> result_value = converter.ToV8Value(value.get(),
2896 context);
2897 serialized_script_value = WebSerializedScriptValue::serialize(result_value);
2898 } else {
2899 serialized_script_value = WebSerializedScriptValue::fromString(params.data);
2902 // Create an event with the message. The final parameter to initMessageEvent
2903 // is the last event ID, which is not used with postMessage.
2904 WebDOMEvent event = frame->document().createEvent("MessageEvent");
2905 WebDOMMessageEvent msg_event = event.to<WebDOMMessageEvent>();
2906 msg_event.initMessageEvent("message",
2907 // |canBubble| and |cancellable| are always false
2908 false, false,
2909 serialized_script_value,
2910 params.source_origin, source_frame, "", channels);
2912 // We must pass in the target_origin to do the security check on this side,
2913 // since it may have changed since the original postMessage call was made.
2914 WebSecurityOrigin target_origin;
2915 if (!params.target_origin.empty()) {
2916 target_origin =
2917 WebSecurityOrigin::createFromString(WebString(params.target_origin));
2919 frame->dispatchMessageEventWithOriginCheck(target_origin, msg_event);
2922 void RenderViewImpl::OnAllowBindings(int enabled_bindings_flags) {
2923 if ((enabled_bindings_flags & BINDINGS_POLICY_WEB_UI) &&
2924 !(enabled_bindings_ & BINDINGS_POLICY_WEB_UI)) {
2925 // WebUIExtensionData deletes itself when we're destroyed.
2926 new WebUIExtensionData(this);
2927 // WebUIMojo deletes itself when we're destroyed.
2928 new WebUIMojo(this);
2931 enabled_bindings_ |= enabled_bindings_flags;
2933 // Keep track of the total bindings accumulated in this process.
2934 RenderProcess::current()->AddBindings(enabled_bindings_flags);
2937 void RenderViewImpl::OnDragTargetDragEnter(const DropData& drop_data,
2938 const gfx::Point& client_point,
2939 const gfx::Point& screen_point,
2940 WebDragOperationsMask ops,
2941 int key_modifiers) {
2942 WebDragOperation operation = webview()->dragTargetDragEnter(
2943 DropDataToWebDragData(drop_data),
2944 client_point,
2945 screen_point,
2946 ops,
2947 key_modifiers);
2949 Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
2952 void RenderViewImpl::OnDragTargetDragOver(const gfx::Point& client_point,
2953 const gfx::Point& screen_point,
2954 WebDragOperationsMask ops,
2955 int key_modifiers) {
2956 WebDragOperation operation = webview()->dragTargetDragOver(
2957 client_point,
2958 screen_point,
2959 ops,
2960 key_modifiers);
2962 Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
2965 void RenderViewImpl::OnDragTargetDragLeave() {
2966 webview()->dragTargetDragLeave();
2969 void RenderViewImpl::OnDragTargetDrop(const gfx::Point& client_point,
2970 const gfx::Point& screen_point,
2971 int key_modifiers) {
2972 webview()->dragTargetDrop(client_point, screen_point, key_modifiers);
2974 Send(new DragHostMsg_TargetDrop_ACK(routing_id_));
2977 void RenderViewImpl::OnDragSourceEnded(const gfx::Point& client_point,
2978 const gfx::Point& screen_point,
2979 WebDragOperation op) {
2980 webview()->dragSourceEndedAt(client_point, screen_point, op);
2983 void RenderViewImpl::OnDragSourceSystemDragEnded() {
2984 webview()->dragSourceSystemDragEnded();
2987 void RenderViewImpl::OnUpdateWebPreferences(const WebPreferences& prefs) {
2988 webkit_preferences_ = prefs;
2989 ApplyWebPreferences(webkit_preferences_, webview());
2992 void RenderViewImpl::OnEnumerateDirectoryResponse(
2993 int id,
2994 const std::vector<base::FilePath>& paths) {
2995 if (!enumeration_completions_[id])
2996 return;
2998 WebVector<WebString> ws_file_names(paths.size());
2999 for (size_t i = 0; i < paths.size(); ++i)
3000 ws_file_names[i] = paths[i].AsUTF16Unsafe();
3002 enumeration_completions_[id]->didChooseFile(ws_file_names);
3003 enumeration_completions_.erase(id);
3006 void RenderViewImpl::OnFileChooserResponse(
3007 const std::vector<content::FileChooserFileInfo>& files) {
3008 // This could happen if we navigated to a different page before the user
3009 // closed the chooser.
3010 if (file_chooser_completions_.empty())
3011 return;
3013 // Convert Chrome's SelectedFileInfo list to WebKit's.
3014 WebVector<WebFileChooserCompletion::SelectedFileInfo> selected_files(
3015 files.size());
3016 for (size_t i = 0; i < files.size(); ++i) {
3017 WebFileChooserCompletion::SelectedFileInfo selected_file;
3018 selected_file.path = files[i].file_path.AsUTF16Unsafe();
3019 selected_file.displayName =
3020 base::FilePath(files[i].display_name).AsUTF16Unsafe();
3021 selected_files[i] = selected_file;
3024 if (file_chooser_completions_.front()->completion)
3025 file_chooser_completions_.front()->completion->didChooseFile(
3026 selected_files);
3027 file_chooser_completions_.pop_front();
3029 // If there are more pending file chooser requests, schedule one now.
3030 if (!file_chooser_completions_.empty()) {
3031 Send(new ViewHostMsg_RunFileChooser(routing_id_,
3032 file_chooser_completions_.front()->params));
3036 void RenderViewImpl::OnEnableAutoResize(const gfx::Size& min_size,
3037 const gfx::Size& max_size) {
3038 DCHECK(disable_scrollbars_size_limit_.IsEmpty());
3039 if (!webview())
3040 return;
3041 auto_resize_mode_ = true;
3042 webview()->enableAutoResizeMode(min_size, max_size);
3045 void RenderViewImpl::OnDisableAutoResize(const gfx::Size& new_size) {
3046 DCHECK(disable_scrollbars_size_limit_.IsEmpty());
3047 if (!webview())
3048 return;
3049 auto_resize_mode_ = false;
3050 webview()->disableAutoResizeMode();
3052 if (!new_size.IsEmpty()) {
3053 Resize(new_size,
3054 physical_backing_size_,
3055 top_controls_layout_height_,
3056 visible_viewport_size_,
3057 resizer_rect_,
3058 is_fullscreen_,
3059 NO_RESIZE_ACK);
3063 void RenderViewImpl::OnEnablePreferredSizeChangedMode() {
3064 if (send_preferred_size_changes_)
3065 return;
3066 send_preferred_size_changes_ = true;
3068 // Start off with an initial preferred size notification (in case
3069 // |didUpdateLayout| was already called).
3070 didUpdateLayout();
3073 void RenderViewImpl::OnDisableScrollbarsForSmallWindows(
3074 const gfx::Size& disable_scrollbar_size_limit) {
3075 disable_scrollbars_size_limit_ = disable_scrollbar_size_limit;
3078 void RenderViewImpl::OnSetRendererPrefs(
3079 const RendererPreferences& renderer_prefs) {
3080 double old_zoom_level = renderer_preferences_.default_zoom_level;
3081 std::string old_accept_languages = renderer_preferences_.accept_languages;
3083 renderer_preferences_ = renderer_prefs;
3084 UpdateFontRenderingFromRendererPrefs();
3086 #if defined(USE_DEFAULT_RENDER_THEME)
3087 if (renderer_prefs.use_custom_colors) {
3088 WebColorName name = blink::WebColorWebkitFocusRingColor;
3089 blink::setNamedColors(&name, &renderer_prefs.focus_ring_color, 1);
3090 blink::setCaretBlinkInterval(renderer_prefs.caret_blink_interval);
3092 if (webview()) {
3093 webview()->setSelectionColors(
3094 renderer_prefs.active_selection_bg_color,
3095 renderer_prefs.active_selection_fg_color,
3096 renderer_prefs.inactive_selection_bg_color,
3097 renderer_prefs.inactive_selection_fg_color);
3098 webview()->themeChanged();
3101 #endif // defined(USE_DEFAULT_RENDER_THEME)
3103 // If the zoom level for this page matches the old zoom default, and this
3104 // is not a plugin, update the zoom level to match the new default.
3105 if (webview() && webview()->mainFrame()->isWebLocalFrame() &&
3106 !webview()->mainFrame()->document().isPluginDocument() &&
3107 !ZoomValuesEqual(old_zoom_level,
3108 renderer_preferences_.default_zoom_level) &&
3109 ZoomValuesEqual(webview()->zoomLevel(), old_zoom_level)) {
3110 webview()->setZoomLevel(renderer_preferences_.default_zoom_level);
3111 zoomLevelChanged();
3114 if (webview() &&
3115 old_accept_languages != renderer_preferences_.accept_languages) {
3116 webview()->acceptLanguagesChanged();
3120 void RenderViewImpl::OnMediaPlayerActionAt(const gfx::Point& location,
3121 const WebMediaPlayerAction& action) {
3122 if (webview())
3123 webview()->performMediaPlayerAction(action, location);
3126 void RenderViewImpl::OnOrientationChange() {
3127 // TODO(mlamouri): consumers of that event should be using DisplayObserver.
3128 FOR_EACH_OBSERVER(RenderViewObserver,
3129 observers_,
3130 OrientationChangeEvent());
3132 webview()->mainFrame()->toWebLocalFrame()->sendOrientationChangeEvent();
3135 void RenderViewImpl::OnPluginActionAt(const gfx::Point& location,
3136 const WebPluginAction& action) {
3137 if (webview())
3138 webview()->performPluginAction(action, location);
3141 void RenderViewImpl::OnGetAllSavableResourceLinksForCurrentPage(
3142 const GURL& page_url) {
3143 // Prepare list to storage all savable resource links.
3144 std::vector<GURL> resources_list;
3145 std::vector<GURL> referrer_urls_list;
3146 std::vector<blink::WebReferrerPolicy> referrer_policies_list;
3147 std::vector<GURL> frames_list;
3148 SavableResourcesResult result(&resources_list,
3149 &referrer_urls_list,
3150 &referrer_policies_list,
3151 &frames_list);
3153 // webkit/ doesn't know about Referrer.
3154 if (!GetAllSavableResourceLinksForCurrentPage(
3155 webview(),
3156 page_url,
3157 &result,
3158 const_cast<const char**>(GetSavableSchemes()))) {
3159 // If something is wrong when collecting all savable resource links,
3160 // send empty list to embedder(browser) to tell it failed.
3161 referrer_urls_list.clear();
3162 referrer_policies_list.clear();
3163 resources_list.clear();
3164 frames_list.clear();
3167 std::vector<Referrer> referrers_list;
3168 CHECK_EQ(referrer_urls_list.size(), referrer_policies_list.size());
3169 for (unsigned i = 0; i < referrer_urls_list.size(); ++i) {
3170 referrers_list.push_back(
3171 Referrer(referrer_urls_list[i], referrer_policies_list[i]));
3174 // Send result of all savable resource links to embedder.
3175 Send(new ViewHostMsg_SendCurrentPageAllSavableResourceLinks(routing_id(),
3176 resources_list,
3177 referrers_list,
3178 frames_list));
3181 void RenderViewImpl::OnGetSerializedHtmlDataForCurrentPageWithLocalLinks(
3182 const std::vector<GURL>& links,
3183 const std::vector<base::FilePath>& local_paths,
3184 const base::FilePath& local_directory_name) {
3186 // Convert std::vector of GURLs to WebVector<WebURL>
3187 WebVector<WebURL> weburl_links(links);
3189 // Convert std::vector of base::FilePath to WebVector<WebString>
3190 WebVector<WebString> webstring_paths(local_paths.size());
3191 for (size_t i = 0; i < local_paths.size(); i++)
3192 webstring_paths[i] = local_paths[i].AsUTF16Unsafe();
3194 WebPageSerializer::serialize(webview()->mainFrame()->toWebLocalFrame(),
3195 true,
3196 this,
3197 weburl_links,
3198 webstring_paths,
3199 local_directory_name.AsUTF16Unsafe());
3202 void RenderViewImpl::OnSuppressDialogsUntilSwapOut() {
3203 // Don't show any more dialogs until we finish OnSwapOut.
3204 suppress_dialogs_until_swap_out_ = true;
3207 void RenderViewImpl::NavigateToSwappedOutURL(blink::WebFrame* frame) {
3208 // We use loadRequest instead of loadHTMLString because the former commits
3209 // synchronously. Otherwise a new navigation can interrupt the navigation
3210 // to kSwappedOutURL. If that happens to be to the page we had been
3211 // showing, then WebKit will never send a commit and we'll be left spinning.
3212 // TODO(creis): Until we move this to RenderFrame, we may call this from a
3213 // swapped out RenderFrame while our own is_swapped_out_ is false.
3214 RenderFrameImpl* rf = RenderFrameImpl::FromWebFrame(frame);
3215 CHECK(is_swapped_out_ || rf->is_swapped_out());
3216 GURL swappedOutURL(kSwappedOutURL);
3217 WebURLRequest request(swappedOutURL);
3218 if (frame->isWebLocalFrame())
3219 frame->loadRequest(request);
3222 void RenderViewImpl::OnClosePage() {
3223 FOR_EACH_OBSERVER(RenderViewObserver, observers_, ClosePage());
3224 // TODO(creis): We'd rather use webview()->Close() here, but that currently
3225 // sets the WebView's delegate_ to NULL, preventing any JavaScript dialogs
3226 // in the onunload handler from appearing. For now, we're bypassing that and
3227 // calling the FrameLoader's CloseURL method directly. This should be
3228 // revisited to avoid having two ways to close a page. Having a single way
3229 // to close that can run onunload is also useful for fixing
3230 // http://b/issue?id=753080.
3231 webview()->mainFrame()->dispatchUnloadEvent();
3233 Send(new ViewHostMsg_ClosePage_ACK(routing_id_));
3236 void RenderViewImpl::OnThemeChanged() {
3237 #if defined(USE_AURA)
3238 // Aura doesn't care if we switch themes.
3239 #elif defined(OS_WIN)
3240 ui::NativeThemeWin::instance()->CloseHandles();
3241 if (webview())
3242 webview()->themeChanged();
3243 #else // defined(OS_WIN)
3244 // TODO(port): we don't support theming on non-Windows platforms yet
3245 NOTIMPLEMENTED();
3246 #endif
3249 void RenderViewImpl::OnMoveOrResizeStarted() {
3250 if (webview())
3251 webview()->hidePopups();
3254 void RenderViewImpl::OnResize(const ViewMsg_Resize_Params& params) {
3255 TRACE_EVENT0("renderer", "RenderViewImpl::OnResize");
3256 if (webview()) {
3257 webview()->hidePopups();
3258 if (send_preferred_size_changes_) {
3259 webview()->mainFrame()->setCanHaveScrollbars(
3260 ShouldDisplayScrollbars(params.new_size.width(),
3261 params.new_size.height()));
3265 gfx::Size old_visible_viewport_size = visible_viewport_size_;
3267 RenderWidget::OnResize(params);
3269 if (old_visible_viewport_size != visible_viewport_size_)
3270 has_scrolled_focused_editable_node_into_rect_ = false;
3272 FOR_EACH_OBSERVER(RenderViewObserver,
3273 observers_,
3274 Resized());
3277 void RenderViewImpl::DidInitiatePaint() {
3278 #if defined(ENABLE_PLUGINS)
3279 // Notify all instances that we painted. The same caveats apply as for
3280 // ViewFlushedPaint regarding instances closing themselves, so we take
3281 // similar precautions.
3282 PepperPluginSet plugins = active_pepper_instances_;
3283 for (PepperPluginSet::iterator i = plugins.begin(); i != plugins.end(); ++i) {
3284 if (active_pepper_instances_.find(*i) != active_pepper_instances_.end())
3285 (*i)->ViewInitiatedPaint();
3287 #endif
3290 void RenderViewImpl::DidFlushPaint() {
3291 #if defined(ENABLE_PLUGINS)
3292 // Notify all instances that we flushed. This will call into the plugin, and
3293 // we it may ask to close itself as a result. This will, in turn, modify our
3294 // set, possibly invalidating the iterator. So we iterate on a copy that
3295 // won't change out from under us.
3296 PepperPluginSet plugins = active_pepper_instances_;
3297 for (PepperPluginSet::iterator i = plugins.begin(); i != plugins.end(); ++i) {
3298 // The copy above makes sure our iterator is never invalid if some plugins
3299 // are destroyed. But some plugin may decide to close all of its views in
3300 // response to a paint in one of them, so we need to make sure each one is
3301 // still "current" before using it.
3303 // It's possible that a plugin was destroyed, but another one was created
3304 // with the same address. In this case, we'll call ViewFlushedPaint on that
3305 // new plugin. But that's OK for this particular case since we're just
3306 // notifying all of our instances that the view flushed, and the new one is
3307 // one of our instances.
3309 // What about the case where a new one is created in a callback at a new
3310 // address and we don't issue the callback? We're still OK since this
3311 // callback is used for flush callbacks and we could not have possibly
3312 // started a new paint for the new plugin while processing a previous paint
3313 // for an existing one.
3314 if (active_pepper_instances_.find(*i) != active_pepper_instances_.end())
3315 (*i)->ViewFlushedPaint();
3317 #endif
3319 // If the RenderWidget is closing down then early-exit, otherwise we'll crash.
3320 // See crbug.com/112921.
3321 if (!webview())
3322 return;
3324 WebFrame* main_frame = webview()->mainFrame();
3325 for (WebFrame* frame = main_frame; frame;
3326 frame = frame->traverseNext(false)) {
3327 if (frame->isWebLocalFrame())
3328 main_frame = frame;
3331 // If we have a provisional frame we are between the start and commit stages
3332 // of loading and we don't want to save stats.
3333 if (!main_frame->provisionalDataSource()) {
3334 WebDataSource* ds = main_frame->dataSource();
3335 DocumentState* document_state = DocumentState::FromDataSource(ds);
3337 // TODO(jar): The following code should all be inside a method, probably in
3338 // NavigatorState.
3339 Time now = Time::Now();
3340 if (document_state->first_paint_time().is_null()) {
3341 document_state->set_first_paint_time(now);
3343 if (document_state->first_paint_after_load_time().is_null() &&
3344 !document_state->finish_load_time().is_null()) {
3345 document_state->set_first_paint_after_load_time(now);
3350 gfx::Vector2d RenderViewImpl::GetScrollOffset() {
3351 WebFrame* main_frame = webview()->mainFrame();
3352 for (WebFrame* frame = main_frame; frame;
3353 frame = frame->traverseNext(false)) {
3354 // TODO(nasko): This is a hack for the case in which the top-level
3355 // frame is being rendered in another process. It will not
3356 // behave correctly for out of process iframes.
3357 if (frame->isWebLocalFrame()) {
3358 main_frame = frame;
3359 break;
3363 WebSize scroll_offset = main_frame->scrollOffset();
3364 return gfx::Vector2d(scroll_offset.width, scroll_offset.height);
3367 void RenderViewImpl::OnClearFocusedElement() {
3368 if (webview())
3369 webview()->clearFocusedElement();
3372 void RenderViewImpl::OnSetBackgroundOpaque(bool opaque) {
3373 if (webview())
3374 webview()->setIsTransparent(!opaque);
3375 if (compositor_)
3376 compositor_->setHasTransparentBackground(!opaque);
3379 void RenderViewImpl::OnSetActive(bool active) {
3380 if (webview())
3381 webview()->setIsActive(active);
3383 #if defined(ENABLE_PLUGINS) && defined(OS_MACOSX)
3384 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3385 for (plugin_it = plugin_delegates_.begin();
3386 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3387 (*plugin_it)->SetWindowFocus(active);
3389 #endif
3392 #if defined(OS_MACOSX)
3393 void RenderViewImpl::OnSetWindowVisibility(bool visible) {
3394 #if defined(ENABLE_PLUGINS)
3395 // Inform plugins that their container has changed visibility.
3396 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3397 for (plugin_it = plugin_delegates_.begin();
3398 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3399 (*plugin_it)->SetContainerVisibility(visible);
3401 #endif
3404 void RenderViewImpl::OnWindowFrameChanged(const gfx::Rect& window_frame,
3405 const gfx::Rect& view_frame) {
3406 #if defined(ENABLE_PLUGINS)
3407 // Inform plugins that their window's frame has changed.
3408 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3409 for (plugin_it = plugin_delegates_.begin();
3410 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3411 (*plugin_it)->WindowFrameChanged(window_frame, view_frame);
3413 #endif
3416 void RenderViewImpl::OnPluginImeCompositionCompleted(const base::string16& text,
3417 int plugin_id) {
3418 // WebPluginDelegateProxy is responsible for figuring out if this event
3419 // applies to it or not, so inform all the delegates.
3420 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3421 for (plugin_it = plugin_delegates_.begin();
3422 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3423 (*plugin_it)->ImeCompositionCompleted(text, plugin_id);
3426 #endif // OS_MACOSX
3428 void RenderViewImpl::OnClose() {
3429 if (closing_)
3430 RenderThread::Get()->Send(new ViewHostMsg_Close_ACK(routing_id_));
3431 RenderWidget::OnClose();
3434 void RenderViewImpl::Close() {
3435 // We need to grab a pointer to the doomed WebView before we destroy it.
3436 WebView* doomed = webview();
3437 RenderWidget::Close();
3438 g_view_map.Get().erase(doomed);
3439 g_routing_id_view_map.Get().erase(routing_id_);
3440 RenderThread::Get()->Send(new ViewHostMsg_Close_ACK(routing_id_));
3443 void RenderViewImpl::DidHandleKeyEvent() {
3444 ClearEditCommands();
3447 bool RenderViewImpl::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
3448 possible_drag_event_info_.event_source =
3449 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE;
3450 possible_drag_event_info_.event_location =
3451 gfx::Point(event.globalX, event.globalY);
3453 #if defined(ENABLE_PLUGINS)
3454 // This method is called for every mouse event that the render view receives.
3455 // And then the mouse event is forwarded to WebKit, which dispatches it to the
3456 // event target. Potentially a Pepper plugin will receive the event.
3457 // In order to tell whether a plugin gets the last mouse event and which it
3458 // is, we set |pepper_last_mouse_event_target_| to NULL here. If a plugin gets
3459 // the event, it will notify us via DidReceiveMouseEvent() and set itself as
3460 // |pepper_last_mouse_event_target_|.
3461 pepper_last_mouse_event_target_ = NULL;
3462 #endif
3464 // If the mouse is locked, only the current owner of the mouse lock can
3465 // process mouse events.
3466 return mouse_lock_dispatcher_->WillHandleMouseEvent(event);
3469 bool RenderViewImpl::WillHandleGestureEvent(
3470 const blink::WebGestureEvent& event) {
3471 possible_drag_event_info_.event_source =
3472 ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH;
3473 possible_drag_event_info_.event_location =
3474 gfx::Point(event.globalX, event.globalY);
3475 return false;
3478 void RenderViewImpl::DidHandleMouseEvent(const WebMouseEvent& event) {
3479 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidHandleMouseEvent(event));
3482 void RenderViewImpl::DidHandleTouchEvent(const WebTouchEvent& event) {
3483 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidHandleTouchEvent(event));
3486 bool RenderViewImpl::HasTouchEventHandlersAt(const gfx::Point& point) const {
3487 if (!webview())
3488 return false;
3489 return webview()->hasTouchEventHandlersAt(point);
3492 void RenderViewImpl::OnWasHidden() {
3493 RenderWidget::OnWasHidden();
3495 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3496 RenderThreadImpl::current()->video_capture_impl_manager()->
3497 SuspendDevices(true);
3498 if (speech_recognition_dispatcher_)
3499 speech_recognition_dispatcher_->AbortAllRecognitions();
3500 #endif
3502 if (webview())
3503 webview()->setVisibilityState(visibilityState(), false);
3505 #if defined(ENABLE_PLUGINS)
3506 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3507 i != active_pepper_instances_.end(); ++i)
3508 (*i)->PageVisibilityChanged(false);
3510 #if defined(OS_MACOSX)
3511 // Inform NPAPI plugins that their container is no longer visible.
3512 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3513 for (plugin_it = plugin_delegates_.begin();
3514 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3515 (*plugin_it)->SetContainerVisibility(false);
3517 #endif // OS_MACOSX
3518 #endif // ENABLE_PLUGINS
3521 void RenderViewImpl::OnWasShown(bool needs_repainting,
3522 const ui::LatencyInfo& latency_info) {
3523 RenderWidget::OnWasShown(needs_repainting, latency_info);
3525 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3526 RenderThreadImpl::current()->video_capture_impl_manager()->
3527 SuspendDevices(false);
3528 #endif
3530 if (webview())
3531 webview()->setVisibilityState(visibilityState(), false);
3533 #if defined(ENABLE_PLUGINS)
3534 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3535 i != active_pepper_instances_.end(); ++i)
3536 (*i)->PageVisibilityChanged(true);
3538 #if defined(OS_MACOSX)
3539 // Inform NPAPI plugins that their container is now visible.
3540 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3541 for (plugin_it = plugin_delegates_.begin();
3542 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3543 (*plugin_it)->SetContainerVisibility(true);
3545 #endif // OS_MACOSX
3546 #endif // ENABLE_PLUGINS
3549 GURL RenderViewImpl::GetURLForGraphicsContext3D() {
3550 DCHECK(webview());
3551 if (webview()->mainFrame()->isWebLocalFrame())
3552 return GURL(webview()->mainFrame()->document().url());
3553 else
3554 return GURL("chrome://gpu/RenderViewImpl::CreateGraphicsContext3D");
3557 void RenderViewImpl::OnSetFocus(bool enable) {
3558 RenderWidget::OnSetFocus(enable);
3560 #if defined(ENABLE_PLUGINS)
3561 if (webview() && webview()->isActive()) {
3562 // Notify all NPAPI plugins.
3563 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3564 for (plugin_it = plugin_delegates_.begin();
3565 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3566 #if defined(OS_MACOSX)
3567 // RenderWidget's call to setFocus can cause the underlying webview's
3568 // activation state to change just like a call to setIsActive.
3569 if (enable)
3570 (*plugin_it)->SetWindowFocus(true);
3571 #endif
3572 (*plugin_it)->SetContentAreaFocus(enable);
3575 // Notify all Pepper plugins.
3576 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3577 i != active_pepper_instances_.end(); ++i)
3578 (*i)->SetContentAreaFocus(enable);
3579 #endif
3580 // Notify all BrowserPlugins of the RenderView's focus state.
3581 if (browser_plugin_manager_.get())
3582 browser_plugin_manager_->UpdateFocusState();
3585 void RenderViewImpl::OnImeSetComposition(
3586 const base::string16& text,
3587 const std::vector<blink::WebCompositionUnderline>& underlines,
3588 int selection_start,
3589 int selection_end) {
3590 #if defined(ENABLE_PLUGINS)
3591 if (focused_pepper_plugin_) {
3592 focused_pepper_plugin_->render_frame()->OnImeSetComposition(
3593 text, underlines, selection_start, selection_end);
3594 return;
3597 #if defined(OS_WIN)
3598 // When a plug-in has focus, we create platform-specific IME data used by
3599 // our IME emulator and send it directly to the focused plug-in, i.e. we
3600 // bypass WebKit. (WebPluginDelegate dispatches this IME data only when its
3601 // instance ID is the same one as the specified ID.)
3602 if (focused_plugin_id_ >= 0) {
3603 std::vector<int> clauses;
3604 std::vector<int> target;
3605 for (size_t i = 0; i < underlines.size(); ++i) {
3606 clauses.push_back(underlines[i].startOffset);
3607 clauses.push_back(underlines[i].endOffset);
3608 if (underlines[i].thick) {
3609 target.clear();
3610 target.push_back(underlines[i].startOffset);
3611 target.push_back(underlines[i].endOffset);
3614 std::set<WebPluginDelegateProxy*>::iterator it;
3615 for (it = plugin_delegates_.begin(); it != plugin_delegates_.end(); ++it) {
3616 (*it)->ImeCompositionUpdated(text, clauses, target, selection_end,
3617 focused_plugin_id_);
3619 return;
3621 #endif // OS_WIN
3622 #endif // ENABLE_PLUGINS
3623 RenderWidget::OnImeSetComposition(text,
3624 underlines,
3625 selection_start,
3626 selection_end);
3629 void RenderViewImpl::OnImeConfirmComposition(
3630 const base::string16& text,
3631 const gfx::Range& replacement_range,
3632 bool keep_selection) {
3633 #if defined(ENABLE_PLUGINS)
3634 if (focused_pepper_plugin_) {
3635 focused_pepper_plugin_->render_frame()->OnImeConfirmComposition(
3636 text, replacement_range, keep_selection);
3637 return;
3639 #if defined(OS_WIN)
3640 // Same as OnImeSetComposition(), we send the text from IMEs directly to
3641 // plug-ins. When we send IME text directly to plug-ins, we should not send
3642 // it to WebKit to prevent WebKit from controlling IMEs.
3643 // TODO(thakis): Honor |replacement_range| for plugins?
3644 if (focused_plugin_id_ >= 0) {
3645 std::set<WebPluginDelegateProxy*>::iterator it;
3646 for (it = plugin_delegates_.begin();
3647 it != plugin_delegates_.end(); ++it) {
3648 (*it)->ImeCompositionCompleted(text, focused_plugin_id_);
3650 return;
3652 #endif // OS_WIN
3653 #endif // ENABLE_PLUGINS
3654 if (replacement_range.IsValid() && webview()) {
3655 // Select the text in |replacement_range|, it will then be replaced by
3656 // text added by the call to RenderWidget::OnImeConfirmComposition().
3657 if (WebLocalFrame* frame = webview()->focusedFrame()->toWebLocalFrame()) {
3658 WebRange webrange = WebRange::fromDocumentRange(
3659 frame, replacement_range.start(), replacement_range.length());
3660 if (!webrange.isNull())
3661 frame->selectRange(webrange);
3664 RenderWidget::OnImeConfirmComposition(text,
3665 replacement_range,
3666 keep_selection);
3669 void RenderViewImpl::SetDeviceScaleFactor(float device_scale_factor) {
3670 RenderWidget::SetDeviceScaleFactor(device_scale_factor);
3671 if (webview()) {
3672 webview()->setDeviceScaleFactor(device_scale_factor);
3673 webview()->settings()->setPreferCompositingToLCDTextEnabled(
3674 PreferCompositingToLCDText(device_scale_factor_));
3675 webview()->settings()->setAcceleratedCompositingForTransitionEnabled(
3676 ShouldUseTransitionCompositing(device_scale_factor_));
3678 if (auto_resize_mode_)
3679 AutoResizeCompositor();
3681 if (browser_plugin_manager_.get())
3682 browser_plugin_manager_->UpdateDeviceScaleFactor();
3685 bool RenderViewImpl::SetDeviceColorProfile(
3686 const std::vector<char>& profile) {
3687 bool changed = RenderWidget::SetDeviceColorProfile(profile);
3688 if (changed && webview()) {
3689 WebVector<char> colorProfile = profile;
3690 webview()->setDeviceColorProfile(colorProfile);
3692 return changed;
3695 void RenderViewImpl::ResetDeviceColorProfileForTesting() {
3696 RenderWidget::ResetDeviceColorProfileForTesting();
3697 if (webview())
3698 webview()->resetDeviceColorProfile();
3701 ui::TextInputType RenderViewImpl::GetTextInputType() {
3702 #if defined(ENABLE_PLUGINS)
3703 if (focused_pepper_plugin_)
3704 return focused_pepper_plugin_->text_input_type();
3705 #endif
3706 return RenderWidget::GetTextInputType();
3709 void RenderViewImpl::GetSelectionBounds(gfx::Rect* start, gfx::Rect* end) {
3710 #if defined(ENABLE_PLUGINS)
3711 if (focused_pepper_plugin_) {
3712 // TODO(kinaba) http://crbug.com/101101
3713 // Current Pepper IME API does not handle selection bounds. So we simply
3714 // use the caret position as an empty range for now. It will be updated
3715 // after Pepper API equips features related to surrounding text retrieval.
3716 gfx::Rect caret = focused_pepper_plugin_->GetCaretBounds();
3717 *start = caret;
3718 *end = caret;
3719 return;
3721 #endif
3722 RenderWidget::GetSelectionBounds(start, end);
3725 #if defined(OS_MACOSX) || defined(USE_AURA)
3726 void RenderViewImpl::GetCompositionCharacterBounds(
3727 std::vector<gfx::Rect>* bounds) {
3728 DCHECK(bounds);
3729 bounds->clear();
3731 #if defined(ENABLE_PLUGINS)
3732 if (focused_pepper_plugin_) {
3733 return;
3735 #endif
3737 if (!webview())
3738 return;
3739 size_t start_offset = 0;
3740 size_t character_count = 0;
3741 if (!webview()->compositionRange(&start_offset, &character_count))
3742 return;
3743 if (character_count == 0)
3744 return;
3746 blink::WebFrame* frame = webview()->focusedFrame();
3747 if (!frame)
3748 return;
3750 bounds->reserve(character_count);
3751 blink::WebRect webrect;
3752 for (size_t i = 0; i < character_count; ++i) {
3753 if (!frame->firstRectForCharacterRange(start_offset + i, 1, webrect)) {
3754 DLOG(ERROR) << "Could not retrieve character rectangle at " << i;
3755 bounds->clear();
3756 return;
3758 bounds->push_back(webrect);
3762 void RenderViewImpl::GetCompositionRange(gfx::Range* range) {
3763 #if defined(ENABLE_PLUGINS)
3764 if (focused_pepper_plugin_) {
3765 return;
3767 #endif
3768 RenderWidget::GetCompositionRange(range);
3770 #endif
3772 bool RenderViewImpl::CanComposeInline() {
3773 #if defined(ENABLE_PLUGINS)
3774 if (focused_pepper_plugin_)
3775 return focused_pepper_plugin_->IsPluginAcceptingCompositionEvents();
3776 #endif
3777 return true;
3780 void RenderViewImpl::InstrumentWillBeginFrame(int frame_id) {
3781 if (!webview())
3782 return;
3783 if (!webview()->devToolsAgent())
3784 return;
3785 webview()->devToolsAgent()->didBeginFrame(frame_id);
3788 void RenderViewImpl::InstrumentDidBeginFrame() {
3789 if (!webview())
3790 return;
3791 if (!webview()->devToolsAgent())
3792 return;
3793 // TODO(jamesr/caseq): Decide if this needs to be renamed.
3794 webview()->devToolsAgent()->didComposite();
3797 void RenderViewImpl::InstrumentDidCancelFrame() {
3798 if (!webview())
3799 return;
3800 if (!webview()->devToolsAgent())
3801 return;
3802 webview()->devToolsAgent()->didCancelFrame();
3805 void RenderViewImpl::InstrumentWillComposite() {
3806 if (!webview())
3807 return;
3808 if (!webview()->devToolsAgent())
3809 return;
3810 webview()->devToolsAgent()->willComposite();
3813 void RenderViewImpl::SetScreenMetricsEmulationParameters(
3814 float device_scale_factor,
3815 const gfx::Point& root_layer_offset,
3816 float root_layer_scale) {
3817 if (webview() && compositor()) {
3818 webview()->setCompositorDeviceScaleFactorOverride(device_scale_factor);
3819 webview()->setRootLayerTransform(
3820 blink::WebSize(root_layer_offset.x(), root_layer_offset.y()),
3821 root_layer_scale);
3825 bool RenderViewImpl::ScheduleFileChooser(
3826 const FileChooserParams& params,
3827 WebFileChooserCompletion* completion) {
3828 static const size_t kMaximumPendingFileChooseRequests = 4;
3829 if (file_chooser_completions_.size() > kMaximumPendingFileChooseRequests) {
3830 // This sanity check prevents too many file choose requests from getting
3831 // queued which could DoS the user. Getting these is most likely a
3832 // programming error (there are many ways to DoS the user so it's not
3833 // considered a "real" security check), either in JS requesting many file
3834 // choosers to pop up, or in a plugin.
3836 // TODO(brettw) we might possibly want to require a user gesture to open
3837 // a file picker, which will address this issue in a better way.
3838 return false;
3841 file_chooser_completions_.push_back(linked_ptr<PendingFileChooser>(
3842 new PendingFileChooser(params, completion)));
3843 if (file_chooser_completions_.size() == 1) {
3844 // Actually show the browse dialog when this is the first request.
3845 Send(new ViewHostMsg_RunFileChooser(routing_id_, params));
3847 return true;
3850 blink::WebSpeechRecognizer* RenderViewImpl::speechRecognizer() {
3851 if (!speech_recognition_dispatcher_)
3852 speech_recognition_dispatcher_ = new SpeechRecognitionDispatcher(this);
3853 return speech_recognition_dispatcher_;
3856 void RenderViewImpl::zoomLimitsChanged(double minimum_level,
3857 double maximum_level) {
3858 int minimum_percent = static_cast<int>(
3859 ZoomLevelToZoomFactor(minimum_level) * 100);
3860 int maximum_percent = static_cast<int>(
3861 ZoomLevelToZoomFactor(maximum_level) * 100);
3863 Send(new ViewHostMsg_UpdateZoomLimits(
3864 routing_id_, minimum_percent, maximum_percent));
3867 void RenderViewImpl::zoomLevelChanged() {
3868 double zoom_level = webview()->zoomLevel();
3870 // Do not send empty URLs to the browser when we are just setting the default
3871 // zoom level (from RendererPreferences) before the first navigation.
3872 if (!webview()->mainFrame()->document().url().isEmpty()) {
3873 // Tell the browser which url got zoomed so it can update the menu and the
3874 // saved values if necessary
3875 Send(new ViewHostMsg_DidZoomURL(
3876 routing_id_, zoom_level,
3877 GURL(webview()->mainFrame()->document().url())));
3881 double RenderViewImpl::zoomLevelToZoomFactor(double zoom_level) const {
3882 return ZoomLevelToZoomFactor(zoom_level);
3885 double RenderViewImpl::zoomFactorToZoomLevel(double factor) const {
3886 return ZoomFactorToZoomLevel(factor);
3889 void RenderViewImpl::registerProtocolHandler(const WebString& scheme,
3890 const WebURL& url,
3891 const WebString& title) {
3892 bool user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
3893 Send(new ViewHostMsg_RegisterProtocolHandler(routing_id_,
3894 base::UTF16ToUTF8(scheme),
3895 url,
3896 title,
3897 user_gesture));
3900 void RenderViewImpl::unregisterProtocolHandler(const WebString& scheme,
3901 const WebURL& url) {
3902 bool user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
3903 Send(new ViewHostMsg_UnregisterProtocolHandler(routing_id_,
3904 base::UTF16ToUTF8(scheme),
3905 url,
3906 user_gesture));
3909 blink::WebPageVisibilityState RenderViewImpl::visibilityState() const {
3910 blink::WebPageVisibilityState current_state = is_hidden() ?
3911 blink::WebPageVisibilityStateHidden :
3912 blink::WebPageVisibilityStateVisible;
3913 blink::WebPageVisibilityState override_state = current_state;
3914 // TODO(jam): move this method to WebFrameClient.
3915 if (GetContentClient()->renderer()->
3916 ShouldOverridePageVisibilityState(main_render_frame_.get(),
3917 &override_state))
3918 return override_state;
3919 return current_state;
3922 blink::WebPushClient* RenderViewImpl::webPushClient() {
3923 // TODO(mvanouwerkerk): Remove this method once the Push API code in Blink
3924 // has also switched over to Frame.
3925 return main_render_frame_->pushClient();
3928 void RenderViewImpl::draggableRegionsChanged() {
3929 FOR_EACH_OBSERVER(
3930 RenderViewObserver,
3931 observers_,
3932 DraggableRegionsChanged(webview()->mainFrame()));
3935 #if defined(OS_ANDROID)
3936 WebContentDetectionResult RenderViewImpl::detectContentAround(
3937 const WebHitTestResult& touch_hit) {
3938 DCHECK(!touch_hit.isNull());
3939 DCHECK(!touch_hit.node().isNull());
3940 DCHECK(touch_hit.node().isTextNode());
3942 // Process the position with all the registered content detectors until
3943 // a match is found. Priority is provided by their relative order.
3944 for (ContentDetectorList::const_iterator it = content_detectors_.begin();
3945 it != content_detectors_.end(); ++it) {
3946 ContentDetector::Result content = (*it)->FindTappedContent(touch_hit);
3947 if (content.valid) {
3948 return WebContentDetectionResult(content.content_boundaries,
3949 base::UTF8ToUTF16(content.text), content.intent_url);
3952 return WebContentDetectionResult();
3955 void RenderViewImpl::scheduleContentIntent(const WebURL& intent) {
3956 // Introduce a short delay so that the user can notice the content.
3957 base::MessageLoop::current()->PostDelayedTask(
3958 FROM_HERE,
3959 base::Bind(&RenderViewImpl::LaunchAndroidContentIntent,
3960 AsWeakPtr(),
3961 intent,
3962 expected_content_intent_id_),
3963 base::TimeDelta::FromMilliseconds(kContentIntentDelayMilliseconds));
3966 void RenderViewImpl::cancelScheduledContentIntents() {
3967 ++expected_content_intent_id_;
3970 void RenderViewImpl::LaunchAndroidContentIntent(const GURL& intent,
3971 size_t request_id) {
3972 if (request_id != expected_content_intent_id_)
3973 return;
3975 // Remove the content highlighting if any.
3976 scheduleComposite();
3978 if (!intent.is_empty())
3979 Send(new ViewHostMsg_StartContentIntent(routing_id_, intent));
3982 bool RenderViewImpl::openDateTimeChooser(
3983 const blink::WebDateTimeChooserParams& params,
3984 blink::WebDateTimeChooserCompletion* completion) {
3985 // JavaScript may try to open a date time chooser while one is already open.
3986 if (date_time_picker_client_)
3987 return false;
3988 date_time_picker_client_.reset(
3989 new RendererDateTimePicker(this, params, completion));
3990 return date_time_picker_client_->Open();
3993 void RenderViewImpl::DismissDateTimeDialog() {
3994 DCHECK(date_time_picker_client_);
3995 date_time_picker_client_.reset(NULL);
3998 #endif // defined(OS_ANDROID)
4000 void RenderViewImpl::OnShowContextMenu(
4001 ui::MenuSourceType source_type, const gfx::Point& location) {
4002 context_menu_source_type_ = source_type;
4003 has_host_context_menu_location_ = true;
4004 host_context_menu_location_ = location;
4005 if (webview())
4006 webview()->showContextMenu();
4007 has_host_context_menu_location_ = false;
4010 void RenderViewImpl::OnEnableViewSourceMode() {
4011 if (!webview())
4012 return;
4013 WebFrame* main_frame = webview()->mainFrame();
4014 if (!main_frame)
4015 return;
4016 main_frame->enableViewSourceMode(true);
4019 #if defined(OS_ANDROID) || defined(TOOLKIT_VIEWS)
4020 bool RenderViewImpl::didTapMultipleTargets(
4021 const WebSize& inner_viewport_offset,
4022 const WebRect& touch_rect,
4023 const WebVector<WebRect>& target_rects) {
4024 // Never show a disambiguation popup when accessibility is enabled,
4025 // as this interferes with "touch exploration".
4026 AccessibilityMode accessibility_mode =
4027 GetMainRenderFrame()->accessibility_mode();
4028 bool matches_accessibility_mode_complete =
4029 (accessibility_mode & AccessibilityModeComplete) ==
4030 AccessibilityModeComplete;
4031 if (matches_accessibility_mode_complete)
4032 return false;
4034 // The touch_rect, target_rects and zoom_rect are in the outer viewport
4035 // reference frame.
4036 gfx::Rect zoom_rect;
4037 float new_total_scale =
4038 DisambiguationPopupHelper::ComputeZoomAreaAndScaleFactor(
4039 touch_rect, target_rects, GetSize(),
4040 gfx::Rect(webview()->mainFrame()->visibleContentRect()).size(),
4041 device_scale_factor_ * webview()->pageScaleFactor(), &zoom_rect);
4042 if (!new_total_scale)
4043 return false;
4045 bool handled = false;
4046 switch (renderer_preferences_.tap_multiple_targets_strategy) {
4047 case TAP_MULTIPLE_TARGETS_STRATEGY_ZOOM:
4048 handled = webview()->zoomToMultipleTargetsRect(zoom_rect);
4049 break;
4050 case TAP_MULTIPLE_TARGETS_STRATEGY_POPUP: {
4051 gfx::Size canvas_size =
4052 gfx::ToCeiledSize(gfx::ScaleSize(zoom_rect.size(), new_total_scale));
4053 cc::SharedBitmapManager* manager =
4054 RenderThreadImpl::current()->shared_bitmap_manager();
4055 scoped_ptr<cc::SharedBitmap> shared_bitmap =
4056 manager->AllocateSharedBitmap(canvas_size);
4058 SkBitmap bitmap;
4059 SkImageInfo info = SkImageInfo::MakeN32Premul(canvas_size.width(),
4060 canvas_size.height());
4061 bitmap.installPixels(info, shared_bitmap->pixels(), info.minRowBytes());
4062 SkCanvas canvas(bitmap);
4064 // TODO(trchen): Cleanup the device scale factor mess.
4065 // device scale will be applied in WebKit
4066 // --> zoom_rect doesn't include device scale,
4067 // but WebKit will still draw on zoom_rect * device_scale_factor_
4068 canvas.scale(new_total_scale / device_scale_factor_,
4069 new_total_scale / device_scale_factor_);
4070 canvas.translate(-zoom_rect.x() * device_scale_factor_,
4071 -zoom_rect.y() * device_scale_factor_);
4073 DCHECK(webwidget_->isAcceleratedCompositingActive());
4074 // TODO(aelias): The disambiguation popup should be composited so we
4075 // don't have to call this method.
4076 webwidget_->paintCompositedDeprecated(&canvas, zoom_rect);
4079 gfx::Rect zoom_rect_in_screen =
4080 zoom_rect - gfx::Vector2d(inner_viewport_offset.width,
4081 inner_viewport_offset.height);
4083 gfx::Rect physical_window_zoom_rect = gfx::ToEnclosingRect(
4084 ClientRectToPhysicalWindowRect(gfx::RectF(zoom_rect_in_screen)));
4086 Send(new ViewHostMsg_ShowDisambiguationPopup(routing_id_,
4087 physical_window_zoom_rect,
4088 canvas_size,
4089 shared_bitmap->id()));
4090 cc::SharedBitmapId id = shared_bitmap->id();
4091 disambiguation_bitmaps_[id] = shared_bitmap.release();
4092 handled = true;
4093 break;
4095 case TAP_MULTIPLE_TARGETS_STRATEGY_NONE:
4096 // No-op.
4097 break;
4100 return handled;
4102 #endif // defined(OS_ANDROID) || defined(TOOLKIT_VIEWS)
4104 unsigned RenderViewImpl::GetLocalSessionHistoryLengthForTesting() const {
4105 return history_list_length_;
4108 void RenderViewImpl::SetFocusAndActivateForTesting(bool enable) {
4109 if (enable) {
4110 if (has_focus())
4111 return;
4112 OnSetActive(true);
4113 OnSetFocus(true);
4114 } else {
4115 if (!has_focus())
4116 return;
4117 OnSetFocus(false);
4118 OnSetActive(false);
4122 void RenderViewImpl::SetDeviceScaleFactorForTesting(float factor) {
4123 ViewMsg_Resize_Params params;
4124 params.screen_info = screen_info_;
4125 params.screen_info.deviceScaleFactor = factor;
4126 params.new_size = size();
4127 params.physical_backing_size =
4128 gfx::ToCeiledSize(gfx::ScaleSize(size(), factor));
4129 params.top_controls_layout_height = 0.f;
4130 params.resizer_rect = WebRect();
4131 params.is_fullscreen = is_fullscreen();
4132 OnResize(params);
4135 void RenderViewImpl::SetDeviceColorProfileForTesting(
4136 const std::vector<char>& color_profile) {
4137 SetDeviceColorProfile(color_profile);
4140 void RenderViewImpl::ForceResizeForTesting(const gfx::Size& new_size) {
4141 gfx::Rect new_position(rootWindowRect().x,
4142 rootWindowRect().y,
4143 new_size.width(),
4144 new_size.height());
4145 ResizeSynchronously(new_position);
4148 void RenderViewImpl::UseSynchronousResizeModeForTesting(bool enable) {
4149 resizing_mode_selector_->set_is_synchronous_mode(enable);
4152 void RenderViewImpl::EnableAutoResizeForTesting(const gfx::Size& min_size,
4153 const gfx::Size& max_size) {
4154 OnEnableAutoResize(min_size, max_size);
4157 void RenderViewImpl::DisableAutoResizeForTesting(const gfx::Size& new_size) {
4158 OnDisableAutoResize(new_size);
4161 void RenderViewImpl::OnReleaseDisambiguationPopupBitmap(
4162 const cc::SharedBitmapId& id) {
4163 BitmapMap::iterator it = disambiguation_bitmaps_.find(id);
4164 DCHECK(it != disambiguation_bitmaps_.end());
4165 delete it->second;
4166 disambiguation_bitmaps_.erase(it);
4169 void RenderViewImpl::DidCommitCompositorFrame() {
4170 RenderWidget::DidCommitCompositorFrame();
4171 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidCommitCompositorFrame());
4174 void RenderViewImpl::SendUpdateFaviconURL(const std::vector<FaviconURL>& urls) {
4175 if (!urls.empty())
4176 Send(new ViewHostMsg_UpdateFaviconURL(routing_id_, urls));
4179 void RenderViewImpl::DidStopLoadingIcons() {
4180 int icon_types = WebIconURL::TypeFavicon;
4181 if (TouchEnabled())
4182 icon_types |= WebIconURL::TypeTouchPrecomposed | WebIconURL::TypeTouch;
4184 WebVector<WebIconURL> icon_urls =
4185 webview()->mainFrame()->iconURLs(icon_types);
4187 std::vector<FaviconURL> urls;
4188 for (size_t i = 0; i < icon_urls.size(); i++) {
4189 WebURL url = icon_urls[i].iconURL();
4190 std::vector<gfx::Size> sizes;
4191 ConvertToFaviconSizes(icon_urls[i].sizes(), &sizes);
4192 if (!url.isEmpty())
4193 urls.push_back(
4194 FaviconURL(url, ToFaviconType(icon_urls[i].iconType()), sizes));
4196 SendUpdateFaviconURL(urls);
4199 } // namespace content