[Icons NTP] Enable Touch Icon parsing, so Chrome gets URL (no fetch or storage).
[chromium-blink-merge.git] / content / renderer / render_view_impl.cc
blob95c6938d6207025ef71e87ce23b3e02cbc228083
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 "content/child/appcache/appcache_dispatcher.h"
35 #include "content/child/appcache/web_application_cache_host_impl.h"
36 #include "content/child/child_shared_bitmap_manager.h"
37 #include "content/child/npapi/webplugin_delegate_impl.h"
38 #include "content/child/request_extra_data.h"
39 #include "content/child/v8_value_converter_impl.h"
40 #include "content/child/webmessageportchannel_impl.h"
41 #include "content/common/content_constants_internal.h"
42 #include "content/common/database_messages.h"
43 #include "content/common/dom_storage/dom_storage_types.h"
44 #include "content/common/drag_messages.h"
45 #include "content/common/frame_messages.h"
46 #include "content/common/frame_replication_state.h"
47 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
48 #include "content/common/input_messages.h"
49 #include "content/common/pepper_messages.h"
50 #include "content/common/ssl_status_serialization.h"
51 #include "content/common/view_messages.h"
52 #include "content/public/common/bindings_policy.h"
53 #include "content/public/common/content_client.h"
54 #include "content/public/common/content_constants.h"
55 #include "content/public/common/content_switches.h"
56 #include "content/public/common/drop_data.h"
57 #include "content/public/common/favicon_url.h"
58 #include "content/public/common/file_chooser_file_info.h"
59 #include "content/public/common/file_chooser_params.h"
60 #include "content/public/common/page_state.h"
61 #include "content/public/common/page_zoom.h"
62 #include "content/public/common/ssl_status.h"
63 #include "content/public/common/three_d_api_types.h"
64 #include "content/public/common/url_constants.h"
65 #include "content/public/common/url_utils.h"
66 #include "content/public/common/web_preferences.h"
67 #include "content/public/renderer/content_renderer_client.h"
68 #include "content/public/renderer/document_state.h"
69 #include "content/public/renderer/navigation_state.h"
70 #include "content/public/renderer/render_view_observer.h"
71 #include "content/public/renderer/render_view_visitor.h"
72 #include "content/renderer/browser_plugin/browser_plugin.h"
73 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
74 #include "content/renderer/devtools/devtools_agent.h"
75 #include "content/renderer/disambiguation_popup_helper.h"
76 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
77 #include "content/renderer/drop_data_builder.h"
78 #include "content/renderer/gpu/render_widget_compositor.h"
79 #include "content/renderer/history_controller.h"
80 #include "content/renderer/history_serialization.h"
81 #include "content/renderer/idle_user_detector.h"
82 #include "content/renderer/ime_event_guard.h"
83 #include "content/renderer/input/input_handler_manager.h"
84 #include "content/renderer/internal_document_state_data.h"
85 #include "content/renderer/media/audio_device_factory.h"
86 #include "content/renderer/media/video_capture_impl_manager.h"
87 #include "content/renderer/mhtml_generator.h"
88 #include "content/renderer/net_info_helper.h"
89 #include "content/renderer/render_frame_impl.h"
90 #include "content/renderer/render_frame_proxy.h"
91 #include "content/renderer/render_process.h"
92 #include "content/renderer/render_thread_impl.h"
93 #include "content/renderer/render_view_mouse_lock_dispatcher.h"
94 #include "content/renderer/render_widget_fullscreen_pepper.h"
95 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
96 #include "content/renderer/resizing_mode_selector.h"
97 #include "content/renderer/savable_resources.h"
98 #include "content/renderer/speech_recognition_dispatcher.h"
99 #include "content/renderer/text_input_client_observer.h"
100 #include "content/renderer/web_ui_extension_data.h"
101 #include "content/renderer/web_ui_mojo.h"
102 #include "content/renderer/websharedworker_proxy.h"
103 #include "media/audio/audio_output_device.h"
104 #include "media/base/media_switches.h"
105 #include "media/renderers/audio_renderer_impl.h"
106 #include "media/renderers/gpu_video_accelerator_factories.h"
107 #include "net/base/data_url.h"
108 #include "net/base/escape.h"
109 #include "net/base/net_errors.h"
110 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
111 #include "net/http/http_util.h"
112 #include "skia/ext/platform_canvas.h"
113 #include "third_party/WebKit/public/platform/WebCString.h"
114 #include "third_party/WebKit/public/platform/WebConnectionType.h"
115 #include "third_party/WebKit/public/platform/WebDragData.h"
116 #include "third_party/WebKit/public/platform/WebHTTPBody.h"
117 #include "third_party/WebKit/public/platform/WebImage.h"
118 #include "third_party/WebKit/public/platform/WebMessagePortChannel.h"
119 #include "third_party/WebKit/public/platform/WebPoint.h"
120 #include "third_party/WebKit/public/platform/WebRect.h"
121 #include "third_party/WebKit/public/platform/WebSize.h"
122 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
123 #include "third_party/WebKit/public/platform/WebString.h"
124 #include "third_party/WebKit/public/platform/WebURL.h"
125 #include "third_party/WebKit/public/platform/WebURLError.h"
126 #include "third_party/WebKit/public/platform/WebURLRequest.h"
127 #include "third_party/WebKit/public/platform/WebURLResponse.h"
128 #include "third_party/WebKit/public/platform/WebVector.h"
129 #include "third_party/WebKit/public/web/WebAXObject.h"
130 #include "third_party/WebKit/public/web/WebColorName.h"
131 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
132 #include "third_party/WebKit/public/web/WebDOMEvent.h"
133 #include "third_party/WebKit/public/web/WebDOMMessageEvent.h"
134 #include "third_party/WebKit/public/web/WebDataSource.h"
135 #include "third_party/WebKit/public/web/WebDateTimeChooserCompletion.h"
136 #include "third_party/WebKit/public/web/WebDateTimeChooserParams.h"
137 #include "third_party/WebKit/public/web/WebDevToolsAgent.h"
138 #include "third_party/WebKit/public/web/WebDocument.h"
139 #include "third_party/WebKit/public/web/WebElement.h"
140 #include "third_party/WebKit/public/web/WebFileChooserParams.h"
141 #include "third_party/WebKit/public/web/WebFindOptions.h"
142 #include "third_party/WebKit/public/web/WebFormControlElement.h"
143 #include "third_party/WebKit/public/web/WebFormElement.h"
144 #include "third_party/WebKit/public/web/WebFrame.h"
145 #include "third_party/WebKit/public/web/WebGlyphCache.h"
146 #include "third_party/WebKit/public/web/WebHistoryItem.h"
147 #include "third_party/WebKit/public/web/WebHitTestResult.h"
148 #include "third_party/WebKit/public/web/WebInputElement.h"
149 #include "third_party/WebKit/public/web/WebInputEvent.h"
150 #include "third_party/WebKit/public/web/WebKit.h"
151 #include "third_party/WebKit/public/web/WebLocalFrame.h"
152 #include "third_party/WebKit/public/web/WebMediaPlayerAction.h"
153 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
154 #include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
155 #include "third_party/WebKit/public/web/WebNodeList.h"
156 #include "third_party/WebKit/public/web/WebPageSerializer.h"
157 #include "third_party/WebKit/public/web/WebPlugin.h"
158 #include "third_party/WebKit/public/web/WebPluginAction.h"
159 #include "third_party/WebKit/public/web/WebPluginContainer.h"
160 #include "third_party/WebKit/public/web/WebPluginDocument.h"
161 #include "third_party/WebKit/public/web/WebRange.h"
162 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
163 #include "third_party/WebKit/public/web/WebScriptSource.h"
164 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
165 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
166 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
167 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
168 #include "third_party/WebKit/public/web/WebSettings.h"
169 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
170 #include "third_party/WebKit/public/web/WebView.h"
171 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
172 #include "third_party/WebKit/public/web/default/WebRenderTheme.h"
173 #include "third_party/icu/source/common/unicode/uchar.h"
174 #include "third_party/icu/source/common/unicode/uscript.h"
175 #include "ui/base/clipboard/clipboard.h"
176 #include "ui/base/ui_base_switches_util.h"
177 #include "ui/events/latency_info.h"
178 #include "ui/gfx/geometry/point.h"
179 #include "ui/gfx/geometry/rect.h"
180 #include "ui/gfx/geometry/rect_conversions.h"
181 #include "ui/gfx/geometry/size_conversions.h"
182 #include "ui/gfx/native_widget_types.h"
183 #include "v8/include/v8.h"
185 #if defined(OS_ANDROID)
186 #include <cpu-features.h>
188 #include "content/renderer/android/address_detector.h"
189 #include "content/renderer/android/content_detector.h"
190 #include "content/renderer/android/email_detector.h"
191 #include "content/renderer/android/phone_number_detector.h"
192 #include "net/android/network_library.h"
193 #include "third_party/WebKit/public/platform/WebFloatPoint.h"
194 #include "third_party/WebKit/public/platform/WebFloatRect.h"
195 #include "ui/gfx/geometry/rect_f.h"
197 #elif defined(OS_WIN)
198 // TODO(port): these files are currently Windows only because they concern:
199 // * theming
200 #include "ui/native_theme/native_theme_win.h"
201 #elif defined(USE_X11)
202 #include "ui/native_theme/native_theme.h"
203 #elif defined(OS_MACOSX)
204 #include "skia/ext/skia_utils_mac.h"
205 #endif
207 #if defined(ENABLE_PLUGINS)
208 #include "content/renderer/npapi/webplugin_delegate_proxy.h"
209 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
210 #include "content/renderer/pepper/pepper_plugin_registry.h"
211 #endif
213 #if defined(ENABLE_WEBRTC)
214 #include "content/renderer/media/rtc_peer_connection_handler.h"
215 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
216 #endif
218 using blink::WebAXObject;
219 using blink::WebApplicationCacheHost;
220 using blink::WebApplicationCacheHostClient;
221 using blink::WebCString;
222 using blink::WebColor;
223 using blink::WebColorName;
224 using blink::WebConsoleMessage;
225 using blink::WebData;
226 using blink::WebDataSource;
227 using blink::WebDocument;
228 using blink::WebDOMEvent;
229 using blink::WebDOMMessageEvent;
230 using blink::WebDragData;
231 using blink::WebDragOperation;
232 using blink::WebDragOperationsMask;
233 using blink::WebElement;
234 using blink::WebFileChooserCompletion;
235 using blink::WebFindOptions;
236 using blink::WebFormControlElement;
237 using blink::WebFormElement;
238 using blink::WebFrame;
239 using blink::WebGestureEvent;
240 using blink::WebHistoryItem;
241 using blink::WebHTTPBody;
242 using blink::WebIconURL;
243 using blink::WebImage;
244 using blink::WebInputElement;
245 using blink::WebInputEvent;
246 using blink::WebLocalFrame;
247 using blink::WebMediaPlayerAction;
248 using blink::WebMouseEvent;
249 using blink::WebNavigationPolicy;
250 using blink::WebNavigationType;
251 using blink::WebNode;
252 using blink::WebPageSerializer;
253 using blink::WebPageSerializerClient;
254 using blink::WebPeerConnection00Handler;
255 using blink::WebPeerConnection00HandlerClient;
256 using blink::WebPeerConnectionHandler;
257 using blink::WebPeerConnectionHandlerClient;
258 using blink::WebPluginAction;
259 using blink::WebPluginContainer;
260 using blink::WebPluginDocument;
261 using blink::WebPoint;
262 using blink::WebRange;
263 using blink::WebRect;
264 using blink::WebReferrerPolicy;
265 using blink::WebScriptSource;
266 using blink::WebSearchableFormData;
267 using blink::WebSecurityOrigin;
268 using blink::WebSecurityPolicy;
269 using blink::WebSerializedScriptValue;
270 using blink::WebSettings;
271 using blink::WebSize;
272 using blink::WebStorageNamespace;
273 using blink::WebStorageQuotaCallbacks;
274 using blink::WebStorageQuotaError;
275 using blink::WebStorageQuotaType;
276 using blink::WebString;
277 using blink::WebTextAffinity;
278 using blink::WebTextDirection;
279 using blink::WebTouchEvent;
280 using blink::WebURL;
281 using blink::WebURLError;
282 using blink::WebURLRequest;
283 using blink::WebURLResponse;
284 using blink::WebUserGestureIndicator;
285 using blink::WebVector;
286 using blink::WebView;
287 using blink::WebWidget;
288 using blink::WebWindowFeatures;
289 using blink::WebNetworkStateNotifier;
290 using blink::WebRuntimeFeatures;
291 using base::Time;
292 using base::TimeDelta;
294 #if defined(OS_ANDROID)
295 using blink::WebContentDetectionResult;
296 using blink::WebFloatPoint;
297 using blink::WebFloatRect;
298 using blink::WebHitTestResult;
299 #endif
301 namespace content {
303 //-----------------------------------------------------------------------------
305 typedef std::map<blink::WebView*, RenderViewImpl*> ViewMap;
306 static base::LazyInstance<ViewMap> g_view_map = LAZY_INSTANCE_INITIALIZER;
307 typedef std::map<int32, RenderViewImpl*> RoutingIDViewMap;
308 static base::LazyInstance<RoutingIDViewMap> g_routing_id_view_map =
309 LAZY_INSTANCE_INITIALIZER;
311 // Time, in seconds, we delay before sending content state changes (such as form
312 // state and scroll position) to the browser. We delay sending changes to avoid
313 // spamming the browser.
314 // To avoid having tab/session restore require sending a message to get the
315 // current content state during tab closing we use a shorter timeout for the
316 // foreground renderer. This means there is a small window of time from which
317 // content state is modified and not sent to session restore, but this is
318 // better than having to wake up all renderers during shutdown.
319 const int kDelaySecondsForContentStateSyncHidden = 5;
320 const int kDelaySecondsForContentStateSync = 1;
322 #if defined(OS_ANDROID)
323 // Delay between tapping in content and launching the associated android intent.
324 // Used to allow users see what has been recognized as content.
325 const size_t kContentIntentDelayMilliseconds = 700;
326 #endif
328 static RenderViewImpl* (*g_create_render_view_impl)(const ViewMsg_New_Params&) =
329 NULL;
331 // static
332 bool RenderViewImpl::IsReload(FrameMsg_Navigate_Type::Value navigation_type) {
333 return navigation_type == FrameMsg_Navigate_Type::RELOAD ||
334 navigation_type == FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE ||
335 navigation_type == FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL;
338 // static
339 Referrer RenderViewImpl::GetReferrerFromRequest(
340 WebFrame* frame,
341 const WebURLRequest& request) {
342 return Referrer(GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
343 request.referrerPolicy());
346 // static
347 WindowOpenDisposition RenderViewImpl::NavigationPolicyToDisposition(
348 WebNavigationPolicy policy) {
349 switch (policy) {
350 case blink::WebNavigationPolicyIgnore:
351 return IGNORE_ACTION;
352 case blink::WebNavigationPolicyDownload:
353 return SAVE_TO_DISK;
354 case blink::WebNavigationPolicyCurrentTab:
355 return CURRENT_TAB;
356 case blink::WebNavigationPolicyNewBackgroundTab:
357 return NEW_BACKGROUND_TAB;
358 case blink::WebNavigationPolicyNewForegroundTab:
359 return NEW_FOREGROUND_TAB;
360 case blink::WebNavigationPolicyNewWindow:
361 return NEW_WINDOW;
362 case blink::WebNavigationPolicyNewPopup:
363 return NEW_POPUP;
364 default:
365 NOTREACHED() << "Unexpected WebNavigationPolicy";
366 return IGNORE_ACTION;
370 // Returns true if the device scale is high enough that losing subpixel
371 // antialiasing won't have a noticeable effect on text quality.
372 static bool DeviceScaleEnsuresTextQuality(float device_scale_factor) {
373 #if defined(OS_ANDROID)
374 // On Android, we never have subpixel antialiasing.
375 return true;
376 #else
377 return device_scale_factor > 1.5f;
378 #endif
382 static bool PreferCompositingToLCDText(CompositorDependencies* compositor_deps,
383 float device_scale_factor) {
384 const base::CommandLine& command_line =
385 *base::CommandLine::ForCurrentProcess();
386 if (command_line.HasSwitch(switches::kDisablePreferCompositingToLCDText))
387 return false;
388 if (command_line.HasSwitch(switches::kEnablePreferCompositingToLCDText))
389 return true;
390 if (!compositor_deps->IsLcdTextEnabled())
391 return true;
392 return DeviceScaleEnsuresTextQuality(device_scale_factor);
395 static FaviconURL::IconType ToFaviconType(blink::WebIconURL::Type type) {
396 switch (type) {
397 case blink::WebIconURL::TypeFavicon:
398 return FaviconURL::FAVICON;
399 case blink::WebIconURL::TypeTouch:
400 return FaviconURL::TOUCH_ICON;
401 case blink::WebIconURL::TypeTouchPrecomposed:
402 return FaviconURL::TOUCH_PRECOMPOSED_ICON;
403 case blink::WebIconURL::TypeInvalid:
404 return FaviconURL::INVALID_ICON;
406 return FaviconURL::INVALID_ICON;
409 static void ConvertToFaviconSizes(
410 const blink::WebVector<blink::WebSize>& web_sizes,
411 std::vector<gfx::Size>* sizes) {
412 DCHECK(sizes->empty());
413 sizes->reserve(web_sizes.size());
414 for (size_t i = 0; i < web_sizes.size(); ++i)
415 sizes->push_back(gfx::Size(web_sizes[i]));
418 ///////////////////////////////////////////////////////////////////////////////
420 struct RenderViewImpl::PendingFileChooser {
421 PendingFileChooser(const FileChooserParams& p, WebFileChooserCompletion* c)
422 : params(p),
423 completion(c) {
425 FileChooserParams params;
426 WebFileChooserCompletion* completion; // MAY BE NULL to skip callback.
429 namespace {
431 class WebWidgetLockTarget : public MouseLockDispatcher::LockTarget {
432 public:
433 explicit WebWidgetLockTarget(blink::WebWidget* webwidget)
434 : webwidget_(webwidget) {}
436 void OnLockMouseACK(bool succeeded) override {
437 if (succeeded)
438 webwidget_->didAcquirePointerLock();
439 else
440 webwidget_->didNotAcquirePointerLock();
443 void OnMouseLockLost() override { webwidget_->didLosePointerLock(); }
445 bool HandleMouseLockedInputEvent(const blink::WebMouseEvent& event) override {
446 // The WebWidget handles mouse lock in WebKit's handleInputEvent().
447 return false;
450 private:
451 blink::WebWidget* webwidget_;
454 WebDragData DropDataToWebDragData(const DropData& drop_data) {
455 std::vector<WebDragData::Item> item_list;
457 // These fields are currently unused when dragging into WebKit.
458 DCHECK(drop_data.download_metadata.empty());
459 DCHECK(drop_data.file_contents.empty());
460 DCHECK(drop_data.file_description_filename.empty());
462 if (!drop_data.text.is_null()) {
463 WebDragData::Item item;
464 item.storageType = WebDragData::Item::StorageTypeString;
465 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeText);
466 item.stringData = drop_data.text.string();
467 item_list.push_back(item);
470 // TODO(dcheng): Do we need to distinguish between null and empty URLs? Is it
471 // meaningful to write an empty URL to the clipboard?
472 if (!drop_data.url.is_empty()) {
473 WebDragData::Item item;
474 item.storageType = WebDragData::Item::StorageTypeString;
475 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeURIList);
476 item.stringData = WebString::fromUTF8(drop_data.url.spec());
477 item.title = drop_data.url_title;
478 item_list.push_back(item);
481 if (!drop_data.html.is_null()) {
482 WebDragData::Item item;
483 item.storageType = WebDragData::Item::StorageTypeString;
484 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeHTML);
485 item.stringData = drop_data.html.string();
486 item.baseURL = drop_data.html_base_url;
487 item_list.push_back(item);
490 for (std::vector<ui::FileInfo>::const_iterator it =
491 drop_data.filenames.begin();
492 it != drop_data.filenames.end();
493 ++it) {
494 WebDragData::Item item;
495 item.storageType = WebDragData::Item::StorageTypeFilename;
496 item.filenameData = it->path.AsUTF16Unsafe();
497 item.displayNameData = it->display_name.AsUTF16Unsafe();
498 item_list.push_back(item);
501 for (std::vector<DropData::FileSystemFileInfo>::const_iterator it =
502 drop_data.file_system_files.begin();
503 it != drop_data.file_system_files.end();
504 ++it) {
505 WebDragData::Item item;
506 item.storageType = WebDragData::Item::StorageTypeFileSystemFile;
507 item.fileSystemURL = it->url;
508 item.fileSystemFileSize = it->size;
509 item_list.push_back(item);
512 for (std::map<base::string16, base::string16>::const_iterator it =
513 drop_data.custom_data.begin();
514 it != drop_data.custom_data.end();
515 ++it) {
516 WebDragData::Item item;
517 item.storageType = WebDragData::Item::StorageTypeString;
518 item.stringType = it->first;
519 item.stringData = it->second;
520 item_list.push_back(item);
523 WebDragData result;
524 result.initialize();
525 result.setItems(item_list);
526 result.setFilesystemId(drop_data.filesystem_id);
527 return result;
530 typedef void (*SetFontFamilyWrapper)(blink::WebSettings*,
531 const base::string16&,
532 UScriptCode);
534 void SetStandardFontFamilyWrapper(WebSettings* settings,
535 const base::string16& font,
536 UScriptCode script) {
537 settings->setStandardFontFamily(font, script);
540 void SetFixedFontFamilyWrapper(WebSettings* settings,
541 const base::string16& font,
542 UScriptCode script) {
543 settings->setFixedFontFamily(font, script);
546 void SetSerifFontFamilyWrapper(WebSettings* settings,
547 const base::string16& font,
548 UScriptCode script) {
549 settings->setSerifFontFamily(font, script);
552 void SetSansSerifFontFamilyWrapper(WebSettings* settings,
553 const base::string16& font,
554 UScriptCode script) {
555 settings->setSansSerifFontFamily(font, script);
558 void SetCursiveFontFamilyWrapper(WebSettings* settings,
559 const base::string16& font,
560 UScriptCode script) {
561 settings->setCursiveFontFamily(font, script);
564 void SetFantasyFontFamilyWrapper(WebSettings* settings,
565 const base::string16& font,
566 UScriptCode script) {
567 settings->setFantasyFontFamily(font, script);
570 void SetPictographFontFamilyWrapper(WebSettings* settings,
571 const base::string16& font,
572 UScriptCode script) {
573 settings->setPictographFontFamily(font, script);
576 // If |scriptCode| is a member of a family of "similar" script codes, returns
577 // the script code in that family that is used by WebKit for font selection
578 // purposes. For example, USCRIPT_KATAKANA_OR_HIRAGANA and USCRIPT_JAPANESE are
579 // considered equivalent for the purposes of font selection. WebKit uses the
580 // script code USCRIPT_KATAKANA_OR_HIRAGANA. So, if |scriptCode| is
581 // USCRIPT_JAPANESE, the function returns USCRIPT_KATAKANA_OR_HIRAGANA. WebKit
582 // uses different scripts than the ones in Chrome pref names because the version
583 // of ICU included on certain ports does not have some of the newer scripts. If
584 // |scriptCode| is not a member of such a family, returns |scriptCode|.
585 UScriptCode GetScriptForWebSettings(UScriptCode scriptCode) {
586 switch (scriptCode) {
587 case USCRIPT_HIRAGANA:
588 case USCRIPT_KATAKANA:
589 case USCRIPT_JAPANESE:
590 return USCRIPT_KATAKANA_OR_HIRAGANA;
591 case USCRIPT_KOREAN:
592 return USCRIPT_HANGUL;
593 default:
594 return scriptCode;
598 void ApplyFontsFromMap(const ScriptFontFamilyMap& map,
599 SetFontFamilyWrapper setter,
600 WebSettings* settings) {
601 for (ScriptFontFamilyMap::const_iterator it = map.begin(); it != map.end();
602 ++it) {
603 int32 script = u_getPropertyValueEnum(UCHAR_SCRIPT, (it->first).c_str());
604 if (script >= 0 && script < USCRIPT_CODE_LIMIT) {
605 UScriptCode code = static_cast<UScriptCode>(script);
606 (*setter)(settings, it->second, GetScriptForWebSettings(code));
611 } // namespace
613 RenderViewImpl::RenderViewImpl(const ViewMsg_New_Params& params)
614 : RenderWidget(blink::WebPopupTypeNone,
615 params.initial_size.screen_info,
616 params.swapped_out,
617 params.hidden,
618 params.never_visible),
619 webkit_preferences_(params.web_preferences),
620 send_content_state_immediately_(false),
621 enabled_bindings_(0),
622 send_preferred_size_changes_(false),
623 navigation_gesture_(NavigationGestureUnknown),
624 opened_by_user_gesture_(true),
625 opener_suppressed_(false),
626 suppress_dialogs_until_swap_out_(false),
627 page_id_(-1),
628 next_page_id_(params.next_page_id),
629 history_list_offset_(-1),
630 history_list_length_(0),
631 frames_in_progress_(0),
632 target_url_status_(TARGET_NONE),
633 uses_temporary_zoom_level_(false),
634 #if defined(OS_ANDROID)
635 top_controls_constraints_(TOP_CONTROLS_STATE_BOTH),
636 #endif
637 has_scrolled_focused_editable_node_into_rect_(false),
638 speech_recognition_dispatcher_(NULL),
639 devtools_agent_(NULL),
640 mouse_lock_dispatcher_(NULL),
641 #if defined(OS_ANDROID)
642 expected_content_intent_id_(0),
643 #endif
644 #if defined(OS_WIN)
645 focused_plugin_id_(-1),
646 #endif
647 #if defined(ENABLE_PLUGINS)
648 plugin_find_handler_(NULL),
649 focused_pepper_plugin_(NULL),
650 pepper_last_mouse_event_target_(NULL),
651 #endif
652 enumeration_completion_id_(0),
653 session_storage_namespace_id_(params.session_storage_namespace_id),
654 page_scale_factor_is_one_(true),
655 debug_info_(params.debug_info) {
658 void RenderViewImpl::Initialize(const ViewMsg_New_Params& params,
659 CompositorDependencies* compositor_deps,
660 bool was_created_by_renderer) {
661 routing_id_ = params.view_id;
662 surface_id_ = params.surface_id;
663 if (params.opener_route_id != MSG_ROUTING_NONE && was_created_by_renderer)
664 opener_id_ = params.opener_route_id;
666 // Ensure we start with a valid next_page_id_ from the browser.
667 DCHECK_GE(next_page_id_, 0);
669 main_render_frame_.reset(RenderFrameImpl::Create(
670 this, params.main_frame_routing_id));
671 // The main frame WebLocalFrame object is closed by
672 // RenderFrameImpl::frameDetached().
673 WebLocalFrame* web_frame = WebLocalFrame::create(main_render_frame_.get());
674 main_render_frame_->SetWebFrame(web_frame);
676 compositor_deps_ = compositor_deps;
677 webwidget_ = WebView::create(this);
678 webwidget_mouse_lock_target_.reset(new WebWidgetLockTarget(webwidget_));
680 const base::CommandLine& command_line =
681 *base::CommandLine::ForCurrentProcess();
683 if (command_line.HasSwitch(switches::kStatsCollectionController))
684 stats_collection_observer_.reset(new StatsCollectionObserver(this));
686 #if defined(OS_ANDROID)
687 const std::string region_code =
688 command_line.HasSwitch(switches::kNetworkCountryIso)
689 ? command_line.GetSwitchValueASCII(switches::kNetworkCountryIso)
690 : net::android::GetTelephonyNetworkCountryIso();
691 content_detectors_.push_back(linked_ptr<ContentDetector>(
692 new AddressDetector()));
693 if (!region_code.empty()) {
694 content_detectors_.push_back(linked_ptr<ContentDetector>(
695 new PhoneNumberDetector(region_code)));
697 content_detectors_.push_back(linked_ptr<ContentDetector>(
698 new EmailDetector()));
699 #endif
701 RenderThread::Get()->AddRoute(routing_id_, this);
702 // Take a reference on behalf of the RenderThread. This will be balanced
703 // when we receive ViewMsg_ClosePage.
704 AddRef();
705 if (RenderThreadImpl::current()) {
706 RenderThreadImpl::current()->WidgetCreated();
707 if (is_hidden_)
708 RenderThreadImpl::current()->WidgetHidden();
711 // If this is a popup, we must wait for the CreatingNew_ACK message before
712 // completing initialization. Otherwise, we can finish it now.
713 if (opener_id_ == MSG_ROUTING_NONE) {
714 did_show_ = true;
715 CompleteInit();
718 g_view_map.Get().insert(std::make_pair(webview(), this));
719 g_routing_id_view_map.Get().insert(std::make_pair(routing_id_, this));
720 webview()->setDeviceScaleFactor(device_scale_factor_);
721 webview()->settings()->setPreferCompositingToLCDTextEnabled(
722 PreferCompositingToLCDText(compositor_deps_, device_scale_factor_));
723 webview()->settings()->setThreadedScrollingEnabled(
724 !command_line.HasSwitch(switches::kDisableThreadedScrolling));
725 webview()->settings()->setRootLayerScrolls(
726 command_line.HasSwitch(switches::kRootLayerScrolls));
728 ApplyWebPreferences(webkit_preferences_, webview());
730 webview()->settings()->setAllowConnectingInsecureWebSocket(
731 command_line.HasSwitch(switches::kAllowInsecureWebSocketFromHttpsOrigin));
733 RenderFrameProxy* proxy = NULL;
734 if (params.proxy_routing_id != MSG_ROUTING_NONE) {
735 CHECK(params.swapped_out);
736 proxy = RenderFrameProxy::CreateProxyToReplaceFrame(
737 main_render_frame_.get(), params.proxy_routing_id);
738 main_render_frame_->set_render_frame_proxy(proxy);
741 // In --site-per-process, just use the WebRemoteFrame as the main frame.
742 if (command_line.HasSwitch(switches::kSitePerProcess) && proxy) {
743 webview()->setMainFrame(proxy->web_frame());
744 // Initialize the WebRemoteFrame with information replicated from the
745 // browser process.
746 proxy->SetReplicatedState(params.replicated_frame_state);
747 } else {
748 webview()->setMainFrame(main_render_frame_->GetWebFrame());
750 main_render_frame_->Initialize();
752 if (switches::IsTouchDragDropEnabled())
753 webview()->settings()->setTouchDragDropEnabled(true);
755 if (switches::IsTouchEditingEnabled())
756 webview()->settings()->setTouchEditingEnabled(true);
758 if (!params.frame_name.empty())
759 webview()->mainFrame()->setName(params.frame_name);
761 // TODO(davidben): Move this state from Blink into content.
762 if (params.window_was_created_with_opener)
763 webview()->setOpenedByDOM();
765 OnSetRendererPrefs(params.renderer_preferences);
767 if (!params.enable_auto_resize) {
768 OnResize(params.initial_size);
769 } else {
770 OnEnableAutoResize(params.min_size, params.max_size);
773 new MHTMLGenerator(this);
774 #if defined(OS_MACOSX)
775 new TextInputClientObserver(this);
776 #endif // defined(OS_MACOSX)
778 // The next group of objects all implement RenderViewObserver, so are deleted
779 // along with the RenderView automatically.
780 devtools_agent_ = new DevToolsAgent(main_render_frame_.get());
781 if (RenderWidgetCompositor* rwc = compositor()) {
782 webview()->devToolsAgent()->setLayerTreeId(rwc->GetLayerTreeId());
784 mouse_lock_dispatcher_ = new RenderViewMouseLockDispatcher(this);
786 history_controller_.reset(new HistoryController(this));
788 new IdleUserDetector(this);
790 if (command_line.HasSwitch(switches::kDomAutomationController))
791 enabled_bindings_ |= BINDINGS_POLICY_DOM_AUTOMATION;
792 if (command_line.HasSwitch(switches::kStatsCollectionController))
793 enabled_bindings_ |= BINDINGS_POLICY_STATS_COLLECTION;
795 GetContentClient()->renderer()->RenderViewCreated(this);
797 // If we have an opener_id but we weren't created by a renderer, then
798 // it's the browser asking us to set our opener to another RenderView.
799 if (params.opener_route_id != MSG_ROUTING_NONE && !was_created_by_renderer) {
800 RenderViewImpl* opener_view = FromRoutingID(params.opener_route_id);
801 if (opener_view)
802 webview()->mainFrame()->setOpener(opener_view->webview()->mainFrame());
805 // If we are initially swapped out, navigate to kSwappedOutURL.
806 // This ensures we are in a unique origin that others cannot script.
807 if (is_swapped_out_ && webview()->mainFrame()->isWebLocalFrame())
808 main_render_frame_->NavigateToSwappedOutURL();
811 RenderViewImpl::~RenderViewImpl() {
812 for (BitmapMap::iterator it = disambiguation_bitmaps_.begin();
813 it != disambiguation_bitmaps_.end();
814 ++it)
815 delete it->second;
816 base::trace_event::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_);
818 // If file chooser is still waiting for answer, dispatch empty answer.
819 while (!file_chooser_completions_.empty()) {
820 if (file_chooser_completions_.front()->completion) {
821 file_chooser_completions_.front()->completion->didChooseFile(
822 WebVector<WebString>());
824 file_chooser_completions_.pop_front();
827 #if defined(OS_ANDROID)
828 // The date/time picker client is both a scoped_ptr member of this class and
829 // a RenderViewObserver. Reset it to prevent double deletion.
830 date_time_picker_client_.reset();
831 #endif
833 #ifndef NDEBUG
834 // Make sure we are no longer referenced by the ViewMap or RoutingIDViewMap.
835 ViewMap* views = g_view_map.Pointer();
836 for (ViewMap::iterator it = views->begin(); it != views->end(); ++it)
837 DCHECK_NE(this, it->second) << "Failed to call Close?";
838 RoutingIDViewMap* routing_id_views = g_routing_id_view_map.Pointer();
839 for (RoutingIDViewMap::iterator it = routing_id_views->begin();
840 it != routing_id_views->end(); ++it)
841 DCHECK_NE(this, it->second) << "Failed to call Close?";
842 #endif
844 FOR_EACH_OBSERVER(RenderViewObserver, observers_, RenderViewGone());
845 FOR_EACH_OBSERVER(RenderViewObserver, observers_, OnDestruct());
848 /*static*/
849 RenderViewImpl* RenderViewImpl::FromWebView(WebView* webview) {
850 ViewMap* views = g_view_map.Pointer();
851 ViewMap::iterator it = views->find(webview);
852 return it == views->end() ? NULL : it->second;
855 /*static*/
856 RenderView* RenderView::FromWebView(blink::WebView* webview) {
857 return RenderViewImpl::FromWebView(webview);
860 /*static*/
861 RenderViewImpl* RenderViewImpl::FromRoutingID(int32 routing_id) {
862 RoutingIDViewMap* views = g_routing_id_view_map.Pointer();
863 RoutingIDViewMap::iterator it = views->find(routing_id);
864 return it == views->end() ? NULL : it->second;
867 /*static*/
868 RenderView* RenderView::FromRoutingID(int routing_id) {
869 return RenderViewImpl::FromRoutingID(routing_id);
872 /* static */
873 size_t RenderViewImpl::GetRenderViewCount() {
874 return g_view_map.Get().size();
877 /*static*/
878 void RenderView::ForEach(RenderViewVisitor* visitor) {
879 ViewMap* views = g_view_map.Pointer();
880 for (ViewMap::iterator it = views->begin(); it != views->end(); ++it) {
881 if (!visitor->Visit(it->second))
882 return;
886 /*static*/
887 void RenderView::ApplyWebPreferences(const WebPreferences& prefs,
888 WebView* web_view) {
889 WebSettings* settings = web_view->settings();
890 ApplyFontsFromMap(prefs.standard_font_family_map,
891 SetStandardFontFamilyWrapper, settings);
892 ApplyFontsFromMap(prefs.fixed_font_family_map,
893 SetFixedFontFamilyWrapper, settings);
894 ApplyFontsFromMap(prefs.serif_font_family_map,
895 SetSerifFontFamilyWrapper, settings);
896 ApplyFontsFromMap(prefs.sans_serif_font_family_map,
897 SetSansSerifFontFamilyWrapper, settings);
898 ApplyFontsFromMap(prefs.cursive_font_family_map,
899 SetCursiveFontFamilyWrapper, settings);
900 ApplyFontsFromMap(prefs.fantasy_font_family_map,
901 SetFantasyFontFamilyWrapper, settings);
902 ApplyFontsFromMap(prefs.pictograph_font_family_map,
903 SetPictographFontFamilyWrapper, settings);
904 settings->setDefaultFontSize(prefs.default_font_size);
905 settings->setDefaultFixedFontSize(prefs.default_fixed_font_size);
906 settings->setMinimumFontSize(prefs.minimum_font_size);
907 settings->setMinimumLogicalFontSize(prefs.minimum_logical_font_size);
908 settings->setDefaultTextEncodingName(
909 base::ASCIIToUTF16(prefs.default_encoding));
910 settings->setJavaScriptEnabled(prefs.javascript_enabled);
911 settings->setWebSecurityEnabled(prefs.web_security_enabled);
912 settings->setJavaScriptCanOpenWindowsAutomatically(
913 prefs.javascript_can_open_windows_automatically);
914 settings->setLoadsImagesAutomatically(prefs.loads_images_automatically);
915 settings->setImagesEnabled(prefs.images_enabled);
916 settings->setPluginsEnabled(prefs.plugins_enabled);
917 settings->setDOMPasteAllowed(prefs.dom_paste_enabled);
918 settings->setShrinksStandaloneImagesToFit(
919 prefs.shrinks_standalone_images_to_fit);
920 settings->setUsesEncodingDetector(prefs.uses_universal_detector);
921 settings->setTextAreasAreResizable(prefs.text_areas_are_resizable);
922 settings->setAllowScriptsToCloseWindows(prefs.allow_scripts_to_close_windows);
923 settings->setDownloadableBinaryFontsEnabled(prefs.remote_fonts_enabled);
924 settings->setJavaScriptCanAccessClipboard(
925 prefs.javascript_can_access_clipboard);
926 WebRuntimeFeatures::enableXSLT(prefs.xslt_enabled);
927 WebRuntimeFeatures::enableSlimmingPaint(prefs.slimming_paint_enabled);
928 settings->setXSSAuditorEnabled(prefs.xss_auditor_enabled);
929 settings->setDNSPrefetchingEnabled(prefs.dns_prefetching_enabled);
930 settings->setLocalStorageEnabled(prefs.local_storage_enabled);
931 settings->setSyncXHRInDocumentsEnabled(prefs.sync_xhr_in_documents_enabled);
932 WebRuntimeFeatures::enableDatabase(prefs.databases_enabled);
933 settings->setOfflineWebApplicationCacheEnabled(
934 prefs.application_cache_enabled);
935 settings->setCaretBrowsingEnabled(prefs.caret_browsing_enabled);
936 settings->setHyperlinkAuditingEnabled(prefs.hyperlink_auditing_enabled);
937 settings->setCookieEnabled(prefs.cookie_enabled);
938 settings->setNavigateOnDragDrop(prefs.navigate_on_drag_drop);
940 settings->setJavaEnabled(prefs.java_enabled);
942 // By default, allow_universal_access_from_file_urls is set to false and thus
943 // we mitigate attacks from local HTML files by not granting file:// URLs
944 // universal access. Only test shell will enable this.
945 settings->setAllowUniversalAccessFromFileURLs(
946 prefs.allow_universal_access_from_file_urls);
947 settings->setAllowFileAccessFromFileURLs(
948 prefs.allow_file_access_from_file_urls);
950 // Enable the web audio API if requested on the command line.
951 settings->setWebAudioEnabled(prefs.webaudio_enabled);
953 // Enable experimental WebGL support if requested on command line
954 // and support is compiled in.
955 settings->setExperimentalWebGLEnabled(prefs.experimental_webgl_enabled);
957 // Disable GL multisampling if requested on command line.
958 settings->setOpenGLMultisamplingEnabled(prefs.gl_multisampling_enabled);
960 // Enable WebGL errors to the JS console if requested.
961 settings->setWebGLErrorsToConsoleEnabled(
962 prefs.webgl_errors_to_console_enabled);
964 // Uses the mock theme engine for scrollbars.
965 settings->setMockScrollbarsEnabled(prefs.mock_scrollbars_enabled);
967 // Enable gpu-accelerated 2d canvas if requested on the command line.
968 settings->setAccelerated2dCanvasEnabled(prefs.accelerated_2d_canvas_enabled);
970 settings->setMinimumAccelerated2dCanvasSize(
971 prefs.minimum_accelerated_2d_canvas_size);
973 // Disable antialiasing for 2d canvas if requested on the command line.
974 settings->setAntialiased2dCanvasEnabled(
975 !prefs.antialiased_2d_canvas_disabled);
977 // Enabled antialiasing of clips for 2d canvas if requested on the command
978 // line.
979 settings->setAntialiasedClips2dCanvasEnabled(
980 prefs.antialiased_clips_2d_canvas_enabled);
982 // Set MSAA sample count for 2d canvas if requested on the command line (or
983 // default value if not).
984 settings->setAccelerated2dCanvasMSAASampleCount(
985 prefs.accelerated_2d_canvas_msaa_sample_count);
987 WebRuntimeFeatures::enableTextBlobs(prefs.text_blobs_enabled);
989 settings->setAsynchronousSpellCheckingEnabled(
990 prefs.asynchronous_spell_checking_enabled);
991 settings->setUnifiedTextCheckerEnabled(prefs.unified_textchecker_enabled);
993 // Tabs to link is not part of the settings. WebCore calls
994 // ChromeClient::tabsToLinks which is part of the glue code.
995 web_view->setTabsToLinks(prefs.tabs_to_links);
997 settings->setAllowDisplayOfInsecureContent(
998 prefs.allow_displaying_insecure_content);
999 settings->setAllowRunningOfInsecureContent(
1000 prefs.allow_running_insecure_content);
1001 settings->setDisableReadingFromCanvas(prefs.disable_reading_from_canvas);
1002 settings->setStrictMixedContentChecking(prefs.strict_mixed_content_checking);
1003 settings->setStrictPowerfulFeatureRestrictions(
1004 prefs.strict_powerful_feature_restrictions);
1005 settings->setPasswordEchoEnabled(prefs.password_echo_enabled);
1006 settings->setShouldPrintBackgrounds(prefs.should_print_backgrounds);
1007 settings->setShouldClearDocumentBackground(
1008 prefs.should_clear_document_background);
1009 settings->setEnableScrollAnimator(prefs.enable_scroll_animator);
1011 settings->setRegionBasedColumnsEnabled(prefs.region_based_columns_enabled);
1013 WebRuntimeFeatures::enableTouch(prefs.touch_enabled);
1014 settings->setMaxTouchPoints(prefs.pointer_events_max_touch_points);
1015 settings->setAvailablePointerTypes(prefs.available_pointer_types);
1016 settings->setPrimaryPointerType(
1017 static_cast<WebSettings::PointerType>(prefs.primary_pointer_type));
1018 settings->setAvailableHoverTypes(prefs.available_hover_types);
1019 settings->setPrimaryHoverType(
1020 static_cast<WebSettings::HoverType>(prefs.primary_hover_type));
1021 settings->setDeviceSupportsTouch(prefs.device_supports_touch);
1022 settings->setDeviceSupportsMouse(prefs.device_supports_mouse);
1023 settings->setEnableTouchAdjustment(prefs.touch_adjustment_enabled);
1025 settings->setDeferredImageDecodingEnabled(
1026 prefs.deferred_image_decoding_enabled);
1027 WebRuntimeFeatures::enableImageColorProfiles(
1028 prefs.image_color_profiles_enabled);
1029 settings->setShouldRespectImageOrientation(
1030 prefs.should_respect_image_orientation);
1032 settings->setUnsafePluginPastingEnabled(false);
1033 settings->setEditingBehavior(
1034 static_cast<WebSettings::EditingBehavior>(prefs.editing_behavior));
1036 settings->setSupportsMultipleWindows(prefs.supports_multiple_windows);
1038 settings->setViewportEnabled(prefs.viewport_enabled);
1039 settings->setLoadWithOverviewMode(prefs.initialize_at_minimum_page_scale);
1040 settings->setViewportMetaEnabled(prefs.viewport_meta_enabled);
1041 settings->setMainFrameResizesAreOrientationChanges(
1042 prefs.main_frame_resizes_are_orientation_changes);
1044 settings->setSmartInsertDeleteEnabled(prefs.smart_insert_delete_enabled);
1046 settings->setSpatialNavigationEnabled(prefs.spatial_navigation_enabled);
1048 settings->setSelectionIncludesAltImageText(true);
1050 settings->setV8CacheOptions(
1051 static_cast<WebSettings::V8CacheOptions>(prefs.v8_cache_options));
1053 settings->setImageAnimationPolicy(
1054 static_cast<WebSettings::ImageAnimationPolicy>(prefs.animation_policy));
1056 // Needs to happen before setIgnoreVIewportTagScaleLimits below.
1057 web_view->setDefaultPageScaleLimits(
1058 prefs.default_minimum_page_scale_factor,
1059 prefs.default_maximum_page_scale_factor);
1061 #if defined(OS_ANDROID)
1062 settings->setAllowCustomScrollbarInMainFrame(false);
1063 settings->setTextAutosizingEnabled(prefs.text_autosizing_enabled);
1064 settings->setAccessibilityFontScaleFactor(prefs.font_scale_factor);
1065 settings->setDeviceScaleAdjustment(prefs.device_scale_adjustment);
1066 settings->setFullscreenSupported(prefs.fullscreen_supported);
1067 web_view->setIgnoreViewportTagScaleLimits(prefs.force_enable_zoom);
1068 settings->setAutoZoomFocusedNodeToLegibleScale(true);
1069 settings->setDoubleTapToZoomEnabled(prefs.double_tap_to_zoom_enabled);
1070 settings->setMediaControlsOverlayPlayButtonEnabled(true);
1071 settings->setMediaPlaybackRequiresUserGesture(
1072 prefs.user_gesture_required_for_media_playback);
1073 settings->setDefaultVideoPosterURL(
1074 base::ASCIIToUTF16(prefs.default_video_poster_url.spec()));
1075 settings->setSupportDeprecatedTargetDensityDPI(
1076 prefs.support_deprecated_target_density_dpi);
1077 settings->setUseLegacyBackgroundSizeShorthandBehavior(
1078 prefs.use_legacy_background_size_shorthand_behavior);
1079 settings->setWideViewportQuirkEnabled(prefs.wide_viewport_quirk);
1080 settings->setUseWideViewport(prefs.use_wide_viewport);
1081 settings->setForceZeroLayoutHeight(prefs.force_zero_layout_height);
1082 settings->setViewportMetaLayoutSizeQuirk(
1083 prefs.viewport_meta_layout_size_quirk);
1084 settings->setViewportMetaMergeContentQuirk(
1085 prefs.viewport_meta_merge_content_quirk);
1086 settings->setViewportMetaNonUserScalableQuirk(
1087 prefs.viewport_meta_non_user_scalable_quirk);
1088 settings->setViewportMetaZeroValuesQuirk(
1089 prefs.viewport_meta_zero_values_quirk);
1090 settings->setClobberUserAgentInitialScaleQuirk(
1091 prefs.clobber_user_agent_initial_scale_quirk);
1092 settings->setIgnoreMainFrameOverflowHiddenQuirk(
1093 prefs.ignore_main_frame_overflow_hidden_quirk);
1094 settings->setReportScreenSizeInPhysicalPixelsQuirk(
1095 prefs.report_screen_size_in_physical_pixels_quirk);
1097 bool record_full_layer =
1098 RenderViewImpl::FromWebView(web_view)
1099 ? RenderViewImpl::FromWebView(web_view)->DoesRecordFullLayer()
1100 : false;
1101 settings->setMainFrameClipsContent(!record_full_layer);
1103 settings->setShrinksStandaloneImagesToFit(false);
1104 settings->setShrinksViewportContentToFit(true);
1105 settings->setUseMobileViewportStyle(true);
1106 #endif
1108 WebNetworkStateNotifier::setOnLine(prefs.is_online);
1109 WebNetworkStateNotifier::setWebConnectionType(
1110 NetConnectionTypeToWebConnectionType(prefs.connection_type));
1111 settings->setPinchVirtualViewportEnabled(
1112 prefs.pinch_virtual_viewport_enabled);
1114 settings->setPinchOverlayScrollbarThickness(
1115 prefs.pinch_overlay_scrollbar_thickness);
1116 settings->setUseSolidColorScrollbars(prefs.use_solid_color_scrollbars);
1118 settings->setShowContextMenuOnMouseUp(prefs.context_menu_on_mouse_up);
1120 #if defined(OS_MACOSX)
1121 settings->setDoubleTapToZoomEnabled(true);
1122 web_view->setMaximumLegibleScale(prefs.default_maximum_page_scale_factor);
1123 #endif
1126 /*static*/
1127 RenderViewImpl* RenderViewImpl::Create(const ViewMsg_New_Params& params,
1128 CompositorDependencies* compositor_deps,
1129 bool was_created_by_renderer) {
1130 DCHECK(params.view_id != MSG_ROUTING_NONE);
1131 RenderViewImpl* render_view = NULL;
1132 if (g_create_render_view_impl)
1133 render_view = g_create_render_view_impl(params);
1134 else
1135 render_view = new RenderViewImpl(params);
1137 render_view->Initialize(params, compositor_deps, was_created_by_renderer);
1138 return render_view;
1141 // static
1142 void RenderViewImpl::InstallCreateHook(
1143 RenderViewImpl* (*create_render_view_impl)(const ViewMsg_New_Params&)) {
1144 CHECK(!g_create_render_view_impl);
1145 g_create_render_view_impl = create_render_view_impl;
1148 void RenderViewImpl::AddObserver(RenderViewObserver* observer) {
1149 observers_.AddObserver(observer);
1152 void RenderViewImpl::RemoveObserver(RenderViewObserver* observer) {
1153 observer->RenderViewGone();
1154 observers_.RemoveObserver(observer);
1157 blink::WebView* RenderViewImpl::webview() const {
1158 return static_cast<blink::WebView*>(webwidget());
1161 #if defined(ENABLE_PLUGINS)
1162 void RenderViewImpl::PepperInstanceCreated(
1163 PepperPluginInstanceImpl* instance) {
1164 active_pepper_instances_.insert(instance);
1167 void RenderViewImpl::PepperInstanceDeleted(
1168 PepperPluginInstanceImpl* instance) {
1169 active_pepper_instances_.erase(instance);
1171 if (pepper_last_mouse_event_target_ == instance)
1172 pepper_last_mouse_event_target_ = NULL;
1173 if (focused_pepper_plugin_ == instance)
1174 PepperFocusChanged(instance, false);
1177 void RenderViewImpl::PepperFocusChanged(PepperPluginInstanceImpl* instance,
1178 bool focused) {
1179 if (focused)
1180 focused_pepper_plugin_ = instance;
1181 else if (focused_pepper_plugin_ == instance)
1182 focused_pepper_plugin_ = NULL;
1184 UpdateTextInputType();
1185 UpdateSelectionBounds();
1188 void RenderViewImpl::RegisterPluginDelegate(WebPluginDelegateProxy* delegate) {
1189 plugin_delegates_.insert(delegate);
1190 // If the renderer is visible, set initial visibility and focus state.
1191 if (!is_hidden()) {
1192 #if defined(OS_MACOSX)
1193 delegate->SetContainerVisibility(true);
1194 if (webview() && webview()->isActive())
1195 delegate->SetWindowFocus(true);
1196 #endif
1198 // Plugins start assuming the content has focus (so that they work in
1199 // environments where RenderView isn't hosting them), so we always have to
1200 // set the initial state. See webplugin_delegate_impl.h for details.
1201 delegate->SetContentAreaFocus(has_focus());
1204 void RenderViewImpl::UnregisterPluginDelegate(
1205 WebPluginDelegateProxy* delegate) {
1206 plugin_delegates_.erase(delegate);
1209 #if defined(OS_WIN)
1210 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1211 if (focused)
1212 focused_plugin_id_ = plugin_id;
1213 else
1214 focused_plugin_id_ = -1;
1216 #endif
1218 #if defined(OS_MACOSX)
1219 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1220 Send(new ViewHostMsg_PluginFocusChanged(routing_id(), focused, plugin_id));
1223 void RenderViewImpl::OnGetRenderedText() {
1224 if (!webview())
1225 return;
1226 // Get rendered text from WebLocalFrame.
1227 // TODO: Currently IPC truncates any data that has a
1228 // size > kMaximumMessageSize. May be split the text into smaller chunks and
1229 // send back using multiple IPC. See http://crbug.com/393444.
1230 static const size_t kMaximumMessageSize = 8 * 1024 * 1024;
1231 std::string text = webview()->mainFrame()->contentAsText(
1232 kMaximumMessageSize).utf8();
1234 Send(new ViewMsg_GetRenderedTextCompleted(routing_id(), text));
1237 void RenderViewImpl::StartPluginIme() {
1238 IPC::Message* msg = new ViewHostMsg_StartPluginIme(routing_id());
1239 // This message can be sent during event-handling, and needs to be delivered
1240 // within that context.
1241 msg->set_unblock(true);
1242 Send(msg);
1244 #endif // defined(OS_MACOSX)
1246 #endif // ENABLE_PLUGINS
1248 void RenderViewImpl::TransferActiveWheelFlingAnimation(
1249 const blink::WebActiveWheelFlingParameters& params) {
1250 if (webview())
1251 webview()->transferActiveWheelFlingAnimation(params);
1254 bool RenderViewImpl::HasIMETextFocus() {
1255 return GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE;
1258 bool RenderViewImpl::OnMessageReceived(const IPC::Message& message) {
1259 WebFrame* main_frame = webview() ? webview()->mainFrame() : NULL;
1260 if (main_frame && main_frame->isWebLocalFrame())
1261 GetContentClient()->SetActiveURL(main_frame->document().url());
1263 ObserverListBase<RenderViewObserver>::Iterator it(&observers_);
1264 RenderViewObserver* observer;
1265 while ((observer = it.GetNext()) != NULL)
1266 if (observer->OnMessageReceived(message))
1267 return true;
1269 bool handled = true;
1270 IPC_BEGIN_MESSAGE_MAP(RenderViewImpl, message)
1271 IPC_MESSAGE_HANDLER(InputMsg_ExecuteEditCommand, OnExecuteEditCommand)
1272 IPC_MESSAGE_HANDLER(InputMsg_MoveCaret, OnMoveCaret)
1273 IPC_MESSAGE_HANDLER(InputMsg_ScrollFocusedEditableNodeIntoRect,
1274 OnScrollFocusedEditableNodeIntoRect)
1275 IPC_MESSAGE_HANDLER(InputMsg_SetEditCommandsForNextKeyEvent,
1276 OnSetEditCommandsForNextKeyEvent)
1277 IPC_MESSAGE_HANDLER(ViewMsg_CopyImageAt, OnCopyImageAt)
1278 IPC_MESSAGE_HANDLER(ViewMsg_SaveImageAt, OnSaveImageAt)
1279 IPC_MESSAGE_HANDLER(ViewMsg_Find, OnFind)
1280 IPC_MESSAGE_HANDLER(ViewMsg_StopFinding, OnStopFinding)
1281 IPC_MESSAGE_HANDLER(ViewMsg_ResetPageScale, OnResetPageScale)
1282 IPC_MESSAGE_HANDLER(ViewMsg_Zoom, OnZoom)
1283 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForLoadingURL,
1284 OnSetZoomLevelForLoadingURL)
1285 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForView,
1286 OnSetZoomLevelForView)
1287 IPC_MESSAGE_HANDLER(ViewMsg_SetPageEncoding, OnSetPageEncoding)
1288 IPC_MESSAGE_HANDLER(ViewMsg_ResetPageEncodingToDefault,
1289 OnResetPageEncodingToDefault)
1290 IPC_MESSAGE_HANDLER(ViewMsg_PostMessageEvent, OnPostMessageEvent)
1291 IPC_MESSAGE_HANDLER(DragMsg_TargetDragEnter, OnDragTargetDragEnter)
1292 IPC_MESSAGE_HANDLER(DragMsg_TargetDragOver, OnDragTargetDragOver)
1293 IPC_MESSAGE_HANDLER(DragMsg_TargetDragLeave, OnDragTargetDragLeave)
1294 IPC_MESSAGE_HANDLER(DragMsg_TargetDrop, OnDragTargetDrop)
1295 IPC_MESSAGE_HANDLER(DragMsg_SourceEnded, OnDragSourceEnded)
1296 IPC_MESSAGE_HANDLER(DragMsg_SourceSystemDragEnded,
1297 OnDragSourceSystemDragEnded)
1298 IPC_MESSAGE_HANDLER(ViewMsg_AllowBindings, OnAllowBindings)
1299 IPC_MESSAGE_HANDLER(ViewMsg_SetInitialFocus, OnSetInitialFocus)
1300 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTargetURL_ACK, OnUpdateTargetURLAck)
1301 IPC_MESSAGE_HANDLER(ViewMsg_UpdateWebPreferences, OnUpdateWebPreferences)
1302 IPC_MESSAGE_HANDLER(ViewMsg_EnumerateDirectoryResponse,
1303 OnEnumerateDirectoryResponse)
1304 IPC_MESSAGE_HANDLER(ViewMsg_RunFileChooserResponse, OnFileChooserResponse)
1305 IPC_MESSAGE_HANDLER(ViewMsg_SuppressDialogsUntilSwapOut,
1306 OnSuppressDialogsUntilSwapOut)
1307 IPC_MESSAGE_HANDLER(ViewMsg_ClosePage, OnClosePage)
1308 IPC_MESSAGE_HANDLER(ViewMsg_ThemeChanged, OnThemeChanged)
1309 IPC_MESSAGE_HANDLER(ViewMsg_MoveOrResizeStarted, OnMoveOrResizeStarted)
1310 IPC_MESSAGE_HANDLER(ViewMsg_ClearFocusedElement, OnClearFocusedElement)
1311 IPC_MESSAGE_HANDLER(ViewMsg_SetBackgroundOpaque, OnSetBackgroundOpaque)
1312 IPC_MESSAGE_HANDLER(ViewMsg_EnablePreferredSizeChangedMode,
1313 OnEnablePreferredSizeChangedMode)
1314 IPC_MESSAGE_HANDLER(ViewMsg_EnableAutoResize, OnEnableAutoResize)
1315 IPC_MESSAGE_HANDLER(ViewMsg_DisableAutoResize, OnDisableAutoResize)
1316 IPC_MESSAGE_HANDLER(ViewMsg_DisableScrollbarsForSmallWindows,
1317 OnDisableScrollbarsForSmallWindows)
1318 IPC_MESSAGE_HANDLER(ViewMsg_SetRendererPrefs, OnSetRendererPrefs)
1319 IPC_MESSAGE_HANDLER(ViewMsg_MediaPlayerActionAt, OnMediaPlayerActionAt)
1320 IPC_MESSAGE_HANDLER(ViewMsg_PluginActionAt, OnPluginActionAt)
1321 IPC_MESSAGE_HANDLER(ViewMsg_SetActive, OnSetActive)
1322 IPC_MESSAGE_HANDLER(ViewMsg_GetAllSavableResourceLinksForCurrentPage,
1323 OnGetAllSavableResourceLinksForCurrentPage)
1324 IPC_MESSAGE_HANDLER(
1325 ViewMsg_GetSerializedHtmlDataForCurrentPageWithLocalLinks,
1326 OnGetSerializedHtmlDataForCurrentPageWithLocalLinks)
1327 IPC_MESSAGE_HANDLER(ViewMsg_ShowContextMenu, OnShowContextMenu)
1328 // TODO(viettrungluu): Move to a separate message filter.
1329 IPC_MESSAGE_HANDLER(ViewMsg_SetHistoryOffsetAndLength,
1330 OnSetHistoryOffsetAndLength)
1331 IPC_MESSAGE_HANDLER(ViewMsg_EnableViewSourceMode, OnEnableViewSourceMode)
1332 IPC_MESSAGE_HANDLER(ViewMsg_ReleaseDisambiguationPopupBitmap,
1333 OnReleaseDisambiguationPopupBitmap)
1334 IPC_MESSAGE_HANDLER(ViewMsg_ForceRedraw, OnForceRedraw)
1335 IPC_MESSAGE_HANDLER(ViewMsg_SelectWordAroundCaret, OnSelectWordAroundCaret)
1336 #if defined(OS_ANDROID)
1337 IPC_MESSAGE_HANDLER(InputMsg_ActivateNearestFindResult,
1338 OnActivateNearestFindResult)
1339 IPC_MESSAGE_HANDLER(ViewMsg_FindMatchRects, OnFindMatchRects)
1340 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTopControlsState,
1341 OnUpdateTopControlsState)
1342 IPC_MESSAGE_HANDLER(ViewMsg_ExtractSmartClipData, OnExtractSmartClipData)
1343 #elif defined(OS_MACOSX)
1344 IPC_MESSAGE_HANDLER(ViewMsg_GetRenderedText,
1345 OnGetRenderedText)
1346 IPC_MESSAGE_HANDLER(ViewMsg_PluginImeCompositionCompleted,
1347 OnPluginImeCompositionCompleted)
1348 IPC_MESSAGE_HANDLER(ViewMsg_SetInLiveResize, OnSetInLiveResize)
1349 IPC_MESSAGE_HANDLER(ViewMsg_SetWindowVisibility, OnSetWindowVisibility)
1350 IPC_MESSAGE_HANDLER(ViewMsg_WindowFrameChanged, OnWindowFrameChanged)
1351 #endif
1352 // Adding a new message? Add platform independent ones first, then put the
1353 // platform specific ones at the end.
1355 // Have the super handle all other messages.
1356 IPC_MESSAGE_UNHANDLED(handled = RenderWidget::OnMessageReceived(message))
1357 IPC_END_MESSAGE_MAP()
1359 return handled;
1362 void RenderViewImpl::OnSelectWordAroundCaret() {
1363 if (!webview())
1364 return;
1366 handling_input_event_ = true;
1367 webview()->focusedFrame()->selectWordAroundCaret();
1368 handling_input_event_ = false;
1371 void RenderViewImpl::OnCopyImageAt(int x, int y) {
1372 webview()->copyImageAt(WebPoint(x, y));
1375 void RenderViewImpl::OnSaveImageAt(int x, int y) {
1376 webview()->saveImageAt(WebPoint(x, y));
1379 void RenderViewImpl::OnUpdateTargetURLAck() {
1380 // Check if there is a targeturl waiting to be sent.
1381 if (target_url_status_ == TARGET_PENDING)
1382 Send(new ViewHostMsg_UpdateTargetURL(routing_id_, pending_target_url_));
1384 target_url_status_ = TARGET_NONE;
1387 void RenderViewImpl::OnExecuteEditCommand(const std::string& name,
1388 const std::string& value) {
1389 if (!webview() || !webview()->focusedFrame())
1390 return;
1392 webview()->focusedFrame()->executeCommand(
1393 WebString::fromUTF8(name), WebString::fromUTF8(value));
1396 void RenderViewImpl::OnMoveCaret(const gfx::Point& point) {
1397 if (!webview())
1398 return;
1400 Send(new InputHostMsg_MoveCaret_ACK(routing_id_));
1402 webview()->focusedFrame()->moveCaretSelection(point);
1405 void RenderViewImpl::OnScrollFocusedEditableNodeIntoRect(
1406 const gfx::Rect& rect) {
1407 if (has_scrolled_focused_editable_node_into_rect_ &&
1408 rect == rect_for_scrolled_focused_editable_node_) {
1409 FocusChangeComplete();
1410 return;
1413 blink::WebElement element = GetFocusedElement();
1414 bool will_animate = false;
1415 if (!element.isNull() && IsEditableNode(element)) {
1416 rect_for_scrolled_focused_editable_node_ = rect;
1417 has_scrolled_focused_editable_node_into_rect_ = true;
1418 will_animate = webview()->scrollFocusedNodeIntoRect(rect);
1421 if (!will_animate)
1422 FocusChangeComplete();
1425 void RenderViewImpl::OnSetEditCommandsForNextKeyEvent(
1426 const EditCommands& edit_commands) {
1427 edit_commands_ = edit_commands;
1430 void RenderViewImpl::OnSetHistoryOffsetAndLength(int history_offset,
1431 int history_length) {
1432 DCHECK_GE(history_offset, -1);
1433 DCHECK_GE(history_length, 0);
1435 history_list_offset_ = history_offset;
1436 history_list_length_ = history_length;
1439 void RenderViewImpl::OnSetInitialFocus(bool reverse) {
1440 if (!webview())
1441 return;
1442 webview()->setInitialFocus(reverse);
1445 #if defined(OS_MACOSX)
1446 void RenderViewImpl::OnSetInLiveResize(bool in_live_resize) {
1447 if (!webview())
1448 return;
1449 if (in_live_resize)
1450 webview()->willStartLiveResize();
1451 else
1452 webview()->willEndLiveResize();
1454 #endif
1456 ///////////////////////////////////////////////////////////////////////////////
1458 // Sends the current history state to the browser so it will be saved before we
1459 // navigate to a new page.
1460 void RenderViewImpl::UpdateSessionHistory(WebFrame* frame) {
1461 // If we have a valid page ID at this point, then it corresponds to the page
1462 // we are navigating away from. Otherwise, this is the first navigation, so
1463 // there is no past session history to record.
1464 if (page_id_ == -1)
1465 return;
1466 SendUpdateState(history_controller_->GetCurrentEntry());
1469 void RenderViewImpl::SendUpdateState(HistoryEntry* entry) {
1470 if (!entry)
1471 return;
1473 // Don't send state updates for kSwappedOutURL.
1474 if (entry->root().urlString() == WebString::fromUTF8(kSwappedOutURL))
1475 return;
1477 Send(new ViewHostMsg_UpdateState(
1478 routing_id_, page_id_, HistoryEntryToPageState(entry)));
1481 bool RenderViewImpl::SendAndRunNestedMessageLoop(IPC::SyncMessage* message) {
1482 // Before WebKit asks us to show an alert (etc.), it takes care of doing the
1483 // equivalent of WebView::willEnterModalLoop. In the case of showModalDialog
1484 // it is particularly important that we do not call willEnterModalLoop as
1485 // that would defer resource loads for the dialog itself.
1486 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
1487 RenderThreadImpl::current()->DoNotNotifyWebKitOfModalLoop();
1489 message->EnableMessagePumping(); // Runs a nested message loop.
1490 return Send(message);
1493 void RenderViewImpl::OnForceRedraw(int id) {
1494 ui::LatencyInfo latency_info;
1495 if (id) {
1496 latency_info.AddLatencyNumber(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
1498 id);
1500 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1501 if (RenderWidgetCompositor* rwc = compositor()) {
1502 latency_info_swap_promise_monitor =
1503 rwc->CreateLatencyInfoSwapPromiseMonitor(&latency_info).Pass();
1505 ScheduleCompositeWithForcedRedraw();
1508 // blink::WebViewClient ------------------------------------------------------
1510 WebView* RenderViewImpl::createView(WebLocalFrame* creator,
1511 const WebURLRequest& request,
1512 const WebWindowFeatures& features,
1513 const WebString& frame_name,
1514 WebNavigationPolicy policy,
1515 bool suppress_opener) {
1516 ViewHostMsg_CreateWindow_Params params;
1517 params.opener_id = routing_id_;
1518 params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
1519 if (GetContentClient()->renderer()->AllowPopup())
1520 params.user_gesture = true;
1521 params.window_container_type = WindowFeaturesToContainerType(features);
1522 params.session_storage_namespace_id = session_storage_namespace_id_;
1523 if (frame_name != "_blank")
1524 params.frame_name = frame_name;
1525 params.opener_render_frame_id =
1526 RenderFrameImpl::FromWebFrame(creator)->GetRoutingID();
1527 params.opener_url = creator->document().url();
1528 params.opener_top_level_frame_url = creator->top()->document().url();
1529 GURL security_url(creator->document().securityOrigin().toString());
1530 if (!security_url.is_valid())
1531 security_url = GURL();
1532 params.opener_security_origin = security_url;
1533 params.opener_suppressed = suppress_opener;
1534 params.disposition = NavigationPolicyToDisposition(policy);
1535 if (!request.isNull()) {
1536 params.target_url = request.url();
1537 params.referrer = GetReferrerFromRequest(creator, request);
1539 params.features = features;
1541 for (size_t i = 0; i < features.additionalFeatures.size(); ++i)
1542 params.additional_features.push_back(features.additionalFeatures[i]);
1544 int32 routing_id = MSG_ROUTING_NONE;
1545 int32 main_frame_routing_id = MSG_ROUTING_NONE;
1546 int32 surface_id = 0;
1547 int64 cloned_session_storage_namespace_id = 0;
1549 RenderThread::Get()->Send(new ViewHostMsg_CreateWindow(
1550 params, &routing_id, &main_frame_routing_id, &surface_id,
1551 &cloned_session_storage_namespace_id));
1552 if (routing_id == MSG_ROUTING_NONE)
1553 return NULL;
1555 WebUserGestureIndicator::consumeUserGesture();
1557 // While this view may be a background extension page, it can spawn a visible
1558 // render view. So we just assume that the new one is not another background
1559 // page instead of passing on our own value.
1560 // TODO(vangelis): Can we tell if the new view will be a background page?
1561 bool never_visible = false;
1563 ViewMsg_Resize_Params initial_size = ViewMsg_Resize_Params();
1564 initial_size.screen_info = screen_info_;
1566 // The initial hidden state for the RenderViewImpl here has to match what the
1567 // browser will eventually decide for the given disposition. Since we have to
1568 // return from this call synchronously, we just have to make our best guess
1569 // and rely on the browser sending a WasHidden / WasShown message if it
1570 // disagrees.
1571 ViewMsg_New_Params view_params;
1572 view_params.opener_route_id = routing_id_;
1573 view_params.window_was_created_with_opener = true;
1574 view_params.renderer_preferences = renderer_preferences_;
1575 view_params.web_preferences = webkit_preferences_;
1576 view_params.view_id = routing_id;
1577 view_params.main_frame_routing_id = main_frame_routing_id;
1578 view_params.surface_id = surface_id;
1579 view_params.session_storage_namespace_id =
1580 cloned_session_storage_namespace_id;
1581 // WebCore will take care of setting the correct name.
1582 view_params.frame_name = base::string16();
1583 view_params.swapped_out = false;
1584 view_params.replicated_frame_state = FrameReplicationState();
1585 view_params.proxy_routing_id = MSG_ROUTING_NONE;
1586 view_params.hidden = (params.disposition == NEW_BACKGROUND_TAB);
1587 view_params.never_visible = never_visible;
1588 view_params.next_page_id = 1;
1589 view_params.initial_size = initial_size;
1590 view_params.enable_auto_resize = false;
1591 view_params.min_size = gfx::Size();
1592 view_params.max_size = gfx::Size();
1594 RenderViewImpl* view =
1595 RenderViewImpl::Create(view_params, compositor_deps_, true);
1596 view->opened_by_user_gesture_ = params.user_gesture;
1598 // Record whether the creator frame is trying to suppress the opener field.
1599 view->opener_suppressed_ = params.opener_suppressed;
1601 return view->webview();
1604 WebWidget* RenderViewImpl::createPopupMenu(blink::WebPopupType popup_type) {
1605 RenderWidget* widget = RenderWidget::Create(routing_id_, compositor_deps_,
1606 popup_type, screen_info_);
1607 if (!widget)
1608 return NULL;
1609 if (screen_metrics_emulator_) {
1610 widget->SetPopupOriginAdjustmentsForEmulation(
1611 screen_metrics_emulator_.get());
1613 return widget->webwidget();
1616 WebStorageNamespace* RenderViewImpl::createSessionStorageNamespace() {
1617 CHECK(session_storage_namespace_id_ != kInvalidSessionStorageNamespaceId);
1618 return new WebStorageNamespaceImpl(session_storage_namespace_id_);
1621 void RenderViewImpl::printPage(WebLocalFrame* frame) {
1622 FOR_EACH_OBSERVER(RenderViewObserver, observers_,
1623 PrintPage(frame, handling_input_event_));
1626 void RenderViewImpl::saveImageFromDataURL(const blink::WebString& data_url) {
1627 // Note: We should basically send GURL but we use size-limited string instead
1628 // in order to send a larger data url to save a image for <canvas> or <img>.
1629 if (data_url.length() < kMaxLengthOfDataURLString)
1630 Send(new ViewHostMsg_SaveImageFromDataURL(routing_id_, data_url.utf8()));
1633 bool RenderViewImpl::enumerateChosenDirectory(
1634 const WebString& path,
1635 WebFileChooserCompletion* chooser_completion) {
1636 int id = enumeration_completion_id_++;
1637 enumeration_completions_[id] = chooser_completion;
1638 return Send(new ViewHostMsg_EnumerateDirectory(
1639 routing_id_,
1641 base::FilePath::FromUTF16Unsafe(path)));
1644 void RenderViewImpl::FrameDidStartLoading(WebFrame* frame) {
1645 DCHECK_GE(frames_in_progress_, 0);
1646 if (frames_in_progress_ == 0)
1647 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStartLoading());
1648 frames_in_progress_++;
1651 void RenderViewImpl::FrameDidStopLoading(WebFrame* frame) {
1652 // TODO(japhet): This should be a DCHECK, but the pdf plugin sometimes
1653 // calls DidStopLoading() without a matching DidStartLoading().
1654 if (frames_in_progress_ == 0)
1655 return;
1656 frames_in_progress_--;
1657 if (frames_in_progress_ == 0) {
1658 DidStopLoadingIcons();
1659 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStopLoading());
1663 void RenderViewImpl::didCancelCompositionOnSelectionChange() {
1664 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
1667 bool RenderViewImpl::handleCurrentKeyboardEvent() {
1668 if (edit_commands_.empty())
1669 return false;
1671 WebFrame* frame = webview()->focusedFrame();
1672 if (!frame)
1673 return false;
1675 EditCommands::iterator it = edit_commands_.begin();
1676 EditCommands::iterator end = edit_commands_.end();
1678 bool did_execute_command = false;
1679 for (; it != end; ++it) {
1680 // In gtk and cocoa, it's possible to bind multiple edit commands to one
1681 // key (but it's the exception). Once one edit command is not executed, it
1682 // seems safest to not execute the rest.
1683 if (!frame->executeCommand(WebString::fromUTF8(it->name),
1684 WebString::fromUTF8(it->value),
1685 GetFocusedElement()))
1686 break;
1687 did_execute_command = true;
1690 return did_execute_command;
1693 bool RenderViewImpl::runFileChooser(
1694 const blink::WebFileChooserParams& params,
1695 WebFileChooserCompletion* chooser_completion) {
1696 // Do not open the file dialog in a hidden RenderView.
1697 if (is_hidden())
1698 return false;
1699 FileChooserParams ipc_params;
1700 if (params.directory)
1701 ipc_params.mode = FileChooserParams::UploadFolder;
1702 else if (params.multiSelect)
1703 ipc_params.mode = FileChooserParams::OpenMultiple;
1704 else if (params.saveAs)
1705 ipc_params.mode = FileChooserParams::Save;
1706 else
1707 ipc_params.mode = FileChooserParams::Open;
1708 ipc_params.title = params.title;
1709 ipc_params.default_file_name =
1710 base::FilePath::FromUTF16Unsafe(params.initialValue).BaseName();
1711 ipc_params.accept_types.reserve(params.acceptTypes.size());
1712 for (size_t i = 0; i < params.acceptTypes.size(); ++i)
1713 ipc_params.accept_types.push_back(params.acceptTypes[i]);
1714 ipc_params.need_local_path = params.needLocalPath;
1715 #if defined(OS_ANDROID)
1716 ipc_params.capture = params.useMediaCapture;
1717 #endif
1719 return ScheduleFileChooser(ipc_params, chooser_completion);
1722 void RenderViewImpl::SetValidationMessageDirection(
1723 base::string16* wrapped_main_text,
1724 blink::WebTextDirection main_text_hint,
1725 base::string16* wrapped_sub_text,
1726 blink::WebTextDirection sub_text_hint) {
1727 if (main_text_hint == blink::WebTextDirectionLeftToRight) {
1728 *wrapped_main_text =
1729 base::i18n::GetDisplayStringInLTRDirectionality(*wrapped_main_text);
1730 } else if (main_text_hint == blink::WebTextDirectionRightToLeft &&
1731 !base::i18n::IsRTL()) {
1732 base::i18n::WrapStringWithRTLFormatting(wrapped_main_text);
1735 if (!wrapped_sub_text->empty()) {
1736 if (sub_text_hint == blink::WebTextDirectionLeftToRight) {
1737 *wrapped_sub_text =
1738 base::i18n::GetDisplayStringInLTRDirectionality(*wrapped_sub_text);
1739 } else if (sub_text_hint == blink::WebTextDirectionRightToLeft) {
1740 base::i18n::WrapStringWithRTLFormatting(wrapped_sub_text);
1745 void RenderViewImpl::showValidationMessage(
1746 const blink::WebRect& anchor_in_root_view,
1747 const blink::WebString& main_text,
1748 blink::WebTextDirection main_text_hint,
1749 const blink::WebString& sub_text,
1750 blink::WebTextDirection sub_text_hint) {
1751 base::string16 wrapped_main_text = main_text;
1752 base::string16 wrapped_sub_text = sub_text;
1754 SetValidationMessageDirection(
1755 &wrapped_main_text, main_text_hint, &wrapped_sub_text, sub_text_hint);
1757 Send(new ViewHostMsg_ShowValidationMessage(
1758 routing_id(), AdjustValidationMessageAnchor(anchor_in_root_view),
1759 wrapped_main_text, wrapped_sub_text));
1762 void RenderViewImpl::hideValidationMessage() {
1763 Send(new ViewHostMsg_HideValidationMessage(routing_id()));
1766 void RenderViewImpl::moveValidationMessage(
1767 const blink::WebRect& anchor_in_root_view) {
1768 Send(new ViewHostMsg_MoveValidationMessage(
1769 routing_id(), AdjustValidationMessageAnchor(anchor_in_root_view)));
1772 void RenderViewImpl::setStatusText(const WebString& text) {
1775 void RenderViewImpl::UpdateTargetURL(const GURL& url,
1776 const GURL& fallback_url) {
1777 GURL latest_url = url.is_empty() ? fallback_url : url;
1778 if (latest_url == target_url_)
1779 return;
1781 // Tell the browser to display a destination link.
1782 if (target_url_status_ == TARGET_INFLIGHT ||
1783 target_url_status_ == TARGET_PENDING) {
1784 // If we have a request in-flight, save the URL to be sent when we
1785 // receive an ACK to the in-flight request. We can happily overwrite
1786 // any existing pending sends.
1787 pending_target_url_ = latest_url;
1788 target_url_status_ = TARGET_PENDING;
1789 } else {
1790 // URLs larger than |MaxURLChars()| cannot be sent through IPC -
1791 // see |ParamTraits<GURL>|.
1792 if (latest_url.possibly_invalid_spec().size() > GetMaxURLChars())
1793 latest_url = GURL();
1794 Send(new ViewHostMsg_UpdateTargetURL(routing_id_, latest_url));
1795 target_url_ = latest_url;
1796 target_url_status_ = TARGET_INFLIGHT;
1800 gfx::RectF RenderViewImpl::ClientRectToPhysicalWindowRect(
1801 const gfx::RectF& rect) const {
1802 gfx::RectF window_rect = rect;
1803 window_rect.Scale(device_scale_factor_ * webview()->pageScaleFactor());
1804 return window_rect;
1807 void RenderViewImpl::StartNavStateSyncTimerIfNecessary() {
1808 // No need to update state if no page has committed yet.
1809 if (page_id_ == -1)
1810 return;
1812 int delay;
1813 if (send_content_state_immediately_)
1814 delay = 0;
1815 else if (is_hidden())
1816 delay = kDelaySecondsForContentStateSyncHidden;
1817 else
1818 delay = kDelaySecondsForContentStateSync;
1820 if (nav_state_sync_timer_.IsRunning()) {
1821 // The timer is already running. If the delay of the timer maches the amount
1822 // we want to delay by, then return. Otherwise stop the timer so that it
1823 // gets started with the right delay.
1824 if (nav_state_sync_timer_.GetCurrentDelay().InSeconds() == delay)
1825 return;
1826 nav_state_sync_timer_.Stop();
1829 nav_state_sync_timer_.Start(FROM_HERE, TimeDelta::FromSeconds(delay), this,
1830 &RenderViewImpl::SyncNavigationState);
1833 void RenderViewImpl::setMouseOverURL(const WebURL& url) {
1834 mouse_over_url_ = GURL(url);
1835 UpdateTargetURL(mouse_over_url_, focus_url_);
1838 void RenderViewImpl::setKeyboardFocusURL(const WebURL& url) {
1839 focus_url_ = GURL(url);
1840 UpdateTargetURL(focus_url_, mouse_over_url_);
1843 void RenderViewImpl::startDragging(WebLocalFrame* frame,
1844 const WebDragData& data,
1845 WebDragOperationsMask mask,
1846 const WebImage& image,
1847 const WebPoint& webImageOffset) {
1848 DropData drop_data(DropDataBuilder::Build(data));
1849 drop_data.referrer_policy = frame->document().referrerPolicy();
1850 gfx::Vector2d imageOffset(webImageOffset.x, webImageOffset.y);
1851 Send(new DragHostMsg_StartDragging(routing_id_,
1852 drop_data,
1853 mask,
1854 image.getSkBitmap(),
1855 imageOffset,
1856 possible_drag_event_info_));
1859 bool RenderViewImpl::acceptsLoadDrops() {
1860 return renderer_preferences_.can_accept_load_drops;
1863 void RenderViewImpl::focusNext() {
1864 Send(new ViewHostMsg_TakeFocus(routing_id_, false));
1867 void RenderViewImpl::focusPrevious() {
1868 Send(new ViewHostMsg_TakeFocus(routing_id_, true));
1871 void RenderViewImpl::focusedNodeChanged(const WebNode& fromNode,
1872 const WebNode& toNode) {
1873 has_scrolled_focused_editable_node_into_rect_ = false;
1875 gfx::Rect node_bounds;
1876 if (!toNode.isNull() && toNode.isElementNode()) {
1877 WebNode web_node = const_cast<WebNode&>(toNode);
1878 node_bounds = gfx::Rect(web_node.to<WebElement>().boundsInViewportSpace());
1880 Send(new ViewHostMsg_FocusedNodeChanged(routing_id_, IsEditableNode(toNode),
1881 node_bounds));
1883 // TODO(estade): remove.
1884 FOR_EACH_OBSERVER(RenderViewObserver, observers_, FocusedNodeChanged(toNode));
1886 RenderFrameImpl* previous_frame = nullptr;
1887 if (!fromNode.isNull())
1888 previous_frame = RenderFrameImpl::FromWebFrame(fromNode.document().frame());
1889 RenderFrameImpl* new_frame = nullptr;
1890 if (!toNode.isNull())
1891 new_frame = RenderFrameImpl::FromWebFrame(toNode.document().frame());
1893 if (previous_frame && previous_frame != new_frame)
1894 previous_frame->FocusedNodeChanged(WebNode());
1895 if (new_frame)
1896 new_frame->FocusedNodeChanged(toNode);
1898 // TODO(dmazzoni): remove once there's a separate a11y tree per frame.
1899 GetMainRenderFrame()->FocusedNodeChangedForAccessibility(toNode);
1902 void RenderViewImpl::didUpdateLayout() {
1903 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidUpdateLayout());
1905 // We don't always want to set up a timer, only if we've been put in that
1906 // mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
1907 // message.
1908 if (!send_preferred_size_changes_ || !webview())
1909 return;
1911 if (check_preferred_size_timer_.IsRunning())
1912 return;
1913 check_preferred_size_timer_.Start(FROM_HERE,
1914 TimeDelta::FromMilliseconds(0), this,
1915 &RenderViewImpl::CheckPreferredSize);
1918 void RenderViewImpl::navigateBackForwardSoon(int offset) {
1919 Send(new ViewHostMsg_GoToEntryAtOffset(routing_id_, offset));
1922 int RenderViewImpl::historyBackListCount() {
1923 return history_list_offset_ < 0 ? 0 : history_list_offset_;
1926 int RenderViewImpl::historyForwardListCount() {
1927 return history_list_length_ - historyBackListCount() - 1;
1930 // blink::WebWidgetClient ----------------------------------------------------
1932 void RenderViewImpl::didFocus() {
1933 // TODO(jcivelli): when https://bugs.webkit.org/show_bug.cgi?id=33389 is fixed
1934 // we won't have to test for user gesture anymore and we can
1935 // move that code back to render_widget.cc
1936 if (WebUserGestureIndicator::isProcessingUserGesture() &&
1937 !RenderThreadImpl::current()->layout_test_mode()) {
1938 Send(new ViewHostMsg_Focus(routing_id_));
1942 void RenderViewImpl::didBlur() {
1943 // TODO(jcivelli): see TODO above in didFocus().
1944 if (WebUserGestureIndicator::isProcessingUserGesture() &&
1945 !RenderThreadImpl::current()->layout_test_mode()) {
1946 Send(new ViewHostMsg_Blur(routing_id_));
1950 // We are supposed to get a single call to Show for a newly created RenderView
1951 // that was created via RenderViewImpl::CreateWebView. So, we wait until this
1952 // point to dispatch the ShowView message.
1954 // This method provides us with the information about how to display the newly
1955 // created RenderView (i.e., as a blocked popup or as a new tab).
1957 void RenderViewImpl::show(WebNavigationPolicy policy) {
1958 if (did_show_) {
1959 // When supports_multiple_windows is disabled, popups are reusing
1960 // the same view. In some scenarios, this makes WebKit to call show() twice.
1961 if (webkit_preferences_.supports_multiple_windows)
1962 NOTREACHED() << "received extraneous Show call";
1963 return;
1965 did_show_ = true;
1967 DCHECK(opener_id_ != MSG_ROUTING_NONE);
1969 // NOTE: initial_rect_ may still have its default values at this point, but
1970 // that's okay. It'll be ignored if disposition is not NEW_POPUP, or the
1971 // browser process will impose a default position otherwise.
1972 Send(new ViewHostMsg_ShowView(opener_id_, routing_id_,
1973 NavigationPolicyToDisposition(policy), initial_rect_,
1974 opened_by_user_gesture_));
1975 SetPendingWindowRect(initial_rect_);
1978 bool RenderViewImpl::requestPointerLock() {
1979 return mouse_lock_dispatcher_->LockMouse(webwidget_mouse_lock_target_.get());
1982 void RenderViewImpl::requestPointerUnlock() {
1983 mouse_lock_dispatcher_->UnlockMouse(webwidget_mouse_lock_target_.get());
1986 bool RenderViewImpl::isPointerLocked() {
1987 return mouse_lock_dispatcher_->IsMouseLockedTo(
1988 webwidget_mouse_lock_target_.get());
1991 void RenderViewImpl::didHandleGestureEvent(
1992 const WebGestureEvent& event,
1993 bool event_cancelled) {
1994 RenderWidget::didHandleGestureEvent(event, event_cancelled);
1996 if (!event_cancelled) {
1997 FOR_EACH_OBSERVER(
1998 RenderViewObserver, observers_, DidHandleGestureEvent(event));
2001 // TODO(ananta): Piggyback off existing IPCs to communicate this information,
2002 // crbug/420130.
2003 #if defined(OS_WIN)
2004 if (event.type != blink::WebGestureEvent::GestureTap)
2005 return;
2007 // TODO(estade): hit test the event against focused node to make sure
2008 // the tap actually hit the focused node.
2009 blink::WebTextInputType text_input_type =
2010 GetWebView()->textInputInfo().type;
2012 Send(new ViewHostMsg_FocusedNodeTouched(
2013 routing_id(), text_input_type != blink::WebTextInputTypeNone));
2014 #endif
2017 void RenderViewImpl::initializeLayerTreeView() {
2018 RenderWidget::initializeLayerTreeView();
2019 RenderWidgetCompositor* rwc = compositor();
2020 if (!rwc)
2021 return;
2022 if (webview() && webview()->devToolsAgent())
2023 webview()->devToolsAgent()->setLayerTreeId(rwc->GetLayerTreeId());
2025 bool use_threaded_event_handling = true;
2026 #if defined(OS_MACOSX) && !defined(OS_IOS)
2027 // Disable threaded event handling if content is not handling the elastic
2028 // overscroll effect. This includes the cases where the elastic overscroll
2029 // effect is being handled by Blink (because of command line flags) and older
2030 // operating system versions which do not have an elastic overscroll effect
2031 // (SnowLeopard, which has Aqua scrollbars which need synchronous updates).
2032 use_threaded_event_handling = compositor_deps_->IsElasticOverscrollEnabled();
2033 #endif
2034 if (use_threaded_event_handling) {
2035 RenderThreadImpl* render_thread = RenderThreadImpl::current();
2036 // render_thread may be NULL in tests.
2037 InputHandlerManager* input_handler_manager =
2038 render_thread ? render_thread->input_handler_manager() : NULL;
2039 if (input_handler_manager) {
2040 input_handler_manager->AddInputHandler(
2041 routing_id_, rwc->GetInputHandler(), AsWeakPtr());
2046 // blink::WebFrameClient -----------------------------------------------------
2048 void RenderViewImpl::Repaint(const gfx::Size& size) {
2049 OnRepaint(size);
2052 void RenderViewImpl::SetEditCommandForNextKeyEvent(const std::string& name,
2053 const std::string& value) {
2054 EditCommands edit_commands;
2055 edit_commands.push_back(EditCommand(name, value));
2056 OnSetEditCommandsForNextKeyEvent(edit_commands);
2059 void RenderViewImpl::ClearEditCommands() {
2060 edit_commands_.clear();
2063 SSLStatus RenderViewImpl::GetSSLStatusOfFrame(blink::WebFrame* frame) const {
2064 std::string security_info;
2065 if (frame && frame->dataSource())
2066 security_info = frame->dataSource()->response().securityInfo();
2068 SSLStatus ssl_status;
2069 DeserializeSecurityInfo(security_info,
2070 &ssl_status.cert_id,
2071 &ssl_status.cert_status,
2072 &ssl_status.security_bits,
2073 &ssl_status.connection_status,
2074 &ssl_status.signed_certificate_timestamp_ids);
2075 return ssl_status;
2078 const std::string& RenderViewImpl::GetAcceptLanguages() const {
2079 return renderer_preferences_.accept_languages;
2082 void RenderViewImpl::didCreateDataSource(WebLocalFrame* frame,
2083 WebDataSource* ds) {
2084 bool content_initiated = !pending_navigation_params_.get();
2086 // Make sure any previous redirect URLs end up in our new data source.
2087 if (pending_navigation_params_.get()) {
2088 for (std::vector<GURL>::const_iterator i =
2089 pending_navigation_params_->commit_params.redirects.begin();
2090 i != pending_navigation_params_->commit_params.redirects.end(); ++i) {
2091 ds->appendRedirect(*i);
2095 DocumentState* document_state = DocumentState::FromDataSource(ds);
2096 if (!document_state) {
2097 document_state = new DocumentState;
2098 ds->setExtraData(document_state);
2099 if (!content_initiated)
2100 PopulateDocumentStateFromPending(document_state);
2103 // Carry over the user agent override flag, if it exists.
2104 if (content_initiated && webview() && webview()->mainFrame() &&
2105 webview()->mainFrame()->isWebLocalFrame() &&
2106 webview()->mainFrame()->dataSource()) {
2107 DocumentState* old_document_state =
2108 DocumentState::FromDataSource(webview()->mainFrame()->dataSource());
2109 if (old_document_state) {
2110 InternalDocumentStateData* internal_data =
2111 InternalDocumentStateData::FromDocumentState(document_state);
2112 InternalDocumentStateData* old_internal_data =
2113 InternalDocumentStateData::FromDocumentState(old_document_state);
2114 internal_data->set_is_overriding_user_agent(
2115 old_internal_data->is_overriding_user_agent());
2119 // The rest of RenderView assumes that a WebDataSource will always have a
2120 // non-null NavigationState.
2121 if (content_initiated) {
2122 document_state->set_navigation_state(
2123 NavigationState::CreateContentInitiated());
2124 } else {
2125 document_state->set_navigation_state(CreateNavigationStateFromPending());
2126 pending_navigation_params_.reset();
2129 // DocumentState::referred_by_prefetcher_ is true if we are
2130 // navigating from a page that used prefetching using a link on that
2131 // page. We are early enough in the request process here that we
2132 // can still see the DocumentState of the previous page and set
2133 // this value appropriately.
2134 // TODO(gavinp): catch the important case of navigation in a new
2135 // renderer process.
2136 if (webview()) {
2137 if (WebFrame* old_frame = webview()->mainFrame()) {
2138 const WebURLRequest& original_request = ds->originalRequest();
2139 const GURL referrer(
2140 original_request.httpHeaderField(WebString::fromUTF8("Referer")));
2141 if (!referrer.is_empty() && old_frame->isWebLocalFrame() &&
2142 DocumentState::FromDataSource(old_frame->dataSource())
2143 ->was_prefetcher()) {
2144 for (; old_frame; old_frame = old_frame->traverseNext(false)) {
2145 WebDataSource* old_frame_ds = old_frame->dataSource();
2146 if (old_frame_ds && referrer == GURL(old_frame_ds->request().url())) {
2147 document_state->set_was_referred_by_prefetcher(true);
2148 break;
2155 if (content_initiated) {
2156 const WebURLRequest& request = ds->request();
2157 switch (request.cachePolicy()) {
2158 case WebURLRequest::UseProtocolCachePolicy: // normal load.
2159 document_state->set_load_type(DocumentState::LINK_LOAD_NORMAL);
2160 break;
2161 case WebURLRequest::ReloadIgnoringCacheData: // reload.
2162 case WebURLRequest::ReloadBypassingCache: // end-to-end reload.
2163 document_state->set_load_type(DocumentState::LINK_LOAD_RELOAD);
2164 break;
2165 case WebURLRequest::ReturnCacheDataElseLoad: // allow stale data.
2166 document_state->set_load_type(
2167 DocumentState::LINK_LOAD_CACHE_STALE_OK);
2168 break;
2169 case WebURLRequest::ReturnCacheDataDontLoad: // Don't re-post.
2170 document_state->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY);
2171 break;
2172 default:
2173 NOTREACHED();
2177 FOR_EACH_OBSERVER(
2178 RenderViewObserver, observers_, DidCreateDataSource(frame, ds));
2181 void RenderViewImpl::PopulateDocumentStateFromPending(
2182 DocumentState* document_state) {
2183 document_state->set_request_time(
2184 pending_navigation_params_->commit_params.request_time);
2186 InternalDocumentStateData* internal_data =
2187 InternalDocumentStateData::FromDocumentState(document_state);
2189 if (!pending_navigation_params_->common_params.url.SchemeIs(
2190 url::kJavaScriptScheme) &&
2191 pending_navigation_params_->common_params.navigation_type ==
2192 FrameMsg_Navigate_Type::RESTORE) {
2193 // We're doing a load of a page that was restored from the last session. By
2194 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
2195 // can result in stale data for pages that are set to expire. We explicitly
2196 // override that by setting the policy here so that as necessary we load
2197 // from the network.
2199 // TODO(davidben): Remove this in favor of passing a cache policy to the
2200 // loadHistoryItem call in OnNavigate. That requires not overloading
2201 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
2202 // policy based on load type, etc".
2203 internal_data->set_cache_policy_override(
2204 WebURLRequest::UseProtocolCachePolicy);
2207 if (IsReload(pending_navigation_params_->common_params.navigation_type))
2208 document_state->set_load_type(DocumentState::RELOAD);
2209 else if (pending_navigation_params_->history_params.page_state.IsValid())
2210 document_state->set_load_type(DocumentState::HISTORY_LOAD);
2211 else
2212 document_state->set_load_type(DocumentState::NORMAL_LOAD);
2214 internal_data->set_is_overriding_user_agent(
2215 pending_navigation_params_->commit_params.is_overriding_user_agent);
2216 internal_data->set_must_reset_scroll_and_scale_state(
2217 pending_navigation_params_->common_params.navigation_type ==
2218 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
2219 document_state->set_can_load_local_resources(
2220 pending_navigation_params_->commit_params.can_load_local_resources);
2223 NavigationState* RenderViewImpl::CreateNavigationStateFromPending() {
2224 NavigationState* navigation_state = NULL;
2226 // A navigation resulting from loading a javascript URL should not be treated
2227 // as a browser initiated event. Instead, we want it to look as if the page
2228 // initiated any load resulting from JS execution.
2229 if (!pending_navigation_params_->common_params.url.SchemeIs(
2230 url::kJavaScriptScheme)) {
2231 navigation_state = NavigationState::CreateBrowserInitiated(
2232 pending_navigation_params_->history_params.page_id,
2233 pending_navigation_params_->history_params.pending_history_list_offset,
2234 pending_navigation_params_->history_params.should_clear_history_list,
2235 pending_navigation_params_->common_params.transition);
2236 navigation_state->set_allow_download(
2237 pending_navigation_params_->common_params.allow_download);
2238 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
2239 switches::kEnableBrowserSideNavigation)) {
2240 navigation_state->set_should_replace_current_entry(
2241 pending_navigation_params_->start_params
2242 .should_replace_current_entry);
2243 navigation_state->set_transferred_request_child_id(
2244 pending_navigation_params_->start_params
2245 .transferred_request_child_id);
2246 navigation_state->set_transferred_request_request_id(
2247 pending_navigation_params_->start_params
2248 .transferred_request_request_id);
2249 navigation_state->set_extra_headers(
2250 pending_navigation_params_->start_params.extra_headers);
2252 } else {
2253 navigation_state = NavigationState::CreateContentInitiated();
2255 return navigation_state;
2258 void RenderViewImpl::didChangeIcon(WebLocalFrame* frame,
2259 WebIconURL::Type icon_type) {
2260 if (frame->parent())
2261 return;
2263 WebVector<WebIconURL> icon_urls = frame->iconURLs(icon_type);
2264 std::vector<FaviconURL> urls;
2265 for (size_t i = 0; i < icon_urls.size(); i++) {
2266 std::vector<gfx::Size> sizes;
2267 ConvertToFaviconSizes(icon_urls[i].sizes(), &sizes);
2268 urls.push_back(FaviconURL(
2269 icon_urls[i].iconURL(), ToFaviconType(icon_urls[i].iconType()), sizes));
2271 SendUpdateFaviconURL(urls);
2274 void RenderViewImpl::didUpdateCurrentHistoryItem(WebLocalFrame* frame) {
2275 StartNavStateSyncTimerIfNecessary();
2278 void RenderViewImpl::CheckPreferredSize() {
2279 // We don't always want to send the change messages over IPC, only if we've
2280 // been put in that mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
2281 // message.
2282 if (!send_preferred_size_changes_ || !webview())
2283 return;
2285 gfx::Size size = webview()->contentsPreferredMinimumSize();
2286 if (size == preferred_size_)
2287 return;
2289 preferred_size_ = size;
2290 Send(new ViewHostMsg_DidContentsPreferredSizeChange(routing_id_,
2291 preferred_size_));
2294 void RenderViewImpl::didChangeScrollOffset(WebLocalFrame* frame) {
2295 StartNavStateSyncTimerIfNecessary();
2298 void RenderViewImpl::SendFindReply(int request_id,
2299 int match_count,
2300 int ordinal,
2301 const WebRect& selection_rect,
2302 bool final_status_update) {
2303 Send(new ViewHostMsg_Find_Reply(routing_id_,
2304 request_id,
2305 match_count,
2306 selection_rect,
2307 ordinal,
2308 final_status_update));
2311 blink::WebString RenderViewImpl::acceptLanguages() {
2312 return WebString::fromUTF8(renderer_preferences_.accept_languages);
2315 // blink::WebPageSerializerClient implementation ------------------------------
2317 void RenderViewImpl::didSerializeDataForFrame(
2318 const WebURL& frame_url,
2319 const WebCString& data,
2320 WebPageSerializerClient::PageSerializationStatus status) {
2321 Send(new ViewHostMsg_SendSerializedHtmlData(
2322 routing_id(),
2323 frame_url,
2324 data.data(),
2325 static_cast<int32>(status)));
2328 // RenderView implementation ---------------------------------------------------
2330 bool RenderViewImpl::Send(IPC::Message* message) {
2331 return RenderWidget::Send(message);
2334 RenderFrameImpl* RenderViewImpl::GetMainRenderFrame() {
2335 return main_render_frame_.get();
2338 int RenderViewImpl::GetRoutingID() const {
2339 return routing_id_;
2342 gfx::Size RenderViewImpl::GetSize() const {
2343 return size();
2346 WebPreferences& RenderViewImpl::GetWebkitPreferences() {
2347 return webkit_preferences_;
2350 void RenderViewImpl::SetWebkitPreferences(const WebPreferences& preferences) {
2351 OnUpdateWebPreferences(preferences);
2354 blink::WebView* RenderViewImpl::GetWebView() {
2355 return webview();
2358 bool RenderViewImpl::IsEditableNode(const WebNode& node) const {
2359 if (node.isNull())
2360 return false;
2362 if (node.isContentEditable())
2363 return true;
2365 if (node.isElementNode()) {
2366 const WebElement& element = node.toConst<WebElement>();
2367 if (element.isTextFormControlElement()) {
2368 if (!(element.hasAttribute("readonly") ||
2369 element.hasAttribute("disabled")))
2370 return true;
2373 // Also return true if it has an ARIA role of 'textbox'.
2374 for (unsigned i = 0; i < element.attributeCount(); ++i) {
2375 if (LowerCaseEqualsASCII(element.attributeLocalName(i), "role")) {
2376 if (LowerCaseEqualsASCII(element.attributeValue(i), "textbox"))
2377 return true;
2378 break;
2383 return false;
2386 bool RenderViewImpl::ShouldDisplayScrollbars(int width, int height) const {
2387 return (!send_preferred_size_changes_ ||
2388 (disable_scrollbars_size_limit_.width() <= width ||
2389 disable_scrollbars_size_limit_.height() <= height));
2392 int RenderViewImpl::GetEnabledBindings() const {
2393 return enabled_bindings_;
2396 bool RenderViewImpl::GetContentStateImmediately() const {
2397 return send_content_state_immediately_;
2400 blink::WebPageVisibilityState RenderViewImpl::GetVisibilityState() const {
2401 return visibilityState();
2404 void RenderViewImpl::DidStartLoading() {
2405 main_render_frame_->didStartLoading(true);
2408 void RenderViewImpl::DidStopLoading() {
2409 main_render_frame_->didStopLoading();
2412 void RenderViewImpl::SyncNavigationState() {
2413 if (!webview())
2414 return;
2415 SendUpdateState(history_controller_->GetCurrentEntry());
2418 blink::WebElement RenderViewImpl::GetFocusedElement() const {
2419 if (!webview())
2420 return WebElement();
2421 WebFrame* focused_frame = webview()->focusedFrame();
2422 if (focused_frame) {
2423 WebDocument doc = focused_frame->document();
2424 if (!doc.isNull())
2425 return doc.focusedElement();
2428 return WebElement();
2431 blink::WebPlugin* RenderViewImpl::GetWebPluginForFind() {
2432 if (!webview())
2433 return NULL;
2435 WebFrame* main_frame = webview()->mainFrame();
2436 if (main_frame->isWebLocalFrame() &&
2437 main_frame->document().isPluginDocument())
2438 return webview()->mainFrame()->document().to<WebPluginDocument>().plugin();
2440 #if defined(ENABLE_PLUGINS)
2441 if (plugin_find_handler_)
2442 return plugin_find_handler_->container()->plugin();
2443 #endif
2445 return NULL;
2448 void RenderViewImpl::OnFind(int request_id,
2449 const base::string16& search_text,
2450 const WebFindOptions& options) {
2451 WebFrame* main_frame = webview()->mainFrame();
2452 blink::WebPlugin* plugin = GetWebPluginForFind();
2453 // Check if the plugin still exists in the document.
2454 if (plugin) {
2455 if (options.findNext) {
2456 // Just navigate back/forward.
2457 plugin->selectFindResult(options.forward);
2458 } else {
2459 if (!plugin->startFind(
2460 search_text, options.matchCase, request_id)) {
2461 // Send "no results".
2462 SendFindReply(request_id, 0, 0, gfx::Rect(), true);
2465 return;
2468 WebFrame* frame_after_main = main_frame->traverseNext(true);
2469 WebFrame* focused_frame = webview()->focusedFrame();
2470 WebFrame* search_frame = focused_frame; // start searching focused frame.
2472 bool multi_frame = (frame_after_main != main_frame);
2474 // If we have multiple frames, we don't want to wrap the search within the
2475 // frame, so we check here if we only have main_frame in the chain.
2476 bool wrap_within_frame = !multi_frame;
2478 WebRect selection_rect;
2479 bool result = false;
2481 // If something is selected when we start searching it means we cannot just
2482 // increment the current match ordinal; we need to re-generate it.
2483 WebRange current_selection = focused_frame->selectionRange();
2485 do {
2486 result = search_frame->find(
2487 request_id, search_text, options, wrap_within_frame, &selection_rect);
2489 if (!result) {
2490 // don't leave text selected as you move to the next frame.
2491 search_frame->executeCommand(WebString::fromUTF8("Unselect"),
2492 GetFocusedElement());
2494 // Find the next frame, but skip the invisible ones.
2495 do {
2496 // What is the next frame to search? (we might be going backwards). Note
2497 // that we specify wrap=true so that search_frame never becomes NULL.
2498 search_frame = options.forward ?
2499 search_frame->traverseNext(true) :
2500 search_frame->traversePrevious(true);
2501 } while (!search_frame->hasVisibleContent() &&
2502 search_frame != focused_frame);
2504 // Make sure selection doesn't affect the search operation in new frame.
2505 search_frame->executeCommand(WebString::fromUTF8("Unselect"),
2506 GetFocusedElement());
2508 // If we have multiple frames and we have wrapped back around to the
2509 // focused frame, we need to search it once more allowing wrap within
2510 // the frame, otherwise it will report 'no match' if the focused frame has
2511 // reported matches, but no frames after the focused_frame contain a
2512 // match for the search word(s).
2513 if (multi_frame && search_frame == focused_frame) {
2514 result = search_frame->find(
2515 request_id, search_text, options, true, // Force wrapping.
2516 &selection_rect);
2520 webview()->setFocusedFrame(search_frame);
2521 } while (!result && search_frame != focused_frame);
2523 if (options.findNext && current_selection.isNull()) {
2524 // Force the main_frame to report the actual count.
2525 main_frame->increaseMatchCount(0, request_id);
2526 } else {
2527 // If nothing is found, set result to "0 of 0", otherwise, set it to
2528 // "-1 of 1" to indicate that we found at least one item, but we don't know
2529 // yet what is active.
2530 int ordinal = result ? -1 : 0; // -1 here means, we might know more later.
2531 int match_count = result ? 1 : 0; // 1 here means possibly more coming.
2533 // If we find no matches then this will be our last status update.
2534 // Otherwise the scoping effort will send more results.
2535 bool final_status_update = !result;
2537 SendFindReply(request_id, match_count, ordinal, selection_rect,
2538 final_status_update);
2540 // Scoping effort begins, starting with the mainframe.
2541 search_frame = main_frame;
2543 main_frame->resetMatchCount();
2545 do {
2546 // Cancel all old scoping requests before starting a new one.
2547 search_frame->cancelPendingScopingEffort();
2549 // We don't start another scoping effort unless at least one match has
2550 // been found.
2551 if (result) {
2552 // Start new scoping request. If the scoping function determines that it
2553 // needs to scope, it will defer until later.
2554 search_frame->scopeStringMatches(request_id,
2555 search_text,
2556 options,
2557 true); // reset the tickmarks
2560 // Iterate to the next frame. The frame will not necessarily scope, for
2561 // example if it is not visible.
2562 search_frame = search_frame->traverseNext(true);
2563 } while (search_frame != main_frame);
2567 void RenderViewImpl::OnStopFinding(StopFindAction action) {
2568 WebView* view = webview();
2569 if (!view)
2570 return;
2572 blink::WebPlugin* plugin = GetWebPluginForFind();
2573 if (plugin) {
2574 plugin->stopFind();
2575 return;
2578 bool clear_selection = action == STOP_FIND_ACTION_CLEAR_SELECTION;
2579 if (clear_selection) {
2580 view->focusedFrame()->executeCommand(WebString::fromUTF8("Unselect"),
2581 GetFocusedElement());
2584 WebFrame* frame = view->mainFrame();
2585 while (frame) {
2586 frame->stopFinding(clear_selection);
2587 frame = frame->traverseNext(false);
2590 if (action == STOP_FIND_ACTION_ACTIVATE_SELECTION) {
2591 WebFrame* focused_frame = view->focusedFrame();
2592 if (focused_frame) {
2593 WebDocument doc = focused_frame->document();
2594 if (!doc.isNull()) {
2595 WebElement element = doc.focusedElement();
2596 if (!element.isNull())
2597 element.simulateClick();
2603 #if defined(OS_ANDROID)
2604 void RenderViewImpl::OnActivateNearestFindResult(int request_id,
2605 float x, float y) {
2606 if (!webview())
2607 return;
2609 WebFrame* main_frame = webview()->mainFrame();
2610 WebRect selection_rect;
2611 int ordinal = main_frame->selectNearestFindMatch(WebFloatPoint(x, y),
2612 &selection_rect);
2613 if (ordinal == -1) {
2614 // Something went wrong, so send a no-op reply (force the main_frame to
2615 // report the current match count) in case the host is waiting for a
2616 // response due to rate-limiting).
2617 main_frame->increaseMatchCount(0, request_id);
2618 return;
2621 SendFindReply(request_id,
2622 -1 /* number_of_matches */,
2623 ordinal,
2624 selection_rect,
2625 true /* final_update */);
2628 void RenderViewImpl::OnFindMatchRects(int current_version) {
2629 if (!webview())
2630 return;
2632 WebFrame* main_frame = webview()->mainFrame();
2633 std::vector<gfx::RectF> match_rects;
2635 int rects_version = main_frame->findMatchMarkersVersion();
2636 if (current_version != rects_version) {
2637 WebVector<WebFloatRect> web_match_rects;
2638 main_frame->findMatchRects(web_match_rects);
2639 match_rects.reserve(web_match_rects.size());
2640 for (size_t i = 0; i < web_match_rects.size(); ++i)
2641 match_rects.push_back(gfx::RectF(web_match_rects[i]));
2644 gfx::RectF active_rect = main_frame->activeFindMatchRect();
2645 Send(new ViewHostMsg_FindMatchRects_Reply(routing_id_,
2646 rects_version,
2647 match_rects,
2648 active_rect));
2650 #endif
2652 void RenderViewImpl::OnResetPageScale() {
2653 if (!webview())
2654 return;
2655 webview()->setPageScaleFactor(1);
2658 void RenderViewImpl::OnZoom(PageZoom zoom) {
2659 if (!webview()) // Not sure if this can happen, but no harm in being safe.
2660 return;
2662 webview()->hidePopups();
2664 double old_zoom_level = webview()->zoomLevel();
2665 double zoom_level;
2666 if (zoom == PAGE_ZOOM_RESET) {
2667 zoom_level = 0;
2668 } else if (static_cast<int>(old_zoom_level) == old_zoom_level) {
2669 // Previous zoom level is a whole number, so just increment/decrement.
2670 zoom_level = old_zoom_level + zoom;
2671 } else {
2672 // Either the user hit the zoom factor limit and thus the zoom level is now
2673 // not a whole number, or a plugin changed it to a custom value. We want
2674 // to go to the next whole number so that the user can always get back to
2675 // 100% with the keyboard/menu.
2676 if ((old_zoom_level > 1 && zoom > 0) ||
2677 (old_zoom_level < 1 && zoom < 0)) {
2678 zoom_level = static_cast<int>(old_zoom_level + zoom);
2679 } else {
2680 // We're going towards 100%, so first go to the next whole number.
2681 zoom_level = static_cast<int>(old_zoom_level);
2684 webview()->setZoomLevel(zoom_level);
2685 zoomLevelChanged();
2688 void RenderViewImpl::OnSetZoomLevelForLoadingURL(const GURL& url,
2689 double zoom_level) {
2690 #if !defined(OS_ANDROID)
2691 // On Android, page zoom isn't used, and in case of WebView, text zoom is used
2692 // for legacy WebView text scaling emulation. Thus, the code that resets
2693 // the zoom level from this map will be effectively resetting text zoom level.
2694 host_zoom_levels_[url] = zoom_level;
2695 #endif
2698 void RenderViewImpl::OnSetZoomLevelForView(bool uses_temporary_zoom_level,
2699 double level) {
2700 uses_temporary_zoom_level_ = uses_temporary_zoom_level;
2702 webview()->hidePopups();
2703 webview()->setZoomLevel(level);
2706 void RenderViewImpl::OnSetPageEncoding(const std::string& encoding_name) {
2707 webview()->setPageEncoding(WebString::fromUTF8(encoding_name));
2710 void RenderViewImpl::OnResetPageEncodingToDefault() {
2711 WebString no_encoding;
2712 webview()->setPageEncoding(no_encoding);
2715 void RenderViewImpl::OnPostMessageEvent(
2716 const ViewMsg_PostMessage_Params& params) {
2717 // TODO(nasko): Support sending to subframes.
2718 WebFrame* frame = webview()->mainFrame();
2720 // Find the source frame if it exists.
2721 WebFrame* source_frame = NULL;
2722 if (params.source_routing_id != MSG_ROUTING_NONE) {
2723 RenderViewImpl* source_view = FromRoutingID(params.source_routing_id);
2724 if (source_view)
2725 source_frame = source_view->webview()->mainFrame();
2728 // If the message contained MessagePorts, create the corresponding endpoints.
2729 blink::WebMessagePortChannelArray channels =
2730 WebMessagePortChannelImpl::CreatePorts(
2731 params.message_ports, params.new_routing_ids,
2732 base::MessageLoopProxy::current().get());
2734 WebSerializedScriptValue serialized_script_value;
2735 if (params.is_data_raw_string) {
2736 v8::HandleScope handle_scope(blink::mainThreadIsolate());
2737 v8::Local<v8::Context> context = frame->mainWorldScriptContext();
2738 v8::Context::Scope context_scope(context);
2739 V8ValueConverterImpl converter;
2740 converter.SetDateAllowed(true);
2741 converter.SetRegExpAllowed(true);
2742 scoped_ptr<base::Value> value(new base::StringValue(params.data));
2743 v8::Handle<v8::Value> result_value = converter.ToV8Value(value.get(),
2744 context);
2745 serialized_script_value = WebSerializedScriptValue::serialize(result_value);
2746 } else {
2747 serialized_script_value = WebSerializedScriptValue::fromString(params.data);
2750 // Create an event with the message. The final parameter to initMessageEvent
2751 // is the last event ID, which is not used with postMessage.
2752 WebDOMEvent event = frame->document().createEvent("MessageEvent");
2753 WebDOMMessageEvent msg_event = event.to<WebDOMMessageEvent>();
2754 msg_event.initMessageEvent("message",
2755 // |canBubble| and |cancellable| are always false
2756 false, false,
2757 serialized_script_value,
2758 params.source_origin, source_frame, "", channels);
2760 // We must pass in the target_origin to do the security check on this side,
2761 // since it may have changed since the original postMessage call was made.
2762 WebSecurityOrigin target_origin;
2763 if (!params.target_origin.empty()) {
2764 target_origin =
2765 WebSecurityOrigin::createFromString(WebString(params.target_origin));
2767 frame->dispatchMessageEventWithOriginCheck(target_origin, msg_event);
2770 void RenderViewImpl::OnAllowBindings(int enabled_bindings_flags) {
2771 if ((enabled_bindings_flags & BINDINGS_POLICY_WEB_UI) &&
2772 !(enabled_bindings_ & BINDINGS_POLICY_WEB_UI)) {
2773 // WebUIExtensionData deletes itself when we're destroyed.
2774 new WebUIExtensionData(this);
2775 // WebUIMojo deletes itself when we're destroyed.
2776 new WebUIMojo(this);
2779 enabled_bindings_ |= enabled_bindings_flags;
2781 // Keep track of the total bindings accumulated in this process.
2782 RenderProcess::current()->AddBindings(enabled_bindings_flags);
2785 void RenderViewImpl::OnDragTargetDragEnter(const DropData& drop_data,
2786 const gfx::Point& client_point,
2787 const gfx::Point& screen_point,
2788 WebDragOperationsMask ops,
2789 int key_modifiers) {
2790 WebDragOperation operation = webview()->dragTargetDragEnter(
2791 DropDataToWebDragData(drop_data),
2792 client_point,
2793 screen_point,
2794 ops,
2795 key_modifiers);
2797 Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
2800 void RenderViewImpl::OnDragTargetDragOver(const gfx::Point& client_point,
2801 const gfx::Point& screen_point,
2802 WebDragOperationsMask ops,
2803 int key_modifiers) {
2804 WebDragOperation operation = webview()->dragTargetDragOver(
2805 client_point,
2806 screen_point,
2807 ops,
2808 key_modifiers);
2810 Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
2813 void RenderViewImpl::OnDragTargetDragLeave() {
2814 webview()->dragTargetDragLeave();
2817 void RenderViewImpl::OnDragTargetDrop(const gfx::Point& client_point,
2818 const gfx::Point& screen_point,
2819 int key_modifiers) {
2820 webview()->dragTargetDrop(client_point, screen_point, key_modifiers);
2822 Send(new DragHostMsg_TargetDrop_ACK(routing_id_));
2825 void RenderViewImpl::OnDragSourceEnded(const gfx::Point& client_point,
2826 const gfx::Point& screen_point,
2827 WebDragOperation op) {
2828 webview()->dragSourceEndedAt(client_point, screen_point, op);
2831 void RenderViewImpl::OnDragSourceSystemDragEnded() {
2832 webview()->dragSourceSystemDragEnded();
2835 void RenderViewImpl::OnUpdateWebPreferences(const WebPreferences& prefs) {
2836 webkit_preferences_ = prefs;
2837 ApplyWebPreferences(webkit_preferences_, webview());
2840 void RenderViewImpl::OnEnumerateDirectoryResponse(
2841 int id,
2842 const std::vector<base::FilePath>& paths) {
2843 if (!enumeration_completions_[id])
2844 return;
2846 WebVector<WebString> ws_file_names(paths.size());
2847 for (size_t i = 0; i < paths.size(); ++i)
2848 ws_file_names[i] = paths[i].AsUTF16Unsafe();
2850 enumeration_completions_[id]->didChooseFile(ws_file_names);
2851 enumeration_completions_.erase(id);
2854 void RenderViewImpl::OnFileChooserResponse(
2855 const std::vector<content::FileChooserFileInfo>& files) {
2856 // This could happen if we navigated to a different page before the user
2857 // closed the chooser.
2858 if (file_chooser_completions_.empty())
2859 return;
2861 // Convert Chrome's SelectedFileInfo list to WebKit's.
2862 WebVector<WebFileChooserCompletion::SelectedFileInfo> selected_files(
2863 files.size());
2864 for (size_t i = 0; i < files.size(); ++i) {
2865 WebFileChooserCompletion::SelectedFileInfo selected_file;
2866 selected_file.path = files[i].file_path.AsUTF16Unsafe();
2867 selected_file.displayName =
2868 base::FilePath(files[i].display_name).AsUTF16Unsafe();
2869 if (files[i].file_system_url.is_valid()) {
2870 selected_file.fileSystemURL = files[i].file_system_url;
2871 selected_file.length = files[i].length;
2872 selected_file.modificationTime = files[i].modification_time.ToDoubleT();
2873 selected_file.isDirectory = files[i].is_directory;
2875 selected_files[i] = selected_file;
2878 if (file_chooser_completions_.front()->completion)
2879 file_chooser_completions_.front()->completion->didChooseFile(
2880 selected_files);
2881 file_chooser_completions_.pop_front();
2883 // If there are more pending file chooser requests, schedule one now.
2884 if (!file_chooser_completions_.empty()) {
2885 Send(new ViewHostMsg_RunFileChooser(routing_id_,
2886 file_chooser_completions_.front()->params));
2890 void RenderViewImpl::OnEnableAutoResize(const gfx::Size& min_size,
2891 const gfx::Size& max_size) {
2892 DCHECK(disable_scrollbars_size_limit_.IsEmpty());
2893 if (!webview())
2894 return;
2895 auto_resize_mode_ = true;
2896 webview()->enableAutoResizeMode(min_size, max_size);
2899 void RenderViewImpl::OnDisableAutoResize(const gfx::Size& new_size) {
2900 DCHECK(disable_scrollbars_size_limit_.IsEmpty());
2901 if (!webview())
2902 return;
2903 auto_resize_mode_ = false;
2904 webview()->disableAutoResizeMode();
2906 if (!new_size.IsEmpty()) {
2907 Resize(new_size,
2908 physical_backing_size_,
2909 top_controls_shrink_blink_size_,
2910 top_controls_height_,
2911 visible_viewport_size_,
2912 resizer_rect_,
2913 is_fullscreen_,
2914 NO_RESIZE_ACK);
2918 void RenderViewImpl::OnEnablePreferredSizeChangedMode() {
2919 if (send_preferred_size_changes_)
2920 return;
2921 send_preferred_size_changes_ = true;
2923 // Start off with an initial preferred size notification (in case
2924 // |didUpdateLayout| was already called).
2925 didUpdateLayout();
2928 void RenderViewImpl::OnDisableScrollbarsForSmallWindows(
2929 const gfx::Size& disable_scrollbar_size_limit) {
2930 disable_scrollbars_size_limit_ = disable_scrollbar_size_limit;
2933 void RenderViewImpl::OnSetRendererPrefs(
2934 const RendererPreferences& renderer_prefs) {
2935 double old_zoom_level = renderer_preferences_.default_zoom_level;
2936 std::string old_accept_languages = renderer_preferences_.accept_languages;
2938 renderer_preferences_ = renderer_prefs;
2939 UpdateFontRenderingFromRendererPrefs();
2941 #if defined(USE_DEFAULT_RENDER_THEME)
2942 if (renderer_prefs.use_custom_colors) {
2943 WebColorName name = blink::WebColorWebkitFocusRingColor;
2944 blink::setNamedColors(&name, &renderer_prefs.focus_ring_color, 1);
2945 blink::setCaretBlinkInterval(renderer_prefs.caret_blink_interval);
2947 if (webview()) {
2948 webview()->setSelectionColors(
2949 renderer_prefs.active_selection_bg_color,
2950 renderer_prefs.active_selection_fg_color,
2951 renderer_prefs.inactive_selection_bg_color,
2952 renderer_prefs.inactive_selection_fg_color);
2953 webview()->themeChanged();
2956 #endif // defined(USE_DEFAULT_RENDER_THEME)
2958 // If the zoom level for this page matches the old zoom default, and this
2959 // is not a plugin, update the zoom level to match the new default.
2960 if (webview() && webview()->mainFrame()->isWebLocalFrame() &&
2961 !webview()->mainFrame()->document().isPluginDocument() &&
2962 !ZoomValuesEqual(old_zoom_level,
2963 renderer_preferences_.default_zoom_level) &&
2964 ZoomValuesEqual(webview()->zoomLevel(), old_zoom_level)) {
2965 webview()->setZoomLevel(renderer_preferences_.default_zoom_level);
2966 zoomLevelChanged();
2969 if (webview() &&
2970 old_accept_languages != renderer_preferences_.accept_languages) {
2971 webview()->acceptLanguagesChanged();
2975 void RenderViewImpl::OnMediaPlayerActionAt(const gfx::Point& location,
2976 const WebMediaPlayerAction& action) {
2977 if (webview())
2978 webview()->performMediaPlayerAction(action, location);
2981 void RenderViewImpl::OnOrientationChange() {
2982 webview()->mainFrame()->toWebLocalFrame()->sendOrientationChangeEvent();
2985 void RenderViewImpl::OnPluginActionAt(const gfx::Point& location,
2986 const WebPluginAction& action) {
2987 if (webview())
2988 webview()->performPluginAction(action, location);
2991 void RenderViewImpl::OnGetAllSavableResourceLinksForCurrentPage(
2992 const GURL& page_url) {
2993 // Prepare list to storage all savable resource links.
2994 std::vector<GURL> resources_list;
2995 std::vector<GURL> referrer_urls_list;
2996 std::vector<blink::WebReferrerPolicy> referrer_policies_list;
2997 std::vector<GURL> frames_list;
2998 SavableResourcesResult result(&resources_list,
2999 &referrer_urls_list,
3000 &referrer_policies_list,
3001 &frames_list);
3003 // webkit/ doesn't know about Referrer.
3004 if (!GetAllSavableResourceLinksForCurrentPage(
3005 webview(),
3006 page_url,
3007 &result,
3008 const_cast<const char**>(GetSavableSchemes()))) {
3009 // If something is wrong when collecting all savable resource links,
3010 // send empty list to embedder(browser) to tell it failed.
3011 referrer_urls_list.clear();
3012 referrer_policies_list.clear();
3013 resources_list.clear();
3014 frames_list.clear();
3017 std::vector<Referrer> referrers_list;
3018 CHECK_EQ(referrer_urls_list.size(), referrer_policies_list.size());
3019 for (unsigned i = 0; i < referrer_urls_list.size(); ++i) {
3020 referrers_list.push_back(
3021 Referrer(referrer_urls_list[i], referrer_policies_list[i]));
3024 // Send result of all savable resource links to embedder.
3025 Send(new ViewHostMsg_SendCurrentPageAllSavableResourceLinks(routing_id(),
3026 resources_list,
3027 referrers_list,
3028 frames_list));
3031 void RenderViewImpl::OnGetSerializedHtmlDataForCurrentPageWithLocalLinks(
3032 const std::vector<GURL>& links,
3033 const std::vector<base::FilePath>& local_paths,
3034 const base::FilePath& local_directory_name) {
3036 // Convert std::vector of GURLs to WebVector<WebURL>
3037 WebVector<WebURL> weburl_links(links);
3039 // Convert std::vector of base::FilePath to WebVector<WebString>
3040 WebVector<WebString> webstring_paths(local_paths.size());
3041 for (size_t i = 0; i < local_paths.size(); i++)
3042 webstring_paths[i] = local_paths[i].AsUTF16Unsafe();
3044 WebPageSerializer::serialize(webview()->mainFrame()->toWebLocalFrame(),
3045 true,
3046 this,
3047 weburl_links,
3048 webstring_paths,
3049 local_directory_name.AsUTF16Unsafe());
3052 void RenderViewImpl::OnSuppressDialogsUntilSwapOut() {
3053 // Don't show any more dialogs until we finish OnSwapOut.
3054 suppress_dialogs_until_swap_out_ = true;
3057 void RenderViewImpl::OnClosePage() {
3058 FOR_EACH_OBSERVER(RenderViewObserver, observers_, ClosePage());
3059 // TODO(creis): We'd rather use webview()->Close() here, but that currently
3060 // sets the WebView's delegate_ to NULL, preventing any JavaScript dialogs
3061 // in the onunload handler from appearing. For now, we're bypassing that and
3062 // calling the FrameLoader's CloseURL method directly. This should be
3063 // revisited to avoid having two ways to close a page. Having a single way
3064 // to close that can run onunload is also useful for fixing
3065 // http://b/issue?id=753080.
3066 webview()->mainFrame()->dispatchUnloadEvent();
3068 Send(new ViewHostMsg_ClosePage_ACK(routing_id_));
3071 void RenderViewImpl::OnThemeChanged() {
3072 #if defined(USE_AURA)
3073 // Aura doesn't care if we switch themes.
3074 #elif defined(OS_WIN)
3075 ui::NativeThemeWin::instance()->CloseHandles();
3076 if (webview())
3077 webview()->themeChanged();
3078 #else // defined(OS_WIN)
3079 // TODO(port): we don't support theming on non-Windows platforms yet
3080 NOTIMPLEMENTED();
3081 #endif
3084 void RenderViewImpl::OnMoveOrResizeStarted() {
3085 if (webview())
3086 webview()->hidePopups();
3089 void RenderViewImpl::OnResize(const ViewMsg_Resize_Params& params) {
3090 TRACE_EVENT0("renderer", "RenderViewImpl::OnResize");
3091 if (webview()) {
3092 webview()->hidePopups();
3093 if (send_preferred_size_changes_) {
3094 webview()->mainFrame()->setCanHaveScrollbars(
3095 ShouldDisplayScrollbars(params.new_size.width(),
3096 params.new_size.height()));
3100 gfx::Size old_visible_viewport_size = visible_viewport_size_;
3102 RenderWidget::OnResize(params);
3104 if (old_visible_viewport_size != visible_viewport_size_)
3105 has_scrolled_focused_editable_node_into_rect_ = false;
3108 void RenderViewImpl::DidInitiatePaint() {
3109 #if defined(ENABLE_PLUGINS)
3110 // Notify all instances that we painted. The same caveats apply as for
3111 // ViewFlushedPaint regarding instances closing themselves, so we take
3112 // similar precautions.
3113 PepperPluginSet plugins = active_pepper_instances_;
3114 for (PepperPluginSet::iterator i = plugins.begin(); i != plugins.end(); ++i) {
3115 if (active_pepper_instances_.find(*i) != active_pepper_instances_.end())
3116 (*i)->ViewInitiatedPaint();
3118 #endif
3121 void RenderViewImpl::DidFlushPaint() {
3122 // If the RenderWidget is closing down then early-exit, otherwise we'll crash.
3123 // See crbug.com/112921.
3124 if (!webview())
3125 return;
3127 WebFrame* main_frame = webview()->mainFrame();
3128 for (WebFrame* frame = main_frame; frame;
3129 frame = frame->traverseNext(false)) {
3130 // TODO(nasko): This is a hack for the case in which the top-level
3131 // frame is being rendered in another process. It will not
3132 // behave correctly for out of process iframes.
3133 if (frame->isWebLocalFrame()) {
3134 main_frame = frame;
3135 break;
3139 // If we have a provisional frame we are between the start and commit stages
3140 // of loading and we don't want to save stats.
3141 if (!main_frame->provisionalDataSource()) {
3142 WebDataSource* ds = main_frame->dataSource();
3143 DocumentState* document_state = DocumentState::FromDataSource(ds);
3145 // TODO(jar): The following code should all be inside a method, probably in
3146 // NavigatorState.
3147 Time now = Time::Now();
3148 if (document_state->first_paint_time().is_null()) {
3149 document_state->set_first_paint_time(now);
3151 if (document_state->first_paint_after_load_time().is_null() &&
3152 !document_state->finish_load_time().is_null()) {
3153 document_state->set_first_paint_after_load_time(now);
3158 gfx::Vector2d RenderViewImpl::GetScrollOffset() {
3159 WebFrame* main_frame = webview()->mainFrame();
3160 for (WebFrame* frame = main_frame; frame;
3161 frame = frame->traverseNext(false)) {
3162 // TODO(nasko): This is a hack for the case in which the top-level
3163 // frame is being rendered in another process. It will not
3164 // behave correctly for out of process iframes.
3165 if (frame->isWebLocalFrame()) {
3166 main_frame = frame;
3167 break;
3171 WebSize scroll_offset = main_frame->scrollOffset();
3172 return gfx::Vector2d(scroll_offset.width, scroll_offset.height);
3175 void RenderViewImpl::OnClearFocusedElement() {
3176 if (webview())
3177 webview()->clearFocusedElement();
3180 void RenderViewImpl::OnSetBackgroundOpaque(bool opaque) {
3181 if (webview())
3182 webview()->setIsTransparent(!opaque);
3183 if (compositor_)
3184 compositor_->setHasTransparentBackground(!opaque);
3187 void RenderViewImpl::OnSetActive(bool active) {
3188 if (webview())
3189 webview()->setIsActive(active);
3191 #if defined(ENABLE_PLUGINS) && defined(OS_MACOSX)
3192 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3193 for (plugin_it = plugin_delegates_.begin();
3194 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3195 (*plugin_it)->SetWindowFocus(active);
3197 #endif
3200 #if defined(OS_MACOSX)
3201 void RenderViewImpl::OnSetWindowVisibility(bool visible) {
3202 #if defined(ENABLE_PLUGINS)
3203 // Inform plugins that their container has changed visibility.
3204 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3205 for (plugin_it = plugin_delegates_.begin();
3206 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3207 (*plugin_it)->SetContainerVisibility(visible);
3209 #endif
3212 void RenderViewImpl::OnWindowFrameChanged(const gfx::Rect& window_frame,
3213 const gfx::Rect& view_frame) {
3214 #if defined(ENABLE_PLUGINS)
3215 // Inform plugins that their window's frame has changed.
3216 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3217 for (plugin_it = plugin_delegates_.begin();
3218 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3219 (*plugin_it)->WindowFrameChanged(window_frame, view_frame);
3221 #endif
3224 void RenderViewImpl::OnPluginImeCompositionCompleted(const base::string16& text,
3225 int plugin_id) {
3226 // WebPluginDelegateProxy is responsible for figuring out if this event
3227 // applies to it or not, so inform all the delegates.
3228 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3229 for (plugin_it = plugin_delegates_.begin();
3230 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3231 (*plugin_it)->ImeCompositionCompleted(text, plugin_id);
3234 #endif // OS_MACOSX
3236 void RenderViewImpl::OnClose() {
3237 if (closing_)
3238 RenderThread::Get()->Send(new ViewHostMsg_Close_ACK(routing_id_));
3239 RenderWidget::OnClose();
3242 void RenderViewImpl::Close() {
3243 // We need to grab a pointer to the doomed WebView before we destroy it.
3244 WebView* doomed = webview();
3245 RenderWidget::Close();
3246 g_view_map.Get().erase(doomed);
3247 g_routing_id_view_map.Get().erase(routing_id_);
3248 RenderThread::Get()->Send(new ViewHostMsg_Close_ACK(routing_id_));
3251 void RenderViewImpl::DidHandleKeyEvent() {
3252 ClearEditCommands();
3255 bool RenderViewImpl::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
3256 possible_drag_event_info_.event_source =
3257 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE;
3258 possible_drag_event_info_.event_location =
3259 gfx::Point(event.globalX, event.globalY);
3261 #if defined(ENABLE_PLUGINS)
3262 // This method is called for every mouse event that the render view receives.
3263 // And then the mouse event is forwarded to WebKit, which dispatches it to the
3264 // event target. Potentially a Pepper plugin will receive the event.
3265 // In order to tell whether a plugin gets the last mouse event and which it
3266 // is, we set |pepper_last_mouse_event_target_| to NULL here. If a plugin gets
3267 // the event, it will notify us via DidReceiveMouseEvent() and set itself as
3268 // |pepper_last_mouse_event_target_|.
3269 pepper_last_mouse_event_target_ = NULL;
3270 #endif
3272 // If the mouse is locked, only the current owner of the mouse lock can
3273 // process mouse events.
3274 return mouse_lock_dispatcher_->WillHandleMouseEvent(event);
3277 bool RenderViewImpl::WillHandleGestureEvent(
3278 const blink::WebGestureEvent& event) {
3279 possible_drag_event_info_.event_source =
3280 ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH;
3281 possible_drag_event_info_.event_location =
3282 gfx::Point(event.globalX, event.globalY);
3283 return false;
3286 void RenderViewImpl::DidHandleMouseEvent(const WebMouseEvent& event) {
3287 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidHandleMouseEvent(event));
3290 void RenderViewImpl::DidHandleTouchEvent(const WebTouchEvent& event) {
3291 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidHandleTouchEvent(event));
3294 bool RenderViewImpl::HasTouchEventHandlersAt(const gfx::Point& point) const {
3295 if (!webview())
3296 return false;
3297 return webview()->hasTouchEventHandlersAt(point);
3300 void RenderViewImpl::OnWasHidden() {
3301 RenderWidget::OnWasHidden();
3303 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3304 RenderThreadImpl::current()->video_capture_impl_manager()->
3305 SuspendDevices(true);
3306 if (speech_recognition_dispatcher_)
3307 speech_recognition_dispatcher_->AbortAllRecognitions();
3308 #endif
3310 if (webview())
3311 webview()->setVisibilityState(visibilityState(), false);
3313 #if defined(ENABLE_PLUGINS)
3314 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3315 i != active_pepper_instances_.end(); ++i)
3316 (*i)->PageVisibilityChanged(false);
3318 #if defined(OS_MACOSX)
3319 // Inform NPAPI plugins that their container is no longer visible.
3320 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3321 for (plugin_it = plugin_delegates_.begin();
3322 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3323 (*plugin_it)->SetContainerVisibility(false);
3325 #endif // OS_MACOSX
3326 #endif // ENABLE_PLUGINS
3329 void RenderViewImpl::OnWasShown(bool needs_repainting,
3330 const ui::LatencyInfo& latency_info) {
3331 RenderWidget::OnWasShown(needs_repainting, latency_info);
3333 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3334 RenderThreadImpl::current()->video_capture_impl_manager()->
3335 SuspendDevices(false);
3336 #endif
3338 if (webview())
3339 webview()->setVisibilityState(visibilityState(), false);
3341 #if defined(ENABLE_PLUGINS)
3342 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3343 i != active_pepper_instances_.end(); ++i)
3344 (*i)->PageVisibilityChanged(true);
3346 #if defined(OS_MACOSX)
3347 // Inform NPAPI plugins that their container is now visible.
3348 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3349 for (plugin_it = plugin_delegates_.begin();
3350 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3351 (*plugin_it)->SetContainerVisibility(true);
3353 #endif // OS_MACOSX
3354 #endif // ENABLE_PLUGINS
3357 GURL RenderViewImpl::GetURLForGraphicsContext3D() {
3358 DCHECK(webview());
3359 if (webview()->mainFrame()->isWebLocalFrame())
3360 return GURL(webview()->mainFrame()->document().url());
3361 else
3362 return GURL("chrome://gpu/RenderViewImpl::CreateGraphicsContext3D");
3365 void RenderViewImpl::OnSetFocus(bool enable) {
3366 RenderWidget::OnSetFocus(enable);
3368 #if defined(ENABLE_PLUGINS)
3369 if (webview() && webview()->isActive()) {
3370 // Notify all NPAPI plugins.
3371 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3372 for (plugin_it = plugin_delegates_.begin();
3373 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3374 #if defined(OS_MACOSX)
3375 // RenderWidget's call to setFocus can cause the underlying webview's
3376 // activation state to change just like a call to setIsActive.
3377 if (enable)
3378 (*plugin_it)->SetWindowFocus(true);
3379 #endif
3380 (*plugin_it)->SetContentAreaFocus(enable);
3383 // Notify all Pepper plugins.
3384 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3385 i != active_pepper_instances_.end(); ++i)
3386 (*i)->SetContentAreaFocus(enable);
3387 #endif
3388 // Notify all BrowserPlugins of the RenderView's focus state.
3389 if (BrowserPluginManager::Get())
3390 BrowserPluginManager::Get()->UpdateFocusState();
3393 void RenderViewImpl::OnImeSetComposition(
3394 const base::string16& text,
3395 const std::vector<blink::WebCompositionUnderline>& underlines,
3396 int selection_start,
3397 int selection_end) {
3398 #if defined(ENABLE_PLUGINS)
3399 if (focused_pepper_plugin_) {
3400 focused_pepper_plugin_->render_frame()->OnImeSetComposition(
3401 text, underlines, selection_start, selection_end);
3402 return;
3405 #if defined(OS_WIN)
3406 // When a plugin has focus, we create platform-specific IME data used by
3407 // our IME emulator and send it directly to the focused plugin, i.e. we
3408 // bypass WebKit. (WebPluginDelegate dispatches this IME data only when its
3409 // instance ID is the same one as the specified ID.)
3410 if (focused_plugin_id_ >= 0) {
3411 std::vector<int> clauses;
3412 std::vector<int> target;
3413 for (size_t i = 0; i < underlines.size(); ++i) {
3414 clauses.push_back(underlines[i].startOffset);
3415 clauses.push_back(underlines[i].endOffset);
3416 if (underlines[i].thick) {
3417 target.clear();
3418 target.push_back(underlines[i].startOffset);
3419 target.push_back(underlines[i].endOffset);
3422 std::set<WebPluginDelegateProxy*>::iterator it;
3423 for (it = plugin_delegates_.begin(); it != plugin_delegates_.end(); ++it) {
3424 (*it)->ImeCompositionUpdated(text, clauses, target, selection_end,
3425 focused_plugin_id_);
3427 return;
3429 #endif // OS_WIN
3430 #endif // ENABLE_PLUGINS
3431 RenderWidget::OnImeSetComposition(text,
3432 underlines,
3433 selection_start,
3434 selection_end);
3437 void RenderViewImpl::OnImeConfirmComposition(
3438 const base::string16& text,
3439 const gfx::Range& replacement_range,
3440 bool keep_selection) {
3441 #if defined(ENABLE_PLUGINS)
3442 if (focused_pepper_plugin_) {
3443 focused_pepper_plugin_->render_frame()->OnImeConfirmComposition(
3444 text, replacement_range, keep_selection);
3445 return;
3447 #if defined(OS_WIN)
3448 // Same as OnImeSetComposition(), we send the text from IMEs directly to
3449 // plugins. When we send IME text directly to plugins, we should not send
3450 // it to WebKit to prevent WebKit from controlling IMEs.
3451 // TODO(thakis): Honor |replacement_range| for plugins?
3452 if (focused_plugin_id_ >= 0) {
3453 std::set<WebPluginDelegateProxy*>::iterator it;
3454 for (it = plugin_delegates_.begin();
3455 it != plugin_delegates_.end(); ++it) {
3456 (*it)->ImeCompositionCompleted(text, focused_plugin_id_);
3458 return;
3460 #endif // OS_WIN
3461 #endif // ENABLE_PLUGINS
3462 if (replacement_range.IsValid() && webview()) {
3463 // Select the text in |replacement_range|, it will then be replaced by
3464 // text added by the call to RenderWidget::OnImeConfirmComposition().
3465 if (WebLocalFrame* frame = webview()->focusedFrame()->toWebLocalFrame()) {
3466 WebRange webrange = WebRange::fromDocumentRange(
3467 frame, replacement_range.start(), replacement_range.length());
3468 if (!webrange.isNull())
3469 frame->selectRange(webrange);
3472 RenderWidget::OnImeConfirmComposition(text,
3473 replacement_range,
3474 keep_selection);
3477 void RenderViewImpl::SetDeviceScaleFactor(float device_scale_factor) {
3478 RenderWidget::SetDeviceScaleFactor(device_scale_factor);
3479 if (webview()) {
3480 webview()->setDeviceScaleFactor(device_scale_factor);
3481 webview()->settings()->setPreferCompositingToLCDTextEnabled(
3482 PreferCompositingToLCDText(compositor_deps_, device_scale_factor_));
3484 if (auto_resize_mode_)
3485 AutoResizeCompositor();
3488 bool RenderViewImpl::SetDeviceColorProfile(
3489 const std::vector<char>& profile) {
3490 bool changed = RenderWidget::SetDeviceColorProfile(profile);
3491 if (changed && webview()) {
3492 WebVector<char> colorProfile = profile;
3493 webview()->setDeviceColorProfile(colorProfile);
3495 return changed;
3498 void RenderViewImpl::ResetDeviceColorProfileForTesting() {
3499 RenderWidget::ResetDeviceColorProfileForTesting();
3500 if (webview())
3501 webview()->resetDeviceColorProfile();
3504 ui::TextInputType RenderViewImpl::GetTextInputType() {
3505 #if defined(ENABLE_PLUGINS)
3506 if (focused_pepper_plugin_)
3507 return focused_pepper_plugin_->text_input_type();
3508 #endif
3509 return RenderWidget::GetTextInputType();
3512 void RenderViewImpl::GetSelectionBounds(gfx::Rect* start, gfx::Rect* end) {
3513 #if defined(ENABLE_PLUGINS)
3514 if (focused_pepper_plugin_) {
3515 // TODO(kinaba) http://crbug.com/101101
3516 // Current Pepper IME API does not handle selection bounds. So we simply
3517 // use the caret position as an empty range for now. It will be updated
3518 // after Pepper API equips features related to surrounding text retrieval.
3519 gfx::Rect caret = focused_pepper_plugin_->GetCaretBounds();
3520 *start = caret;
3521 *end = caret;
3522 return;
3524 #endif
3525 RenderWidget::GetSelectionBounds(start, end);
3528 void RenderViewImpl::FocusChangeComplete() {
3529 RenderWidget::FocusChangeComplete();
3530 FOR_EACH_OBSERVER(RenderViewObserver, observers_, FocusChangeComplete());
3533 void RenderViewImpl::GetCompositionCharacterBounds(
3534 std::vector<gfx::Rect>* bounds) {
3535 DCHECK(bounds);
3536 bounds->clear();
3538 #if defined(ENABLE_PLUGINS)
3539 if (focused_pepper_plugin_) {
3540 return;
3542 #endif
3544 if (!webview())
3545 return;
3546 size_t start_offset = 0;
3547 size_t character_count = 0;
3548 if (!webview()->compositionRange(&start_offset, &character_count))
3549 return;
3550 if (character_count == 0)
3551 return;
3553 blink::WebFrame* frame = webview()->focusedFrame();
3554 if (!frame)
3555 return;
3557 bounds->reserve(character_count);
3558 blink::WebRect webrect;
3559 for (size_t i = 0; i < character_count; ++i) {
3560 if (!frame->firstRectForCharacterRange(start_offset + i, 1, webrect)) {
3561 DLOG(ERROR) << "Could not retrieve character rectangle at " << i;
3562 bounds->clear();
3563 return;
3565 bounds->push_back(webrect);
3569 void RenderViewImpl::GetCompositionRange(gfx::Range* range) {
3570 #if defined(ENABLE_PLUGINS)
3571 if (focused_pepper_plugin_) {
3572 return;
3574 #endif
3575 RenderWidget::GetCompositionRange(range);
3578 bool RenderViewImpl::CanComposeInline() {
3579 #if defined(ENABLE_PLUGINS)
3580 if (focused_pepper_plugin_)
3581 return focused_pepper_plugin_->IsPluginAcceptingCompositionEvents();
3582 #endif
3583 return true;
3586 void RenderViewImpl::DidCompletePageScaleAnimation() {
3587 FocusChangeComplete();
3590 void RenderViewImpl::SetScreenMetricsEmulationParameters(
3591 bool enabled,
3592 const blink::WebDeviceEmulationParams& params) {
3593 if (webview() && compositor()) {
3594 if (enabled)
3595 webview()->enableDeviceEmulation(params);
3596 else
3597 webview()->disableDeviceEmulation();
3601 bool RenderViewImpl::ScheduleFileChooser(
3602 const FileChooserParams& params,
3603 WebFileChooserCompletion* completion) {
3604 static const size_t kMaximumPendingFileChooseRequests = 4;
3605 if (file_chooser_completions_.size() > kMaximumPendingFileChooseRequests) {
3606 // This sanity check prevents too many file choose requests from getting
3607 // queued which could DoS the user. Getting these is most likely a
3608 // programming error (there are many ways to DoS the user so it's not
3609 // considered a "real" security check), either in JS requesting many file
3610 // choosers to pop up, or in a plugin.
3612 // TODO(brettw) we might possibly want to require a user gesture to open
3613 // a file picker, which will address this issue in a better way.
3614 return false;
3617 file_chooser_completions_.push_back(linked_ptr<PendingFileChooser>(
3618 new PendingFileChooser(params, completion)));
3619 if (file_chooser_completions_.size() == 1) {
3620 // Actually show the browse dialog when this is the first request.
3621 Send(new ViewHostMsg_RunFileChooser(routing_id_, params));
3623 return true;
3626 blink::WebSpeechRecognizer* RenderViewImpl::speechRecognizer() {
3627 if (!speech_recognition_dispatcher_)
3628 speech_recognition_dispatcher_ = new SpeechRecognitionDispatcher(this);
3629 return speech_recognition_dispatcher_;
3632 void RenderViewImpl::zoomLimitsChanged(double minimum_level,
3633 double maximum_level) {
3634 // Round the double to avoid returning incorrect minimum/maximum zoom
3635 // percentages.
3636 int minimum_percent = round(
3637 ZoomLevelToZoomFactor(minimum_level) * 100);
3638 int maximum_percent = round(
3639 ZoomLevelToZoomFactor(maximum_level) * 100);
3641 Send(new ViewHostMsg_UpdateZoomLimits(
3642 routing_id_, minimum_percent, maximum_percent));
3645 void RenderViewImpl::zoomLevelChanged() {
3646 double zoom_level = webview()->zoomLevel();
3648 // Do not send empty URLs to the browser when we are just setting the default
3649 // zoom level (from RendererPreferences) before the first navigation.
3650 if (!webview()->mainFrame()->document().url().isEmpty()) {
3651 // Tell the browser which url got zoomed so it can update the menu and the
3652 // saved values if necessary
3653 Send(new ViewHostMsg_DidZoomURL(
3654 routing_id_, zoom_level,
3655 GURL(webview()->mainFrame()->document().url())));
3659 void RenderViewImpl::pageScaleFactorChanged() {
3660 if (!webview())
3661 return;
3662 bool page_scale_factor_is_one = webview()->pageScaleFactor() == 1;
3663 if (page_scale_factor_is_one == page_scale_factor_is_one_)
3664 return;
3665 page_scale_factor_is_one_ = page_scale_factor_is_one;
3666 Send(new ViewHostMsg_PageScaleFactorIsOneChanged(routing_id_,
3667 page_scale_factor_is_one_));
3670 double RenderViewImpl::zoomLevelToZoomFactor(double zoom_level) const {
3671 return ZoomLevelToZoomFactor(zoom_level);
3674 double RenderViewImpl::zoomFactorToZoomLevel(double factor) const {
3675 return ZoomFactorToZoomLevel(factor);
3678 void RenderViewImpl::registerProtocolHandler(const WebString& scheme,
3679 const WebURL& url,
3680 const WebString& title) {
3681 bool user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
3682 Send(new ViewHostMsg_RegisterProtocolHandler(routing_id_,
3683 base::UTF16ToUTF8(scheme),
3684 url,
3685 title,
3686 user_gesture));
3689 void RenderViewImpl::unregisterProtocolHandler(const WebString& scheme,
3690 const WebURL& url) {
3691 bool user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
3692 Send(new ViewHostMsg_UnregisterProtocolHandler(routing_id_,
3693 base::UTF16ToUTF8(scheme),
3694 url,
3695 user_gesture));
3698 blink::WebPageVisibilityState RenderViewImpl::visibilityState() const {
3699 blink::WebPageVisibilityState current_state = is_hidden() ?
3700 blink::WebPageVisibilityStateHidden :
3701 blink::WebPageVisibilityStateVisible;
3702 blink::WebPageVisibilityState override_state = current_state;
3703 // TODO(jam): move this method to WebFrameClient.
3704 if (GetContentClient()->renderer()->
3705 ShouldOverridePageVisibilityState(main_render_frame_.get(),
3706 &override_state))
3707 return override_state;
3708 return current_state;
3711 void RenderViewImpl::draggableRegionsChanged() {
3712 FOR_EACH_OBSERVER(
3713 RenderViewObserver,
3714 observers_,
3715 DraggableRegionsChanged(webview()->mainFrame()));
3718 #if defined(OS_ANDROID)
3719 WebContentDetectionResult RenderViewImpl::detectContentAround(
3720 const WebHitTestResult& touch_hit) {
3721 DCHECK(touch_hit.node().isTextNode());
3723 // Process the position with all the registered content detectors until
3724 // a match is found. Priority is provided by their relative order.
3725 for (ContentDetectorList::const_iterator it = content_detectors_.begin();
3726 it != content_detectors_.end(); ++it) {
3727 ContentDetector::Result content = (*it)->FindTappedContent(touch_hit);
3728 if (content.valid) {
3729 return WebContentDetectionResult(content.content_boundaries,
3730 base::UTF8ToUTF16(content.text), content.intent_url);
3733 return WebContentDetectionResult();
3736 void RenderViewImpl::scheduleContentIntent(const WebURL& intent) {
3737 // Introduce a short delay so that the user can notice the content.
3738 base::MessageLoop::current()->PostDelayedTask(
3739 FROM_HERE,
3740 base::Bind(&RenderViewImpl::LaunchAndroidContentIntent,
3741 AsWeakPtr(),
3742 intent,
3743 expected_content_intent_id_),
3744 base::TimeDelta::FromMilliseconds(kContentIntentDelayMilliseconds));
3747 void RenderViewImpl::cancelScheduledContentIntents() {
3748 ++expected_content_intent_id_;
3751 void RenderViewImpl::LaunchAndroidContentIntent(const GURL& intent,
3752 size_t request_id) {
3753 if (request_id != expected_content_intent_id_)
3754 return;
3756 // Remove the content highlighting if any.
3757 scheduleComposite();
3759 if (!intent.is_empty())
3760 Send(new ViewHostMsg_StartContentIntent(routing_id_, intent));
3763 bool RenderViewImpl::openDateTimeChooser(
3764 const blink::WebDateTimeChooserParams& params,
3765 blink::WebDateTimeChooserCompletion* completion) {
3766 // JavaScript may try to open a date time chooser while one is already open.
3767 if (date_time_picker_client_)
3768 return false;
3769 date_time_picker_client_.reset(
3770 new RendererDateTimePicker(this, params, completion));
3771 return date_time_picker_client_->Open();
3774 void RenderViewImpl::DismissDateTimeDialog() {
3775 DCHECK(date_time_picker_client_);
3776 date_time_picker_client_.reset(NULL);
3779 #endif // defined(OS_ANDROID)
3781 void RenderViewImpl::OnShowContextMenu(
3782 ui::MenuSourceType source_type, const gfx::Point& location) {
3783 context_menu_source_type_ = source_type;
3784 has_host_context_menu_location_ = true;
3785 host_context_menu_location_ = location;
3786 if (webview())
3787 webview()->showContextMenu();
3788 has_host_context_menu_location_ = false;
3791 void RenderViewImpl::OnEnableViewSourceMode() {
3792 if (!webview())
3793 return;
3794 WebFrame* main_frame = webview()->mainFrame();
3795 if (!main_frame)
3796 return;
3797 main_frame->enableViewSourceMode(true);
3800 #if defined(OS_ANDROID) || defined(TOOLKIT_VIEWS)
3801 bool RenderViewImpl::didTapMultipleTargets(
3802 const WebSize& inner_viewport_offset,
3803 const WebRect& touch_rect,
3804 const WebVector<WebRect>& target_rects) {
3805 if (!switches::IsLinkDisambiguationPopupEnabled())
3806 return false;
3808 // Never show a disambiguation popup when accessibility is enabled,
3809 // as this interferes with "touch exploration".
3810 AccessibilityMode accessibility_mode =
3811 GetMainRenderFrame()->accessibility_mode();
3812 bool matches_accessibility_mode_complete =
3813 (accessibility_mode & AccessibilityModeComplete) ==
3814 AccessibilityModeComplete;
3815 if (matches_accessibility_mode_complete)
3816 return false;
3818 // The touch_rect, target_rects and zoom_rect are in the outer viewport
3819 // reference frame.
3820 gfx::Rect zoom_rect;
3821 float new_total_scale =
3822 DisambiguationPopupHelper::ComputeZoomAreaAndScaleFactor(
3823 touch_rect, target_rects, GetSize(),
3824 gfx::Rect(webview()->mainFrame()->visibleContentRect()).size(),
3825 device_scale_factor_ * webview()->pageScaleFactor(), &zoom_rect);
3826 if (!new_total_scale || zoom_rect.IsEmpty())
3827 return false;
3829 bool handled = false;
3830 switch (renderer_preferences_.tap_multiple_targets_strategy) {
3831 case TAP_MULTIPLE_TARGETS_STRATEGY_ZOOM:
3832 handled = webview()->zoomToMultipleTargetsRect(zoom_rect);
3833 break;
3834 case TAP_MULTIPLE_TARGETS_STRATEGY_POPUP: {
3835 gfx::Size canvas_size =
3836 gfx::ToCeiledSize(gfx::ScaleSize(zoom_rect.size(), new_total_scale));
3837 cc::SharedBitmapManager* manager =
3838 RenderThreadImpl::current()->shared_bitmap_manager();
3839 scoped_ptr<cc::SharedBitmap> shared_bitmap =
3840 manager->AllocateSharedBitmap(canvas_size);
3841 CHECK(!!shared_bitmap);
3843 SkBitmap bitmap;
3844 SkImageInfo info = SkImageInfo::MakeN32Premul(canvas_size.width(),
3845 canvas_size.height());
3846 bitmap.installPixels(info, shared_bitmap->pixels(), info.minRowBytes());
3847 SkCanvas canvas(bitmap);
3849 // TODO(trchen): Cleanup the device scale factor mess.
3850 // device scale will be applied in WebKit
3851 // --> zoom_rect doesn't include device scale,
3852 // but WebKit will still draw on zoom_rect * device_scale_factor_
3853 canvas.scale(new_total_scale / device_scale_factor_,
3854 new_total_scale / device_scale_factor_);
3855 canvas.translate(-zoom_rect.x() * device_scale_factor_,
3856 -zoom_rect.y() * device_scale_factor_);
3858 DCHECK(webwidget_->isAcceleratedCompositingActive());
3859 // TODO(aelias): The disambiguation popup should be composited so we
3860 // don't have to call this method.
3861 webwidget_->paintCompositedDeprecated(&canvas, zoom_rect);
3864 gfx::Rect zoom_rect_in_screen =
3865 zoom_rect - gfx::Vector2d(inner_viewport_offset.width,
3866 inner_viewport_offset.height);
3868 gfx::Rect physical_window_zoom_rect = gfx::ToEnclosingRect(
3869 ClientRectToPhysicalWindowRect(gfx::RectF(zoom_rect_in_screen)));
3871 Send(new ViewHostMsg_ShowDisambiguationPopup(routing_id_,
3872 physical_window_zoom_rect,
3873 canvas_size,
3874 shared_bitmap->id()));
3875 cc::SharedBitmapId id = shared_bitmap->id();
3876 disambiguation_bitmaps_[id] = shared_bitmap.release();
3877 handled = true;
3878 break;
3880 case TAP_MULTIPLE_TARGETS_STRATEGY_NONE:
3881 // No-op.
3882 break;
3885 return handled;
3887 #endif // defined(OS_ANDROID) || defined(TOOLKIT_VIEWS)
3889 unsigned RenderViewImpl::GetLocalSessionHistoryLengthForTesting() const {
3890 return history_list_length_;
3893 void RenderViewImpl::SetFocusAndActivateForTesting(bool enable) {
3894 if (enable) {
3895 if (has_focus())
3896 return;
3897 OnSetActive(true);
3898 OnSetFocus(true);
3899 } else {
3900 if (!has_focus())
3901 return;
3902 OnSetFocus(false);
3903 OnSetActive(false);
3907 void RenderViewImpl::SetDeviceScaleFactorForTesting(float factor) {
3908 ViewMsg_Resize_Params params;
3909 params.screen_info = screen_info_;
3910 params.screen_info.deviceScaleFactor = factor;
3911 params.new_size = size();
3912 params.visible_viewport_size = visible_viewport_size_;
3913 params.physical_backing_size =
3914 gfx::ToCeiledSize(gfx::ScaleSize(size(), factor));
3915 params.top_controls_shrink_blink_size = false;
3916 params.top_controls_height = 0.f;
3917 params.resizer_rect = WebRect();
3918 params.is_fullscreen = is_fullscreen();
3919 OnResize(params);
3922 void RenderViewImpl::SetDeviceColorProfileForTesting(
3923 const std::vector<char>& color_profile) {
3924 SetDeviceColorProfile(color_profile);
3927 void RenderViewImpl::ForceResizeForTesting(const gfx::Size& new_size) {
3928 gfx::Rect new_window_rect(rootWindowRect().x,
3929 rootWindowRect().y,
3930 new_size.width(),
3931 new_size.height());
3932 SetWindowRectSynchronously(new_window_rect);
3935 void RenderViewImpl::UseSynchronousResizeModeForTesting(bool enable) {
3936 resizing_mode_selector_->set_is_synchronous_mode(enable);
3939 void RenderViewImpl::EnableAutoResizeForTesting(const gfx::Size& min_size,
3940 const gfx::Size& max_size) {
3941 OnEnableAutoResize(min_size, max_size);
3944 void RenderViewImpl::DisableAutoResizeForTesting(const gfx::Size& new_size) {
3945 OnDisableAutoResize(new_size);
3948 void RenderViewImpl::OnReleaseDisambiguationPopupBitmap(
3949 const cc::SharedBitmapId& id) {
3950 BitmapMap::iterator it = disambiguation_bitmaps_.find(id);
3951 DCHECK(it != disambiguation_bitmaps_.end());
3952 delete it->second;
3953 disambiguation_bitmaps_.erase(it);
3956 void RenderViewImpl::DidCommitCompositorFrame() {
3957 RenderWidget::DidCommitCompositorFrame();
3958 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidCommitCompositorFrame());
3961 void RenderViewImpl::SendUpdateFaviconURL(const std::vector<FaviconURL>& urls) {
3962 if (!urls.empty())
3963 Send(new ViewHostMsg_UpdateFaviconURL(routing_id_, urls));
3966 void RenderViewImpl::DidStopLoadingIcons() {
3967 int icon_types = WebIconURL::TypeFavicon | WebIconURL::TypeTouchPrecomposed |
3968 WebIconURL::TypeTouch;
3970 // Favicons matter only for the top-level frame. If it is a WebRemoteFrame,
3971 // just return early.
3972 if (webview()->mainFrame()->isWebRemoteFrame())
3973 return;
3975 WebVector<WebIconURL> icon_urls =
3976 webview()->mainFrame()->iconURLs(icon_types);
3978 std::vector<FaviconURL> urls;
3979 for (size_t i = 0; i < icon_urls.size(); i++) {
3980 WebURL url = icon_urls[i].iconURL();
3981 std::vector<gfx::Size> sizes;
3982 ConvertToFaviconSizes(icon_urls[i].sizes(), &sizes);
3983 if (!url.isEmpty())
3984 urls.push_back(
3985 FaviconURL(url, ToFaviconType(icon_urls[i].iconType()), sizes));
3987 SendUpdateFaviconURL(urls);
3990 } // namespace content