Update linux-release/sizes/chrome-data expectations.
[chromium-blink-merge.git] / content / renderer / render_view_impl.cc
blob203ee4bf33b1a3fbbc2b38b4f240c3c975d79cbc
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/database_messages.h"
44 #include "content/common/dom_storage/dom_storage_types.h"
45 #include "content/common/drag_messages.h"
46 #include "content/common/frame_messages.h"
47 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
48 #include "content/common/input_messages.h"
49 #include "content/common/pepper_messages.h"
50 #include "content/common/socket_stream_handle_data.h"
51 #include "content/common/ssl_status_serialization.h"
52 #include "content/common/view_messages.h"
53 #include "content/public/common/bindings_policy.h"
54 #include "content/public/common/content_client.h"
55 #include "content/public/common/content_constants.h"
56 #include "content/public/common/content_switches.h"
57 #include "content/public/common/drop_data.h"
58 #include "content/public/common/favicon_url.h"
59 #include "content/public/common/file_chooser_params.h"
60 #include "content/public/common/page_zoom.h"
61 #include "content/public/common/ssl_status.h"
62 #include "content/public/common/three_d_api_types.h"
63 #include "content/public/common/url_constants.h"
64 #include "content/public/common/url_utils.h"
65 #include "content/public/common/web_preferences.h"
66 #include "content/public/renderer/content_renderer_client.h"
67 #include "content/public/renderer/document_state.h"
68 #include "content/public/renderer/navigation_state.h"
69 #include "content/public/renderer/render_view_observer.h"
70 #include "content/public/renderer/render_view_visitor.h"
71 #include "content/renderer/accessibility/renderer_accessibility.h"
72 #include "content/renderer/accessibility/renderer_accessibility_complete.h"
73 #include "content/renderer/accessibility/renderer_accessibility_focus_only.h"
74 #include "content/renderer/browser_plugin/browser_plugin.h"
75 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
76 #include "content/renderer/browser_plugin/browser_plugin_manager_impl.h"
77 #include "content/renderer/devtools/devtools_agent.h"
78 #include "content/renderer/disambiguation_popup_helper.h"
79 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
80 #include "content/renderer/drop_data_builder.h"
81 #include "content/renderer/gpu/render_widget_compositor.h"
82 #include "content/renderer/history_controller.h"
83 #include "content/renderer/history_serialization.h"
84 #include "content/renderer/idle_user_detector.h"
85 #include "content/renderer/ime_event_guard.h"
86 #include "content/renderer/input/input_handler_manager.h"
87 #include "content/renderer/internal_document_state_data.h"
88 #include "content/renderer/media/audio_device_factory.h"
89 #include "content/renderer/media/video_capture_impl_manager.h"
90 #include "content/renderer/memory_benchmarking_extension.h"
91 #include "content/renderer/mhtml_generator.h"
92 #include "content/renderer/net_info_helper.h"
93 #include "content/renderer/render_frame_impl.h"
94 #include "content/renderer/render_frame_proxy.h"
95 #include "content/renderer/render_process.h"
96 #include "content/renderer/render_thread_impl.h"
97 #include "content/renderer/render_view_impl_params.h"
98 #include "content/renderer/render_view_mouse_lock_dispatcher.h"
99 #include "content/renderer/render_widget_fullscreen_pepper.h"
100 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
101 #include "content/renderer/resizing_mode_selector.h"
102 #include "content/renderer/savable_resources.h"
103 #include "content/renderer/skia_benchmarking_extension.h"
104 #include "content/renderer/speech_recognition_dispatcher.h"
105 #include "content/renderer/stats_collection_controller.h"
106 #include "content/renderer/stats_collection_observer.h"
107 #include "content/renderer/text_input_client_observer.h"
108 #include "content/renderer/v8_value_converter_impl.h"
109 #include "content/renderer/web_ui_extension.h"
110 #include "content/renderer/web_ui_extension_data.h"
111 #include "content/renderer/web_ui_mojo.h"
112 #include "content/renderer/websharedworker_proxy.h"
113 #include "media/audio/audio_output_device.h"
114 #include "media/base/media_switches.h"
115 #include "media/filters/audio_renderer_impl.h"
116 #include "media/filters/gpu_video_accelerator_factories.h"
117 #include "net/base/data_url.h"
118 #include "net/base/escape.h"
119 #include "net/base/net_errors.h"
120 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
121 #include "net/http/http_util.h"
122 #include "third_party/WebKit/public/platform/WebCString.h"
123 #include "third_party/WebKit/public/platform/WebConnectionType.h"
124 #include "third_party/WebKit/public/platform/WebDragData.h"
125 #include "third_party/WebKit/public/platform/WebHTTPBody.h"
126 #include "third_party/WebKit/public/platform/WebImage.h"
127 #include "third_party/WebKit/public/platform/WebMessagePortChannel.h"
128 #include "third_party/WebKit/public/platform/WebPoint.h"
129 #include "third_party/WebKit/public/platform/WebRect.h"
130 #include "third_party/WebKit/public/platform/WebSize.h"
131 #include "third_party/WebKit/public/platform/WebSocketStreamHandle.h"
132 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
133 #include "third_party/WebKit/public/platform/WebString.h"
134 #include "third_party/WebKit/public/platform/WebURL.h"
135 #include "third_party/WebKit/public/platform/WebURLError.h"
136 #include "third_party/WebKit/public/platform/WebURLRequest.h"
137 #include "third_party/WebKit/public/platform/WebURLResponse.h"
138 #include "third_party/WebKit/public/platform/WebVector.h"
139 #include "third_party/WebKit/public/web/WebAXObject.h"
140 #include "third_party/WebKit/public/web/WebColorName.h"
141 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
142 #include "third_party/WebKit/public/web/WebDOMEvent.h"
143 #include "third_party/WebKit/public/web/WebDOMMessageEvent.h"
144 #include "third_party/WebKit/public/web/WebDataSource.h"
145 #include "third_party/WebKit/public/web/WebDateTimeChooserCompletion.h"
146 #include "third_party/WebKit/public/web/WebDateTimeChooserParams.h"
147 #include "third_party/WebKit/public/web/WebDevToolsAgent.h"
148 #include "third_party/WebKit/public/web/WebDocument.h"
149 #include "third_party/WebKit/public/web/WebElement.h"
150 #include "third_party/WebKit/public/web/WebFileChooserParams.h"
151 #include "third_party/WebKit/public/web/WebFindOptions.h"
152 #include "third_party/WebKit/public/web/WebFormControlElement.h"
153 #include "third_party/WebKit/public/web/WebFormElement.h"
154 #include "third_party/WebKit/public/web/WebFrame.h"
155 #include "third_party/WebKit/public/web/WebGlyphCache.h"
156 #include "third_party/WebKit/public/web/WebHistoryItem.h"
157 #include "third_party/WebKit/public/web/WebHitTestResult.h"
158 #include "third_party/WebKit/public/web/WebInputElement.h"
159 #include "third_party/WebKit/public/web/WebInputEvent.h"
160 #include "third_party/WebKit/public/web/WebKit.h"
161 #include "third_party/WebKit/public/web/WebLocalFrame.h"
162 #include "third_party/WebKit/public/web/WebMediaPlayerAction.h"
163 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
164 #include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
165 #include "third_party/WebKit/public/web/WebNodeList.h"
166 #include "third_party/WebKit/public/web/WebPageSerializer.h"
167 #include "third_party/WebKit/public/web/WebPlugin.h"
168 #include "third_party/WebKit/public/web/WebPluginAction.h"
169 #include "third_party/WebKit/public/web/WebPluginContainer.h"
170 #include "third_party/WebKit/public/web/WebPluginDocument.h"
171 #include "third_party/WebKit/public/web/WebRange.h"
172 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
173 #include "third_party/WebKit/public/web/WebScriptSource.h"
174 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
175 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
176 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
177 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
178 #include "third_party/WebKit/public/web/WebSettings.h"
179 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
180 #include "third_party/WebKit/public/web/WebView.h"
181 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
182 #include "third_party/WebKit/public/web/default/WebRenderTheme.h"
183 #include "third_party/icu/source/common/unicode/uchar.h"
184 #include "third_party/icu/source/common/unicode/uscript.h"
185 #include "ui/base/clipboard/clipboard.h"
186 #include "ui/base/ui_base_switches_util.h"
187 #include "ui/events/latency_info.h"
188 #include "ui/gfx/native_widget_types.h"
189 #include "ui/gfx/point.h"
190 #include "ui/gfx/rect.h"
191 #include "ui/gfx/rect_conversions.h"
192 #include "ui/gfx/size_conversions.h"
193 #include "ui/shell_dialogs/selected_file_info.h"
194 #include "v8/include/v8.h"
196 #if defined(OS_ANDROID)
197 #include <cpu-features.h>
199 #include "content/renderer/android/address_detector.h"
200 #include "content/renderer/android/content_detector.h"
201 #include "content/renderer/android/email_detector.h"
202 #include "content/renderer/android/phone_number_detector.h"
203 #include "net/android/network_library.h"
204 #include "skia/ext/platform_canvas.h"
205 #include "third_party/WebKit/public/platform/WebFloatPoint.h"
206 #include "third_party/WebKit/public/platform/WebFloatRect.h"
207 #include "ui/gfx/rect_f.h"
209 #elif defined(OS_WIN)
210 // TODO(port): these files are currently Windows only because they concern:
211 // * theming
212 #include "ui/native_theme/native_theme_win.h"
213 #elif defined(USE_X11)
214 #include "ui/native_theme/native_theme.h"
215 #elif defined(OS_MACOSX)
216 #include "skia/ext/skia_utils_mac.h"
217 #endif
219 #if defined(ENABLE_PLUGINS)
220 #include "content/renderer/npapi/webplugin_delegate_proxy.h"
221 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
222 #include "content/renderer/pepper/pepper_plugin_registry.h"
223 #endif
225 #if defined(ENABLE_WEBRTC)
226 #include "content/renderer/media/rtc_peer_connection_handler.h"
227 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
228 #endif
230 using blink::WebAXObject;
231 using blink::WebApplicationCacheHost;
232 using blink::WebApplicationCacheHostClient;
233 using blink::WebCString;
234 using blink::WebColor;
235 using blink::WebColorName;
236 using blink::WebConsoleMessage;
237 using blink::WebData;
238 using blink::WebDataSource;
239 using blink::WebDocument;
240 using blink::WebDOMEvent;
241 using blink::WebDOMMessageEvent;
242 using blink::WebDragData;
243 using blink::WebDragOperation;
244 using blink::WebDragOperationsMask;
245 using blink::WebElement;
246 using blink::WebFileChooserCompletion;
247 using blink::WebFindOptions;
248 using blink::WebFormControlElement;
249 using blink::WebFormElement;
250 using blink::WebFrame;
251 using blink::WebGestureEvent;
252 using blink::WebHistoryItem;
253 using blink::WebHTTPBody;
254 using blink::WebIconURL;
255 using blink::WebImage;
256 using blink::WebInputElement;
257 using blink::WebInputEvent;
258 using blink::WebLocalFrame;
259 using blink::WebMediaPlayerAction;
260 using blink::WebMouseEvent;
261 using blink::WebNavigationPolicy;
262 using blink::WebNavigationType;
263 using blink::WebNode;
264 using blink::WebPageSerializer;
265 using blink::WebPageSerializerClient;
266 using blink::WebPeerConnection00Handler;
267 using blink::WebPeerConnection00HandlerClient;
268 using blink::WebPeerConnectionHandler;
269 using blink::WebPeerConnectionHandlerClient;
270 using blink::WebPluginAction;
271 using blink::WebPluginContainer;
272 using blink::WebPluginDocument;
273 using blink::WebPoint;
274 using blink::WebRange;
275 using blink::WebRect;
276 using blink::WebReferrerPolicy;
277 using blink::WebScriptSource;
278 using blink::WebSearchableFormData;
279 using blink::WebSecurityOrigin;
280 using blink::WebSecurityPolicy;
281 using blink::WebSerializedScriptValue;
282 using blink::WebSettings;
283 using blink::WebSize;
284 using blink::WebSocketStreamHandle;
285 using blink::WebStorageNamespace;
286 using blink::WebStorageQuotaCallbacks;
287 using blink::WebStorageQuotaError;
288 using blink::WebStorageQuotaType;
289 using blink::WebString;
290 using blink::WebTextAffinity;
291 using blink::WebTextDirection;
292 using blink::WebTouchEvent;
293 using blink::WebURL;
294 using blink::WebURLError;
295 using blink::WebURLRequest;
296 using blink::WebURLResponse;
297 using blink::WebUserGestureIndicator;
298 using blink::WebVector;
299 using blink::WebView;
300 using blink::WebWidget;
301 using blink::WebWindowFeatures;
302 using blink::WebNetworkStateNotifier;
303 using blink::WebRuntimeFeatures;
304 using base::Time;
305 using base::TimeDelta;
307 #if defined(OS_ANDROID)
308 using blink::WebContentDetectionResult;
309 using blink::WebFloatPoint;
310 using blink::WebFloatRect;
311 using blink::WebHitTestResult;
312 #endif
314 namespace content {
316 //-----------------------------------------------------------------------------
318 typedef std::map<blink::WebView*, RenderViewImpl*> ViewMap;
319 static base::LazyInstance<ViewMap> g_view_map = LAZY_INSTANCE_INITIALIZER;
320 typedef std::map<int32, RenderViewImpl*> RoutingIDViewMap;
321 static base::LazyInstance<RoutingIDViewMap> g_routing_id_view_map =
322 LAZY_INSTANCE_INITIALIZER;
324 // Time, in seconds, we delay before sending content state changes (such as form
325 // state and scroll position) to the browser. We delay sending changes to avoid
326 // spamming the browser.
327 // To avoid having tab/session restore require sending a message to get the
328 // current content state during tab closing we use a shorter timeout for the
329 // foreground renderer. This means there is a small window of time from which
330 // content state is modified and not sent to session restore, but this is
331 // better than having to wake up all renderers during shutdown.
332 const int kDelaySecondsForContentStateSyncHidden = 5;
333 const int kDelaySecondsForContentStateSync = 1;
335 #if defined(OS_ANDROID)
336 // Delay between tapping in content and launching the associated android intent.
337 // Used to allow users see what has been recognized as content.
338 const size_t kContentIntentDelayMilliseconds = 700;
339 #endif
341 static RenderViewImpl* (*g_create_render_view_impl)(RenderViewImplParams*) =
342 NULL;
344 // static
345 bool RenderViewImpl::IsReload(const FrameMsg_Navigate_Params& params) {
346 return
347 params.navigation_type == FrameMsg_Navigate_Type::RELOAD ||
348 params.navigation_type == FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE ||
349 params.navigation_type ==
350 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL;
353 // static
354 Referrer RenderViewImpl::GetReferrerFromRequest(
355 WebFrame* frame,
356 const WebURLRequest& request) {
357 return Referrer(GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
358 request.referrerPolicy());
361 // static
362 WindowOpenDisposition RenderViewImpl::NavigationPolicyToDisposition(
363 WebNavigationPolicy policy) {
364 switch (policy) {
365 case blink::WebNavigationPolicyIgnore:
366 return IGNORE_ACTION;
367 case blink::WebNavigationPolicyDownload:
368 return SAVE_TO_DISK;
369 case blink::WebNavigationPolicyCurrentTab:
370 return CURRENT_TAB;
371 case blink::WebNavigationPolicyNewBackgroundTab:
372 return NEW_BACKGROUND_TAB;
373 case blink::WebNavigationPolicyNewForegroundTab:
374 return NEW_FOREGROUND_TAB;
375 case blink::WebNavigationPolicyNewWindow:
376 return NEW_WINDOW;
377 case blink::WebNavigationPolicyNewPopup:
378 return NEW_POPUP;
379 default:
380 NOTREACHED() << "Unexpected WebNavigationPolicy";
381 return IGNORE_ACTION;
385 // Returns true if the device scale is high enough that losing subpixel
386 // antialiasing won't have a noticeable effect on text quality.
387 static bool DeviceScaleEnsuresTextQuality(float device_scale_factor) {
388 #if defined(OS_ANDROID)
389 // On Android, we never have subpixel antialiasing.
390 return true;
391 #else
392 return device_scale_factor > 1.5f;
393 #endif
397 static bool PreferCompositingToLCDText(float device_scale_factor) {
398 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
399 if (command_line.HasSwitch(switches::kDisablePreferCompositingToLCDText))
400 return false;
401 if (command_line.HasSwitch(switches::kEnablePreferCompositingToLCDText))
402 return true;
403 if (RenderThreadImpl::current() &&
404 !RenderThreadImpl::current()->is_lcd_text_enabled())
405 return true;
406 return DeviceScaleEnsuresTextQuality(device_scale_factor);
409 static bool ShouldUseTransitionCompositing(float device_scale_factor) {
410 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
412 if (command_line.HasSwitch(switches::kDisableCompositingForTransition))
413 return false;
415 if (command_line.HasSwitch(switches::kEnableCompositingForTransition))
416 return true;
418 // TODO(ajuma): Re-enable this by default for high-DPI once the problem
419 // of excessive layer promotion caused by overlap has been addressed.
420 // http://crbug.com/178119.
421 return false;
424 static FaviconURL::IconType ToFaviconType(blink::WebIconURL::Type type) {
425 switch (type) {
426 case blink::WebIconURL::TypeFavicon:
427 return FaviconURL::FAVICON;
428 case blink::WebIconURL::TypeTouch:
429 return FaviconURL::TOUCH_ICON;
430 case blink::WebIconURL::TypeTouchPrecomposed:
431 return FaviconURL::TOUCH_PRECOMPOSED_ICON;
432 case blink::WebIconURL::TypeInvalid:
433 return FaviconURL::INVALID_ICON;
435 return FaviconURL::INVALID_ICON;
438 static void ConvertToFaviconSizes(
439 const blink::WebVector<blink::WebSize>& web_sizes,
440 std::vector<gfx::Size>* sizes) {
441 DCHECK(sizes->empty());
442 sizes->reserve(web_sizes.size());
443 for (size_t i = 0; i < web_sizes.size(); ++i)
444 sizes->push_back(gfx::Size(web_sizes[i]));
447 ///////////////////////////////////////////////////////////////////////////////
449 struct RenderViewImpl::PendingFileChooser {
450 PendingFileChooser(const FileChooserParams& p, WebFileChooserCompletion* c)
451 : params(p),
452 completion(c) {
454 FileChooserParams params;
455 WebFileChooserCompletion* completion; // MAY BE NULL to skip callback.
458 namespace {
460 class WebWidgetLockTarget : public MouseLockDispatcher::LockTarget {
461 public:
462 explicit WebWidgetLockTarget(blink::WebWidget* webwidget)
463 : webwidget_(webwidget) {}
465 virtual void OnLockMouseACK(bool succeeded) OVERRIDE {
466 if (succeeded)
467 webwidget_->didAcquirePointerLock();
468 else
469 webwidget_->didNotAcquirePointerLock();
472 virtual void OnMouseLockLost() OVERRIDE {
473 webwidget_->didLosePointerLock();
476 virtual bool HandleMouseLockedInputEvent(
477 const blink::WebMouseEvent &event) OVERRIDE {
478 // The WebWidget handles mouse lock in WebKit's handleInputEvent().
479 return false;
482 private:
483 blink::WebWidget* webwidget_;
486 bool TouchEnabled() {
487 // Based on the definition of chrome::kEnableTouchIcon.
488 #if defined(OS_ANDROID)
489 return true;
490 #else
491 return false;
492 #endif
495 WebDragData DropDataToWebDragData(const DropData& drop_data) {
496 std::vector<WebDragData::Item> item_list;
498 // These fields are currently unused when dragging into WebKit.
499 DCHECK(drop_data.download_metadata.empty());
500 DCHECK(drop_data.file_contents.empty());
501 DCHECK(drop_data.file_description_filename.empty());
503 if (!drop_data.text.is_null()) {
504 WebDragData::Item item;
505 item.storageType = WebDragData::Item::StorageTypeString;
506 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeText);
507 item.stringData = drop_data.text.string();
508 item_list.push_back(item);
511 // TODO(dcheng): Do we need to distinguish between null and empty URLs? Is it
512 // meaningful to write an empty URL to the clipboard?
513 if (!drop_data.url.is_empty()) {
514 WebDragData::Item item;
515 item.storageType = WebDragData::Item::StorageTypeString;
516 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeURIList);
517 item.stringData = WebString::fromUTF8(drop_data.url.spec());
518 item.title = drop_data.url_title;
519 item_list.push_back(item);
522 if (!drop_data.html.is_null()) {
523 WebDragData::Item item;
524 item.storageType = WebDragData::Item::StorageTypeString;
525 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeHTML);
526 item.stringData = drop_data.html.string();
527 item.baseURL = drop_data.html_base_url;
528 item_list.push_back(item);
531 for (std::vector<ui::FileInfo>::const_iterator it =
532 drop_data.filenames.begin();
533 it != drop_data.filenames.end();
534 ++it) {
535 WebDragData::Item item;
536 item.storageType = WebDragData::Item::StorageTypeFilename;
537 item.filenameData = it->path.AsUTF16Unsafe();
538 item.displayNameData = it->display_name.AsUTF16Unsafe();
539 item_list.push_back(item);
542 for (std::vector<DropData::FileSystemFileInfo>::const_iterator it =
543 drop_data.file_system_files.begin();
544 it != drop_data.file_system_files.end();
545 ++it) {
546 WebDragData::Item item;
547 item.storageType = WebDragData::Item::StorageTypeFileSystemFile;
548 item.fileSystemURL = it->url;
549 item.fileSystemFileSize = it->size;
550 item_list.push_back(item);
553 for (std::map<base::string16, base::string16>::const_iterator it =
554 drop_data.custom_data.begin();
555 it != drop_data.custom_data.end();
556 ++it) {
557 WebDragData::Item item;
558 item.storageType = WebDragData::Item::StorageTypeString;
559 item.stringType = it->first;
560 item.stringData = it->second;
561 item_list.push_back(item);
564 WebDragData result;
565 result.initialize();
566 result.setItems(item_list);
567 result.setFilesystemId(drop_data.filesystem_id);
568 return result;
571 typedef void (*SetFontFamilyWrapper)(blink::WebSettings*,
572 const base::string16&,
573 UScriptCode);
575 void SetStandardFontFamilyWrapper(WebSettings* settings,
576 const base::string16& font,
577 UScriptCode script) {
578 settings->setStandardFontFamily(font, script);
581 void SetFixedFontFamilyWrapper(WebSettings* settings,
582 const base::string16& font,
583 UScriptCode script) {
584 settings->setFixedFontFamily(font, script);
587 void SetSerifFontFamilyWrapper(WebSettings* settings,
588 const base::string16& font,
589 UScriptCode script) {
590 settings->setSerifFontFamily(font, script);
593 void SetSansSerifFontFamilyWrapper(WebSettings* settings,
594 const base::string16& font,
595 UScriptCode script) {
596 settings->setSansSerifFontFamily(font, script);
599 void SetCursiveFontFamilyWrapper(WebSettings* settings,
600 const base::string16& font,
601 UScriptCode script) {
602 settings->setCursiveFontFamily(font, script);
605 void SetFantasyFontFamilyWrapper(WebSettings* settings,
606 const base::string16& font,
607 UScriptCode script) {
608 settings->setFantasyFontFamily(font, script);
611 void SetPictographFontFamilyWrapper(WebSettings* settings,
612 const base::string16& font,
613 UScriptCode script) {
614 settings->setPictographFontFamily(font, script);
617 // If |scriptCode| is a member of a family of "similar" script codes, returns
618 // the script code in that family that is used by WebKit for font selection
619 // purposes. For example, USCRIPT_KATAKANA_OR_HIRAGANA and USCRIPT_JAPANESE are
620 // considered equivalent for the purposes of font selection. WebKit uses the
621 // script code USCRIPT_KATAKANA_OR_HIRAGANA. So, if |scriptCode| is
622 // USCRIPT_JAPANESE, the function returns USCRIPT_KATAKANA_OR_HIRAGANA. WebKit
623 // uses different scripts than the ones in Chrome pref names because the version
624 // of ICU included on certain ports does not have some of the newer scripts. If
625 // |scriptCode| is not a member of such a family, returns |scriptCode|.
626 UScriptCode GetScriptForWebSettings(UScriptCode scriptCode) {
627 switch (scriptCode) {
628 case USCRIPT_HIRAGANA:
629 case USCRIPT_KATAKANA:
630 case USCRIPT_JAPANESE:
631 return USCRIPT_KATAKANA_OR_HIRAGANA;
632 case USCRIPT_KOREAN:
633 return USCRIPT_HANGUL;
634 default:
635 return scriptCode;
639 void ApplyFontsFromMap(const ScriptFontFamilyMap& map,
640 SetFontFamilyWrapper setter,
641 WebSettings* settings) {
642 for (ScriptFontFamilyMap::const_iterator it = map.begin(); it != map.end();
643 ++it) {
644 int32 script = u_getPropertyValueEnum(UCHAR_SCRIPT, (it->first).c_str());
645 if (script >= 0 && script < USCRIPT_CODE_LIMIT) {
646 UScriptCode code = static_cast<UScriptCode>(script);
647 (*setter)(settings, it->second, GetScriptForWebSettings(code));
652 } // namespace
654 RenderViewImpl::RenderViewImpl(RenderViewImplParams* params)
655 : RenderWidget(blink::WebPopupTypeNone,
656 params->screen_info,
657 params->swapped_out,
658 params->hidden,
659 params->never_visible),
660 webkit_preferences_(params->webkit_prefs),
661 send_content_state_immediately_(false),
662 enabled_bindings_(0),
663 send_preferred_size_changes_(false),
664 navigation_gesture_(NavigationGestureUnknown),
665 opened_by_user_gesture_(true),
666 opener_suppressed_(false),
667 suppress_dialogs_until_swap_out_(false),
668 page_id_(-1),
669 last_page_id_sent_to_browser_(-1),
670 next_page_id_(params->next_page_id),
671 history_list_offset_(-1),
672 history_list_length_(0),
673 frames_in_progress_(0),
674 target_url_status_(TARGET_NONE),
675 uses_temporary_zoom_level_(false),
676 #if defined(OS_ANDROID)
677 top_controls_constraints_(cc::BOTH),
678 #endif
679 has_scrolled_focused_editable_node_into_rect_(false),
680 speech_recognition_dispatcher_(NULL),
681 browser_plugin_manager_(NULL),
682 devtools_agent_(NULL),
683 mouse_lock_dispatcher_(NULL),
684 #if defined(OS_ANDROID)
685 expected_content_intent_id_(0),
686 #endif
687 #if defined(OS_WIN)
688 focused_plugin_id_(-1),
689 #endif
690 #if defined(ENABLE_PLUGINS)
691 plugin_find_handler_(NULL),
692 focused_pepper_plugin_(NULL),
693 pepper_last_mouse_event_target_(NULL),
694 #endif
695 enumeration_completion_id_(0),
696 session_storage_namespace_id_(params->session_storage_namespace_id),
697 next_snapshot_id_(0) {
700 void RenderViewImpl::Initialize(RenderViewImplParams* params) {
701 routing_id_ = params->routing_id;
702 surface_id_ = params->surface_id;
703 if (params->opener_id != MSG_ROUTING_NONE && params->is_renderer_created)
704 opener_id_ = params->opener_id;
706 // Ensure we start with a valid next_page_id_ from the browser.
707 DCHECK_GE(next_page_id_, 0);
709 main_render_frame_.reset(RenderFrameImpl::Create(
710 this, params->main_frame_routing_id));
711 // The main frame WebLocalFrame object is closed by
712 // RenderFrameImpl::frameDetached().
713 WebLocalFrame* web_frame = WebLocalFrame::create(main_render_frame_.get());
714 main_render_frame_->SetWebFrame(web_frame);
716 webwidget_ = WebView::create(this);
717 webwidget_mouse_lock_target_.reset(new WebWidgetLockTarget(webwidget_));
719 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
721 if (command_line.HasSwitch(switches::kStatsCollectionController))
722 stats_collection_observer_.reset(new StatsCollectionObserver(this));
724 #if defined(OS_ANDROID)
725 const std::string region_code =
726 command_line.HasSwitch(switches::kNetworkCountryIso)
727 ? command_line.GetSwitchValueASCII(switches::kNetworkCountryIso)
728 : net::android::GetTelephonyNetworkOperator();
729 content_detectors_.push_back(linked_ptr<ContentDetector>(
730 new AddressDetector()));
731 content_detectors_.push_back(linked_ptr<ContentDetector>(
732 new PhoneNumberDetector(region_code)));
733 content_detectors_.push_back(linked_ptr<ContentDetector>(
734 new EmailDetector()));
735 #endif
737 RenderThread::Get()->AddRoute(routing_id_, this);
738 // Take a reference on behalf of the RenderThread. This will be balanced
739 // when we receive ViewMsg_ClosePage.
740 AddRef();
741 if (RenderThreadImpl::current()) {
742 RenderThreadImpl::current()->WidgetCreated();
743 if (is_hidden_)
744 RenderThreadImpl::current()->WidgetHidden();
747 // If this is a popup, we must wait for the CreatingNew_ACK message before
748 // completing initialization. Otherwise, we can finish it now.
749 if (opener_id_ == MSG_ROUTING_NONE) {
750 did_show_ = true;
751 CompleteInit();
754 g_view_map.Get().insert(std::make_pair(webview(), this));
755 g_routing_id_view_map.Get().insert(std::make_pair(routing_id_, this));
756 webview()->setDeviceScaleFactor(device_scale_factor_);
757 webview()->settings()->setPreferCompositingToLCDTextEnabled(
758 PreferCompositingToLCDText(device_scale_factor_));
759 webview()->settings()->setAcceleratedCompositingForTransitionEnabled(
760 ShouldUseTransitionCompositing(device_scale_factor_));
762 ApplyWebPreferences(webkit_preferences_, webview());
764 webview()->settings()->setAllowConnectingInsecureWebSocket(
765 command_line.HasSwitch(switches::kAllowInsecureWebSocketFromHttpsOrigin));
767 RenderFrameProxy* proxy = NULL;
768 if (params->proxy_routing_id != MSG_ROUTING_NONE) {
769 CHECK(params->swapped_out);
770 proxy = RenderFrameProxy::CreateProxyToReplaceFrame(
771 main_render_frame_.get(), params->proxy_routing_id);
772 main_render_frame_->set_render_frame_proxy(proxy);
775 // In --site-per-process, just use the WebRemoteFrame as the main frame.
776 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess) &&
777 proxy) {
778 webview()->setMainFrame(proxy->web_frame());
779 } else {
780 webview()->setMainFrame(main_render_frame_->GetWebFrame());
782 main_render_frame_->Initialize();
784 if (switches::IsTouchDragDropEnabled())
785 webview()->settings()->setTouchDragDropEnabled(true);
787 if (switches::IsTouchEditingEnabled())
788 webview()->settings()->setTouchEditingEnabled(true);
790 if (!params->frame_name.empty())
791 webview()->mainFrame()->setName(params->frame_name);
793 // TODO(davidben): Move this state from Blink into content.
794 if (params->window_was_created_with_opener)
795 webview()->setOpenedByDOM();
797 OnSetRendererPrefs(params->renderer_prefs);
799 new MHTMLGenerator(this);
800 #if defined(OS_MACOSX)
801 new TextInputClientObserver(this);
802 #endif // defined(OS_MACOSX)
804 // The next group of objects all implement RenderViewObserver, so are deleted
805 // along with the RenderView automatically.
806 devtools_agent_ = new DevToolsAgent(this);
807 if (RenderWidgetCompositor* rwc = compositor()) {
808 webview()->devToolsAgent()->setLayerTreeId(rwc->GetLayerTreeId());
810 mouse_lock_dispatcher_ = new RenderViewMouseLockDispatcher(this);
812 history_controller_.reset(new HistoryController(this));
814 new IdleUserDetector(this);
816 if (command_line.HasSwitch(switches::kDomAutomationController))
817 enabled_bindings_ |= BINDINGS_POLICY_DOM_AUTOMATION;
818 if (command_line.HasSwitch(switches::kStatsCollectionController))
819 enabled_bindings_ |= BINDINGS_POLICY_STATS_COLLECTION;
821 ProcessViewLayoutFlags(command_line);
823 GetContentClient()->renderer()->RenderViewCreated(this);
825 // If we have an opener_id but we weren't created by a renderer, then
826 // it's the browser asking us to set our opener to another RenderView.
827 if (params->opener_id != MSG_ROUTING_NONE && !params->is_renderer_created) {
828 RenderViewImpl* opener_view = FromRoutingID(params->opener_id);
829 if (opener_view)
830 webview()->mainFrame()->setOpener(opener_view->webview()->mainFrame());
833 // If we are initially swapped out, navigate to kSwappedOutURL.
834 // This ensures we are in a unique origin that others cannot script.
835 if (is_swapped_out_ && webview()->mainFrame()->isWebLocalFrame())
836 NavigateToSwappedOutURL(webview()->mainFrame());
839 RenderViewImpl::~RenderViewImpl() {
840 for (BitmapMap::iterator it = disambiguation_bitmaps_.begin();
841 it != disambiguation_bitmaps_.end();
842 ++it)
843 delete it->second;
844 history_page_ids_.clear();
846 base::debug::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_);
848 // If file chooser is still waiting for answer, dispatch empty answer.
849 while (!file_chooser_completions_.empty()) {
850 if (file_chooser_completions_.front()->completion) {
851 file_chooser_completions_.front()->completion->didChooseFile(
852 WebVector<WebString>());
854 file_chooser_completions_.pop_front();
857 #if defined(OS_ANDROID)
858 // The date/time picker client is both a scoped_ptr member of this class and
859 // a RenderViewObserver. Reset it to prevent double deletion.
860 date_time_picker_client_.reset();
861 #endif
863 #ifndef NDEBUG
864 // Make sure we are no longer referenced by the ViewMap or RoutingIDViewMap.
865 ViewMap* views = g_view_map.Pointer();
866 for (ViewMap::iterator it = views->begin(); it != views->end(); ++it)
867 DCHECK_NE(this, it->second) << "Failed to call Close?";
868 RoutingIDViewMap* routing_id_views = g_routing_id_view_map.Pointer();
869 for (RoutingIDViewMap::iterator it = routing_id_views->begin();
870 it != routing_id_views->end(); ++it)
871 DCHECK_NE(this, it->second) << "Failed to call Close?";
872 #endif
874 FOR_EACH_OBSERVER(RenderViewObserver, observers_, RenderViewGone());
875 FOR_EACH_OBSERVER(RenderViewObserver, observers_, OnDestruct());
878 /*static*/
879 RenderViewImpl* RenderViewImpl::FromWebView(WebView* webview) {
880 ViewMap* views = g_view_map.Pointer();
881 ViewMap::iterator it = views->find(webview);
882 return it == views->end() ? NULL : it->second;
885 /*static*/
886 RenderView* RenderView::FromWebView(blink::WebView* webview) {
887 return RenderViewImpl::FromWebView(webview);
890 /*static*/
891 RenderViewImpl* RenderViewImpl::FromRoutingID(int32 routing_id) {
892 RoutingIDViewMap* views = g_routing_id_view_map.Pointer();
893 RoutingIDViewMap::iterator it = views->find(routing_id);
894 return it == views->end() ? NULL : it->second;
897 /*static*/
898 RenderView* RenderView::FromRoutingID(int routing_id) {
899 return RenderViewImpl::FromRoutingID(routing_id);
902 /* static */
903 size_t RenderViewImpl::GetRenderViewCount() {
904 return g_view_map.Get().size();
907 /*static*/
908 void RenderView::ForEach(RenderViewVisitor* visitor) {
909 ViewMap* views = g_view_map.Pointer();
910 for (ViewMap::iterator it = views->begin(); it != views->end(); ++it) {
911 if (!visitor->Visit(it->second))
912 return;
916 /*static*/
917 void RenderView::ApplyWebPreferences(const WebPreferences& prefs,
918 WebView* web_view) {
919 WebSettings* settings = web_view->settings();
920 ApplyFontsFromMap(prefs.standard_font_family_map,
921 SetStandardFontFamilyWrapper, settings);
922 ApplyFontsFromMap(prefs.fixed_font_family_map,
923 SetFixedFontFamilyWrapper, settings);
924 ApplyFontsFromMap(prefs.serif_font_family_map,
925 SetSerifFontFamilyWrapper, settings);
926 ApplyFontsFromMap(prefs.sans_serif_font_family_map,
927 SetSansSerifFontFamilyWrapper, settings);
928 ApplyFontsFromMap(prefs.cursive_font_family_map,
929 SetCursiveFontFamilyWrapper, settings);
930 ApplyFontsFromMap(prefs.fantasy_font_family_map,
931 SetFantasyFontFamilyWrapper, settings);
932 ApplyFontsFromMap(prefs.pictograph_font_family_map,
933 SetPictographFontFamilyWrapper, settings);
934 settings->setDefaultFontSize(prefs.default_font_size);
935 settings->setDefaultFixedFontSize(prefs.default_fixed_font_size);
936 settings->setMinimumFontSize(prefs.minimum_font_size);
937 settings->setMinimumLogicalFontSize(prefs.minimum_logical_font_size);
938 settings->setDefaultTextEncodingName(
939 base::ASCIIToUTF16(prefs.default_encoding));
940 settings->setJavaScriptEnabled(prefs.javascript_enabled);
941 settings->setWebSecurityEnabled(prefs.web_security_enabled);
942 settings->setJavaScriptCanOpenWindowsAutomatically(
943 prefs.javascript_can_open_windows_automatically);
944 settings->setLoadsImagesAutomatically(prefs.loads_images_automatically);
945 settings->setImagesEnabled(prefs.images_enabled);
946 settings->setPluginsEnabled(prefs.plugins_enabled);
947 settings->setDOMPasteAllowed(prefs.dom_paste_enabled);
948 settings->setShrinksStandaloneImagesToFit(
949 prefs.shrinks_standalone_images_to_fit);
950 settings->setUsesEncodingDetector(prefs.uses_universal_detector);
951 settings->setTextAreasAreResizable(prefs.text_areas_are_resizable);
952 settings->setAllowScriptsToCloseWindows(prefs.allow_scripts_to_close_windows);
953 settings->setDownloadableBinaryFontsEnabled(prefs.remote_fonts_enabled);
954 settings->setJavaScriptCanAccessClipboard(
955 prefs.javascript_can_access_clipboard);
956 WebRuntimeFeatures::enableXSLT(prefs.xslt_enabled);
957 settings->setXSSAuditorEnabled(prefs.xss_auditor_enabled);
958 settings->setDNSPrefetchingEnabled(prefs.dns_prefetching_enabled);
959 settings->setLocalStorageEnabled(prefs.local_storage_enabled);
960 settings->setSyncXHRInDocumentsEnabled(prefs.sync_xhr_in_documents_enabled);
961 WebRuntimeFeatures::enableDatabase(prefs.databases_enabled);
962 settings->setOfflineWebApplicationCacheEnabled(
963 prefs.application_cache_enabled);
964 settings->setCaretBrowsingEnabled(prefs.caret_browsing_enabled);
965 settings->setHyperlinkAuditingEnabled(prefs.hyperlink_auditing_enabled);
966 settings->setCookieEnabled(prefs.cookie_enabled);
967 settings->setNavigateOnDragDrop(prefs.navigate_on_drag_drop);
969 settings->setJavaEnabled(prefs.java_enabled);
971 // By default, allow_universal_access_from_file_urls is set to false and thus
972 // we mitigate attacks from local HTML files by not granting file:// URLs
973 // universal access. Only test shell will enable this.
974 settings->setAllowUniversalAccessFromFileURLs(
975 prefs.allow_universal_access_from_file_urls);
976 settings->setAllowFileAccessFromFileURLs(
977 prefs.allow_file_access_from_file_urls);
979 // Enable the web audio API if requested on the command line.
980 settings->setWebAudioEnabled(prefs.webaudio_enabled);
982 // Enable experimental WebGL support if requested on command line
983 // and support is compiled in.
984 settings->setExperimentalWebGLEnabled(prefs.experimental_webgl_enabled);
986 // Disable GL multisampling if requested on command line.
987 settings->setOpenGLMultisamplingEnabled(prefs.gl_multisampling_enabled);
989 // Enable WebGL errors to the JS console if requested.
990 settings->setWebGLErrorsToConsoleEnabled(
991 prefs.webgl_errors_to_console_enabled);
993 // Uses the mock theme engine for scrollbars.
994 settings->setMockScrollbarsEnabled(prefs.mock_scrollbars_enabled);
996 settings->setLayerSquashingEnabled(prefs.layer_squashing_enabled);
998 // Enable gpu-accelerated 2d canvas if requested on the command line.
999 settings->setAccelerated2dCanvasEnabled(prefs.accelerated_2d_canvas_enabled);
1001 settings->setMinimumAccelerated2dCanvasSize(
1002 prefs.minimum_accelerated_2d_canvas_size);
1004 // Disable antialiasing for 2d canvas if requested on the command line.
1005 settings->setAntialiased2dCanvasEnabled(
1006 !prefs.antialiased_2d_canvas_disabled);
1008 // Set MSAA sample count for 2d canvas if requested on the command line (or
1009 // default value if not).
1010 settings->setAccelerated2dCanvasMSAASampleCount(
1011 prefs.accelerated_2d_canvas_msaa_sample_count);
1013 // Enable deferred filter rendering if requested on the command line.
1014 settings->setDeferredFiltersEnabled(prefs.deferred_filters_enabled);
1016 // Enable container culling if requested on the command line.
1017 settings->setContainerCullingEnabled(prefs.container_culling_enabled);
1019 settings->setAsynchronousSpellCheckingEnabled(
1020 prefs.asynchronous_spell_checking_enabled);
1021 settings->setUnifiedTextCheckerEnabled(prefs.unified_textchecker_enabled);
1023 // Tabs to link is not part of the settings. WebCore calls
1024 // ChromeClient::tabsToLinks which is part of the glue code.
1025 web_view->setTabsToLinks(prefs.tabs_to_links);
1027 settings->setAllowDisplayOfInsecureContent(
1028 prefs.allow_displaying_insecure_content);
1029 settings->setAllowRunningOfInsecureContent(
1030 prefs.allow_running_insecure_content);
1031 settings->setPasswordEchoEnabled(prefs.password_echo_enabled);
1032 settings->setShouldPrintBackgrounds(prefs.should_print_backgrounds);
1033 settings->setShouldClearDocumentBackground(
1034 prefs.should_clear_document_background);
1035 settings->setEnableScrollAnimator(prefs.enable_scroll_animator);
1037 settings->setRegionBasedColumnsEnabled(prefs.region_based_columns_enabled);
1039 WebRuntimeFeatures::enableTouch(prefs.touch_enabled);
1040 settings->setMaxTouchPoints(prefs.pointer_events_max_touch_points);
1041 settings->setDeviceSupportsTouch(prefs.device_supports_touch);
1042 settings->setDeviceSupportsMouse(prefs.device_supports_mouse);
1043 settings->setEnableTouchAdjustment(prefs.touch_adjustment_enabled);
1045 settings->setDeferredImageDecodingEnabled(
1046 prefs.deferred_image_decoding_enabled);
1047 settings->setShouldRespectImageOrientation(
1048 prefs.should_respect_image_orientation);
1050 settings->setUnsafePluginPastingEnabled(false);
1051 settings->setEditingBehavior(
1052 static_cast<WebSettings::EditingBehavior>(prefs.editing_behavior));
1054 settings->setSupportsMultipleWindows(prefs.supports_multiple_windows);
1056 settings->setViewportEnabled(prefs.viewport_enabled);
1057 settings->setLoadWithOverviewMode(prefs.initialize_at_minimum_page_scale);
1058 settings->setViewportMetaEnabled(prefs.viewport_meta_enabled);
1059 settings->setMainFrameResizesAreOrientationChanges(
1060 prefs.main_frame_resizes_are_orientation_changes);
1062 settings->setSmartInsertDeleteEnabled(prefs.smart_insert_delete_enabled);
1064 settings->setSpatialNavigationEnabled(prefs.spatial_navigation_enabled);
1066 settings->setSelectionIncludesAltImageText(true);
1068 settings->setV8CacheOptions(
1069 static_cast<WebSettings::V8CacheOptions>(prefs.v8_cache_options));
1071 #if defined(OS_ANDROID)
1072 settings->setAllowCustomScrollbarInMainFrame(false);
1073 settings->setTextAutosizingEnabled(prefs.text_autosizing_enabled);
1074 settings->setAccessibilityFontScaleFactor(prefs.font_scale_factor);
1075 settings->setDeviceScaleAdjustment(prefs.device_scale_adjustment);
1076 settings->setDisallowFullscreenForNonMediaElements(
1077 prefs.disallow_fullscreen_for_non_media_elements);
1078 settings->setFullscreenSupported(prefs.fullscreen_supported);
1079 web_view->setIgnoreViewportTagScaleLimits(prefs.force_enable_zoom);
1080 settings->setAutoZoomFocusedNodeToLegibleScale(true);
1081 settings->setDoubleTapToZoomEnabled(prefs.double_tap_to_zoom_enabled);
1082 settings->setMediaControlsOverlayPlayButtonEnabled(true);
1083 settings->setMediaPlaybackRequiresUserGesture(
1084 prefs.user_gesture_required_for_media_playback);
1085 settings->setDefaultVideoPosterURL(
1086 base::ASCIIToUTF16(prefs.default_video_poster_url.spec()));
1087 settings->setSupportDeprecatedTargetDensityDPI(
1088 prefs.support_deprecated_target_density_dpi);
1089 settings->setUseLegacyBackgroundSizeShorthandBehavior(
1090 prefs.use_legacy_background_size_shorthand_behavior);
1091 settings->setWideViewportQuirkEnabled(prefs.wide_viewport_quirk);
1092 settings->setUseWideViewport(prefs.use_wide_viewport);
1093 settings->setForceZeroLayoutHeight(prefs.force_zero_layout_height);
1094 settings->setViewportMetaLayoutSizeQuirk(
1095 prefs.viewport_meta_layout_size_quirk);
1096 settings->setViewportMetaMergeContentQuirk(
1097 prefs.viewport_meta_merge_content_quirk);
1098 settings->setViewportMetaNonUserScalableQuirk(
1099 prefs.viewport_meta_non_user_scalable_quirk);
1100 settings->setViewportMetaZeroValuesQuirk(
1101 prefs.viewport_meta_zero_values_quirk);
1102 settings->setClobberUserAgentInitialScaleQuirk(
1103 prefs.clobber_user_agent_initial_scale_quirk);
1104 settings->setIgnoreMainFrameOverflowHiddenQuirk(
1105 prefs.ignore_main_frame_overflow_hidden_quirk);
1106 settings->setReportScreenSizeInPhysicalPixelsQuirk(
1107 prefs.report_screen_size_in_physical_pixels_quirk);
1108 settings->setMainFrameClipsContent(false);
1109 settings->setShrinksStandaloneImagesToFit(false);
1110 settings->setShrinksViewportContentToFit(true);
1111 #endif
1113 WebNetworkStateNotifier::setOnLine(prefs.is_online);
1114 WebNetworkStateNotifier::setWebConnectionType(
1115 NetConnectionTypeToWebConnectionType(prefs.connection_type));
1116 settings->setPinchVirtualViewportEnabled(
1117 prefs.pinch_virtual_viewport_enabled);
1119 settings->setPinchOverlayScrollbarThickness(
1120 prefs.pinch_overlay_scrollbar_thickness);
1121 settings->setUseSolidColorScrollbars(prefs.use_solid_color_scrollbars);
1124 /*static*/
1125 RenderViewImpl* RenderViewImpl::Create(
1126 int32 opener_id,
1127 bool window_was_created_with_opener,
1128 const RendererPreferences& renderer_prefs,
1129 const WebPreferences& webkit_prefs,
1130 int32 routing_id,
1131 int32 main_frame_routing_id,
1132 int32 surface_id,
1133 int64 session_storage_namespace_id,
1134 const base::string16& frame_name,
1135 bool is_renderer_created,
1136 bool swapped_out,
1137 int32 proxy_routing_id,
1138 bool hidden,
1139 bool never_visible,
1140 int32 next_page_id,
1141 const blink::WebScreenInfo& screen_info) {
1142 DCHECK(routing_id != MSG_ROUTING_NONE);
1143 RenderViewImplParams params(opener_id,
1144 window_was_created_with_opener,
1145 renderer_prefs,
1146 webkit_prefs,
1147 routing_id,
1148 main_frame_routing_id,
1149 surface_id,
1150 session_storage_namespace_id,
1151 frame_name,
1152 is_renderer_created,
1153 swapped_out,
1154 proxy_routing_id,
1155 hidden,
1156 never_visible,
1157 next_page_id,
1158 screen_info);
1159 RenderViewImpl* render_view = NULL;
1160 if (g_create_render_view_impl)
1161 render_view = g_create_render_view_impl(&params);
1162 else
1163 render_view = new RenderViewImpl(&params);
1165 render_view->Initialize(&params);
1166 return render_view;
1169 // static
1170 void RenderViewImpl::InstallCreateHook(
1171 RenderViewImpl* (*create_render_view_impl)(RenderViewImplParams*)) {
1172 CHECK(!g_create_render_view_impl);
1173 g_create_render_view_impl = create_render_view_impl;
1176 void RenderViewImpl::AddObserver(RenderViewObserver* observer) {
1177 observers_.AddObserver(observer);
1180 void RenderViewImpl::RemoveObserver(RenderViewObserver* observer) {
1181 observer->RenderViewGone();
1182 observers_.RemoveObserver(observer);
1185 blink::WebView* RenderViewImpl::webview() const {
1186 return static_cast<blink::WebView*>(webwidget());
1189 #if defined(ENABLE_PLUGINS)
1190 void RenderViewImpl::PepperInstanceCreated(
1191 PepperPluginInstanceImpl* instance) {
1192 active_pepper_instances_.insert(instance);
1195 void RenderViewImpl::PepperInstanceDeleted(
1196 PepperPluginInstanceImpl* instance) {
1197 active_pepper_instances_.erase(instance);
1199 if (pepper_last_mouse_event_target_ == instance)
1200 pepper_last_mouse_event_target_ = NULL;
1201 if (focused_pepper_plugin_ == instance)
1202 PepperFocusChanged(instance, false);
1205 void RenderViewImpl::PepperFocusChanged(PepperPluginInstanceImpl* instance,
1206 bool focused) {
1207 if (focused)
1208 focused_pepper_plugin_ = instance;
1209 else if (focused_pepper_plugin_ == instance)
1210 focused_pepper_plugin_ = NULL;
1212 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
1213 UpdateSelectionBounds();
1216 void RenderViewImpl::RegisterPluginDelegate(WebPluginDelegateProxy* delegate) {
1217 plugin_delegates_.insert(delegate);
1218 // If the renderer is visible, set initial visibility and focus state.
1219 if (!is_hidden()) {
1220 #if defined(OS_MACOSX)
1221 delegate->SetContainerVisibility(true);
1222 if (webview() && webview()->isActive())
1223 delegate->SetWindowFocus(true);
1224 #endif
1226 // Plugins start assuming the content has focus (so that they work in
1227 // environments where RenderView isn't hosting them), so we always have to
1228 // set the initial state. See webplugin_delegate_impl.h for details.
1229 delegate->SetContentAreaFocus(has_focus());
1232 void RenderViewImpl::UnregisterPluginDelegate(
1233 WebPluginDelegateProxy* delegate) {
1234 plugin_delegates_.erase(delegate);
1237 #if defined(OS_WIN)
1238 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1239 if (focused)
1240 focused_plugin_id_ = plugin_id;
1241 else
1242 focused_plugin_id_ = -1;
1244 #endif
1246 #if defined(OS_MACOSX)
1247 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1248 Send(new ViewHostMsg_PluginFocusChanged(routing_id(), focused, plugin_id));
1251 void RenderViewImpl::OnGetRenderedText() {
1252 if (!webview())
1253 return;
1254 // Get rendered text from WebLocalFrame.
1255 // TODO: Currently IPC truncates any data that has a
1256 // size > kMaximumMessageSize. May be split the text into smaller chunks and
1257 // send back using multiple IPC. See http://crbug.com/393444.
1258 static const size_t kMaximumMessageSize = 8 * 1024 * 1024;
1259 std::string text = webview()->mainFrame()->contentAsText(
1260 kMaximumMessageSize).utf8();
1262 Send(new ViewMsg_GetRenderedTextCompleted(routing_id(), text));
1265 void RenderViewImpl::StartPluginIme() {
1266 IPC::Message* msg = new ViewHostMsg_StartPluginIme(routing_id());
1267 // This message can be sent during event-handling, and needs to be delivered
1268 // within that context.
1269 msg->set_unblock(true);
1270 Send(msg);
1272 #endif // defined(OS_MACOSX)
1274 #endif // ENABLE_PLUGINS
1276 void RenderViewImpl::TransferActiveWheelFlingAnimation(
1277 const blink::WebActiveWheelFlingParameters& params) {
1278 if (webview())
1279 webview()->transferActiveWheelFlingAnimation(params);
1282 bool RenderViewImpl::HasIMETextFocus() {
1283 return GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE;
1286 bool RenderViewImpl::OnMessageReceived(const IPC::Message& message) {
1287 WebFrame* main_frame = webview() ? webview()->mainFrame() : NULL;
1288 if (main_frame && main_frame->isWebLocalFrame())
1289 GetContentClient()->SetActiveURL(main_frame->document().url());
1291 ObserverListBase<RenderViewObserver>::Iterator it(observers_);
1292 RenderViewObserver* observer;
1293 while ((observer = it.GetNext()) != NULL)
1294 if (observer->OnMessageReceived(message))
1295 return true;
1297 bool handled = true;
1298 IPC_BEGIN_MESSAGE_MAP(RenderViewImpl, message)
1299 IPC_MESSAGE_HANDLER(InputMsg_ExecuteEditCommand, OnExecuteEditCommand)
1300 IPC_MESSAGE_HANDLER(InputMsg_MoveCaret, OnMoveCaret)
1301 IPC_MESSAGE_HANDLER(InputMsg_ScrollFocusedEditableNodeIntoRect,
1302 OnScrollFocusedEditableNodeIntoRect)
1303 IPC_MESSAGE_HANDLER(InputMsg_SetEditCommandsForNextKeyEvent,
1304 OnSetEditCommandsForNextKeyEvent)
1305 IPC_MESSAGE_HANDLER(ViewMsg_CopyImageAt, OnCopyImageAt)
1306 IPC_MESSAGE_HANDLER(ViewMsg_SaveImageAt, OnSaveImageAt)
1307 IPC_MESSAGE_HANDLER(ViewMsg_Find, OnFind)
1308 IPC_MESSAGE_HANDLER(ViewMsg_StopFinding, OnStopFinding)
1309 IPC_MESSAGE_HANDLER(ViewMsg_Zoom, OnZoom)
1310 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForLoadingURL,
1311 OnSetZoomLevelForLoadingURL)
1312 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForView,
1313 OnSetZoomLevelForView)
1314 IPC_MESSAGE_HANDLER(ViewMsg_SetPageEncoding, OnSetPageEncoding)
1315 IPC_MESSAGE_HANDLER(ViewMsg_ResetPageEncodingToDefault,
1316 OnResetPageEncodingToDefault)
1317 IPC_MESSAGE_HANDLER(ViewMsg_PostMessageEvent, OnPostMessageEvent)
1318 IPC_MESSAGE_HANDLER(DragMsg_TargetDragEnter, OnDragTargetDragEnter)
1319 IPC_MESSAGE_HANDLER(DragMsg_TargetDragOver, OnDragTargetDragOver)
1320 IPC_MESSAGE_HANDLER(DragMsg_TargetDragLeave, OnDragTargetDragLeave)
1321 IPC_MESSAGE_HANDLER(DragMsg_TargetDrop, OnDragTargetDrop)
1322 IPC_MESSAGE_HANDLER(DragMsg_SourceEnded, OnDragSourceEnded)
1323 IPC_MESSAGE_HANDLER(DragMsg_SourceSystemDragEnded,
1324 OnDragSourceSystemDragEnded)
1325 IPC_MESSAGE_HANDLER(ViewMsg_AllowBindings, OnAllowBindings)
1326 IPC_MESSAGE_HANDLER(ViewMsg_SetInitialFocus, OnSetInitialFocus)
1327 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTargetURL_ACK, OnUpdateTargetURLAck)
1328 IPC_MESSAGE_HANDLER(ViewMsg_UpdateWebPreferences, OnUpdateWebPreferences)
1329 IPC_MESSAGE_HANDLER(ViewMsg_EnumerateDirectoryResponse,
1330 OnEnumerateDirectoryResponse)
1331 IPC_MESSAGE_HANDLER(ViewMsg_RunFileChooserResponse, OnFileChooserResponse)
1332 IPC_MESSAGE_HANDLER(ViewMsg_SuppressDialogsUntilSwapOut,
1333 OnSuppressDialogsUntilSwapOut)
1334 IPC_MESSAGE_HANDLER(ViewMsg_ClosePage, OnClosePage)
1335 IPC_MESSAGE_HANDLER(ViewMsg_ThemeChanged, OnThemeChanged)
1336 IPC_MESSAGE_HANDLER(ViewMsg_MoveOrResizeStarted, OnMoveOrResizeStarted)
1337 IPC_MESSAGE_HANDLER(ViewMsg_ClearFocusedElement, OnClearFocusedElement)
1338 IPC_MESSAGE_HANDLER(ViewMsg_SetBackgroundOpaque, OnSetBackgroundOpaque)
1339 IPC_MESSAGE_HANDLER(ViewMsg_EnablePreferredSizeChangedMode,
1340 OnEnablePreferredSizeChangedMode)
1341 IPC_MESSAGE_HANDLER(ViewMsg_EnableAutoResize, OnEnableAutoResize)
1342 IPC_MESSAGE_HANDLER(ViewMsg_DisableAutoResize, OnDisableAutoResize)
1343 IPC_MESSAGE_HANDLER(ViewMsg_DisableScrollbarsForSmallWindows,
1344 OnDisableScrollbarsForSmallWindows)
1345 IPC_MESSAGE_HANDLER(ViewMsg_SetRendererPrefs, OnSetRendererPrefs)
1346 IPC_MESSAGE_HANDLER(ViewMsg_MediaPlayerActionAt, OnMediaPlayerActionAt)
1347 IPC_MESSAGE_HANDLER(ViewMsg_PluginActionAt, OnPluginActionAt)
1348 IPC_MESSAGE_HANDLER(ViewMsg_SetActive, OnSetActive)
1349 IPC_MESSAGE_HANDLER(ViewMsg_GetAllSavableResourceLinksForCurrentPage,
1350 OnGetAllSavableResourceLinksForCurrentPage)
1351 IPC_MESSAGE_HANDLER(
1352 ViewMsg_GetSerializedHtmlDataForCurrentPageWithLocalLinks,
1353 OnGetSerializedHtmlDataForCurrentPageWithLocalLinks)
1354 IPC_MESSAGE_HANDLER(ViewMsg_ShowContextMenu, OnShowContextMenu)
1355 // TODO(viettrungluu): Move to a separate message filter.
1356 IPC_MESSAGE_HANDLER(ViewMsg_SetHistoryLengthAndPrune,
1357 OnSetHistoryLengthAndPrune)
1358 IPC_MESSAGE_HANDLER(ViewMsg_EnableViewSourceMode, OnEnableViewSourceMode)
1359 IPC_MESSAGE_HANDLER(ViewMsg_ReleaseDisambiguationPopupBitmap,
1360 OnReleaseDisambiguationPopupBitmap)
1361 IPC_MESSAGE_HANDLER(ViewMsg_WindowSnapshotCompleted,
1362 OnWindowSnapshotCompleted)
1363 IPC_MESSAGE_HANDLER(ViewMsg_ForceRedraw, OnForceRedraw)
1364 IPC_MESSAGE_HANDLER(ViewMsg_SelectWordAroundCaret, OnSelectWordAroundCaret)
1365 #if defined(OS_ANDROID)
1366 IPC_MESSAGE_HANDLER(InputMsg_ActivateNearestFindResult,
1367 OnActivateNearestFindResult)
1368 IPC_MESSAGE_HANDLER(ViewMsg_FindMatchRects, OnFindMatchRects)
1369 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTopControlsState,
1370 OnUpdateTopControlsState)
1371 IPC_MESSAGE_HANDLER(ViewMsg_ExtractSmartClipData, OnExtractSmartClipData)
1372 #elif defined(OS_MACOSX)
1373 IPC_MESSAGE_HANDLER(ViewMsg_GetRenderedText,
1374 OnGetRenderedText)
1375 IPC_MESSAGE_HANDLER(ViewMsg_PluginImeCompositionCompleted,
1376 OnPluginImeCompositionCompleted)
1377 IPC_MESSAGE_HANDLER(ViewMsg_SetInLiveResize, OnSetInLiveResize)
1378 IPC_MESSAGE_HANDLER(ViewMsg_SetWindowVisibility, OnSetWindowVisibility)
1379 IPC_MESSAGE_HANDLER(ViewMsg_WindowFrameChanged, OnWindowFrameChanged)
1380 #endif
1381 // Adding a new message? Add platform independent ones first, then put the
1382 // platform specific ones at the end.
1384 // Have the super handle all other messages.
1385 IPC_MESSAGE_UNHANDLED(handled = RenderWidget::OnMessageReceived(message))
1386 IPC_END_MESSAGE_MAP()
1388 return handled;
1391 void RenderViewImpl::OnSelectWordAroundCaret() {
1392 if (!webview())
1393 return;
1395 handling_input_event_ = true;
1396 webview()->focusedFrame()->selectWordAroundCaret();
1397 handling_input_event_ = false;
1400 bool RenderViewImpl::IsBackForwardToStaleEntry(
1401 const FrameMsg_Navigate_Params& params,
1402 bool is_reload) {
1403 // Make sure this isn't a back/forward to an entry we have already cropped
1404 // or replaced from our history, before the browser knew about it. If so,
1405 // a new navigation has committed in the mean time, and we can ignore this.
1406 bool is_back_forward = !is_reload && params.page_state.IsValid();
1408 // Note: if the history_list_length_ is 0 for a back/forward, we must be
1409 // restoring from a previous session. We'll update our state in OnNavigate.
1410 if (!is_back_forward || history_list_length_ <= 0)
1411 return false;
1413 DCHECK_EQ(static_cast<int>(history_page_ids_.size()), history_list_length_);
1415 // Check for whether the forward history has been cropped due to a recent
1416 // navigation the browser didn't know about.
1417 if (params.pending_history_list_offset >= history_list_length_)
1418 return true;
1420 // Check for whether this entry has been replaced with a new one.
1421 int expected_page_id =
1422 history_page_ids_[params.pending_history_list_offset];
1423 if (expected_page_id > 0 && params.page_id != expected_page_id) {
1424 if (params.page_id < expected_page_id)
1425 return true;
1427 // Otherwise we've removed an earlier entry and should have shifted all
1428 // entries left. For now, it's ok to lazily update the list.
1429 // TODO(creis): Notify all live renderers when we remove entries from
1430 // the front of the list, so that we don't hit this case.
1431 history_page_ids_[params.pending_history_list_offset] = params.page_id;
1434 return false;
1437 void RenderViewImpl::OnCopyImageAt(int x, int y) {
1438 webview()->copyImageAt(WebPoint(x, y));
1441 void RenderViewImpl::OnSaveImageAt(int x, int y) {
1442 webview()->saveImageAt(WebPoint(x, y));
1445 void RenderViewImpl::OnUpdateTargetURLAck() {
1446 // Check if there is a targeturl waiting to be sent.
1447 if (target_url_status_ == TARGET_PENDING) {
1448 Send(new ViewHostMsg_UpdateTargetURL(routing_id_, page_id_,
1449 pending_target_url_));
1452 target_url_status_ = TARGET_NONE;
1455 void RenderViewImpl::OnExecuteEditCommand(const std::string& name,
1456 const std::string& value) {
1457 if (!webview() || !webview()->focusedFrame())
1458 return;
1460 webview()->focusedFrame()->executeCommand(
1461 WebString::fromUTF8(name), WebString::fromUTF8(value));
1464 void RenderViewImpl::OnMoveCaret(const gfx::Point& point) {
1465 if (!webview())
1466 return;
1468 Send(new ViewHostMsg_MoveCaret_ACK(routing_id_));
1470 webview()->focusedFrame()->moveCaretSelection(point);
1473 void RenderViewImpl::OnScrollFocusedEditableNodeIntoRect(
1474 const gfx::Rect& rect) {
1475 if (has_scrolled_focused_editable_node_into_rect_ &&
1476 rect == rect_for_scrolled_focused_editable_node_) {
1477 return;
1480 blink::WebElement element = GetFocusedElement();
1481 if (!element.isNull() && IsEditableNode(element)) {
1482 rect_for_scrolled_focused_editable_node_ = rect;
1483 has_scrolled_focused_editable_node_into_rect_ = true;
1484 webview()->scrollFocusedNodeIntoRect(rect);
1488 void RenderViewImpl::OnSetEditCommandsForNextKeyEvent(
1489 const EditCommands& edit_commands) {
1490 edit_commands_ = edit_commands;
1493 void RenderViewImpl::OnSetHistoryLengthAndPrune(int history_length,
1494 int32 minimum_page_id) {
1495 DCHECK_GE(history_length, 0);
1496 DCHECK(history_list_offset_ == history_list_length_ - 1);
1497 DCHECK_GE(minimum_page_id, -1);
1499 // Generate the new list.
1500 std::vector<int32> new_history_page_ids(history_length, -1);
1501 for (size_t i = 0; i < history_page_ids_.size(); ++i) {
1502 if (minimum_page_id >= 0 && history_page_ids_[i] < minimum_page_id)
1503 continue;
1504 new_history_page_ids.push_back(history_page_ids_[i]);
1506 new_history_page_ids.swap(history_page_ids_);
1508 // Update indexes.
1509 history_list_length_ = history_page_ids_.size();
1510 history_list_offset_ = history_list_length_ - 1;
1514 void RenderViewImpl::OnSetInitialFocus(bool reverse) {
1515 if (!webview())
1516 return;
1517 webview()->setInitialFocus(reverse);
1520 #if defined(OS_MACOSX)
1521 void RenderViewImpl::OnSetInLiveResize(bool in_live_resize) {
1522 if (!webview())
1523 return;
1524 if (in_live_resize)
1525 webview()->willStartLiveResize();
1526 else
1527 webview()->willEndLiveResize();
1529 #endif
1531 ///////////////////////////////////////////////////////////////////////////////
1533 // Sends the current history state to the browser so it will be saved before we
1534 // navigate to a new page.
1535 void RenderViewImpl::UpdateSessionHistory(WebFrame* frame) {
1536 // If we have a valid page ID at this point, then it corresponds to the page
1537 // we are navigating away from. Otherwise, this is the first navigation, so
1538 // there is no past session history to record.
1539 if (page_id_ == -1)
1540 return;
1541 SendUpdateState(history_controller_->GetCurrentEntry());
1544 void RenderViewImpl::SendUpdateState(HistoryEntry* entry) {
1545 if (!entry)
1546 return;
1548 // Don't send state updates for kSwappedOutURL.
1549 if (entry->root().urlString() == WebString::fromUTF8(kSwappedOutURL))
1550 return;
1552 Send(new ViewHostMsg_UpdateState(
1553 routing_id_, page_id_, HistoryEntryToPageState(entry)));
1556 bool RenderViewImpl::SendAndRunNestedMessageLoop(IPC::SyncMessage* message) {
1557 // Before WebKit asks us to show an alert (etc.), it takes care of doing the
1558 // equivalent of WebView::willEnterModalLoop. In the case of showModalDialog
1559 // it is particularly important that we do not call willEnterModalLoop as
1560 // that would defer resource loads for the dialog itself.
1561 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
1562 RenderThreadImpl::current()->DoNotNotifyWebKitOfModalLoop();
1564 message->EnableMessagePumping(); // Runs a nested message loop.
1565 return Send(message);
1568 void RenderViewImpl::GetWindowSnapshot(const WindowSnapshotCallback& callback) {
1569 int id = next_snapshot_id_++;
1570 pending_snapshots_.insert(std::make_pair(id, callback));
1571 ui::LatencyInfo latency_info;
1572 latency_info.AddLatencyNumber(ui::WINDOW_OLD_SNAPSHOT_FRAME_NUMBER_COMPONENT,
1574 id);
1575 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1576 if (RenderWidgetCompositor* rwc = compositor()) {
1577 latency_info_swap_promise_monitor =
1578 rwc->CreateLatencyInfoSwapPromiseMonitor(&latency_info).Pass();
1580 ScheduleCompositeWithForcedRedraw();
1583 void RenderViewImpl::OnForceRedraw(int id) {
1584 ui::LatencyInfo latency_info;
1585 if (id) {
1586 latency_info.AddLatencyNumber(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
1588 id);
1590 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1591 if (RenderWidgetCompositor* rwc = compositor()) {
1592 latency_info_swap_promise_monitor =
1593 rwc->CreateLatencyInfoSwapPromiseMonitor(&latency_info).Pass();
1595 ScheduleCompositeWithForcedRedraw();
1598 void RenderViewImpl::OnWindowSnapshotCompleted(const int snapshot_id,
1599 const gfx::Size& size, const std::vector<unsigned char>& png) {
1601 // Any pending snapshots with a lower ID than the one received are considered
1602 // to be implicitly complete, and returned the same snapshot data.
1603 PendingSnapshotMap::iterator it = pending_snapshots_.begin();
1604 while(it != pending_snapshots_.end()) {
1605 if (it->first <= snapshot_id) {
1606 it->second.Run(size, png);
1607 pending_snapshots_.erase(it++);
1608 } else {
1609 ++it;
1614 // blink::WebViewClient ------------------------------------------------------
1616 WebView* RenderViewImpl::createView(WebLocalFrame* creator,
1617 const WebURLRequest& request,
1618 const WebWindowFeatures& features,
1619 const WebString& frame_name,
1620 WebNavigationPolicy policy,
1621 bool suppress_opener) {
1622 ViewHostMsg_CreateWindow_Params params;
1623 params.opener_id = routing_id_;
1624 params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
1625 if (GetContentClient()->renderer()->AllowPopup())
1626 params.user_gesture = true;
1627 params.window_container_type = WindowFeaturesToContainerType(features);
1628 params.session_storage_namespace_id = session_storage_namespace_id_;
1629 if (frame_name != "_blank")
1630 params.frame_name = frame_name;
1631 params.opener_render_frame_id =
1632 RenderFrameImpl::FromWebFrame(creator)->GetRoutingID();
1633 params.opener_url = creator->document().url();
1634 params.opener_top_level_frame_url = creator->top()->document().url();
1635 GURL security_url(creator->document().securityOrigin().toString());
1636 if (!security_url.is_valid())
1637 security_url = GURL();
1638 params.opener_security_origin = security_url;
1639 params.opener_suppressed = suppress_opener;
1640 params.disposition = NavigationPolicyToDisposition(policy);
1641 if (!request.isNull()) {
1642 params.target_url = request.url();
1643 params.referrer = GetReferrerFromRequest(creator, request);
1645 params.features = features;
1647 for (size_t i = 0; i < features.additionalFeatures.size(); ++i)
1648 params.additional_features.push_back(features.additionalFeatures[i]);
1650 int32 routing_id = MSG_ROUTING_NONE;
1651 int32 main_frame_routing_id = MSG_ROUTING_NONE;
1652 int32 surface_id = 0;
1653 int64 cloned_session_storage_namespace_id = 0;
1655 RenderThread::Get()->Send(
1656 new ViewHostMsg_CreateWindow(params,
1657 &routing_id,
1658 &main_frame_routing_id,
1659 &surface_id,
1660 &cloned_session_storage_namespace_id));
1661 if (routing_id == MSG_ROUTING_NONE)
1662 return NULL;
1664 WebUserGestureIndicator::consumeUserGesture();
1666 // While this view may be a background extension page, it can spawn a visible
1667 // render view. So we just assume that the new one is not another background
1668 // page instead of passing on our own value.
1669 // TODO(vangelis): Can we tell if the new view will be a background page?
1670 bool never_visible = false;
1672 // The initial hidden state for the RenderViewImpl here has to match what the
1673 // browser will eventually decide for the given disposition. Since we have to
1674 // return from this call synchronously, we just have to make our best guess
1675 // and rely on the browser sending a WasHidden / WasShown message if it
1676 // disagrees.
1677 RenderViewImpl* view = RenderViewImpl::Create(
1678 routing_id_,
1679 true, // window_was_created_with_opener
1680 renderer_preferences_,
1681 webkit_preferences_,
1682 routing_id,
1683 main_frame_routing_id,
1684 surface_id,
1685 cloned_session_storage_namespace_id,
1686 base::string16(), // WebCore will take care of setting the correct name.
1687 true, // is_renderer_created
1688 false, // swapped_out
1689 MSG_ROUTING_NONE, // proxy_routing_id
1690 params.disposition == NEW_BACKGROUND_TAB, // hidden
1691 never_visible,
1692 1, // next_page_id
1693 screen_info_);
1694 view->opened_by_user_gesture_ = params.user_gesture;
1696 // Record whether the creator frame is trying to suppress the opener field.
1697 view->opener_suppressed_ = params.opener_suppressed;
1699 return view->webview();
1702 WebWidget* RenderViewImpl::createPopupMenu(blink::WebPopupType popup_type) {
1703 RenderWidget* widget =
1704 RenderWidget::Create(routing_id_, popup_type, screen_info_);
1705 if (!widget)
1706 return NULL;
1707 if (screen_metrics_emulator_) {
1708 widget->SetPopupOriginAdjustmentsForEmulation(
1709 screen_metrics_emulator_.get());
1711 return widget->webwidget();
1714 WebStorageNamespace* RenderViewImpl::createSessionStorageNamespace() {
1715 CHECK(session_storage_namespace_id_ != kInvalidSessionStorageNamespaceId);
1716 return new WebStorageNamespaceImpl(session_storage_namespace_id_);
1719 void RenderViewImpl::printPage(WebLocalFrame* frame) {
1720 FOR_EACH_OBSERVER(RenderViewObserver, observers_,
1721 PrintPage(frame, handling_input_event_));
1724 bool RenderViewImpl::enumerateChosenDirectory(
1725 const WebString& path,
1726 WebFileChooserCompletion* chooser_completion) {
1727 int id = enumeration_completion_id_++;
1728 enumeration_completions_[id] = chooser_completion;
1729 return Send(new ViewHostMsg_EnumerateDirectory(
1730 routing_id_,
1732 base::FilePath::FromUTF16Unsafe(path)));
1735 void RenderViewImpl::FrameDidStartLoading(WebFrame* frame) {
1736 DCHECK_GE(frames_in_progress_, 0);
1737 if (frames_in_progress_ == 0)
1738 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStartLoading());
1739 frames_in_progress_++;
1742 void RenderViewImpl::FrameDidStopLoading(WebFrame* frame) {
1743 // TODO(japhet): This should be a DCHECK, but the pdf plugin sometimes
1744 // calls DidStopLoading() without a matching DidStartLoading().
1745 if (frames_in_progress_ == 0)
1746 return;
1747 frames_in_progress_--;
1748 if (frames_in_progress_ == 0) {
1749 DidStopLoadingIcons();
1750 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStopLoading());
1754 void RenderViewImpl::didCancelCompositionOnSelectionChange() {
1755 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
1758 bool RenderViewImpl::handleCurrentKeyboardEvent() {
1759 if (edit_commands_.empty())
1760 return false;
1762 WebFrame* frame = webview()->focusedFrame();
1763 if (!frame)
1764 return false;
1766 EditCommands::iterator it = edit_commands_.begin();
1767 EditCommands::iterator end = edit_commands_.end();
1769 bool did_execute_command = false;
1770 for (; it != end; ++it) {
1771 // In gtk and cocoa, it's possible to bind multiple edit commands to one
1772 // key (but it's the exception). Once one edit command is not executed, it
1773 // seems safest to not execute the rest.
1774 if (!frame->executeCommand(WebString::fromUTF8(it->name),
1775 WebString::fromUTF8(it->value),
1776 GetFocusedElement()))
1777 break;
1778 did_execute_command = true;
1781 return did_execute_command;
1784 bool RenderViewImpl::runFileChooser(
1785 const blink::WebFileChooserParams& params,
1786 WebFileChooserCompletion* chooser_completion) {
1787 // Do not open the file dialog in a hidden RenderView.
1788 if (is_hidden())
1789 return false;
1790 FileChooserParams ipc_params;
1791 if (params.directory)
1792 ipc_params.mode = FileChooserParams::UploadFolder;
1793 else if (params.multiSelect)
1794 ipc_params.mode = FileChooserParams::OpenMultiple;
1795 else if (params.saveAs)
1796 ipc_params.mode = FileChooserParams::Save;
1797 else
1798 ipc_params.mode = FileChooserParams::Open;
1799 ipc_params.title = params.title;
1800 ipc_params.default_file_name =
1801 base::FilePath::FromUTF16Unsafe(params.initialValue);
1802 ipc_params.accept_types.reserve(params.acceptTypes.size());
1803 for (size_t i = 0; i < params.acceptTypes.size(); ++i)
1804 ipc_params.accept_types.push_back(params.acceptTypes[i]);
1805 #if defined(OS_ANDROID)
1806 ipc_params.capture = params.useMediaCapture;
1807 #endif
1809 return ScheduleFileChooser(ipc_params, chooser_completion);
1812 void RenderViewImpl::showValidationMessage(
1813 const blink::WebRect& anchor_in_root_view,
1814 const blink::WebString& main_text,
1815 const blink::WebString& sub_text,
1816 blink::WebTextDirection hint) {
1817 base::string16 wrapped_main_text = main_text;
1818 base::string16 wrapped_sub_text = sub_text;
1819 if (hint == blink::WebTextDirectionLeftToRight) {
1820 wrapped_main_text =
1821 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_main_text);
1822 if (!wrapped_sub_text.empty()) {
1823 wrapped_sub_text =
1824 base::i18n::GetDisplayStringInLTRDirectionality(wrapped_sub_text);
1826 } else if (hint == blink::WebTextDirectionRightToLeft
1827 && !base::i18n::IsRTL()) {
1828 base::i18n::WrapStringWithRTLFormatting(&wrapped_main_text);
1829 if (!wrapped_sub_text.empty()) {
1830 base::i18n::WrapStringWithRTLFormatting(&wrapped_sub_text);
1833 Send(new ViewHostMsg_ShowValidationMessage(
1834 routing_id(), AdjustValidationMessageAnchor(anchor_in_root_view),
1835 wrapped_main_text, wrapped_sub_text));
1838 void RenderViewImpl::hideValidationMessage() {
1839 Send(new ViewHostMsg_HideValidationMessage(routing_id()));
1842 void RenderViewImpl::moveValidationMessage(
1843 const blink::WebRect& anchor_in_root_view) {
1844 Send(new ViewHostMsg_MoveValidationMessage(
1845 routing_id(), AdjustValidationMessageAnchor(anchor_in_root_view)));
1848 void RenderViewImpl::setStatusText(const WebString& text) {
1851 void RenderViewImpl::UpdateTargetURL(const GURL& url,
1852 const GURL& fallback_url) {
1853 GURL latest_url = url.is_empty() ? fallback_url : url;
1854 if (latest_url == target_url_)
1855 return;
1857 // Tell the browser to display a destination link.
1858 if (target_url_status_ == TARGET_INFLIGHT ||
1859 target_url_status_ == TARGET_PENDING) {
1860 // If we have a request in-flight, save the URL to be sent when we
1861 // receive an ACK to the in-flight request. We can happily overwrite
1862 // any existing pending sends.
1863 pending_target_url_ = latest_url;
1864 target_url_status_ = TARGET_PENDING;
1865 } else {
1866 // URLs larger than |MaxURLChars()| cannot be sent through IPC -
1867 // see |ParamTraits<GURL>|.
1868 if (latest_url.possibly_invalid_spec().size() > GetMaxURLChars())
1869 latest_url = GURL();
1870 Send(new ViewHostMsg_UpdateTargetURL(routing_id_, page_id_, latest_url));
1871 target_url_ = latest_url;
1872 target_url_status_ = TARGET_INFLIGHT;
1876 gfx::RectF RenderViewImpl::ClientRectToPhysicalWindowRect(
1877 const gfx::RectF& rect) const {
1878 gfx::RectF window_rect = rect;
1879 window_rect.Scale(device_scale_factor_ * webview()->pageScaleFactor());
1880 return window_rect;
1883 void RenderViewImpl::StartNavStateSyncTimerIfNecessary() {
1884 // No need to update state if no page has committed yet.
1885 if (page_id_ == -1)
1886 return;
1888 int delay;
1889 if (send_content_state_immediately_)
1890 delay = 0;
1891 else if (is_hidden())
1892 delay = kDelaySecondsForContentStateSyncHidden;
1893 else
1894 delay = kDelaySecondsForContentStateSync;
1896 if (nav_state_sync_timer_.IsRunning()) {
1897 // The timer is already running. If the delay of the timer maches the amount
1898 // we want to delay by, then return. Otherwise stop the timer so that it
1899 // gets started with the right delay.
1900 if (nav_state_sync_timer_.GetCurrentDelay().InSeconds() == delay)
1901 return;
1902 nav_state_sync_timer_.Stop();
1905 nav_state_sync_timer_.Start(FROM_HERE, TimeDelta::FromSeconds(delay), this,
1906 &RenderViewImpl::SyncNavigationState);
1909 void RenderViewImpl::setMouseOverURL(const WebURL& url) {
1910 mouse_over_url_ = GURL(url);
1911 UpdateTargetURL(mouse_over_url_, focus_url_);
1914 void RenderViewImpl::setKeyboardFocusURL(const WebURL& url) {
1915 focus_url_ = GURL(url);
1916 UpdateTargetURL(focus_url_, mouse_over_url_);
1919 void RenderViewImpl::startDragging(WebLocalFrame* frame,
1920 const WebDragData& data,
1921 WebDragOperationsMask mask,
1922 const WebImage& image,
1923 const WebPoint& webImageOffset) {
1924 DropData drop_data(DropDataBuilder::Build(data));
1925 drop_data.referrer_policy = frame->document().referrerPolicy();
1926 gfx::Vector2d imageOffset(webImageOffset.x, webImageOffset.y);
1927 Send(new DragHostMsg_StartDragging(routing_id_,
1928 drop_data,
1929 mask,
1930 image.getSkBitmap(),
1931 imageOffset,
1932 possible_drag_event_info_));
1935 bool RenderViewImpl::acceptsLoadDrops() {
1936 return renderer_preferences_.can_accept_load_drops;
1939 void RenderViewImpl::focusNext() {
1940 Send(new ViewHostMsg_TakeFocus(routing_id_, false));
1943 void RenderViewImpl::focusPrevious() {
1944 Send(new ViewHostMsg_TakeFocus(routing_id_, true));
1947 void RenderViewImpl::focusedNodeChanged(const WebNode& node) {
1948 has_scrolled_focused_editable_node_into_rect_ = false;
1950 Send(new ViewHostMsg_FocusedNodeChanged(routing_id_, IsEditableNode(node)));
1952 FOR_EACH_OBSERVER(RenderViewObserver, observers_, FocusedNodeChanged(node));
1954 // TODO(dmazzoni): this should be part of RenderFrameObserver.
1955 main_render_frame()->FocusedNodeChanged(node);
1958 void RenderViewImpl::didUpdateLayout() {
1959 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidUpdateLayout());
1961 // We don't always want to set up a timer, only if we've been put in that
1962 // mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
1963 // message.
1964 if (!send_preferred_size_changes_ || !webview())
1965 return;
1967 if (check_preferred_size_timer_.IsRunning())
1968 return;
1969 check_preferred_size_timer_.Start(FROM_HERE,
1970 TimeDelta::FromMilliseconds(0), this,
1971 &RenderViewImpl::CheckPreferredSize);
1974 void RenderViewImpl::navigateBackForwardSoon(int offset) {
1975 Send(new ViewHostMsg_GoToEntryAtOffset(routing_id_, offset));
1978 int RenderViewImpl::historyBackListCount() {
1979 return history_list_offset_ < 0 ? 0 : history_list_offset_;
1982 int RenderViewImpl::historyForwardListCount() {
1983 return history_list_length_ - historyBackListCount() - 1;
1986 void RenderViewImpl::postAccessibilityEvent(
1987 const WebAXObject& obj, blink::WebAXEvent event) {
1988 main_render_frame()->HandleWebAccessibilityEvent(obj, event);
1991 // blink::WebWidgetClient ----------------------------------------------------
1993 void RenderViewImpl::didFocus() {
1994 // TODO(jcivelli): when https://bugs.webkit.org/show_bug.cgi?id=33389 is fixed
1995 // we won't have to test for user gesture anymore and we can
1996 // move that code back to render_widget.cc
1997 if (WebUserGestureIndicator::isProcessingUserGesture() &&
1998 !RenderThreadImpl::current()->layout_test_mode()) {
1999 Send(new ViewHostMsg_Focus(routing_id_));
2003 void RenderViewImpl::didBlur() {
2004 // TODO(jcivelli): see TODO above in didFocus().
2005 if (WebUserGestureIndicator::isProcessingUserGesture() &&
2006 !RenderThreadImpl::current()->layout_test_mode()) {
2007 Send(new ViewHostMsg_Blur(routing_id_));
2011 // We are supposed to get a single call to Show for a newly created RenderView
2012 // that was created via RenderViewImpl::CreateWebView. So, we wait until this
2013 // point to dispatch the ShowView message.
2015 // This method provides us with the information about how to display the newly
2016 // created RenderView (i.e., as a blocked popup or as a new tab).
2018 void RenderViewImpl::show(WebNavigationPolicy policy) {
2019 if (did_show_) {
2020 // When supports_multiple_windows is disabled, popups are reusing
2021 // the same view. In some scenarios, this makes WebKit to call show() twice.
2022 if (webkit_preferences_.supports_multiple_windows)
2023 NOTREACHED() << "received extraneous Show call";
2024 return;
2026 did_show_ = true;
2028 DCHECK(opener_id_ != MSG_ROUTING_NONE);
2030 // Force new windows to a popup if they were not opened with a user gesture.
2031 if (!opened_by_user_gesture_) {
2032 // We exempt background tabs for compat with older versions of Chrome.
2033 // TODO(darin): This seems bogus. These should have a user gesture, so
2034 // we probably don't need this check.
2035 if (policy != blink::WebNavigationPolicyNewBackgroundTab)
2036 policy = blink::WebNavigationPolicyNewPopup;
2039 // NOTE: initial_pos_ may still have its default values at this point, but
2040 // that's okay. It'll be ignored if disposition is not NEW_POPUP, or the
2041 // browser process will impose a default position otherwise.
2042 Send(new ViewHostMsg_ShowView(opener_id_, routing_id_,
2043 NavigationPolicyToDisposition(policy), initial_pos_,
2044 opened_by_user_gesture_));
2045 SetPendingWindowRect(initial_pos_);
2048 void RenderViewImpl::runModal() {
2049 DCHECK(did_show_) << "should already have shown the view";
2051 // Don't allow further dialogs if we are waiting to swap out, since the
2052 // PageGroupLoadDeferrer in our stack prevents it.
2053 if (suppress_dialogs_until_swap_out_)
2054 return;
2056 // We must keep WebKit's shared timer running in this case in order to allow
2057 // showModalDialog to function properly.
2059 // TODO(darin): WebKit should really be smarter about suppressing events and
2060 // timers so that we do not need to manage the shared timer in such a heavy
2061 // handed manner.
2063 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
2064 RenderThreadImpl::current()->DoNotSuspendWebKitSharedTimer();
2066 SendAndRunNestedMessageLoop(new ViewHostMsg_RunModal(
2067 routing_id_, opener_id_));
2070 bool RenderViewImpl::enterFullScreen() {
2071 Send(new ViewHostMsg_ToggleFullscreen(routing_id_, true));
2072 return true;
2075 void RenderViewImpl::exitFullScreen() {
2076 Send(new ViewHostMsg_ToggleFullscreen(routing_id_, false));
2079 bool RenderViewImpl::requestPointerLock() {
2080 return mouse_lock_dispatcher_->LockMouse(webwidget_mouse_lock_target_.get());
2083 void RenderViewImpl::requestPointerUnlock() {
2084 mouse_lock_dispatcher_->UnlockMouse(webwidget_mouse_lock_target_.get());
2087 bool RenderViewImpl::isPointerLocked() {
2088 return mouse_lock_dispatcher_->IsMouseLockedTo(
2089 webwidget_mouse_lock_target_.get());
2092 void RenderViewImpl::didHandleGestureEvent(
2093 const WebGestureEvent& event,
2094 bool event_cancelled) {
2095 RenderWidget::didHandleGestureEvent(event, event_cancelled);
2097 if (!event_cancelled) {
2098 FOR_EACH_OBSERVER(
2099 RenderViewObserver, observers_, DidHandleGestureEvent(event));
2102 if (event.type != blink::WebGestureEvent::GestureTap)
2103 return;
2105 // TODO(estade): hit test the event against focused node to make sure
2106 // the tap actually hit the focused node.
2107 blink::WebTextInputType text_input_type =
2108 GetWebView()->textInputInfo().type;
2110 Send(new ViewHostMsg_FocusedNodeTouched(
2111 routing_id(), text_input_type != blink::WebTextInputTypeNone));
2114 void RenderViewImpl::initializeLayerTreeView() {
2115 RenderWidget::initializeLayerTreeView();
2116 RenderWidgetCompositor* rwc = compositor();
2117 if (!rwc)
2118 return;
2119 if (webview() && webview()->devToolsAgent())
2120 webview()->devToolsAgent()->setLayerTreeId(rwc->GetLayerTreeId());
2122 #if !defined(OS_MACOSX) // many events are unhandled - http://crbug.com/138003
2123 RenderThreadImpl* render_thread = RenderThreadImpl::current();
2124 // render_thread may be NULL in tests.
2125 InputHandlerManager* input_handler_manager =
2126 render_thread ? render_thread->input_handler_manager() : NULL;
2127 if (input_handler_manager) {
2128 input_handler_manager->AddInputHandler(
2129 routing_id_, rwc->GetInputHandler(), AsWeakPtr());
2131 #endif
2134 // blink::WebFrameClient -----------------------------------------------------
2136 void RenderViewImpl::Repaint(const gfx::Size& size) {
2137 OnRepaint(size);
2140 void RenderViewImpl::SetEditCommandForNextKeyEvent(const std::string& name,
2141 const std::string& value) {
2142 EditCommands edit_commands;
2143 edit_commands.push_back(EditCommand(name, value));
2144 OnSetEditCommandsForNextKeyEvent(edit_commands);
2147 void RenderViewImpl::ClearEditCommands() {
2148 edit_commands_.clear();
2151 SSLStatus RenderViewImpl::GetSSLStatusOfFrame(blink::WebFrame* frame) const {
2152 std::string security_info;
2153 if (frame && frame->dataSource())
2154 security_info = frame->dataSource()->response().securityInfo();
2156 SSLStatus ssl_status;
2157 DeserializeSecurityInfo(security_info,
2158 &ssl_status.cert_id,
2159 &ssl_status.cert_status,
2160 &ssl_status.security_bits,
2161 &ssl_status.connection_status,
2162 &ssl_status.signed_certificate_timestamp_ids);
2163 return ssl_status;
2166 const std::string& RenderViewImpl::GetAcceptLanguages() const {
2167 return renderer_preferences_.accept_languages;
2170 void RenderViewImpl::didCreateDataSource(WebLocalFrame* frame,
2171 WebDataSource* ds) {
2172 bool content_initiated = !pending_navigation_params_.get();
2174 // Make sure any previous redirect URLs end up in our new data source.
2175 if (pending_navigation_params_.get()) {
2176 for (std::vector<GURL>::const_iterator i =
2177 pending_navigation_params_->redirects.begin();
2178 i != pending_navigation_params_->redirects.end(); ++i) {
2179 ds->appendRedirect(*i);
2183 DocumentState* document_state = DocumentState::FromDataSource(ds);
2184 if (!document_state) {
2185 document_state = new DocumentState;
2186 ds->setExtraData(document_state);
2187 if (!content_initiated)
2188 PopulateDocumentStateFromPending(document_state);
2191 // Carry over the user agent override flag, if it exists.
2192 if (content_initiated && webview() && webview()->mainFrame() &&
2193 webview()->mainFrame()->isWebLocalFrame() &&
2194 webview()->mainFrame()->dataSource()) {
2195 DocumentState* old_document_state =
2196 DocumentState::FromDataSource(webview()->mainFrame()->dataSource());
2197 if (old_document_state) {
2198 InternalDocumentStateData* internal_data =
2199 InternalDocumentStateData::FromDocumentState(document_state);
2200 InternalDocumentStateData* old_internal_data =
2201 InternalDocumentStateData::FromDocumentState(old_document_state);
2202 internal_data->set_is_overriding_user_agent(
2203 old_internal_data->is_overriding_user_agent());
2207 // The rest of RenderView assumes that a WebDataSource will always have a
2208 // non-null NavigationState.
2209 if (content_initiated) {
2210 document_state->set_navigation_state(
2211 NavigationState::CreateContentInitiated());
2212 } else {
2213 document_state->set_navigation_state(CreateNavigationStateFromPending());
2214 pending_navigation_params_.reset();
2217 // DocumentState::referred_by_prefetcher_ is true if we are
2218 // navigating from a page that used prefetching using a link on that
2219 // page. We are early enough in the request process here that we
2220 // can still see the DocumentState of the previous page and set
2221 // this value appropriately.
2222 // TODO(gavinp): catch the important case of navigation in a new
2223 // renderer process.
2224 if (webview()) {
2225 if (WebFrame* old_frame = webview()->mainFrame()) {
2226 const WebURLRequest& original_request = ds->originalRequest();
2227 const GURL referrer(
2228 original_request.httpHeaderField(WebString::fromUTF8("Referer")));
2229 if (!referrer.is_empty() && old_frame->isWebLocalFrame() &&
2230 DocumentState::FromDataSource(old_frame->dataSource())
2231 ->was_prefetcher()) {
2232 for (; old_frame; old_frame = old_frame->traverseNext(false)) {
2233 WebDataSource* old_frame_ds = old_frame->dataSource();
2234 if (old_frame_ds && referrer == GURL(old_frame_ds->request().url())) {
2235 document_state->set_was_referred_by_prefetcher(true);
2236 break;
2243 if (content_initiated) {
2244 const WebURLRequest& request = ds->request();
2245 switch (request.cachePolicy()) {
2246 case WebURLRequest::UseProtocolCachePolicy: // normal load.
2247 document_state->set_load_type(DocumentState::LINK_LOAD_NORMAL);
2248 break;
2249 case WebURLRequest::ReloadIgnoringCacheData: // reload.
2250 case WebURLRequest::ReloadBypassingCache: // end-to-end reload.
2251 document_state->set_load_type(DocumentState::LINK_LOAD_RELOAD);
2252 break;
2253 case WebURLRequest::ReturnCacheDataElseLoad: // allow stale data.
2254 document_state->set_load_type(
2255 DocumentState::LINK_LOAD_CACHE_STALE_OK);
2256 break;
2257 case WebURLRequest::ReturnCacheDataDontLoad: // Don't re-post.
2258 document_state->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY);
2259 break;
2260 default:
2261 NOTREACHED();
2265 FOR_EACH_OBSERVER(
2266 RenderViewObserver, observers_, DidCreateDataSource(frame, ds));
2269 void RenderViewImpl::PopulateDocumentStateFromPending(
2270 DocumentState* document_state) {
2271 const FrameMsg_Navigate_Params& params = *pending_navigation_params_.get();
2272 document_state->set_request_time(params.request_time);
2274 InternalDocumentStateData* internal_data =
2275 InternalDocumentStateData::FromDocumentState(document_state);
2277 if (!params.url.SchemeIs(url::kJavaScriptScheme) &&
2278 params.navigation_type == FrameMsg_Navigate_Type::RESTORE) {
2279 // We're doing a load of a page that was restored from the last session. By
2280 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
2281 // can result in stale data for pages that are set to expire. We explicitly
2282 // override that by setting the policy here so that as necessary we load
2283 // from the network.
2285 // TODO(davidben): Remove this in favor of passing a cache policy to the
2286 // loadHistoryItem call in OnNavigate. That requires not overloading
2287 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
2288 // policy based on load type, etc".
2289 internal_data->set_cache_policy_override(
2290 WebURLRequest::UseProtocolCachePolicy);
2293 if (IsReload(params))
2294 document_state->set_load_type(DocumentState::RELOAD);
2295 else if (params.page_state.IsValid())
2296 document_state->set_load_type(DocumentState::HISTORY_LOAD);
2297 else
2298 document_state->set_load_type(DocumentState::NORMAL_LOAD);
2300 internal_data->set_is_overriding_user_agent(params.is_overriding_user_agent);
2301 internal_data->set_must_reset_scroll_and_scale_state(
2302 params.navigation_type ==
2303 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
2304 document_state->set_can_load_local_resources(params.can_load_local_resources);
2307 NavigationState* RenderViewImpl::CreateNavigationStateFromPending() {
2308 const FrameMsg_Navigate_Params& params = *pending_navigation_params_.get();
2309 NavigationState* navigation_state = NULL;
2311 // A navigation resulting from loading a javascript URL should not be treated
2312 // as a browser initiated event. Instead, we want it to look as if the page
2313 // initiated any load resulting from JS execution.
2314 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
2315 navigation_state = NavigationState::CreateBrowserInitiated(
2316 params.page_id,
2317 params.pending_history_list_offset,
2318 params.should_clear_history_list,
2319 params.transition);
2320 navigation_state->set_should_replace_current_entry(
2321 params.should_replace_current_entry);
2322 navigation_state->set_transferred_request_child_id(
2323 params.transferred_request_child_id);
2324 navigation_state->set_transferred_request_request_id(
2325 params.transferred_request_request_id);
2326 navigation_state->set_allow_download(params.allow_download);
2327 navigation_state->set_extra_headers(params.extra_headers);
2328 } else {
2329 navigation_state = NavigationState::CreateContentInitiated();
2331 return navigation_state;
2334 void RenderViewImpl::ProcessViewLayoutFlags(const CommandLine& command_line) {
2335 bool enable_viewport =
2336 command_line.HasSwitch(switches::kEnableViewport) ||
2337 command_line.HasSwitch(switches::kEnableViewportMeta);
2339 // If viewport tag is enabled, then the WebKit side will take care
2340 // of setting the fixed layout size and page scale limits.
2341 if (enable_viewport)
2342 return;
2344 // When navigating to a new page, reset the page scale factor to be 1.0.
2345 webview()->setInitialPageScaleOverride(1.f);
2347 float maxPageScaleFactor =
2348 command_line.HasSwitch(switches::kEnablePinch) ? 4.f : 1.f ;
2349 webview()->setPageScaleFactorLimits(1, maxPageScaleFactor);
2352 void RenderViewImpl::didClearWindowObject(WebLocalFrame* frame) {
2353 FOR_EACH_OBSERVER(
2354 RenderViewObserver, observers_, DidClearWindowObject(frame));
2356 if (enabled_bindings_& BINDINGS_POLICY_WEB_UI)
2357 WebUIExtension::Install(frame);
2359 if (enabled_bindings_ & BINDINGS_POLICY_STATS_COLLECTION)
2360 StatsCollectionController::Install(frame);
2362 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
2364 if (command_line.HasSwitch(switches::kEnableSkiaBenchmarking))
2365 SkiaBenchmarking::Install(frame);
2367 if (command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
2368 MemoryBenchmarkingExtension::Install(frame);
2371 void RenderViewImpl::didChangeIcon(WebLocalFrame* frame,
2372 WebIconURL::Type icon_type) {
2373 if (frame->parent())
2374 return;
2376 if (!TouchEnabled() && icon_type != WebIconURL::TypeFavicon)
2377 return;
2379 WebVector<WebIconURL> icon_urls = frame->iconURLs(icon_type);
2380 std::vector<FaviconURL> urls;
2381 for (size_t i = 0; i < icon_urls.size(); i++) {
2382 std::vector<gfx::Size> sizes;
2383 ConvertToFaviconSizes(icon_urls[i].sizes(), &sizes);
2384 urls.push_back(FaviconURL(
2385 icon_urls[i].iconURL(), ToFaviconType(icon_urls[i].iconType()), sizes));
2387 SendUpdateFaviconURL(urls);
2390 void RenderViewImpl::didUpdateCurrentHistoryItem(WebLocalFrame* frame) {
2391 StartNavStateSyncTimerIfNecessary();
2394 void RenderViewImpl::CheckPreferredSize() {
2395 // We don't always want to send the change messages over IPC, only if we've
2396 // been put in that mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
2397 // message.
2398 if (!send_preferred_size_changes_ || !webview())
2399 return;
2401 gfx::Size size = webview()->contentsPreferredMinimumSize();
2403 // In the presence of zoom, these sizes are still reported as if unzoomed,
2404 // so we need to adjust.
2405 double zoom_factor = ZoomLevelToZoomFactor(webview()->zoomLevel());
2406 size.set_width(static_cast<int>(size.width() * zoom_factor));
2407 size.set_height(static_cast<int>(size.height() * zoom_factor));
2409 if (size == preferred_size_)
2410 return;
2412 preferred_size_ = size;
2413 Send(new ViewHostMsg_DidContentsPreferredSizeChange(routing_id_,
2414 preferred_size_));
2417 BrowserPluginManager* RenderViewImpl::GetBrowserPluginManager() {
2418 if (!browser_plugin_manager_.get())
2419 browser_plugin_manager_ = BrowserPluginManager::Create(this);
2420 return browser_plugin_manager_.get();
2423 void RenderViewImpl::didChangeScrollOffset(WebLocalFrame* frame) {
2424 StartNavStateSyncTimerIfNecessary();
2426 FOR_EACH_OBSERVER(
2427 RenderViewObserver, observers_, DidChangeScrollOffset(frame));
2430 void RenderViewImpl::SendFindReply(int request_id,
2431 int match_count,
2432 int ordinal,
2433 const WebRect& selection_rect,
2434 bool final_status_update) {
2435 Send(new ViewHostMsg_Find_Reply(routing_id_,
2436 request_id,
2437 match_count,
2438 selection_rect,
2439 ordinal,
2440 final_status_update));
2443 blink::WebString RenderViewImpl::acceptLanguages() {
2444 return WebString::fromUTF8(renderer_preferences_.accept_languages);
2447 // blink::WebPageSerializerClient implementation ------------------------------
2449 void RenderViewImpl::didSerializeDataForFrame(
2450 const WebURL& frame_url,
2451 const WebCString& data,
2452 WebPageSerializerClient::PageSerializationStatus status) {
2453 Send(new ViewHostMsg_SendSerializedHtmlData(
2454 routing_id(),
2455 frame_url,
2456 data.data(),
2457 static_cast<int32>(status)));
2460 // RenderView implementation ---------------------------------------------------
2462 bool RenderViewImpl::Send(IPC::Message* message) {
2463 return RenderWidget::Send(message);
2466 RenderFrame* RenderViewImpl::GetMainRenderFrame() {
2467 return main_render_frame_.get();
2470 int RenderViewImpl::GetRoutingID() const {
2471 return routing_id_;
2474 gfx::Size RenderViewImpl::GetSize() const {
2475 return size();
2478 WebPreferences& RenderViewImpl::GetWebkitPreferences() {
2479 return webkit_preferences_;
2482 void RenderViewImpl::SetWebkitPreferences(const WebPreferences& preferences) {
2483 OnUpdateWebPreferences(preferences);
2486 blink::WebView* RenderViewImpl::GetWebView() {
2487 return webview();
2490 blink::WebElement RenderViewImpl::GetFocusedElement() const {
2491 if (!webview())
2492 return WebElement();
2493 WebFrame* focused_frame = webview()->focusedFrame();
2494 if (focused_frame) {
2495 WebDocument doc = focused_frame->document();
2496 if (!doc.isNull())
2497 return doc.focusedElement();
2500 return WebElement();
2503 bool RenderViewImpl::IsEditableNode(const WebNode& node) const {
2504 if (node.isNull())
2505 return false;
2507 if (node.isContentEditable())
2508 return true;
2510 if (node.isElementNode()) {
2511 const WebElement& element = node.toConst<WebElement>();
2512 if (element.isTextFormControlElement())
2513 return true;
2515 // Also return true if it has an ARIA role of 'textbox'.
2516 for (unsigned i = 0; i < element.attributeCount(); ++i) {
2517 if (LowerCaseEqualsASCII(element.attributeLocalName(i), "role")) {
2518 if (LowerCaseEqualsASCII(element.attributeValue(i), "textbox"))
2519 return true;
2520 break;
2525 return false;
2528 bool RenderViewImpl::NodeContainsPoint(const WebNode& node,
2529 const gfx::Point& point) const {
2530 blink::WebHitTestResult hit_test =
2531 webview()->hitTestResultAt(WebPoint(point.x(), point.y()));
2532 return node.containsIncludingShadowDOM(hit_test.node());
2535 bool RenderViewImpl::ShouldDisplayScrollbars(int width, int height) const {
2536 return (!send_preferred_size_changes_ ||
2537 (disable_scrollbars_size_limit_.width() <= width ||
2538 disable_scrollbars_size_limit_.height() <= height));
2541 int RenderViewImpl::GetEnabledBindings() const {
2542 return enabled_bindings_;
2545 bool RenderViewImpl::GetContentStateImmediately() const {
2546 return send_content_state_immediately_;
2549 blink::WebPageVisibilityState RenderViewImpl::GetVisibilityState() const {
2550 return visibilityState();
2553 void RenderViewImpl::DidStartLoading() {
2554 main_render_frame_->didStartLoading(true);
2557 void RenderViewImpl::DidStopLoading() {
2558 main_render_frame_->didStopLoading();
2561 void RenderViewImpl::SyncNavigationState() {
2562 if (!webview())
2563 return;
2564 SendUpdateState(history_controller_->GetCurrentEntry());
2567 blink::WebPlugin* RenderViewImpl::GetWebPluginForFind() {
2568 if (!webview())
2569 return NULL;
2571 WebFrame* main_frame = webview()->mainFrame();
2572 if (main_frame->isWebLocalFrame() &&
2573 main_frame->document().isPluginDocument())
2574 return webview()->mainFrame()->document().to<WebPluginDocument>().plugin();
2576 #if defined(ENABLE_PLUGINS)
2577 if (plugin_find_handler_)
2578 return plugin_find_handler_->container()->plugin();
2579 #endif
2581 return NULL;
2584 void RenderViewImpl::OnFind(int request_id,
2585 const base::string16& search_text,
2586 const WebFindOptions& options) {
2587 WebFrame* main_frame = webview()->mainFrame();
2588 blink::WebPlugin* plugin = GetWebPluginForFind();
2589 // Check if the plugin still exists in the document.
2590 if (plugin) {
2591 if (options.findNext) {
2592 // Just navigate back/forward.
2593 plugin->selectFindResult(options.forward);
2594 } else {
2595 if (!plugin->startFind(
2596 search_text, options.matchCase, request_id)) {
2597 // Send "no results".
2598 SendFindReply(request_id, 0, 0, gfx::Rect(), true);
2601 return;
2604 WebFrame* frame_after_main = main_frame->traverseNext(true);
2605 WebFrame* focused_frame = webview()->focusedFrame();
2606 WebFrame* search_frame = focused_frame; // start searching focused frame.
2608 bool multi_frame = (frame_after_main != main_frame);
2610 // If we have multiple frames, we don't want to wrap the search within the
2611 // frame, so we check here if we only have main_frame in the chain.
2612 bool wrap_within_frame = !multi_frame;
2614 WebRect selection_rect;
2615 bool result = false;
2617 // If something is selected when we start searching it means we cannot just
2618 // increment the current match ordinal; we need to re-generate it.
2619 WebRange current_selection = focused_frame->selectionRange();
2621 do {
2622 result = search_frame->find(
2623 request_id, search_text, options, wrap_within_frame, &selection_rect);
2625 if (!result) {
2626 // don't leave text selected as you move to the next frame.
2627 search_frame->executeCommand(WebString::fromUTF8("Unselect"),
2628 GetFocusedElement());
2630 // Find the next frame, but skip the invisible ones.
2631 do {
2632 // What is the next frame to search? (we might be going backwards). Note
2633 // that we specify wrap=true so that search_frame never becomes NULL.
2634 search_frame = options.forward ?
2635 search_frame->traverseNext(true) :
2636 search_frame->traversePrevious(true);
2637 } while (!search_frame->hasVisibleContent() &&
2638 search_frame != focused_frame);
2640 // Make sure selection doesn't affect the search operation in new frame.
2641 search_frame->executeCommand(WebString::fromUTF8("Unselect"),
2642 GetFocusedElement());
2644 // If we have multiple frames and we have wrapped back around to the
2645 // focused frame, we need to search it once more allowing wrap within
2646 // the frame, otherwise it will report 'no match' if the focused frame has
2647 // reported matches, but no frames after the focused_frame contain a
2648 // match for the search word(s).
2649 if (multi_frame && search_frame == focused_frame) {
2650 result = search_frame->find(
2651 request_id, search_text, options, true, // Force wrapping.
2652 &selection_rect);
2656 webview()->setFocusedFrame(search_frame);
2657 } while (!result && search_frame != focused_frame);
2659 if (options.findNext && current_selection.isNull()) {
2660 // Force the main_frame to report the actual count.
2661 main_frame->increaseMatchCount(0, request_id);
2662 } else {
2663 // If nothing is found, set result to "0 of 0", otherwise, set it to
2664 // "-1 of 1" to indicate that we found at least one item, but we don't know
2665 // yet what is active.
2666 int ordinal = result ? -1 : 0; // -1 here means, we might know more later.
2667 int match_count = result ? 1 : 0; // 1 here means possibly more coming.
2669 // If we find no matches then this will be our last status update.
2670 // Otherwise the scoping effort will send more results.
2671 bool final_status_update = !result;
2673 SendFindReply(request_id, match_count, ordinal, selection_rect,
2674 final_status_update);
2676 // Scoping effort begins, starting with the mainframe.
2677 search_frame = main_frame;
2679 main_frame->resetMatchCount();
2681 do {
2682 // Cancel all old scoping requests before starting a new one.
2683 search_frame->cancelPendingScopingEffort();
2685 // We don't start another scoping effort unless at least one match has
2686 // been found.
2687 if (result) {
2688 // Start new scoping request. If the scoping function determines that it
2689 // needs to scope, it will defer until later.
2690 search_frame->scopeStringMatches(request_id,
2691 search_text,
2692 options,
2693 true); // reset the tickmarks
2696 // Iterate to the next frame. The frame will not necessarily scope, for
2697 // example if it is not visible.
2698 search_frame = search_frame->traverseNext(true);
2699 } while (search_frame != main_frame);
2703 void RenderViewImpl::OnStopFinding(StopFindAction action) {
2704 WebView* view = webview();
2705 if (!view)
2706 return;
2708 blink::WebPlugin* plugin = GetWebPluginForFind();
2709 if (plugin) {
2710 plugin->stopFind();
2711 return;
2714 bool clear_selection = action == STOP_FIND_ACTION_CLEAR_SELECTION;
2715 if (clear_selection) {
2716 view->focusedFrame()->executeCommand(WebString::fromUTF8("Unselect"),
2717 GetFocusedElement());
2720 WebFrame* frame = view->mainFrame();
2721 while (frame) {
2722 frame->stopFinding(clear_selection);
2723 frame = frame->traverseNext(false);
2726 if (action == STOP_FIND_ACTION_ACTIVATE_SELECTION) {
2727 WebFrame* focused_frame = view->focusedFrame();
2728 if (focused_frame) {
2729 WebDocument doc = focused_frame->document();
2730 if (!doc.isNull()) {
2731 WebElement element = doc.focusedElement();
2732 if (!element.isNull())
2733 element.simulateClick();
2739 #if defined(OS_ANDROID)
2740 void RenderViewImpl::OnActivateNearestFindResult(int request_id,
2741 float x, float y) {
2742 if (!webview())
2743 return;
2745 WebFrame* main_frame = webview()->mainFrame();
2746 WebRect selection_rect;
2747 int ordinal = main_frame->selectNearestFindMatch(WebFloatPoint(x, y),
2748 &selection_rect);
2749 if (ordinal == -1) {
2750 // Something went wrong, so send a no-op reply (force the main_frame to
2751 // report the current match count) in case the host is waiting for a
2752 // response due to rate-limiting).
2753 main_frame->increaseMatchCount(0, request_id);
2754 return;
2757 SendFindReply(request_id,
2758 -1 /* number_of_matches */,
2759 ordinal,
2760 selection_rect,
2761 true /* final_update */);
2764 void RenderViewImpl::OnFindMatchRects(int current_version) {
2765 if (!webview())
2766 return;
2768 WebFrame* main_frame = webview()->mainFrame();
2769 std::vector<gfx::RectF> match_rects;
2771 int rects_version = main_frame->findMatchMarkersVersion();
2772 if (current_version != rects_version) {
2773 WebVector<WebFloatRect> web_match_rects;
2774 main_frame->findMatchRects(web_match_rects);
2775 match_rects.reserve(web_match_rects.size());
2776 for (size_t i = 0; i < web_match_rects.size(); ++i)
2777 match_rects.push_back(gfx::RectF(web_match_rects[i]));
2780 gfx::RectF active_rect = main_frame->activeFindMatchRect();
2781 Send(new ViewHostMsg_FindMatchRects_Reply(routing_id_,
2782 rects_version,
2783 match_rects,
2784 active_rect));
2786 #endif
2788 void RenderViewImpl::OnZoom(PageZoom zoom) {
2789 if (!webview()) // Not sure if this can happen, but no harm in being safe.
2790 return;
2792 webview()->hidePopups();
2794 double old_zoom_level = webview()->zoomLevel();
2795 double zoom_level;
2796 if (zoom == PAGE_ZOOM_RESET) {
2797 zoom_level = 0;
2798 } else if (static_cast<int>(old_zoom_level) == old_zoom_level) {
2799 // Previous zoom level is a whole number, so just increment/decrement.
2800 zoom_level = old_zoom_level + zoom;
2801 } else {
2802 // Either the user hit the zoom factor limit and thus the zoom level is now
2803 // not a whole number, or a plugin changed it to a custom value. We want
2804 // to go to the next whole number so that the user can always get back to
2805 // 100% with the keyboard/menu.
2806 if ((old_zoom_level > 1 && zoom > 0) ||
2807 (old_zoom_level < 1 && zoom < 0)) {
2808 zoom_level = static_cast<int>(old_zoom_level + zoom);
2809 } else {
2810 // We're going towards 100%, so first go to the next whole number.
2811 zoom_level = static_cast<int>(old_zoom_level);
2814 webview()->setZoomLevel(zoom_level);
2815 zoomLevelChanged();
2818 void RenderViewImpl::OnSetZoomLevelForLoadingURL(const GURL& url,
2819 double zoom_level) {
2820 #if !defined(OS_ANDROID)
2821 // On Android, page zoom isn't used, and in case of WebView, text zoom is used
2822 // for legacy WebView text scaling emulation. Thus, the code that resets
2823 // the zoom level from this map will be effectively resetting text zoom level.
2824 host_zoom_levels_[url] = zoom_level;
2825 #endif
2828 void RenderViewImpl::OnSetZoomLevelForView(bool uses_temporary_zoom_level,
2829 double level) {
2830 uses_temporary_zoom_level_ = uses_temporary_zoom_level;
2832 webview()->hidePopups();
2833 webview()->setZoomLevel(level);
2836 void RenderViewImpl::OnSetPageEncoding(const std::string& encoding_name) {
2837 webview()->setPageEncoding(WebString::fromUTF8(encoding_name));
2840 void RenderViewImpl::OnResetPageEncodingToDefault() {
2841 WebString no_encoding;
2842 webview()->setPageEncoding(no_encoding);
2845 void RenderViewImpl::OnPostMessageEvent(
2846 const ViewMsg_PostMessage_Params& params) {
2847 // TODO(nasko): Support sending to subframes.
2848 WebFrame* frame = webview()->mainFrame();
2850 // Find the source frame if it exists.
2851 WebFrame* source_frame = NULL;
2852 if (params.source_routing_id != MSG_ROUTING_NONE) {
2853 RenderViewImpl* source_view = FromRoutingID(params.source_routing_id);
2854 if (source_view)
2855 source_frame = source_view->webview()->mainFrame();
2858 // If the message contained MessagePorts, create the corresponding endpoints.
2859 DCHECK_EQ(params.message_port_ids.size(), params.new_routing_ids.size());
2860 blink::WebMessagePortChannelArray channels(params.message_port_ids.size());
2861 for (size_t i = 0;
2862 i < params.message_port_ids.size() && i < params.new_routing_ids.size();
2863 ++i) {
2864 channels[i] =
2865 new WebMessagePortChannelImpl(params.new_routing_ids[i],
2866 params.message_port_ids[i],
2867 base::MessageLoopProxy::current().get());
2870 WebSerializedScriptValue serialized_script_value;
2871 if (params.is_data_raw_string) {
2872 v8::HandleScope handle_scope(blink::mainThreadIsolate());
2873 v8::Local<v8::Context> context = frame->mainWorldScriptContext();
2874 v8::Context::Scope context_scope(context);
2875 V8ValueConverterImpl converter;
2876 converter.SetDateAllowed(true);
2877 converter.SetRegExpAllowed(true);
2878 scoped_ptr<base::Value> value(new base::StringValue(params.data));
2879 v8::Handle<v8::Value> result_value = converter.ToV8Value(value.get(),
2880 context);
2881 serialized_script_value = WebSerializedScriptValue::serialize(result_value);
2882 } else {
2883 serialized_script_value = WebSerializedScriptValue::fromString(params.data);
2886 // Create an event with the message. The final parameter to initMessageEvent
2887 // is the last event ID, which is not used with postMessage.
2888 WebDOMEvent event = frame->document().createEvent("MessageEvent");
2889 WebDOMMessageEvent msg_event = event.to<WebDOMMessageEvent>();
2890 msg_event.initMessageEvent("message",
2891 // |canBubble| and |cancellable| are always false
2892 false, false,
2893 serialized_script_value,
2894 params.source_origin, source_frame, "", channels);
2896 // We must pass in the target_origin to do the security check on this side,
2897 // since it may have changed since the original postMessage call was made.
2898 WebSecurityOrigin target_origin;
2899 if (!params.target_origin.empty()) {
2900 target_origin =
2901 WebSecurityOrigin::createFromString(WebString(params.target_origin));
2903 frame->dispatchMessageEventWithOriginCheck(target_origin, msg_event);
2906 void RenderViewImpl::OnAllowBindings(int enabled_bindings_flags) {
2907 if ((enabled_bindings_flags & BINDINGS_POLICY_WEB_UI) &&
2908 !(enabled_bindings_ & BINDINGS_POLICY_WEB_UI)) {
2909 // WebUIExtensionData deletes itself when we're destroyed.
2910 new WebUIExtensionData(this);
2911 // WebUIMojo deletes itself when we're destroyed.
2912 new WebUIMojo(this);
2915 enabled_bindings_ |= enabled_bindings_flags;
2917 // Keep track of the total bindings accumulated in this process.
2918 RenderProcess::current()->AddBindings(enabled_bindings_flags);
2921 void RenderViewImpl::OnDragTargetDragEnter(const DropData& drop_data,
2922 const gfx::Point& client_point,
2923 const gfx::Point& screen_point,
2924 WebDragOperationsMask ops,
2925 int key_modifiers) {
2926 WebDragOperation operation = webview()->dragTargetDragEnter(
2927 DropDataToWebDragData(drop_data),
2928 client_point,
2929 screen_point,
2930 ops,
2931 key_modifiers);
2933 Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
2936 void RenderViewImpl::OnDragTargetDragOver(const gfx::Point& client_point,
2937 const gfx::Point& screen_point,
2938 WebDragOperationsMask ops,
2939 int key_modifiers) {
2940 WebDragOperation operation = webview()->dragTargetDragOver(
2941 client_point,
2942 screen_point,
2943 ops,
2944 key_modifiers);
2946 Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
2949 void RenderViewImpl::OnDragTargetDragLeave() {
2950 webview()->dragTargetDragLeave();
2953 void RenderViewImpl::OnDragTargetDrop(const gfx::Point& client_point,
2954 const gfx::Point& screen_point,
2955 int key_modifiers) {
2956 webview()->dragTargetDrop(client_point, screen_point, key_modifiers);
2958 Send(new DragHostMsg_TargetDrop_ACK(routing_id_));
2961 void RenderViewImpl::OnDragSourceEnded(const gfx::Point& client_point,
2962 const gfx::Point& screen_point,
2963 WebDragOperation op) {
2964 webview()->dragSourceEndedAt(client_point, screen_point, op);
2967 void RenderViewImpl::OnDragSourceSystemDragEnded() {
2968 webview()->dragSourceSystemDragEnded();
2971 void RenderViewImpl::OnUpdateWebPreferences(const WebPreferences& prefs) {
2972 webkit_preferences_ = prefs;
2973 ApplyWebPreferences(webkit_preferences_, webview());
2976 void RenderViewImpl::OnEnumerateDirectoryResponse(
2977 int id,
2978 const std::vector<base::FilePath>& paths) {
2979 if (!enumeration_completions_[id])
2980 return;
2982 WebVector<WebString> ws_file_names(paths.size());
2983 for (size_t i = 0; i < paths.size(); ++i)
2984 ws_file_names[i] = paths[i].AsUTF16Unsafe();
2986 enumeration_completions_[id]->didChooseFile(ws_file_names);
2987 enumeration_completions_.erase(id);
2990 void RenderViewImpl::OnFileChooserResponse(
2991 const std::vector<ui::SelectedFileInfo>& files) {
2992 // This could happen if we navigated to a different page before the user
2993 // closed the chooser.
2994 if (file_chooser_completions_.empty())
2995 return;
2997 // Convert Chrome's SelectedFileInfo list to WebKit's.
2998 WebVector<WebFileChooserCompletion::SelectedFileInfo> selected_files(
2999 files.size());
3000 for (size_t i = 0; i < files.size(); ++i) {
3001 WebFileChooserCompletion::SelectedFileInfo selected_file;
3002 selected_file.path = files[i].local_path.AsUTF16Unsafe();
3003 selected_file.displayName =
3004 base::FilePath(files[i].display_name).AsUTF16Unsafe();
3005 selected_files[i] = selected_file;
3008 if (file_chooser_completions_.front()->completion)
3009 file_chooser_completions_.front()->completion->didChooseFile(
3010 selected_files);
3011 file_chooser_completions_.pop_front();
3013 // If there are more pending file chooser requests, schedule one now.
3014 if (!file_chooser_completions_.empty()) {
3015 Send(new ViewHostMsg_RunFileChooser(routing_id_,
3016 file_chooser_completions_.front()->params));
3020 void RenderViewImpl::OnEnableAutoResize(const gfx::Size& min_size,
3021 const gfx::Size& max_size) {
3022 DCHECK(disable_scrollbars_size_limit_.IsEmpty());
3023 if (!webview())
3024 return;
3025 auto_resize_mode_ = true;
3026 webview()->enableAutoResizeMode(min_size, max_size);
3029 void RenderViewImpl::OnDisableAutoResize(const gfx::Size& new_size) {
3030 DCHECK(disable_scrollbars_size_limit_.IsEmpty());
3031 if (!webview())
3032 return;
3033 auto_resize_mode_ = false;
3034 webview()->disableAutoResizeMode();
3036 if (!new_size.IsEmpty()) {
3037 Resize(new_size,
3038 physical_backing_size_,
3039 top_controls_layout_height_,
3040 visible_viewport_size_,
3041 resizer_rect_,
3042 is_fullscreen_,
3043 NO_RESIZE_ACK);
3047 void RenderViewImpl::OnEnablePreferredSizeChangedMode() {
3048 if (send_preferred_size_changes_)
3049 return;
3050 send_preferred_size_changes_ = true;
3052 // Start off with an initial preferred size notification (in case
3053 // |didUpdateLayout| was already called).
3054 didUpdateLayout();
3057 void RenderViewImpl::OnDisableScrollbarsForSmallWindows(
3058 const gfx::Size& disable_scrollbar_size_limit) {
3059 disable_scrollbars_size_limit_ = disable_scrollbar_size_limit;
3062 void RenderViewImpl::OnSetRendererPrefs(
3063 const RendererPreferences& renderer_prefs) {
3064 double old_zoom_level = renderer_preferences_.default_zoom_level;
3065 std::string old_accept_languages = renderer_preferences_.accept_languages;
3067 renderer_preferences_ = renderer_prefs;
3068 UpdateFontRenderingFromRendererPrefs();
3070 #if defined(USE_DEFAULT_RENDER_THEME)
3071 if (renderer_prefs.use_custom_colors) {
3072 WebColorName name = blink::WebColorWebkitFocusRingColor;
3073 blink::setNamedColors(&name, &renderer_prefs.focus_ring_color, 1);
3074 blink::setCaretBlinkInterval(renderer_prefs.caret_blink_interval);
3076 if (webview()) {
3077 webview()->setSelectionColors(
3078 renderer_prefs.active_selection_bg_color,
3079 renderer_prefs.active_selection_fg_color,
3080 renderer_prefs.inactive_selection_bg_color,
3081 renderer_prefs.inactive_selection_fg_color);
3082 webview()->themeChanged();
3085 #endif // defined(USE_DEFAULT_RENDER_THEME)
3087 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
3088 RenderThreadImpl::current()->SetFlingCurveParameters(
3089 renderer_prefs.touchpad_fling_profile,
3090 renderer_prefs.touchscreen_fling_profile);
3092 // If the zoom level for this page matches the old zoom default, and this
3093 // is not a plugin, update the zoom level to match the new default.
3094 if (webview() && webview()->mainFrame()->isWebLocalFrame() &&
3095 !webview()->mainFrame()->document().isPluginDocument() &&
3096 !ZoomValuesEqual(old_zoom_level,
3097 renderer_preferences_.default_zoom_level) &&
3098 ZoomValuesEqual(webview()->zoomLevel(), old_zoom_level)) {
3099 webview()->setZoomLevel(renderer_preferences_.default_zoom_level);
3100 zoomLevelChanged();
3103 if (webview() &&
3104 old_accept_languages != renderer_preferences_.accept_languages) {
3105 webview()->acceptLanguagesChanged();
3109 void RenderViewImpl::OnMediaPlayerActionAt(const gfx::Point& location,
3110 const WebMediaPlayerAction& action) {
3111 if (webview())
3112 webview()->performMediaPlayerAction(action, location);
3115 void RenderViewImpl::OnOrientationChange() {
3116 // TODO(mlamouri): consumers of that event should be using DisplayObserver.
3117 FOR_EACH_OBSERVER(RenderViewObserver,
3118 observers_,
3119 OrientationChangeEvent());
3121 webview()->mainFrame()->sendOrientationChangeEvent();
3124 void RenderViewImpl::OnPluginActionAt(const gfx::Point& location,
3125 const WebPluginAction& action) {
3126 if (webview())
3127 webview()->performPluginAction(action, location);
3130 void RenderViewImpl::OnGetAllSavableResourceLinksForCurrentPage(
3131 const GURL& page_url) {
3132 // Prepare list to storage all savable resource links.
3133 std::vector<GURL> resources_list;
3134 std::vector<GURL> referrer_urls_list;
3135 std::vector<blink::WebReferrerPolicy> referrer_policies_list;
3136 std::vector<GURL> frames_list;
3137 SavableResourcesResult result(&resources_list,
3138 &referrer_urls_list,
3139 &referrer_policies_list,
3140 &frames_list);
3142 // webkit/ doesn't know about Referrer.
3143 if (!GetAllSavableResourceLinksForCurrentPage(
3144 webview(),
3145 page_url,
3146 &result,
3147 const_cast<const char**>(GetSavableSchemes()))) {
3148 // If something is wrong when collecting all savable resource links,
3149 // send empty list to embedder(browser) to tell it failed.
3150 referrer_urls_list.clear();
3151 referrer_policies_list.clear();
3152 resources_list.clear();
3153 frames_list.clear();
3156 std::vector<Referrer> referrers_list;
3157 CHECK_EQ(referrer_urls_list.size(), referrer_policies_list.size());
3158 for (unsigned i = 0; i < referrer_urls_list.size(); ++i) {
3159 referrers_list.push_back(
3160 Referrer(referrer_urls_list[i], referrer_policies_list[i]));
3163 // Send result of all savable resource links to embedder.
3164 Send(new ViewHostMsg_SendCurrentPageAllSavableResourceLinks(routing_id(),
3165 resources_list,
3166 referrers_list,
3167 frames_list));
3170 void RenderViewImpl::OnGetSerializedHtmlDataForCurrentPageWithLocalLinks(
3171 const std::vector<GURL>& links,
3172 const std::vector<base::FilePath>& local_paths,
3173 const base::FilePath& local_directory_name) {
3175 // Convert std::vector of GURLs to WebVector<WebURL>
3176 WebVector<WebURL> weburl_links(links);
3178 // Convert std::vector of base::FilePath to WebVector<WebString>
3179 WebVector<WebString> webstring_paths(local_paths.size());
3180 for (size_t i = 0; i < local_paths.size(); i++)
3181 webstring_paths[i] = local_paths[i].AsUTF16Unsafe();
3183 WebPageSerializer::serialize(webview()->mainFrame()->toWebLocalFrame(),
3184 true,
3185 this,
3186 weburl_links,
3187 webstring_paths,
3188 local_directory_name.AsUTF16Unsafe());
3191 void RenderViewImpl::OnSuppressDialogsUntilSwapOut() {
3192 // Don't show any more dialogs until we finish OnSwapOut.
3193 suppress_dialogs_until_swap_out_ = true;
3196 void RenderViewImpl::NavigateToSwappedOutURL(blink::WebFrame* frame) {
3197 // We use loadRequest instead of loadHTMLString because the former commits
3198 // synchronously. Otherwise a new navigation can interrupt the navigation
3199 // to kSwappedOutURL. If that happens to be to the page we had been
3200 // showing, then WebKit will never send a commit and we'll be left spinning.
3201 // TODO(creis): Until we move this to RenderFrame, we may call this from a
3202 // swapped out RenderFrame while our own is_swapped_out_ is false.
3203 RenderFrameImpl* rf = RenderFrameImpl::FromWebFrame(frame);
3204 CHECK(is_swapped_out_ || rf->is_swapped_out());
3205 GURL swappedOutURL(kSwappedOutURL);
3206 WebURLRequest request(swappedOutURL);
3207 if (frame->isWebLocalFrame())
3208 frame->loadRequest(request);
3211 void RenderViewImpl::OnClosePage() {
3212 FOR_EACH_OBSERVER(RenderViewObserver, observers_, ClosePage());
3213 // TODO(creis): We'd rather use webview()->Close() here, but that currently
3214 // sets the WebView's delegate_ to NULL, preventing any JavaScript dialogs
3215 // in the onunload handler from appearing. For now, we're bypassing that and
3216 // calling the FrameLoader's CloseURL method directly. This should be
3217 // revisited to avoid having two ways to close a page. Having a single way
3218 // to close that can run onunload is also useful for fixing
3219 // http://b/issue?id=753080.
3220 webview()->mainFrame()->dispatchUnloadEvent();
3222 Send(new ViewHostMsg_ClosePage_ACK(routing_id_));
3225 void RenderViewImpl::OnThemeChanged() {
3226 #if defined(USE_AURA)
3227 // Aura doesn't care if we switch themes.
3228 #elif defined(OS_WIN)
3229 ui::NativeThemeWin::instance()->CloseHandles();
3230 if (webview())
3231 webview()->themeChanged();
3232 #else // defined(OS_WIN)
3233 // TODO(port): we don't support theming on non-Windows platforms yet
3234 NOTIMPLEMENTED();
3235 #endif
3238 void RenderViewImpl::OnMoveOrResizeStarted() {
3239 if (webview())
3240 webview()->hidePopups();
3243 void RenderViewImpl::OnResize(const ViewMsg_Resize_Params& params) {
3244 TRACE_EVENT0("renderer", "RenderViewImpl::OnResize");
3245 if (webview()) {
3246 webview()->hidePopups();
3247 if (send_preferred_size_changes_) {
3248 webview()->mainFrame()->setCanHaveScrollbars(
3249 ShouldDisplayScrollbars(params.new_size.width(),
3250 params.new_size.height()));
3254 gfx::Size old_visible_viewport_size = visible_viewport_size_;
3256 RenderWidget::OnResize(params);
3258 if (old_visible_viewport_size != visible_viewport_size_)
3259 has_scrolled_focused_editable_node_into_rect_ = false;
3261 FOR_EACH_OBSERVER(RenderViewObserver,
3262 observers_,
3263 Resized());
3266 void RenderViewImpl::DidInitiatePaint() {
3267 #if defined(ENABLE_PLUGINS)
3268 // Notify all instances that we painted. The same caveats apply as for
3269 // ViewFlushedPaint regarding instances closing themselves, so we take
3270 // similar precautions.
3271 PepperPluginSet plugins = active_pepper_instances_;
3272 for (PepperPluginSet::iterator i = plugins.begin(); i != plugins.end(); ++i) {
3273 if (active_pepper_instances_.find(*i) != active_pepper_instances_.end())
3274 (*i)->ViewInitiatedPaint();
3276 #endif
3279 void RenderViewImpl::DidFlushPaint() {
3280 #if defined(ENABLE_PLUGINS)
3281 // Notify all instances that we flushed. This will call into the plugin, and
3282 // we it may ask to close itself as a result. This will, in turn, modify our
3283 // set, possibly invalidating the iterator. So we iterate on a copy that
3284 // won't change out from under us.
3285 PepperPluginSet plugins = active_pepper_instances_;
3286 for (PepperPluginSet::iterator i = plugins.begin(); i != plugins.end(); ++i) {
3287 // The copy above makes sure our iterator is never invalid if some plugins
3288 // are destroyed. But some plugin may decide to close all of its views in
3289 // response to a paint in one of them, so we need to make sure each one is
3290 // still "current" before using it.
3292 // It's possible that a plugin was destroyed, but another one was created
3293 // with the same address. In this case, we'll call ViewFlushedPaint on that
3294 // new plugin. But that's OK for this particular case since we're just
3295 // notifying all of our instances that the view flushed, and the new one is
3296 // one of our instances.
3298 // What about the case where a new one is created in a callback at a new
3299 // address and we don't issue the callback? We're still OK since this
3300 // callback is used for flush callbacks and we could not have possibly
3301 // started a new paint for the new plugin while processing a previous paint
3302 // for an existing one.
3303 if (active_pepper_instances_.find(*i) != active_pepper_instances_.end())
3304 (*i)->ViewFlushedPaint();
3306 #endif
3308 // If the RenderWidget is closing down then early-exit, otherwise we'll crash.
3309 // See crbug.com/112921.
3310 if (!webview())
3311 return;
3313 WebFrame* main_frame = webview()->mainFrame();
3314 for (WebFrame* frame = main_frame; frame;
3315 frame = frame->traverseNext(false)) {
3316 if (frame->isWebLocalFrame())
3317 main_frame = frame;
3320 // If we have a provisional frame we are between the start and commit stages
3321 // of loading and we don't want to save stats.
3322 if (!main_frame->provisionalDataSource()) {
3323 WebDataSource* ds = main_frame->dataSource();
3324 DocumentState* document_state = DocumentState::FromDataSource(ds);
3326 // TODO(jar): The following code should all be inside a method, probably in
3327 // NavigatorState.
3328 Time now = Time::Now();
3329 if (document_state->first_paint_time().is_null()) {
3330 document_state->set_first_paint_time(now);
3332 if (document_state->first_paint_after_load_time().is_null() &&
3333 !document_state->finish_load_time().is_null()) {
3334 document_state->set_first_paint_after_load_time(now);
3339 gfx::Vector2d RenderViewImpl::GetScrollOffset() {
3340 WebFrame* main_frame = webview()->mainFrame();
3341 for (WebFrame* frame = main_frame; frame;
3342 frame = frame->traverseNext(false)) {
3343 // TODO(nasko): This is a hack for the case in which the top-level
3344 // frame is being rendered in another process. It will not
3345 // behave correctly for out of process iframes.
3346 if (frame->isWebLocalFrame()) {
3347 main_frame = frame;
3348 break;
3352 WebSize scroll_offset = main_frame->scrollOffset();
3353 return gfx::Vector2d(scroll_offset.width, scroll_offset.height);
3356 void RenderViewImpl::OnClearFocusedElement() {
3357 if (webview())
3358 webview()->clearFocusedElement();
3361 void RenderViewImpl::OnSetBackgroundOpaque(bool opaque) {
3362 if (webview())
3363 webview()->setIsTransparent(!opaque);
3364 if (compositor_)
3365 compositor_->setHasTransparentBackground(!opaque);
3368 void RenderViewImpl::OnSetActive(bool active) {
3369 if (webview())
3370 webview()->setIsActive(active);
3372 #if defined(ENABLE_PLUGINS) && defined(OS_MACOSX)
3373 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3374 for (plugin_it = plugin_delegates_.begin();
3375 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3376 (*plugin_it)->SetWindowFocus(active);
3378 #endif
3381 #if defined(OS_MACOSX)
3382 void RenderViewImpl::OnSetWindowVisibility(bool visible) {
3383 #if defined(ENABLE_PLUGINS)
3384 // Inform plugins that their container has changed visibility.
3385 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3386 for (plugin_it = plugin_delegates_.begin();
3387 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3388 (*plugin_it)->SetContainerVisibility(visible);
3390 #endif
3393 void RenderViewImpl::OnWindowFrameChanged(const gfx::Rect& window_frame,
3394 const gfx::Rect& view_frame) {
3395 #if defined(ENABLE_PLUGINS)
3396 // Inform plugins that their window's frame has changed.
3397 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3398 for (plugin_it = plugin_delegates_.begin();
3399 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3400 (*plugin_it)->WindowFrameChanged(window_frame, view_frame);
3402 #endif
3405 void RenderViewImpl::OnPluginImeCompositionCompleted(const base::string16& text,
3406 int plugin_id) {
3407 // WebPluginDelegateProxy is responsible for figuring out if this event
3408 // applies to it or not, so inform all the delegates.
3409 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3410 for (plugin_it = plugin_delegates_.begin();
3411 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3412 (*plugin_it)->ImeCompositionCompleted(text, plugin_id);
3415 #endif // OS_MACOSX
3417 void RenderViewImpl::OnClose() {
3418 if (closing_)
3419 RenderThread::Get()->Send(new ViewHostMsg_Close_ACK(routing_id_));
3420 RenderWidget::OnClose();
3423 void RenderViewImpl::Close() {
3424 // We need to grab a pointer to the doomed WebView before we destroy it.
3425 WebView* doomed = webview();
3426 RenderWidget::Close();
3427 g_view_map.Get().erase(doomed);
3428 g_routing_id_view_map.Get().erase(routing_id_);
3429 RenderThread::Get()->Send(new ViewHostMsg_Close_ACK(routing_id_));
3432 void RenderViewImpl::DidHandleKeyEvent() {
3433 ClearEditCommands();
3436 bool RenderViewImpl::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
3437 possible_drag_event_info_.event_source =
3438 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE;
3439 possible_drag_event_info_.event_location =
3440 gfx::Point(event.globalX, event.globalY);
3442 #if defined(ENABLE_PLUGINS)
3443 // This method is called for every mouse event that the render view receives.
3444 // And then the mouse event is forwarded to WebKit, which dispatches it to the
3445 // event target. Potentially a Pepper plugin will receive the event.
3446 // In order to tell whether a plugin gets the last mouse event and which it
3447 // is, we set |pepper_last_mouse_event_target_| to NULL here. If a plugin gets
3448 // the event, it will notify us via DidReceiveMouseEvent() and set itself as
3449 // |pepper_last_mouse_event_target_|.
3450 pepper_last_mouse_event_target_ = NULL;
3451 #endif
3453 // If the mouse is locked, only the current owner of the mouse lock can
3454 // process mouse events.
3455 return mouse_lock_dispatcher_->WillHandleMouseEvent(event);
3458 bool RenderViewImpl::WillHandleGestureEvent(
3459 const blink::WebGestureEvent& event) {
3460 possible_drag_event_info_.event_source =
3461 ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH;
3462 possible_drag_event_info_.event_location =
3463 gfx::Point(event.globalX, event.globalY);
3464 return false;
3467 void RenderViewImpl::DidHandleMouseEvent(const WebMouseEvent& event) {
3468 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidHandleMouseEvent(event));
3471 void RenderViewImpl::DidHandleTouchEvent(const WebTouchEvent& event) {
3472 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidHandleTouchEvent(event));
3475 bool RenderViewImpl::HasTouchEventHandlersAt(const gfx::Point& point) const {
3476 if (!webview())
3477 return false;
3478 return webview()->hasTouchEventHandlersAt(point);
3481 void RenderViewImpl::OnWasHidden() {
3482 RenderWidget::OnWasHidden();
3484 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3485 RenderThreadImpl::current()->video_capture_impl_manager()->
3486 SuspendDevices(true);
3487 if (speech_recognition_dispatcher_)
3488 speech_recognition_dispatcher_->AbortAllRecognitions();
3489 #endif
3491 if (webview())
3492 webview()->setVisibilityState(visibilityState(), false);
3494 #if defined(ENABLE_PLUGINS)
3495 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3496 i != active_pepper_instances_.end(); ++i)
3497 (*i)->PageVisibilityChanged(false);
3499 #if defined(OS_MACOSX)
3500 // Inform NPAPI plugins that their container is no longer visible.
3501 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3502 for (plugin_it = plugin_delegates_.begin();
3503 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3504 (*plugin_it)->SetContainerVisibility(false);
3506 #endif // OS_MACOSX
3507 #endif // ENABLE_PLUGINS
3510 void RenderViewImpl::OnWasShown(bool needs_repainting,
3511 const ui::LatencyInfo& latency_info) {
3512 RenderWidget::OnWasShown(needs_repainting, latency_info);
3514 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3515 RenderThreadImpl::current()->video_capture_impl_manager()->
3516 SuspendDevices(false);
3517 #endif
3519 if (webview())
3520 webview()->setVisibilityState(visibilityState(), false);
3522 #if defined(ENABLE_PLUGINS)
3523 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3524 i != active_pepper_instances_.end(); ++i)
3525 (*i)->PageVisibilityChanged(true);
3527 #if defined(OS_MACOSX)
3528 // Inform NPAPI plugins that their container is now visible.
3529 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3530 for (plugin_it = plugin_delegates_.begin();
3531 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3532 (*plugin_it)->SetContainerVisibility(true);
3534 #endif // OS_MACOSX
3535 #endif // ENABLE_PLUGINS
3538 GURL RenderViewImpl::GetURLForGraphicsContext3D() {
3539 DCHECK(webview());
3540 if (webview()->mainFrame()->isWebLocalFrame())
3541 return GURL(webview()->mainFrame()->document().url());
3542 else
3543 return GURL("chrome://gpu/RenderViewImpl::CreateGraphicsContext3D");
3546 void RenderViewImpl::OnSetFocus(bool enable) {
3547 RenderWidget::OnSetFocus(enable);
3549 #if defined(ENABLE_PLUGINS)
3550 if (webview() && webview()->isActive()) {
3551 // Notify all NPAPI plugins.
3552 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3553 for (plugin_it = plugin_delegates_.begin();
3554 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3555 #if defined(OS_MACOSX)
3556 // RenderWidget's call to setFocus can cause the underlying webview's
3557 // activation state to change just like a call to setIsActive.
3558 if (enable)
3559 (*plugin_it)->SetWindowFocus(true);
3560 #endif
3561 (*plugin_it)->SetContentAreaFocus(enable);
3564 // Notify all Pepper plugins.
3565 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3566 i != active_pepper_instances_.end(); ++i)
3567 (*i)->SetContentAreaFocus(enable);
3568 #endif
3569 // Notify all BrowserPlugins of the RenderView's focus state.
3570 if (browser_plugin_manager_.get())
3571 browser_plugin_manager_->UpdateFocusState();
3574 void RenderViewImpl::OnImeSetComposition(
3575 const base::string16& text,
3576 const std::vector<blink::WebCompositionUnderline>& underlines,
3577 int selection_start,
3578 int selection_end) {
3579 #if defined(ENABLE_PLUGINS)
3580 if (focused_pepper_plugin_) {
3581 focused_pepper_plugin_->render_frame()->OnImeSetComposition(
3582 text, underlines, selection_start, selection_end);
3583 return;
3586 #if defined(OS_WIN)
3587 // When a plug-in has focus, we create platform-specific IME data used by
3588 // our IME emulator and send it directly to the focused plug-in, i.e. we
3589 // bypass WebKit. (WebPluginDelegate dispatches this IME data only when its
3590 // instance ID is the same one as the specified ID.)
3591 if (focused_plugin_id_ >= 0) {
3592 std::vector<int> clauses;
3593 std::vector<int> target;
3594 for (size_t i = 0; i < underlines.size(); ++i) {
3595 clauses.push_back(underlines[i].startOffset);
3596 clauses.push_back(underlines[i].endOffset);
3597 if (underlines[i].thick) {
3598 target.clear();
3599 target.push_back(underlines[i].startOffset);
3600 target.push_back(underlines[i].endOffset);
3603 std::set<WebPluginDelegateProxy*>::iterator it;
3604 for (it = plugin_delegates_.begin(); it != plugin_delegates_.end(); ++it) {
3605 (*it)->ImeCompositionUpdated(text, clauses, target, selection_end,
3606 focused_plugin_id_);
3608 return;
3610 #endif // OS_WIN
3611 #endif // ENABLE_PLUGINS
3612 RenderWidget::OnImeSetComposition(text,
3613 underlines,
3614 selection_start,
3615 selection_end);
3618 void RenderViewImpl::OnImeConfirmComposition(
3619 const base::string16& text,
3620 const gfx::Range& replacement_range,
3621 bool keep_selection) {
3622 #if defined(ENABLE_PLUGINS)
3623 if (focused_pepper_plugin_) {
3624 focused_pepper_plugin_->render_frame()->OnImeConfirmComposition(
3625 text, replacement_range, keep_selection);
3626 return;
3628 #if defined(OS_WIN)
3629 // Same as OnImeSetComposition(), we send the text from IMEs directly to
3630 // plug-ins. When we send IME text directly to plug-ins, we should not send
3631 // it to WebKit to prevent WebKit from controlling IMEs.
3632 // TODO(thakis): Honor |replacement_range| for plugins?
3633 if (focused_plugin_id_ >= 0) {
3634 std::set<WebPluginDelegateProxy*>::iterator it;
3635 for (it = plugin_delegates_.begin();
3636 it != plugin_delegates_.end(); ++it) {
3637 (*it)->ImeCompositionCompleted(text, focused_plugin_id_);
3639 return;
3641 #endif // OS_WIN
3642 #endif // ENABLE_PLUGINS
3643 if (replacement_range.IsValid() && webview()) {
3644 // Select the text in |replacement_range|, it will then be replaced by
3645 // text added by the call to RenderWidget::OnImeConfirmComposition().
3646 if (WebLocalFrame* frame = webview()->focusedFrame()->toWebLocalFrame()) {
3647 WebRange webrange = WebRange::fromDocumentRange(
3648 frame, replacement_range.start(), replacement_range.length());
3649 if (!webrange.isNull())
3650 frame->selectRange(webrange);
3653 RenderWidget::OnImeConfirmComposition(text,
3654 replacement_range,
3655 keep_selection);
3658 void RenderViewImpl::SetDeviceScaleFactor(float device_scale_factor) {
3659 RenderWidget::SetDeviceScaleFactor(device_scale_factor);
3660 if (webview()) {
3661 webview()->setDeviceScaleFactor(device_scale_factor);
3662 webview()->settings()->setPreferCompositingToLCDTextEnabled(
3663 PreferCompositingToLCDText(device_scale_factor_));
3664 webview()->settings()->setAcceleratedCompositingForTransitionEnabled(
3665 ShouldUseTransitionCompositing(device_scale_factor_));
3667 if (auto_resize_mode_)
3668 AutoResizeCompositor();
3670 if (browser_plugin_manager_.get())
3671 browser_plugin_manager_->UpdateDeviceScaleFactor(device_scale_factor_);
3674 bool RenderViewImpl::SetDeviceColorProfile(
3675 const std::vector<char>& profile) {
3676 bool changed = RenderWidget::SetDeviceColorProfile(profile);
3677 if (changed && webview()) {
3678 // TODO(noel): notify the webview() of the color profile change so it
3679 // can update and repaint all color profiled page elements.
3681 return changed;
3684 ui::TextInputType RenderViewImpl::GetTextInputType() {
3685 #if defined(ENABLE_PLUGINS)
3686 if (focused_pepper_plugin_)
3687 return focused_pepper_plugin_->text_input_type();
3688 #endif
3689 return RenderWidget::GetTextInputType();
3692 void RenderViewImpl::GetSelectionBounds(gfx::Rect* start, gfx::Rect* end) {
3693 #if defined(ENABLE_PLUGINS)
3694 if (focused_pepper_plugin_) {
3695 // TODO(kinaba) http://crbug.com/101101
3696 // Current Pepper IME API does not handle selection bounds. So we simply
3697 // use the caret position as an empty range for now. It will be updated
3698 // after Pepper API equips features related to surrounding text retrieval.
3699 gfx::Rect caret = focused_pepper_plugin_->GetCaretBounds();
3700 *start = caret;
3701 *end = caret;
3702 return;
3704 #endif
3705 RenderWidget::GetSelectionBounds(start, end);
3708 #if defined(OS_MACOSX) || defined(USE_AURA)
3709 void RenderViewImpl::GetCompositionCharacterBounds(
3710 std::vector<gfx::Rect>* bounds) {
3711 DCHECK(bounds);
3712 bounds->clear();
3714 #if defined(ENABLE_PLUGINS)
3715 if (focused_pepper_plugin_) {
3716 return;
3718 #endif
3720 if (!webview())
3721 return;
3722 size_t start_offset = 0;
3723 size_t character_count = 0;
3724 if (!webview()->compositionRange(&start_offset, &character_count))
3725 return;
3726 if (character_count == 0)
3727 return;
3729 blink::WebFrame* frame = webview()->focusedFrame();
3730 if (!frame)
3731 return;
3733 bounds->reserve(character_count);
3734 blink::WebRect webrect;
3735 for (size_t i = 0; i < character_count; ++i) {
3736 if (!frame->firstRectForCharacterRange(start_offset + i, 1, webrect)) {
3737 DLOG(ERROR) << "Could not retrieve character rectangle at " << i;
3738 bounds->clear();
3739 return;
3741 bounds->push_back(webrect);
3745 void RenderViewImpl::GetCompositionRange(gfx::Range* range) {
3746 #if defined(ENABLE_PLUGINS)
3747 if (focused_pepper_plugin_) {
3748 return;
3750 #endif
3751 RenderWidget::GetCompositionRange(range);
3753 #endif
3755 bool RenderViewImpl::CanComposeInline() {
3756 #if defined(ENABLE_PLUGINS)
3757 if (focused_pepper_plugin_)
3758 return focused_pepper_plugin_->IsPluginAcceptingCompositionEvents();
3759 #endif
3760 return true;
3763 void RenderViewImpl::InstrumentWillBeginFrame(int frame_id) {
3764 if (!webview())
3765 return;
3766 if (!webview()->devToolsAgent())
3767 return;
3768 webview()->devToolsAgent()->didBeginFrame(frame_id);
3771 void RenderViewImpl::InstrumentDidBeginFrame() {
3772 if (!webview())
3773 return;
3774 if (!webview()->devToolsAgent())
3775 return;
3776 // TODO(jamesr/caseq): Decide if this needs to be renamed.
3777 webview()->devToolsAgent()->didComposite();
3780 void RenderViewImpl::InstrumentDidCancelFrame() {
3781 if (!webview())
3782 return;
3783 if (!webview()->devToolsAgent())
3784 return;
3785 webview()->devToolsAgent()->didCancelFrame();
3788 void RenderViewImpl::InstrumentWillComposite() {
3789 if (!webview())
3790 return;
3791 if (!webview()->devToolsAgent())
3792 return;
3793 webview()->devToolsAgent()->willComposite();
3796 void RenderViewImpl::SetScreenMetricsEmulationParameters(
3797 float device_scale_factor,
3798 const gfx::Point& root_layer_offset,
3799 float root_layer_scale) {
3800 if (webview() && compositor()) {
3801 webview()->setCompositorDeviceScaleFactorOverride(device_scale_factor);
3802 webview()->setRootLayerTransform(
3803 blink::WebSize(root_layer_offset.x(), root_layer_offset.y()),
3804 root_layer_scale);
3808 bool RenderViewImpl::ScheduleFileChooser(
3809 const FileChooserParams& params,
3810 WebFileChooserCompletion* completion) {
3811 static const size_t kMaximumPendingFileChooseRequests = 4;
3812 if (file_chooser_completions_.size() > kMaximumPendingFileChooseRequests) {
3813 // This sanity check prevents too many file choose requests from getting
3814 // queued which could DoS the user. Getting these is most likely a
3815 // programming error (there are many ways to DoS the user so it's not
3816 // considered a "real" security check), either in JS requesting many file
3817 // choosers to pop up, or in a plugin.
3819 // TODO(brettw) we might possibly want to require a user gesture to open
3820 // a file picker, which will address this issue in a better way.
3821 return false;
3824 file_chooser_completions_.push_back(linked_ptr<PendingFileChooser>(
3825 new PendingFileChooser(params, completion)));
3826 if (file_chooser_completions_.size() == 1) {
3827 // Actually show the browse dialog when this is the first request.
3828 Send(new ViewHostMsg_RunFileChooser(routing_id_, params));
3830 return true;
3833 blink::WebSpeechRecognizer* RenderViewImpl::speechRecognizer() {
3834 if (!speech_recognition_dispatcher_)
3835 speech_recognition_dispatcher_ = new SpeechRecognitionDispatcher(this);
3836 return speech_recognition_dispatcher_;
3839 void RenderViewImpl::zoomLimitsChanged(double minimum_level,
3840 double maximum_level) {
3841 int minimum_percent = static_cast<int>(
3842 ZoomLevelToZoomFactor(minimum_level) * 100);
3843 int maximum_percent = static_cast<int>(
3844 ZoomLevelToZoomFactor(maximum_level) * 100);
3846 Send(new ViewHostMsg_UpdateZoomLimits(
3847 routing_id_, minimum_percent, maximum_percent));
3850 void RenderViewImpl::zoomLevelChanged() {
3851 double zoom_level = webview()->zoomLevel();
3853 // Do not send empty URLs to the browser when we are just setting the default
3854 // zoom level (from RendererPreferences) before the first navigation.
3855 if (!webview()->mainFrame()->document().url().isEmpty()) {
3856 // Tell the browser which url got zoomed so it can update the menu and the
3857 // saved values if necessary
3858 Send(new ViewHostMsg_DidZoomURL(
3859 routing_id_, zoom_level,
3860 GURL(webview()->mainFrame()->document().url())));
3864 double RenderViewImpl::zoomLevelToZoomFactor(double zoom_level) const {
3865 return ZoomLevelToZoomFactor(zoom_level);
3868 double RenderViewImpl::zoomFactorToZoomLevel(double factor) const {
3869 return ZoomFactorToZoomLevel(factor);
3872 // TODO(sanjoy.pal): Remove once blink patch lands. http://crbug.com/406236.
3873 void RenderViewImpl::registerProtocolHandler(const WebString& scheme,
3874 const WebURL& base_url,
3875 const WebURL& url,
3876 const WebString& title) {
3877 bool user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
3878 GURL base(base_url);
3879 GURL absolute_url = base.Resolve(base::UTF16ToUTF8(url.string()));
3880 if (base.GetOrigin() != absolute_url.GetOrigin()) {
3881 return;
3883 Send(new ViewHostMsg_RegisterProtocolHandler(routing_id_,
3884 base::UTF16ToUTF8(scheme),
3885 absolute_url,
3886 title,
3887 user_gesture));
3890 void RenderViewImpl::unregisterProtocolHandler(const WebString& scheme,
3891 const WebURL& base_url,
3892 const WebURL& url) {
3893 bool user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
3894 GURL base(base_url);
3895 GURL absolute_url = base.Resolve(base::UTF16ToUTF8(url.string()));
3896 if (base.GetOrigin() != absolute_url.GetOrigin())
3897 return;
3898 Send(new ViewHostMsg_UnregisterProtocolHandler(routing_id_,
3899 base::UTF16ToUTF8(scheme),
3900 absolute_url,
3901 user_gesture));
3904 void RenderViewImpl::registerProtocolHandler(const WebString& scheme,
3905 const WebURL& url,
3906 const WebString& title) {
3907 bool user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
3908 Send(new ViewHostMsg_RegisterProtocolHandler(routing_id_,
3909 base::UTF16ToUTF8(scheme),
3910 url,
3911 title,
3912 user_gesture));
3915 void RenderViewImpl::unregisterProtocolHandler(const WebString& scheme,
3916 const WebURL& url) {
3917 bool user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
3918 Send(new ViewHostMsg_UnregisterProtocolHandler(routing_id_,
3919 base::UTF16ToUTF8(scheme),
3920 url,
3921 user_gesture));
3924 blink::WebPageVisibilityState RenderViewImpl::visibilityState() const {
3925 blink::WebPageVisibilityState current_state = is_hidden() ?
3926 blink::WebPageVisibilityStateHidden :
3927 blink::WebPageVisibilityStateVisible;
3928 blink::WebPageVisibilityState override_state = current_state;
3929 // TODO(jam): move this method to WebFrameClient.
3930 if (GetContentClient()->renderer()->
3931 ShouldOverridePageVisibilityState(main_render_frame_.get(),
3932 &override_state))
3933 return override_state;
3934 return current_state;
3937 blink::WebPushClient* RenderViewImpl::webPushClient() {
3938 // TODO(mvanouwerkerk): Remove this method once the Push API code in Blink
3939 // has also switched over to Frame.
3940 return main_render_frame_->pushClient();
3943 void RenderViewImpl::draggableRegionsChanged() {
3944 FOR_EACH_OBSERVER(
3945 RenderViewObserver,
3946 observers_,
3947 DraggableRegionsChanged(webview()->mainFrame()));
3950 #if defined(OS_ANDROID)
3951 WebContentDetectionResult RenderViewImpl::detectContentAround(
3952 const WebHitTestResult& touch_hit) {
3953 DCHECK(!touch_hit.isNull());
3954 DCHECK(!touch_hit.node().isNull());
3955 DCHECK(touch_hit.node().isTextNode());
3957 // Process the position with all the registered content detectors until
3958 // a match is found. Priority is provided by their relative order.
3959 for (ContentDetectorList::const_iterator it = content_detectors_.begin();
3960 it != content_detectors_.end(); ++it) {
3961 ContentDetector::Result content = (*it)->FindTappedContent(touch_hit);
3962 if (content.valid) {
3963 return WebContentDetectionResult(content.content_boundaries,
3964 base::UTF8ToUTF16(content.text), content.intent_url);
3967 return WebContentDetectionResult();
3970 void RenderViewImpl::scheduleContentIntent(const WebURL& intent) {
3971 // Introduce a short delay so that the user can notice the content.
3972 base::MessageLoop::current()->PostDelayedTask(
3973 FROM_HERE,
3974 base::Bind(&RenderViewImpl::LaunchAndroidContentIntent,
3975 AsWeakPtr(),
3976 intent,
3977 expected_content_intent_id_),
3978 base::TimeDelta::FromMilliseconds(kContentIntentDelayMilliseconds));
3981 void RenderViewImpl::cancelScheduledContentIntents() {
3982 ++expected_content_intent_id_;
3985 void RenderViewImpl::LaunchAndroidContentIntent(const GURL& intent,
3986 size_t request_id) {
3987 if (request_id != expected_content_intent_id_)
3988 return;
3990 // Remove the content highlighting if any.
3991 scheduleComposite();
3993 if (!intent.is_empty())
3994 Send(new ViewHostMsg_StartContentIntent(routing_id_, intent));
3997 bool RenderViewImpl::openDateTimeChooser(
3998 const blink::WebDateTimeChooserParams& params,
3999 blink::WebDateTimeChooserCompletion* completion) {
4000 // JavaScript may try to open a date time chooser while one is already open.
4001 if (date_time_picker_client_)
4002 return false;
4003 date_time_picker_client_.reset(
4004 new RendererDateTimePicker(this, params, completion));
4005 return date_time_picker_client_->Open();
4008 void RenderViewImpl::DismissDateTimeDialog() {
4009 DCHECK(date_time_picker_client_);
4010 date_time_picker_client_.reset(NULL);
4013 #endif // defined(OS_ANDROID)
4015 void RenderViewImpl::OnShowContextMenu(
4016 ui::MenuSourceType source_type, const gfx::Point& location) {
4017 context_menu_source_type_ = source_type;
4018 has_host_context_menu_location_ = true;
4019 host_context_menu_location_ = location;
4020 if (webview())
4021 webview()->showContextMenu();
4022 has_host_context_menu_location_ = false;
4025 void RenderViewImpl::OnEnableViewSourceMode() {
4026 if (!webview())
4027 return;
4028 WebFrame* main_frame = webview()->mainFrame();
4029 if (!main_frame)
4030 return;
4031 main_frame->enableViewSourceMode(true);
4034 #if defined(OS_ANDROID)
4035 bool RenderViewImpl::didTapMultipleTargets(
4036 const blink::WebGestureEvent& event,
4037 const WebVector<WebRect>& target_rects) {
4038 // Never show a disambiguation popup when accessibility is enabled,
4039 // as this interferes with "touch exploration".
4040 AccessibilityMode accessibility_mode =
4041 main_render_frame()->accessibility_mode();
4042 bool matches_accessibility_mode_complete =
4043 (accessibility_mode & AccessibilityModeComplete) ==
4044 AccessibilityModeComplete;
4045 if (matches_accessibility_mode_complete)
4046 return false;
4048 gfx::Rect finger_rect(
4049 event.x - event.data.tap.width / 2, event.y - event.data.tap.height / 2,
4050 event.data.tap.width, event.data.tap.height);
4051 gfx::Rect zoom_rect;
4052 float new_total_scale =
4053 DisambiguationPopupHelper::ComputeZoomAreaAndScaleFactor(
4054 finger_rect, target_rects, GetSize(),
4055 gfx::Rect(webview()->mainFrame()->visibleContentRect()).size(),
4056 device_scale_factor_ * webview()->pageScaleFactor(), &zoom_rect);
4057 if (!new_total_scale)
4058 return false;
4060 bool handled = false;
4061 switch (renderer_preferences_.tap_multiple_targets_strategy) {
4062 case TAP_MULTIPLE_TARGETS_STRATEGY_ZOOM:
4063 handled = webview()->zoomToMultipleTargetsRect(zoom_rect);
4064 break;
4065 case TAP_MULTIPLE_TARGETS_STRATEGY_POPUP: {
4066 gfx::Size canvas_size =
4067 gfx::ToCeiledSize(gfx::ScaleSize(zoom_rect.size(), new_total_scale));
4068 cc::SharedBitmapManager* manager =
4069 RenderThreadImpl::current()->shared_bitmap_manager();
4070 scoped_ptr<cc::SharedBitmap> shared_bitmap =
4071 manager->AllocateSharedBitmap(canvas_size);
4073 SkBitmap bitmap;
4074 SkImageInfo info = SkImageInfo::MakeN32Premul(canvas_size.width(),
4075 canvas_size.height());
4076 bitmap.installPixels(info, shared_bitmap->pixels(), info.minRowBytes());
4077 SkCanvas canvas(bitmap);
4079 // TODO(trchen): Cleanup the device scale factor mess.
4080 // device scale will be applied in WebKit
4081 // --> zoom_rect doesn't include device scale,
4082 // but WebKit will still draw on zoom_rect * device_scale_factor_
4083 canvas.scale(new_total_scale / device_scale_factor_,
4084 new_total_scale / device_scale_factor_);
4085 canvas.translate(-zoom_rect.x() * device_scale_factor_,
4086 -zoom_rect.y() * device_scale_factor_);
4088 DCHECK(webwidget_->isAcceleratedCompositingActive());
4089 // TODO(aelias): The disambiguation popup should be composited so we
4090 // don't have to call this method.
4091 webwidget_->paintCompositedDeprecated(&canvas, zoom_rect);
4094 gfx::Rect physical_window_zoom_rect = gfx::ToEnclosingRect(
4095 ClientRectToPhysicalWindowRect(gfx::RectF(zoom_rect)));
4096 Send(new ViewHostMsg_ShowDisambiguationPopup(routing_id_,
4097 physical_window_zoom_rect,
4098 canvas_size,
4099 shared_bitmap->id()));
4100 cc::SharedBitmapId id = shared_bitmap->id();
4101 disambiguation_bitmaps_[id] = shared_bitmap.release();
4102 handled = true;
4103 break;
4105 case TAP_MULTIPLE_TARGETS_STRATEGY_NONE:
4106 // No-op.
4107 break;
4110 return handled;
4112 #endif
4114 unsigned RenderViewImpl::GetLocalSessionHistoryLengthForTesting() const {
4115 return history_list_length_;
4118 void RenderViewImpl::SetFocusAndActivateForTesting(bool enable) {
4119 if (enable) {
4120 if (has_focus())
4121 return;
4122 OnSetActive(true);
4123 OnSetFocus(true);
4124 } else {
4125 if (!has_focus())
4126 return;
4127 OnSetFocus(false);
4128 OnSetActive(false);
4132 void RenderViewImpl::SetDeviceScaleFactorForTesting(float factor) {
4133 ViewMsg_Resize_Params params;
4134 params.screen_info = screen_info_;
4135 params.screen_info.deviceScaleFactor = factor;
4136 params.new_size = size();
4137 params.physical_backing_size =
4138 gfx::ToCeiledSize(gfx::ScaleSize(size(), factor));
4139 params.top_controls_layout_height = 0.f;
4140 params.resizer_rect = WebRect();
4141 params.is_fullscreen = is_fullscreen();
4142 OnResize(params);
4145 void RenderViewImpl::SetDeviceColorProfileForTesting(
4146 const std::vector<char>& color_profile) {
4147 SetDeviceColorProfile(color_profile);
4150 void RenderViewImpl::ForceResizeForTesting(const gfx::Size& new_size) {
4151 gfx::Rect new_position(rootWindowRect().x,
4152 rootWindowRect().y,
4153 new_size.width(),
4154 new_size.height());
4155 ResizeSynchronously(new_position);
4158 void RenderViewImpl::UseSynchronousResizeModeForTesting(bool enable) {
4159 resizing_mode_selector_->set_is_synchronous_mode(enable);
4162 void RenderViewImpl::EnableAutoResizeForTesting(const gfx::Size& min_size,
4163 const gfx::Size& max_size) {
4164 OnEnableAutoResize(min_size, max_size);
4167 void RenderViewImpl::DisableAutoResizeForTesting(const gfx::Size& new_size) {
4168 OnDisableAutoResize(new_size);
4171 void RenderViewImpl::OnReleaseDisambiguationPopupBitmap(
4172 const cc::SharedBitmapId& id) {
4173 BitmapMap::iterator it = disambiguation_bitmaps_.find(id);
4174 DCHECK(it != disambiguation_bitmaps_.end());
4175 delete it->second;
4176 disambiguation_bitmaps_.erase(it);
4179 void RenderViewImpl::DidCommitCompositorFrame() {
4180 RenderWidget::DidCommitCompositorFrame();
4181 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidCommitCompositorFrame());
4184 void RenderViewImpl::SendUpdateFaviconURL(const std::vector<FaviconURL>& urls) {
4185 if (!urls.empty())
4186 Send(new ViewHostMsg_UpdateFaviconURL(routing_id_, urls));
4189 void RenderViewImpl::DidStopLoadingIcons() {
4190 int icon_types = WebIconURL::TypeFavicon;
4191 if (TouchEnabled())
4192 icon_types |= WebIconURL::TypeTouchPrecomposed | WebIconURL::TypeTouch;
4194 WebVector<WebIconURL> icon_urls =
4195 webview()->mainFrame()->iconURLs(icon_types);
4197 std::vector<FaviconURL> urls;
4198 for (size_t i = 0; i < icon_urls.size(); i++) {
4199 WebURL url = icon_urls[i].iconURL();
4200 std::vector<gfx::Size> sizes;
4201 ConvertToFaviconSizes(icon_urls[i].sizes(), &sizes);
4202 if (!url.isEmpty())
4203 urls.push_back(
4204 FaviconURL(url, ToFaviconType(icon_urls[i].iconType()), sizes));
4206 SendUpdateFaviconURL(urls);
4209 } // namespace content