Add ICU message format support
[chromium-blink-merge.git] / content / renderer / render_view_impl.cc
blobeca03fa30f15aa9c5c07e72e10cd773baea5d540
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/metrics/field_trial.h"
22 #include "base/metrics/histogram.h"
23 #include "base/process/kill.h"
24 #include "base/process/process.h"
25 #include "base/strings/string_number_conversions.h"
26 #include "base/strings/string_piece.h"
27 #include "base/strings/string_split.h"
28 #include "base/strings/string_util.h"
29 #include "base/strings/sys_string_conversions.h"
30 #include "base/strings/utf_string_conversions.h"
31 #include "base/time/time.h"
32 #include "base/trace_event/trace_event.h"
33 #include "content/child/appcache/appcache_dispatcher.h"
34 #include "content/child/appcache/web_application_cache_host_impl.h"
35 #include "content/child/child_shared_bitmap_manager.h"
36 #include "content/child/npapi/webplugin_delegate_impl.h"
37 #include "content/child/request_extra_data.h"
38 #include "content/child/v8_value_converter_impl.h"
39 #include "content/child/webmessageportchannel_impl.h"
40 #include "content/common/content_constants_internal.h"
41 #include "content/common/database_messages.h"
42 #include "content/common/dom_storage/dom_storage_types.h"
43 #include "content/common/drag_messages.h"
44 #include "content/common/frame_messages.h"
45 #include "content/common/frame_replication_state.h"
46 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
47 #include "content/common/input_messages.h"
48 #include "content/common/pepper_messages.h"
49 #include "content/common/site_isolation_policy.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/disambiguation_popup_helper.h"
75 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
76 #include "content/renderer/drop_data_builder.h"
77 #include "content/renderer/gpu/render_widget_compositor.h"
78 #include "content/renderer/history_controller.h"
79 #include "content/renderer/history_serialization.h"
80 #include "content/renderer/idle_user_detector.h"
81 #include "content/renderer/ime_event_guard.h"
82 #include "content/renderer/input/input_handler_manager.h"
83 #include "content/renderer/internal_document_state_data.h"
84 #include "content/renderer/media/audio_device_factory.h"
85 #include "content/renderer/media/video_capture_impl_manager.h"
86 #include "content/renderer/mhtml_generator.h"
87 #include "content/renderer/navigation_state_impl.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/WebDocument.h"
138 #include "third_party/WebKit/public/web/WebElement.h"
139 #include "third_party/WebKit/public/web/WebFileChooserParams.h"
140 #include "third_party/WebKit/public/web/WebFindOptions.h"
141 #include "third_party/WebKit/public/web/WebFormControlElement.h"
142 #include "third_party/WebKit/public/web/WebFormElement.h"
143 #include "third_party/WebKit/public/web/WebFrame.h"
144 #include "third_party/WebKit/public/web/WebGlyphCache.h"
145 #include "third_party/WebKit/public/web/WebHistoryItem.h"
146 #include "third_party/WebKit/public/web/WebHitTestResult.h"
147 #include "third_party/WebKit/public/web/WebInputElement.h"
148 #include "third_party/WebKit/public/web/WebInputEvent.h"
149 #include "third_party/WebKit/public/web/WebLocalFrame.h"
150 #include "third_party/WebKit/public/web/WebMediaPlayerAction.h"
151 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
152 #include "third_party/WebKit/public/web/WebNetworkStateNotifier.h"
153 #include "third_party/WebKit/public/web/WebNodeList.h"
154 #include "third_party/WebKit/public/web/WebPageSerializer.h"
155 #include "third_party/WebKit/public/web/WebPlugin.h"
156 #include "third_party/WebKit/public/web/WebPluginAction.h"
157 #include "third_party/WebKit/public/web/WebPluginContainer.h"
158 #include "third_party/WebKit/public/web/WebPluginDocument.h"
159 #include "third_party/WebKit/public/web/WebRange.h"
160 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
161 #include "third_party/WebKit/public/web/WebScriptSource.h"
162 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
163 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
164 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
165 #include "third_party/WebKit/public/web/WebSettings.h"
166 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
167 #include "third_party/WebKit/public/web/WebView.h"
168 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
169 #include "third_party/WebKit/public/web/default/WebRenderTheme.h"
170 #include "third_party/icu/source/common/unicode/uchar.h"
171 #include "third_party/icu/source/common/unicode/uscript.h"
172 #include "ui/base/clipboard/clipboard.h"
173 #include "ui/base/ui_base_switches_util.h"
174 #include "ui/events/latency_info.h"
175 #include "ui/gfx/geometry/point.h"
176 #include "ui/gfx/geometry/rect.h"
177 #include "ui/gfx/geometry/rect_conversions.h"
178 #include "ui/gfx/geometry/size_conversions.h"
179 #include "ui/gfx/native_widget_types.h"
180 #include "v8/include/v8.h"
182 #if defined(OS_ANDROID)
183 #include <cpu-features.h>
185 #include "content/renderer/android/address_detector.h"
186 #include "content/renderer/android/content_detector.h"
187 #include "content/renderer/android/email_detector.h"
188 #include "content/renderer/android/phone_number_detector.h"
189 #include "third_party/WebKit/public/platform/WebFloatPoint.h"
190 #include "third_party/WebKit/public/platform/WebFloatRect.h"
191 #include "ui/gfx/geometry/rect_f.h"
193 #elif defined(OS_WIN)
194 // TODO(port): these files are currently Windows only because they concern:
195 // * theming
196 #include "ui/native_theme/native_theme_win.h"
197 #elif defined(USE_X11)
198 #include "ui/native_theme/native_theme.h"
199 #elif defined(OS_MACOSX)
200 #include "skia/ext/skia_utils_mac.h"
201 #endif
203 #if defined(ENABLE_PLUGINS)
204 #include "content/renderer/npapi/webplugin_delegate_proxy.h"
205 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
206 #include "content/renderer/pepper/pepper_plugin_registry.h"
207 #endif
209 #if defined(ENABLE_WEBRTC)
210 #include "content/renderer/media/rtc_peer_connection_handler.h"
211 #include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
212 #endif
214 using blink::WebAXObject;
215 using blink::WebApplicationCacheHost;
216 using blink::WebApplicationCacheHostClient;
217 using blink::WebCString;
218 using blink::WebColor;
219 using blink::WebColorName;
220 using blink::WebConsoleMessage;
221 using blink::WebData;
222 using blink::WebDataSource;
223 using blink::WebDocument;
224 using blink::WebDragData;
225 using blink::WebDragOperation;
226 using blink::WebDragOperationsMask;
227 using blink::WebElement;
228 using blink::WebFileChooserCompletion;
229 using blink::WebFindOptions;
230 using blink::WebFormControlElement;
231 using blink::WebFormElement;
232 using blink::WebFrame;
233 using blink::WebGestureEvent;
234 using blink::WebHistoryItem;
235 using blink::WebHTTPBody;
236 using blink::WebIconURL;
237 using blink::WebImage;
238 using blink::WebInputElement;
239 using blink::WebInputEvent;
240 using blink::WebLocalFrame;
241 using blink::WebMediaPlayerAction;
242 using blink::WebMouseEvent;
243 using blink::WebNavigationPolicy;
244 using blink::WebNavigationType;
245 using blink::WebNode;
246 using blink::WebPageSerializer;
247 using blink::WebPageSerializerClient;
248 using blink::WebPeerConnection00Handler;
249 using blink::WebPeerConnection00HandlerClient;
250 using blink::WebPeerConnectionHandler;
251 using blink::WebPeerConnectionHandlerClient;
252 using blink::WebPluginAction;
253 using blink::WebPluginContainer;
254 using blink::WebPluginDocument;
255 using blink::WebPoint;
256 using blink::WebRange;
257 using blink::WebRect;
258 using blink::WebReferrerPolicy;
259 using blink::WebScriptSource;
260 using blink::WebSearchableFormData;
261 using blink::WebSecurityOrigin;
262 using blink::WebSecurityPolicy;
263 using blink::WebSettings;
264 using blink::WebSize;
265 using blink::WebStorageNamespace;
266 using blink::WebStorageQuotaCallbacks;
267 using blink::WebStorageQuotaError;
268 using blink::WebStorageQuotaType;
269 using blink::WebString;
270 using blink::WebTextAffinity;
271 using blink::WebTextDirection;
272 using blink::WebTouchEvent;
273 using blink::WebURL;
274 using blink::WebURLError;
275 using blink::WebURLRequest;
276 using blink::WebURLResponse;
277 using blink::WebUserGestureIndicator;
278 using blink::WebVector;
279 using blink::WebView;
280 using blink::WebWidget;
281 using blink::WebWindowFeatures;
282 using blink::WebNetworkStateNotifier;
283 using blink::WebRuntimeFeatures;
284 using base::Time;
285 using base::TimeDelta;
287 #if defined(OS_ANDROID)
288 using blink::WebContentDetectionResult;
289 using blink::WebFloatPoint;
290 using blink::WebFloatRect;
291 using blink::WebHitTestResult;
292 #endif
294 namespace content {
296 //-----------------------------------------------------------------------------
298 typedef std::map<blink::WebView*, RenderViewImpl*> ViewMap;
299 static base::LazyInstance<ViewMap> g_view_map = LAZY_INSTANCE_INITIALIZER;
300 typedef std::map<int32, RenderViewImpl*> RoutingIDViewMap;
301 static base::LazyInstance<RoutingIDViewMap> g_routing_id_view_map =
302 LAZY_INSTANCE_INITIALIZER;
304 // Time, in seconds, we delay before sending content state changes (such as form
305 // state and scroll position) to the browser. We delay sending changes to avoid
306 // spamming the browser.
307 // To avoid having tab/session restore require sending a message to get the
308 // current content state during tab closing we use a shorter timeout for the
309 // foreground renderer. This means there is a small window of time from which
310 // content state is modified and not sent to session restore, but this is
311 // better than having to wake up all renderers during shutdown.
312 const int kDelaySecondsForContentStateSyncHidden = 5;
313 const int kDelaySecondsForContentStateSync = 1;
315 #if defined(OS_ANDROID)
316 // Delay between tapping in content and launching the associated android intent.
317 // Used to allow users see what has been recognized as content.
318 const size_t kContentIntentDelayMilliseconds = 700;
319 #endif
321 static RenderViewImpl* (*g_create_render_view_impl)(
322 CompositorDependencies* compositor_deps,
323 const ViewMsg_New_Params&) = nullptr;
325 // static
326 Referrer RenderViewImpl::GetReferrerFromRequest(
327 WebFrame* frame,
328 const WebURLRequest& request) {
329 return Referrer(GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
330 request.referrerPolicy());
333 // static
334 WindowOpenDisposition RenderViewImpl::NavigationPolicyToDisposition(
335 WebNavigationPolicy policy) {
336 switch (policy) {
337 case blink::WebNavigationPolicyIgnore:
338 return IGNORE_ACTION;
339 case blink::WebNavigationPolicyDownload:
340 return SAVE_TO_DISK;
341 case blink::WebNavigationPolicyCurrentTab:
342 return CURRENT_TAB;
343 case blink::WebNavigationPolicyNewBackgroundTab:
344 return NEW_BACKGROUND_TAB;
345 case blink::WebNavigationPolicyNewForegroundTab:
346 return NEW_FOREGROUND_TAB;
347 case blink::WebNavigationPolicyNewWindow:
348 return NEW_WINDOW;
349 case blink::WebNavigationPolicyNewPopup:
350 return NEW_POPUP;
351 default:
352 NOTREACHED() << "Unexpected WebNavigationPolicy";
353 return IGNORE_ACTION;
357 // Returns true if the device scale is high enough that losing subpixel
358 // antialiasing won't have a noticeable effect on text quality.
359 static bool DeviceScaleEnsuresTextQuality(float device_scale_factor) {
360 #if defined(OS_ANDROID)
361 // On Android, we never have subpixel antialiasing.
362 return true;
363 #else
364 return device_scale_factor > 1.5f;
365 #endif
369 static bool PreferCompositingToLCDText(CompositorDependencies* compositor_deps,
370 float device_scale_factor) {
371 const base::CommandLine& command_line =
372 *base::CommandLine::ForCurrentProcess();
373 if (command_line.HasSwitch(switches::kDisablePreferCompositingToLCDText))
374 return false;
375 if (command_line.HasSwitch(switches::kEnablePreferCompositingToLCDText))
376 return true;
377 if (!compositor_deps->IsLcdTextEnabled())
378 return true;
379 return DeviceScaleEnsuresTextQuality(device_scale_factor);
382 static FaviconURL::IconType ToFaviconType(blink::WebIconURL::Type type) {
383 switch (type) {
384 case blink::WebIconURL::TypeFavicon:
385 return FaviconURL::FAVICON;
386 case blink::WebIconURL::TypeTouch:
387 return FaviconURL::TOUCH_ICON;
388 case blink::WebIconURL::TypeTouchPrecomposed:
389 return FaviconURL::TOUCH_PRECOMPOSED_ICON;
390 case blink::WebIconURL::TypeInvalid:
391 return FaviconURL::INVALID_ICON;
393 return FaviconURL::INVALID_ICON;
396 static void ConvertToFaviconSizes(
397 const blink::WebVector<blink::WebSize>& web_sizes,
398 std::vector<gfx::Size>* sizes) {
399 DCHECK(sizes->empty());
400 sizes->reserve(web_sizes.size());
401 for (size_t i = 0; i < web_sizes.size(); ++i)
402 sizes->push_back(gfx::Size(web_sizes[i]));
405 ///////////////////////////////////////////////////////////////////////////////
407 struct RenderViewImpl::PendingFileChooser {
408 PendingFileChooser(const FileChooserParams& p, WebFileChooserCompletion* c)
409 : params(p),
410 completion(c) {
412 FileChooserParams params;
413 WebFileChooserCompletion* completion; // MAY BE NULL to skip callback.
416 namespace {
418 class WebWidgetLockTarget : public MouseLockDispatcher::LockTarget {
419 public:
420 explicit WebWidgetLockTarget(blink::WebWidget* webwidget)
421 : webwidget_(webwidget) {}
423 void OnLockMouseACK(bool succeeded) override {
424 if (succeeded)
425 webwidget_->didAcquirePointerLock();
426 else
427 webwidget_->didNotAcquirePointerLock();
430 void OnMouseLockLost() override { webwidget_->didLosePointerLock(); }
432 bool HandleMouseLockedInputEvent(const blink::WebMouseEvent& event) override {
433 // The WebWidget handles mouse lock in WebKit's handleInputEvent().
434 return false;
437 private:
438 blink::WebWidget* webwidget_;
441 WebDragData DropDataToWebDragData(const DropData& drop_data) {
442 std::vector<WebDragData::Item> item_list;
444 // These fields are currently unused when dragging into WebKit.
445 DCHECK(drop_data.download_metadata.empty());
446 DCHECK(drop_data.file_contents.empty());
447 DCHECK(drop_data.file_description_filename.empty());
449 if (!drop_data.text.is_null()) {
450 WebDragData::Item item;
451 item.storageType = WebDragData::Item::StorageTypeString;
452 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeText);
453 item.stringData = drop_data.text.string();
454 item_list.push_back(item);
457 // TODO(dcheng): Do we need to distinguish between null and empty URLs? Is it
458 // meaningful to write an empty URL to the clipboard?
459 if (!drop_data.url.is_empty()) {
460 WebDragData::Item item;
461 item.storageType = WebDragData::Item::StorageTypeString;
462 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeURIList);
463 item.stringData = WebString::fromUTF8(drop_data.url.spec());
464 item.title = drop_data.url_title;
465 item_list.push_back(item);
468 if (!drop_data.html.is_null()) {
469 WebDragData::Item item;
470 item.storageType = WebDragData::Item::StorageTypeString;
471 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeHTML);
472 item.stringData = drop_data.html.string();
473 item.baseURL = drop_data.html_base_url;
474 item_list.push_back(item);
477 for (std::vector<ui::FileInfo>::const_iterator it =
478 drop_data.filenames.begin();
479 it != drop_data.filenames.end();
480 ++it) {
481 WebDragData::Item item;
482 item.storageType = WebDragData::Item::StorageTypeFilename;
483 item.filenameData = it->path.AsUTF16Unsafe();
484 item.displayNameData = it->display_name.AsUTF16Unsafe();
485 item_list.push_back(item);
488 for (std::vector<DropData::FileSystemFileInfo>::const_iterator it =
489 drop_data.file_system_files.begin();
490 it != drop_data.file_system_files.end();
491 ++it) {
492 WebDragData::Item item;
493 item.storageType = WebDragData::Item::StorageTypeFileSystemFile;
494 item.fileSystemURL = it->url;
495 item.fileSystemFileSize = it->size;
496 item_list.push_back(item);
499 for (std::map<base::string16, base::string16>::const_iterator it =
500 drop_data.custom_data.begin();
501 it != drop_data.custom_data.end();
502 ++it) {
503 WebDragData::Item item;
504 item.storageType = WebDragData::Item::StorageTypeString;
505 item.stringType = it->first;
506 item.stringData = it->second;
507 item_list.push_back(item);
510 WebDragData result;
511 result.initialize();
512 result.setItems(item_list);
513 result.setFilesystemId(drop_data.filesystem_id);
514 return result;
517 typedef void (*SetFontFamilyWrapper)(blink::WebSettings*,
518 const base::string16&,
519 UScriptCode);
521 void SetStandardFontFamilyWrapper(WebSettings* settings,
522 const base::string16& font,
523 UScriptCode script) {
524 settings->setStandardFontFamily(font, script);
527 void SetFixedFontFamilyWrapper(WebSettings* settings,
528 const base::string16& font,
529 UScriptCode script) {
530 settings->setFixedFontFamily(font, script);
533 void SetSerifFontFamilyWrapper(WebSettings* settings,
534 const base::string16& font,
535 UScriptCode script) {
536 settings->setSerifFontFamily(font, script);
539 void SetSansSerifFontFamilyWrapper(WebSettings* settings,
540 const base::string16& font,
541 UScriptCode script) {
542 settings->setSansSerifFontFamily(font, script);
545 void SetCursiveFontFamilyWrapper(WebSettings* settings,
546 const base::string16& font,
547 UScriptCode script) {
548 settings->setCursiveFontFamily(font, script);
551 void SetFantasyFontFamilyWrapper(WebSettings* settings,
552 const base::string16& font,
553 UScriptCode script) {
554 settings->setFantasyFontFamily(font, script);
557 void SetPictographFontFamilyWrapper(WebSettings* settings,
558 const base::string16& font,
559 UScriptCode script) {
560 settings->setPictographFontFamily(font, script);
563 // If |scriptCode| is a member of a family of "similar" script codes, returns
564 // the script code in that family that is used by WebKit for font selection
565 // purposes. For example, USCRIPT_KATAKANA_OR_HIRAGANA and USCRIPT_JAPANESE are
566 // considered equivalent for the purposes of font selection. WebKit uses the
567 // script code USCRIPT_KATAKANA_OR_HIRAGANA. So, if |scriptCode| is
568 // USCRIPT_JAPANESE, the function returns USCRIPT_KATAKANA_OR_HIRAGANA. WebKit
569 // uses different scripts than the ones in Chrome pref names because the version
570 // of ICU included on certain ports does not have some of the newer scripts. If
571 // |scriptCode| is not a member of such a family, returns |scriptCode|.
572 UScriptCode GetScriptForWebSettings(UScriptCode scriptCode) {
573 switch (scriptCode) {
574 case USCRIPT_HIRAGANA:
575 case USCRIPT_KATAKANA:
576 case USCRIPT_JAPANESE:
577 return USCRIPT_KATAKANA_OR_HIRAGANA;
578 case USCRIPT_KOREAN:
579 return USCRIPT_HANGUL;
580 default:
581 return scriptCode;
585 void ApplyFontsFromMap(const ScriptFontFamilyMap& map,
586 SetFontFamilyWrapper setter,
587 WebSettings* settings) {
588 for (ScriptFontFamilyMap::const_iterator it = map.begin(); it != map.end();
589 ++it) {
590 int32 script = u_getPropertyValueEnum(UCHAR_SCRIPT, (it->first).c_str());
591 if (script >= 0 && script < USCRIPT_CODE_LIMIT) {
592 UScriptCode code = static_cast<UScriptCode>(script);
593 (*setter)(settings, it->second, GetScriptForWebSettings(code));
598 void ApplyBlinkSettings(const base::CommandLine& command_line,
599 WebSettings* settings) {
600 if (!command_line.HasSwitch(switches::kBlinkSettings))
601 return;
603 std::vector<std::string> blink_settings;
604 base::SplitString(
605 command_line.GetSwitchValueASCII(switches::kBlinkSettings), ',',
606 &blink_settings);
607 for (const std::string& setting : blink_settings) {
608 size_t pos = setting.find('=');
609 settings->setFromStrings(
610 blink::WebString::fromLatin1(setting.substr(0, pos)),
611 blink::WebString::fromLatin1(
612 pos == std::string::npos ? "" : setting.substr(pos + 1)));
616 // Looks up and returns the WebFrame corresponding to a given opener frame
617 // routing ID. Also stores the opener's RenderView routing ID into
618 // |opener_view_routing_id|.
619 WebFrame* ResolveOpener(int opener_frame_routing_id,
620 int* opener_view_routing_id) {
621 *opener_view_routing_id = MSG_ROUTING_NONE;
622 if (opener_frame_routing_id == MSG_ROUTING_NONE)
623 return nullptr;
625 // Opener routing ID could refer to either a RenderFrameProxy or a
626 // RenderFrame, so need to check both.
627 RenderFrameProxy* opener_proxy =
628 RenderFrameProxy::FromRoutingID(opener_frame_routing_id);
629 if (opener_proxy) {
630 *opener_view_routing_id = opener_proxy->render_view()->GetRoutingID();
632 // TODO(nasko,alexmos): This check won't be needed once swapped-out:// is
633 // gone.
634 if (opener_proxy->IsMainFrameDetachedFromTree()) {
635 DCHECK(!SiteIsolationPolicy::IsSwappedOutStateForbidden());
636 return opener_proxy->render_view()->webview()->mainFrame();
637 } else {
638 return opener_proxy->web_frame();
642 RenderFrameImpl* opener_frame =
643 RenderFrameImpl::FromRoutingID(opener_frame_routing_id);
644 if (opener_frame) {
645 *opener_view_routing_id = opener_frame->render_view()->GetRoutingID();
646 return opener_frame->GetWebFrame();
649 return nullptr;
652 } // namespace
654 RenderViewImpl::RenderViewImpl(CompositorDependencies* compositor_deps,
655 const ViewMsg_New_Params& params)
656 : RenderWidget(compositor_deps,
657 blink::WebPopupTypeNone,
658 params.initial_size.screen_info,
659 params.swapped_out,
660 params.hidden,
661 params.never_visible),
662 webkit_preferences_(params.web_preferences),
663 send_content_state_immediately_(false),
664 enabled_bindings_(0),
665 send_preferred_size_changes_(false),
666 navigation_gesture_(NavigationGestureUnknown),
667 opened_by_user_gesture_(true),
668 opener_suppressed_(false),
669 suppress_dialogs_until_swap_out_(false),
670 page_id_(-1),
671 next_page_id_(params.next_page_id),
672 history_list_offset_(-1),
673 history_list_length_(0),
674 frames_in_progress_(0),
675 target_url_status_(TARGET_NONE),
676 uses_temporary_zoom_level_(false),
677 #if defined(OS_ANDROID)
678 top_controls_constraints_(TOP_CONTROLS_STATE_BOTH),
679 #endif
680 has_scrolled_focused_editable_node_into_rect_(false),
681 main_render_frame_(nullptr),
682 speech_recognition_dispatcher_(NULL),
683 mouse_lock_dispatcher_(NULL),
684 #if defined(OS_ANDROID)
685 expected_content_intent_id_(0),
686 #endif
687 #if defined(OS_WIN)
688 focused_plugin_id_(-1),
689 #endif
690 #if defined(ENABLE_PLUGINS)
691 plugin_find_handler_(NULL),
692 focused_pepper_plugin_(NULL),
693 pepper_last_mouse_event_target_(NULL),
694 #endif
695 enumeration_completion_id_(0),
696 session_storage_namespace_id_(params.session_storage_namespace_id),
697 page_scale_factor_is_one_(true) {
700 void RenderViewImpl::Initialize(const ViewMsg_New_Params& params,
701 bool was_created_by_renderer) {
702 routing_id_ = params.view_id;
703 surface_id_ = params.surface_id;
705 int opener_view_routing_id;
706 WebFrame* opener_frame =
707 ResolveOpener(params.opener_frame_route_id, &opener_view_routing_id);
708 if (opener_view_routing_id != MSG_ROUTING_NONE && was_created_by_renderer)
709 opener_id_ = opener_view_routing_id;
711 display_mode_= params.initial_size.display_mode;
713 // Ensure we start with a valid next_page_id_ from the browser.
714 DCHECK_GE(next_page_id_, 0);
716 if (params.main_frame_routing_id != MSG_ROUTING_NONE) {
717 main_render_frame_ = RenderFrameImpl::Create(
718 this, params.main_frame_routing_id);
719 // The main frame WebLocalFrame object is closed by
720 // RenderFrameImpl::frameDetached().
721 WebLocalFrame* web_frame = WebLocalFrame::create(
722 blink::WebTreeScopeType::Document, main_render_frame_);
723 main_render_frame_->SetWebFrame(web_frame);
726 webwidget_ = WebView::create(this);
727 webwidget_mouse_lock_target_.reset(new WebWidgetLockTarget(webwidget_));
729 g_view_map.Get().insert(std::make_pair(webview(), this));
730 g_routing_id_view_map.Get().insert(std::make_pair(routing_id_, this));
732 const base::CommandLine& command_line =
733 *base::CommandLine::ForCurrentProcess();
735 if (command_line.HasSwitch(switches::kStatsCollectionController))
736 stats_collection_observer_.reset(new StatsCollectionObserver(this));
738 RenderFrameProxy* proxy = NULL;
739 if (params.proxy_routing_id != MSG_ROUTING_NONE) {
740 CHECK(params.swapped_out);
741 if (main_render_frame_) {
742 proxy = RenderFrameProxy::CreateProxyToReplaceFrame(
743 main_render_frame_, params.proxy_routing_id,
744 blink::WebTreeScopeType::Document);
745 main_render_frame_->set_render_frame_proxy(proxy);
746 } else {
747 proxy = RenderFrameProxy::CreateFrameProxy(
748 params.proxy_routing_id,
749 MSG_ROUTING_NONE,
750 routing_id_,
751 params.replicated_frame_state);
755 // When not using swapped out state, just use the WebRemoteFrame as the main
756 // frame.
757 if (proxy && SiteIsolationPolicy::IsSwappedOutStateForbidden()) {
758 webview()->setMainFrame(proxy->web_frame());
759 // Initialize the WebRemoteFrame with information replicated from the
760 // browser process.
761 proxy->SetReplicatedState(params.replicated_frame_state);
762 } else {
763 webview()->setMainFrame(main_render_frame_->GetWebFrame());
765 if (main_render_frame_)
766 main_render_frame_->Initialize();
768 #if defined(OS_ANDROID)
769 content_detectors_.push_back(linked_ptr<ContentDetector>(
770 new AddressDetector()));
771 const std::string& contry_iso =
772 params.renderer_preferences.network_contry_iso;
773 if (!contry_iso.empty()) {
774 content_detectors_.push_back(linked_ptr<ContentDetector>(
775 new PhoneNumberDetector(contry_iso)));
777 content_detectors_.push_back(linked_ptr<ContentDetector>(
778 new EmailDetector()));
779 #endif
781 RenderThread::Get()->AddRoute(routing_id_, this);
782 // Take a reference on behalf of the RenderThread. This will be balanced
783 // when we receive ViewMsg_Close in the RenderWidget (which RenderView
784 // inherits from).
785 AddRef();
786 if (RenderThreadImpl::current()) {
787 RenderThreadImpl::current()->WidgetCreated();
788 if (is_hidden_)
789 RenderThreadImpl::current()->WidgetHidden();
792 // If this is a popup, we must wait for the CreatingNew_ACK message before
793 // completing initialization. Otherwise, we can finish it now.
794 if (opener_id_ == MSG_ROUTING_NONE) {
795 did_show_ = true;
796 CompleteInit();
799 webview()->setDeviceScaleFactor(device_scale_factor_);
800 webview()->setDisplayMode(display_mode_);
801 webview()->settings()->setPreferCompositingToLCDTextEnabled(
802 PreferCompositingToLCDText(compositor_deps_, device_scale_factor_));
803 webview()->settings()->setThreadedScrollingEnabled(
804 !command_line.HasSwitch(switches::kDisableThreadedScrolling));
805 webview()->settings()->setRootLayerScrolls(
806 command_line.HasSwitch(switches::kRootLayerScrolls));
808 ApplyWebPreferencesInternal(webkit_preferences_, webview(), compositor_deps_);
810 if (switches::IsTouchDragDropEnabled())
811 webview()->settings()->setTouchDragDropEnabled(true);
813 if (switches::IsTouchEditingEnabled())
814 webview()->settings()->setTouchEditingEnabled(true);
816 WebSettings::SelectionStrategyType selection_strategy =
817 WebSettings::SelectionStrategyType::Character;
818 const std::string selection_strategy_str =
819 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
820 switches::kTouchTextSelectionStrategy);
821 if (selection_strategy_str == "direction")
822 selection_strategy = WebSettings::SelectionStrategyType::Direction;
823 webview()->settings()->setSelectionStrategy(selection_strategy);
825 // Set the main frame's name. Only needs to be done for WebLocalFrames,
826 // since the remote case was handled as part of SetReplicatedState on the
827 // proxy above.
828 if (!params.replicated_frame_state.name.empty() &&
829 webview()->mainFrame()->isWebLocalFrame()) {
830 webview()->mainFrame()->setName(
831 blink::WebString::fromUTF8(params.replicated_frame_state.name));
834 // TODO(davidben): Move this state from Blink into content.
835 if (params.window_was_created_with_opener)
836 webview()->setOpenedByDOM();
838 OnSetRendererPrefs(params.renderer_preferences);
840 ApplyBlinkSettings(command_line, webview()->settings());
842 if (!params.enable_auto_resize) {
843 OnResize(params.initial_size);
844 } else {
845 OnEnableAutoResize(params.min_size, params.max_size);
848 new MHTMLGenerator(this);
849 #if defined(OS_MACOSX)
850 new TextInputClientObserver(this);
851 #endif // defined(OS_MACOSX)
853 // The next group of objects all implement RenderViewObserver, so are deleted
854 // along with the RenderView automatically.
855 mouse_lock_dispatcher_ = new RenderViewMouseLockDispatcher(this);
857 history_controller_.reset(new HistoryController(this));
859 new IdleUserDetector(this);
861 if (command_line.HasSwitch(switches::kDomAutomationController))
862 enabled_bindings_ |= BINDINGS_POLICY_DOM_AUTOMATION;
863 if (command_line.HasSwitch(switches::kStatsCollectionController))
864 enabled_bindings_ |= BINDINGS_POLICY_STATS_COLLECTION;
866 GetContentClient()->renderer()->RenderViewCreated(this);
868 // If we have an opener_frame but we weren't created by a renderer, then it's
869 // the browser asking us to set our opener to another frame.
870 if (opener_frame && !was_created_by_renderer)
871 webview()->mainFrame()->setOpener(opener_frame);
873 // If we are initially swapped out, navigate to kSwappedOutURL.
874 // This ensures we are in a unique origin that others cannot script.
875 if (is_swapped_out_ && webview()->mainFrame()->isWebLocalFrame())
876 main_render_frame_->NavigateToSwappedOutURL();
879 RenderViewImpl::~RenderViewImpl() {
880 for (BitmapMap::iterator it = disambiguation_bitmaps_.begin();
881 it != disambiguation_bitmaps_.end();
882 ++it)
883 delete it->second;
885 // If file chooser is still waiting for answer, dispatch empty answer.
886 while (!file_chooser_completions_.empty()) {
887 if (file_chooser_completions_.front()->completion) {
888 file_chooser_completions_.front()->completion->didChooseFile(
889 WebVector<WebString>());
891 file_chooser_completions_.pop_front();
894 #if defined(OS_ANDROID)
895 // The date/time picker client is both a scoped_ptr member of this class and
896 // a RenderViewObserver. Reset it to prevent double deletion.
897 date_time_picker_client_.reset();
898 #endif
900 #ifndef NDEBUG
901 // Make sure we are no longer referenced by the ViewMap or RoutingIDViewMap.
902 ViewMap* views = g_view_map.Pointer();
903 for (ViewMap::iterator it = views->begin(); it != views->end(); ++it)
904 DCHECK_NE(this, it->second) << "Failed to call Close?";
905 RoutingIDViewMap* routing_id_views = g_routing_id_view_map.Pointer();
906 for (RoutingIDViewMap::iterator it = routing_id_views->begin();
907 it != routing_id_views->end(); ++it)
908 DCHECK_NE(this, it->second) << "Failed to call Close?";
909 #endif
911 FOR_EACH_OBSERVER(RenderViewObserver, observers_, RenderViewGone());
912 FOR_EACH_OBSERVER(RenderViewObserver, observers_, OnDestruct());
915 /*static*/
916 RenderViewImpl* RenderViewImpl::FromWebView(WebView* webview) {
917 ViewMap* views = g_view_map.Pointer();
918 ViewMap::iterator it = views->find(webview);
919 return it == views->end() ? NULL : it->second;
922 /*static*/
923 RenderView* RenderView::FromWebView(blink::WebView* webview) {
924 return RenderViewImpl::FromWebView(webview);
927 /*static*/
928 RenderViewImpl* RenderViewImpl::FromRoutingID(int32 routing_id) {
929 RoutingIDViewMap* views = g_routing_id_view_map.Pointer();
930 RoutingIDViewMap::iterator it = views->find(routing_id);
931 return it == views->end() ? NULL : it->second;
934 /*static*/
935 RenderView* RenderView::FromRoutingID(int routing_id) {
936 return RenderViewImpl::FromRoutingID(routing_id);
939 /* static */
940 size_t RenderView::GetRenderViewCount() {
941 return g_view_map.Get().size();
944 /*static*/
945 void RenderView::ForEach(RenderViewVisitor* visitor) {
946 ViewMap* views = g_view_map.Pointer();
947 for (ViewMap::iterator it = views->begin(); it != views->end(); ++it) {
948 if (!visitor->Visit(it->second))
949 return;
953 /*static*/
954 void RenderView::ApplyWebPreferences(const WebPreferences& prefs,
955 WebView* web_view) {
956 WebSettings* settings = web_view->settings();
957 ApplyFontsFromMap(prefs.standard_font_family_map,
958 SetStandardFontFamilyWrapper, settings);
959 ApplyFontsFromMap(prefs.fixed_font_family_map,
960 SetFixedFontFamilyWrapper, settings);
961 ApplyFontsFromMap(prefs.serif_font_family_map,
962 SetSerifFontFamilyWrapper, settings);
963 ApplyFontsFromMap(prefs.sans_serif_font_family_map,
964 SetSansSerifFontFamilyWrapper, settings);
965 ApplyFontsFromMap(prefs.cursive_font_family_map,
966 SetCursiveFontFamilyWrapper, settings);
967 ApplyFontsFromMap(prefs.fantasy_font_family_map,
968 SetFantasyFontFamilyWrapper, settings);
969 ApplyFontsFromMap(prefs.pictograph_font_family_map,
970 SetPictographFontFamilyWrapper, settings);
971 settings->setDefaultFontSize(prefs.default_font_size);
972 settings->setDefaultFixedFontSize(prefs.default_fixed_font_size);
973 settings->setMinimumFontSize(prefs.minimum_font_size);
974 settings->setMinimumLogicalFontSize(prefs.minimum_logical_font_size);
975 settings->setDefaultTextEncodingName(
976 base::ASCIIToUTF16(prefs.default_encoding));
977 settings->setJavaScriptEnabled(prefs.javascript_enabled);
978 settings->setWebSecurityEnabled(prefs.web_security_enabled);
979 settings->setJavaScriptCanOpenWindowsAutomatically(
980 prefs.javascript_can_open_windows_automatically);
981 settings->setLoadsImagesAutomatically(prefs.loads_images_automatically);
982 settings->setImagesEnabled(prefs.images_enabled);
983 settings->setPluginsEnabled(prefs.plugins_enabled);
984 settings->setDOMPasteAllowed(prefs.dom_paste_enabled);
985 settings->setUsesEncodingDetector(prefs.uses_universal_detector);
986 settings->setTextAreasAreResizable(prefs.text_areas_are_resizable);
987 settings->setAllowScriptsToCloseWindows(prefs.allow_scripts_to_close_windows);
988 settings->setDownloadableBinaryFontsEnabled(prefs.remote_fonts_enabled);
989 settings->setJavaScriptCanAccessClipboard(
990 prefs.javascript_can_access_clipboard);
991 WebRuntimeFeatures::enableXSLT(prefs.xslt_enabled);
992 WebRuntimeFeatures::enableSlimmingPaint(prefs.slimming_paint_enabled);
993 settings->setXSSAuditorEnabled(prefs.xss_auditor_enabled);
994 settings->setDNSPrefetchingEnabled(prefs.dns_prefetching_enabled);
995 settings->setLocalStorageEnabled(prefs.local_storage_enabled);
996 settings->setSyncXHRInDocumentsEnabled(prefs.sync_xhr_in_documents_enabled);
997 WebRuntimeFeatures::enableDatabase(prefs.databases_enabled);
998 settings->setOfflineWebApplicationCacheEnabled(
999 prefs.application_cache_enabled);
1000 settings->setCaretBrowsingEnabled(prefs.caret_browsing_enabled);
1001 settings->setHyperlinkAuditingEnabled(prefs.hyperlink_auditing_enabled);
1002 settings->setCookieEnabled(prefs.cookie_enabled);
1003 settings->setNavigateOnDragDrop(prefs.navigate_on_drag_drop);
1005 settings->setJavaEnabled(prefs.java_enabled);
1007 // By default, allow_universal_access_from_file_urls is set to false and thus
1008 // we mitigate attacks from local HTML files by not granting file:// URLs
1009 // universal access. Only test shell will enable this.
1010 settings->setAllowUniversalAccessFromFileURLs(
1011 prefs.allow_universal_access_from_file_urls);
1012 settings->setAllowFileAccessFromFileURLs(
1013 prefs.allow_file_access_from_file_urls);
1015 // Enable the web audio API if requested on the command line.
1016 settings->setWebAudioEnabled(prefs.webaudio_enabled);
1018 // Enable experimental WebGL support if requested on command line
1019 // and support is compiled in.
1020 settings->setExperimentalWebGLEnabled(prefs.experimental_webgl_enabled);
1022 // Disable GL multisampling if requested on command line.
1023 settings->setOpenGLMultisamplingEnabled(prefs.gl_multisampling_enabled);
1025 // Enable WebGL errors to the JS console if requested.
1026 settings->setWebGLErrorsToConsoleEnabled(
1027 prefs.webgl_errors_to_console_enabled);
1029 // Uses the mock theme engine for scrollbars.
1030 settings->setMockScrollbarsEnabled(prefs.mock_scrollbars_enabled);
1032 // Enable gpu-accelerated 2d canvas if requested on the command line.
1033 settings->setAccelerated2dCanvasEnabled(prefs.accelerated_2d_canvas_enabled);
1035 settings->setMinimumAccelerated2dCanvasSize(
1036 prefs.minimum_accelerated_2d_canvas_size);
1038 // Disable antialiasing for 2d canvas if requested on the command line.
1039 settings->setAntialiased2dCanvasEnabled(
1040 !prefs.antialiased_2d_canvas_disabled);
1042 // Enabled antialiasing of clips for 2d canvas if requested on the command
1043 // line.
1044 settings->setAntialiasedClips2dCanvasEnabled(
1045 prefs.antialiased_clips_2d_canvas_enabled);
1047 // Set MSAA sample count for 2d canvas if requested on the command line (or
1048 // default value if not).
1049 settings->setAccelerated2dCanvasMSAASampleCount(
1050 prefs.accelerated_2d_canvas_msaa_sample_count);
1052 WebRuntimeFeatures::enableTextBlobs(prefs.text_blobs_enabled);
1054 settings->setAsynchronousSpellCheckingEnabled(
1055 prefs.asynchronous_spell_checking_enabled);
1056 settings->setUnifiedTextCheckerEnabled(prefs.unified_textchecker_enabled);
1058 // Tabs to link is not part of the settings. WebCore calls
1059 // ChromeClient::tabsToLinks which is part of the glue code.
1060 web_view->setTabsToLinks(prefs.tabs_to_links);
1062 settings->setAllowDisplayOfInsecureContent(
1063 prefs.allow_displaying_insecure_content);
1064 settings->setAllowRunningOfInsecureContent(
1065 prefs.allow_running_insecure_content);
1066 settings->setDisableReadingFromCanvas(prefs.disable_reading_from_canvas);
1067 settings->setStrictMixedContentChecking(prefs.strict_mixed_content_checking);
1069 settings->setStrictlyBlockBlockableMixedContent(
1070 prefs.strictly_block_blockable_mixed_content);
1072 settings->setStrictPowerfulFeatureRestrictions(
1073 prefs.strict_powerful_feature_restrictions);
1074 settings->setPasswordEchoEnabled(prefs.password_echo_enabled);
1075 settings->setShouldPrintBackgrounds(prefs.should_print_backgrounds);
1076 settings->setShouldClearDocumentBackground(
1077 prefs.should_clear_document_background);
1078 settings->setEnableScrollAnimator(prefs.enable_scroll_animator);
1080 WebRuntimeFeatures::enableTouch(prefs.touch_enabled);
1081 settings->setMaxTouchPoints(prefs.pointer_events_max_touch_points);
1082 settings->setAvailablePointerTypes(prefs.available_pointer_types);
1083 settings->setPrimaryPointerType(
1084 static_cast<WebSettings::PointerType>(prefs.primary_pointer_type));
1085 settings->setAvailableHoverTypes(prefs.available_hover_types);
1086 settings->setPrimaryHoverType(
1087 static_cast<WebSettings::HoverType>(prefs.primary_hover_type));
1088 settings->setDeviceSupportsTouch(prefs.device_supports_touch);
1089 settings->setDeviceSupportsMouse(prefs.device_supports_mouse);
1090 settings->setEnableTouchAdjustment(prefs.touch_adjustment_enabled);
1091 settings->setMultiTargetTapNotificationEnabled(
1092 switches::IsLinkDisambiguationPopupEnabled());
1094 WebRuntimeFeatures::enableImageColorProfiles(
1095 prefs.image_color_profiles_enabled);
1096 settings->setShouldRespectImageOrientation(
1097 prefs.should_respect_image_orientation);
1099 settings->setUnsafePluginPastingEnabled(false);
1100 settings->setEditingBehavior(
1101 static_cast<WebSettings::EditingBehavior>(prefs.editing_behavior));
1103 settings->setSupportsMultipleWindows(prefs.supports_multiple_windows);
1105 settings->setInvertViewportScrollOrder(prefs.invert_viewport_scroll_order);
1106 settings->setViewportEnabled(prefs.viewport_enabled);
1107 settings->setLoadWithOverviewMode(prefs.initialize_at_minimum_page_scale);
1108 settings->setViewportMetaEnabled(prefs.viewport_meta_enabled);
1109 settings->setMainFrameResizesAreOrientationChanges(
1110 prefs.main_frame_resizes_are_orientation_changes);
1112 settings->setSmartInsertDeleteEnabled(prefs.smart_insert_delete_enabled);
1114 settings->setSpatialNavigationEnabled(prefs.spatial_navigation_enabled);
1116 settings->setSelectionIncludesAltImageText(true);
1118 settings->setV8CacheOptions(
1119 static_cast<WebSettings::V8CacheOptions>(prefs.v8_cache_options));
1121 settings->setImageAnimationPolicy(
1122 static_cast<WebSettings::ImageAnimationPolicy>(prefs.animation_policy));
1124 // Needs to happen before setIgnoreVIewportTagScaleLimits below.
1125 web_view->setDefaultPageScaleLimits(
1126 prefs.default_minimum_page_scale_factor,
1127 prefs.default_maximum_page_scale_factor);
1129 #if defined(OS_ANDROID)
1130 settings->setAllowCustomScrollbarInMainFrame(false);
1131 settings->setTextAutosizingEnabled(prefs.text_autosizing_enabled);
1132 settings->setAccessibilityFontScaleFactor(prefs.font_scale_factor);
1133 settings->setDeviceScaleAdjustment(prefs.device_scale_adjustment);
1134 settings->setFullscreenSupported(prefs.fullscreen_supported);
1135 web_view->setIgnoreViewportTagScaleLimits(prefs.force_enable_zoom);
1136 settings->setAutoZoomFocusedNodeToLegibleScale(true);
1137 settings->setDoubleTapToZoomEnabled(prefs.double_tap_to_zoom_enabled);
1138 settings->setMediaControlsOverlayPlayButtonEnabled(true);
1139 settings->setMediaPlaybackRequiresUserGesture(
1140 prefs.user_gesture_required_for_media_playback);
1141 settings->setDefaultVideoPosterURL(
1142 base::ASCIIToUTF16(prefs.default_video_poster_url.spec()));
1143 settings->setSupportDeprecatedTargetDensityDPI(
1144 prefs.support_deprecated_target_density_dpi);
1145 settings->setUseLegacyBackgroundSizeShorthandBehavior(
1146 prefs.use_legacy_background_size_shorthand_behavior);
1147 settings->setWideViewportQuirkEnabled(prefs.wide_viewport_quirk);
1148 settings->setUseWideViewport(prefs.use_wide_viewport);
1149 settings->setForceZeroLayoutHeight(prefs.force_zero_layout_height);
1150 settings->setViewportMetaLayoutSizeQuirk(
1151 prefs.viewport_meta_layout_size_quirk);
1152 settings->setViewportMetaMergeContentQuirk(
1153 prefs.viewport_meta_merge_content_quirk);
1154 settings->setViewportMetaNonUserScalableQuirk(
1155 prefs.viewport_meta_non_user_scalable_quirk);
1156 settings->setViewportMetaZeroValuesQuirk(
1157 prefs.viewport_meta_zero_values_quirk);
1158 settings->setClobberUserAgentInitialScaleQuirk(
1159 prefs.clobber_user_agent_initial_scale_quirk);
1160 settings->setIgnoreMainFrameOverflowHiddenQuirk(
1161 prefs.ignore_main_frame_overflow_hidden_quirk);
1162 settings->setReportScreenSizeInPhysicalPixelsQuirk(
1163 prefs.report_screen_size_in_physical_pixels_quirk);
1165 bool record_full_layer =
1166 RenderViewImpl::FromWebView(web_view)
1167 ? RenderViewImpl::FromWebView(web_view)->DoesRecordFullLayer()
1168 : false;
1169 settings->setMainFrameClipsContent(!record_full_layer);
1171 settings->setShrinksViewportContentToFit(true);
1172 settings->setUseMobileViewportStyle(true);
1173 #endif
1175 WebNetworkStateNotifier::setOnLine(prefs.is_online);
1176 WebNetworkStateNotifier::setWebConnectionType(
1177 NetConnectionTypeToWebConnectionType(prefs.connection_type));
1179 settings->setPinchOverlayScrollbarThickness(
1180 prefs.pinch_overlay_scrollbar_thickness);
1181 settings->setUseSolidColorScrollbars(prefs.use_solid_color_scrollbars);
1183 settings->setShowContextMenuOnMouseUp(prefs.context_menu_on_mouse_up);
1185 #if defined(OS_MACOSX)
1186 settings->setDoubleTapToZoomEnabled(true);
1187 web_view->setMaximumLegibleScale(prefs.default_maximum_page_scale_factor);
1188 #endif
1190 #if !defined(OS_ANDROID) && !defined(OS_MACOSX)
1191 // On platforms where the pinch viewport and the layout viewport can
1192 // both show scrollbars, hide pinch scrollbars when we are near minimum
1193 // page scale. (See http://crbug.com/446411 and http://crbug.com/515746.)
1194 settings->setHidePinchScrollbarsNearMinScale(true);
1195 #endif
1198 /*static*/
1199 RenderViewImpl* RenderViewImpl::Create(CompositorDependencies* compositor_deps,
1200 const ViewMsg_New_Params& params,
1201 bool was_created_by_renderer) {
1202 DCHECK(params.view_id != MSG_ROUTING_NONE);
1203 RenderViewImpl* render_view = NULL;
1204 if (g_create_render_view_impl)
1205 render_view = g_create_render_view_impl(compositor_deps, params);
1206 else
1207 render_view = new RenderViewImpl(compositor_deps, params);
1209 render_view->Initialize(params, was_created_by_renderer);
1210 return render_view;
1213 // static
1214 void RenderViewImpl::InstallCreateHook(RenderViewImpl* (
1215 *create_render_view_impl)(CompositorDependencies* compositor_deps,
1216 const ViewMsg_New_Params&)) {
1217 CHECK(!g_create_render_view_impl);
1218 g_create_render_view_impl = create_render_view_impl;
1221 void RenderViewImpl::AddObserver(RenderViewObserver* observer) {
1222 observers_.AddObserver(observer);
1225 void RenderViewImpl::RemoveObserver(RenderViewObserver* observer) {
1226 observer->RenderViewGone();
1227 observers_.RemoveObserver(observer);
1230 blink::WebView* RenderViewImpl::webview() const {
1231 return static_cast<blink::WebView*>(webwidget());
1234 #if defined(ENABLE_PLUGINS)
1235 void RenderViewImpl::PepperInstanceCreated(
1236 PepperPluginInstanceImpl* instance) {
1237 active_pepper_instances_.insert(instance);
1239 RenderFrameImpl* const render_frame = instance->render_frame();
1240 render_frame->Send(
1241 new FrameHostMsg_PepperInstanceCreated(render_frame->GetRoutingID()));
1244 void RenderViewImpl::PepperInstanceDeleted(
1245 PepperPluginInstanceImpl* instance) {
1246 active_pepper_instances_.erase(instance);
1248 if (pepper_last_mouse_event_target_ == instance)
1249 pepper_last_mouse_event_target_ = NULL;
1250 if (focused_pepper_plugin_ == instance)
1251 PepperFocusChanged(instance, false);
1253 RenderFrameImpl* const render_frame = instance->render_frame();
1254 if (render_frame)
1255 render_frame->Send(
1256 new FrameHostMsg_PepperInstanceDeleted(render_frame->GetRoutingID()));
1259 void RenderViewImpl::PepperFocusChanged(PepperPluginInstanceImpl* instance,
1260 bool focused) {
1261 if (focused)
1262 focused_pepper_plugin_ = instance;
1263 else if (focused_pepper_plugin_ == instance)
1264 focused_pepper_plugin_ = NULL;
1266 UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME);
1267 UpdateSelectionBounds();
1270 void RenderViewImpl::RegisterPluginDelegate(WebPluginDelegateProxy* delegate) {
1271 plugin_delegates_.insert(delegate);
1272 // If the renderer is visible, set initial visibility and focus state.
1273 if (!is_hidden()) {
1274 #if defined(OS_MACOSX)
1275 delegate->SetContainerVisibility(true);
1276 if (webview() && webview()->isActive())
1277 delegate->SetWindowFocus(true);
1278 #endif
1280 // Plugins start assuming the content has focus (so that they work in
1281 // environments where RenderView isn't hosting them), so we always have to
1282 // set the initial state. See webplugin_delegate_impl.h for details.
1283 delegate->SetContentAreaFocus(has_focus());
1286 void RenderViewImpl::UnregisterPluginDelegate(
1287 WebPluginDelegateProxy* delegate) {
1288 plugin_delegates_.erase(delegate);
1291 #if defined(OS_WIN)
1292 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1293 if (focused)
1294 focused_plugin_id_ = plugin_id;
1295 else
1296 focused_plugin_id_ = -1;
1298 #endif
1300 #if defined(OS_MACOSX)
1301 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1302 Send(new ViewHostMsg_PluginFocusChanged(routing_id(), focused, plugin_id));
1305 void RenderViewImpl::OnGetRenderedText() {
1306 if (!webview())
1307 return;
1308 // Get rendered text from WebLocalFrame.
1309 // TODO: Currently IPC truncates any data that has a
1310 // size > kMaximumMessageSize. May be split the text into smaller chunks and
1311 // send back using multiple IPC. See http://crbug.com/393444.
1312 static const size_t kMaximumMessageSize = 8 * 1024 * 1024;
1313 std::string text = webview()->mainFrame()->contentAsText(
1314 kMaximumMessageSize).utf8();
1316 Send(new ViewMsg_GetRenderedTextCompleted(routing_id(), text));
1319 void RenderViewImpl::StartPluginIme() {
1320 IPC::Message* msg = new ViewHostMsg_StartPluginIme(routing_id());
1321 // This message can be sent during event-handling, and needs to be delivered
1322 // within that context.
1323 msg->set_unblock(true);
1324 Send(msg);
1326 #endif // defined(OS_MACOSX)
1328 #endif // ENABLE_PLUGINS
1330 void RenderViewImpl::TransferActiveWheelFlingAnimation(
1331 const blink::WebActiveWheelFlingParameters& params) {
1332 if (webview())
1333 webview()->transferActiveWheelFlingAnimation(params);
1336 bool RenderViewImpl::HasIMETextFocus() {
1337 return GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE;
1340 bool RenderViewImpl::OnMessageReceived(const IPC::Message& message) {
1341 WebFrame* main_frame = webview() ? webview()->mainFrame() : NULL;
1342 if (main_frame && main_frame->isWebLocalFrame())
1343 GetContentClient()->SetActiveURL(main_frame->document().url());
1345 base::ObserverListBase<RenderViewObserver>::Iterator it(&observers_);
1346 RenderViewObserver* observer;
1347 while ((observer = it.GetNext()) != NULL)
1348 if (observer->OnMessageReceived(message))
1349 return true;
1351 bool handled = true;
1352 IPC_BEGIN_MESSAGE_MAP(RenderViewImpl, message)
1353 IPC_MESSAGE_HANDLER(InputMsg_ExecuteEditCommand, OnExecuteEditCommand)
1354 IPC_MESSAGE_HANDLER(InputMsg_MoveCaret, OnMoveCaret)
1355 IPC_MESSAGE_HANDLER(InputMsg_ScrollFocusedEditableNodeIntoRect,
1356 OnScrollFocusedEditableNodeIntoRect)
1357 IPC_MESSAGE_HANDLER(InputMsg_SetEditCommandsForNextKeyEvent,
1358 OnSetEditCommandsForNextKeyEvent)
1359 IPC_MESSAGE_HANDLER(ViewMsg_CopyImageAt, OnCopyImageAt)
1360 IPC_MESSAGE_HANDLER(ViewMsg_SaveImageAt, OnSaveImageAt)
1361 IPC_MESSAGE_HANDLER(ViewMsg_Find, OnFind)
1362 IPC_MESSAGE_HANDLER(ViewMsg_StopFinding, OnStopFinding)
1363 IPC_MESSAGE_HANDLER(ViewMsg_ResetPageScale, OnResetPageScale)
1364 IPC_MESSAGE_HANDLER(ViewMsg_Zoom, OnZoom)
1365 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForLoadingURL,
1366 OnSetZoomLevelForLoadingURL)
1367 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForView,
1368 OnSetZoomLevelForView)
1369 IPC_MESSAGE_HANDLER(ViewMsg_SetPageEncoding, OnSetPageEncoding)
1370 IPC_MESSAGE_HANDLER(ViewMsg_ResetPageEncodingToDefault,
1371 OnResetPageEncodingToDefault)
1372 IPC_MESSAGE_HANDLER(DragMsg_TargetDragEnter, OnDragTargetDragEnter)
1373 IPC_MESSAGE_HANDLER(DragMsg_TargetDragOver, OnDragTargetDragOver)
1374 IPC_MESSAGE_HANDLER(DragMsg_TargetDragLeave, OnDragTargetDragLeave)
1375 IPC_MESSAGE_HANDLER(DragMsg_TargetDrop, OnDragTargetDrop)
1376 IPC_MESSAGE_HANDLER(DragMsg_SourceEnded, OnDragSourceEnded)
1377 IPC_MESSAGE_HANDLER(DragMsg_SourceSystemDragEnded,
1378 OnDragSourceSystemDragEnded)
1379 IPC_MESSAGE_HANDLER(ViewMsg_AllowBindings, OnAllowBindings)
1380 IPC_MESSAGE_HANDLER(ViewMsg_SetInitialFocus, OnSetInitialFocus)
1381 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTargetURL_ACK, OnUpdateTargetURLAck)
1382 IPC_MESSAGE_HANDLER(ViewMsg_UpdateWebPreferences, OnUpdateWebPreferences)
1383 IPC_MESSAGE_HANDLER(ViewMsg_EnumerateDirectoryResponse,
1384 OnEnumerateDirectoryResponse)
1385 IPC_MESSAGE_HANDLER(ViewMsg_RunFileChooserResponse, OnFileChooserResponse)
1386 IPC_MESSAGE_HANDLER(ViewMsg_SuppressDialogsUntilSwapOut,
1387 OnSuppressDialogsUntilSwapOut)
1388 IPC_MESSAGE_HANDLER(ViewMsg_ClosePage, OnClosePage)
1389 IPC_MESSAGE_HANDLER(ViewMsg_ThemeChanged, OnThemeChanged)
1390 IPC_MESSAGE_HANDLER(ViewMsg_MoveOrResizeStarted, OnMoveOrResizeStarted)
1391 IPC_MESSAGE_HANDLER(ViewMsg_ClearFocusedElement, OnClearFocusedElement)
1392 IPC_MESSAGE_HANDLER(ViewMsg_SetBackgroundOpaque, OnSetBackgroundOpaque)
1393 IPC_MESSAGE_HANDLER(ViewMsg_EnablePreferredSizeChangedMode,
1394 OnEnablePreferredSizeChangedMode)
1395 IPC_MESSAGE_HANDLER(ViewMsg_EnableAutoResize, OnEnableAutoResize)
1396 IPC_MESSAGE_HANDLER(ViewMsg_DisableAutoResize, OnDisableAutoResize)
1397 IPC_MESSAGE_HANDLER(ViewMsg_DisableScrollbarsForSmallWindows,
1398 OnDisableScrollbarsForSmallWindows)
1399 IPC_MESSAGE_HANDLER(ViewMsg_SetRendererPrefs, OnSetRendererPrefs)
1400 IPC_MESSAGE_HANDLER(ViewMsg_MediaPlayerActionAt, OnMediaPlayerActionAt)
1401 IPC_MESSAGE_HANDLER(ViewMsg_PluginActionAt, OnPluginActionAt)
1402 IPC_MESSAGE_HANDLER(ViewMsg_SetActive, OnSetActive)
1403 IPC_MESSAGE_HANDLER(ViewMsg_GetAllSavableResourceLinksForCurrentPage,
1404 OnGetAllSavableResourceLinksForCurrentPage)
1405 IPC_MESSAGE_HANDLER(
1406 ViewMsg_GetSerializedHtmlDataForCurrentPageWithLocalLinks,
1407 OnGetSerializedHtmlDataForCurrentPageWithLocalLinks)
1408 IPC_MESSAGE_HANDLER(ViewMsg_ShowContextMenu, OnShowContextMenu)
1409 // TODO(viettrungluu): Move to a separate message filter.
1410 IPC_MESSAGE_HANDLER(ViewMsg_SetHistoryOffsetAndLength,
1411 OnSetHistoryOffsetAndLength)
1412 IPC_MESSAGE_HANDLER(ViewMsg_EnableViewSourceMode, OnEnableViewSourceMode)
1413 IPC_MESSAGE_HANDLER(ViewMsg_ReleaseDisambiguationPopupBitmap,
1414 OnReleaseDisambiguationPopupBitmap)
1415 IPC_MESSAGE_HANDLER(ViewMsg_ForceRedraw, OnForceRedraw)
1416 IPC_MESSAGE_HANDLER(ViewMsg_SelectWordAroundCaret, OnSelectWordAroundCaret)
1417 #if defined(OS_ANDROID)
1418 IPC_MESSAGE_HANDLER(InputMsg_ActivateNearestFindResult,
1419 OnActivateNearestFindResult)
1420 IPC_MESSAGE_HANDLER(ViewMsg_FindMatchRects, OnFindMatchRects)
1421 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTopControlsState,
1422 OnUpdateTopControlsState)
1423 IPC_MESSAGE_HANDLER(ViewMsg_ExtractSmartClipData, OnExtractSmartClipData)
1424 #elif defined(OS_MACOSX)
1425 IPC_MESSAGE_HANDLER(ViewMsg_GetRenderedText,
1426 OnGetRenderedText)
1427 IPC_MESSAGE_HANDLER(ViewMsg_PluginImeCompositionCompleted,
1428 OnPluginImeCompositionCompleted)
1429 IPC_MESSAGE_HANDLER(ViewMsg_Close, OnClose)
1430 IPC_MESSAGE_HANDLER(ViewMsg_SetInLiveResize, OnSetInLiveResize)
1431 IPC_MESSAGE_HANDLER(ViewMsg_SetWindowVisibility, OnSetWindowVisibility)
1432 IPC_MESSAGE_HANDLER(ViewMsg_WindowFrameChanged, OnWindowFrameChanged)
1433 #endif
1434 // Adding a new message? Add platform independent ones first, then put the
1435 // platform specific ones at the end.
1437 // Have the super handle all other messages.
1438 IPC_MESSAGE_UNHANDLED(handled = RenderWidget::OnMessageReceived(message))
1439 IPC_END_MESSAGE_MAP()
1441 return handled;
1444 void RenderViewImpl::OnSelectWordAroundCaret() {
1445 if (!webview())
1446 return;
1448 handling_input_event_ = true;
1449 webview()->focusedFrame()->selectWordAroundCaret();
1450 handling_input_event_ = false;
1453 void RenderViewImpl::OnCopyImageAt(int x, int y) {
1454 webview()->copyImageAt(WebPoint(x, y));
1457 void RenderViewImpl::OnSaveImageAt(int x, int y) {
1458 webview()->saveImageAt(WebPoint(x, y));
1461 void RenderViewImpl::OnUpdateTargetURLAck() {
1462 // Check if there is a targeturl waiting to be sent.
1463 if (target_url_status_ == TARGET_PENDING)
1464 Send(new ViewHostMsg_UpdateTargetURL(routing_id_, pending_target_url_));
1466 target_url_status_ = TARGET_NONE;
1469 void RenderViewImpl::OnExecuteEditCommand(const std::string& name,
1470 const std::string& value) {
1471 if (!webview() || !webview()->focusedFrame())
1472 return;
1474 webview()->focusedFrame()->executeCommand(
1475 WebString::fromUTF8(name), WebString::fromUTF8(value));
1478 void RenderViewImpl::OnMoveCaret(const gfx::Point& point) {
1479 if (!webview())
1480 return;
1482 Send(new InputHostMsg_MoveCaret_ACK(routing_id_));
1484 webview()->focusedFrame()->moveCaretSelection(point);
1487 void RenderViewImpl::OnScrollFocusedEditableNodeIntoRect(
1488 const gfx::Rect& rect) {
1489 if (has_scrolled_focused_editable_node_into_rect_ &&
1490 rect == rect_for_scrolled_focused_editable_node_) {
1491 FocusChangeComplete();
1492 return;
1495 blink::WebElement element = GetFocusedElement();
1496 bool will_animate = false;
1497 if (!element.isNull() && IsEditableNode(element)) {
1498 rect_for_scrolled_focused_editable_node_ = rect;
1499 has_scrolled_focused_editable_node_into_rect_ = true;
1500 will_animate = webview()->scrollFocusedNodeIntoRect(rect);
1503 if (!will_animate)
1504 FocusChangeComplete();
1507 void RenderViewImpl::OnSetEditCommandsForNextKeyEvent(
1508 const EditCommands& edit_commands) {
1509 edit_commands_ = edit_commands;
1512 void RenderViewImpl::OnSetHistoryOffsetAndLength(int history_offset,
1513 int history_length) {
1514 DCHECK_GE(history_offset, -1);
1515 DCHECK_GE(history_length, 0);
1517 history_list_offset_ = history_offset;
1518 history_list_length_ = history_length;
1521 void RenderViewImpl::OnSetInitialFocus(bool reverse) {
1522 if (!webview())
1523 return;
1524 webview()->setInitialFocus(reverse);
1527 #if defined(OS_MACOSX)
1528 void RenderViewImpl::OnSetInLiveResize(bool in_live_resize) {
1529 if (!webview())
1530 return;
1531 if (in_live_resize)
1532 webview()->willStartLiveResize();
1533 else
1534 webview()->willEndLiveResize();
1536 #endif
1538 ///////////////////////////////////////////////////////////////////////////////
1540 void RenderViewImpl::SendUpdateState() {
1541 HistoryEntry* entry = history_controller_->GetCurrentEntry();
1542 if (!entry)
1543 return;
1545 // Don't send state updates for kSwappedOutURL.
1546 if (entry->root().urlString() == WebString::fromUTF8(kSwappedOutURL))
1547 return;
1549 Send(new ViewHostMsg_UpdateState(
1550 routing_id_, page_id_, HistoryEntryToPageState(entry)));
1553 void RenderViewImpl::ApplyWebPreferencesInternal(
1554 const WebPreferences& prefs,
1555 blink::WebView* web_view,
1556 CompositorDependencies* compositor_deps) {
1557 ApplyWebPreferences(prefs, web_view);
1558 #if defined(OS_MACOSX) && !defined(OS_IOS)
1559 DCHECK(compositor_deps);
1560 bool is_elastic_overscroll_enabled =
1561 compositor_deps->IsElasticOverscrollEnabled();
1562 web_view->settings()->setReportWheelOverscroll(is_elastic_overscroll_enabled);
1563 #endif
1566 bool RenderViewImpl::SendAndRunNestedMessageLoop(IPC::SyncMessage* message) {
1567 // Before WebKit asks us to show an alert (etc.), it takes care of doing the
1568 // equivalent of WebView::willEnterModalLoop. In the case of showModalDialog
1569 // it is particularly important that we do not call willEnterModalLoop as
1570 // that would defer resource loads for the dialog itself.
1571 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
1572 RenderThreadImpl::current()->DoNotNotifyWebKitOfModalLoop();
1574 message->EnableMessagePumping(); // Runs a nested message loop.
1575 return Send(message);
1578 void RenderViewImpl::OnForceRedraw(int id) {
1579 ui::LatencyInfo latency_info;
1580 if (id) {
1581 latency_info.AddLatencyNumber(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
1583 id);
1585 scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor;
1586 if (RenderWidgetCompositor* rwc = compositor()) {
1587 latency_info_swap_promise_monitor =
1588 rwc->CreateLatencyInfoSwapPromiseMonitor(&latency_info).Pass();
1590 ScheduleCompositeWithForcedRedraw();
1593 // blink::WebViewClient ------------------------------------------------------
1595 WebView* RenderViewImpl::createView(WebLocalFrame* creator,
1596 const WebURLRequest& request,
1597 const WebWindowFeatures& features,
1598 const WebString& frame_name,
1599 WebNavigationPolicy policy,
1600 bool suppress_opener) {
1601 ViewHostMsg_CreateWindow_Params params;
1602 params.opener_id = routing_id_;
1603 params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
1604 if (GetContentClient()->renderer()->AllowPopup())
1605 params.user_gesture = true;
1606 params.window_container_type = WindowFeaturesToContainerType(features);
1607 params.session_storage_namespace_id = session_storage_namespace_id_;
1608 if (frame_name != "_blank")
1609 params.frame_name = base::UTF16ToUTF8(base::StringPiece16(frame_name));
1610 params.opener_render_frame_id =
1611 RenderFrameImpl::FromWebFrame(creator)->GetRoutingID();
1612 params.opener_url = creator->document().url();
1614 // The browser process uses the top frame's URL for a content settings check
1615 // to determine whether the popup is allowed. If the top frame is remote,
1616 // its URL is not available, so use its replicated origin instead.
1618 // TODO(alexmos): This works fine for regular origins but may break path
1619 // matching for file URLs with OOP subframes that open popups. This should
1620 // be fixed by either moving this lookup to the browser process or removing
1621 // path-based matching for file URLs from content settings. See
1622 // https://crbug.com/466297.
1623 if (creator->top()->isWebLocalFrame()) {
1624 params.opener_top_level_frame_url = creator->top()->document().url();
1625 } else {
1626 params.opener_top_level_frame_url =
1627 GURL(creator->top()->securityOrigin().toString());
1630 GURL security_url(creator->document().securityOrigin().toString());
1631 if (!security_url.is_valid())
1632 security_url = GURL();
1633 params.opener_security_origin = security_url;
1634 params.opener_suppressed = suppress_opener;
1635 params.disposition = NavigationPolicyToDisposition(policy);
1636 if (!request.isNull()) {
1637 params.target_url = request.url();
1638 params.referrer = GetReferrerFromRequest(creator, request);
1640 params.features = features;
1642 for (size_t i = 0; i < features.additionalFeatures.size(); ++i)
1643 params.additional_features.push_back(features.additionalFeatures[i]);
1645 int32 routing_id = MSG_ROUTING_NONE;
1646 int32 main_frame_routing_id = MSG_ROUTING_NONE;
1647 int32 surface_id = 0;
1648 int64 cloned_session_storage_namespace_id = 0;
1650 RenderThread::Get()->Send(new ViewHostMsg_CreateWindow(
1651 params, &routing_id, &main_frame_routing_id, &surface_id,
1652 &cloned_session_storage_namespace_id));
1653 if (routing_id == MSG_ROUTING_NONE)
1654 return NULL;
1656 WebUserGestureIndicator::consumeUserGesture();
1658 // While this view may be a background extension page, it can spawn a visible
1659 // render view. So we just assume that the new one is not another background
1660 // page instead of passing on our own value.
1661 // TODO(vangelis): Can we tell if the new view will be a background page?
1662 bool never_visible = false;
1664 ViewMsg_Resize_Params initial_size = ViewMsg_Resize_Params();
1665 initial_size.screen_info = screen_info_;
1667 // The initial hidden state for the RenderViewImpl here has to match what the
1668 // browser will eventually decide for the given disposition. Since we have to
1669 // return from this call synchronously, we just have to make our best guess
1670 // and rely on the browser sending a WasHidden / WasShown message if it
1671 // disagrees.
1672 ViewMsg_New_Params view_params;
1674 RenderFrameImpl* creator_frame = RenderFrameImpl::FromWebFrame(creator);
1675 view_params.opener_frame_route_id = creator_frame->GetRoutingID();
1676 DCHECK_EQ(routing_id_, creator_frame->render_view()->GetRoutingID());
1678 view_params.window_was_created_with_opener = true;
1679 view_params.renderer_preferences = renderer_preferences_;
1680 view_params.web_preferences = webkit_preferences_;
1681 view_params.view_id = routing_id;
1682 view_params.main_frame_routing_id = main_frame_routing_id;
1683 view_params.surface_id = surface_id;
1684 view_params.session_storage_namespace_id =
1685 cloned_session_storage_namespace_id;
1686 view_params.swapped_out = false;
1687 // WebCore will take care of setting the correct name.
1688 view_params.replicated_frame_state = FrameReplicationState();
1689 view_params.proxy_routing_id = MSG_ROUTING_NONE;
1690 view_params.hidden = (params.disposition == NEW_BACKGROUND_TAB);
1691 view_params.never_visible = never_visible;
1692 view_params.next_page_id = 1;
1693 view_params.initial_size = initial_size;
1694 view_params.enable_auto_resize = false;
1695 view_params.min_size = gfx::Size();
1696 view_params.max_size = gfx::Size();
1698 RenderViewImpl* view =
1699 RenderViewImpl::Create(compositor_deps_, view_params, true);
1700 view->opened_by_user_gesture_ = params.user_gesture;
1702 // Record whether the creator frame is trying to suppress the opener field.
1703 view->opener_suppressed_ = params.opener_suppressed;
1705 return view->webview();
1708 WebWidget* RenderViewImpl::createPopupMenu(blink::WebPopupType popup_type) {
1709 RenderWidget* widget = RenderWidget::Create(routing_id_, compositor_deps_,
1710 popup_type, screen_info_);
1711 if (!widget)
1712 return NULL;
1713 if (screen_metrics_emulator_) {
1714 widget->SetPopupOriginAdjustmentsForEmulation(
1715 screen_metrics_emulator_.get());
1717 return widget->webwidget();
1720 WebStorageNamespace* RenderViewImpl::createSessionStorageNamespace() {
1721 CHECK(session_storage_namespace_id_ != kInvalidSessionStorageNamespaceId);
1722 return new WebStorageNamespaceImpl(session_storage_namespace_id_);
1725 void RenderViewImpl::printPage(WebLocalFrame* frame) {
1726 FOR_EACH_OBSERVER(RenderViewObserver, observers_,
1727 PrintPage(frame, handling_input_event_));
1730 void RenderViewImpl::saveImageFromDataURL(const blink::WebString& data_url) {
1731 // Note: We should basically send GURL but we use size-limited string instead
1732 // in order to send a larger data url to save a image for <canvas> or <img>.
1733 if (data_url.length() < kMaxLengthOfDataURLString)
1734 Send(new ViewHostMsg_SaveImageFromDataURL(routing_id_, data_url.utf8()));
1737 bool RenderViewImpl::enumerateChosenDirectory(
1738 const WebString& path,
1739 WebFileChooserCompletion* chooser_completion) {
1740 int id = enumeration_completion_id_++;
1741 enumeration_completions_[id] = chooser_completion;
1742 return Send(new ViewHostMsg_EnumerateDirectory(
1743 routing_id_,
1745 base::FilePath::FromUTF16Unsafe(path)));
1748 void RenderViewImpl::FrameDidStartLoading(WebFrame* frame) {
1749 DCHECK_GE(frames_in_progress_, 0);
1750 if (frames_in_progress_ == 0)
1751 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStartLoading());
1752 frames_in_progress_++;
1755 void RenderViewImpl::FrameDidStopLoading(WebFrame* frame) {
1756 // TODO(japhet): This should be a DCHECK, but the pdf plugin sometimes
1757 // calls DidStopLoading() without a matching DidStartLoading().
1758 if (frames_in_progress_ == 0)
1759 return;
1760 frames_in_progress_--;
1761 if (frames_in_progress_ == 0) {
1762 DidStopLoadingIcons();
1763 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStopLoading());
1767 void RenderViewImpl::didCancelCompositionOnSelectionChange() {
1768 Send(new InputHostMsg_ImeCancelComposition(routing_id()));
1771 bool RenderViewImpl::handleCurrentKeyboardEvent() {
1772 if (edit_commands_.empty())
1773 return false;
1775 WebFrame* frame = webview()->focusedFrame();
1776 if (!frame)
1777 return false;
1779 EditCommands::iterator it = edit_commands_.begin();
1780 EditCommands::iterator end = edit_commands_.end();
1782 bool did_execute_command = false;
1783 for (; it != end; ++it) {
1784 // In gtk and cocoa, it's possible to bind multiple edit commands to one
1785 // key (but it's the exception). Once one edit command is not executed, it
1786 // seems safest to not execute the rest.
1787 if (!frame->executeCommand(WebString::fromUTF8(it->name),
1788 WebString::fromUTF8(it->value),
1789 GetFocusedElement()))
1790 break;
1791 did_execute_command = true;
1794 return did_execute_command;
1797 bool RenderViewImpl::runFileChooser(
1798 const blink::WebFileChooserParams& params,
1799 WebFileChooserCompletion* chooser_completion) {
1800 // Do not open the file dialog in a hidden RenderView.
1801 if (is_hidden())
1802 return false;
1803 FileChooserParams ipc_params;
1804 if (params.directory)
1805 ipc_params.mode = FileChooserParams::UploadFolder;
1806 else if (params.multiSelect)
1807 ipc_params.mode = FileChooserParams::OpenMultiple;
1808 else if (params.saveAs)
1809 ipc_params.mode = FileChooserParams::Save;
1810 else
1811 ipc_params.mode = FileChooserParams::Open;
1812 ipc_params.title = params.title;
1813 ipc_params.default_file_name =
1814 base::FilePath::FromUTF16Unsafe(params.initialValue).BaseName();
1815 ipc_params.accept_types.reserve(params.acceptTypes.size());
1816 for (size_t i = 0; i < params.acceptTypes.size(); ++i)
1817 ipc_params.accept_types.push_back(params.acceptTypes[i]);
1818 ipc_params.need_local_path = params.needLocalPath;
1819 #if defined(OS_ANDROID)
1820 ipc_params.capture = params.useMediaCapture;
1821 #endif
1823 return ScheduleFileChooser(ipc_params, chooser_completion);
1826 void RenderViewImpl::SetValidationMessageDirection(
1827 base::string16* wrapped_main_text,
1828 blink::WebTextDirection main_text_hint,
1829 base::string16* wrapped_sub_text,
1830 blink::WebTextDirection sub_text_hint) {
1831 if (main_text_hint == blink::WebTextDirectionLeftToRight) {
1832 *wrapped_main_text =
1833 base::i18n::GetDisplayStringInLTRDirectionality(*wrapped_main_text);
1834 } else if (main_text_hint == blink::WebTextDirectionRightToLeft &&
1835 !base::i18n::IsRTL()) {
1836 base::i18n::WrapStringWithRTLFormatting(wrapped_main_text);
1839 if (!wrapped_sub_text->empty()) {
1840 if (sub_text_hint == blink::WebTextDirectionLeftToRight) {
1841 *wrapped_sub_text =
1842 base::i18n::GetDisplayStringInLTRDirectionality(*wrapped_sub_text);
1843 } else if (sub_text_hint == blink::WebTextDirectionRightToLeft) {
1844 base::i18n::WrapStringWithRTLFormatting(wrapped_sub_text);
1849 void RenderViewImpl::showValidationMessage(
1850 const blink::WebRect& anchor_in_root_view,
1851 const blink::WebString& main_text,
1852 blink::WebTextDirection main_text_hint,
1853 const blink::WebString& sub_text,
1854 blink::WebTextDirection sub_text_hint) {
1855 base::string16 wrapped_main_text = main_text;
1856 base::string16 wrapped_sub_text = sub_text;
1858 SetValidationMessageDirection(
1859 &wrapped_main_text, main_text_hint, &wrapped_sub_text, sub_text_hint);
1861 Send(new ViewHostMsg_ShowValidationMessage(
1862 routing_id(), AdjustValidationMessageAnchor(anchor_in_root_view),
1863 wrapped_main_text, wrapped_sub_text));
1866 void RenderViewImpl::hideValidationMessage() {
1867 Send(new ViewHostMsg_HideValidationMessage(routing_id()));
1870 void RenderViewImpl::moveValidationMessage(
1871 const blink::WebRect& anchor_in_root_view) {
1872 Send(new ViewHostMsg_MoveValidationMessage(
1873 routing_id(), AdjustValidationMessageAnchor(anchor_in_root_view)));
1876 void RenderViewImpl::setStatusText(const WebString& text) {
1879 void RenderViewImpl::UpdateTargetURL(const GURL& url,
1880 const GURL& fallback_url) {
1881 GURL latest_url = url.is_empty() ? fallback_url : url;
1882 if (latest_url == target_url_)
1883 return;
1885 // Tell the browser to display a destination link.
1886 if (target_url_status_ == TARGET_INFLIGHT ||
1887 target_url_status_ == TARGET_PENDING) {
1888 // If we have a request in-flight, save the URL to be sent when we
1889 // receive an ACK to the in-flight request. We can happily overwrite
1890 // any existing pending sends.
1891 pending_target_url_ = latest_url;
1892 target_url_status_ = TARGET_PENDING;
1893 } else {
1894 // URLs larger than |MaxURLChars()| cannot be sent through IPC -
1895 // see |ParamTraits<GURL>|.
1896 if (latest_url.possibly_invalid_spec().size() > GetMaxURLChars())
1897 latest_url = GURL();
1898 Send(new ViewHostMsg_UpdateTargetURL(routing_id_, latest_url));
1899 target_url_ = latest_url;
1900 target_url_status_ = TARGET_INFLIGHT;
1904 gfx::RectF RenderViewImpl::ClientRectToPhysicalWindowRect(
1905 const gfx::RectF& rect) const {
1906 gfx::RectF window_rect = rect;
1907 window_rect.Scale(device_scale_factor_ * webview()->pageScaleFactor());
1908 return window_rect;
1911 void RenderViewImpl::StartNavStateSyncTimerIfNecessary() {
1912 int delay;
1913 if (send_content_state_immediately_)
1914 delay = 0;
1915 else if (is_hidden())
1916 delay = kDelaySecondsForContentStateSyncHidden;
1917 else
1918 delay = kDelaySecondsForContentStateSync;
1920 if (nav_state_sync_timer_.IsRunning()) {
1921 // The timer is already running. If the delay of the timer maches the amount
1922 // we want to delay by, then return. Otherwise stop the timer so that it
1923 // gets started with the right delay.
1924 if (nav_state_sync_timer_.GetCurrentDelay().InSeconds() == delay)
1925 return;
1926 nav_state_sync_timer_.Stop();
1929 nav_state_sync_timer_.Start(FROM_HERE, TimeDelta::FromSeconds(delay), this,
1930 &RenderViewImpl::SendUpdateState);
1933 void RenderViewImpl::setMouseOverURL(const WebURL& url) {
1934 mouse_over_url_ = GURL(url);
1935 UpdateTargetURL(mouse_over_url_, focus_url_);
1938 void RenderViewImpl::setKeyboardFocusURL(const WebURL& url) {
1939 focus_url_ = GURL(url);
1940 UpdateTargetURL(focus_url_, mouse_over_url_);
1943 void RenderViewImpl::startDragging(WebLocalFrame* frame,
1944 const WebDragData& data,
1945 WebDragOperationsMask mask,
1946 const WebImage& image,
1947 const WebPoint& webImageOffset) {
1948 DropData drop_data(DropDataBuilder::Build(data));
1949 drop_data.referrer_policy = frame->document().referrerPolicy();
1950 gfx::Vector2d imageOffset(webImageOffset.x, webImageOffset.y);
1951 Send(new DragHostMsg_StartDragging(routing_id_,
1952 drop_data,
1953 mask,
1954 image.getSkBitmap(),
1955 imageOffset,
1956 possible_drag_event_info_));
1959 bool RenderViewImpl::acceptsLoadDrops() {
1960 return renderer_preferences_.can_accept_load_drops;
1963 void RenderViewImpl::focusNext() {
1964 Send(new ViewHostMsg_TakeFocus(routing_id_, false));
1967 void RenderViewImpl::focusPrevious() {
1968 Send(new ViewHostMsg_TakeFocus(routing_id_, true));
1971 void RenderViewImpl::focusedNodeChanged(const WebNode& fromNode,
1972 const WebNode& toNode) {
1973 has_scrolled_focused_editable_node_into_rect_ = false;
1975 gfx::Rect node_bounds;
1976 if (!toNode.isNull() && toNode.isElementNode()) {
1977 WebNode web_node = const_cast<WebNode&>(toNode);
1978 node_bounds = gfx::Rect(web_node.to<WebElement>().boundsInViewportSpace());
1980 Send(new ViewHostMsg_FocusedNodeChanged(routing_id_, IsEditableNode(toNode),
1981 node_bounds));
1983 // TODO(estade): remove.
1984 FOR_EACH_OBSERVER(RenderViewObserver, observers_, FocusedNodeChanged(toNode));
1986 RenderFrameImpl* previous_frame = nullptr;
1987 if (!fromNode.isNull())
1988 previous_frame = RenderFrameImpl::FromWebFrame(fromNode.document().frame());
1989 RenderFrameImpl* new_frame = nullptr;
1990 if (!toNode.isNull())
1991 new_frame = RenderFrameImpl::FromWebFrame(toNode.document().frame());
1993 if (previous_frame && previous_frame != new_frame)
1994 previous_frame->FocusedNodeChanged(WebNode());
1995 if (new_frame)
1996 new_frame->FocusedNodeChanged(toNode);
1998 // TODO(dmazzoni): remove once there's a separate a11y tree per frame.
1999 if (main_render_frame_)
2000 main_render_frame_->FocusedNodeChangedForAccessibility(toNode);
2003 void RenderViewImpl::didUpdateLayout() {
2004 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidUpdateLayout());
2006 // We don't always want to set up a timer, only if we've been put in that
2007 // mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
2008 // message.
2009 if (!send_preferred_size_changes_ || !webview())
2010 return;
2012 if (check_preferred_size_timer_.IsRunning())
2013 return;
2014 check_preferred_size_timer_.Start(FROM_HERE,
2015 TimeDelta::FromMilliseconds(0), this,
2016 &RenderViewImpl::CheckPreferredSize);
2019 void RenderViewImpl::navigateBackForwardSoon(int offset) {
2020 Send(new ViewHostMsg_GoToEntryAtOffset(routing_id_, offset));
2023 int RenderViewImpl::historyBackListCount() {
2024 return history_list_offset_ < 0 ? 0 : history_list_offset_;
2027 int RenderViewImpl::historyForwardListCount() {
2028 return history_list_length_ - historyBackListCount() - 1;
2031 // blink::WebWidgetClient ----------------------------------------------------
2033 void RenderViewImpl::didFocus() {
2034 // TODO(jcivelli): when https://bugs.webkit.org/show_bug.cgi?id=33389 is fixed
2035 // we won't have to test for user gesture anymore and we can
2036 // move that code back to render_widget.cc
2037 if (WebUserGestureIndicator::isProcessingUserGesture() &&
2038 !RenderThreadImpl::current()->layout_test_mode()) {
2039 Send(new ViewHostMsg_Focus(routing_id_));
2043 void RenderViewImpl::didBlur() {
2044 // TODO(jcivelli): see TODO above in didFocus().
2045 if (WebUserGestureIndicator::isProcessingUserGesture() &&
2046 !RenderThreadImpl::current()->layout_test_mode()) {
2047 Send(new ViewHostMsg_Blur(routing_id_));
2051 // We are supposed to get a single call to Show for a newly created RenderView
2052 // that was created via RenderViewImpl::CreateWebView. So, we wait until this
2053 // point to dispatch the ShowView message.
2055 // This method provides us with the information about how to display the newly
2056 // created RenderView (i.e., as a blocked popup or as a new tab).
2058 void RenderViewImpl::show(WebNavigationPolicy policy) {
2059 if (did_show_) {
2060 // When supports_multiple_windows is disabled, popups are reusing
2061 // the same view. In some scenarios, this makes WebKit to call show() twice.
2062 if (webkit_preferences_.supports_multiple_windows)
2063 NOTREACHED() << "received extraneous Show call";
2064 return;
2066 did_show_ = true;
2068 DCHECK(opener_id_ != MSG_ROUTING_NONE);
2070 // NOTE: initial_rect_ may still have its default values at this point, but
2071 // that's okay. It'll be ignored if disposition is not NEW_POPUP, or the
2072 // browser process will impose a default position otherwise.
2073 Send(new ViewHostMsg_ShowView(opener_id_, routing_id_,
2074 NavigationPolicyToDisposition(policy), initial_rect_,
2075 opened_by_user_gesture_));
2076 SetPendingWindowRect(initial_rect_);
2079 bool RenderViewImpl::requestPointerLock() {
2080 return mouse_lock_dispatcher_->LockMouse(webwidget_mouse_lock_target_.get());
2083 void RenderViewImpl::requestPointerUnlock() {
2084 mouse_lock_dispatcher_->UnlockMouse(webwidget_mouse_lock_target_.get());
2087 bool RenderViewImpl::isPointerLocked() {
2088 return mouse_lock_dispatcher_->IsMouseLockedTo(
2089 webwidget_mouse_lock_target_.get());
2092 void RenderViewImpl::onMouseDown(const WebNode& mouse_down_node) {
2093 FOR_EACH_OBSERVER(
2094 RenderViewObserver, observers_, OnMouseDown(mouse_down_node));
2097 void RenderViewImpl::didHandleGestureEvent(
2098 const WebGestureEvent& event,
2099 bool event_cancelled) {
2100 RenderWidget::didHandleGestureEvent(event, event_cancelled);
2102 if (!event_cancelled) {
2103 FOR_EACH_OBSERVER(
2104 RenderViewObserver, observers_, DidHandleGestureEvent(event));
2107 // TODO(ananta): Piggyback off existing IPCs to communicate this information,
2108 // crbug/420130.
2109 #if defined(OS_WIN)
2110 if (event.type != blink::WebGestureEvent::GestureTap)
2111 return;
2113 // TODO(estade): hit test the event against focused node to make sure
2114 // the tap actually hit the focused node.
2115 blink::WebTextInputType text_input_type =
2116 GetWebView()->textInputInfo().type;
2118 Send(new ViewHostMsg_FocusedNodeTouched(
2119 routing_id(), text_input_type != blink::WebTextInputTypeNone));
2120 #endif
2123 void RenderViewImpl::initializeLayerTreeView() {
2124 RenderWidget::initializeLayerTreeView();
2125 RenderWidgetCompositor* rwc = compositor();
2126 if (!rwc)
2127 return;
2129 bool use_threaded_event_handling = true;
2130 #if defined(OS_MACOSX) && !defined(OS_IOS)
2131 // Disable threaded event handling if content is not handling the elastic
2132 // overscroll effect. This includes the cases where the elastic overscroll
2133 // effect is being handled by Blink (because of command line flags) and older
2134 // operating system versions which do not have an elastic overscroll effect
2135 // (SnowLeopard, which has Aqua scrollbars which need synchronous updates).
2136 use_threaded_event_handling = compositor_deps_->IsElasticOverscrollEnabled();
2137 #endif
2138 if (use_threaded_event_handling) {
2139 RenderThreadImpl* render_thread = RenderThreadImpl::current();
2140 // render_thread may be NULL in tests.
2141 InputHandlerManager* input_handler_manager =
2142 render_thread ? render_thread->input_handler_manager() : NULL;
2143 if (input_handler_manager) {
2144 input_handler_manager->AddInputHandler(
2145 routing_id_, rwc->GetInputHandler(), AsWeakPtr());
2150 // blink::WebFrameClient -----------------------------------------------------
2152 void RenderViewImpl::Repaint(const gfx::Size& size) {
2153 OnRepaint(size);
2156 void RenderViewImpl::SetEditCommandForNextKeyEvent(const std::string& name,
2157 const std::string& value) {
2158 EditCommands edit_commands;
2159 edit_commands.push_back(EditCommand(name, value));
2160 OnSetEditCommandsForNextKeyEvent(edit_commands);
2163 void RenderViewImpl::ClearEditCommands() {
2164 edit_commands_.clear();
2167 SSLStatus RenderViewImpl::GetSSLStatusOfFrame(blink::WebFrame* frame) const {
2168 std::string security_info;
2169 if (frame && frame->dataSource())
2170 security_info = frame->dataSource()->response().securityInfo();
2172 SSLStatus result;
2173 CHECK(DeserializeSecurityInfo(security_info, &result));
2174 return result;
2177 const std::string& RenderViewImpl::GetAcceptLanguages() const {
2178 return renderer_preferences_.accept_languages;
2181 void RenderViewImpl::didChangeIcon(WebLocalFrame* frame,
2182 WebIconURL::Type icon_type) {
2183 if (frame->parent())
2184 return;
2186 WebVector<WebIconURL> icon_urls = frame->iconURLs(icon_type);
2187 std::vector<FaviconURL> urls;
2188 for (size_t i = 0; i < icon_urls.size(); i++) {
2189 std::vector<gfx::Size> sizes;
2190 ConvertToFaviconSizes(icon_urls[i].sizes(), &sizes);
2191 urls.push_back(FaviconURL(
2192 icon_urls[i].iconURL(), ToFaviconType(icon_urls[i].iconType()), sizes));
2194 SendUpdateFaviconURL(urls);
2197 void RenderViewImpl::didUpdateCurrentHistoryItem(WebLocalFrame* frame) {
2198 StartNavStateSyncTimerIfNecessary();
2201 void RenderViewImpl::CheckPreferredSize() {
2202 // We don't always want to send the change messages over IPC, only if we've
2203 // been put in that mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
2204 // message.
2205 if (!send_preferred_size_changes_ || !webview())
2206 return;
2208 gfx::Size size = webview()->contentsPreferredMinimumSize();
2209 if (size == preferred_size_)
2210 return;
2212 preferred_size_ = size;
2213 Send(new ViewHostMsg_DidContentsPreferredSizeChange(routing_id_,
2214 preferred_size_));
2217 void RenderViewImpl::didChangeScrollOffset(WebLocalFrame* frame) {
2218 StartNavStateSyncTimerIfNecessary();
2221 void RenderViewImpl::SendFindReply(int request_id,
2222 int match_count,
2223 int ordinal,
2224 const WebRect& selection_rect,
2225 bool final_status_update) {
2226 Send(new ViewHostMsg_Find_Reply(routing_id_,
2227 request_id,
2228 match_count,
2229 selection_rect,
2230 ordinal,
2231 final_status_update));
2234 blink::WebString RenderViewImpl::acceptLanguages() {
2235 return WebString::fromUTF8(renderer_preferences_.accept_languages);
2238 // blink::WebPageSerializerClient implementation ------------------------------
2240 void RenderViewImpl::didSerializeDataForFrame(
2241 const WebURL& frame_url,
2242 const WebCString& data,
2243 WebPageSerializerClient::PageSerializationStatus status) {
2244 Send(new ViewHostMsg_SendSerializedHtmlData(
2245 routing_id(),
2246 frame_url,
2247 data.data(),
2248 static_cast<int32>(status)));
2251 // RenderView implementation ---------------------------------------------------
2253 bool RenderViewImpl::Send(IPC::Message* message) {
2254 return RenderWidget::Send(message);
2257 RenderFrameImpl* RenderViewImpl::GetMainRenderFrame() {
2258 return main_render_frame_;
2261 int RenderViewImpl::GetRoutingID() const {
2262 return routing_id_;
2265 gfx::Size RenderViewImpl::GetSize() const {
2266 return size();
2269 WebPreferences& RenderViewImpl::GetWebkitPreferences() {
2270 return webkit_preferences_;
2273 void RenderViewImpl::SetWebkitPreferences(const WebPreferences& preferences) {
2274 OnUpdateWebPreferences(preferences);
2277 blink::WebView* RenderViewImpl::GetWebView() {
2278 return webview();
2281 bool RenderViewImpl::IsEditableNode(const WebNode& node) const {
2282 if (node.isNull())
2283 return false;
2285 if (node.isContentEditable())
2286 return true;
2288 if (node.isElementNode()) {
2289 const WebElement& element = node.toConst<WebElement>();
2290 if (element.isTextFormControlElement()) {
2291 if (!(element.hasAttribute("readonly") ||
2292 element.hasAttribute("disabled")))
2293 return true;
2296 return base::LowerCaseEqualsASCII(
2297 base::StringPiece16(element.getAttribute("role")), "textbox");
2300 return false;
2303 bool RenderViewImpl::ShouldDisplayScrollbars(int width, int height) const {
2304 return (!send_preferred_size_changes_ ||
2305 (disable_scrollbars_size_limit_.width() <= width ||
2306 disable_scrollbars_size_limit_.height() <= height));
2309 int RenderViewImpl::GetEnabledBindings() const {
2310 return enabled_bindings_;
2313 bool RenderViewImpl::GetContentStateImmediately() const {
2314 return send_content_state_immediately_;
2317 blink::WebPageVisibilityState RenderViewImpl::GetVisibilityState() const {
2318 return visibilityState();
2321 void RenderViewImpl::DidStartLoading() {
2322 main_render_frame_->didStartLoading(true);
2325 void RenderViewImpl::DidStopLoading() {
2326 main_render_frame_->didStopLoading();
2329 blink::WebElement RenderViewImpl::GetFocusedElement() const {
2330 if (!webview())
2331 return WebElement();
2332 WebFrame* focused_frame = webview()->focusedFrame();
2333 if (focused_frame) {
2334 WebDocument doc = focused_frame->document();
2335 if (!doc.isNull())
2336 return doc.focusedElement();
2339 return WebElement();
2342 blink::WebPlugin* RenderViewImpl::GetWebPluginForFind() {
2343 if (!webview())
2344 return NULL;
2346 WebFrame* main_frame = webview()->mainFrame();
2347 if (main_frame->isWebLocalFrame() &&
2348 main_frame->document().isPluginDocument())
2349 return webview()->mainFrame()->document().to<WebPluginDocument>().plugin();
2351 #if defined(ENABLE_PLUGINS)
2352 if (plugin_find_handler_)
2353 return plugin_find_handler_->container()->plugin();
2354 #endif
2356 return NULL;
2359 void RenderViewImpl::OnFind(int request_id,
2360 const base::string16& search_text,
2361 const WebFindOptions& options) {
2362 WebFrame* main_frame = webview()->mainFrame();
2363 blink::WebPlugin* plugin = GetWebPluginForFind();
2364 // Check if the plugin still exists in the document.
2365 if (plugin) {
2366 if (options.findNext) {
2367 // Just navigate back/forward.
2368 plugin->selectFindResult(options.forward);
2369 } else {
2370 if (!plugin->startFind(
2371 search_text, options.matchCase, request_id)) {
2372 // Send "no results".
2373 SendFindReply(request_id, 0, 0, gfx::Rect(), true);
2376 return;
2379 WebFrame* frame_after_main = main_frame->traverseNext(true);
2380 WebFrame* focused_frame = webview()->focusedFrame();
2381 WebFrame* search_frame = focused_frame; // start searching focused frame.
2383 bool multi_frame = (frame_after_main != main_frame);
2385 // If we have multiple frames, we don't want to wrap the search within the
2386 // frame, so we check here if we only have main_frame in the chain.
2387 bool wrap_within_frame = !multi_frame;
2389 WebRect selection_rect;
2390 bool result = false;
2392 // If something is selected when we start searching it means we cannot just
2393 // increment the current match ordinal; we need to re-generate it.
2394 WebRange current_selection = focused_frame->selectionRange();
2396 do {
2397 result = search_frame->find(
2398 request_id, search_text, options, wrap_within_frame, &selection_rect);
2400 if (!result) {
2401 // don't leave text selected as you move to the next frame.
2402 search_frame->executeCommand(WebString::fromUTF8("Unselect"),
2403 GetFocusedElement());
2405 // Find the next frame, but skip the invisible ones.
2406 do {
2407 // What is the next frame to search? (we might be going backwards). Note
2408 // that we specify wrap=true so that search_frame never becomes NULL.
2409 search_frame = options.forward ?
2410 search_frame->traverseNext(true) :
2411 search_frame->traversePrevious(true);
2412 } while (!search_frame->hasVisibleContent() &&
2413 search_frame != focused_frame);
2415 // Make sure selection doesn't affect the search operation in new frame.
2416 search_frame->executeCommand(WebString::fromUTF8("Unselect"),
2417 GetFocusedElement());
2419 // If we have multiple frames and we have wrapped back around to the
2420 // focused frame, we need to search it once more allowing wrap within
2421 // the frame, otherwise it will report 'no match' if the focused frame has
2422 // reported matches, but no frames after the focused_frame contain a
2423 // match for the search word(s).
2424 if (multi_frame && search_frame == focused_frame) {
2425 result = search_frame->find(
2426 request_id, search_text, options, true, // Force wrapping.
2427 &selection_rect);
2431 webview()->setFocusedFrame(search_frame);
2432 } while (!result && search_frame != focused_frame);
2434 if (options.findNext && current_selection.isNull()) {
2435 // Force the main_frame to report the actual count.
2436 main_frame->increaseMatchCount(0, request_id);
2437 } else {
2438 // If nothing is found, set result to "0 of 0", otherwise, set it to
2439 // "-1 of 1" to indicate that we found at least one item, but we don't know
2440 // yet what is active.
2441 int ordinal = result ? -1 : 0; // -1 here means, we might know more later.
2442 int match_count = result ? 1 : 0; // 1 here means possibly more coming.
2444 // If we find no matches then this will be our last status update.
2445 // Otherwise the scoping effort will send more results.
2446 bool final_status_update = !result;
2448 SendFindReply(request_id, match_count, ordinal, selection_rect,
2449 final_status_update);
2451 // Scoping effort begins, starting with the mainframe.
2452 search_frame = main_frame;
2454 main_frame->resetMatchCount();
2456 do {
2457 // Cancel all old scoping requests before starting a new one.
2458 search_frame->cancelPendingScopingEffort();
2460 // We don't start another scoping effort unless at least one match has
2461 // been found.
2462 if (result) {
2463 // Start new scoping request. If the scoping function determines that it
2464 // needs to scope, it will defer until later.
2465 search_frame->scopeStringMatches(request_id,
2466 search_text,
2467 options,
2468 true); // reset the tickmarks
2471 // Iterate to the next frame. The frame will not necessarily scope, for
2472 // example if it is not visible.
2473 search_frame = search_frame->traverseNext(true);
2474 } while (search_frame != main_frame);
2478 void RenderViewImpl::OnStopFinding(StopFindAction action) {
2479 WebView* view = webview();
2480 if (!view)
2481 return;
2483 blink::WebPlugin* plugin = GetWebPluginForFind();
2484 if (plugin) {
2485 plugin->stopFind();
2486 return;
2489 bool clear_selection = action == STOP_FIND_ACTION_CLEAR_SELECTION;
2490 if (clear_selection) {
2491 view->focusedFrame()->executeCommand(WebString::fromUTF8("Unselect"),
2492 GetFocusedElement());
2495 WebFrame* frame = view->mainFrame();
2496 while (frame) {
2497 frame->stopFinding(clear_selection);
2498 frame = frame->traverseNext(false);
2501 if (action == STOP_FIND_ACTION_ACTIVATE_SELECTION) {
2502 WebFrame* focused_frame = view->focusedFrame();
2503 if (focused_frame) {
2504 WebDocument doc = focused_frame->document();
2505 if (!doc.isNull()) {
2506 WebElement element = doc.focusedElement();
2507 if (!element.isNull())
2508 element.simulateClick();
2514 #if defined(OS_ANDROID)
2515 void RenderViewImpl::OnActivateNearestFindResult(int request_id,
2516 float x, float y) {
2517 if (!webview())
2518 return;
2520 WebFrame* main_frame = webview()->mainFrame();
2521 WebRect selection_rect;
2522 int ordinal = main_frame->selectNearestFindMatch(WebFloatPoint(x, y),
2523 &selection_rect);
2524 if (ordinal == -1) {
2525 // Something went wrong, so send a no-op reply (force the main_frame to
2526 // report the current match count) in case the host is waiting for a
2527 // response due to rate-limiting).
2528 main_frame->increaseMatchCount(0, request_id);
2529 return;
2532 SendFindReply(request_id,
2533 -1 /* number_of_matches */,
2534 ordinal,
2535 selection_rect,
2536 true /* final_update */);
2539 void RenderViewImpl::OnFindMatchRects(int current_version) {
2540 if (!webview())
2541 return;
2543 WebFrame* main_frame = webview()->mainFrame();
2544 std::vector<gfx::RectF> match_rects;
2546 int rects_version = main_frame->findMatchMarkersVersion();
2547 if (current_version != rects_version) {
2548 WebVector<WebFloatRect> web_match_rects;
2549 main_frame->findMatchRects(web_match_rects);
2550 match_rects.reserve(web_match_rects.size());
2551 for (size_t i = 0; i < web_match_rects.size(); ++i)
2552 match_rects.push_back(gfx::RectF(web_match_rects[i]));
2555 gfx::RectF active_rect = main_frame->activeFindMatchRect();
2556 Send(new ViewHostMsg_FindMatchRects_Reply(routing_id_,
2557 rects_version,
2558 match_rects,
2559 active_rect));
2561 #endif
2563 void RenderViewImpl::OnResetPageScale() {
2564 if (!webview())
2565 return;
2566 webview()->setPageScaleFactor(1);
2569 void RenderViewImpl::OnZoom(PageZoom zoom) {
2570 if (!webview()) // Not sure if this can happen, but no harm in being safe.
2571 return;
2573 webview()->hidePopups();
2575 double old_zoom_level = webview()->zoomLevel();
2576 double zoom_level;
2577 if (zoom == PAGE_ZOOM_RESET) {
2578 zoom_level = 0;
2579 } else if (static_cast<int>(old_zoom_level) == old_zoom_level) {
2580 // Previous zoom level is a whole number, so just increment/decrement.
2581 zoom_level = old_zoom_level + zoom;
2582 } else {
2583 // Either the user hit the zoom factor limit and thus the zoom level is now
2584 // not a whole number, or a plugin changed it to a custom value. We want
2585 // to go to the next whole number so that the user can always get back to
2586 // 100% with the keyboard/menu.
2587 if ((old_zoom_level > 1 && zoom > 0) ||
2588 (old_zoom_level < 1 && zoom < 0)) {
2589 zoom_level = static_cast<int>(old_zoom_level + zoom);
2590 } else {
2591 // We're going towards 100%, so first go to the next whole number.
2592 zoom_level = static_cast<int>(old_zoom_level);
2595 webview()->setZoomLevel(zoom_level);
2596 zoomLevelChanged();
2599 void RenderViewImpl::OnSetZoomLevelForLoadingURL(const GURL& url,
2600 double zoom_level) {
2601 #if !defined(OS_ANDROID)
2602 // On Android, page zoom isn't used, and in case of WebView, text zoom is used
2603 // for legacy WebView text scaling emulation. Thus, the code that resets
2604 // the zoom level from this map will be effectively resetting text zoom level.
2605 host_zoom_levels_[url] = zoom_level;
2606 #endif
2609 void RenderViewImpl::OnSetZoomLevelForView(bool uses_temporary_zoom_level,
2610 double level) {
2611 uses_temporary_zoom_level_ = uses_temporary_zoom_level;
2613 webview()->hidePopups();
2614 webview()->setZoomLevel(level);
2617 void RenderViewImpl::OnSetPageEncoding(const std::string& encoding_name) {
2618 webview()->setPageEncoding(WebString::fromUTF8(encoding_name));
2621 void RenderViewImpl::OnResetPageEncodingToDefault() {
2622 WebString no_encoding;
2623 webview()->setPageEncoding(no_encoding);
2626 void RenderViewImpl::OnAllowBindings(int enabled_bindings_flags) {
2627 if ((enabled_bindings_flags & BINDINGS_POLICY_WEB_UI) &&
2628 !(enabled_bindings_ & BINDINGS_POLICY_WEB_UI)) {
2629 // WebUIExtensionData deletes itself when we're destroyed.
2630 new WebUIExtensionData(this);
2631 // WebUIMojo deletes itself when we're destroyed.
2632 new WebUIMojo(this);
2635 enabled_bindings_ |= enabled_bindings_flags;
2637 // Keep track of the total bindings accumulated in this process.
2638 RenderProcess::current()->AddBindings(enabled_bindings_flags);
2641 void RenderViewImpl::OnDragTargetDragEnter(const DropData& drop_data,
2642 const gfx::Point& client_point,
2643 const gfx::Point& screen_point,
2644 WebDragOperationsMask ops,
2645 int key_modifiers) {
2646 WebDragOperation operation = webview()->dragTargetDragEnter(
2647 DropDataToWebDragData(drop_data),
2648 client_point,
2649 screen_point,
2650 ops,
2651 key_modifiers);
2653 Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
2656 void RenderViewImpl::OnDragTargetDragOver(const gfx::Point& client_point,
2657 const gfx::Point& screen_point,
2658 WebDragOperationsMask ops,
2659 int key_modifiers) {
2660 WebDragOperation operation = webview()->dragTargetDragOver(
2661 client_point,
2662 screen_point,
2663 ops,
2664 key_modifiers);
2666 Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
2669 void RenderViewImpl::OnDragTargetDragLeave() {
2670 webview()->dragTargetDragLeave();
2673 void RenderViewImpl::OnDragTargetDrop(const gfx::Point& client_point,
2674 const gfx::Point& screen_point,
2675 int key_modifiers) {
2676 webview()->dragTargetDrop(client_point, screen_point, key_modifiers);
2679 void RenderViewImpl::OnDragSourceEnded(const gfx::Point& client_point,
2680 const gfx::Point& screen_point,
2681 WebDragOperation op) {
2682 webview()->dragSourceEndedAt(client_point, screen_point, op);
2685 void RenderViewImpl::OnDragSourceSystemDragEnded() {
2686 webview()->dragSourceSystemDragEnded();
2689 void RenderViewImpl::OnUpdateWebPreferences(const WebPreferences& prefs) {
2690 webkit_preferences_ = prefs;
2691 ApplyWebPreferencesInternal(webkit_preferences_, webview(), compositor_deps_);
2694 void RenderViewImpl::OnEnumerateDirectoryResponse(
2695 int id,
2696 const std::vector<base::FilePath>& paths) {
2697 if (!enumeration_completions_[id])
2698 return;
2700 WebVector<WebString> ws_file_names(paths.size());
2701 for (size_t i = 0; i < paths.size(); ++i)
2702 ws_file_names[i] = paths[i].AsUTF16Unsafe();
2704 enumeration_completions_[id]->didChooseFile(ws_file_names);
2705 enumeration_completions_.erase(id);
2708 void RenderViewImpl::OnFileChooserResponse(
2709 const std::vector<content::FileChooserFileInfo>& files) {
2710 // This could happen if we navigated to a different page before the user
2711 // closed the chooser.
2712 if (file_chooser_completions_.empty())
2713 return;
2715 // Convert Chrome's SelectedFileInfo list to WebKit's.
2716 WebVector<WebFileChooserCompletion::SelectedFileInfo> selected_files(
2717 files.size());
2718 for (size_t i = 0; i < files.size(); ++i) {
2719 WebFileChooserCompletion::SelectedFileInfo selected_file;
2720 selected_file.path = files[i].file_path.AsUTF16Unsafe();
2721 selected_file.displayName =
2722 base::FilePath(files[i].display_name).AsUTF16Unsafe();
2723 if (files[i].file_system_url.is_valid()) {
2724 selected_file.fileSystemURL = files[i].file_system_url;
2725 selected_file.length = files[i].length;
2726 selected_file.modificationTime = files[i].modification_time.ToDoubleT();
2727 selected_file.isDirectory = files[i].is_directory;
2729 selected_files[i] = selected_file;
2732 if (file_chooser_completions_.front()->completion)
2733 file_chooser_completions_.front()->completion->didChooseFile(
2734 selected_files);
2735 file_chooser_completions_.pop_front();
2737 // If there are more pending file chooser requests, schedule one now.
2738 if (!file_chooser_completions_.empty()) {
2739 Send(new ViewHostMsg_RunFileChooser(routing_id_,
2740 file_chooser_completions_.front()->params));
2744 void RenderViewImpl::OnEnableAutoResize(const gfx::Size& min_size,
2745 const gfx::Size& max_size) {
2746 DCHECK(disable_scrollbars_size_limit_.IsEmpty());
2747 if (!webview())
2748 return;
2749 auto_resize_mode_ = true;
2750 webview()->enableAutoResizeMode(min_size, max_size);
2753 void RenderViewImpl::OnDisableAutoResize(const gfx::Size& new_size) {
2754 DCHECK(disable_scrollbars_size_limit_.IsEmpty());
2755 if (!webview())
2756 return;
2757 auto_resize_mode_ = false;
2758 webview()->disableAutoResizeMode();
2760 if (!new_size.IsEmpty()) {
2761 Resize(new_size,
2762 physical_backing_size_,
2763 top_controls_shrink_blink_size_,
2764 top_controls_height_,
2765 visible_viewport_size_,
2766 resizer_rect_,
2767 is_fullscreen_granted_,
2768 display_mode_,
2769 NO_RESIZE_ACK);
2773 void RenderViewImpl::OnEnablePreferredSizeChangedMode() {
2774 if (send_preferred_size_changes_)
2775 return;
2776 send_preferred_size_changes_ = true;
2778 // Start off with an initial preferred size notification (in case
2779 // |didUpdateLayout| was already called).
2780 didUpdateLayout();
2783 void RenderViewImpl::OnDisableScrollbarsForSmallWindows(
2784 const gfx::Size& disable_scrollbar_size_limit) {
2785 disable_scrollbars_size_limit_ = disable_scrollbar_size_limit;
2788 void RenderViewImpl::OnSetRendererPrefs(
2789 const RendererPreferences& renderer_prefs) {
2790 double old_zoom_level = renderer_preferences_.default_zoom_level;
2791 std::string old_accept_languages = renderer_preferences_.accept_languages;
2793 renderer_preferences_ = renderer_prefs;
2795 UpdateFontRenderingFromRendererPrefs();
2796 UpdateThemePrefs();
2798 #if defined(USE_DEFAULT_RENDER_THEME)
2799 if (renderer_prefs.use_custom_colors) {
2800 WebColorName name = blink::WebColorWebkitFocusRingColor;
2801 blink::setNamedColors(&name, &renderer_prefs.focus_ring_color, 1);
2802 blink::setCaretBlinkInterval(renderer_prefs.caret_blink_interval);
2804 if (webview()) {
2805 webview()->setSelectionColors(
2806 renderer_prefs.active_selection_bg_color,
2807 renderer_prefs.active_selection_fg_color,
2808 renderer_prefs.inactive_selection_bg_color,
2809 renderer_prefs.inactive_selection_fg_color);
2810 webview()->themeChanged();
2813 #endif // defined(USE_DEFAULT_RENDER_THEME)
2815 // If the zoom level for this page matches the old zoom default, and this
2816 // is not a plugin, update the zoom level to match the new default.
2817 if (webview() && webview()->mainFrame()->isWebLocalFrame() &&
2818 !webview()->mainFrame()->document().isPluginDocument() &&
2819 !ZoomValuesEqual(old_zoom_level,
2820 renderer_preferences_.default_zoom_level) &&
2821 ZoomValuesEqual(webview()->zoomLevel(), old_zoom_level)) {
2822 webview()->setZoomLevel(renderer_preferences_.default_zoom_level);
2823 zoomLevelChanged();
2826 if (webview() &&
2827 old_accept_languages != renderer_preferences_.accept_languages) {
2828 webview()->acceptLanguagesChanged();
2832 void RenderViewImpl::OnMediaPlayerActionAt(const gfx::Point& location,
2833 const WebMediaPlayerAction& action) {
2834 if (webview())
2835 webview()->performMediaPlayerAction(action, location);
2838 void RenderViewImpl::OnOrientationChange() {
2839 if (webview() && webview()->mainFrame()->isWebLocalFrame())
2840 webview()->mainFrame()->toWebLocalFrame()->sendOrientationChangeEvent();
2843 void RenderViewImpl::OnPluginActionAt(const gfx::Point& location,
2844 const WebPluginAction& action) {
2845 if (webview())
2846 webview()->performPluginAction(action, location);
2849 void RenderViewImpl::OnGetAllSavableResourceLinksForCurrentPage(
2850 const GURL& page_url) {
2851 // Prepare list to storage all savable resource links.
2852 std::vector<GURL> resources_list;
2853 std::vector<GURL> referrer_urls_list;
2854 std::vector<blink::WebReferrerPolicy> referrer_policies_list;
2855 std::vector<GURL> frames_list;
2856 SavableResourcesResult result(&resources_list,
2857 &referrer_urls_list,
2858 &referrer_policies_list,
2859 &frames_list);
2861 // webkit/ doesn't know about Referrer.
2862 if (!GetAllSavableResourceLinksForCurrentPage(
2863 webview(),
2864 page_url,
2865 &result,
2866 const_cast<const char**>(GetSavableSchemes()))) {
2867 // If something is wrong when collecting all savable resource links,
2868 // send empty list to embedder(browser) to tell it failed.
2869 referrer_urls_list.clear();
2870 referrer_policies_list.clear();
2871 resources_list.clear();
2872 frames_list.clear();
2875 std::vector<Referrer> referrers_list;
2876 CHECK_EQ(referrer_urls_list.size(), referrer_policies_list.size());
2877 for (unsigned i = 0; i < referrer_urls_list.size(); ++i) {
2878 referrers_list.push_back(
2879 Referrer(referrer_urls_list[i], referrer_policies_list[i]));
2882 // Send result of all savable resource links to embedder.
2883 Send(new ViewHostMsg_SendCurrentPageAllSavableResourceLinks(routing_id(),
2884 resources_list,
2885 referrers_list,
2886 frames_list));
2889 void RenderViewImpl::OnGetSerializedHtmlDataForCurrentPageWithLocalLinks(
2890 const std::vector<GURL>& links,
2891 const std::vector<base::FilePath>& local_paths,
2892 const base::FilePath& local_directory_name) {
2894 // Convert std::vector of GURLs to WebVector<WebURL>
2895 WebVector<WebURL> weburl_links(links);
2897 // Convert std::vector of base::FilePath to WebVector<WebString>
2898 WebVector<WebString> webstring_paths(local_paths.size());
2899 for (size_t i = 0; i < local_paths.size(); i++)
2900 webstring_paths[i] = local_paths[i].AsUTF16Unsafe();
2902 WebPageSerializer::serialize(webview()->mainFrame()->toWebLocalFrame(),
2903 true,
2904 this,
2905 weburl_links,
2906 webstring_paths,
2907 local_directory_name.AsUTF16Unsafe());
2910 void RenderViewImpl::OnSuppressDialogsUntilSwapOut() {
2911 // Don't show any more dialogs until we finish OnSwapOut.
2912 suppress_dialogs_until_swap_out_ = true;
2915 void RenderViewImpl::OnClosePage() {
2916 FOR_EACH_OBSERVER(RenderViewObserver, observers_, ClosePage());
2917 // TODO(creis): We'd rather use webview()->Close() here, but that currently
2918 // sets the WebView's delegate_ to NULL, preventing any JavaScript dialogs
2919 // in the onunload handler from appearing. For now, we're bypassing that and
2920 // calling the FrameLoader's CloseURL method directly. This should be
2921 // revisited to avoid having two ways to close a page. Having a single way
2922 // to close that can run onunload is also useful for fixing
2923 // http://b/issue?id=753080.
2924 webview()->mainFrame()->dispatchUnloadEvent();
2926 Send(new ViewHostMsg_ClosePage_ACK(routing_id_));
2929 void RenderViewImpl::OnClose() {
2930 if (closing_)
2931 RenderThread::Get()->Send(new ViewHostMsg_Close_ACK(routing_id_));
2932 RenderWidget::OnClose();
2935 void RenderViewImpl::OnThemeChanged() {
2936 #if defined(USE_AURA)
2937 // Aura doesn't care if we switch themes.
2938 #elif defined(OS_WIN)
2939 ui::NativeThemeWin::instance()->CloseHandles();
2940 if (webview())
2941 webview()->themeChanged();
2942 #else // defined(OS_WIN)
2943 // TODO(port): we don't support theming on non-Windows platforms yet
2944 NOTIMPLEMENTED();
2945 #endif
2948 void RenderViewImpl::OnMoveOrResizeStarted() {
2949 if (webview())
2950 webview()->hidePopups();
2953 void RenderViewImpl::OnResize(const ViewMsg_Resize_Params& params) {
2954 TRACE_EVENT0("renderer", "RenderViewImpl::OnResize");
2955 if (webview()) {
2956 webview()->hidePopups();
2957 if (send_preferred_size_changes_) {
2958 webview()->mainFrame()->setCanHaveScrollbars(
2959 ShouldDisplayScrollbars(params.new_size.width(),
2960 params.new_size.height()));
2962 if (display_mode_ != params.display_mode) {
2963 display_mode_ = params.display_mode;
2964 webview()->setDisplayMode(display_mode_);
2968 gfx::Size old_visible_viewport_size = visible_viewport_size_;
2970 RenderWidget::OnResize(params);
2972 if (old_visible_viewport_size != visible_viewport_size_)
2973 has_scrolled_focused_editable_node_into_rect_ = false;
2976 void RenderViewImpl::DidInitiatePaint() {
2977 #if defined(ENABLE_PLUGINS)
2978 // Notify all instances that we painted. The same caveats apply as for
2979 // ViewFlushedPaint regarding instances closing themselves, so we take
2980 // similar precautions.
2981 PepperPluginSet plugins = active_pepper_instances_;
2982 for (PepperPluginSet::iterator i = plugins.begin(); i != plugins.end(); ++i) {
2983 if (active_pepper_instances_.find(*i) != active_pepper_instances_.end())
2984 (*i)->ViewInitiatedPaint();
2986 #endif
2989 void RenderViewImpl::DidFlushPaint() {
2990 // If the RenderWidget is closing down then early-exit, otherwise we'll crash.
2991 // See crbug.com/112921.
2992 if (!webview())
2993 return;
2995 WebFrame* main_frame = webview()->mainFrame();
2996 for (WebFrame* frame = main_frame; frame;
2997 frame = frame->traverseNext(false)) {
2998 // TODO(nasko): This is a hack for the case in which the top-level
2999 // frame is being rendered in another process. It will not
3000 // behave correctly for out of process iframes.
3001 if (frame->isWebLocalFrame()) {
3002 main_frame = frame;
3003 break;
3007 // There's nothing to do if there are no local frames in this RenderView's
3008 // frame tree. This can happen if DidFlushPaint is called after the
3009 // RenderView's local main frame is swapped to a remote frame. See
3010 // http://crbug.com/513552.
3011 if (main_frame->isWebRemoteFrame())
3012 return;
3014 // If we have a provisional frame we are between the start and commit stages
3015 // of loading and we don't want to save stats.
3016 if (!main_frame->provisionalDataSource()) {
3017 WebDataSource* ds = main_frame->dataSource();
3018 if (!ds)
3019 return;
3021 DocumentState* document_state = DocumentState::FromDataSource(ds);
3023 // TODO(jar): The following code should all be inside a method, probably in
3024 // NavigatorState.
3025 Time now = Time::Now();
3026 if (document_state->first_paint_time().is_null()) {
3027 document_state->set_first_paint_time(now);
3029 if (document_state->first_paint_after_load_time().is_null() &&
3030 !document_state->finish_load_time().is_null()) {
3031 document_state->set_first_paint_after_load_time(now);
3036 gfx::Vector2d RenderViewImpl::GetScrollOffset() {
3037 WebFrame* main_frame = webview()->mainFrame();
3038 for (WebFrame* frame = main_frame; frame;
3039 frame = frame->traverseNext(false)) {
3040 // TODO(nasko): This is a hack for the case in which the top-level
3041 // frame is being rendered in another process. It will not
3042 // behave correctly for out of process iframes.
3043 if (frame->isWebLocalFrame()) {
3044 main_frame = frame;
3045 break;
3049 WebSize scroll_offset = main_frame->scrollOffset();
3050 return gfx::Vector2d(scroll_offset.width, scroll_offset.height);
3053 void RenderViewImpl::OnClearFocusedElement() {
3054 if (webview())
3055 webview()->clearFocusedElement();
3058 void RenderViewImpl::OnSetBackgroundOpaque(bool opaque) {
3059 if (webview())
3060 webview()->setIsTransparent(!opaque);
3061 if (compositor_)
3062 compositor_->setHasTransparentBackground(!opaque);
3065 void RenderViewImpl::OnSetActive(bool active) {
3066 if (webview())
3067 webview()->setIsActive(active);
3069 #if defined(ENABLE_PLUGINS) && defined(OS_MACOSX)
3070 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3071 for (plugin_it = plugin_delegates_.begin();
3072 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3073 (*plugin_it)->SetWindowFocus(active);
3075 #endif
3078 #if defined(OS_MACOSX)
3079 void RenderViewImpl::OnSetWindowVisibility(bool visible) {
3080 #if defined(ENABLE_PLUGINS)
3081 // Inform plugins that their container has changed visibility.
3082 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3083 for (plugin_it = plugin_delegates_.begin();
3084 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3085 (*plugin_it)->SetContainerVisibility(visible);
3087 #endif
3090 void RenderViewImpl::OnWindowFrameChanged(const gfx::Rect& window_frame,
3091 const gfx::Rect& view_frame) {
3092 #if defined(ENABLE_PLUGINS)
3093 // Inform plugins that their window's frame has changed.
3094 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3095 for (plugin_it = plugin_delegates_.begin();
3096 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3097 (*plugin_it)->WindowFrameChanged(window_frame, view_frame);
3099 #endif
3102 void RenderViewImpl::OnPluginImeCompositionCompleted(const base::string16& text,
3103 int plugin_id) {
3104 // WebPluginDelegateProxy is responsible for figuring out if this event
3105 // applies to it or not, so inform all the delegates.
3106 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3107 for (plugin_it = plugin_delegates_.begin();
3108 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3109 (*plugin_it)->ImeCompositionCompleted(text, plugin_id);
3112 #endif // OS_MACOSX
3114 void RenderViewImpl::Close() {
3115 // We need to grab a pointer to the doomed WebView before we destroy it.
3116 WebView* doomed = webview();
3117 RenderWidget::Close();
3118 g_view_map.Get().erase(doomed);
3119 g_routing_id_view_map.Get().erase(routing_id_);
3120 RenderThread::Get()->Send(new ViewHostMsg_Close_ACK(routing_id_));
3123 void RenderViewImpl::DidHandleKeyEvent() {
3124 ClearEditCommands();
3127 bool RenderViewImpl::WillHandleMouseEvent(const blink::WebMouseEvent& event) {
3128 possible_drag_event_info_.event_source =
3129 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE;
3130 possible_drag_event_info_.event_location =
3131 gfx::Point(event.globalX, event.globalY);
3133 #if defined(ENABLE_PLUGINS)
3134 // This method is called for every mouse event that the render view receives.
3135 // And then the mouse event is forwarded to WebKit, which dispatches it to the
3136 // event target. Potentially a Pepper plugin will receive the event.
3137 // In order to tell whether a plugin gets the last mouse event and which it
3138 // is, we set |pepper_last_mouse_event_target_| to NULL here. If a plugin gets
3139 // the event, it will notify us via DidReceiveMouseEvent() and set itself as
3140 // |pepper_last_mouse_event_target_|.
3141 pepper_last_mouse_event_target_ = NULL;
3142 #endif
3144 // If the mouse is locked, only the current owner of the mouse lock can
3145 // process mouse events.
3146 return mouse_lock_dispatcher_->WillHandleMouseEvent(event);
3149 bool RenderViewImpl::WillHandleGestureEvent(
3150 const blink::WebGestureEvent& event) {
3151 possible_drag_event_info_.event_source =
3152 ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH;
3153 possible_drag_event_info_.event_location =
3154 gfx::Point(event.globalX, event.globalY);
3155 return false;
3158 bool RenderViewImpl::HasTouchEventHandlersAt(const gfx::Point& point) const {
3159 if (!webview())
3160 return false;
3161 return webview()->hasTouchEventHandlersAt(point);
3164 void RenderViewImpl::OnWasHidden() {
3165 RenderWidget::OnWasHidden();
3167 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3168 RenderThreadImpl::current()->video_capture_impl_manager()->
3169 SuspendDevices(true);
3170 if (speech_recognition_dispatcher_)
3171 speech_recognition_dispatcher_->AbortAllRecognitions();
3172 #endif
3174 if (webview())
3175 webview()->setVisibilityState(visibilityState(), false);
3177 #if defined(ENABLE_PLUGINS)
3178 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3179 i != active_pepper_instances_.end(); ++i)
3180 (*i)->PageVisibilityChanged(false);
3182 #if defined(OS_MACOSX)
3183 // Inform NPAPI plugins that their container is no longer visible.
3184 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3185 for (plugin_it = plugin_delegates_.begin();
3186 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3187 (*plugin_it)->SetContainerVisibility(false);
3189 #endif // OS_MACOSX
3190 #endif // ENABLE_PLUGINS
3193 void RenderViewImpl::OnWasShown(bool needs_repainting,
3194 const ui::LatencyInfo& latency_info) {
3195 RenderWidget::OnWasShown(needs_repainting, latency_info);
3197 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
3198 RenderThreadImpl::current()->video_capture_impl_manager()->
3199 SuspendDevices(false);
3200 #endif
3202 if (webview())
3203 webview()->setVisibilityState(visibilityState(), false);
3205 #if defined(ENABLE_PLUGINS)
3206 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3207 i != active_pepper_instances_.end(); ++i)
3208 (*i)->PageVisibilityChanged(true);
3210 #if defined(OS_MACOSX)
3211 // Inform NPAPI plugins that their container is now visible.
3212 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3213 for (plugin_it = plugin_delegates_.begin();
3214 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3215 (*plugin_it)->SetContainerVisibility(true);
3217 #endif // OS_MACOSX
3218 #endif // ENABLE_PLUGINS
3221 GURL RenderViewImpl::GetURLForGraphicsContext3D() {
3222 DCHECK(webview());
3223 if (webview()->mainFrame()->isWebLocalFrame())
3224 return GURL(webview()->mainFrame()->document().url());
3225 else
3226 return GURL("chrome://gpu/RenderViewImpl::CreateGraphicsContext3D");
3229 void RenderViewImpl::OnSetFocus(bool enable) {
3230 RenderWidget::OnSetFocus(enable);
3232 #if defined(ENABLE_PLUGINS)
3233 if (webview() && webview()->isActive()) {
3234 // Notify all NPAPI plugins.
3235 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
3236 for (plugin_it = plugin_delegates_.begin();
3237 plugin_it != plugin_delegates_.end(); ++plugin_it) {
3238 #if defined(OS_MACOSX)
3239 // RenderWidget's call to setFocus can cause the underlying webview's
3240 // activation state to change just like a call to setIsActive.
3241 if (enable)
3242 (*plugin_it)->SetWindowFocus(true);
3243 #endif
3244 (*plugin_it)->SetContentAreaFocus(enable);
3247 // Notify all Pepper plugins.
3248 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
3249 i != active_pepper_instances_.end(); ++i)
3250 (*i)->SetContentAreaFocus(enable);
3251 #endif
3252 // Notify all BrowserPlugins of the RenderView's focus state.
3253 if (BrowserPluginManager::Get())
3254 BrowserPluginManager::Get()->UpdateFocusState();
3257 void RenderViewImpl::OnImeSetComposition(
3258 const base::string16& text,
3259 const std::vector<blink::WebCompositionUnderline>& underlines,
3260 int selection_start,
3261 int selection_end) {
3262 #if defined(ENABLE_PLUGINS)
3263 if (focused_pepper_plugin_) {
3264 focused_pepper_plugin_->render_frame()->OnImeSetComposition(
3265 text, underlines, selection_start, selection_end);
3266 return;
3269 #if defined(OS_WIN)
3270 // When a plugin has focus, we create platform-specific IME data used by
3271 // our IME emulator and send it directly to the focused plugin, i.e. we
3272 // bypass WebKit. (WebPluginDelegate dispatches this IME data only when its
3273 // instance ID is the same one as the specified ID.)
3274 if (focused_plugin_id_ >= 0) {
3275 std::vector<int> clauses;
3276 std::vector<int> target;
3277 for (size_t i = 0; i < underlines.size(); ++i) {
3278 clauses.push_back(underlines[i].startOffset);
3279 clauses.push_back(underlines[i].endOffset);
3280 if (underlines[i].thick) {
3281 target.clear();
3282 target.push_back(underlines[i].startOffset);
3283 target.push_back(underlines[i].endOffset);
3286 std::set<WebPluginDelegateProxy*>::iterator it;
3287 for (it = plugin_delegates_.begin(); it != plugin_delegates_.end(); ++it) {
3288 (*it)->ImeCompositionUpdated(text, clauses, target, selection_end,
3289 focused_plugin_id_);
3291 return;
3293 #endif // OS_WIN
3294 #endif // ENABLE_PLUGINS
3295 RenderWidget::OnImeSetComposition(text,
3296 underlines,
3297 selection_start,
3298 selection_end);
3301 void RenderViewImpl::OnImeConfirmComposition(
3302 const base::string16& text,
3303 const gfx::Range& replacement_range,
3304 bool keep_selection) {
3305 #if defined(ENABLE_PLUGINS)
3306 if (focused_pepper_plugin_) {
3307 focused_pepper_plugin_->render_frame()->OnImeConfirmComposition(
3308 text, replacement_range, keep_selection);
3309 return;
3311 #if defined(OS_WIN)
3312 // Same as OnImeSetComposition(), we send the text from IMEs directly to
3313 // plugins. When we send IME text directly to plugins, we should not send
3314 // it to WebKit to prevent WebKit from controlling IMEs.
3315 // TODO(thakis): Honor |replacement_range| for plugins?
3316 if (focused_plugin_id_ >= 0) {
3317 std::set<WebPluginDelegateProxy*>::iterator it;
3318 for (it = plugin_delegates_.begin();
3319 it != plugin_delegates_.end(); ++it) {
3320 (*it)->ImeCompositionCompleted(text, focused_plugin_id_);
3322 return;
3324 #endif // OS_WIN
3325 #endif // ENABLE_PLUGINS
3326 if (replacement_range.IsValid() && webview()) {
3327 // Select the text in |replacement_range|, it will then be replaced by
3328 // text added by the call to RenderWidget::OnImeConfirmComposition().
3329 if (WebLocalFrame* frame = webview()->focusedFrame()->toWebLocalFrame()) {
3330 WebRange webrange = WebRange::fromDocumentRange(
3331 frame, replacement_range.start(), replacement_range.length());
3332 if (!webrange.isNull())
3333 frame->selectRange(webrange);
3336 RenderWidget::OnImeConfirmComposition(text,
3337 replacement_range,
3338 keep_selection);
3341 void RenderViewImpl::SetDeviceScaleFactor(float device_scale_factor) {
3342 RenderWidget::SetDeviceScaleFactor(device_scale_factor);
3343 if (webview()) {
3344 webview()->setDeviceScaleFactor(device_scale_factor);
3345 webview()->settings()->setPreferCompositingToLCDTextEnabled(
3346 PreferCompositingToLCDText(compositor_deps_, device_scale_factor_));
3348 if (auto_resize_mode_)
3349 AutoResizeCompositor();
3352 bool RenderViewImpl::SetDeviceColorProfile(
3353 const std::vector<char>& profile) {
3354 bool changed = RenderWidget::SetDeviceColorProfile(profile);
3355 if (changed && webview()) {
3356 WebVector<char> colorProfile = profile;
3357 webview()->setDeviceColorProfile(colorProfile);
3359 return changed;
3362 void RenderViewImpl::ResetDeviceColorProfileForTesting() {
3363 RenderWidget::ResetDeviceColorProfileForTesting();
3364 if (webview())
3365 webview()->resetDeviceColorProfile();
3368 ui::TextInputType RenderViewImpl::GetTextInputType() {
3369 #if defined(ENABLE_PLUGINS)
3370 if (focused_pepper_plugin_)
3371 return focused_pepper_plugin_->text_input_type();
3372 #endif
3373 return RenderWidget::GetTextInputType();
3376 void RenderViewImpl::GetSelectionBounds(gfx::Rect* start, gfx::Rect* end) {
3377 #if defined(ENABLE_PLUGINS)
3378 if (focused_pepper_plugin_) {
3379 // TODO(kinaba) http://crbug.com/101101
3380 // Current Pepper IME API does not handle selection bounds. So we simply
3381 // use the caret position as an empty range for now. It will be updated
3382 // after Pepper API equips features related to surrounding text retrieval.
3383 gfx::Rect caret = focused_pepper_plugin_->GetCaretBounds();
3384 *start = caret;
3385 *end = caret;
3386 return;
3388 #endif
3389 RenderWidget::GetSelectionBounds(start, end);
3392 void RenderViewImpl::FocusChangeComplete() {
3393 RenderWidget::FocusChangeComplete();
3394 FOR_EACH_OBSERVER(RenderViewObserver, observers_, FocusChangeComplete());
3397 void RenderViewImpl::GetCompositionCharacterBounds(
3398 std::vector<gfx::Rect>* bounds) {
3399 DCHECK(bounds);
3400 bounds->clear();
3402 #if defined(ENABLE_PLUGINS)
3403 if (focused_pepper_plugin_) {
3404 return;
3406 #endif
3408 if (!webview())
3409 return;
3410 size_t start_offset = 0;
3411 size_t character_count = 0;
3412 if (!webview()->compositionRange(&start_offset, &character_count))
3413 return;
3414 if (character_count == 0)
3415 return;
3417 blink::WebFrame* frame = webview()->focusedFrame();
3418 if (!frame)
3419 return;
3421 bounds->reserve(character_count);
3422 blink::WebRect webrect;
3423 for (size_t i = 0; i < character_count; ++i) {
3424 if (!frame->firstRectForCharacterRange(start_offset + i, 1, webrect)) {
3425 DLOG(ERROR) << "Could not retrieve character rectangle at " << i;
3426 bounds->clear();
3427 return;
3429 bounds->push_back(webrect);
3433 void RenderViewImpl::GetCompositionRange(gfx::Range* range) {
3434 #if defined(ENABLE_PLUGINS)
3435 if (focused_pepper_plugin_) {
3436 return;
3438 #endif
3439 RenderWidget::GetCompositionRange(range);
3442 bool RenderViewImpl::CanComposeInline() {
3443 #if defined(ENABLE_PLUGINS)
3444 if (focused_pepper_plugin_)
3445 return focused_pepper_plugin_->IsPluginAcceptingCompositionEvents();
3446 #endif
3447 return true;
3450 void RenderViewImpl::DidCompletePageScaleAnimation() {
3451 FocusChangeComplete();
3454 void RenderViewImpl::SetScreenMetricsEmulationParameters(
3455 bool enabled,
3456 const blink::WebDeviceEmulationParams& params) {
3457 if (webview() && compositor()) {
3458 if (enabled)
3459 webview()->enableDeviceEmulation(params);
3460 else
3461 webview()->disableDeviceEmulation();
3465 bool RenderViewImpl::ScheduleFileChooser(
3466 const FileChooserParams& params,
3467 WebFileChooserCompletion* completion) {
3468 static const size_t kMaximumPendingFileChooseRequests = 4;
3469 if (file_chooser_completions_.size() > kMaximumPendingFileChooseRequests) {
3470 // This sanity check prevents too many file choose requests from getting
3471 // queued which could DoS the user. Getting these is most likely a
3472 // programming error (there are many ways to DoS the user so it's not
3473 // considered a "real" security check), either in JS requesting many file
3474 // choosers to pop up, or in a plugin.
3476 // TODO(brettw) we might possibly want to require a user gesture to open
3477 // a file picker, which will address this issue in a better way.
3478 return false;
3481 file_chooser_completions_.push_back(linked_ptr<PendingFileChooser>(
3482 new PendingFileChooser(params, completion)));
3483 if (file_chooser_completions_.size() == 1) {
3484 // Actually show the browse dialog when this is the first request.
3485 Send(new ViewHostMsg_RunFileChooser(routing_id_, params));
3487 return true;
3490 blink::WebSpeechRecognizer* RenderViewImpl::speechRecognizer() {
3491 if (!speech_recognition_dispatcher_)
3492 speech_recognition_dispatcher_ = new SpeechRecognitionDispatcher(this);
3493 return speech_recognition_dispatcher_;
3496 void RenderViewImpl::zoomLimitsChanged(double minimum_level,
3497 double maximum_level) {
3498 // Round the double to avoid returning incorrect minimum/maximum zoom
3499 // percentages.
3500 int minimum_percent = round(
3501 ZoomLevelToZoomFactor(minimum_level) * 100);
3502 int maximum_percent = round(
3503 ZoomLevelToZoomFactor(maximum_level) * 100);
3505 Send(new ViewHostMsg_UpdateZoomLimits(
3506 routing_id_, minimum_percent, maximum_percent));
3509 void RenderViewImpl::zoomLevelChanged() {
3510 double zoom_level = webview()->zoomLevel();
3512 // Do not send empty URLs to the browser when we are just setting the default
3513 // zoom level (from RendererPreferences) before the first navigation.
3514 if (!webview()->mainFrame()->document().url().isEmpty()) {
3515 // Tell the browser which url got zoomed so it can update the menu and the
3516 // saved values if necessary
3517 Send(new ViewHostMsg_DidZoomURL(
3518 routing_id_, zoom_level,
3519 GURL(webview()->mainFrame()->document().url())));
3523 void RenderViewImpl::pageScaleFactorChanged() {
3524 if (!webview())
3525 return;
3526 bool page_scale_factor_is_one = webview()->pageScaleFactor() == 1;
3527 if (page_scale_factor_is_one == page_scale_factor_is_one_)
3528 return;
3529 page_scale_factor_is_one_ = page_scale_factor_is_one;
3530 Send(new ViewHostMsg_PageScaleFactorIsOneChanged(routing_id_,
3531 page_scale_factor_is_one_));
3534 double RenderViewImpl::zoomLevelToZoomFactor(double zoom_level) const {
3535 return ZoomLevelToZoomFactor(zoom_level);
3538 double RenderViewImpl::zoomFactorToZoomLevel(double factor) const {
3539 return ZoomFactorToZoomLevel(factor);
3542 blink::WebPageVisibilityState RenderViewImpl::visibilityState() const {
3543 blink::WebPageVisibilityState current_state = is_hidden() ?
3544 blink::WebPageVisibilityStateHidden :
3545 blink::WebPageVisibilityStateVisible;
3546 blink::WebPageVisibilityState override_state = current_state;
3547 // TODO(jam): move this method to WebFrameClient.
3548 if (GetContentClient()->renderer()->
3549 ShouldOverridePageVisibilityState(main_render_frame_,
3550 &override_state))
3551 return override_state;
3552 return current_state;
3555 void RenderViewImpl::draggableRegionsChanged() {
3556 FOR_EACH_OBSERVER(
3557 RenderViewObserver,
3558 observers_,
3559 DraggableRegionsChanged(webview()->mainFrame()));
3562 #if defined(OS_ANDROID)
3563 WebContentDetectionResult RenderViewImpl::detectContentAround(
3564 const WebHitTestResult& touch_hit) {
3565 DCHECK(touch_hit.node().isTextNode());
3567 // Process the position with all the registered content detectors until
3568 // a match is found. Priority is provided by their relative order.
3569 for (ContentDetectorList::const_iterator it = content_detectors_.begin();
3570 it != content_detectors_.end(); ++it) {
3571 ContentDetector::Result content = (*it)->FindTappedContent(touch_hit);
3572 if (content.valid) {
3573 return WebContentDetectionResult(content.content_boundaries,
3574 base::UTF8ToUTF16(content.text), content.intent_url);
3577 return WebContentDetectionResult();
3580 void RenderViewImpl::scheduleContentIntent(const WebURL& intent) {
3581 // Introduce a short delay so that the user can notice the content.
3582 base::MessageLoop::current()->PostDelayedTask(
3583 FROM_HERE,
3584 base::Bind(&RenderViewImpl::LaunchAndroidContentIntent,
3585 AsWeakPtr(),
3586 intent,
3587 expected_content_intent_id_),
3588 base::TimeDelta::FromMilliseconds(kContentIntentDelayMilliseconds));
3591 void RenderViewImpl::cancelScheduledContentIntents() {
3592 ++expected_content_intent_id_;
3595 void RenderViewImpl::LaunchAndroidContentIntent(const GURL& intent,
3596 size_t request_id) {
3597 if (request_id != expected_content_intent_id_)
3598 return;
3600 // Remove the content highlighting if any.
3601 ScheduleComposite();
3603 if (!intent.is_empty())
3604 Send(new ViewHostMsg_StartContentIntent(routing_id_, intent));
3607 bool RenderViewImpl::openDateTimeChooser(
3608 const blink::WebDateTimeChooserParams& params,
3609 blink::WebDateTimeChooserCompletion* completion) {
3610 // JavaScript may try to open a date time chooser while one is already open.
3611 if (date_time_picker_client_)
3612 return false;
3613 date_time_picker_client_.reset(
3614 new RendererDateTimePicker(this, params, completion));
3615 return date_time_picker_client_->Open();
3618 void RenderViewImpl::DismissDateTimeDialog() {
3619 DCHECK(date_time_picker_client_);
3620 date_time_picker_client_.reset(NULL);
3623 #endif // defined(OS_ANDROID)
3625 void RenderViewImpl::OnShowContextMenu(
3626 ui::MenuSourceType source_type, const gfx::Point& location) {
3627 context_menu_source_type_ = source_type;
3628 has_host_context_menu_location_ = true;
3629 host_context_menu_location_ = location;
3630 if (webview())
3631 webview()->showContextMenu();
3632 has_host_context_menu_location_ = false;
3635 void RenderViewImpl::OnEnableViewSourceMode() {
3636 if (!webview())
3637 return;
3638 WebFrame* main_frame = webview()->mainFrame();
3639 if (!main_frame)
3640 return;
3641 main_frame->enableViewSourceMode(true);
3644 #if defined(OS_ANDROID) || defined(USE_AURA)
3645 bool RenderViewImpl::didTapMultipleTargets(
3646 const WebSize& inner_viewport_offset,
3647 const WebRect& touch_rect,
3648 const WebVector<WebRect>& target_rects) {
3649 DCHECK(switches::IsLinkDisambiguationPopupEnabled());
3651 // Never show a disambiguation popup when accessibility is enabled,
3652 // as this interferes with "touch exploration".
3653 AccessibilityMode accessibility_mode =
3654 GetMainRenderFrame()->accessibility_mode();
3655 bool matches_accessibility_mode_complete =
3656 (accessibility_mode & AccessibilityModeComplete) ==
3657 AccessibilityModeComplete;
3658 if (matches_accessibility_mode_complete)
3659 return false;
3661 // The touch_rect, target_rects and zoom_rect are in the outer viewport
3662 // reference frame.
3663 gfx::Rect zoom_rect;
3664 float new_total_scale =
3665 DisambiguationPopupHelper::ComputeZoomAreaAndScaleFactor(
3666 touch_rect, target_rects, GetSize(),
3667 gfx::Rect(webview()->mainFrame()->visibleContentRect()).size(),
3668 device_scale_factor_ * webview()->pageScaleFactor(), &zoom_rect);
3669 if (!new_total_scale || zoom_rect.IsEmpty())
3670 return false;
3672 bool handled = false;
3673 switch (renderer_preferences_.tap_multiple_targets_strategy) {
3674 case TAP_MULTIPLE_TARGETS_STRATEGY_ZOOM:
3675 handled = webview()->zoomToMultipleTargetsRect(zoom_rect);
3676 break;
3677 case TAP_MULTIPLE_TARGETS_STRATEGY_POPUP: {
3678 gfx::Size canvas_size =
3679 gfx::ToCeiledSize(gfx::ScaleSize(zoom_rect.size(), new_total_scale));
3680 cc::SharedBitmapManager* manager =
3681 RenderThreadImpl::current()->shared_bitmap_manager();
3682 scoped_ptr<cc::SharedBitmap> shared_bitmap =
3683 manager->AllocateSharedBitmap(canvas_size);
3684 CHECK(!!shared_bitmap);
3686 SkBitmap bitmap;
3687 SkImageInfo info = SkImageInfo::MakeN32Premul(canvas_size.width(),
3688 canvas_size.height());
3689 bitmap.installPixels(info, shared_bitmap->pixels(), info.minRowBytes());
3690 SkCanvas canvas(bitmap);
3692 // TODO(trchen): Cleanup the device scale factor mess.
3693 // device scale will be applied in WebKit
3694 // --> zoom_rect doesn't include device scale,
3695 // but WebKit will still draw on zoom_rect * device_scale_factor_
3696 canvas.scale(new_total_scale / device_scale_factor_,
3697 new_total_scale / device_scale_factor_);
3698 canvas.translate(-zoom_rect.x() * device_scale_factor_,
3699 -zoom_rect.y() * device_scale_factor_);
3701 DCHECK(webwidget_->isAcceleratedCompositingActive());
3702 // TODO(aelias): The disambiguation popup should be composited so we
3703 // don't have to call this method.
3704 webwidget_->paintCompositedDeprecated(&canvas, zoom_rect);
3707 gfx::Rect zoom_rect_in_screen =
3708 zoom_rect - gfx::Vector2d(inner_viewport_offset.width,
3709 inner_viewport_offset.height);
3711 gfx::Rect physical_window_zoom_rect = gfx::ToEnclosingRect(
3712 ClientRectToPhysicalWindowRect(gfx::RectF(zoom_rect_in_screen)));
3714 Send(new ViewHostMsg_ShowDisambiguationPopup(routing_id_,
3715 physical_window_zoom_rect,
3716 canvas_size,
3717 shared_bitmap->id()));
3718 cc::SharedBitmapId id = shared_bitmap->id();
3719 disambiguation_bitmaps_[id] = shared_bitmap.release();
3720 handled = true;
3721 break;
3723 case TAP_MULTIPLE_TARGETS_STRATEGY_NONE:
3724 // No-op.
3725 break;
3728 return handled;
3730 #endif // defined(OS_ANDROID) || defined(USE_AURA)
3732 unsigned RenderViewImpl::GetLocalSessionHistoryLengthForTesting() const {
3733 return history_list_length_;
3736 void RenderViewImpl::SetFocusAndActivateForTesting(bool enable) {
3737 if (enable) {
3738 if (has_focus())
3739 return;
3740 OnSetActive(true);
3741 OnSetFocus(true);
3742 } else {
3743 if (!has_focus())
3744 return;
3745 OnSetFocus(false);
3746 OnSetActive(false);
3750 void RenderViewImpl::SetDeviceScaleFactorForTesting(float factor) {
3751 ViewMsg_Resize_Params params;
3752 params.screen_info = screen_info_;
3753 params.screen_info.deviceScaleFactor = factor;
3754 params.new_size = size();
3755 params.visible_viewport_size = visible_viewport_size_;
3756 params.physical_backing_size =
3757 gfx::ToCeiledSize(gfx::ScaleSize(size(), factor));
3758 params.top_controls_shrink_blink_size = false;
3759 params.top_controls_height = 0.f;
3760 params.resizer_rect = WebRect();
3761 params.is_fullscreen_granted = is_fullscreen_granted();
3762 params.display_mode = display_mode_;
3763 OnResize(params);
3766 void RenderViewImpl::SetDeviceColorProfileForTesting(
3767 const std::vector<char>& color_profile) {
3768 SetDeviceColorProfile(color_profile);
3771 void RenderViewImpl::ForceResizeForTesting(const gfx::Size& new_size) {
3772 gfx::Rect new_window_rect(rootWindowRect().x,
3773 rootWindowRect().y,
3774 new_size.width(),
3775 new_size.height());
3776 SetWindowRectSynchronously(new_window_rect);
3779 void RenderViewImpl::UseSynchronousResizeModeForTesting(bool enable) {
3780 resizing_mode_selector_->set_is_synchronous_mode(enable);
3783 void RenderViewImpl::EnableAutoResizeForTesting(const gfx::Size& min_size,
3784 const gfx::Size& max_size) {
3785 OnEnableAutoResize(min_size, max_size);
3788 void RenderViewImpl::DisableAutoResizeForTesting(const gfx::Size& new_size) {
3789 OnDisableAutoResize(new_size);
3792 void RenderViewImpl::OnReleaseDisambiguationPopupBitmap(
3793 const cc::SharedBitmapId& id) {
3794 BitmapMap::iterator it = disambiguation_bitmaps_.find(id);
3795 DCHECK(it != disambiguation_bitmaps_.end());
3796 delete it->second;
3797 disambiguation_bitmaps_.erase(it);
3800 void RenderViewImpl::DidCommitCompositorFrame() {
3801 RenderWidget::DidCommitCompositorFrame();
3802 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidCommitCompositorFrame());
3805 void RenderViewImpl::SendUpdateFaviconURL(const std::vector<FaviconURL>& urls) {
3806 if (!urls.empty())
3807 Send(new ViewHostMsg_UpdateFaviconURL(routing_id_, urls));
3810 void RenderViewImpl::DidStopLoadingIcons() {
3811 int icon_types = WebIconURL::TypeFavicon | WebIconURL::TypeTouchPrecomposed |
3812 WebIconURL::TypeTouch;
3814 // Favicons matter only for the top-level frame. If it is a WebRemoteFrame,
3815 // just return early.
3816 if (webview()->mainFrame()->isWebRemoteFrame())
3817 return;
3819 WebVector<WebIconURL> icon_urls =
3820 webview()->mainFrame()->iconURLs(icon_types);
3822 std::vector<FaviconURL> urls;
3823 for (size_t i = 0; i < icon_urls.size(); i++) {
3824 WebURL url = icon_urls[i].iconURL();
3825 std::vector<gfx::Size> sizes;
3826 ConvertToFaviconSizes(icon_urls[i].sizes(), &sizes);
3827 if (!url.isEmpty())
3828 urls.push_back(
3829 FaviconURL(url, ToFaviconType(icon_urls[i].iconType()), sizes));
3831 SendUpdateFaviconURL(urls);
3834 } // namespace content