[Ozone-Gbm] Explicitly crash if trying software rendering on GBM
[chromium-blink-merge.git] / content / renderer / render_view_impl.cc
blob6519f3789292af260f8da4c1d0029d625661ef73
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/files/file_path.h"
17 #include "base/i18n/rtl.h"
18 #include "base/json/json_writer.h"
19 #include "base/lazy_instance.h"
20 #include "base/memory/scoped_ptr.h"
21 #include "base/message_loop/message_loop_proxy.h"
22 #include "base/metrics/field_trial.h"
23 #include "base/metrics/histogram.h"
24 #include "base/process/kill.h"
25 #include "base/process/process.h"
26 #include "base/strings/string_number_conversions.h"
27 #include "base/strings/string_piece.h"
28 #include "base/strings/string_split.h"
29 #include "base/strings/string_util.h"
30 #include "base/strings/sys_string_conversions.h"
31 #include "base/strings/utf_string_conversions.h"
32 #include "base/time/time.h"
33 #include "base/trace_event/trace_event.h"
34 #include "cc/base/switches.h"
35 #include "content/child/appcache/appcache_dispatcher.h"
36 #include "content/child/appcache/web_application_cache_host_impl.h"
37 #include "content/child/child_shared_bitmap_manager.h"
38 #include "content/child/npapi/webplugin_delegate_impl.h"
39 #include "content/child/request_extra_data.h"
40 #include "content/child/v8_value_converter_impl.h"
41 #include "content/child/webmessageportchannel_impl.h"
42 #include "content/common/content_constants_internal.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/frame_replication_state.h"
48 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
49 #include "content/common/input_messages.h"
50 #include "content/common/pepper_messages.h"
51 #include "content/common/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_file_info.h"
60 #include "content/public/common/file_chooser_params.h"
61 #include "content/public/common/page_state.h"
62 #include "content/public/common/page_zoom.h"
63 #include "content/public/common/ssl_status.h"
64 #include "content/public/common/three_d_api_types.h"
65 #include "content/public/common/url_constants.h"
66 #include "content/public/common/url_utils.h"
67 #include "content/public/common/web_preferences.h"
68 #include "content/public/renderer/content_renderer_client.h"
69 #include "content/public/renderer/document_state.h"
70 #include "content/public/renderer/navigation_state.h"
71 #include "content/public/renderer/render_view_observer.h"
72 #include "content/public/renderer/render_view_visitor.h"
73 #include "content/renderer/browser_plugin/browser_plugin.h"
74 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
75 #include "content/renderer/devtools/devtools_agent.h"
76 #include "content/renderer/disambiguation_popup_helper.h"
77 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
78 #include "content/renderer/drop_data_builder.h"
79 #include "content/renderer/gpu/gpu_benchmarking_extension.h"
80 #include "content/renderer/gpu/render_widget_compositor.h"
81 #include "content/renderer/history_controller.h"
82 #include "content/renderer/history_serialization.h"
83 #include "content/renderer/idle_user_detector.h"
84 #include "content/renderer/ime_event_guard.h"
85 #include "content/renderer/input/input_handler_manager.h"
86 #include "content/renderer/internal_document_state_data.h"
87 #include "content/renderer/media/audio_device_factory.h"
88 #include "content/renderer/media/video_capture_impl_manager.h"
89 #include "content/renderer/memory_benchmarking_extension.h"
90 #include "content/renderer/mhtml_generator.h"
91 #include "content/renderer/net_info_helper.h"
92 #include "content/renderer/render_frame_impl.h"
93 #include "content/renderer/render_frame_proxy.h"
94 #include "content/renderer/render_process.h"
95 #include "content/renderer/render_thread_impl.h"
96 #include "content/renderer/render_view_mouse_lock_dispatcher.h"
97 #include "content/renderer/render_widget_fullscreen_pepper.h"
98 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
99 #include "content/renderer/resizing_mode_selector.h"
100 #include "content/renderer/savable_resources.h"
101 #include "content/renderer/skia_benchmarking_extension.h"
102 #include "content/renderer/speech_recognition_dispatcher.h"
103 #include "content/renderer/stats_collection_controller.h"
104 #include "content/renderer/stats_collection_observer.h"
105 #include "content/renderer/text_input_client_observer.h"
106 #include "content/renderer/web_ui_extension.h"
107 #include "content/renderer/web_ui_extension_data.h"
108 #include "content/renderer/web_ui_mojo.h"
109 #include "content/renderer/websharedworker_proxy.h"
110 #include "media/audio/audio_output_device.h"
111 #include "media/base/media_switches.h"
112 #include "media/filters/gpu_video_accelerator_factories.h"
113 #include "media/renderers/audio_renderer_impl.h"
114 #include "net/base/data_url.h"
115 #include "net/base/escape.h"
116 #include "net/base/net_errors.h"
117 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
118 #include "net/http/http_util.h"
119 #include "skia/ext/platform_canvas.h"
120 #include "third_party/WebKit/public/platform/WebCString.h"
121 #include "third_party/WebKit/public/platform/WebConnectionType.h"
122 #include "third_party/WebKit/public/platform/WebDragData.h"
123 #include "third_party/WebKit/public/platform/WebHTTPBody.h"
124 #include "third_party/WebKit/public/platform/WebImage.h"
125 #include "third_party/WebKit/public/platform/WebMessagePortChannel.h"
126 #include "third_party/WebKit/public/platform/WebPoint.h"
127 #include "third_party/WebKit/public/platform/WebRect.h"
128 #include "third_party/WebKit/public/platform/WebSize.h"
129 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
130 #include "third_party/WebKit/public/platform/WebString.h"
131 #include "third_party/WebKit/public/platform/WebURL.h"
132 #include "third_party/WebKit/public/platform/WebURLError.h"
133 #include "third_party/WebKit/public/platform/WebURLRequest.h"
134 #include "third_party/WebKit/public/platform/WebURLResponse.h"
135 #include "third_party/WebKit/public/platform/WebVector.h"
136 #include "third_party/WebKit/public/web/WebAXObject.h"
137 #include "third_party/WebKit/public/web/WebColorName.h"
138 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
139 #include "third_party/WebKit/public/web/WebDOMEvent.h"
140 #include "third_party/WebKit/public/web/WebDOMMessageEvent.h"
141 #include "third_party/WebKit/public/web/WebDataSource.h"
142 #include "third_party/WebKit/public/web/WebDateTimeChooserCompletion.h"
143 #include "third_party/WebKit/public/web/WebDateTimeChooserParams.h"
144 #include "third_party/WebKit/public/web/WebDevToolsAgent.h"
145 #include "third_party/WebKit/public/web/WebDocument.h"
146 #include "third_party/WebKit/public/web/WebElement.h"
147 #include "third_party/WebKit/public/web/WebFileChooserParams.h"
148 #include "third_party/WebKit/public/web/WebFindOptions.h"
149 #include "third_party/WebKit/public/web/WebFormControlElement.h"
150 #include "third_party/WebKit/public/web/WebFormElement.h"
151 #include "third_party/WebKit/public/web/WebFrame.h"
152 #include "third_party/WebKit/public/web/WebGlyphCache.h"
153 #include "third_party/WebKit/public/web/WebHistoryItem.h"
154 #include "third_party/WebKit/public/web/WebHitTestResult.h"
155 #include "third_party/WebKit/public/web/WebInputElement.h"
156 #include "third_party/WebKit/public/web/WebInputEvent.h"
157 #include "third_party/WebKit/public/web/WebKit.h"
158 #include "third_party/WebKit/public/web/WebLocalFrame.h"
159 #include "third_party/WebKit/public/web/WebMediaPlayerAction.h"
160 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
161 #include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
162 #include "third_party/WebKit/public/web/WebNodeList.h"
163 #include "third_party/WebKit/public/web/WebPageSerializer.h"
164 #include "third_party/WebKit/public/web/WebPlugin.h"
165 #include "third_party/WebKit/public/web/WebPluginAction.h"
166 #include "third_party/WebKit/public/web/WebPluginContainer.h"
167 #include "third_party/WebKit/public/web/WebPluginDocument.h"
168 #include "third_party/WebKit/public/web/WebRange.h"
169 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
170 #include "third_party/WebKit/public/web/WebScriptSource.h"
171 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
172 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
173 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
174 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
175 #include "third_party/WebKit/public/web/WebSettings.h"
176 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
177 #include "third_party/WebKit/public/web/WebView.h"
178 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
179 #include "third_party/WebKit/public/web/default/WebRenderTheme.h"
180 #include "third_party/icu/source/common/unicode/uchar.h"
181 #include "third_party/icu/source/common/unicode/uscript.h"
182 #include "ui/base/clipboard/clipboard.h"
183 #include "ui/base/ui_base_switches_util.h"
184 #include "ui/events/latency_info.h"
185 #include "ui/gfx/geometry/point.h"
186 #include "ui/gfx/geometry/rect.h"
187 #include "ui/gfx/geometry/rect_conversions.h"
188 #include "ui/gfx/geometry/size_conversions.h"
189 #include "ui/gfx/native_widget_types.h"
190 #include "v8/include/v8.h"
192 #if defined(OS_ANDROID)
193 #include <cpu-features.h>
195 #include "content/renderer/android/address_detector.h"
196 #include "content/renderer/android/content_detector.h"
197 #include "content/renderer/android/email_detector.h"
198 #include "content/renderer/android/phone_number_detector.h"
199 #include "net/android/network_library.h"
200 #include "third_party/WebKit/public/platform/WebFloatPoint.h"
201 #include "third_party/WebKit/public/platform/WebFloatRect.h"
202 #include "ui/gfx/geometry/rect_f.h"
204 #elif defined(OS_WIN)
205 // TODO(port): these files are currently Windows only because they concern:
206 // * theming
207 #include "ui/native_theme/native_theme_win.h"
208 #elif defined(USE_X11)
209 #include "ui/native_theme/native_theme.h"
210 #elif defined(OS_MACOSX)
211 #include "skia/ext/skia_utils_mac.h"
212 #endif
214 #if defined(ENABLE_PLUGINS)
215 #include "content/renderer/npapi/webplugin_delegate_proxy.h"
216 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
217 #include "content/renderer/pepper/pepper_plugin_registry.h"
218 #endif
220 #if defined(ENABLE_WEBRTC)
221 #include "content/renderer/media/rtc_peer_connection_handler.h"
222 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
223 #endif
225 using blink::WebAXObject;
226 using blink::WebApplicationCacheHost;
227 using blink::WebApplicationCacheHostClient;
228 using blink::WebCString;
229 using blink::WebColor;
230 using blink::WebColorName;
231 using blink::WebConsoleMessage;
232 using blink::WebData;
233 using blink::WebDataSource;
234 using blink::WebDocument;
235 using blink::WebDOMEvent;
236 using blink::WebDOMMessageEvent;
237 using blink::WebDragData;
238 using blink::WebDragOperation;
239 using blink::WebDragOperationsMask;
240 using blink::WebElement;
241 using blink::WebFileChooserCompletion;
242 using blink::WebFindOptions;
243 using blink::WebFormControlElement;
244 using blink::WebFormElement;
245 using blink::WebFrame;
246 using blink::WebGestureEvent;
247 using blink::WebHistoryItem;
248 using blink::WebHTTPBody;
249 using blink::WebIconURL;
250 using blink::WebImage;
251 using blink::WebInputElement;
252 using blink::WebInputEvent;
253 using blink::WebLocalFrame;
254 using blink::WebMediaPlayerAction;
255 using blink::WebMouseEvent;
256 using blink::WebNavigationPolicy;
257 using blink::WebNavigationType;
258 using blink::WebNode;
259 using blink::WebPageSerializer;
260 using blink::WebPageSerializerClient;
261 using blink::WebPeerConnection00Handler;
262 using blink::WebPeerConnection00HandlerClient;
263 using blink::WebPeerConnectionHandler;
264 using blink::WebPeerConnectionHandlerClient;
265 using blink::WebPluginAction;
266 using blink::WebPluginContainer;
267 using blink::WebPluginDocument;
268 using blink::WebPoint;
269 using blink::WebRange;
270 using blink::WebRect;
271 using blink::WebReferrerPolicy;
272 using blink::WebScriptSource;
273 using blink::WebSearchableFormData;
274 using blink::WebSecurityOrigin;
275 using blink::WebSecurityPolicy;
276 using blink::WebSerializedScriptValue;
277 using blink::WebSettings;
278 using blink::WebSize;
279 using blink::WebStorageNamespace;
280 using blink::WebStorageQuotaCallbacks;
281 using blink::WebStorageQuotaError;
282 using blink::WebStorageQuotaType;
283 using blink::WebString;
284 using blink::WebTextAffinity;
285 using blink::WebTextDirection;
286 using blink::WebTouchEvent;
287 using blink::WebURL;
288 using blink::WebURLError;
289 using blink::WebURLRequest;
290 using blink::WebURLResponse;
291 using blink::WebUserGestureIndicator;
292 using blink::WebVector;
293 using blink::WebView;
294 using blink::WebWidget;
295 using blink::WebWindowFeatures;
296 using blink::WebNetworkStateNotifier;
297 using blink::WebRuntimeFeatures;
298 using base::Time;
299 using base::TimeDelta;
301 #if defined(OS_ANDROID)
302 using blink::WebContentDetectionResult;
303 using blink::WebFloatPoint;
304 using blink::WebFloatRect;
305 using blink::WebHitTestResult;
306 #endif
308 namespace content {
310 //-----------------------------------------------------------------------------
312 typedef std::map<blink::WebView*, RenderViewImpl*> ViewMap;
313 static base::LazyInstance<ViewMap> g_view_map = LAZY_INSTANCE_INITIALIZER;
314 typedef std::map<int32, RenderViewImpl*> RoutingIDViewMap;
315 static base::LazyInstance<RoutingIDViewMap> g_routing_id_view_map =
316 LAZY_INSTANCE_INITIALIZER;
318 // Time, in seconds, we delay before sending content state changes (such as form
319 // state and scroll position) to the browser. We delay sending changes to avoid
320 // spamming the browser.
321 // To avoid having tab/session restore require sending a message to get the
322 // current content state during tab closing we use a shorter timeout for the
323 // foreground renderer. This means there is a small window of time from which
324 // content state is modified and not sent to session restore, but this is
325 // better than having to wake up all renderers during shutdown.
326 const int kDelaySecondsForContentStateSyncHidden = 5;
327 const int kDelaySecondsForContentStateSync = 1;
329 #if defined(OS_ANDROID)
330 // Delay between tapping in content and launching the associated android intent.
331 // Used to allow users see what has been recognized as content.
332 const size_t kContentIntentDelayMilliseconds = 700;
333 #endif
335 static RenderViewImpl* (*g_create_render_view_impl)(const ViewMsg_New_Params&) =
336 NULL;
338 // static
339 bool RenderViewImpl::IsReload(FrameMsg_Navigate_Type::Value navigation_type) {
340 return navigation_type == FrameMsg_Navigate_Type::RELOAD ||
341 navigation_type == FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE ||
342 navigation_type == FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL;
345 // static
346 Referrer RenderViewImpl::GetReferrerFromRequest(
347 WebFrame* frame,
348 const WebURLRequest& request) {
349 return Referrer(GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
350 request.referrerPolicy());
353 // static
354 WindowOpenDisposition RenderViewImpl::NavigationPolicyToDisposition(
355 WebNavigationPolicy policy) {
356 switch (policy) {
357 case blink::WebNavigationPolicyIgnore:
358 return IGNORE_ACTION;
359 case blink::WebNavigationPolicyDownload:
360 return SAVE_TO_DISK;
361 case blink::WebNavigationPolicyCurrentTab:
362 return CURRENT_TAB;
363 case blink::WebNavigationPolicyNewBackgroundTab:
364 return NEW_BACKGROUND_TAB;
365 case blink::WebNavigationPolicyNewForegroundTab:
366 return NEW_FOREGROUND_TAB;
367 case blink::WebNavigationPolicyNewWindow:
368 return NEW_WINDOW;
369 case blink::WebNavigationPolicyNewPopup:
370 return NEW_POPUP;
371 default:
372 NOTREACHED() << "Unexpected WebNavigationPolicy";
373 return IGNORE_ACTION;
377 // Returns true if the device scale is high enough that losing subpixel
378 // antialiasing won't have a noticeable effect on text quality.
379 static bool DeviceScaleEnsuresTextQuality(float device_scale_factor) {
380 #if defined(OS_ANDROID)
381 // On Android, we never have subpixel antialiasing.
382 return true;
383 #else
384 return device_scale_factor > 1.5f;
385 #endif
389 static bool PreferCompositingToLCDText(CompositorDependencies* compositor_deps,
390 float device_scale_factor) {
391 const base::CommandLine& command_line =
392 *base::CommandLine::ForCurrentProcess();
393 if (command_line.HasSwitch(switches::kDisablePreferCompositingToLCDText))
394 return false;
395 if (command_line.HasSwitch(switches::kEnablePreferCompositingToLCDText))
396 return true;
397 if (!compositor_deps->IsLcdTextEnabled())
398 return true;
399 return DeviceScaleEnsuresTextQuality(device_scale_factor);
402 static FaviconURL::IconType ToFaviconType(blink::WebIconURL::Type type) {
403 switch (type) {
404 case blink::WebIconURL::TypeFavicon:
405 return FaviconURL::FAVICON;
406 case blink::WebIconURL::TypeTouch:
407 return FaviconURL::TOUCH_ICON;
408 case blink::WebIconURL::TypeTouchPrecomposed:
409 return FaviconURL::TOUCH_PRECOMPOSED_ICON;
410 case blink::WebIconURL::TypeInvalid:
411 return FaviconURL::INVALID_ICON;
413 return FaviconURL::INVALID_ICON;
416 static void ConvertToFaviconSizes(
417 const blink::WebVector<blink::WebSize>& web_sizes,
418 std::vector<gfx::Size>* sizes) {
419 DCHECK(sizes->empty());
420 sizes->reserve(web_sizes.size());
421 for (size_t i = 0; i < web_sizes.size(); ++i)
422 sizes->push_back(gfx::Size(web_sizes[i]));
425 ///////////////////////////////////////////////////////////////////////////////
427 struct RenderViewImpl::PendingFileChooser {
428 PendingFileChooser(const FileChooserParams& p, WebFileChooserCompletion* c)
429 : params(p),
430 completion(c) {
432 FileChooserParams params;
433 WebFileChooserCompletion* completion; // MAY BE NULL to skip callback.
436 namespace {
438 class WebWidgetLockTarget : public MouseLockDispatcher::LockTarget {
439 public:
440 explicit WebWidgetLockTarget(blink::WebWidget* webwidget)
441 : webwidget_(webwidget) {}
443 void OnLockMouseACK(bool succeeded) override {
444 if (succeeded)
445 webwidget_->didAcquirePointerLock();
446 else
447 webwidget_->didNotAcquirePointerLock();
450 void OnMouseLockLost() override { webwidget_->didLosePointerLock(); }
452 bool HandleMouseLockedInputEvent(const blink::WebMouseEvent& event) override {
453 // The WebWidget handles mouse lock in WebKit's handleInputEvent().
454 return false;
457 private:
458 blink::WebWidget* webwidget_;
461 bool TouchEnabled() {
462 // Based on the definition of chrome::kEnableTouchIcon.
463 #if defined(OS_ANDROID)
464 return true;
465 #else
466 return false;
467 #endif
470 WebDragData DropDataToWebDragData(const DropData& drop_data) {
471 std::vector<WebDragData::Item> item_list;
473 // These fields are currently unused when dragging into WebKit.
474 DCHECK(drop_data.download_metadata.empty());
475 DCHECK(drop_data.file_contents.empty());
476 DCHECK(drop_data.file_description_filename.empty());
478 if (!drop_data.text.is_null()) {
479 WebDragData::Item item;
480 item.storageType = WebDragData::Item::StorageTypeString;
481 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeText);
482 item.stringData = drop_data.text.string();
483 item_list.push_back(item);
486 // TODO(dcheng): Do we need to distinguish between null and empty URLs? Is it
487 // meaningful to write an empty URL to the clipboard?
488 if (!drop_data.url.is_empty()) {
489 WebDragData::Item item;
490 item.storageType = WebDragData::Item::StorageTypeString;
491 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeURIList);
492 item.stringData = WebString::fromUTF8(drop_data.url.spec());
493 item.title = drop_data.url_title;
494 item_list.push_back(item);
497 if (!drop_data.html.is_null()) {
498 WebDragData::Item item;
499 item.storageType = WebDragData::Item::StorageTypeString;
500 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeHTML);
501 item.stringData = drop_data.html.string();
502 item.baseURL = drop_data.html_base_url;
503 item_list.push_back(item);
506 for (std::vector<ui::FileInfo>::const_iterator it =
507 drop_data.filenames.begin();
508 it != drop_data.filenames.end();
509 ++it) {
510 WebDragData::Item item;
511 item.storageType = WebDragData::Item::StorageTypeFilename;
512 item.filenameData = it->path.AsUTF16Unsafe();
513 item.displayNameData = it->display_name.AsUTF16Unsafe();
514 item_list.push_back(item);
517 for (std::vector<DropData::FileSystemFileInfo>::const_iterator it =
518 drop_data.file_system_files.begin();
519 it != drop_data.file_system_files.end();
520 ++it) {
521 WebDragData::Item item;
522 item.storageType = WebDragData::Item::StorageTypeFileSystemFile;
523 item.fileSystemURL = it->url;
524 item.fileSystemFileSize = it->size;
525 item_list.push_back(item);
528 for (std::map<base::string16, base::string16>::const_iterator it =
529 drop_data.custom_data.begin();
530 it != drop_data.custom_data.end();
531 ++it) {
532 WebDragData::Item item;
533 item.storageType = WebDragData::Item::StorageTypeString;
534 item.stringType = it->first;
535 item.stringData = it->second;
536 item_list.push_back(item);
539 WebDragData result;
540 result.initialize();
541 result.setItems(item_list);
542 result.setFilesystemId(drop_data.filesystem_id);
543 return result;
546 typedef void (*SetFontFamilyWrapper)(blink::WebSettings*,
547 const base::string16&,
548 UScriptCode);
550 void SetStandardFontFamilyWrapper(WebSettings* settings,
551 const base::string16& font,
552 UScriptCode script) {
553 settings->setStandardFontFamily(font, script);
556 void SetFixedFontFamilyWrapper(WebSettings* settings,
557 const base::string16& font,
558 UScriptCode script) {
559 settings->setFixedFontFamily(font, script);
562 void SetSerifFontFamilyWrapper(WebSettings* settings,
563 const base::string16& font,
564 UScriptCode script) {
565 settings->setSerifFontFamily(font, script);
568 void SetSansSerifFontFamilyWrapper(WebSettings* settings,
569 const base::string16& font,
570 UScriptCode script) {
571 settings->setSansSerifFontFamily(font, script);
574 void SetCursiveFontFamilyWrapper(WebSettings* settings,
575 const base::string16& font,
576 UScriptCode script) {
577 settings->setCursiveFontFamily(font, script);
580 void SetFantasyFontFamilyWrapper(WebSettings* settings,
581 const base::string16& font,
582 UScriptCode script) {
583 settings->setFantasyFontFamily(font, script);
586 void SetPictographFontFamilyWrapper(WebSettings* settings,
587 const base::string16& font,
588 UScriptCode script) {
589 settings->setPictographFontFamily(font, script);
592 // If |scriptCode| is a member of a family of "similar" script codes, returns
593 // the script code in that family that is used by WebKit for font selection
594 // purposes. For example, USCRIPT_KATAKANA_OR_HIRAGANA and USCRIPT_JAPANESE are
595 // considered equivalent for the purposes of font selection. WebKit uses the
596 // script code USCRIPT_KATAKANA_OR_HIRAGANA. So, if |scriptCode| is
597 // USCRIPT_JAPANESE, the function returns USCRIPT_KATAKANA_OR_HIRAGANA. WebKit
598 // uses different scripts than the ones in Chrome pref names because the version
599 // of ICU included on certain ports does not have some of the newer scripts. If
600 // |scriptCode| is not a member of such a family, returns |scriptCode|.
601 UScriptCode GetScriptForWebSettings(UScriptCode scriptCode) {
602 switch (scriptCode) {
603 case USCRIPT_HIRAGANA:
604 case USCRIPT_KATAKANA:
605 case USCRIPT_JAPANESE:
606 return USCRIPT_KATAKANA_OR_HIRAGANA;
607 case USCRIPT_KOREAN:
608 return USCRIPT_HANGUL;
609 default:
610 return scriptCode;
614 void ApplyFontsFromMap(const ScriptFontFamilyMap& map,
615 SetFontFamilyWrapper setter,
616 WebSettings* settings) {
617 for (ScriptFontFamilyMap::const_iterator it = map.begin(); it != map.end();
618 ++it) {
619 int32 script = u_getPropertyValueEnum(UCHAR_SCRIPT, (it->first).c_str());
620 if (script >= 0 && script < USCRIPT_CODE_LIMIT) {
621 UScriptCode code = static_cast<UScriptCode>(script);
622 (*setter)(settings, it->second, GetScriptForWebSettings(code));
627 } // namespace
629 RenderViewImpl::RenderViewImpl(const ViewMsg_New_Params& params)
630 : RenderWidget(blink::WebPopupTypeNone,
631 params.initial_size.screen_info,
632 params.swapped_out,
633 params.hidden,
634 params.never_visible),
635 webkit_preferences_(params.web_preferences),
636 send_content_state_immediately_(false),
637 enabled_bindings_(0),
638 send_preferred_size_changes_(false),
639 navigation_gesture_(NavigationGestureUnknown),
640 opened_by_user_gesture_(true),
641 opener_suppressed_(false),
642 suppress_dialogs_until_swap_out_(false),
643 page_id_(-1),
644 next_page_id_(params.next_page_id),
645 history_list_offset_(-1),
646 history_list_length_(0),
647 frames_in_progress_(0),
648 target_url_status_(TARGET_NONE),
649 uses_temporary_zoom_level_(false),
650 #if defined(OS_ANDROID)
651 top_controls_constraints_(TOP_CONTROLS_STATE_BOTH),
652 #endif
653 has_scrolled_focused_editable_node_into_rect_(false),
654 speech_recognition_dispatcher_(NULL),
655 devtools_agent_(NULL),
656 mouse_lock_dispatcher_(NULL),
657 #if defined(OS_ANDROID)
658 expected_content_intent_id_(0),
659 #endif
660 #if defined(OS_WIN)
661 focused_plugin_id_(-1),
662 #endif
663 #if defined(ENABLE_PLUGINS)
664 plugin_find_handler_(NULL),
665 focused_pepper_plugin_(NULL),
666 pepper_last_mouse_event_target_(NULL),
667 #endif
668 enumeration_completion_id_(0),
669 session_storage_namespace_id_(params.session_storage_namespace_id),
670 next_snapshot_id_(0) {
673 void RenderViewImpl::Initialize(const ViewMsg_New_Params& params,
674 CompositorDependencies* compositor_deps,
675 bool was_created_by_renderer) {
676 routing_id_ = params.view_id;
677 surface_id_ = params.surface_id;
678 if (params.opener_route_id != MSG_ROUTING_NONE && was_created_by_renderer)
679 opener_id_ = params.opener_route_id;
681 // Ensure we start with a valid next_page_id_ from the browser.
682 DCHECK_GE(next_page_id_, 0);
684 main_render_frame_.reset(RenderFrameImpl::Create(
685 this, params.main_frame_routing_id));
686 // The main frame WebLocalFrame object is closed by
687 // RenderFrameImpl::frameDetached().
688 WebLocalFrame* web_frame = WebLocalFrame::create(main_render_frame_.get());
689 main_render_frame_->SetWebFrame(web_frame);
691 compositor_deps_ = compositor_deps;
692 webwidget_ = WebView::create(this);
693 webwidget_mouse_lock_target_.reset(new WebWidgetLockTarget(webwidget_));
695 const base::CommandLine& command_line =
696 *base::CommandLine::ForCurrentProcess();
698 if (command_line.HasSwitch(switches::kStatsCollectionController))
699 stats_collection_observer_.reset(new StatsCollectionObserver(this));
701 #if defined(OS_ANDROID)
702 const std::string region_code =
703 command_line.HasSwitch(switches::kNetworkCountryIso)
704 ? command_line.GetSwitchValueASCII(switches::kNetworkCountryIso)
705 : net::android::GetTelephonyNetworkCountryIso();
706 content_detectors_.push_back(linked_ptr<ContentDetector>(
707 new AddressDetector()));
708 if (!region_code.empty()) {
709 content_detectors_.push_back(linked_ptr<ContentDetector>(
710 new PhoneNumberDetector(region_code)));
712 content_detectors_.push_back(linked_ptr<ContentDetector>(
713 new EmailDetector()));
714 #endif
716 RenderThread::Get()->AddRoute(routing_id_, this);
717 // Take a reference on behalf of the RenderThread. This will be balanced
718 // when we receive ViewMsg_ClosePage.
719 AddRef();
720 if (RenderThreadImpl::current()) {
721 RenderThreadImpl::current()->WidgetCreated();
722 if (is_hidden_)
723 RenderThreadImpl::current()->WidgetHidden();
726 // If this is a popup, we must wait for the CreatingNew_ACK message before
727 // completing initialization. Otherwise, we can finish it now.
728 if (opener_id_ == MSG_ROUTING_NONE) {
729 did_show_ = true;
730 CompleteInit();
733 g_view_map.Get().insert(std::make_pair(webview(), this));
734 g_routing_id_view_map.Get().insert(std::make_pair(routing_id_, this));
735 webview()->setDeviceScaleFactor(device_scale_factor_);
736 webview()->settings()->setPreferCompositingToLCDTextEnabled(
737 PreferCompositingToLCDText(compositor_deps_, device_scale_factor_));
738 webview()->settings()->setThreadedScrollingEnabled(
739 !command_line.HasSwitch(switches::kDisableThreadedScrolling));
740 webview()->settings()->setRootLayerScrolls(
741 command_line.HasSwitch(switches::kRootLayerScrolls));
743 ApplyWebPreferences(webkit_preferences_, webview());
745 webview()->settings()->setAllowConnectingInsecureWebSocket(
746 command_line.HasSwitch(switches::kAllowInsecureWebSocketFromHttpsOrigin));
748 RenderFrameProxy* proxy = NULL;
749 if (params.proxy_routing_id != MSG_ROUTING_NONE) {
750 CHECK(params.swapped_out);
751 proxy = RenderFrameProxy::CreateProxyToReplaceFrame(
752 main_render_frame_.get(), params.proxy_routing_id);
753 main_render_frame_->set_render_frame_proxy(proxy);
756 // In --site-per-process, just use the WebRemoteFrame as the main frame.
757 if (command_line.HasSwitch(switches::kSitePerProcess) && proxy) {
758 webview()->setMainFrame(proxy->web_frame());
759 // Initialize the WebRemoteFrame with information replicated from the
760 // browser process.
761 proxy->SetReplicatedState(params.replicated_frame_state);
762 } else {
763 webview()->setMainFrame(main_render_frame_->GetWebFrame());
765 main_render_frame_->Initialize();
767 if (switches::IsTouchDragDropEnabled())
768 webview()->settings()->setTouchDragDropEnabled(true);
770 if (switches::IsTouchEditingEnabled())
771 webview()->settings()->setTouchEditingEnabled(true);
773 if (!params.frame_name.empty())
774 webview()->mainFrame()->setName(params.frame_name);
776 // TODO(davidben): Move this state from Blink into content.
777 if (params.window_was_created_with_opener)
778 webview()->setOpenedByDOM();
780 OnSetRendererPrefs(params.renderer_preferences);
782 if (!params.enable_auto_resize) {
783 OnResize(params.initial_size);
784 } else {
785 OnEnableAutoResize(params.min_size, params.max_size);
788 new MHTMLGenerator(this);
789 #if defined(OS_MACOSX)
790 new TextInputClientObserver(this);
791 #endif // defined(OS_MACOSX)
793 // The next group of objects all implement RenderViewObserver, so are deleted
794 // along with the RenderView automatically.
795 devtools_agent_ = new DevToolsAgent(main_render_frame_.get());
796 if (RenderWidgetCompositor* rwc = compositor()) {
797 webview()->devToolsAgent()->setLayerTreeId(rwc->GetLayerTreeId());
799 mouse_lock_dispatcher_ = new RenderViewMouseLockDispatcher(this);
801 history_controller_.reset(new HistoryController(this));
803 new IdleUserDetector(this);
805 if (command_line.HasSwitch(switches::kDomAutomationController))
806 enabled_bindings_ |= BINDINGS_POLICY_DOM_AUTOMATION;
807 if (command_line.HasSwitch(switches::kStatsCollectionController))
808 enabled_bindings_ |= BINDINGS_POLICY_STATS_COLLECTION;
810 GetContentClient()->renderer()->RenderViewCreated(this);
812 // If we have an opener_id but we weren't created by a renderer, then
813 // it's the browser asking us to set our opener to another RenderView.
814 if (params.opener_route_id != MSG_ROUTING_NONE && !was_created_by_renderer) {
815 RenderViewImpl* opener_view = FromRoutingID(params.opener_route_id);
816 if (opener_view)
817 webview()->mainFrame()->setOpener(opener_view->webview()->mainFrame());
820 // If we are initially swapped out, navigate to kSwappedOutURL.
821 // This ensures we are in a unique origin that others cannot script.
822 if (is_swapped_out_ && webview()->mainFrame()->isWebLocalFrame())
823 main_render_frame_->NavigateToSwappedOutURL();
826 RenderViewImpl::~RenderViewImpl() {
827 for (BitmapMap::iterator it = disambiguation_bitmaps_.begin();
828 it != disambiguation_bitmaps_.end();
829 ++it)
830 delete it->second;
831 base::trace_event::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_);
833 // If file chooser is still waiting for answer, dispatch empty answer.
834 while (!file_chooser_completions_.empty()) {
835 if (file_chooser_completions_.front()->completion) {
836 file_chooser_completions_.front()->completion->didChooseFile(
837 WebVector<WebString>());
839 file_chooser_completions_.pop_front();
842 #if defined(OS_ANDROID)
843 // The date/time picker client is both a scoped_ptr member of this class and
844 // a RenderViewObserver. Reset it to prevent double deletion.
845 date_time_picker_client_.reset();
846 #endif
848 #ifndef NDEBUG
849 // Make sure we are no longer referenced by the ViewMap or RoutingIDViewMap.
850 ViewMap* views = g_view_map.Pointer();
851 for (ViewMap::iterator it = views->begin(); it != views->end(); ++it)
852 DCHECK_NE(this, it->second) << "Failed to call Close?";
853 RoutingIDViewMap* routing_id_views = g_routing_id_view_map.Pointer();
854 for (RoutingIDViewMap::iterator it = routing_id_views->begin();
855 it != routing_id_views->end(); ++it)
856 DCHECK_NE(this, it->second) << "Failed to call Close?";
857 #endif
859 FOR_EACH_OBSERVER(RenderViewObserver, observers_, RenderViewGone());
860 FOR_EACH_OBSERVER(RenderViewObserver, observers_, OnDestruct());
863 /*static*/
864 RenderViewImpl* RenderViewImpl::FromWebView(WebView* webview) {
865 ViewMap* views = g_view_map.Pointer();
866 ViewMap::iterator it = views->find(webview);
867 return it == views->end() ? NULL : it->second;
870 /*static*/
871 RenderView* RenderView::FromWebView(blink::WebView* webview) {
872 return RenderViewImpl::FromWebView(webview);
875 /*static*/
876 RenderViewImpl* RenderViewImpl::FromRoutingID(int32 routing_id) {
877 RoutingIDViewMap* views = g_routing_id_view_map.Pointer();
878 RoutingIDViewMap::iterator it = views->find(routing_id);
879 return it == views->end() ? NULL : it->second;
882 /*static*/
883 RenderView* RenderView::FromRoutingID(int routing_id) {
884 return RenderViewImpl::FromRoutingID(routing_id);
887 /* static */
888 size_t RenderViewImpl::GetRenderViewCount() {
889 return g_view_map.Get().size();
892 /*static*/
893 void RenderView::ForEach(RenderViewVisitor* visitor) {
894 ViewMap* views = g_view_map.Pointer();
895 for (ViewMap::iterator it = views->begin(); it != views->end(); ++it) {
896 if (!visitor->Visit(it->second))
897 return;
901 /*static*/
902 void RenderView::ApplyWebPreferences(const WebPreferences& prefs,
903 WebView* web_view) {
904 WebSettings* settings = web_view->settings();
905 ApplyFontsFromMap(prefs.standard_font_family_map,
906 SetStandardFontFamilyWrapper, settings);
907 ApplyFontsFromMap(prefs.fixed_font_family_map,
908 SetFixedFontFamilyWrapper, settings);
909 ApplyFontsFromMap(prefs.serif_font_family_map,
910 SetSerifFontFamilyWrapper, settings);
911 ApplyFontsFromMap(prefs.sans_serif_font_family_map,
912 SetSansSerifFontFamilyWrapper, settings);
913 ApplyFontsFromMap(prefs.cursive_font_family_map,
914 SetCursiveFontFamilyWrapper, settings);
915 ApplyFontsFromMap(prefs.fantasy_font_family_map,
916 SetFantasyFontFamilyWrapper, settings);
917 ApplyFontsFromMap(prefs.pictograph_font_family_map,
918 SetPictographFontFamilyWrapper, settings);
919 settings->setDefaultFontSize(prefs.default_font_size);
920 settings->setDefaultFixedFontSize(prefs.default_fixed_font_size);
921 settings->setMinimumFontSize(prefs.minimum_font_size);
922 settings->setMinimumLogicalFontSize(prefs.minimum_logical_font_size);
923 settings->setDefaultTextEncodingName(
924 base::ASCIIToUTF16(prefs.default_encoding));
925 settings->setJavaScriptEnabled(prefs.javascript_enabled);
926 settings->setWebSecurityEnabled(prefs.web_security_enabled);
927 settings->setJavaScriptCanOpenWindowsAutomatically(
928 prefs.javascript_can_open_windows_automatically);
929 settings->setLoadsImagesAutomatically(prefs.loads_images_automatically);
930 settings->setImagesEnabled(prefs.images_enabled);
931 settings->setPluginsEnabled(prefs.plugins_enabled);
932 settings->setDOMPasteAllowed(prefs.dom_paste_enabled);
933 settings->setShrinksStandaloneImagesToFit(
934 prefs.shrinks_standalone_images_to_fit);
935 settings->setUsesEncodingDetector(prefs.uses_universal_detector);
936 settings->setTextAreasAreResizable(prefs.text_areas_are_resizable);
937 settings->setAllowScriptsToCloseWindows(prefs.allow_scripts_to_close_windows);
938 settings->setDownloadableBinaryFontsEnabled(prefs.remote_fonts_enabled);
939 settings->setJavaScriptCanAccessClipboard(
940 prefs.javascript_can_access_clipboard);
941 WebRuntimeFeatures::enableXSLT(prefs.xslt_enabled);
942 WebRuntimeFeatures::enableSlimmingPaint(prefs.slimming_paint_enabled);
943 settings->setXSSAuditorEnabled(prefs.xss_auditor_enabled);
944 settings->setDNSPrefetchingEnabled(prefs.dns_prefetching_enabled);
945 settings->setLocalStorageEnabled(prefs.local_storage_enabled);
946 settings->setSyncXHRInDocumentsEnabled(prefs.sync_xhr_in_documents_enabled);
947 WebRuntimeFeatures::enableDatabase(prefs.databases_enabled);
948 settings->setOfflineWebApplicationCacheEnabled(
949 prefs.application_cache_enabled);
950 settings->setCaretBrowsingEnabled(prefs.caret_browsing_enabled);
951 settings->setHyperlinkAuditingEnabled(prefs.hyperlink_auditing_enabled);
952 settings->setCookieEnabled(prefs.cookie_enabled);
953 settings->setNavigateOnDragDrop(prefs.navigate_on_drag_drop);
955 settings->setJavaEnabled(prefs.java_enabled);
957 // By default, allow_universal_access_from_file_urls is set to false and thus
958 // we mitigate attacks from local HTML files by not granting file:// URLs
959 // universal access. Only test shell will enable this.
960 settings->setAllowUniversalAccessFromFileURLs(
961 prefs.allow_universal_access_from_file_urls);
962 settings->setAllowFileAccessFromFileURLs(
963 prefs.allow_file_access_from_file_urls);
965 // Enable the web audio API if requested on the command line.
966 settings->setWebAudioEnabled(prefs.webaudio_enabled);
968 // Enable experimental WebGL support if requested on command line
969 // and support is compiled in.
970 settings->setExperimentalWebGLEnabled(prefs.experimental_webgl_enabled);
972 // Disable GL multisampling if requested on command line.
973 settings->setOpenGLMultisamplingEnabled(prefs.gl_multisampling_enabled);
975 // Enable WebGL errors to the JS console if requested.
976 settings->setWebGLErrorsToConsoleEnabled(
977 prefs.webgl_errors_to_console_enabled);
979 // Uses the mock theme engine for scrollbars.
980 settings->setMockScrollbarsEnabled(prefs.mock_scrollbars_enabled);
982 // Enable gpu-accelerated 2d canvas if requested on the command line.
983 settings->setAccelerated2dCanvasEnabled(prefs.accelerated_2d_canvas_enabled);
985 settings->setMinimumAccelerated2dCanvasSize(
986 prefs.minimum_accelerated_2d_canvas_size);
988 // Disable antialiasing for 2d canvas if requested on the command line.
989 settings->setAntialiased2dCanvasEnabled(
990 !prefs.antialiased_2d_canvas_disabled);
992 // Enabled antialiasing of clips for 2d canvas if requested on the command
993 // line.
994 settings->setAntialiasedClips2dCanvasEnabled(
995 prefs.antialiased_clips_2d_canvas_enabled);
997 // Set MSAA sample count for 2d canvas if requested on the command line (or
998 // default value if not).
999 settings->setAccelerated2dCanvasMSAASampleCount(
1000 prefs.accelerated_2d_canvas_msaa_sample_count);
1002 WebRuntimeFeatures::enableTextBlobs(prefs.text_blobs_enabled);
1004 settings->setAsynchronousSpellCheckingEnabled(
1005 prefs.asynchronous_spell_checking_enabled);
1006 settings->setUnifiedTextCheckerEnabled(prefs.unified_textchecker_enabled);
1008 // Tabs to link is not part of the settings. WebCore calls
1009 // ChromeClient::tabsToLinks which is part of the glue code.
1010 web_view->setTabsToLinks(prefs.tabs_to_links);
1012 settings->setAllowDisplayOfInsecureContent(
1013 prefs.allow_displaying_insecure_content);
1014 settings->setAllowRunningOfInsecureContent(
1015 prefs.allow_running_insecure_content);
1016 settings->setDisableReadingFromCanvas(prefs.disable_reading_from_canvas);
1017 settings->setStrictMixedContentChecking(prefs.strict_mixed_content_checking);
1018 settings->setStrictPowerfulFeatureRestrictions(
1019 prefs.strict_powerful_feature_restrictions);
1020 settings->setPasswordEchoEnabled(prefs.password_echo_enabled);
1021 settings->setShouldPrintBackgrounds(prefs.should_print_backgrounds);
1022 settings->setShouldClearDocumentBackground(
1023 prefs.should_clear_document_background);
1024 settings->setEnableScrollAnimator(prefs.enable_scroll_animator);
1026 settings->setRegionBasedColumnsEnabled(prefs.region_based_columns_enabled);
1028 WebRuntimeFeatures::enableTouch(prefs.touch_enabled);
1029 settings->setMaxTouchPoints(prefs.pointer_events_max_touch_points);
1030 settings->setAvailablePointerTypes(prefs.available_pointer_types);
1031 settings->setPrimaryPointerType(
1032 static_cast<WebSettings::PointerType>(prefs.primary_pointer_type));
1033 settings->setAvailableHoverTypes(prefs.available_hover_types);
1034 settings->setPrimaryHoverType(
1035 static_cast<WebSettings::HoverType>(prefs.primary_hover_type));
1036 settings->setDeviceSupportsTouch(prefs.device_supports_touch);
1037 settings->setDeviceSupportsMouse(prefs.device_supports_mouse);
1038 settings->setEnableTouchAdjustment(prefs.touch_adjustment_enabled);
1040 settings->setDeferredImageDecodingEnabled(
1041 prefs.deferred_image_decoding_enabled);
1042 WebRuntimeFeatures::enableImageColorProfiles(
1043 prefs.image_color_profiles_enabled);
1044 settings->setShouldRespectImageOrientation(
1045 prefs.should_respect_image_orientation);
1047 settings->setUnsafePluginPastingEnabled(false);
1048 settings->setEditingBehavior(
1049 static_cast<WebSettings::EditingBehavior>(prefs.editing_behavior));
1051 settings->setSupportsMultipleWindows(prefs.supports_multiple_windows);
1053 settings->setViewportEnabled(prefs.viewport_enabled);
1054 settings->setLoadWithOverviewMode(prefs.initialize_at_minimum_page_scale);
1055 settings->setViewportMetaEnabled(prefs.viewport_meta_enabled);
1056 settings->setMainFrameResizesAreOrientationChanges(
1057 prefs.main_frame_resizes_are_orientation_changes);
1059 settings->setSmartInsertDeleteEnabled(prefs.smart_insert_delete_enabled);
1061 settings->setSpatialNavigationEnabled(prefs.spatial_navigation_enabled);
1063 settings->setSelectionIncludesAltImageText(true);
1065 settings->setV8CacheOptions(
1066 static_cast<WebSettings::V8CacheOptions>(prefs.v8_cache_options));
1068 settings->setImageAnimationPolicy(
1069 static_cast<WebSettings::ImageAnimationPolicy>(prefs.animation_policy));
1071 // Needs to happen before setIgnoreVIewportTagScaleLimits below.
1072 web_view->setDefaultPageScaleLimits(
1073 prefs.default_minimum_page_scale_factor,
1074 prefs.default_maximum_page_scale_factor);
1076 #if defined(OS_ANDROID)
1077 settings->setAllowCustomScrollbarInMainFrame(false);
1078 settings->setTextAutosizingEnabled(prefs.text_autosizing_enabled);
1079 settings->setAccessibilityFontScaleFactor(prefs.font_scale_factor);
1080 settings->setDeviceScaleAdjustment(prefs.device_scale_adjustment);
1081 settings->setFullscreenSupported(prefs.fullscreen_supported);
1082 web_view->setIgnoreViewportTagScaleLimits(prefs.force_enable_zoom);
1083 settings->setAutoZoomFocusedNodeToLegibleScale(true);
1084 settings->setDoubleTapToZoomEnabled(prefs.double_tap_to_zoom_enabled);
1085 settings->setMediaControlsOverlayPlayButtonEnabled(true);
1086 settings->setMediaPlaybackRequiresUserGesture(
1087 prefs.user_gesture_required_for_media_playback);
1088 settings->setDefaultVideoPosterURL(
1089 base::ASCIIToUTF16(prefs.default_video_poster_url.spec()));
1090 settings->setSupportDeprecatedTargetDensityDPI(
1091 prefs.support_deprecated_target_density_dpi);
1092 settings->setUseLegacyBackgroundSizeShorthandBehavior(
1093 prefs.use_legacy_background_size_shorthand_behavior);
1094 settings->setWideViewportQuirkEnabled(prefs.wide_viewport_quirk);
1095 settings->setUseWideViewport(prefs.use_wide_viewport);
1096 settings->setForceZeroLayoutHeight(prefs.force_zero_layout_height);
1097 settings->setViewportMetaLayoutSizeQuirk(
1098 prefs.viewport_meta_layout_size_quirk);
1099 settings->setViewportMetaMergeContentQuirk(
1100 prefs.viewport_meta_merge_content_quirk);
1101 settings->setViewportMetaNonUserScalableQuirk(
1102 prefs.viewport_meta_non_user_scalable_quirk);
1103 settings->setViewportMetaZeroValuesQuirk(
1104 prefs.viewport_meta_zero_values_quirk);
1105 settings->setClobberUserAgentInitialScaleQuirk(
1106 prefs.clobber_user_agent_initial_scale_quirk);
1107 settings->setIgnoreMainFrameOverflowHiddenQuirk(
1108 prefs.ignore_main_frame_overflow_hidden_quirk);
1109 settings->setReportScreenSizeInPhysicalPixelsQuirk(
1110 prefs.report_screen_size_in_physical_pixels_quirk);
1112 bool record_full_layer =
1113 RenderViewImpl::FromWebView(web_view)
1114 ? RenderViewImpl::FromWebView(web_view)->DoesRecordFullLayer()
1115 : false;
1116 settings->setMainFrameClipsContent(!record_full_layer);
1118 settings->setShrinksStandaloneImagesToFit(false);
1119 settings->setShrinksViewportContentToFit(true);
1120 #endif
1122 WebNetworkStateNotifier::setOnLine(prefs.is_online);
1123 WebNetworkStateNotifier::setWebConnectionType(
1124 NetConnectionTypeToWebConnectionType(prefs.connection_type));
1125 settings->setPinchVirtualViewportEnabled(
1126 prefs.pinch_virtual_viewport_enabled);
1128 settings->setPinchOverlayScrollbarThickness(
1129 prefs.pinch_overlay_scrollbar_thickness);
1130 settings->setRubberBandingOnCompositorThread(
1131 prefs.rubber_banding_on_compositor_thread);
1132 settings->setUseSolidColorScrollbars(prefs.use_solid_color_scrollbars);
1134 #if defined(OS_WIN)
1135 settings->setShowContextMenuOnMouseUp(true);
1136 #endif
1138 #if defined(OS_MACOSX)
1139 settings->setDoubleTapToZoomEnabled(true);
1140 web_view->setMaximumLegibleScale(prefs.default_maximum_page_scale_factor);
1141 #endif
1144 /*static*/
1145 RenderViewImpl* RenderViewImpl::Create(const ViewMsg_New_Params& params,
1146 CompositorDependencies* compositor_deps,
1147 bool was_created_by_renderer) {
1148 DCHECK(params.view_id != MSG_ROUTING_NONE);
1149 RenderViewImpl* render_view = NULL;
1150 if (g_create_render_view_impl)
1151 render_view = g_create_render_view_impl(params);
1152 else
1153 render_view = new RenderViewImpl(params);
1155 render_view->Initialize(params, compositor_deps, was_created_by_renderer);
1156 return render_view;
1159 // static
1160 void RenderViewImpl::InstallCreateHook(
1161 RenderViewImpl* (*create_render_view_impl)(const ViewMsg_New_Params&)) {
1162 CHECK(!g_create_render_view_impl);
1163 g_create_render_view_impl = create_render_view_impl;
1166 void RenderViewImpl::AddObserver(RenderViewObserver* observer) {
1167 observers_.AddObserver(observer);
1170 void RenderViewImpl::RemoveObserver(RenderViewObserver* observer) {
1171 observer->RenderViewGone();
1172 observers_.RemoveObserver(observer);
1175 blink::WebView* RenderViewImpl::webview() const {
1176 return static_cast<blink::WebView*>(webwidget());
1179 #if defined(ENABLE_PLUGINS)
1180 void RenderViewImpl::PepperInstanceCreated(
1181 PepperPluginInstanceImpl* instance) {
1182 active_pepper_instances_.insert(instance);
1185 void RenderViewImpl::PepperInstanceDeleted(
1186 PepperPluginInstanceImpl* instance) {
1187 active_pepper_instances_.erase(instance);
1189 if (pepper_last_mouse_event_target_ == instance)
1190 pepper_last_mouse_event_target_ = NULL;
1191 if (focused_pepper_plugin_ == instance)
1192 PepperFocusChanged(instance, false);
1195 void RenderViewImpl::PepperFocusChanged(PepperPluginInstanceImpl* instance,
1196 bool focused) {
1197 if (focused)
1198 focused_pepper_plugin_ = instance;
1199 else if (focused_pepper_plugin_ == instance)
1200 focused_pepper_plugin_ = NULL;
1202 UpdateTextInputType();
1203 UpdateSelectionBounds();
1206 void RenderViewImpl::RegisterPluginDelegate(WebPluginDelegateProxy* delegate) {
1207 plugin_delegates_.insert(delegate);
1208 // If the renderer is visible, set initial visibility and focus state.
1209 if (!is_hidden()) {
1210 #if defined(OS_MACOSX)
1211 delegate->SetContainerVisibility(true);
1212 if (webview() && webview()->isActive())
1213 delegate->SetWindowFocus(true);
1214 #endif
1216 // Plugins start assuming the content has focus (so that they work in
1217 // environments where RenderView isn't hosting them), so we always have to
1218 // set the initial state. See webplugin_delegate_impl.h for details.
1219 delegate->SetContentAreaFocus(has_focus());
1222 void RenderViewImpl::UnregisterPluginDelegate(
1223 WebPluginDelegateProxy* delegate) {
1224 plugin_delegates_.erase(delegate);
1227 #if defined(OS_WIN)
1228 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1229 if (focused)
1230 focused_plugin_id_ = plugin_id;
1231 else
1232 focused_plugin_id_ = -1;
1234 #endif
1236 #if defined(OS_MACOSX)
1237 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1238 Send(new ViewHostMsg_PluginFocusChanged(routing_id(), focused, plugin_id));
1241 void RenderViewImpl::OnGetRenderedText() {
1242 if (!webview())
1243 return;
1244 // Get rendered text from WebLocalFrame.
1245 // TODO: Currently IPC truncates any data that has a
1246 // size > kMaximumMessageSize. May be split the text into smaller chunks and
1247 // send back using multiple IPC. See http://crbug.com/393444.
1248 static const size_t kMaximumMessageSize = 8 * 1024 * 1024;
1249 std::string text = webview()->mainFrame()->contentAsText(
1250 kMaximumMessageSize).utf8();
1252 Send(new ViewMsg_GetRenderedTextCompleted(routing_id(), text));
1255 void RenderViewImpl::StartPluginIme() {
1256 IPC::Message* msg = new ViewHostMsg_StartPluginIme(routing_id());
1257 // This message can be sent during event-handling, and needs to be delivered
1258 // within that context.
1259 msg->set_unblock(true);
1260 Send(msg);
1262 #endif // defined(OS_MACOSX)
1264 #endif // ENABLE_PLUGINS
1266 void RenderViewImpl::TransferActiveWheelFlingAnimation(
1267 const blink::WebActiveWheelFlingParameters& params) {
1268 if (webview())
1269 webview()->transferActiveWheelFlingAnimation(params);
1272 bool RenderViewImpl::HasIMETextFocus() {
1273 return GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE;
1276 bool RenderViewImpl::OnMessageReceived(const IPC::Message& message) {
1277 WebFrame* main_frame = webview() ? webview()->mainFrame() : NULL;
1278 if (main_frame && main_frame->isWebLocalFrame())
1279 GetContentClient()->SetActiveURL(main_frame->document().url());
1281 ObserverListBase<RenderViewObserver>::Iterator it(observers_);
1282 RenderViewObserver* observer;
1283 while ((observer = it.GetNext()) != NULL)
1284 if (observer->OnMessageReceived(message))
1285 return true;
1287 bool handled = true;
1288 IPC_BEGIN_MESSAGE_MAP(RenderViewImpl, message)
1289 IPC_MESSAGE_HANDLER(InputMsg_ExecuteEditCommand, OnExecuteEditCommand)
1290 IPC_MESSAGE_HANDLER(InputMsg_MoveCaret, OnMoveCaret)
1291 IPC_MESSAGE_HANDLER(InputMsg_ScrollFocusedEditableNodeIntoRect,
1292 OnScrollFocusedEditableNodeIntoRect)
1293 IPC_MESSAGE_HANDLER(InputMsg_SetEditCommandsForNextKeyEvent,
1294 OnSetEditCommandsForNextKeyEvent)
1295 IPC_MESSAGE_HANDLER(ViewMsg_CopyImageAt, OnCopyImageAt)
1296 IPC_MESSAGE_HANDLER(ViewMsg_SaveImageAt, OnSaveImageAt)
1297 IPC_MESSAGE_HANDLER(ViewMsg_Find, OnFind)
1298 IPC_MESSAGE_HANDLER(ViewMsg_StopFinding, OnStopFinding)
1299 IPC_MESSAGE_HANDLER(ViewMsg_Zoom, OnZoom)
1300 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForLoadingURL,
1301 OnSetZoomLevelForLoadingURL)
1302 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForView,
1303 OnSetZoomLevelForView)
1304 IPC_MESSAGE_HANDLER(ViewMsg_SetPageEncoding, OnSetPageEncoding)
1305 IPC_MESSAGE_HANDLER(ViewMsg_ResetPageEncodingToDefault,
1306 OnResetPageEncodingToDefault)
1307 IPC_MESSAGE_HANDLER(ViewMsg_PostMessageEvent, OnPostMessageEvent)
1308 IPC_MESSAGE_HANDLER(DragMsg_TargetDragEnter, OnDragTargetDragEnter)
1309 IPC_MESSAGE_HANDLER(DragMsg_TargetDragOver, OnDragTargetDragOver)
1310 IPC_MESSAGE_HANDLER(DragMsg_TargetDragLeave, OnDragTargetDragLeave)
1311 IPC_MESSAGE_HANDLER(DragMsg_TargetDrop, OnDragTargetDrop)
1312 IPC_MESSAGE_HANDLER(DragMsg_SourceEnded, OnDragSourceEnded)
1313 IPC_MESSAGE_HANDLER(DragMsg_SourceSystemDragEnded,
1314 OnDragSourceSystemDragEnded)
1315 IPC_MESSAGE_HANDLER(ViewMsg_AllowBindings, OnAllowBindings)
1316 IPC_MESSAGE_HANDLER(ViewMsg_SetInitialFocus, OnSetInitialFocus)
1317 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTargetURL_ACK, OnUpdateTargetURLAck)
1318 IPC_MESSAGE_HANDLER(ViewMsg_UpdateWebPreferences, OnUpdateWebPreferences)
1319 IPC_MESSAGE_HANDLER(ViewMsg_EnumerateDirectoryResponse,
1320 OnEnumerateDirectoryResponse)
1321 IPC_MESSAGE_HANDLER(ViewMsg_RunFileChooserResponse, OnFileChooserResponse)
1322 IPC_MESSAGE_HANDLER(ViewMsg_SuppressDialogsUntilSwapOut,
1323 OnSuppressDialogsUntilSwapOut)
1324 IPC_MESSAGE_HANDLER(ViewMsg_ClosePage, OnClosePage)
1325 IPC_MESSAGE_HANDLER(ViewMsg_ThemeChanged, OnThemeChanged)
1326 IPC_MESSAGE_HANDLER(ViewMsg_MoveOrResizeStarted, OnMoveOrResizeStarted)
1327 IPC_MESSAGE_HANDLER(ViewMsg_ClearFocusedElement, OnClearFocusedElement)
1328 IPC_MESSAGE_HANDLER(ViewMsg_SetBackgroundOpaque, OnSetBackgroundOpaque)
1329 IPC_MESSAGE_HANDLER(ViewMsg_EnablePreferredSizeChangedMode,
1330 OnEnablePreferredSizeChangedMode)
1331 IPC_MESSAGE_HANDLER(ViewMsg_EnableAutoResize, OnEnableAutoResize)
1332 IPC_MESSAGE_HANDLER(ViewMsg_DisableAutoResize, OnDisableAutoResize)
1333 IPC_MESSAGE_HANDLER(ViewMsg_DisableScrollbarsForSmallWindows,
1334 OnDisableScrollbarsForSmallWindows)
1335 IPC_MESSAGE_HANDLER(ViewMsg_SetRendererPrefs, OnSetRendererPrefs)
1336 IPC_MESSAGE_HANDLER(ViewMsg_MediaPlayerActionAt, OnMediaPlayerActionAt)
1337 IPC_MESSAGE_HANDLER(ViewMsg_PluginActionAt, OnPluginActionAt)
1338 IPC_MESSAGE_HANDLER(ViewMsg_SetActive, OnSetActive)
1339 IPC_MESSAGE_HANDLER(ViewMsg_GetAllSavableResourceLinksForCurrentPage,
1340 OnGetAllSavableResourceLinksForCurrentPage)
1341 IPC_MESSAGE_HANDLER(
1342 ViewMsg_GetSerializedHtmlDataForCurrentPageWithLocalLinks,
1343 OnGetSerializedHtmlDataForCurrentPageWithLocalLinks)
1344 IPC_MESSAGE_HANDLER(ViewMsg_ShowContextMenu, OnShowContextMenu)
1345 // TODO(viettrungluu): Move to a separate message filter.
1346 IPC_MESSAGE_HANDLER(ViewMsg_SetHistoryOffsetAndLength,
1347 OnSetHistoryOffsetAndLength)
1348 IPC_MESSAGE_HANDLER(ViewMsg_EnableViewSourceMode, OnEnableViewSourceMode)
1349 IPC_MESSAGE_HANDLER(ViewMsg_ReleaseDisambiguationPopupBitmap,
1350 OnReleaseDisambiguationPopupBitmap)
1351 IPC_MESSAGE_HANDLER(ViewMsg_WindowSnapshotCompleted,
1352 OnWindowSnapshotCompleted)
1353 IPC_MESSAGE_HANDLER(ViewMsg_ForceRedraw, OnForceRedraw)
1354 IPC_MESSAGE_HANDLER(ViewMsg_SelectWordAroundCaret, OnSelectWordAroundCaret)
1355 #if defined(OS_ANDROID)
1356 IPC_MESSAGE_HANDLER(InputMsg_ActivateNearestFindResult,
1357 OnActivateNearestFindResult)
1358 IPC_MESSAGE_HANDLER(ViewMsg_FindMatchRects, OnFindMatchRects)
1359 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTopControlsState,
1360 OnUpdateTopControlsState)
1361 IPC_MESSAGE_HANDLER(ViewMsg_ExtractSmartClipData, OnExtractSmartClipData)
1362 #elif defined(OS_MACOSX)
1363 IPC_MESSAGE_HANDLER(ViewMsg_GetRenderedText,
1364 OnGetRenderedText)
1365 IPC_MESSAGE_HANDLER(ViewMsg_PluginImeCompositionCompleted,
1366 OnPluginImeCompositionCompleted)
1367 IPC_MESSAGE_HANDLER(ViewMsg_SetInLiveResize, OnSetInLiveResize)
1368 IPC_MESSAGE_HANDLER(ViewMsg_SetWindowVisibility, OnSetWindowVisibility)
1369 IPC_MESSAGE_HANDLER(ViewMsg_WindowFrameChanged, OnWindowFrameChanged)
1370 #endif
1371 // Adding a new message? Add platform independent ones first, then put the
1372 // platform specific ones at the end.
1374 // Have the super handle all other messages.
1375 IPC_MESSAGE_UNHANDLED(handled = RenderWidget::OnMessageReceived(message))
1376 IPC_END_MESSAGE_MAP()
1378 return handled;
1381 void RenderViewImpl::OnSelectWordAroundCaret() {
1382 if (!webview())
1383 return;
1385 handling_input_event_ = true;
1386 webview()->focusedFrame()->selectWordAroundCaret();
1387 handling_input_event_ = false;
1390 void RenderViewImpl::OnCopyImageAt(int x, int y) {
1391 webview()->copyImageAt(WebPoint(x, y));
1394 void RenderViewImpl::OnSaveImageAt(int x, int y) {
1395 webview()->saveImageAt(WebPoint(x, y));
1398 void RenderViewImpl::OnUpdateTargetURLAck() {
1399 // Check if there is a targeturl waiting to be sent.
1400 if (target_url_status_ == TARGET_PENDING)
1401 Send(new ViewHostMsg_UpdateTargetURL(routing_id_, pending_target_url_));
1403 target_url_status_ = TARGET_NONE;
1406 void RenderViewImpl::OnExecuteEditCommand(const std::string& name,
1407 const std::string& value) {
1408 if (!webview() || !webview()->focusedFrame())
1409 return;
1411 webview()->focusedFrame()->executeCommand(
1412 WebString::fromUTF8(name), WebString::fromUTF8(value));
1415 void RenderViewImpl::OnMoveCaret(const gfx::Point& point) {
1416 if (!webview())
1417 return;
1419 Send(new InputHostMsg_MoveCaret_ACK(routing_id_));
1421 webview()->focusedFrame()->moveCaretSelection(point);
1424 void RenderViewImpl::OnScrollFocusedEditableNodeIntoRect(
1425 const gfx::Rect& rect) {
1426 if (has_scrolled_focused_editable_node_into_rect_ &&
1427 rect == rect_for_scrolled_focused_editable_node_) {
1428 FocusChangeComplete();
1429 return;
1432 blink::WebElement element = GetFocusedElement();
1433 bool will_animate = false;
1434 if (!element.isNull() && IsEditableNode(element)) {
1435 rect_for_scrolled_focused_editable_node_ = rect;
1436 has_scrolled_focused_editable_node_into_rect_ = true;
1437 will_animate = webview()->scrollFocusedNodeIntoRect(rect);
1440 if (!will_animate)
1441 FocusChangeComplete();
1444 void RenderViewImpl::OnSetEditCommandsForNextKeyEvent(
1445 const EditCommands& edit_commands) {
1446 edit_commands_ = edit_commands;
1449 void RenderViewImpl::OnSetHistoryOffsetAndLength(int history_offset,
1450 int history_length) {
1451 DCHECK_GE(history_offset, -1);
1452 DCHECK_GE(history_length, 0);
1454 history_list_offset_ = history_offset;
1455 history_list_length_ = history_length;
1458 void RenderViewImpl::OnSetInitialFocus(bool reverse) {
1459 if (!webview())
1460 return;
1461 webview()->setInitialFocus(reverse);
1464 #if defined(OS_MACOSX)
1465 void RenderViewImpl::OnSetInLiveResize(bool in_live_resize) {
1466 if (!webview())
1467 return;
1468 if (in_live_resize)
1469 webview()->willStartLiveResize();
1470 else
1471 webview()->willEndLiveResize();
1473 #endif
1475 ///////////////////////////////////////////////////////////////////////////////
1477 // Sends the current history state to the browser so it will be saved before we
1478 // navigate to a new page.
1479 void RenderViewImpl::UpdateSessionHistory(WebFrame* frame) {
1480 // If we have a valid page ID at this point, then it corresponds to the page
1481 // we are navigating away from. Otherwise, this is the first navigation, so
1482 // there is no past session history to record.
1483 if (page_id_ == -1)
1484 return;
1485 SendUpdateState(history_controller_->GetCurrentEntry());
1488 void RenderViewImpl::SendUpdateState(HistoryEntry* entry) {
1489 if (!entry)
1490 return;
1492 // Don't send state updates for kSwappedOutURL.
1493 if (entry->root().urlString() == WebString::fromUTF8(kSwappedOutURL))
1494 return;
1496 Send(new ViewHostMsg_UpdateState(
1497 routing_id_, page_id_, HistoryEntryToPageState(entry)));
1500 bool RenderViewImpl::SendAndRunNestedMessageLoop(IPC::SyncMessage* message) {
1501 // Before WebKit asks us to show an alert (etc.), it takes care of doing the
1502 // equivalent of WebView::willEnterModalLoop. In the case of showModalDialog
1503 // it is particularly important that we do not call willEnterModalLoop as
1504 // that would defer resource loads for the dialog itself.
1505 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
1506 RenderThreadImpl::current()->DoNotNotifyWebKitOfModalLoop();
1508 message->EnableMessagePumping(); // Runs a nested message loop.
1509 return Send(message);
1512 void RenderViewImpl::GetWindowSnapshot(const WindowSnapshotCallback& callback) {
1513 int id = next_snapshot_id_++;
1514 pending_snapshots_.insert(std::make_pair(id, callback));
1515 ui::LatencyInfo latency_info;
1516 latency_info.AddLatencyNumber(ui::WINDOW_OLD_SNAPSHOT_FRAME_NUMBER_COMPONENT,
1518 id);
1519 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1520 if (RenderWidgetCompositor* rwc = compositor()) {
1521 latency_info_swap_promise_monitor =
1522 rwc->CreateLatencyInfoSwapPromiseMonitor(&latency_info).Pass();
1524 ScheduleCompositeWithForcedRedraw();
1527 void RenderViewImpl::OnForceRedraw(int id) {
1528 ui::LatencyInfo latency_info;
1529 if (id) {
1530 latency_info.AddLatencyNumber(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
1532 id);
1534 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1535 if (RenderWidgetCompositor* rwc = compositor()) {
1536 latency_info_swap_promise_monitor =
1537 rwc->CreateLatencyInfoSwapPromiseMonitor(&latency_info).Pass();
1539 ScheduleCompositeWithForcedRedraw();
1542 void RenderViewImpl::OnWindowSnapshotCompleted(const int snapshot_id,
1543 const gfx::Size& size, const std::vector<unsigned char>& png) {
1545 // Any pending snapshots with a lower ID than the one received are considered
1546 // to be implicitly complete, and returned the same snapshot data.
1547 PendingSnapshotMap::iterator it = pending_snapshots_.begin();
1548 while(it != pending_snapshots_.end()) {
1549 if (it->first <= snapshot_id) {
1550 it->second.Run(size, png);
1551 pending_snapshots_.erase(it++);
1552 } else {
1553 ++it;
1558 // blink::WebViewClient ------------------------------------------------------
1560 WebView* RenderViewImpl::createView(WebLocalFrame* creator,
1561 const WebURLRequest& request,
1562 const WebWindowFeatures& features,
1563 const WebString& frame_name,
1564 WebNavigationPolicy policy,
1565 bool suppress_opener) {
1566 ViewHostMsg_CreateWindow_Params params;
1567 params.opener_id = routing_id_;
1568 params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
1569 if (GetContentClient()->renderer()->AllowPopup())
1570 params.user_gesture = true;
1571 params.window_container_type = WindowFeaturesToContainerType(features);
1572 params.session_storage_namespace_id = session_storage_namespace_id_;
1573 if (frame_name != "_blank")
1574 params.frame_name = frame_name;
1575 params.opener_render_frame_id =
1576 RenderFrameImpl::FromWebFrame(creator)->GetRoutingID();
1577 params.opener_url = creator->document().url();
1578 params.opener_top_level_frame_url = creator->top()->document().url();
1579 GURL security_url(creator->document().securityOrigin().toString());
1580 if (!security_url.is_valid())
1581 security_url = GURL();
1582 params.opener_security_origin = security_url;
1583 params.opener_suppressed = suppress_opener;
1584 params.disposition = NavigationPolicyToDisposition(policy);
1585 if (!request.isNull()) {
1586 params.target_url = request.url();
1587 params.referrer = GetReferrerFromRequest(creator, request);
1589 params.features = features;
1591 for (size_t i = 0; i < features.additionalFeatures.size(); ++i)
1592 params.additional_features.push_back(features.additionalFeatures[i]);
1594 int32 routing_id = MSG_ROUTING_NONE;
1595 int32 main_frame_routing_id = MSG_ROUTING_NONE;
1596 int32 surface_id = 0;
1597 int64 cloned_session_storage_namespace_id = 0;
1599 RenderThread::Get()->Send(new ViewHostMsg_CreateWindow(
1600 params, &routing_id, &main_frame_routing_id, &surface_id,
1601 &cloned_session_storage_namespace_id));
1602 if (routing_id == MSG_ROUTING_NONE)
1603 return NULL;
1605 WebUserGestureIndicator::consumeUserGesture();
1607 // While this view may be a background extension page, it can spawn a visible
1608 // render view. So we just assume that the new one is not another background
1609 // page instead of passing on our own value.
1610 // TODO(vangelis): Can we tell if the new view will be a background page?
1611 bool never_visible = false;
1613 ViewMsg_Resize_Params initial_size = ViewMsg_Resize_Params();
1614 initial_size.screen_info = screen_info_;
1616 // The initial hidden state for the RenderViewImpl here has to match what the
1617 // browser will eventually decide for the given disposition. Since we have to
1618 // return from this call synchronously, we just have to make our best guess
1619 // and rely on the browser sending a WasHidden / WasShown message if it
1620 // disagrees.
1621 ViewMsg_New_Params view_params;
1622 view_params.opener_route_id = routing_id_;
1623 view_params.window_was_created_with_opener = true;
1624 view_params.renderer_preferences = renderer_preferences_;
1625 view_params.web_preferences = webkit_preferences_;
1626 view_params.view_id = routing_id;
1627 view_params.main_frame_routing_id = main_frame_routing_id;
1628 view_params.surface_id = surface_id;
1629 view_params.session_storage_namespace_id =
1630 cloned_session_storage_namespace_id;
1631 // WebCore will take care of setting the correct name.
1632 view_params.frame_name = base::string16();
1633 view_params.swapped_out = false;
1634 view_params.replicated_frame_state = FrameReplicationState();
1635 view_params.proxy_routing_id = MSG_ROUTING_NONE;
1636 view_params.hidden = (params.disposition == NEW_BACKGROUND_TAB);
1637 view_params.never_visible = never_visible;
1638 view_params.next_page_id = 1;
1639 view_params.initial_size = initial_size;
1640 view_params.enable_auto_resize = false;
1641 view_params.min_size = gfx::Size();
1642 view_params.max_size = gfx::Size();
1644 RenderViewImpl* view =
1645 RenderViewImpl::Create(view_params, compositor_deps_, true);
1646 view->opened_by_user_gesture_ = params.user_gesture;
1648 // Record whether the creator frame is trying to suppress the opener field.
1649 view->opener_suppressed_ = params.opener_suppressed;
1651 return view->webview();
1654 WebWidget* RenderViewImpl::createPopupMenu(blink::WebPopupType popup_type) {
1655 RenderWidget* widget = RenderWidget::Create(routing_id_, compositor_deps_,
1656 popup_type, screen_info_);
1657 if (!widget)
1658 return NULL;
1659 if (screen_metrics_emulator_) {
1660 widget->SetPopupOriginAdjustmentsForEmulation(
1661 screen_metrics_emulator_.get());
1663 return widget->webwidget();
1666 WebStorageNamespace* RenderViewImpl::createSessionStorageNamespace() {
1667 CHECK(session_storage_namespace_id_ != kInvalidSessionStorageNamespaceId);
1668 return new WebStorageNamespaceImpl(session_storage_namespace_id_);
1671 void RenderViewImpl::printPage(WebLocalFrame* frame) {
1672 FOR_EACH_OBSERVER(RenderViewObserver, observers_,
1673 PrintPage(frame, handling_input_event_));
1676 void RenderViewImpl::saveImageFromDataURL(const blink::WebString& data_url) {
1677 // Note: We should basically send GURL but we use size-limited string instead
1678 // in order to send a larger data url to save a image for <canvas> or <img>.
1679 if (data_url.length() < kMaxLengthOfDataURLString)
1680 Send(new ViewHostMsg_SaveImageFromDataURL(routing_id_, data_url.utf8()));
1683 bool RenderViewImpl::enumerateChosenDirectory(
1684 const WebString& path,
1685 WebFileChooserCompletion* chooser_completion) {
1686 int id = enumeration_completion_id_++;
1687 enumeration_completions_[id] = chooser_completion;
1688 return Send(new ViewHostMsg_EnumerateDirectory(
1689 routing_id_,
1691 base::FilePath::FromUTF16Unsafe(path)));
1694 void RenderViewImpl::FrameDidStartLoading(WebFrame* frame) {
1695 DCHECK_GE(frames_in_progress_, 0);
1696 if (frames_in_progress_ == 0)
1697 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStartLoading());
1698 frames_in_progress_++;
1701 void RenderViewImpl::FrameDidStopLoading(WebFrame* frame) {
1702 // TODO(japhet): This should be a DCHECK, but the pdf plugin sometimes
1703 // calls DidStopLoading() without a matching DidStartLoading().
1704 if (frames_in_progress_ == 0)
1705 return;
1706 frames_in_progress_--;
1707 if (frames_in_progress_ == 0) {
1708 DidStopLoadingIcons();
1709 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStopLoading());
1713 void RenderViewImpl::didCancelCompositionOnSelectionChange() {
1714 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
1717 bool RenderViewImpl::handleCurrentKeyboardEvent() {
1718 if (edit_commands_.empty())
1719 return false;
1721 WebFrame* frame = webview()->focusedFrame();
1722 if (!frame)
1723 return false;
1725 EditCommands::iterator it = edit_commands_.begin();
1726 EditCommands::iterator end = edit_commands_.end();
1728 bool did_execute_command = false;
1729 for (; it != end; ++it) {
1730 // In gtk and cocoa, it's possible to bind multiple edit commands to one
1731 // key (but it's the exception). Once one edit command is not executed, it
1732 // seems safest to not execute the rest.
1733 if (!frame->executeCommand(WebString::fromUTF8(it->name),
1734 WebString::fromUTF8(it->value),
1735 GetFocusedElement()))
1736 break;
1737 did_execute_command = true;
1740 return did_execute_command;
1743 bool RenderViewImpl::runFileChooser(
1744 const blink::WebFileChooserParams& params,
1745 WebFileChooserCompletion* chooser_completion) {
1746 // Do not open the file dialog in a hidden RenderView.
1747 if (is_hidden())
1748 return false;
1749 FileChooserParams ipc_params;
1750 if (params.directory)
1751 ipc_params.mode = FileChooserParams::UploadFolder;
1752 else if (params.multiSelect)
1753 ipc_params.mode = FileChooserParams::OpenMultiple;
1754 else if (params.saveAs)
1755 ipc_params.mode = FileChooserParams::Save;
1756 else
1757 ipc_params.mode = FileChooserParams::Open;
1758 ipc_params.title = params.title;
1759 ipc_params.default_file_name =
1760 base::FilePath::FromUTF16Unsafe(params.initialValue).BaseName();
1761 ipc_params.accept_types.reserve(params.acceptTypes.size());
1762 for (size_t i = 0; i < params.acceptTypes.size(); ++i)
1763 ipc_params.accept_types.push_back(params.acceptTypes[i]);
1764 ipc_params.need_local_path = params.needLocalPath;
1765 #if defined(OS_ANDROID)
1766 ipc_params.capture = params.useMediaCapture;
1767 #endif
1769 return ScheduleFileChooser(ipc_params, chooser_completion);
1772 void RenderViewImpl::SetValidationMessageDirection(
1773 base::string16* wrapped_main_text,
1774 blink::WebTextDirection main_text_hint,
1775 base::string16* wrapped_sub_text,
1776 blink::WebTextDirection sub_text_hint) {
1777 if (main_text_hint == blink::WebTextDirectionLeftToRight) {
1778 *wrapped_main_text =
1779 base::i18n::GetDisplayStringInLTRDirectionality(*wrapped_main_text);
1780 } else if (main_text_hint == blink::WebTextDirectionRightToLeft &&
1781 !base::i18n::IsRTL()) {
1782 base::i18n::WrapStringWithRTLFormatting(wrapped_main_text);
1785 if (!wrapped_sub_text->empty()) {
1786 if (sub_text_hint == blink::WebTextDirectionLeftToRight) {
1787 *wrapped_sub_text =
1788 base::i18n::GetDisplayStringInLTRDirectionality(*wrapped_sub_text);
1789 } else if (sub_text_hint == blink::WebTextDirectionRightToLeft) {
1790 base::i18n::WrapStringWithRTLFormatting(wrapped_sub_text);
1795 void RenderViewImpl::showValidationMessage(
1796 const blink::WebRect& anchor_in_root_view,
1797 const blink::WebString& main_text,
1798 blink::WebTextDirection main_text_hint,
1799 const blink::WebString& sub_text,
1800 blink::WebTextDirection sub_text_hint) {
1801 base::string16 wrapped_main_text = main_text;
1802 base::string16 wrapped_sub_text = sub_text;
1804 SetValidationMessageDirection(
1805 &wrapped_main_text, main_text_hint, &wrapped_sub_text, sub_text_hint);
1807 Send(new ViewHostMsg_ShowValidationMessage(
1808 routing_id(), AdjustValidationMessageAnchor(anchor_in_root_view),
1809 wrapped_main_text, wrapped_sub_text));
1812 void RenderViewImpl::hideValidationMessage() {
1813 Send(new ViewHostMsg_HideValidationMessage(routing_id()));
1816 void RenderViewImpl::moveValidationMessage(
1817 const blink::WebRect& anchor_in_root_view) {
1818 Send(new ViewHostMsg_MoveValidationMessage(
1819 routing_id(), AdjustValidationMessageAnchor(anchor_in_root_view)));
1822 void RenderViewImpl::setStatusText(const WebString& text) {
1825 void RenderViewImpl::UpdateTargetURL(const GURL& url,
1826 const GURL& fallback_url) {
1827 GURL latest_url = url.is_empty() ? fallback_url : url;
1828 if (latest_url == target_url_)
1829 return;
1831 // Tell the browser to display a destination link.
1832 if (target_url_status_ == TARGET_INFLIGHT ||
1833 target_url_status_ == TARGET_PENDING) {
1834 // If we have a request in-flight, save the URL to be sent when we
1835 // receive an ACK to the in-flight request. We can happily overwrite
1836 // any existing pending sends.
1837 pending_target_url_ = latest_url;
1838 target_url_status_ = TARGET_PENDING;
1839 } else {
1840 // URLs larger than |MaxURLChars()| cannot be sent through IPC -
1841 // see |ParamTraits<GURL>|.
1842 if (latest_url.possibly_invalid_spec().size() > GetMaxURLChars())
1843 latest_url = GURL();
1844 Send(new ViewHostMsg_UpdateTargetURL(routing_id_, latest_url));
1845 target_url_ = latest_url;
1846 target_url_status_ = TARGET_INFLIGHT;
1850 gfx::RectF RenderViewImpl::ClientRectToPhysicalWindowRect(
1851 const gfx::RectF& rect) const {
1852 gfx::RectF window_rect = rect;
1853 window_rect.Scale(device_scale_factor_ * webview()->pageScaleFactor());
1854 return window_rect;
1857 void RenderViewImpl::StartNavStateSyncTimerIfNecessary() {
1858 // No need to update state if no page has committed yet.
1859 if (page_id_ == -1)
1860 return;
1862 int delay;
1863 if (send_content_state_immediately_)
1864 delay = 0;
1865 else if (is_hidden())
1866 delay = kDelaySecondsForContentStateSyncHidden;
1867 else
1868 delay = kDelaySecondsForContentStateSync;
1870 if (nav_state_sync_timer_.IsRunning()) {
1871 // The timer is already running. If the delay of the timer maches the amount
1872 // we want to delay by, then return. Otherwise stop the timer so that it
1873 // gets started with the right delay.
1874 if (nav_state_sync_timer_.GetCurrentDelay().InSeconds() == delay)
1875 return;
1876 nav_state_sync_timer_.Stop();
1879 nav_state_sync_timer_.Start(FROM_HERE, TimeDelta::FromSeconds(delay), this,
1880 &RenderViewImpl::SyncNavigationState);
1883 void RenderViewImpl::setMouseOverURL(const WebURL& url) {
1884 mouse_over_url_ = GURL(url);
1885 UpdateTargetURL(mouse_over_url_, focus_url_);
1888 void RenderViewImpl::setKeyboardFocusURL(const WebURL& url) {
1889 focus_url_ = GURL(url);
1890 UpdateTargetURL(focus_url_, mouse_over_url_);
1893 void RenderViewImpl::startDragging(WebLocalFrame* frame,
1894 const WebDragData& data,
1895 WebDragOperationsMask mask,
1896 const WebImage& image,
1897 const WebPoint& webImageOffset) {
1898 DropData drop_data(DropDataBuilder::Build(data));
1899 drop_data.referrer_policy = frame->document().referrerPolicy();
1900 gfx::Vector2d imageOffset(webImageOffset.x, webImageOffset.y);
1901 Send(new DragHostMsg_StartDragging(routing_id_,
1902 drop_data,
1903 mask,
1904 image.getSkBitmap(),
1905 imageOffset,
1906 possible_drag_event_info_));
1909 bool RenderViewImpl::acceptsLoadDrops() {
1910 return renderer_preferences_.can_accept_load_drops;
1913 void RenderViewImpl::focusNext() {
1914 Send(new ViewHostMsg_TakeFocus(routing_id_, false));
1917 void RenderViewImpl::focusPrevious() {
1918 Send(new ViewHostMsg_TakeFocus(routing_id_, true));
1921 void RenderViewImpl::focusedNodeChanged(const WebNode& fromNode,
1922 const WebNode& toNode) {
1923 has_scrolled_focused_editable_node_into_rect_ = false;
1925 gfx::Rect node_bounds;
1926 if (!toNode.isNull() && toNode.isElementNode()) {
1927 WebNode web_node = const_cast<WebNode&>(toNode);
1928 node_bounds = gfx::Rect(web_node.to<WebElement>().boundsInViewportSpace());
1930 Send(new ViewHostMsg_FocusedNodeChanged(routing_id_, IsEditableNode(toNode),
1931 node_bounds));
1933 // TODO(estade): remove.
1934 FOR_EACH_OBSERVER(RenderViewObserver, observers_, FocusedNodeChanged(toNode));
1936 RenderFrameImpl* previous_frame = nullptr;
1937 if (!fromNode.isNull())
1938 previous_frame = RenderFrameImpl::FromWebFrame(fromNode.document().frame());
1939 RenderFrameImpl* new_frame = nullptr;
1940 if (!toNode.isNull())
1941 new_frame = RenderFrameImpl::FromWebFrame(toNode.document().frame());
1943 if (previous_frame && previous_frame != new_frame)
1944 previous_frame->FocusedNodeChanged(WebNode());
1945 if (new_frame)
1946 new_frame->FocusedNodeChanged(toNode);
1948 // TODO(dmazzoni): remove once there's a separate a11y tree per frame.
1949 GetMainRenderFrame()->FocusedNodeChangedForAccessibility(toNode);
1952 void RenderViewImpl::didUpdateLayout() {
1953 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidUpdateLayout());
1955 // We don't always want to set up a timer, only if we've been put in that
1956 // mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
1957 // message.
1958 if (!send_preferred_size_changes_ || !webview())
1959 return;
1961 if (check_preferred_size_timer_.IsRunning())
1962 return;
1963 check_preferred_size_timer_.Start(FROM_HERE,
1964 TimeDelta::FromMilliseconds(0), this,
1965 &RenderViewImpl::CheckPreferredSize);
1968 void RenderViewImpl::navigateBackForwardSoon(int offset) {
1969 Send(new ViewHostMsg_GoToEntryAtOffset(routing_id_, offset));
1972 int RenderViewImpl::historyBackListCount() {
1973 return history_list_offset_ < 0 ? 0 : history_list_offset_;
1976 int RenderViewImpl::historyForwardListCount() {
1977 return history_list_length_ - historyBackListCount() - 1;
1980 // blink::WebWidgetClient ----------------------------------------------------
1982 void RenderViewImpl::didFocus() {
1983 // TODO(jcivelli): when https://bugs.webkit.org/show_bug.cgi?id=33389 is fixed
1984 // we won't have to test for user gesture anymore and we can
1985 // move that code back to render_widget.cc
1986 if (WebUserGestureIndicator::isProcessingUserGesture() &&
1987 !RenderThreadImpl::current()->layout_test_mode()) {
1988 Send(new ViewHostMsg_Focus(routing_id_));
1992 void RenderViewImpl::didBlur() {
1993 // TODO(jcivelli): see TODO above in didFocus().
1994 if (WebUserGestureIndicator::isProcessingUserGesture() &&
1995 !RenderThreadImpl::current()->layout_test_mode()) {
1996 Send(new ViewHostMsg_Blur(routing_id_));
2000 // We are supposed to get a single call to Show for a newly created RenderView
2001 // that was created via RenderViewImpl::CreateWebView. So, we wait until this
2002 // point to dispatch the ShowView message.
2004 // This method provides us with the information about how to display the newly
2005 // created RenderView (i.e., as a blocked popup or as a new tab).
2007 void RenderViewImpl::show(WebNavigationPolicy policy) {
2008 if (did_show_) {
2009 // When supports_multiple_windows is disabled, popups are reusing
2010 // the same view. In some scenarios, this makes WebKit to call show() twice.
2011 if (webkit_preferences_.supports_multiple_windows)
2012 NOTREACHED() << "received extraneous Show call";
2013 return;
2015 did_show_ = true;
2017 DCHECK(opener_id_ != MSG_ROUTING_NONE);
2019 // NOTE: initial_rect_ may still have its default values at this point, but
2020 // that's okay. It'll be ignored if disposition is not NEW_POPUP, or the
2021 // browser process will impose a default position otherwise.
2022 Send(new ViewHostMsg_ShowView(opener_id_, routing_id_,
2023 NavigationPolicyToDisposition(policy), initial_rect_,
2024 opened_by_user_gesture_));
2025 SetPendingWindowRect(initial_rect_);
2028 bool RenderViewImpl::requestPointerLock() {
2029 return mouse_lock_dispatcher_->LockMouse(webwidget_mouse_lock_target_.get());
2032 void RenderViewImpl::requestPointerUnlock() {
2033 mouse_lock_dispatcher_->UnlockMouse(webwidget_mouse_lock_target_.get());
2036 bool RenderViewImpl::isPointerLocked() {
2037 return mouse_lock_dispatcher_->IsMouseLockedTo(
2038 webwidget_mouse_lock_target_.get());
2041 void RenderViewImpl::didHandleGestureEvent(
2042 const WebGestureEvent& event,
2043 bool event_cancelled) {
2044 RenderWidget::didHandleGestureEvent(event, event_cancelled);
2046 if (!event_cancelled) {
2047 FOR_EACH_OBSERVER(
2048 RenderViewObserver, observers_, DidHandleGestureEvent(event));
2051 // TODO(ananta): Piggyback off existing IPCs to communicate this information,
2052 // crbug/420130.
2053 #if defined(OS_WIN)
2054 if (event.type != blink::WebGestureEvent::GestureTap)
2055 return;
2057 // TODO(estade): hit test the event against focused node to make sure
2058 // the tap actually hit the focused node.
2059 blink::WebTextInputType text_input_type =
2060 GetWebView()->textInputInfo().type;
2062 Send(new ViewHostMsg_FocusedNodeTouched(
2063 routing_id(), text_input_type != blink::WebTextInputTypeNone));
2064 #endif
2067 void RenderViewImpl::initializeLayerTreeView() {
2068 RenderWidget::initializeLayerTreeView();
2069 RenderWidgetCompositor* rwc = compositor();
2070 if (!rwc)
2071 return;
2072 if (webview() && webview()->devToolsAgent())
2073 webview()->devToolsAgent()->setLayerTreeId(rwc->GetLayerTreeId());
2075 bool use_threaded_event_handling = true;
2076 #if defined(OS_MACOSX) && !defined(OS_IOS)
2077 // Disable threaded event handling if content is not handling the elastic
2078 // overscroll effect. This includes the cases where the elastic overscroll
2079 // effect is being handled by Blink (because of command line flags) and older
2080 // operating system versions which do not have an elastic overscroll effect
2081 // (SnowLeopard, which has Aqua scrollbars which need synchronous updates).
2082 use_threaded_event_handling = compositor_deps_->IsElasticOverscrollEnabled();
2083 #endif
2084 if (use_threaded_event_handling) {
2085 RenderThreadImpl* render_thread = RenderThreadImpl::current();
2086 // render_thread may be NULL in tests.
2087 InputHandlerManager* input_handler_manager =
2088 render_thread ? render_thread->input_handler_manager() : NULL;
2089 if (input_handler_manager) {
2090 input_handler_manager->AddInputHandler(
2091 routing_id_, rwc->GetInputHandler(), AsWeakPtr());
2096 // blink::WebFrameClient -----------------------------------------------------
2098 void RenderViewImpl::Repaint(const gfx::Size& size) {
2099 OnRepaint(size);
2102 void RenderViewImpl::SetEditCommandForNextKeyEvent(const std::string& name,
2103 const std::string& value) {
2104 EditCommands edit_commands;
2105 edit_commands.push_back(EditCommand(name, value));
2106 OnSetEditCommandsForNextKeyEvent(edit_commands);
2109 void RenderViewImpl::ClearEditCommands() {
2110 edit_commands_.clear();
2113 SSLStatus RenderViewImpl::GetSSLStatusOfFrame(blink::WebFrame* frame) const {
2114 std::string security_info;
2115 if (frame && frame->dataSource())
2116 security_info = frame->dataSource()->response().securityInfo();
2118 SSLStatus ssl_status;
2119 DeserializeSecurityInfo(security_info,
2120 &ssl_status.cert_id,
2121 &ssl_status.cert_status,
2122 &ssl_status.security_bits,
2123 &ssl_status.connection_status,
2124 &ssl_status.signed_certificate_timestamp_ids);
2125 return ssl_status;
2128 const std::string& RenderViewImpl::GetAcceptLanguages() const {
2129 return renderer_preferences_.accept_languages;
2132 void RenderViewImpl::didCreateDataSource(WebLocalFrame* frame,
2133 WebDataSource* ds) {
2134 bool content_initiated = !pending_navigation_params_.get();
2136 // Make sure any previous redirect URLs end up in our new data source.
2137 if (pending_navigation_params_.get()) {
2138 for (std::vector<GURL>::const_iterator i =
2139 pending_navigation_params_->redirects.begin();
2140 i != pending_navigation_params_->redirects.end(); ++i) {
2141 ds->appendRedirect(*i);
2145 DocumentState* document_state = DocumentState::FromDataSource(ds);
2146 if (!document_state) {
2147 document_state = new DocumentState;
2148 ds->setExtraData(document_state);
2149 if (!content_initiated)
2150 PopulateDocumentStateFromPending(document_state);
2153 // Carry over the user agent override flag, if it exists.
2154 if (content_initiated && webview() && webview()->mainFrame() &&
2155 webview()->mainFrame()->isWebLocalFrame() &&
2156 webview()->mainFrame()->dataSource()) {
2157 DocumentState* old_document_state =
2158 DocumentState::FromDataSource(webview()->mainFrame()->dataSource());
2159 if (old_document_state) {
2160 InternalDocumentStateData* internal_data =
2161 InternalDocumentStateData::FromDocumentState(document_state);
2162 InternalDocumentStateData* old_internal_data =
2163 InternalDocumentStateData::FromDocumentState(old_document_state);
2164 internal_data->set_is_overriding_user_agent(
2165 old_internal_data->is_overriding_user_agent());
2169 // The rest of RenderView assumes that a WebDataSource will always have a
2170 // non-null NavigationState.
2171 if (content_initiated) {
2172 document_state->set_navigation_state(
2173 NavigationState::CreateContentInitiated());
2174 } else {
2175 document_state->set_navigation_state(CreateNavigationStateFromPending());
2176 pending_navigation_params_.reset();
2179 // DocumentState::referred_by_prefetcher_ is true if we are
2180 // navigating from a page that used prefetching using a link on that
2181 // page. We are early enough in the request process here that we
2182 // can still see the DocumentState of the previous page and set
2183 // this value appropriately.
2184 // TODO(gavinp): catch the important case of navigation in a new
2185 // renderer process.
2186 if (webview()) {
2187 if (WebFrame* old_frame = webview()->mainFrame()) {
2188 const WebURLRequest& original_request = ds->originalRequest();
2189 const GURL referrer(
2190 original_request.httpHeaderField(WebString::fromUTF8("Referer")));
2191 if (!referrer.is_empty() && old_frame->isWebLocalFrame() &&
2192 DocumentState::FromDataSource(old_frame->dataSource())
2193 ->was_prefetcher()) {
2194 for (; old_frame; old_frame = old_frame->traverseNext(false)) {
2195 WebDataSource* old_frame_ds = old_frame->dataSource();
2196 if (old_frame_ds && referrer == GURL(old_frame_ds->request().url())) {
2197 document_state->set_was_referred_by_prefetcher(true);
2198 break;
2205 if (content_initiated) {
2206 const WebURLRequest& request = ds->request();
2207 switch (request.cachePolicy()) {
2208 case WebURLRequest::UseProtocolCachePolicy: // normal load.
2209 document_state->set_load_type(DocumentState::LINK_LOAD_NORMAL);
2210 break;
2211 case WebURLRequest::ReloadIgnoringCacheData: // reload.
2212 case WebURLRequest::ReloadBypassingCache: // end-to-end reload.
2213 document_state->set_load_type(DocumentState::LINK_LOAD_RELOAD);
2214 break;
2215 case WebURLRequest::ReturnCacheDataElseLoad: // allow stale data.
2216 document_state->set_load_type(
2217 DocumentState::LINK_LOAD_CACHE_STALE_OK);
2218 break;
2219 case WebURLRequest::ReturnCacheDataDontLoad: // Don't re-post.
2220 document_state->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY);
2221 break;
2222 default:
2223 NOTREACHED();
2227 FOR_EACH_OBSERVER(
2228 RenderViewObserver, observers_, DidCreateDataSource(frame, ds));
2231 void RenderViewImpl::PopulateDocumentStateFromPending(
2232 DocumentState* document_state) {
2233 const FrameMsg_Navigate_Params& params = *pending_navigation_params_.get();
2234 document_state->set_request_time(params.request_time);
2236 InternalDocumentStateData* internal_data =
2237 InternalDocumentStateData::FromDocumentState(document_state);
2239 if (!params.common_params.url.SchemeIs(url::kJavaScriptScheme) &&
2240 params.common_params.navigation_type == FrameMsg_Navigate_Type::RESTORE) {
2241 // We're doing a load of a page that was restored from the last session. By
2242 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
2243 // can result in stale data for pages that are set to expire. We explicitly
2244 // override that by setting the policy here so that as necessary we load
2245 // from the network.
2247 // TODO(davidben): Remove this in favor of passing a cache policy to the
2248 // loadHistoryItem call in OnNavigate. That requires not overloading
2249 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
2250 // policy based on load type, etc".
2251 internal_data->set_cache_policy_override(
2252 WebURLRequest::UseProtocolCachePolicy);
2255 if (IsReload(params.common_params.navigation_type))
2256 document_state->set_load_type(DocumentState::RELOAD);
2257 else if (params.commit_params.page_state.IsValid())
2258 document_state->set_load_type(DocumentState::HISTORY_LOAD);
2259 else
2260 document_state->set_load_type(DocumentState::NORMAL_LOAD);
2262 internal_data->set_is_overriding_user_agent(
2263 params.commit_params.is_overriding_user_agent);
2264 internal_data->set_must_reset_scroll_and_scale_state(
2265 params.common_params.navigation_type ==
2266 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
2267 document_state->set_can_load_local_resources(params.can_load_local_resources);
2270 NavigationState* RenderViewImpl::CreateNavigationStateFromPending() {
2271 const FrameMsg_Navigate_Params& params = *pending_navigation_params_.get();
2272 NavigationState* navigation_state = NULL;
2274 // A navigation resulting from loading a javascript URL should not be treated
2275 // as a browser initiated event. Instead, we want it to look as if the page
2276 // initiated any load resulting from JS execution.
2277 if (!params.common_params.url.SchemeIs(url::kJavaScriptScheme)) {
2278 navigation_state = NavigationState::CreateBrowserInitiated(
2279 params.page_id,
2280 params.pending_history_list_offset,
2281 params.should_clear_history_list,
2282 params.common_params.transition);
2283 navigation_state->set_should_replace_current_entry(
2284 params.should_replace_current_entry);
2285 navigation_state->set_transferred_request_child_id(
2286 params.transferred_request_child_id);
2287 navigation_state->set_transferred_request_request_id(
2288 params.transferred_request_request_id);
2289 navigation_state->set_allow_download(params.common_params.allow_download);
2290 navigation_state->set_extra_headers(params.extra_headers);
2291 } else {
2292 navigation_state = NavigationState::CreateContentInitiated();
2294 return navigation_state;
2297 void RenderViewImpl::didClearWindowObject(WebLocalFrame* frame) {
2298 FOR_EACH_OBSERVER(
2299 RenderViewObserver, observers_, DidClearWindowObject(frame));
2301 if (enabled_bindings_& BINDINGS_POLICY_WEB_UI)
2302 WebUIExtension::Install(frame);
2304 if (enabled_bindings_ & BINDINGS_POLICY_STATS_COLLECTION)
2305 StatsCollectionController::Install(frame);
2307 const base::CommandLine& command_line =
2308 *base::CommandLine::ForCurrentProcess();
2310 if (command_line.HasSwitch(switches::kEnableSkiaBenchmarking))
2311 SkiaBenchmarking::Install(frame);
2313 if (command_line.HasSwitch(cc::switches::kEnableGpuBenchmarking))
2314 GpuBenchmarking::Install(frame);
2316 if (command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
2317 MemoryBenchmarkingExtension::Install(frame);
2320 void RenderViewImpl::didChangeIcon(WebLocalFrame* frame,
2321 WebIconURL::Type icon_type) {
2322 if (frame->parent())
2323 return;
2325 if (!TouchEnabled() && icon_type != WebIconURL::TypeFavicon)
2326 return;
2328 WebVector<WebIconURL> icon_urls = frame->iconURLs(icon_type);
2329 std::vector<FaviconURL> urls;
2330 for (size_t i = 0; i < icon_urls.size(); i++) {
2331 std::vector<gfx::Size> sizes;
2332 ConvertToFaviconSizes(icon_urls[i].sizes(), &sizes);
2333 urls.push_back(FaviconURL(
2334 icon_urls[i].iconURL(), ToFaviconType(icon_urls[i].iconType()), sizes));
2336 SendUpdateFaviconURL(urls);
2339 void RenderViewImpl::didUpdateCurrentHistoryItem(WebLocalFrame* frame) {
2340 StartNavStateSyncTimerIfNecessary();
2343 void RenderViewImpl::CheckPreferredSize() {
2344 // We don't always want to send the change messages over IPC, only if we've
2345 // been put in that mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
2346 // message.
2347 if (!send_preferred_size_changes_ || !webview())
2348 return;
2350 gfx::Size size = webview()->contentsPreferredMinimumSize();
2351 if (size == preferred_size_)
2352 return;
2354 preferred_size_ = size;
2355 Send(new ViewHostMsg_DidContentsPreferredSizeChange(routing_id_,
2356 preferred_size_));
2359 void RenderViewImpl::didChangeScrollOffset(WebLocalFrame* frame) {
2360 StartNavStateSyncTimerIfNecessary();
2363 void RenderViewImpl::SendFindReply(int request_id,
2364 int match_count,
2365 int ordinal,
2366 const WebRect& selection_rect,
2367 bool final_status_update) {
2368 Send(new ViewHostMsg_Find_Reply(routing_id_,
2369 request_id,
2370 match_count,
2371 selection_rect,
2372 ordinal,
2373 final_status_update));
2376 blink::WebString RenderViewImpl::acceptLanguages() {
2377 return WebString::fromUTF8(renderer_preferences_.accept_languages);
2380 // blink::WebPageSerializerClient implementation ------------------------------
2382 void RenderViewImpl::didSerializeDataForFrame(
2383 const WebURL& frame_url,
2384 const WebCString& data,
2385 WebPageSerializerClient::PageSerializationStatus status) {
2386 Send(new ViewHostMsg_SendSerializedHtmlData(
2387 routing_id(),
2388 frame_url,
2389 data.data(),
2390 static_cast<int32>(status)));
2393 // RenderView implementation ---------------------------------------------------
2395 bool RenderViewImpl::Send(IPC::Message* message) {
2396 return RenderWidget::Send(message);
2399 RenderFrameImpl* RenderViewImpl::GetMainRenderFrame() {
2400 return main_render_frame_.get();
2403 int RenderViewImpl::GetRoutingID() const {
2404 return routing_id_;
2407 gfx::Size RenderViewImpl::GetSize() const {
2408 return size();
2411 WebPreferences& RenderViewImpl::GetWebkitPreferences() {
2412 return webkit_preferences_;
2415 void RenderViewImpl::SetWebkitPreferences(const WebPreferences& preferences) {
2416 OnUpdateWebPreferences(preferences);
2419 blink::WebView* RenderViewImpl::GetWebView() {
2420 return webview();
2423 bool RenderViewImpl::IsEditableNode(const WebNode& node) const {
2424 if (node.isNull())
2425 return false;
2427 if (node.isContentEditable())
2428 return true;
2430 if (node.isElementNode()) {
2431 const WebElement& element = node.toConst<WebElement>();
2432 if (element.isTextFormControlElement()) {
2433 if (!(element.hasAttribute("readonly") ||
2434 element.hasAttribute("disabled")))
2435 return true;
2438 // Also return true if it has an ARIA role of 'textbox'.
2439 for (unsigned i = 0; i < element.attributeCount(); ++i) {
2440 if (LowerCaseEqualsASCII(element.attributeLocalName(i), "role")) {
2441 if (LowerCaseEqualsASCII(element.attributeValue(i), "textbox"))
2442 return true;
2443 break;
2448 return false;
2451 bool RenderViewImpl::ShouldDisplayScrollbars(int width, int height) const {
2452 return (!send_preferred_size_changes_ ||
2453 (disable_scrollbars_size_limit_.width() <= width ||
2454 disable_scrollbars_size_limit_.height() <= height));
2457 int RenderViewImpl::GetEnabledBindings() const {
2458 return enabled_bindings_;
2461 bool RenderViewImpl::GetContentStateImmediately() const {
2462 return send_content_state_immediately_;
2465 blink::WebPageVisibilityState RenderViewImpl::GetVisibilityState() const {
2466 return visibilityState();
2469 void RenderViewImpl::DidStartLoading() {
2470 main_render_frame_->didStartLoading(true);
2473 void RenderViewImpl::DidStopLoading() {
2474 main_render_frame_->didStopLoading();
2477 void RenderViewImpl::SyncNavigationState() {
2478 if (!webview())
2479 return;
2480 SendUpdateState(history_controller_->GetCurrentEntry());
2483 blink::WebElement RenderViewImpl::GetFocusedElement() const {
2484 if (!webview())
2485 return WebElement();
2486 WebFrame* focused_frame = webview()->focusedFrame();
2487 if (focused_frame) {
2488 WebDocument doc = focused_frame->document();
2489 if (!doc.isNull())
2490 return doc.focusedElement();
2493 return WebElement();
2496 blink::WebPlugin* RenderViewImpl::GetWebPluginForFind() {
2497 if (!webview())
2498 return NULL;
2500 WebFrame* main_frame = webview()->mainFrame();
2501 if (main_frame->isWebLocalFrame() &&
2502 main_frame->document().isPluginDocument())
2503 return webview()->mainFrame()->document().to<WebPluginDocument>().plugin();
2505 #if defined(ENABLE_PLUGINS)
2506 if (plugin_find_handler_)
2507 return plugin_find_handler_->container()->plugin();
2508 #endif
2510 return NULL;
2513 void RenderViewImpl::OnFind(int request_id,
2514 const base::string16& search_text,
2515 const WebFindOptions& options) {
2516 WebFrame* main_frame = webview()->mainFrame();
2517 blink::WebPlugin* plugin = GetWebPluginForFind();
2518 // Check if the plugin still exists in the document.
2519 if (plugin) {
2520 if (options.findNext) {
2521 // Just navigate back/forward.
2522 plugin->selectFindResult(options.forward);
2523 } else {
2524 if (!plugin->startFind(
2525 search_text, options.matchCase, request_id)) {
2526 // Send "no results".
2527 SendFindReply(request_id, 0, 0, gfx::Rect(), true);
2530 return;
2533 WebFrame* frame_after_main = main_frame->traverseNext(true);
2534 WebFrame* focused_frame = webview()->focusedFrame();
2535 WebFrame* search_frame = focused_frame; // start searching focused frame.
2537 bool multi_frame = (frame_after_main != main_frame);
2539 // If we have multiple frames, we don't want to wrap the search within the
2540 // frame, so we check here if we only have main_frame in the chain.
2541 bool wrap_within_frame = !multi_frame;
2543 WebRect selection_rect;
2544 bool result = false;
2546 // If something is selected when we start searching it means we cannot just
2547 // increment the current match ordinal; we need to re-generate it.
2548 WebRange current_selection = focused_frame->selectionRange();
2550 do {
2551 result = search_frame->find(
2552 request_id, search_text, options, wrap_within_frame, &selection_rect);
2554 if (!result) {
2555 // don't leave text selected as you move to the next frame.
2556 search_frame->executeCommand(WebString::fromUTF8("Unselect"),
2557 GetFocusedElement());
2559 // Find the next frame, but skip the invisible ones.
2560 do {
2561 // What is the next frame to search? (we might be going backwards). Note
2562 // that we specify wrap=true so that search_frame never becomes NULL.
2563 search_frame = options.forward ?
2564 search_frame->traverseNext(true) :
2565 search_frame->traversePrevious(true);
2566 } while (!search_frame->hasVisibleContent() &&
2567 search_frame != focused_frame);
2569 // Make sure selection doesn't affect the search operation in new frame.
2570 search_frame->executeCommand(WebString::fromUTF8("Unselect"),
2571 GetFocusedElement());
2573 // If we have multiple frames and we have wrapped back around to the
2574 // focused frame, we need to search it once more allowing wrap within
2575 // the frame, otherwise it will report 'no match' if the focused frame has
2576 // reported matches, but no frames after the focused_frame contain a
2577 // match for the search word(s).
2578 if (multi_frame && search_frame == focused_frame) {
2579 result = search_frame->find(
2580 request_id, search_text, options, true, // Force wrapping.
2581 &selection_rect);
2585 webview()->setFocusedFrame(search_frame);
2586 } while (!result && search_frame != focused_frame);
2588 if (options.findNext && current_selection.isNull()) {
2589 // Force the main_frame to report the actual count.
2590 main_frame->increaseMatchCount(0, request_id);
2591 } else {
2592 // If nothing is found, set result to "0 of 0", otherwise, set it to
2593 // "-1 of 1" to indicate that we found at least one item, but we don't know
2594 // yet what is active.
2595 int ordinal = result ? -1 : 0; // -1 here means, we might know more later.
2596 int match_count = result ? 1 : 0; // 1 here means possibly more coming.
2598 // If we find no matches then this will be our last status update.
2599 // Otherwise the scoping effort will send more results.
2600 bool final_status_update = !result;
2602 SendFindReply(request_id, match_count, ordinal, selection_rect,
2603 final_status_update);
2605 // Scoping effort begins, starting with the mainframe.
2606 search_frame = main_frame;
2608 main_frame->resetMatchCount();
2610 do {
2611 // Cancel all old scoping requests before starting a new one.
2612 search_frame->cancelPendingScopingEffort();
2614 // We don't start another scoping effort unless at least one match has
2615 // been found.
2616 if (result) {
2617 // Start new scoping request. If the scoping function determines that it
2618 // needs to scope, it will defer until later.
2619 search_frame->scopeStringMatches(request_id,
2620 search_text,
2621 options,
2622 true); // reset the tickmarks
2625 // Iterate to the next frame. The frame will not necessarily scope, for
2626 // example if it is not visible.
2627 search_frame = search_frame->traverseNext(true);
2628 } while (search_frame != main_frame);
2632 void RenderViewImpl::OnStopFinding(StopFindAction action) {
2633 WebView* view = webview();
2634 if (!view)
2635 return;
2637 blink::WebPlugin* plugin = GetWebPluginForFind();
2638 if (plugin) {
2639 plugin->stopFind();
2640 return;
2643 bool clear_selection = action == STOP_FIND_ACTION_CLEAR_SELECTION;
2644 if (clear_selection) {
2645 view->focusedFrame()->executeCommand(WebString::fromUTF8("Unselect"),
2646 GetFocusedElement());
2649 WebFrame* frame = view->mainFrame();
2650 while (frame) {
2651 frame->stopFinding(clear_selection);
2652 frame = frame->traverseNext(false);
2655 if (action == STOP_FIND_ACTION_ACTIVATE_SELECTION) {
2656 WebFrame* focused_frame = view->focusedFrame();
2657 if (focused_frame) {
2658 WebDocument doc = focused_frame->document();
2659 if (!doc.isNull()) {
2660 WebElement element = doc.focusedElement();
2661 if (!element.isNull())
2662 element.simulateClick();
2668 #if defined(OS_ANDROID)
2669 void RenderViewImpl::OnActivateNearestFindResult(int request_id,
2670 float x, float y) {
2671 if (!webview())
2672 return;
2674 WebFrame* main_frame = webview()->mainFrame();
2675 WebRect selection_rect;
2676 int ordinal = main_frame->selectNearestFindMatch(WebFloatPoint(x, y),
2677 &selection_rect);
2678 if (ordinal == -1) {
2679 // Something went wrong, so send a no-op reply (force the main_frame to
2680 // report the current match count) in case the host is waiting for a
2681 // response due to rate-limiting).
2682 main_frame->increaseMatchCount(0, request_id);
2683 return;
2686 SendFindReply(request_id,
2687 -1 /* number_of_matches */,
2688 ordinal,
2689 selection_rect,
2690 true /* final_update */);
2693 void RenderViewImpl::OnFindMatchRects(int current_version) {
2694 if (!webview())
2695 return;
2697 WebFrame* main_frame = webview()->mainFrame();
2698 std::vector<gfx::RectF> match_rects;
2700 int rects_version = main_frame->findMatchMarkersVersion();
2701 if (current_version != rects_version) {
2702 WebVector<WebFloatRect> web_match_rects;
2703 main_frame->findMatchRects(web_match_rects);
2704 match_rects.reserve(web_match_rects.size());
2705 for (size_t i = 0; i < web_match_rects.size(); ++i)
2706 match_rects.push_back(gfx::RectF(web_match_rects[i]));
2709 gfx::RectF active_rect = main_frame->activeFindMatchRect();
2710 Send(new ViewHostMsg_FindMatchRects_Reply(routing_id_,
2711 rects_version,
2712 match_rects,
2713 active_rect));
2715 #endif
2717 void RenderViewImpl::OnZoom(PageZoom zoom) {
2718 if (!webview()) // Not sure if this can happen, but no harm in being safe.
2719 return;
2721 webview()->hidePopups();
2723 double old_zoom_level = webview()->zoomLevel();
2724 double zoom_level;
2725 if (zoom == PAGE_ZOOM_RESET) {
2726 zoom_level = 0;
2727 } else if (static_cast<int>(old_zoom_level) == old_zoom_level) {
2728 // Previous zoom level is a whole number, so just increment/decrement.
2729 zoom_level = old_zoom_level + zoom;
2730 } else {
2731 // Either the user hit the zoom factor limit and thus the zoom level is now
2732 // not a whole number, or a plugin changed it to a custom value. We want
2733 // to go to the next whole number so that the user can always get back to
2734 // 100% with the keyboard/menu.
2735 if ((old_zoom_level > 1 && zoom > 0) ||
2736 (old_zoom_level < 1 && zoom < 0)) {
2737 zoom_level = static_cast<int>(old_zoom_level + zoom);
2738 } else {
2739 // We're going towards 100%, so first go to the next whole number.
2740 zoom_level = static_cast<int>(old_zoom_level);
2743 webview()->setZoomLevel(zoom_level);
2744 zoomLevelChanged();
2747 void RenderViewImpl::OnSetZoomLevelForLoadingURL(const GURL& url,
2748 double zoom_level) {
2749 #if !defined(OS_ANDROID)
2750 // On Android, page zoom isn't used, and in case of WebView, text zoom is used
2751 // for legacy WebView text scaling emulation. Thus, the code that resets
2752 // the zoom level from this map will be effectively resetting text zoom level.
2753 host_zoom_levels_[url] = zoom_level;
2754 #endif
2757 void RenderViewImpl::OnSetZoomLevelForView(bool uses_temporary_zoom_level,
2758 double level) {
2759 uses_temporary_zoom_level_ = uses_temporary_zoom_level;
2761 webview()->hidePopups();
2762 webview()->setZoomLevel(level);
2765 void RenderViewImpl::OnSetPageEncoding(const std::string& encoding_name) {
2766 webview()->setPageEncoding(WebString::fromUTF8(encoding_name));
2769 void RenderViewImpl::OnResetPageEncodingToDefault() {
2770 WebString no_encoding;
2771 webview()->setPageEncoding(no_encoding);
2774 void RenderViewImpl::OnPostMessageEvent(
2775 const ViewMsg_PostMessage_Params& params) {
2776 // TODO(nasko): Support sending to subframes.
2777 WebFrame* frame = webview()->mainFrame();
2779 // Find the source frame if it exists.
2780 WebFrame* source_frame = NULL;
2781 if (params.source_routing_id != MSG_ROUTING_NONE) {
2782 RenderViewImpl* source_view = FromRoutingID(params.source_routing_id);
2783 if (source_view)
2784 source_frame = source_view->webview()->mainFrame();
2787 // If the message contained MessagePorts, create the corresponding endpoints.
2788 blink::WebMessagePortChannelArray channels =
2789 WebMessagePortChannelImpl::CreatePorts(
2790 params.message_ports, params.new_routing_ids,
2791 base::MessageLoopProxy::current().get());
2793 WebSerializedScriptValue serialized_script_value;
2794 if (params.is_data_raw_string) {
2795 v8::HandleScope handle_scope(blink::mainThreadIsolate());
2796 v8::Local<v8::Context> context = frame->mainWorldScriptContext();
2797 v8::Context::Scope context_scope(context);
2798 V8ValueConverterImpl converter;
2799 converter.SetDateAllowed(true);
2800 converter.SetRegExpAllowed(true);
2801 scoped_ptr<base::Value> value(new base::StringValue(params.data));
2802 v8::Handle<v8::Value> result_value = converter.ToV8Value(value.get(),
2803 context);
2804 serialized_script_value = WebSerializedScriptValue::serialize(result_value);
2805 } else {
2806 serialized_script_value = WebSerializedScriptValue::fromString(params.data);
2809 // Create an event with the message. The final parameter to initMessageEvent
2810 // is the last event ID, which is not used with postMessage.
2811 WebDOMEvent event = frame->document().createEvent("MessageEvent");
2812 WebDOMMessageEvent msg_event = event.to<WebDOMMessageEvent>();
2813 msg_event.initMessageEvent("message",
2814 // |canBubble| and |cancellable| are always false
2815 false, false,
2816 serialized_script_value,
2817 params.source_origin, source_frame, "", channels);
2819 // We must pass in the target_origin to do the security check on this side,
2820 // since it may have changed since the original postMessage call was made.
2821 WebSecurityOrigin target_origin;
2822 if (!params.target_origin.empty()) {
2823 target_origin =
2824 WebSecurityOrigin::createFromString(WebString(params.target_origin));
2826 frame->dispatchMessageEventWithOriginCheck(target_origin, msg_event);
2829 void RenderViewImpl::OnAllowBindings(int enabled_bindings_flags) {
2830 if ((enabled_bindings_flags & BINDINGS_POLICY_WEB_UI) &&
2831 !(enabled_bindings_ & BINDINGS_POLICY_WEB_UI)) {
2832 // WebUIExtensionData deletes itself when we're destroyed.
2833 new WebUIExtensionData(this);
2834 // WebUIMojo deletes itself when we're destroyed.
2835 new WebUIMojo(this);
2838 enabled_bindings_ |= enabled_bindings_flags;
2840 // Keep track of the total bindings accumulated in this process.
2841 RenderProcess::current()->AddBindings(enabled_bindings_flags);
2844 void RenderViewImpl::OnDragTargetDragEnter(const DropData& drop_data,
2845 const gfx::Point& client_point,
2846 const gfx::Point& screen_point,
2847 WebDragOperationsMask ops,
2848 int key_modifiers) {
2849 WebDragOperation operation = webview()->dragTargetDragEnter(
2850 DropDataToWebDragData(drop_data),
2851 client_point,
2852 screen_point,
2853 ops,
2854 key_modifiers);
2856 Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
2859 void RenderViewImpl::OnDragTargetDragOver(const gfx::Point& client_point,
2860 const gfx::Point& screen_point,
2861 WebDragOperationsMask ops,
2862 int key_modifiers) {
2863 WebDragOperation operation = webview()->dragTargetDragOver(
2864 client_point,
2865 screen_point,
2866 ops,
2867 key_modifiers);
2869 Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
2872 void RenderViewImpl::OnDragTargetDragLeave() {
2873 webview()->dragTargetDragLeave();
2876 void RenderViewImpl::OnDragTargetDrop(const gfx::Point& client_point,
2877 const gfx::Point& screen_point,
2878 int key_modifiers) {
2879 webview()->dragTargetDrop(client_point, screen_point, key_modifiers);
2881 Send(new DragHostMsg_TargetDrop_ACK(routing_id_));
2884 void RenderViewImpl::OnDragSourceEnded(const gfx::Point& client_point,
2885 const gfx::Point& screen_point,
2886 WebDragOperation op) {
2887 webview()->dragSourceEndedAt(client_point, screen_point, op);
2890 void RenderViewImpl::OnDragSourceSystemDragEnded() {
2891 webview()->dragSourceSystemDragEnded();
2894 void RenderViewImpl::OnUpdateWebPreferences(const WebPreferences& prefs) {
2895 webkit_preferences_ = prefs;
2896 ApplyWebPreferences(webkit_preferences_, webview());
2899 void RenderViewImpl::OnEnumerateDirectoryResponse(
2900 int id,
2901 const std::vector<base::FilePath>& paths) {
2902 if (!enumeration_completions_[id])
2903 return;
2905 WebVector<WebString> ws_file_names(paths.size());
2906 for (size_t i = 0; i < paths.size(); ++i)
2907 ws_file_names[i] = paths[i].AsUTF16Unsafe();
2909 enumeration_completions_[id]->didChooseFile(ws_file_names);
2910 enumeration_completions_.erase(id);
2913 void RenderViewImpl::OnFileChooserResponse(
2914 const std::vector<content::FileChooserFileInfo>& files) {
2915 // This could happen if we navigated to a different page before the user
2916 // closed the chooser.
2917 if (file_chooser_completions_.empty())
2918 return;
2920 // Convert Chrome's SelectedFileInfo list to WebKit's.
2921 WebVector<WebFileChooserCompletion::SelectedFileInfo> selected_files(
2922 files.size());
2923 for (size_t i = 0; i < files.size(); ++i) {
2924 WebFileChooserCompletion::SelectedFileInfo selected_file;
2925 selected_file.path = files[i].file_path.AsUTF16Unsafe();
2926 selected_file.displayName =
2927 base::FilePath(files[i].display_name).AsUTF16Unsafe();
2928 if (files[i].file_system_url.is_valid()) {
2929 selected_file.fileSystemURL = files[i].file_system_url;
2930 selected_file.length = files[i].length;
2931 selected_file.modificationTime = files[i].modification_time.ToDoubleT();
2932 selected_file.isDirectory = files[i].is_directory;
2934 selected_files[i] = selected_file;
2937 if (file_chooser_completions_.front()->completion)
2938 file_chooser_completions_.front()->completion->didChooseFile(
2939 selected_files);
2940 file_chooser_completions_.pop_front();
2942 // If there are more pending file chooser requests, schedule one now.
2943 if (!file_chooser_completions_.empty()) {
2944 Send(new ViewHostMsg_RunFileChooser(routing_id_,
2945 file_chooser_completions_.front()->params));
2949 void RenderViewImpl::OnEnableAutoResize(const gfx::Size& min_size,
2950 const gfx::Size& max_size) {
2951 DCHECK(disable_scrollbars_size_limit_.IsEmpty());
2952 if (!webview())
2953 return;
2954 auto_resize_mode_ = true;
2955 webview()->enableAutoResizeMode(min_size, max_size);
2958 void RenderViewImpl::OnDisableAutoResize(const gfx::Size& new_size) {
2959 DCHECK(disable_scrollbars_size_limit_.IsEmpty());
2960 if (!webview())
2961 return;
2962 auto_resize_mode_ = false;
2963 webview()->disableAutoResizeMode();
2965 if (!new_size.IsEmpty()) {
2966 Resize(new_size,
2967 physical_backing_size_,
2968 top_controls_shrink_blink_size_,
2969 top_controls_height_,
2970 visible_viewport_size_,
2971 resizer_rect_,
2972 is_fullscreen_,
2973 NO_RESIZE_ACK);
2977 void RenderViewImpl::OnEnablePreferredSizeChangedMode() {
2978 if (send_preferred_size_changes_)
2979 return;
2980 send_preferred_size_changes_ = true;
2982 // Start off with an initial preferred size notification (in case
2983 // |didUpdateLayout| was already called).
2984 didUpdateLayout();
2987 void RenderViewImpl::OnDisableScrollbarsForSmallWindows(
2988 const gfx::Size& disable_scrollbar_size_limit) {
2989 disable_scrollbars_size_limit_ = disable_scrollbar_size_limit;
2992 void RenderViewImpl::OnSetRendererPrefs(
2993 const RendererPreferences& renderer_prefs) {
2994 double old_zoom_level = renderer_preferences_.default_zoom_level;
2995 std::string old_accept_languages = renderer_preferences_.accept_languages;
2997 renderer_preferences_ = renderer_prefs;
2998 UpdateFontRenderingFromRendererPrefs();
3000 #if defined(USE_DEFAULT_RENDER_THEME)
3001 if (renderer_prefs.use_custom_colors) {
3002 WebColorName name = blink::WebColorWebkitFocusRingColor;
3003 blink::setNamedColors(&name, &renderer_prefs.focus_ring_color, 1);
3004 blink::setCaretBlinkInterval(renderer_prefs.caret_blink_interval);
3006 if (webview()) {
3007 webview()->setSelectionColors(
3008 renderer_prefs.active_selection_bg_color,
3009 renderer_prefs.active_selection_fg_color,
3010 renderer_prefs.inactive_selection_bg_color,
3011 renderer_prefs.inactive_selection_fg_color);
3012 webview()->themeChanged();
3015 #endif // defined(USE_DEFAULT_RENDER_THEME)
3017 // If the zoom level for this page matches the old zoom default, and this
3018 // is not a plugin, update the zoom level to match the new default.
3019 if (webview() && webview()->mainFrame()->isWebLocalFrame() &&
3020 !webview()->mainFrame()->document().isPluginDocument() &&
3021 !ZoomValuesEqual(old_zoom_level,
3022 renderer_preferences_.default_zoom_level) &&
3023 ZoomValuesEqual(webview()->zoomLevel(), old_zoom_level)) {
3024 webview()->setZoomLevel(renderer_preferences_.default_zoom_level);
3025 zoomLevelChanged();
3028 if (webview() &&
3029 old_accept_languages != renderer_preferences_.accept_languages) {
3030 webview()->acceptLanguagesChanged();
3034 void RenderViewImpl::OnMediaPlayerActionAt(const gfx::Point& location,
3035 const WebMediaPlayerAction& action) {
3036 if (webview())
3037 webview()->performMediaPlayerAction(action, location);
3040 void RenderViewImpl::OnOrientationChange() {
3041 webview()->mainFrame()->toWebLocalFrame()->sendOrientationChangeEvent();
3044 void RenderViewImpl::OnPluginActionAt(const gfx::Point& location,
3045 const WebPluginAction& action) {
3046 if (webview())
3047 webview()->performPluginAction(action, location);
3050 void RenderViewImpl::OnGetAllSavableResourceLinksForCurrentPage(
3051 const GURL& page_url) {
3052 // Prepare list to storage all savable resource links.
3053 std::vector<GURL> resources_list;
3054 std::vector<GURL> referrer_urls_list;
3055 std::vector<blink::WebReferrerPolicy> referrer_policies_list;
3056 std::vector<GURL> frames_list;
3057 SavableResourcesResult result(&resources_list,
3058 &referrer_urls_list,
3059 &referrer_policies_list,
3060 &frames_list);
3062 // webkit/ doesn't know about Referrer.
3063 if (!GetAllSavableResourceLinksForCurrentPage(
3064 webview(),
3065 page_url,
3066 &result,
3067 const_cast<const char**>(GetSavableSchemes()))) {
3068 // If something is wrong when collecting all savable resource links,
3069 // send empty list to embedder(browser) to tell it failed.
3070 referrer_urls_list.clear();
3071 referrer_policies_list.clear();
3072 resources_list.clear();
3073 frames_list.clear();
3076 std::vector<Referrer> referrers_list;
3077 CHECK_EQ(referrer_urls_list.size(), referrer_policies_list.size());
3078 for (unsigned i = 0; i < referrer_urls_list.size(); ++i) {
3079 referrers_list.push_back(
3080 Referrer(referrer_urls_list[i], referrer_policies_list[i]));
3083 // Send result of all savable resource links to embedder.
3084 Send(new ViewHostMsg_SendCurrentPageAllSavableResourceLinks(routing_id(),
3085 resources_list,
3086 referrers_list,
3087 frames_list));
3090 void RenderViewImpl::OnGetSerializedHtmlDataForCurrentPageWithLocalLinks(
3091 const std::vector<GURL>& links,
3092 const std::vector<base::FilePath>& local_paths,
3093 const base::FilePath& local_directory_name) {
3095 // Convert std::vector of GURLs to WebVector<WebURL>
3096 WebVector<WebURL> weburl_links(links);
3098 // Convert std::vector of base::FilePath to WebVector<WebString>
3099 WebVector<WebString> webstring_paths(local_paths.size());
3100 for (size_t i = 0; i < local_paths.size(); i++)
3101 webstring_paths[i] = local_paths[i].AsUTF16Unsafe();
3103 WebPageSerializer::serialize(webview()->mainFrame()->toWebLocalFrame(),
3104 true,
3105 this,
3106 weburl_links,
3107 webstring_paths,
3108 local_directory_name.AsUTF16Unsafe());
3111 void RenderViewImpl::OnSuppressDialogsUntilSwapOut() {
3112 // Don't show any more dialogs until we finish OnSwapOut.
3113 suppress_dialogs_until_swap_out_ = true;
3116 void RenderViewImpl::OnClosePage() {
3117 FOR_EACH_OBSERVER(RenderViewObserver, observers_, ClosePage());
3118 // TODO(creis): We'd rather use webview()->Close() here, but that currently
3119 // sets the WebView's delegate_ to NULL, preventing any JavaScript dialogs
3120 // in the onunload handler from appearing. For now, we're bypassing that and
3121 // calling the FrameLoader's CloseURL method directly. This should be
3122 // revisited to avoid having two ways to close a page. Having a single way
3123 // to close that can run onunload is also useful for fixing
3124 // http://b/issue?id=753080.
3125 webview()->mainFrame()->dispatchUnloadEvent();
3127 Send(new ViewHostMsg_ClosePage_ACK(routing_id_));
3130 void RenderViewImpl::OnThemeChanged() {
3131 #if defined(USE_AURA)
3132 // Aura doesn't care if we switch themes.
3133 #elif defined(OS_WIN)
3134 ui::NativeThemeWin::instance()->CloseHandles();
3135 if (webview())
3136 webview()->themeChanged();
3137 #else // defined(OS_WIN)
3138 // TODO(port): we don't support theming on non-Windows platforms yet
3139 NOTIMPLEMENTED();
3140 #endif
3143 void RenderViewImpl::OnMoveOrResizeStarted() {
3144 if (webview())
3145 webview()->hidePopups();
3148 void RenderViewImpl::OnResize(const ViewMsg_Resize_Params& params) {
3149 TRACE_EVENT0("renderer", "RenderViewImpl::OnResize");
3150 if (webview()) {
3151 webview()->hidePopups();
3152 if (send_preferred_size_changes_) {
3153 webview()->mainFrame()->setCanHaveScrollbars(
3154 ShouldDisplayScrollbars(params.new_size.width(),
3155 params.new_size.height()));
3159 gfx::Size old_visible_viewport_size = visible_viewport_size_;
3161 RenderWidget::OnResize(params);
3163 if (old_visible_viewport_size != visible_viewport_size_)
3164 has_scrolled_focused_editable_node_into_rect_ = false;
3167 void RenderViewImpl::DidInitiatePaint() {
3168 #if defined(ENABLE_PLUGINS)
3169 // Notify all instances that we painted. The same caveats apply as for
3170 // ViewFlushedPaint regarding instances closing themselves, so we take
3171 // similar precautions.
3172 PepperPluginSet plugins = active_pepper_instances_;
3173 for (PepperPluginSet::iterator i = plugins.begin(); i != plugins.end(); ++i) {
3174 if (active_pepper_instances_.find(*i) != active_pepper_instances_.end())
3175 (*i)->ViewInitiatedPaint();
3177 #endif
3180 void RenderViewImpl::DidFlushPaint() {
3181 // If the RenderWidget is closing down then early-exit, otherwise we'll crash.
3182 // See crbug.com/112921.
3183 if (!webview())
3184 return;
3186 WebFrame* main_frame = webview()->mainFrame();
3187 for (WebFrame* frame = main_frame; frame;
3188 frame = frame->traverseNext(false)) {
3189 // TODO(nasko): This is a hack for the case in which the top-level
3190 // frame is being rendered in another process. It will not
3191 // behave correctly for out of process iframes.
3192 if (frame->isWebLocalFrame()) {
3193 main_frame = frame;
3194 break;
3198 // If we have a provisional frame we are between the start and commit stages
3199 // of loading and we don't want to save stats.
3200 if (!main_frame->provisionalDataSource()) {
3201 WebDataSource* ds = main_frame->dataSource();
3202 DocumentState* document_state = DocumentState::FromDataSource(ds);
3204 // TODO(jar): The following code should all be inside a method, probably in
3205 // NavigatorState.
3206 Time now = Time::Now();
3207 if (document_state->first_paint_time().is_null()) {
3208 document_state->set_first_paint_time(now);
3210 if (document_state->first_paint_after_load_time().is_null() &&
3211 !document_state->finish_load_time().is_null()) {
3212 document_state->set_first_paint_after_load_time(now);
3217 gfx::Vector2d RenderViewImpl::GetScrollOffset() {
3218 WebFrame* main_frame = webview()->mainFrame();
3219 for (WebFrame* frame = main_frame; frame;
3220 frame = frame->traverseNext(false)) {
3221 // TODO(nasko): This is a hack for the case in which the top-level
3222 // frame is being rendered in another process. It will not
3223 // behave correctly for out of process iframes.
3224 if (frame->isWebLocalFrame()) {
3225 main_frame = frame;
3226 break;
3230 WebSize scroll_offset = main_frame->scrollOffset();
3231 return gfx::Vector2d(scroll_offset.width, scroll_offset.height);
3234 void RenderViewImpl::OnClearFocusedElement() {
3235 if (webview())
3236 webview()->clearFocusedElement();
3239 void RenderViewImpl::OnSetBackgroundOpaque(bool opaque) {
3240 if (webview())
3241 webview()->setIsTransparent(!opaque);
3242 if (compositor_)
3243 compositor_->setHasTransparentBackground(!opaque);
3246 void RenderViewImpl::OnSetActive(bool active) {
3247 if (webview())
3248 webview()->setIsActive(active);
3250 #if defined(ENABLE_PLUGINS) && defined(OS_MACOSX)
3251 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3252 for (plugin_it = plugin_delegates_.begin();
3253 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3254 (*plugin_it)->SetWindowFocus(active);
3256 #endif
3259 #if defined(OS_MACOSX)
3260 void RenderViewImpl::OnSetWindowVisibility(bool visible) {
3261 #if defined(ENABLE_PLUGINS)
3262 // Inform plugins that their container has changed visibility.
3263 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3264 for (plugin_it = plugin_delegates_.begin();
3265 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3266 (*plugin_it)->SetContainerVisibility(visible);
3268 #endif
3271 void RenderViewImpl::OnWindowFrameChanged(const gfx::Rect& window_frame,
3272 const gfx::Rect& view_frame) {
3273 #if defined(ENABLE_PLUGINS)
3274 // Inform plugins that their window's frame has changed.
3275 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3276 for (plugin_it = plugin_delegates_.begin();
3277 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3278 (*plugin_it)->WindowFrameChanged(window_frame, view_frame);
3280 #endif
3283 void RenderViewImpl::OnPluginImeCompositionCompleted(const base::string16& text,
3284 int plugin_id) {
3285 // WebPluginDelegateProxy is responsible for figuring out if this event
3286 // applies to it or not, so inform all the delegates.
3287 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3288 for (plugin_it = plugin_delegates_.begin();
3289 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3290 (*plugin_it)->ImeCompositionCompleted(text, plugin_id);
3293 #endif // OS_MACOSX
3295 void RenderViewImpl::OnClose() {
3296 if (closing_)
3297 RenderThread::Get()->Send(new ViewHostMsg_Close_ACK(routing_id_));
3298 RenderWidget::OnClose();
3301 void RenderViewImpl::Close() {
3302 // We need to grab a pointer to the doomed WebView before we destroy it.
3303 WebView* doomed = webview();
3304 RenderWidget::Close();
3305 g_view_map.Get().erase(doomed);
3306 g_routing_id_view_map.Get().erase(routing_id_);
3307 RenderThread::Get()->Send(new ViewHostMsg_Close_ACK(routing_id_));
3310 void RenderViewImpl::DidHandleKeyEvent() {
3311 ClearEditCommands();
3314 bool RenderViewImpl::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
3315 possible_drag_event_info_.event_source =
3316 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE;
3317 possible_drag_event_info_.event_location =
3318 gfx::Point(event.globalX, event.globalY);
3320 #if defined(ENABLE_PLUGINS)
3321 // This method is called for every mouse event that the render view receives.
3322 // And then the mouse event is forwarded to WebKit, which dispatches it to the
3323 // event target. Potentially a Pepper plugin will receive the event.
3324 // In order to tell whether a plugin gets the last mouse event and which it
3325 // is, we set |pepper_last_mouse_event_target_| to NULL here. If a plugin gets
3326 // the event, it will notify us via DidReceiveMouseEvent() and set itself as
3327 // |pepper_last_mouse_event_target_|.
3328 pepper_last_mouse_event_target_ = NULL;
3329 #endif
3331 // If the mouse is locked, only the current owner of the mouse lock can
3332 // process mouse events.
3333 return mouse_lock_dispatcher_->WillHandleMouseEvent(event);
3336 bool RenderViewImpl::WillHandleGestureEvent(
3337 const blink::WebGestureEvent& event) {
3338 possible_drag_event_info_.event_source =
3339 ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH;
3340 possible_drag_event_info_.event_location =
3341 gfx::Point(event.globalX, event.globalY);
3342 return false;
3345 void RenderViewImpl::DidHandleMouseEvent(const WebMouseEvent& event) {
3346 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidHandleMouseEvent(event));
3349 void RenderViewImpl::DidHandleTouchEvent(const WebTouchEvent& event) {
3350 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidHandleTouchEvent(event));
3353 bool RenderViewImpl::HasTouchEventHandlersAt(const gfx::Point& point) const {
3354 if (!webview())
3355 return false;
3356 return webview()->hasTouchEventHandlersAt(point);
3359 void RenderViewImpl::OnWasHidden() {
3360 RenderWidget::OnWasHidden();
3362 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3363 RenderThreadImpl::current()->video_capture_impl_manager()->
3364 SuspendDevices(true);
3365 if (speech_recognition_dispatcher_)
3366 speech_recognition_dispatcher_->AbortAllRecognitions();
3367 #endif
3369 if (webview())
3370 webview()->setVisibilityState(visibilityState(), false);
3372 #if defined(ENABLE_PLUGINS)
3373 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3374 i != active_pepper_instances_.end(); ++i)
3375 (*i)->PageVisibilityChanged(false);
3377 #if defined(OS_MACOSX)
3378 // Inform NPAPI plugins that their container is no longer visible.
3379 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3380 for (plugin_it = plugin_delegates_.begin();
3381 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3382 (*plugin_it)->SetContainerVisibility(false);
3384 #endif // OS_MACOSX
3385 #endif // ENABLE_PLUGINS
3388 void RenderViewImpl::OnWasShown(bool needs_repainting,
3389 const ui::LatencyInfo& latency_info) {
3390 RenderWidget::OnWasShown(needs_repainting, latency_info);
3392 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3393 RenderThreadImpl::current()->video_capture_impl_manager()->
3394 SuspendDevices(false);
3395 #endif
3397 if (webview())
3398 webview()->setVisibilityState(visibilityState(), false);
3400 #if defined(ENABLE_PLUGINS)
3401 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3402 i != active_pepper_instances_.end(); ++i)
3403 (*i)->PageVisibilityChanged(true);
3405 #if defined(OS_MACOSX)
3406 // Inform NPAPI plugins that their container is now visible.
3407 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3408 for (plugin_it = plugin_delegates_.begin();
3409 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3410 (*plugin_it)->SetContainerVisibility(true);
3412 #endif // OS_MACOSX
3413 #endif // ENABLE_PLUGINS
3416 GURL RenderViewImpl::GetURLForGraphicsContext3D() {
3417 DCHECK(webview());
3418 if (webview()->mainFrame()->isWebLocalFrame())
3419 return GURL(webview()->mainFrame()->document().url());
3420 else
3421 return GURL("chrome://gpu/RenderViewImpl::CreateGraphicsContext3D");
3424 void RenderViewImpl::OnSetFocus(bool enable) {
3425 RenderWidget::OnSetFocus(enable);
3427 #if defined(ENABLE_PLUGINS)
3428 if (webview() && webview()->isActive()) {
3429 // Notify all NPAPI plugins.
3430 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3431 for (plugin_it = plugin_delegates_.begin();
3432 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3433 #if defined(OS_MACOSX)
3434 // RenderWidget's call to setFocus can cause the underlying webview's
3435 // activation state to change just like a call to setIsActive.
3436 if (enable)
3437 (*plugin_it)->SetWindowFocus(true);
3438 #endif
3439 (*plugin_it)->SetContentAreaFocus(enable);
3442 // Notify all Pepper plugins.
3443 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3444 i != active_pepper_instances_.end(); ++i)
3445 (*i)->SetContentAreaFocus(enable);
3446 #endif
3447 // Notify all BrowserPlugins of the RenderView's focus state.
3448 if (BrowserPluginManager::Get())
3449 BrowserPluginManager::Get()->UpdateFocusState();
3452 void RenderViewImpl::OnImeSetComposition(
3453 const base::string16& text,
3454 const std::vector<blink::WebCompositionUnderline>& underlines,
3455 int selection_start,
3456 int selection_end) {
3457 #if defined(ENABLE_PLUGINS)
3458 if (focused_pepper_plugin_) {
3459 focused_pepper_plugin_->render_frame()->OnImeSetComposition(
3460 text, underlines, selection_start, selection_end);
3461 return;
3464 #if defined(OS_WIN)
3465 // When a plug-in has focus, we create platform-specific IME data used by
3466 // our IME emulator and send it directly to the focused plug-in, i.e. we
3467 // bypass WebKit. (WebPluginDelegate dispatches this IME data only when its
3468 // instance ID is the same one as the specified ID.)
3469 if (focused_plugin_id_ >= 0) {
3470 std::vector<int> clauses;
3471 std::vector<int> target;
3472 for (size_t i = 0; i < underlines.size(); ++i) {
3473 clauses.push_back(underlines[i].startOffset);
3474 clauses.push_back(underlines[i].endOffset);
3475 if (underlines[i].thick) {
3476 target.clear();
3477 target.push_back(underlines[i].startOffset);
3478 target.push_back(underlines[i].endOffset);
3481 std::set<WebPluginDelegateProxy*>::iterator it;
3482 for (it = plugin_delegates_.begin(); it != plugin_delegates_.end(); ++it) {
3483 (*it)->ImeCompositionUpdated(text, clauses, target, selection_end,
3484 focused_plugin_id_);
3486 return;
3488 #endif // OS_WIN
3489 #endif // ENABLE_PLUGINS
3490 RenderWidget::OnImeSetComposition(text,
3491 underlines,
3492 selection_start,
3493 selection_end);
3496 void RenderViewImpl::OnImeConfirmComposition(
3497 const base::string16& text,
3498 const gfx::Range& replacement_range,
3499 bool keep_selection) {
3500 #if defined(ENABLE_PLUGINS)
3501 if (focused_pepper_plugin_) {
3502 focused_pepper_plugin_->render_frame()->OnImeConfirmComposition(
3503 text, replacement_range, keep_selection);
3504 return;
3506 #if defined(OS_WIN)
3507 // Same as OnImeSetComposition(), we send the text from IMEs directly to
3508 // plug-ins. When we send IME text directly to plug-ins, we should not send
3509 // it to WebKit to prevent WebKit from controlling IMEs.
3510 // TODO(thakis): Honor |replacement_range| for plugins?
3511 if (focused_plugin_id_ >= 0) {
3512 std::set<WebPluginDelegateProxy*>::iterator it;
3513 for (it = plugin_delegates_.begin();
3514 it != plugin_delegates_.end(); ++it) {
3515 (*it)->ImeCompositionCompleted(text, focused_plugin_id_);
3517 return;
3519 #endif // OS_WIN
3520 #endif // ENABLE_PLUGINS
3521 if (replacement_range.IsValid() && webview()) {
3522 // Select the text in |replacement_range|, it will then be replaced by
3523 // text added by the call to RenderWidget::OnImeConfirmComposition().
3524 if (WebLocalFrame* frame = webview()->focusedFrame()->toWebLocalFrame()) {
3525 WebRange webrange = WebRange::fromDocumentRange(
3526 frame, replacement_range.start(), replacement_range.length());
3527 if (!webrange.isNull())
3528 frame->selectRange(webrange);
3531 RenderWidget::OnImeConfirmComposition(text,
3532 replacement_range,
3533 keep_selection);
3536 void RenderViewImpl::SetDeviceScaleFactor(float device_scale_factor) {
3537 RenderWidget::SetDeviceScaleFactor(device_scale_factor);
3538 if (webview()) {
3539 webview()->setDeviceScaleFactor(device_scale_factor);
3540 webview()->settings()->setPreferCompositingToLCDTextEnabled(
3541 PreferCompositingToLCDText(compositor_deps_, device_scale_factor_));
3543 if (auto_resize_mode_)
3544 AutoResizeCompositor();
3547 bool RenderViewImpl::SetDeviceColorProfile(
3548 const std::vector<char>& profile) {
3549 bool changed = RenderWidget::SetDeviceColorProfile(profile);
3550 if (changed && webview()) {
3551 WebVector<char> colorProfile = profile;
3552 webview()->setDeviceColorProfile(colorProfile);
3554 return changed;
3557 void RenderViewImpl::ResetDeviceColorProfileForTesting() {
3558 RenderWidget::ResetDeviceColorProfileForTesting();
3559 if (webview())
3560 webview()->resetDeviceColorProfile();
3563 ui::TextInputType RenderViewImpl::GetTextInputType() {
3564 #if defined(ENABLE_PLUGINS)
3565 if (focused_pepper_plugin_)
3566 return focused_pepper_plugin_->text_input_type();
3567 #endif
3568 return RenderWidget::GetTextInputType();
3571 void RenderViewImpl::GetSelectionBounds(gfx::Rect* start, gfx::Rect* end) {
3572 #if defined(ENABLE_PLUGINS)
3573 if (focused_pepper_plugin_) {
3574 // TODO(kinaba) http://crbug.com/101101
3575 // Current Pepper IME API does not handle selection bounds. So we simply
3576 // use the caret position as an empty range for now. It will be updated
3577 // after Pepper API equips features related to surrounding text retrieval.
3578 gfx::Rect caret = focused_pepper_plugin_->GetCaretBounds();
3579 *start = caret;
3580 *end = caret;
3581 return;
3583 #endif
3584 RenderWidget::GetSelectionBounds(start, end);
3587 void RenderViewImpl::FocusChangeComplete() {
3588 RenderWidget::FocusChangeComplete();
3589 FOR_EACH_OBSERVER(RenderViewObserver, observers_, FocusChangeComplete());
3592 void RenderViewImpl::GetCompositionCharacterBounds(
3593 std::vector<gfx::Rect>* bounds) {
3594 DCHECK(bounds);
3595 bounds->clear();
3597 #if defined(ENABLE_PLUGINS)
3598 if (focused_pepper_plugin_) {
3599 return;
3601 #endif
3603 if (!webview())
3604 return;
3605 size_t start_offset = 0;
3606 size_t character_count = 0;
3607 if (!webview()->compositionRange(&start_offset, &character_count))
3608 return;
3609 if (character_count == 0)
3610 return;
3612 blink::WebFrame* frame = webview()->focusedFrame();
3613 if (!frame)
3614 return;
3616 bounds->reserve(character_count);
3617 blink::WebRect webrect;
3618 for (size_t i = 0; i < character_count; ++i) {
3619 if (!frame->firstRectForCharacterRange(start_offset + i, 1, webrect)) {
3620 DLOG(ERROR) << "Could not retrieve character rectangle at " << i;
3621 bounds->clear();
3622 return;
3624 bounds->push_back(webrect);
3628 void RenderViewImpl::GetCompositionRange(gfx::Range* range) {
3629 #if defined(ENABLE_PLUGINS)
3630 if (focused_pepper_plugin_) {
3631 return;
3633 #endif
3634 RenderWidget::GetCompositionRange(range);
3637 bool RenderViewImpl::CanComposeInline() {
3638 #if defined(ENABLE_PLUGINS)
3639 if (focused_pepper_plugin_)
3640 return focused_pepper_plugin_->IsPluginAcceptingCompositionEvents();
3641 #endif
3642 return true;
3645 void RenderViewImpl::DidCompletePageScaleAnimation() {
3646 FocusChangeComplete();
3649 void RenderViewImpl::SetScreenMetricsEmulationParameters(
3650 float device_scale_factor,
3651 const gfx::Point& root_layer_offset,
3652 float root_layer_scale) {
3653 if (webview() && compositor()) {
3654 webview()->setCompositorDeviceScaleFactorOverride(device_scale_factor);
3655 webview()->setRootLayerTransform(
3656 blink::WebSize(root_layer_offset.x(), root_layer_offset.y()),
3657 root_layer_scale);
3661 bool RenderViewImpl::ScheduleFileChooser(
3662 const FileChooserParams& params,
3663 WebFileChooserCompletion* completion) {
3664 static const size_t kMaximumPendingFileChooseRequests = 4;
3665 if (file_chooser_completions_.size() > kMaximumPendingFileChooseRequests) {
3666 // This sanity check prevents too many file choose requests from getting
3667 // queued which could DoS the user. Getting these is most likely a
3668 // programming error (there are many ways to DoS the user so it's not
3669 // considered a "real" security check), either in JS requesting many file
3670 // choosers to pop up, or in a plugin.
3672 // TODO(brettw) we might possibly want to require a user gesture to open
3673 // a file picker, which will address this issue in a better way.
3674 return false;
3677 file_chooser_completions_.push_back(linked_ptr<PendingFileChooser>(
3678 new PendingFileChooser(params, completion)));
3679 if (file_chooser_completions_.size() == 1) {
3680 // Actually show the browse dialog when this is the first request.
3681 Send(new ViewHostMsg_RunFileChooser(routing_id_, params));
3683 return true;
3686 blink::WebSpeechRecognizer* RenderViewImpl::speechRecognizer() {
3687 if (!speech_recognition_dispatcher_)
3688 speech_recognition_dispatcher_ = new SpeechRecognitionDispatcher(this);
3689 return speech_recognition_dispatcher_;
3692 void RenderViewImpl::zoomLimitsChanged(double minimum_level,
3693 double maximum_level) {
3694 // Round the double to avoid returning incorrect minimum/maximum zoom
3695 // percentages.
3696 int minimum_percent = round(
3697 ZoomLevelToZoomFactor(minimum_level) * 100);
3698 int maximum_percent = round(
3699 ZoomLevelToZoomFactor(maximum_level) * 100);
3701 Send(new ViewHostMsg_UpdateZoomLimits(
3702 routing_id_, minimum_percent, maximum_percent));
3705 void RenderViewImpl::zoomLevelChanged() {
3706 double zoom_level = webview()->zoomLevel();
3708 // Do not send empty URLs to the browser when we are just setting the default
3709 // zoom level (from RendererPreferences) before the first navigation.
3710 if (!webview()->mainFrame()->document().url().isEmpty()) {
3711 // Tell the browser which url got zoomed so it can update the menu and the
3712 // saved values if necessary
3713 Send(new ViewHostMsg_DidZoomURL(
3714 routing_id_, zoom_level,
3715 GURL(webview()->mainFrame()->document().url())));
3719 double RenderViewImpl::zoomLevelToZoomFactor(double zoom_level) const {
3720 return ZoomLevelToZoomFactor(zoom_level);
3723 double RenderViewImpl::zoomFactorToZoomLevel(double factor) const {
3724 return ZoomFactorToZoomLevel(factor);
3727 void RenderViewImpl::registerProtocolHandler(const WebString& scheme,
3728 const WebURL& url,
3729 const WebString& title) {
3730 bool user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
3731 Send(new ViewHostMsg_RegisterProtocolHandler(routing_id_,
3732 base::UTF16ToUTF8(scheme),
3733 url,
3734 title,
3735 user_gesture));
3738 void RenderViewImpl::unregisterProtocolHandler(const WebString& scheme,
3739 const WebURL& url) {
3740 bool user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
3741 Send(new ViewHostMsg_UnregisterProtocolHandler(routing_id_,
3742 base::UTF16ToUTF8(scheme),
3743 url,
3744 user_gesture));
3747 blink::WebPageVisibilityState RenderViewImpl::visibilityState() const {
3748 blink::WebPageVisibilityState current_state = is_hidden() ?
3749 blink::WebPageVisibilityStateHidden :
3750 blink::WebPageVisibilityStateVisible;
3751 blink::WebPageVisibilityState override_state = current_state;
3752 // TODO(jam): move this method to WebFrameClient.
3753 if (GetContentClient()->renderer()->
3754 ShouldOverridePageVisibilityState(main_render_frame_.get(),
3755 &override_state))
3756 return override_state;
3757 return current_state;
3760 void RenderViewImpl::draggableRegionsChanged() {
3761 FOR_EACH_OBSERVER(
3762 RenderViewObserver,
3763 observers_,
3764 DraggableRegionsChanged(webview()->mainFrame()));
3767 #if defined(OS_ANDROID)
3768 WebContentDetectionResult RenderViewImpl::detectContentAround(
3769 const WebHitTestResult& touch_hit) {
3770 DCHECK(touch_hit.node().isTextNode());
3772 // Process the position with all the registered content detectors until
3773 // a match is found. Priority is provided by their relative order.
3774 for (ContentDetectorList::const_iterator it = content_detectors_.begin();
3775 it != content_detectors_.end(); ++it) {
3776 ContentDetector::Result content = (*it)->FindTappedContent(touch_hit);
3777 if (content.valid) {
3778 return WebContentDetectionResult(content.content_boundaries,
3779 base::UTF8ToUTF16(content.text), content.intent_url);
3782 return WebContentDetectionResult();
3785 void RenderViewImpl::scheduleContentIntent(const WebURL& intent) {
3786 // Introduce a short delay so that the user can notice the content.
3787 base::MessageLoop::current()->PostDelayedTask(
3788 FROM_HERE,
3789 base::Bind(&RenderViewImpl::LaunchAndroidContentIntent,
3790 AsWeakPtr(),
3791 intent,
3792 expected_content_intent_id_),
3793 base::TimeDelta::FromMilliseconds(kContentIntentDelayMilliseconds));
3796 void RenderViewImpl::cancelScheduledContentIntents() {
3797 ++expected_content_intent_id_;
3800 void RenderViewImpl::LaunchAndroidContentIntent(const GURL& intent,
3801 size_t request_id) {
3802 if (request_id != expected_content_intent_id_)
3803 return;
3805 // Remove the content highlighting if any.
3806 scheduleComposite();
3808 if (!intent.is_empty())
3809 Send(new ViewHostMsg_StartContentIntent(routing_id_, intent));
3812 bool RenderViewImpl::openDateTimeChooser(
3813 const blink::WebDateTimeChooserParams& params,
3814 blink::WebDateTimeChooserCompletion* completion) {
3815 // JavaScript may try to open a date time chooser while one is already open.
3816 if (date_time_picker_client_)
3817 return false;
3818 date_time_picker_client_.reset(
3819 new RendererDateTimePicker(this, params, completion));
3820 return date_time_picker_client_->Open();
3823 void RenderViewImpl::DismissDateTimeDialog() {
3824 DCHECK(date_time_picker_client_);
3825 date_time_picker_client_.reset(NULL);
3828 #endif // defined(OS_ANDROID)
3830 void RenderViewImpl::OnShowContextMenu(
3831 ui::MenuSourceType source_type, const gfx::Point& location) {
3832 context_menu_source_type_ = source_type;
3833 has_host_context_menu_location_ = true;
3834 host_context_menu_location_ = location;
3835 if (webview())
3836 webview()->showContextMenu();
3837 has_host_context_menu_location_ = false;
3840 void RenderViewImpl::OnEnableViewSourceMode() {
3841 if (!webview())
3842 return;
3843 WebFrame* main_frame = webview()->mainFrame();
3844 if (!main_frame)
3845 return;
3846 main_frame->enableViewSourceMode(true);
3849 #if defined(OS_ANDROID) || defined(TOOLKIT_VIEWS)
3850 bool RenderViewImpl::didTapMultipleTargets(
3851 const WebSize& inner_viewport_offset,
3852 const WebRect& touch_rect,
3853 const WebVector<WebRect>& target_rects) {
3854 if (!switches::IsLinkDisambiguationPopupEnabled())
3855 return false;
3857 // Never show a disambiguation popup when accessibility is enabled,
3858 // as this interferes with "touch exploration".
3859 AccessibilityMode accessibility_mode =
3860 GetMainRenderFrame()->accessibility_mode();
3861 bool matches_accessibility_mode_complete =
3862 (accessibility_mode & AccessibilityModeComplete) ==
3863 AccessibilityModeComplete;
3864 if (matches_accessibility_mode_complete)
3865 return false;
3867 // The touch_rect, target_rects and zoom_rect are in the outer viewport
3868 // reference frame.
3869 gfx::Rect zoom_rect;
3870 float new_total_scale =
3871 DisambiguationPopupHelper::ComputeZoomAreaAndScaleFactor(
3872 touch_rect, target_rects, GetSize(),
3873 gfx::Rect(webview()->mainFrame()->visibleContentRect()).size(),
3874 device_scale_factor_ * webview()->pageScaleFactor(), &zoom_rect);
3875 if (!new_total_scale || zoom_rect.IsEmpty())
3876 return false;
3878 bool handled = false;
3879 switch (renderer_preferences_.tap_multiple_targets_strategy) {
3880 case TAP_MULTIPLE_TARGETS_STRATEGY_ZOOM:
3881 handled = webview()->zoomToMultipleTargetsRect(zoom_rect);
3882 break;
3883 case TAP_MULTIPLE_TARGETS_STRATEGY_POPUP: {
3884 gfx::Size canvas_size =
3885 gfx::ToCeiledSize(gfx::ScaleSize(zoom_rect.size(), new_total_scale));
3886 cc::SharedBitmapManager* manager =
3887 RenderThreadImpl::current()->shared_bitmap_manager();
3888 scoped_ptr<cc::SharedBitmap> shared_bitmap =
3889 manager->AllocateSharedBitmap(canvas_size);
3890 CHECK(!!shared_bitmap);
3892 SkBitmap bitmap;
3893 SkImageInfo info = SkImageInfo::MakeN32Premul(canvas_size.width(),
3894 canvas_size.height());
3895 bitmap.installPixels(info, shared_bitmap->pixels(), info.minRowBytes());
3896 SkCanvas canvas(bitmap);
3898 // TODO(trchen): Cleanup the device scale factor mess.
3899 // device scale will be applied in WebKit
3900 // --> zoom_rect doesn't include device scale,
3901 // but WebKit will still draw on zoom_rect * device_scale_factor_
3902 canvas.scale(new_total_scale / device_scale_factor_,
3903 new_total_scale / device_scale_factor_);
3904 canvas.translate(-zoom_rect.x() * device_scale_factor_,
3905 -zoom_rect.y() * device_scale_factor_);
3907 DCHECK(webwidget_->isAcceleratedCompositingActive());
3908 // TODO(aelias): The disambiguation popup should be composited so we
3909 // don't have to call this method.
3910 webwidget_->paintCompositedDeprecated(&canvas, zoom_rect);
3913 gfx::Rect zoom_rect_in_screen =
3914 zoom_rect - gfx::Vector2d(inner_viewport_offset.width,
3915 inner_viewport_offset.height);
3917 gfx::Rect physical_window_zoom_rect = gfx::ToEnclosingRect(
3918 ClientRectToPhysicalWindowRect(gfx::RectF(zoom_rect_in_screen)));
3920 Send(new ViewHostMsg_ShowDisambiguationPopup(routing_id_,
3921 physical_window_zoom_rect,
3922 canvas_size,
3923 shared_bitmap->id()));
3924 cc::SharedBitmapId id = shared_bitmap->id();
3925 disambiguation_bitmaps_[id] = shared_bitmap.release();
3926 handled = true;
3927 break;
3929 case TAP_MULTIPLE_TARGETS_STRATEGY_NONE:
3930 // No-op.
3931 break;
3934 return handled;
3936 #endif // defined(OS_ANDROID) || defined(TOOLKIT_VIEWS)
3938 unsigned RenderViewImpl::GetLocalSessionHistoryLengthForTesting() const {
3939 return history_list_length_;
3942 void RenderViewImpl::SetFocusAndActivateForTesting(bool enable) {
3943 if (enable) {
3944 if (has_focus())
3945 return;
3946 OnSetActive(true);
3947 OnSetFocus(true);
3948 } else {
3949 if (!has_focus())
3950 return;
3951 OnSetFocus(false);
3952 OnSetActive(false);
3956 void RenderViewImpl::SetDeviceScaleFactorForTesting(float factor) {
3957 ViewMsg_Resize_Params params;
3958 params.screen_info = screen_info_;
3959 params.screen_info.deviceScaleFactor = factor;
3960 params.new_size = size();
3961 params.visible_viewport_size = visible_viewport_size_;
3962 params.physical_backing_size =
3963 gfx::ToCeiledSize(gfx::ScaleSize(size(), factor));
3964 params.top_controls_shrink_blink_size = false;
3965 params.top_controls_height = 0.f;
3966 params.resizer_rect = WebRect();
3967 params.is_fullscreen = is_fullscreen();
3968 OnResize(params);
3971 void RenderViewImpl::SetDeviceColorProfileForTesting(
3972 const std::vector<char>& color_profile) {
3973 SetDeviceColorProfile(color_profile);
3976 void RenderViewImpl::ForceResizeForTesting(const gfx::Size& new_size) {
3977 gfx::Rect new_window_rect(rootWindowRect().x,
3978 rootWindowRect().y,
3979 new_size.width(),
3980 new_size.height());
3981 SetWindowRectSynchronously(new_window_rect);
3984 void RenderViewImpl::UseSynchronousResizeModeForTesting(bool enable) {
3985 resizing_mode_selector_->set_is_synchronous_mode(enable);
3988 void RenderViewImpl::EnableAutoResizeForTesting(const gfx::Size& min_size,
3989 const gfx::Size& max_size) {
3990 OnEnableAutoResize(min_size, max_size);
3993 void RenderViewImpl::DisableAutoResizeForTesting(const gfx::Size& new_size) {
3994 OnDisableAutoResize(new_size);
3997 void RenderViewImpl::OnReleaseDisambiguationPopupBitmap(
3998 const cc::SharedBitmapId& id) {
3999 BitmapMap::iterator it = disambiguation_bitmaps_.find(id);
4000 DCHECK(it != disambiguation_bitmaps_.end());
4001 delete it->second;
4002 disambiguation_bitmaps_.erase(it);
4005 void RenderViewImpl::DidCommitCompositorFrame() {
4006 RenderWidget::DidCommitCompositorFrame();
4007 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidCommitCompositorFrame());
4010 void RenderViewImpl::SendUpdateFaviconURL(const std::vector<FaviconURL>& urls) {
4011 if (!urls.empty())
4012 Send(new ViewHostMsg_UpdateFaviconURL(routing_id_, urls));
4015 void RenderViewImpl::DidStopLoadingIcons() {
4016 int icon_types = WebIconURL::TypeFavicon;
4017 if (TouchEnabled())
4018 icon_types |= WebIconURL::TypeTouchPrecomposed | WebIconURL::TypeTouch;
4020 // Favicons matter only for the top-level frame. If it is a WebRemoteFrame,
4021 // just return early.
4022 if (webview()->mainFrame()->isWebRemoteFrame())
4023 return;
4025 WebVector<WebIconURL> icon_urls =
4026 webview()->mainFrame()->iconURLs(icon_types);
4028 std::vector<FaviconURL> urls;
4029 for (size_t i = 0; i < icon_urls.size(); i++) {
4030 WebURL url = icon_urls[i].iconURL();
4031 std::vector<gfx::Size> sizes;
4032 ConvertToFaviconSizes(icon_urls[i].sizes(), &sizes);
4033 if (!url.isEmpty())
4034 urls.push_back(
4035 FaviconURL(url, ToFaviconType(icon_urls[i].iconType()), sizes));
4037 SendUpdateFaviconURL(urls);
4040 } // namespace content