Move IPC for DidStartProvisionalLoadForFrame
[chromium-blink-merge.git] / content / renderer / render_view_impl.cc
blobd123997414774e6967c5f6868bdb700303bb3794
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/renderer/render_view_impl.h"
7 #include <algorithm>
8 #include <cmath>
10 #include "base/auto_reset.h"
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/command_line.h"
14 #include "base/compiler_specific.h"
15 #include "base/debug/alias.h"
16 #include "base/debug/trace_event.h"
17 #include "base/files/file_path.h"
18 #include "base/i18n/char_iterator.h"
19 #include "base/json/json_writer.h"
20 #include "base/lazy_instance.h"
21 #include "base/memory/scoped_ptr.h"
22 #include "base/message_loop/message_loop_proxy.h"
23 #include "base/metrics/histogram.h"
24 #include "base/path_service.h"
25 #include "base/process/kill.h"
26 #include "base/process/process.h"
27 #include "base/strings/string_number_conversions.h"
28 #include "base/strings/string_piece.h"
29 #include "base/strings/string_split.h"
30 #include "base/strings/string_util.h"
31 #include "base/strings/sys_string_conversions.h"
32 #include "base/strings/utf_string_conversions.h"
33 #include "base/time/time.h"
34 #include "cc/base/switches.h"
35 #include "content/child/appcache/appcache_dispatcher.h"
36 #include "content/child/appcache/web_application_cache_host_impl.h"
37 #include "content/child/child_thread.h"
38 #include "content/child/npapi/webplugin_delegate_impl.h"
39 #include "content/child/request_extra_data.h"
40 #include "content/child/webmessageportchannel_impl.h"
41 #include "content/common/clipboard_messages.h"
42 #include "content/common/database_messages.h"
43 #include "content/common/dom_storage/dom_storage_types.h"
44 #include "content/common/drag_messages.h"
45 #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h"
46 #include "content/common/input_messages.h"
47 #include "content/common/java_bridge_messages.h"
48 #include "content/common/pepper_messages.h"
49 #include "content/common/socket_stream_handle_data.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/context_menu_params.h"
57 #include "content/public/common/drop_data.h"
58 #include "content/public/common/favicon_url.h"
59 #include "content/public/common/file_chooser_params.h"
60 #include "content/public/common/page_zoom.h"
61 #include "content/public/common/ssl_status.h"
62 #include "content/public/common/three_d_api_types.h"
63 #include "content/public/common/url_constants.h"
64 #include "content/public/common/url_utils.h"
65 #include "content/public/renderer/content_renderer_client.h"
66 #include "content/public/renderer/context_menu_client.h"
67 #include "content/public/renderer/document_state.h"
68 #include "content/public/renderer/history_item_serialization.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/public/renderer/web_preferences.h"
73 #include "content/renderer/accessibility/renderer_accessibility.h"
74 #include "content/renderer/accessibility/renderer_accessibility_complete.h"
75 #include "content/renderer/accessibility/renderer_accessibility_focus_only.h"
76 #include "content/renderer/browser_plugin/browser_plugin.h"
77 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
78 #include "content/renderer/browser_plugin/browser_plugin_manager_impl.h"
79 #include "content/renderer/context_menu_params_builder.h"
80 #include "content/renderer/devtools/devtools_agent.h"
81 #include "content/renderer/disambiguation_popup_helper.h"
82 #include "content/renderer/dom_automation_controller.h"
83 #include "content/renderer/dom_storage/webstoragenamespace_impl.h"
84 #include "content/renderer/drop_data_builder.h"
85 #include "content/renderer/external_popup_menu.h"
86 #include "content/renderer/fetchers/alt_error_page_resource_fetcher.h"
87 #include "content/renderer/geolocation_dispatcher.h"
88 #include "content/renderer/gpu/input_handler_manager.h"
89 #include "content/renderer/gpu/render_widget_compositor.h"
90 #include "content/renderer/idle_user_detector.h"
91 #include "content/renderer/image_loading_helper.h"
92 #include "content/renderer/ime_event_guard.h"
93 #include "content/renderer/input_tag_speech_dispatcher.h"
94 #include "content/renderer/internal_document_state_data.h"
95 #include "content/renderer/java/java_bridge_dispatcher.h"
96 #include "content/renderer/load_progress_tracker.h"
97 #include "content/renderer/media/audio_device_factory.h"
98 #include "content/renderer/media/audio_renderer_mixer_manager.h"
99 #include "content/renderer/media/media_stream_dependency_factory.h"
100 #include "content/renderer/media/media_stream_dispatcher.h"
101 #include "content/renderer/media/media_stream_impl.h"
102 #include "content/renderer/media/midi_dispatcher.h"
103 #include "content/renderer/media/render_media_log.h"
104 #include "content/renderer/media/video_capture_impl_manager.h"
105 #include "content/renderer/media/webmediaplayer_impl.h"
106 #include "content/renderer/media/webmediaplayer_ms.h"
107 #include "content/renderer/media/webmediaplayer_params.h"
108 #include "content/renderer/mhtml_generator.h"
109 #include "content/renderer/notification_provider.h"
110 #include "content/renderer/render_frame_impl.h"
111 #include "content/renderer/render_process.h"
112 #include "content/renderer/render_thread_impl.h"
113 #include "content/renderer/render_view_impl_params.h"
114 #include "content/renderer/render_view_mouse_lock_dispatcher.h"
115 #include "content/renderer/render_widget_fullscreen_pepper.h"
116 #include "content/renderer/renderer_date_time_picker.h"
117 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
118 #include "content/renderer/renderer_webcolorchooser_impl.h"
119 #include "content/renderer/savable_resources.h"
120 #include "content/renderer/speech_recognition_dispatcher.h"
121 #include "content/renderer/stats_collection_controller.h"
122 #include "content/renderer/stats_collection_observer.h"
123 #include "content/renderer/text_input_client_observer.h"
124 #include "content/renderer/v8_value_converter_impl.h"
125 #include "content/renderer/web_ui_extension.h"
126 #include "content/renderer/web_ui_extension_data.h"
127 #include "content/renderer/websharedworker_proxy.h"
128 #include "media/audio/audio_output_device.h"
129 #include "media/base/audio_renderer_mixer_input.h"
130 #include "media/base/filter_collection.h"
131 #include "media/base/media_switches.h"
132 #include "media/filters/audio_renderer_impl.h"
133 #include "media/filters/gpu_video_accelerator_factories.h"
134 #include "net/base/data_url.h"
135 #include "net/base/escape.h"
136 #include "net/base/net_errors.h"
137 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
138 #include "net/http/http_util.h"
139 #include "third_party/WebKit/public/platform/WebCString.h"
140 #include "third_party/WebKit/public/platform/WebDragData.h"
141 #include "third_party/WebKit/public/platform/WebHTTPBody.h"
142 #include "third_party/WebKit/public/platform/WebImage.h"
143 #include "third_party/WebKit/public/platform/WebMessagePortChannel.h"
144 #include "third_party/WebKit/public/platform/WebPoint.h"
145 #include "third_party/WebKit/public/platform/WebRect.h"
146 #include "third_party/WebKit/public/platform/WebSize.h"
147 #include "third_party/WebKit/public/platform/WebSocketStreamHandle.h"
148 #include "third_party/WebKit/public/platform/WebString.h"
149 #include "third_party/WebKit/public/platform/WebURL.h"
150 #include "third_party/WebKit/public/platform/WebURLError.h"
151 #include "third_party/WebKit/public/platform/WebURLRequest.h"
152 #include "third_party/WebKit/public/platform/WebURLResponse.h"
153 #include "third_party/WebKit/public/platform/WebVector.h"
154 #include "third_party/WebKit/public/web/WebAXObject.h"
155 #include "third_party/WebKit/public/web/WebColorName.h"
156 #include "third_party/WebKit/public/web/WebDOMEvent.h"
157 #include "third_party/WebKit/public/web/WebDOMMessageEvent.h"
158 #include "third_party/WebKit/public/web/WebDataSource.h"
159 #include "third_party/WebKit/public/web/WebDateTimeChooserCompletion.h"
160 #include "third_party/WebKit/public/web/WebDateTimeChooserParams.h"
161 #include "third_party/WebKit/public/web/WebDevToolsAgent.h"
162 #include "third_party/WebKit/public/web/WebDocument.h"
163 #include "third_party/WebKit/public/web/WebElement.h"
164 #include "third_party/WebKit/public/web/WebFileChooserParams.h"
165 #include "third_party/WebKit/public/web/WebFindOptions.h"
166 #include "third_party/WebKit/public/web/WebFormControlElement.h"
167 #include "third_party/WebKit/public/web/WebFormElement.h"
168 #include "third_party/WebKit/public/web/WebFrame.h"
169 #include "third_party/WebKit/public/web/WebGlyphCache.h"
170 #include "third_party/WebKit/public/web/WebHelperPlugin.h"
171 #include "third_party/WebKit/public/web/WebHistoryItem.h"
172 #include "third_party/WebKit/public/web/WebInputElement.h"
173 #include "third_party/WebKit/public/web/WebInputEvent.h"
174 #include "third_party/WebKit/public/web/WebMediaPlayerAction.h"
175 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
176 #include "third_party/WebKit/public/web/WebNodeList.h"
177 #include "third_party/WebKit/public/web/WebPageSerializer.h"
178 #include "third_party/WebKit/public/web/WebPlugin.h"
179 #include "third_party/WebKit/public/web/WebPluginAction.h"
180 #include "third_party/WebKit/public/web/WebPluginContainer.h"
181 #include "third_party/WebKit/public/web/WebPluginDocument.h"
182 #include "third_party/WebKit/public/web/WebPluginParams.h"
183 #include "third_party/WebKit/public/web/WebRange.h"
184 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
185 #include "third_party/WebKit/public/web/WebScriptSource.h"
186 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
187 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
188 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
189 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
190 #include "third_party/WebKit/public/web/WebSettings.h"
191 #include "third_party/WebKit/public/web/WebStorageQuotaCallbacks.h"
192 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
193 #include "third_party/WebKit/public/web/WebUserMediaClient.h"
194 #include "third_party/WebKit/public/web/WebView.h"
195 #include "third_party/WebKit/public/web/WebWindowFeatures.h"
196 #include "third_party/WebKit/public/web/default/WebRenderTheme.h"
197 #include "ui/base/ui_base_switches_util.h"
198 #include "ui/events/latency_info.h"
199 #include "ui/gfx/native_widget_types.h"
200 #include "ui/gfx/point.h"
201 #include "ui/gfx/rect.h"
202 #include "ui/gfx/rect_conversions.h"
203 #include "ui/gfx/size_conversions.h"
204 #include "ui/shell_dialogs/selected_file_info.h"
205 #include "v8/include/v8.h"
206 #include "webkit/child/weburlresponse_extradata_impl.h"
208 #if defined(OS_ANDROID)
209 #include <cpu-features.h>
211 #include "content/common/android/device_telephony_info.h"
212 #include "content/common/gpu/client/context_provider_command_buffer.h"
213 #include "content/renderer/android/address_detector.h"
214 #include "content/renderer/android/content_detector.h"
215 #include "content/renderer/android/email_detector.h"
216 #include "content/renderer/android/phone_number_detector.h"
217 #include "content/renderer/android/synchronous_compositor_factory.h"
218 #include "content/renderer/media/android/renderer_media_player_manager.h"
219 #include "content/renderer/media/android/stream_texture_factory_android_impl.h"
220 #include "content/renderer/media/android/webmediaplayer_android.h"
221 #include "content/renderer/media/android/webmediaplayer_proxy_android.h"
222 #include "skia/ext/platform_canvas.h"
223 #include "third_party/WebKit/public/platform/WebFloatPoint.h"
224 #include "third_party/WebKit/public/platform/WebFloatRect.h"
225 #include "third_party/WebKit/public/web/WebHitTestResult.h"
226 #include "ui/gfx/rect_f.h"
228 #if defined(GOOGLE_TV)
229 #include "content/renderer/media/rtc_video_decoder_bridge_tv.h"
230 #include "content/renderer/media/rtc_video_decoder_factory_tv.h"
231 #endif
233 #elif defined(OS_WIN)
234 // TODO(port): these files are currently Windows only because they concern:
235 // * theming
236 #include "ui/native_theme/native_theme_win.h"
237 #elif defined(USE_X11)
238 #include "ui/native_theme/native_theme.h"
239 #elif defined(OS_MACOSX)
240 #include "skia/ext/skia_utils_mac.h"
241 #endif
243 #if defined(ENABLE_PLUGINS)
244 #include "content/renderer/npapi/webplugin_delegate_proxy.h"
245 #include "content/renderer/npapi/webplugin_impl.h"
246 #include "content/renderer/pepper/pepper_browser_connection.h"
247 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
248 #include "content/renderer/pepper/pepper_plugin_registry.h"
249 #include "content/renderer/pepper/pepper_webplugin_impl.h"
250 #include "content/renderer/pepper/plugin_module.h"
251 #endif
253 #if defined(ENABLE_WEBRTC)
254 #include "content/renderer/media/rtc_peer_connection_handler.h"
255 #endif
257 using WebKit::WebAXObject;
258 using WebKit::WebApplicationCacheHost;
259 using WebKit::WebApplicationCacheHostClient;
260 using WebKit::WebCString;
261 using WebKit::WebColor;
262 using WebKit::WebColorName;
263 using WebKit::WebConsoleMessage;
264 using WebKit::WebContextMenuData;
265 using WebKit::WebCookieJar;
266 using WebKit::WebData;
267 using WebKit::WebDataSource;
268 using WebKit::WebDocument;
269 using WebKit::WebDOMEvent;
270 using WebKit::WebDOMMessageEvent;
271 using WebKit::WebDragData;
272 using WebKit::WebDragOperation;
273 using WebKit::WebDragOperationsMask;
274 using WebKit::WebElement;
275 using WebKit::WebExternalPopupMenu;
276 using WebKit::WebExternalPopupMenuClient;
277 using WebKit::WebFileChooserCompletion;
278 using WebKit::WebFindOptions;
279 using WebKit::WebFormControlElement;
280 using WebKit::WebFormElement;
281 using WebKit::WebFrame;
282 using WebKit::WebGestureEvent;
283 using WebKit::WebHistoryItem;
284 using WebKit::WebHTTPBody;
285 using WebKit::WebIconURL;
286 using WebKit::WebImage;
287 using WebKit::WebInputElement;
288 using WebKit::WebInputEvent;
289 using WebKit::WebMediaPlayer;
290 using WebKit::WebMediaPlayerAction;
291 using WebKit::WebMediaPlayerClient;
292 using WebKit::WebMouseEvent;
293 using WebKit::WebNavigationPolicy;
294 using WebKit::WebNavigationType;
295 using WebKit::WebNode;
296 using WebKit::WebPageSerializer;
297 using WebKit::WebPageSerializerClient;
298 using WebKit::WebPeerConnection00Handler;
299 using WebKit::WebPeerConnection00HandlerClient;
300 using WebKit::WebPeerConnectionHandler;
301 using WebKit::WebPeerConnectionHandlerClient;
302 using WebKit::WebPluginAction;
303 using WebKit::WebPluginContainer;
304 using WebKit::WebPluginDocument;
305 using WebKit::WebPluginParams;
306 using WebKit::WebPoint;
307 using WebKit::WebPopupMenuInfo;
308 using WebKit::WebRange;
309 using WebKit::WebRect;
310 using WebKit::WebReferrerPolicy;
311 using WebKit::WebRuntimeFeatures;
312 using WebKit::WebScriptSource;
313 using WebKit::WebSearchableFormData;
314 using WebKit::WebSecurityOrigin;
315 using WebKit::WebSecurityPolicy;
316 using WebKit::WebSerializedScriptValue;
317 using WebKit::WebSettings;
318 using WebKit::WebSharedWorker;
319 using WebKit::WebSize;
320 using WebKit::WebSocketStreamHandle;
321 using WebKit::WebStorageNamespace;
322 using WebKit::WebStorageQuotaCallbacks;
323 using WebKit::WebStorageQuotaError;
324 using WebKit::WebStorageQuotaType;
325 using WebKit::WebString;
326 using WebKit::WebTextAffinity;
327 using WebKit::WebTextDirection;
328 using WebKit::WebTouchEvent;
329 using WebKit::WebURL;
330 using WebKit::WebURLError;
331 using WebKit::WebURLRequest;
332 using WebKit::WebURLResponse;
333 using WebKit::WebUserGestureIndicator;
334 using WebKit::WebVector;
335 using WebKit::WebView;
336 using WebKit::WebWidget;
337 using WebKit::WebWindowFeatures;
338 using base::Time;
339 using base::TimeDelta;
340 using webkit_glue::WebURLResponseExtraDataImpl;
342 #if defined(OS_ANDROID)
343 using WebKit::WebContentDetectionResult;
344 using WebKit::WebFloatPoint;
345 using WebKit::WebFloatRect;
346 using WebKit::WebHitTestResult;
347 #endif
349 namespace content {
351 //-----------------------------------------------------------------------------
353 typedef std::map<WebKit::WebView*, RenderViewImpl*> ViewMap;
354 static base::LazyInstance<ViewMap> g_view_map = LAZY_INSTANCE_INITIALIZER;
355 typedef std::map<int32, RenderViewImpl*> RoutingIDViewMap;
356 static base::LazyInstance<RoutingIDViewMap> g_routing_id_view_map =
357 LAZY_INSTANCE_INITIALIZER;
359 // Time, in seconds, we delay before sending content state changes (such as form
360 // state and scroll position) to the browser. We delay sending changes to avoid
361 // spamming the browser.
362 // To avoid having tab/session restore require sending a message to get the
363 // current content state during tab closing we use a shorter timeout for the
364 // foreground renderer. This means there is a small window of time from which
365 // content state is modified and not sent to session restore, but this is
366 // better than having to wake up all renderers during shutdown.
367 const int kDelaySecondsForContentStateSyncHidden = 5;
368 const int kDelaySecondsForContentStateSync = 1;
370 const size_t kExtraCharsBeforeAndAfterSelection = 100;
372 const float kScalingIncrementForGesture = 0.01f;
374 #if defined(OS_ANDROID)
375 // Delay between tapping in content and launching the associated android intent.
376 // Used to allow users see what has been recognized as content.
377 const size_t kContentIntentDelayMilliseconds = 700;
378 #endif
380 static RenderViewImpl* (*g_create_render_view_impl)(RenderViewImplParams*) =
381 NULL;
383 static void GetRedirectChain(WebDataSource* ds, std::vector<GURL>* result) {
384 // Replace any occurrences of swappedout:// with about:blank.
385 const WebURL& blank_url = GURL(kAboutBlankURL);
386 WebVector<WebURL> urls;
387 ds->redirectChain(urls);
388 result->reserve(urls.size());
389 for (size_t i = 0; i < urls.size(); ++i) {
390 if (urls[i] != GURL(kSwappedOutURL))
391 result->push_back(urls[i]);
392 else
393 result->push_back(blank_url);
397 // If |data_source| is non-null and has an InternalDocumentStateData associated
398 // with it, the AltErrorPageResourceFetcher is reset.
399 static void StopAltErrorPageFetcher(WebDataSource* data_source) {
400 if (data_source) {
401 InternalDocumentStateData* internal_data =
402 InternalDocumentStateData::FromDataSource(data_source);
403 if (internal_data)
404 internal_data->set_alt_error_page_fetcher(NULL);
408 static bool IsReload(const ViewMsg_Navigate_Params& params) {
409 return
410 params.navigation_type == ViewMsg_Navigate_Type::RELOAD ||
411 params.navigation_type == ViewMsg_Navigate_Type::RELOAD_IGNORING_CACHE ||
412 params.navigation_type ==
413 ViewMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL;
416 // static
417 WebReferrerPolicy RenderViewImpl::GetReferrerPolicyFromRequest(
418 WebFrame* frame,
419 const WebURLRequest& request) {
420 return request.extraData() ?
421 static_cast<RequestExtraData*>(request.extraData())->referrer_policy() :
422 frame->document().referrerPolicy();
425 // static
426 Referrer RenderViewImpl::GetReferrerFromRequest(
427 WebFrame* frame,
428 const WebURLRequest& request) {
429 return Referrer(GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
430 GetReferrerPolicyFromRequest(frame, request));
433 // static
434 WebURLResponseExtraDataImpl* RenderViewImpl::GetExtraDataFromResponse(
435 const WebURLResponse& response) {
436 return static_cast<WebURLResponseExtraDataImpl*>(
437 response.extraData());
440 NOINLINE static void CrashIntentionally() {
441 // NOTE(shess): Crash directly rather than using NOTREACHED() so
442 // that the signature is easier to triage in crash reports.
443 volatile int* zero = NULL;
444 *zero = 0;
447 #if defined(ADDRESS_SANITIZER)
448 NOINLINE static void MaybeTriggerAsanError(const GURL& url) {
449 // NOTE(rogerm): We intentionally perform an invalid heap access here in
450 // order to trigger an Address Sanitizer (ASAN) error report.
451 static const char kCrashDomain[] = "crash";
452 static const char kHeapOverflow[] = "/heap-overflow";
453 static const char kHeapUnderflow[] = "/heap-underflow";
454 static const char kUseAfterFree[] = "/use-after-free";
455 static const int kArraySize = 5;
457 if (!url.DomainIs(kCrashDomain, sizeof(kCrashDomain) - 1))
458 return;
460 if (!url.has_path())
461 return;
463 scoped_ptr<int[]> array(new int[kArraySize]);
464 std::string crash_type(url.path());
465 int dummy = 0;
466 if (crash_type == kHeapOverflow) {
467 dummy = array[kArraySize];
468 } else if (crash_type == kHeapUnderflow ) {
469 dummy = array[-1];
470 } else if (crash_type == kUseAfterFree) {
471 int* dangling = array.get();
472 array.reset();
473 dummy = dangling[kArraySize / 2];
476 // Make sure the assignments to the dummy value aren't optimized away.
477 base::debug::Alias(&dummy);
479 #endif // ADDRESS_SANITIZER
481 static void MaybeHandleDebugURL(const GURL& url) {
482 if (!url.SchemeIs(chrome::kChromeUIScheme))
483 return;
484 if (url == GURL(kChromeUICrashURL)) {
485 CrashIntentionally();
486 } else if (url == GURL(kChromeUIKillURL)) {
487 base::KillProcess(base::GetCurrentProcessHandle(), 1, false);
488 } else if (url == GURL(kChromeUIHangURL)) {
489 for (;;) {
490 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
492 } else if (url == GURL(kChromeUIShorthangURL)) {
493 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
496 #if defined(ADDRESS_SANITIZER)
497 MaybeTriggerAsanError(url);
498 #endif // ADDRESS_SANITIZER
501 // Returns false unless this is a top-level navigation.
502 static bool IsTopLevelNavigation(WebFrame* frame) {
503 return frame->parent() == NULL;
506 // Returns false unless this is a top-level navigation that crosses origins.
507 static bool IsNonLocalTopLevelNavigation(const GURL& url,
508 WebFrame* frame,
509 WebNavigationType type,
510 bool is_form_post) {
511 if (!IsTopLevelNavigation(frame))
512 return false;
514 // Navigations initiated within Webkit are not sent out to the external host
515 // in the following cases.
516 // 1. The url scheme is not http/https
517 // 2. The origin of the url and the opener is the same in which case the
518 // opener relationship is maintained.
519 // 3. Reloads/form submits/back forward navigations
520 if (!url.SchemeIs(kHttpScheme) && !url.SchemeIs(kHttpsScheme))
521 return false;
523 if (type != WebKit::WebNavigationTypeReload &&
524 type != WebKit::WebNavigationTypeBackForward && !is_form_post) {
525 // The opener relationship between the new window and the parent allows the
526 // new window to script the parent and vice versa. This is not allowed if
527 // the origins of the two domains are different. This can be treated as a
528 // top level navigation and routed back to the host.
529 WebKit::WebFrame* opener = frame->opener();
530 if (!opener)
531 return true;
533 if (url.GetOrigin() != GURL(opener->document().url()).GetOrigin())
534 return true;
536 return false;
539 static void NotifyTimezoneChange(WebKit::WebFrame* frame) {
540 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
541 v8::Context::Scope context_scope(frame->mainWorldScriptContext());
542 v8::Date::DateTimeConfigurationChangeNotification();
543 WebKit::WebFrame* child = frame->firstChild();
544 for (; child; child = child->nextSibling())
545 NotifyTimezoneChange(child);
548 static WindowOpenDisposition NavigationPolicyToDisposition(
549 WebNavigationPolicy policy) {
550 switch (policy) {
551 case WebKit::WebNavigationPolicyIgnore:
552 return IGNORE_ACTION;
553 case WebKit::WebNavigationPolicyDownload:
554 return SAVE_TO_DISK;
555 case WebKit::WebNavigationPolicyCurrentTab:
556 return CURRENT_TAB;
557 case WebKit::WebNavigationPolicyNewBackgroundTab:
558 return NEW_BACKGROUND_TAB;
559 case WebKit::WebNavigationPolicyNewForegroundTab:
560 return NEW_FOREGROUND_TAB;
561 case WebKit::WebNavigationPolicyNewWindow:
562 return NEW_WINDOW;
563 case WebKit::WebNavigationPolicyNewPopup:
564 return NEW_POPUP;
565 default:
566 NOTREACHED() << "Unexpected WebNavigationPolicy";
567 return IGNORE_ACTION;
571 // Returns true if the device scale is high enough that losing subpixel
572 // antialiasing won't have a noticeable effect on text quality.
573 static bool DeviceScaleEnsuresTextQuality(float device_scale_factor) {
574 #if defined(OS_ANDROID)
575 // On Android, we never have subpixel antialiasing.
576 return true;
577 #else
578 return device_scale_factor > 1.5f;
579 #endif
583 static bool ShouldUseFixedPositionCompositing(float device_scale_factor) {
584 // Compositing for fixed-position elements is dependent on
585 // device_scale_factor if no flag is set. http://crbug.com/172738
586 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
588 if (command_line.HasSwitch(switches::kDisableCompositingForFixedPosition))
589 return false;
591 if (command_line.HasSwitch(switches::kEnableCompositingForFixedPosition))
592 return true;
594 return DeviceScaleEnsuresTextQuality(device_scale_factor);
597 static bool ShouldUseAcceleratedCompositingForOverflowScroll(
598 float device_scale_factor) {
599 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
601 if (command_line.HasSwitch(switches::kDisableAcceleratedOverflowScroll))
602 return false;
604 if (command_line.HasSwitch(switches::kEnableAcceleratedOverflowScroll))
605 return true;
607 return DeviceScaleEnsuresTextQuality(device_scale_factor);
610 static bool ShouldUseAcceleratedCompositingForScrollableFrames(
611 float device_scale_factor) {
612 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
614 if (command_line.HasSwitch(switches::kDisableAcceleratedScrollableFrames))
615 return false;
617 if (command_line.HasSwitch(switches::kEnableAcceleratedScrollableFrames))
618 return true;
620 if (!cc::switches::IsLCDTextEnabled())
621 return true;
623 return DeviceScaleEnsuresTextQuality(device_scale_factor);
626 static bool ShouldUseCompositedScrollingForFrames(
627 float device_scale_factor) {
628 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
630 if (command_line.HasSwitch(switches::kDisableCompositedScrollingForFrames))
631 return false;
633 if (command_line.HasSwitch(switches::kEnableCompositedScrollingForFrames))
634 return true;
636 if (!cc::switches::IsLCDTextEnabled())
637 return true;
639 return DeviceScaleEnsuresTextQuality(device_scale_factor);
642 static bool ShouldUseUniversalAcceleratedCompositingForOverflowScroll() {
643 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
645 if (command_line.HasSwitch(
646 switches::kDisableUniversalAcceleratedOverflowScroll))
647 return false;
649 if (command_line.HasSwitch(
650 switches::kEnableUniversalAcceleratedOverflowScroll))
651 return true;
653 return false;
656 static bool ShouldUseTransitionCompositing(float device_scale_factor) {
657 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
659 if (command_line.HasSwitch(switches::kDisableCompositingForTransition))
660 return false;
662 if (command_line.HasSwitch(switches::kEnableCompositingForTransition))
663 return true;
665 // TODO(ajuma): Re-enable this by default for high-DPI once the problem
666 // of excessive layer promotion caused by overlap has been addressed.
667 // http://crbug.com/178119.
668 return false;
671 static bool ShouldUseAcceleratedFixedRootBackground(float device_scale_factor) {
672 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
674 if (command_line.HasSwitch(switches::kDisableAcceleratedFixedRootBackground))
675 return false;
677 if (command_line.HasSwitch(switches::kEnableAcceleratedFixedRootBackground))
678 return true;
680 return DeviceScaleEnsuresTextQuality(device_scale_factor);
683 static FaviconURL::IconType ToFaviconType(WebKit::WebIconURL::Type type) {
684 switch (type) {
685 case WebKit::WebIconURL::TypeFavicon:
686 return FaviconURL::FAVICON;
687 case WebKit::WebIconURL::TypeTouch:
688 return FaviconURL::TOUCH_ICON;
689 case WebKit::WebIconURL::TypeTouchPrecomposed:
690 return FaviconURL::TOUCH_PRECOMPOSED_ICON;
691 case WebKit::WebIconURL::TypeInvalid:
692 return FaviconURL::INVALID_ICON;
694 return FaviconURL::INVALID_ICON;
697 ///////////////////////////////////////////////////////////////////////////////
699 struct RenderViewImpl::PendingFileChooser {
700 PendingFileChooser(const FileChooserParams& p, WebFileChooserCompletion* c)
701 : params(p),
702 completion(c) {
704 FileChooserParams params;
705 WebFileChooserCompletion* completion; // MAY BE NULL to skip callback.
708 namespace {
710 class WebWidgetLockTarget : public MouseLockDispatcher::LockTarget {
711 public:
712 explicit WebWidgetLockTarget(WebKit::WebWidget* webwidget)
713 : webwidget_(webwidget) {}
715 virtual void OnLockMouseACK(bool succeeded) OVERRIDE {
716 if (succeeded)
717 webwidget_->didAcquirePointerLock();
718 else
719 webwidget_->didNotAcquirePointerLock();
722 virtual void OnMouseLockLost() OVERRIDE {
723 webwidget_->didLosePointerLock();
726 virtual bool HandleMouseLockedInputEvent(
727 const WebKit::WebMouseEvent &event) OVERRIDE {
728 // The WebWidget handles mouse lock in WebKit's handleInputEvent().
729 return false;
732 private:
733 WebKit::WebWidget* webwidget_;
736 int64 ExtractPostId(const WebHistoryItem& item) {
737 if (item.isNull())
738 return -1;
740 if (item.httpBody().isNull())
741 return -1;
743 return item.httpBody().identifier();
746 bool TouchEnabled() {
747 // Based on the definition of chrome::kEnableTouchIcon.
748 #if defined(OS_ANDROID)
749 return true;
750 #else
751 return false;
752 #endif
755 WebDragData DropDataToWebDragData(const DropData& drop_data) {
756 std::vector<WebDragData::Item> item_list;
758 // These fields are currently unused when dragging into WebKit.
759 DCHECK(drop_data.download_metadata.empty());
760 DCHECK(drop_data.file_contents.empty());
761 DCHECK(drop_data.file_description_filename.empty());
763 if (!drop_data.text.is_null()) {
764 WebDragData::Item item;
765 item.storageType = WebDragData::Item::StorageTypeString;
766 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeText);
767 item.stringData = drop_data.text.string();
768 item_list.push_back(item);
771 // TODO(dcheng): Do we need to distinguish between null and empty URLs? Is it
772 // meaningful to write an empty URL to the clipboard?
773 if (!drop_data.url.is_empty()) {
774 WebDragData::Item item;
775 item.storageType = WebDragData::Item::StorageTypeString;
776 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeURIList);
777 item.stringData = WebString::fromUTF8(drop_data.url.spec());
778 item.title = drop_data.url_title;
779 item_list.push_back(item);
782 if (!drop_data.html.is_null()) {
783 WebDragData::Item item;
784 item.storageType = WebDragData::Item::StorageTypeString;
785 item.stringType = WebString::fromUTF8(ui::Clipboard::kMimeTypeHTML);
786 item.stringData = drop_data.html.string();
787 item.baseURL = drop_data.html_base_url;
788 item_list.push_back(item);
791 for (std::vector<DropData::FileInfo>::const_iterator it =
792 drop_data.filenames.begin();
793 it != drop_data.filenames.end();
794 ++it) {
795 WebDragData::Item item;
796 item.storageType = WebDragData::Item::StorageTypeFilename;
797 item.filenameData = it->path;
798 item.displayNameData = it->display_name;
799 item_list.push_back(item);
802 for (std::map<base::string16, base::string16>::const_iterator it =
803 drop_data.custom_data.begin();
804 it != drop_data.custom_data.end();
805 ++it) {
806 WebDragData::Item item;
807 item.storageType = WebDragData::Item::StorageTypeString;
808 item.stringType = it->first;
809 item.stringData = it->second;
810 item_list.push_back(item);
813 WebDragData result;
814 result.initialize();
815 result.setItems(item_list);
816 result.setFilesystemId(drop_data.filesystem_id);
817 return result;
820 } // namespace
822 RenderViewImpl::RenderViewImpl(RenderViewImplParams* params)
823 : RenderWidget(WebKit::WebPopupTypeNone,
824 params->screen_info,
825 params->swapped_out,
826 params->hidden),
827 webkit_preferences_(params->webkit_prefs),
828 send_content_state_immediately_(false),
829 enabled_bindings_(0),
830 send_preferred_size_changes_(false),
831 is_loading_(false),
832 navigation_gesture_(NavigationGestureUnknown),
833 opened_by_user_gesture_(true),
834 opener_suppressed_(false),
835 page_id_(-1),
836 last_page_id_sent_to_browser_(-1),
837 next_page_id_(params->next_page_id),
838 history_list_offset_(-1),
839 history_list_length_(0),
840 target_url_status_(TARGET_NONE),
841 selection_text_offset_(0),
842 selection_range_(gfx::Range::InvalidRange()),
843 #if defined(OS_ANDROID)
844 top_controls_constraints_(cc::BOTH),
845 #endif
846 cached_is_main_frame_pinned_to_left_(false),
847 cached_is_main_frame_pinned_to_right_(false),
848 cached_has_main_frame_horizontal_scrollbar_(false),
849 cached_has_main_frame_vertical_scrollbar_(false),
850 cookie_jar_(this),
851 notification_provider_(NULL),
852 geolocation_dispatcher_(NULL),
853 input_tag_speech_dispatcher_(NULL),
854 speech_recognition_dispatcher_(NULL),
855 media_stream_dispatcher_(NULL),
856 browser_plugin_manager_(NULL),
857 media_stream_client_(NULL),
858 web_user_media_client_(NULL),
859 midi_dispatcher_(NULL),
860 devtools_agent_(NULL),
861 accessibility_mode_(AccessibilityModeOff),
862 renderer_accessibility_(NULL),
863 java_bridge_dispatcher_(NULL),
864 mouse_lock_dispatcher_(NULL),
865 #if defined(OS_ANDROID)
866 body_background_color_(SK_ColorWHITE),
867 expected_content_intent_id_(0),
868 media_player_proxy_(NULL),
869 #endif
870 #if defined(OS_WIN)
871 focused_plugin_id_(-1),
872 #endif
873 #if defined(ENABLE_PLUGINS)
874 focused_pepper_plugin_(NULL),
875 pepper_last_mouse_event_target_(NULL),
876 #endif
877 enumeration_completion_id_(0),
878 load_progress_tracker_(new LoadProgressTracker(this)),
879 session_storage_namespace_id_(params->session_storage_namespace_id),
880 handling_select_range_(false),
881 next_snapshot_id_(0),
882 allow_partial_swap_(params->allow_partial_swap),
883 context_menu_source_type_(ui::MENU_SOURCE_MOUSE) {
886 void RenderViewImpl::Initialize(RenderViewImplParams* params) {
887 routing_id_ = params->routing_id;
888 surface_id_ = params->surface_id;
889 if (params->opener_id != MSG_ROUTING_NONE && params->is_renderer_created)
890 opener_id_ = params->opener_id;
892 // Ensure we start with a valid next_page_id_ from the browser.
893 DCHECK_GE(next_page_id_, 0);
895 #if defined(ENABLE_NOTIFICATIONS)
896 notification_provider_ = new NotificationProvider(this);
897 #else
898 notification_provider_ = NULL;
899 #endif
901 webwidget_ = WebView::create(this);
902 webwidget_mouse_lock_target_.reset(new WebWidgetLockTarget(webwidget_));
904 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
906 if (command_line.HasSwitch(switches::kStatsCollectionController))
907 stats_collection_observer_.reset(new StatsCollectionObserver(this));
909 #if defined(OS_ANDROID)
910 content::DeviceTelephonyInfo device_info;
912 const std::string region_code =
913 command_line.HasSwitch(switches::kNetworkCountryIso)
914 ? command_line.GetSwitchValueASCII(switches::kNetworkCountryIso)
915 : device_info.GetNetworkCountryIso();
916 content_detectors_.push_back(linked_ptr<ContentDetector>(
917 new AddressDetector()));
918 content_detectors_.push_back(linked_ptr<ContentDetector>(
919 new PhoneNumberDetector(region_code)));
920 content_detectors_.push_back(linked_ptr<ContentDetector>(
921 new EmailDetector()));
922 #endif
924 RenderThread::Get()->AddRoute(routing_id_, this);
925 // Take a reference on behalf of the RenderThread. This will be balanced
926 // when we receive ViewMsg_ClosePage.
927 AddRef();
928 if (is_hidden_)
929 RenderThread::Get()->WidgetHidden();
931 // If this is a popup, we must wait for the CreatingNew_ACK message before
932 // completing initialization. Otherwise, we can finish it now.
933 if (opener_id_ == MSG_ROUTING_NONE) {
934 did_show_ = true;
935 CompleteInit();
938 g_view_map.Get().insert(std::make_pair(webview(), this));
939 g_routing_id_view_map.Get().insert(std::make_pair(routing_id_, this));
940 webview()->setDeviceScaleFactor(device_scale_factor_);
941 webview()->settings()->setAcceleratedCompositingForFixedPositionEnabled(
942 ShouldUseFixedPositionCompositing(device_scale_factor_));
943 webview()->settings()->setAcceleratedCompositingForOverflowScrollEnabled(
944 ShouldUseAcceleratedCompositingForOverflowScroll(device_scale_factor_));
945 webview()->settings()->setCompositorDrivenAcceleratedScrollingEnabled(
946 ShouldUseUniversalAcceleratedCompositingForOverflowScroll());
947 webview()->settings()->setAcceleratedCompositingForTransitionEnabled(
948 ShouldUseTransitionCompositing(device_scale_factor_));
949 webview()->settings()->setAcceleratedCompositingForFixedRootBackgroundEnabled(
950 ShouldUseAcceleratedFixedRootBackground(device_scale_factor_));
951 webview()->settings()->setAcceleratedCompositingForScrollableFramesEnabled(
952 ShouldUseAcceleratedCompositingForScrollableFrames(device_scale_factor_));
953 webview()->settings()->setCompositedScrollingForFramesEnabled(
954 ShouldUseCompositedScrollingForFrames(device_scale_factor_));
956 ApplyWebPreferences(webkit_preferences_, webview());
958 main_render_frame_.reset(
959 RenderFrameImpl::Create(this, params->main_frame_routing_id));
960 // The main frame WebFrame object is closed by
961 // RenderViewImpl::frameDetached().
962 webview()->setMainFrame(WebFrame::create(main_render_frame_.get()));
964 if (switches::IsTouchDragDropEnabled())
965 webview()->settings()->setTouchDragDropEnabled(true);
967 if (switches::IsTouchEditingEnabled())
968 webview()->settings()->setTouchEditingEnabled(true);
970 if (!params->frame_name.empty())
971 webview()->mainFrame()->setName(params->frame_name);
973 OnSetRendererPrefs(params->renderer_prefs);
975 #if defined(ENABLE_WEBRTC)
976 if (!media_stream_dispatcher_)
977 media_stream_dispatcher_ = new MediaStreamDispatcher(this);
978 #endif
980 new MHTMLGenerator(this);
981 #if defined(OS_MACOSX)
982 new TextInputClientObserver(this);
983 #endif // defined(OS_MACOSX)
985 #if defined(OS_ANDROID)
986 media_player_manager_.reset(new RendererMediaPlayerManager());
987 #endif
989 // The next group of objects all implement RenderViewObserver, so are deleted
990 // along with the RenderView automatically.
991 devtools_agent_ = new DevToolsAgent(this);
992 if (RenderWidgetCompositor* rwc = compositor()) {
993 webview()->devToolsAgent()->setLayerTreeId(rwc->GetLayerTreeId());
995 mouse_lock_dispatcher_ = new RenderViewMouseLockDispatcher(this);
996 new ImageLoadingHelper(this);
998 // Create renderer_accessibility_ if needed.
999 OnSetAccessibilityMode(params->accessibility_mode);
1001 new IdleUserDetector(this);
1003 if (command_line.HasSwitch(switches::kDomAutomationController))
1004 enabled_bindings_ |= BINDINGS_POLICY_DOM_AUTOMATION;
1005 if (command_line.HasSwitch(switches::kStatsCollectionController))
1006 enabled_bindings_ |= BINDINGS_POLICY_STATS_COLLECTION;
1008 ProcessViewLayoutFlags(command_line);
1010 #if defined(ENABLE_PLUGINS)
1011 new PepperBrowserConnection(this);
1012 #endif
1014 GetContentClient()->renderer()->RenderViewCreated(this);
1016 // If we have an opener_id but we weren't created by a renderer, then
1017 // it's the browser asking us to set our opener to another RenderView.
1018 if (params->opener_id != MSG_ROUTING_NONE && !params->is_renderer_created) {
1019 RenderViewImpl* opener_view = FromRoutingID(params->opener_id);
1020 if (opener_view)
1021 webview()->mainFrame()->setOpener(opener_view->webview()->mainFrame());
1024 // If we are initially swapped out, navigate to kSwappedOutURL.
1025 // This ensures we are in a unique origin that others cannot script.
1026 if (is_swapped_out_)
1027 NavigateToSwappedOutURL(webview()->mainFrame());
1030 RenderViewImpl::~RenderViewImpl() {
1031 history_page_ids_.clear();
1033 base::debug::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_);
1035 // If file chooser is still waiting for answer, dispatch empty answer.
1036 while (!file_chooser_completions_.empty()) {
1037 if (file_chooser_completions_.front()->completion) {
1038 file_chooser_completions_.front()->completion->didChooseFile(
1039 WebVector<WebString>());
1041 file_chooser_completions_.pop_front();
1044 #if defined(OS_ANDROID)
1045 // The date/time picker client is both a scoped_ptr member of this class and
1046 // a RenderViewObserver. Reset it to prevent double deletion.
1047 date_time_picker_client_.reset();
1048 #endif
1050 #ifndef NDEBUG
1051 // Make sure we are no longer referenced by the ViewMap or RoutingIDViewMap.
1052 ViewMap* views = g_view_map.Pointer();
1053 for (ViewMap::iterator it = views->begin(); it != views->end(); ++it)
1054 DCHECK_NE(this, it->second) << "Failed to call Close?";
1055 RoutingIDViewMap* routing_id_views = g_routing_id_view_map.Pointer();
1056 for (RoutingIDViewMap::iterator it = routing_id_views->begin();
1057 it != routing_id_views->end(); ++it)
1058 DCHECK_NE(this, it->second) << "Failed to call Close?";
1059 #endif
1061 FOR_EACH_OBSERVER(RenderViewObserver, observers_, RenderViewGone());
1062 FOR_EACH_OBSERVER(RenderViewObserver, observers_, OnDestruct());
1065 /*static*/
1066 RenderViewImpl* RenderViewImpl::FromWebView(WebView* webview) {
1067 ViewMap* views = g_view_map.Pointer();
1068 ViewMap::iterator it = views->find(webview);
1069 return it == views->end() ? NULL : it->second;
1072 /*static*/
1073 RenderView* RenderView::FromWebView(WebKit::WebView* webview) {
1074 return RenderViewImpl::FromWebView(webview);
1077 /*static*/
1078 RenderViewImpl* RenderViewImpl::FromRoutingID(int32 routing_id) {
1079 RoutingIDViewMap* views = g_routing_id_view_map.Pointer();
1080 RoutingIDViewMap::iterator it = views->find(routing_id);
1081 return it == views->end() ? NULL : it->second;
1084 /*static*/
1085 RenderView* RenderView::FromRoutingID(int routing_id) {
1086 return RenderViewImpl::FromRoutingID(routing_id);
1089 /*static*/
1090 void RenderView::ForEach(RenderViewVisitor* visitor) {
1091 ViewMap* views = g_view_map.Pointer();
1092 for (ViewMap::iterator it = views->begin(); it != views->end(); ++it) {
1093 if (!visitor->Visit(it->second))
1094 return;
1098 /*static*/
1099 RenderViewImpl* RenderViewImpl::Create(
1100 int32 opener_id,
1101 const RendererPreferences& renderer_prefs,
1102 const WebPreferences& webkit_prefs,
1103 int32 routing_id,
1104 int32 main_frame_routing_id,
1105 int32 surface_id,
1106 int64 session_storage_namespace_id,
1107 const string16& frame_name,
1108 bool is_renderer_created,
1109 bool swapped_out,
1110 bool hidden,
1111 int32 next_page_id,
1112 const WebKit::WebScreenInfo& screen_info,
1113 AccessibilityMode accessibility_mode,
1114 bool allow_partial_swap) {
1115 DCHECK(routing_id != MSG_ROUTING_NONE);
1116 RenderViewImplParams params(
1117 opener_id,
1118 renderer_prefs,
1119 webkit_prefs,
1120 routing_id,
1121 main_frame_routing_id,
1122 surface_id,
1123 session_storage_namespace_id,
1124 frame_name,
1125 is_renderer_created,
1126 swapped_out,
1127 hidden,
1128 next_page_id,
1129 screen_info,
1130 accessibility_mode,
1131 allow_partial_swap);
1132 RenderViewImpl* render_view = NULL;
1133 if (g_create_render_view_impl)
1134 render_view = g_create_render_view_impl(&params);
1135 else
1136 render_view = new RenderViewImpl(&params);
1137 render_view->Initialize(&params);
1138 return render_view;
1141 // static
1142 void RenderViewImpl::InstallCreateHook(
1143 RenderViewImpl* (*create_render_view_impl)(RenderViewImplParams*)) {
1144 CHECK(!g_create_render_view_impl);
1145 g_create_render_view_impl = create_render_view_impl;
1148 void RenderViewImpl::AddObserver(RenderViewObserver* observer) {
1149 observers_.AddObserver(observer);
1152 void RenderViewImpl::RemoveObserver(RenderViewObserver* observer) {
1153 observer->RenderViewGone();
1154 observers_.RemoveObserver(observer);
1157 WebKit::WebView* RenderViewImpl::webview() const {
1158 return static_cast<WebKit::WebView*>(webwidget());
1161 #if defined(ENABLE_PLUGINS)
1162 void RenderViewImpl::PepperInstanceCreated(PepperPluginInstanceImpl* instance) {
1163 active_pepper_instances_.insert(instance);
1166 void RenderViewImpl::PepperInstanceDeleted(PepperPluginInstanceImpl* instance) {
1167 active_pepper_instances_.erase(instance);
1169 if (pepper_last_mouse_event_target_ == instance)
1170 pepper_last_mouse_event_target_ = NULL;
1171 if (focused_pepper_plugin_ == instance)
1172 PepperFocusChanged(instance, false);
1175 void RenderViewImpl::PepperDidChangeCursor(
1176 PepperPluginInstanceImpl* instance,
1177 const WebKit::WebCursorInfo& cursor) {
1178 // Update the cursor appearance immediately if the requesting plugin is the
1179 // one which receives the last mouse event. Otherwise, the new cursor won't be
1180 // picked up until the plugin gets the next input event. That is bad if, e.g.,
1181 // the plugin would like to set an invisible cursor when there isn't any user
1182 // input for a while.
1183 if (instance == pepper_last_mouse_event_target_)
1184 didChangeCursor(cursor);
1187 void RenderViewImpl::PepperDidReceiveMouseEvent(
1188 PepperPluginInstanceImpl* instance) {
1189 pepper_last_mouse_event_target_ = instance;
1192 void RenderViewImpl::PepperFocusChanged(PepperPluginInstanceImpl* instance,
1193 bool focused) {
1194 if (focused)
1195 focused_pepper_plugin_ = instance;
1196 else if (focused_pepper_plugin_ == instance)
1197 focused_pepper_plugin_ = NULL;
1199 UpdateTextInputType();
1200 UpdateSelectionBounds();
1203 void RenderViewImpl::PepperTextInputTypeChanged(
1204 PepperPluginInstanceImpl* instance) {
1205 if (instance != focused_pepper_plugin_)
1206 return;
1208 UpdateTextInputType();
1209 if (renderer_accessibility_)
1210 renderer_accessibility_->FocusedNodeChanged(WebNode());
1213 void RenderViewImpl::PepperCaretPositionChanged(
1214 PepperPluginInstanceImpl* instance) {
1215 if (instance != focused_pepper_plugin_)
1216 return;
1217 UpdateSelectionBounds();
1220 void RenderViewImpl::PepperCancelComposition(
1221 PepperPluginInstanceImpl* instance) {
1222 if (instance != focused_pepper_plugin_)
1223 return;
1224 Send(new ViewHostMsg_ImeCancelComposition(routing_id()));;
1225 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(USE_AURA)
1226 UpdateCompositionInfo(true);
1227 #endif
1230 void RenderViewImpl::PepperSelectionChanged(
1231 PepperPluginInstanceImpl* instance) {
1232 if (instance != focused_pepper_plugin_)
1233 return;
1234 SyncSelectionIfRequired();
1237 RenderWidgetFullscreenPepper* RenderViewImpl::CreatePepperFullscreenContainer(
1238 PepperPluginInstanceImpl* plugin) {
1239 GURL active_url;
1240 if (webview() && webview()->mainFrame())
1241 active_url = GURL(webview()->mainFrame()->document().url());
1242 RenderWidgetFullscreenPepper* widget = RenderWidgetFullscreenPepper::Create(
1243 routing_id_, plugin, active_url, screen_info_);
1244 widget->show(WebKit::WebNavigationPolicyIgnore);
1245 return widget;
1248 void RenderViewImpl::PepperPluginCreated(RendererPpapiHost* host) {
1249 FOR_EACH_OBSERVER(RenderViewObserver, observers_,
1250 DidCreatePepperPlugin(host));
1253 bool RenderViewImpl::GetPepperCaretBounds(gfx::Rect* rect) {
1254 if (!focused_pepper_plugin_)
1255 return false;
1256 *rect = focused_pepper_plugin_->GetCaretBounds();
1257 return true;
1260 bool RenderViewImpl::IsPepperAcceptingCompositionEvents() const {
1261 if (!focused_pepper_plugin_)
1262 return false;
1263 return focused_pepper_plugin_->IsPluginAcceptingCompositionEvents();
1266 void RenderViewImpl::PluginCrashed(const base::FilePath& plugin_path,
1267 base::ProcessId plugin_pid) {
1268 Send(new ViewHostMsg_CrashedPlugin(routing_id_, plugin_path, plugin_pid));
1271 void RenderViewImpl::RegisterPluginDelegate(WebPluginDelegateProxy* delegate) {
1272 plugin_delegates_.insert(delegate);
1273 // If the renderer is visible, set initial visibility and focus state.
1274 if (!is_hidden()) {
1275 #if defined(OS_MACOSX)
1276 delegate->SetContainerVisibility(true);
1277 if (webview() && webview()->isActive())
1278 delegate->SetWindowFocus(true);
1279 #endif
1281 // Plugins start assuming the content has focus (so that they work in
1282 // environments where RenderView isn't hosting them), so we always have to
1283 // set the initial state. See webplugin_delegate_impl.h for details.
1284 delegate->SetContentAreaFocus(has_focus());
1287 void RenderViewImpl::UnregisterPluginDelegate(
1288 WebPluginDelegateProxy* delegate) {
1289 plugin_delegates_.erase(delegate);
1292 bool RenderViewImpl::GetPluginInfo(const GURL& url,
1293 const GURL& page_url,
1294 const std::string& mime_type,
1295 WebPluginInfo* plugin_info,
1296 std::string* actual_mime_type) {
1297 bool found = false;
1298 Send(new ViewHostMsg_GetPluginInfo(
1299 routing_id_, url, page_url, mime_type, &found, plugin_info,
1300 actual_mime_type));
1301 return found;
1304 void RenderViewImpl::SimulateImeSetComposition(
1305 const string16& text,
1306 const std::vector<WebKit::WebCompositionUnderline>& underlines,
1307 int selection_start,
1308 int selection_end) {
1309 OnImeSetComposition(text, underlines, selection_start, selection_end);
1312 void RenderViewImpl::SimulateImeConfirmComposition(
1313 const string16& text,
1314 const gfx::Range& replacement_range) {
1315 OnImeConfirmComposition(text, replacement_range, false);
1318 #if defined(OS_WIN)
1319 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1320 if (focused)
1321 focused_plugin_id_ = plugin_id;
1322 else
1323 focused_plugin_id_ = -1;
1325 #endif
1327 #if defined(OS_MACOSX)
1328 void RenderViewImpl::PluginFocusChanged(bool focused, int plugin_id) {
1329 Send(new ViewHostMsg_PluginFocusChanged(routing_id(), focused, plugin_id));
1332 void RenderViewImpl::StartPluginIme() {
1333 IPC::Message* msg = new ViewHostMsg_StartPluginIme(routing_id());
1334 // This message can be sent during event-handling, and needs to be delivered
1335 // within that context.
1336 msg->set_unblock(true);
1337 Send(msg);
1339 #endif // defined(OS_MACOSX)
1341 #endif // ENABLE_PLUGINS
1343 void RenderViewImpl::TransferActiveWheelFlingAnimation(
1344 const WebKit::WebActiveWheelFlingParameters& params) {
1345 if (webview())
1346 webview()->transferActiveWheelFlingAnimation(params);
1349 bool RenderViewImpl::HasIMETextFocus() {
1350 return GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE;
1353 bool RenderViewImpl::OnMessageReceived(const IPC::Message& message) {
1354 WebFrame* main_frame = webview() ? webview()->mainFrame() : NULL;
1355 if (main_frame)
1356 GetContentClient()->SetActiveURL(main_frame->document().url());
1358 ObserverListBase<RenderViewObserver>::Iterator it(observers_);
1359 RenderViewObserver* observer;
1360 while ((observer = it.GetNext()) != NULL)
1361 if (observer->OnMessageReceived(message))
1362 return true;
1364 bool handled = true;
1365 bool msg_is_ok = true;
1366 IPC_BEGIN_MESSAGE_MAP_EX(RenderViewImpl, message, msg_is_ok)
1367 IPC_MESSAGE_HANDLER(InputMsg_Copy, OnCopy)
1368 IPC_MESSAGE_HANDLER(InputMsg_Cut, OnCut)
1369 IPC_MESSAGE_HANDLER(InputMsg_Delete, OnDelete)
1370 IPC_MESSAGE_HANDLER(InputMsg_ExecuteEditCommand, OnExecuteEditCommand)
1371 IPC_MESSAGE_HANDLER(InputMsg_MoveCaret, OnMoveCaret)
1372 IPC_MESSAGE_HANDLER(InputMsg_Paste, OnPaste)
1373 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle, OnPasteAndMatchStyle)
1374 IPC_MESSAGE_HANDLER(InputMsg_Redo, OnRedo)
1375 IPC_MESSAGE_HANDLER(InputMsg_Replace, OnReplace)
1376 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling, OnReplaceMisspelling)
1377 IPC_MESSAGE_HANDLER(InputMsg_ScrollFocusedEditableNodeIntoRect,
1378 OnScrollFocusedEditableNodeIntoRect)
1379 IPC_MESSAGE_HANDLER(InputMsg_SelectAll, OnSelectAll)
1380 IPC_MESSAGE_HANDLER(InputMsg_SelectRange, OnSelectRange)
1381 IPC_MESSAGE_HANDLER(InputMsg_SetEditCommandsForNextKeyEvent,
1382 OnSetEditCommandsForNextKeyEvent)
1383 IPC_MESSAGE_HANDLER(InputMsg_Undo, OnUndo)
1384 IPC_MESSAGE_HANDLER(InputMsg_Unselect, OnUnselect)
1385 IPC_MESSAGE_HANDLER(ViewMsg_Navigate, OnNavigate)
1386 IPC_MESSAGE_HANDLER(ViewMsg_Stop, OnStop)
1387 IPC_MESSAGE_HANDLER(ViewMsg_ReloadFrame, OnReloadFrame)
1388 IPC_MESSAGE_HANDLER(ViewMsg_SetName, OnSetName)
1389 IPC_MESSAGE_HANDLER(ViewMsg_SetEditableSelectionOffsets,
1390 OnSetEditableSelectionOffsets)
1391 IPC_MESSAGE_HANDLER(ViewMsg_SetCompositionFromExistingText,
1392 OnSetCompositionFromExistingText)
1393 IPC_MESSAGE_HANDLER(ViewMsg_ExtendSelectionAndDelete,
1394 OnExtendSelectionAndDelete)
1395 IPC_MESSAGE_HANDLER(ViewMsg_CopyImageAt, OnCopyImageAt)
1396 IPC_MESSAGE_HANDLER(ViewMsg_Find, OnFind)
1397 IPC_MESSAGE_HANDLER(ViewMsg_StopFinding, OnStopFinding)
1398 IPC_MESSAGE_HANDLER(ViewMsg_Zoom, OnZoom)
1399 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevel, OnSetZoomLevel)
1400 IPC_MESSAGE_HANDLER(ViewMsg_ZoomFactor, OnZoomFactor)
1401 IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForLoadingURL,
1402 OnSetZoomLevelForLoadingURL)
1403 IPC_MESSAGE_HANDLER(ViewMsg_SetPageEncoding, OnSetPageEncoding)
1404 IPC_MESSAGE_HANDLER(ViewMsg_ResetPageEncodingToDefault,
1405 OnResetPageEncodingToDefault)
1406 IPC_MESSAGE_HANDLER(ViewMsg_ScriptEvalRequest, OnScriptEvalRequest)
1407 IPC_MESSAGE_HANDLER(ViewMsg_PostMessageEvent, OnPostMessageEvent)
1408 IPC_MESSAGE_HANDLER(ViewMsg_CSSInsertRequest, OnCSSInsertRequest)
1409 IPC_MESSAGE_HANDLER(DragMsg_TargetDragEnter, OnDragTargetDragEnter)
1410 IPC_MESSAGE_HANDLER(DragMsg_TargetDragOver, OnDragTargetDragOver)
1411 IPC_MESSAGE_HANDLER(DragMsg_TargetDragLeave, OnDragTargetDragLeave)
1412 IPC_MESSAGE_HANDLER(DragMsg_TargetDrop, OnDragTargetDrop)
1413 IPC_MESSAGE_HANDLER(DragMsg_SourceEndedOrMoved, OnDragSourceEndedOrMoved)
1414 IPC_MESSAGE_HANDLER(DragMsg_SourceSystemDragEnded,
1415 OnDragSourceSystemDragEnded)
1416 IPC_MESSAGE_HANDLER(ViewMsg_AllowBindings, OnAllowBindings)
1417 IPC_MESSAGE_HANDLER(ViewMsg_SetInitialFocus, OnSetInitialFocus)
1418 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTargetURL_ACK, OnUpdateTargetURLAck)
1419 IPC_MESSAGE_HANDLER(ViewMsg_UpdateWebPreferences, OnUpdateWebPreferences)
1420 IPC_MESSAGE_HANDLER(ViewMsg_TimezoneChange, OnUpdateTimezone)
1421 IPC_MESSAGE_HANDLER(ViewMsg_SetAltErrorPageURL, OnSetAltErrorPageURL)
1422 IPC_MESSAGE_HANDLER(ViewMsg_EnumerateDirectoryResponse,
1423 OnEnumerateDirectoryResponse)
1424 IPC_MESSAGE_HANDLER(ViewMsg_RunFileChooserResponse, OnFileChooserResponse)
1425 IPC_MESSAGE_HANDLER(ViewMsg_ShouldClose, OnShouldClose)
1426 IPC_MESSAGE_HANDLER(ViewMsg_SwapOut, OnSwapOut)
1427 IPC_MESSAGE_HANDLER(ViewMsg_ClosePage, OnClosePage)
1428 IPC_MESSAGE_HANDLER(ViewMsg_ThemeChanged, OnThemeChanged)
1429 IPC_MESSAGE_HANDLER(ViewMsg_MoveOrResizeStarted, OnMoveOrResizeStarted)
1430 IPC_MESSAGE_HANDLER(ViewMsg_ClearFocusedNode, OnClearFocusedNode)
1431 IPC_MESSAGE_HANDLER(ViewMsg_SetBackground, OnSetBackground)
1432 IPC_MESSAGE_HANDLER(ViewMsg_EnablePreferredSizeChangedMode,
1433 OnEnablePreferredSizeChangedMode)
1434 IPC_MESSAGE_HANDLER(ViewMsg_EnableAutoResize, OnEnableAutoResize)
1435 IPC_MESSAGE_HANDLER(ViewMsg_DisableAutoResize, OnDisableAutoResize)
1436 IPC_MESSAGE_HANDLER(ViewMsg_DisableScrollbarsForSmallWindows,
1437 OnDisableScrollbarsForSmallWindows)
1438 IPC_MESSAGE_HANDLER(ViewMsg_SetRendererPrefs, OnSetRendererPrefs)
1439 IPC_MESSAGE_HANDLER(ViewMsg_MediaPlayerActionAt, OnMediaPlayerActionAt)
1440 IPC_MESSAGE_HANDLER(ViewMsg_OrientationChangeEvent,
1441 OnOrientationChangeEvent)
1442 IPC_MESSAGE_HANDLER(ViewMsg_PluginActionAt, OnPluginActionAt)
1443 IPC_MESSAGE_HANDLER(ViewMsg_SetActive, OnSetActive)
1444 IPC_MESSAGE_HANDLER(ViewMsg_CustomContextMenuAction,
1445 OnCustomContextMenuAction)
1446 IPC_MESSAGE_HANDLER(ViewMsg_GetAllSavableResourceLinksForCurrentPage,
1447 OnGetAllSavableResourceLinksForCurrentPage)
1448 IPC_MESSAGE_HANDLER(
1449 ViewMsg_GetSerializedHtmlDataForCurrentPageWithLocalLinks,
1450 OnGetSerializedHtmlDataForCurrentPageWithLocalLinks)
1451 IPC_MESSAGE_HANDLER(ViewMsg_ContextMenuClosed, OnContextMenuClosed)
1452 IPC_MESSAGE_HANDLER(ViewMsg_ShowContextMenu, OnShowContextMenu)
1453 // TODO(viettrungluu): Move to a separate message filter.
1454 IPC_MESSAGE_HANDLER(ViewMsg_SetHistoryLengthAndPrune,
1455 OnSetHistoryLengthAndPrune)
1456 IPC_MESSAGE_HANDLER(ViewMsg_EnableViewSourceMode, OnEnableViewSourceMode)
1457 #if defined(OS_ANDROID)
1458 IPC_MESSAGE_HANDLER(JavaBridgeMsg_Init, OnJavaBridgeInit)
1459 #endif
1460 IPC_MESSAGE_HANDLER(ViewMsg_SetAccessibilityMode, OnSetAccessibilityMode)
1461 IPC_MESSAGE_HANDLER(ViewMsg_DisownOpener, OnDisownOpener)
1462 #if defined(OS_ANDROID)
1463 IPC_MESSAGE_HANDLER(InputMsg_ActivateNearestFindResult,
1464 OnActivateNearestFindResult)
1465 IPC_MESSAGE_HANDLER(ViewMsg_FindMatchRects, OnFindMatchRects)
1466 IPC_MESSAGE_HANDLER(ViewMsg_SelectPopupMenuItems, OnSelectPopupMenuItems)
1467 IPC_MESSAGE_HANDLER(ViewMsg_UndoScrollFocusedEditableNodeIntoView,
1468 OnUndoScrollFocusedEditableNodeIntoRect)
1469 IPC_MESSAGE_HANDLER(ViewMsg_UpdateTopControlsState,
1470 OnUpdateTopControlsState)
1471 IPC_MESSAGE_HANDLER(ViewMsg_PauseVideo, OnPauseVideo)
1472 #elif defined(OS_MACOSX)
1473 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard, OnCopyToFindPboard)
1474 IPC_MESSAGE_HANDLER(ViewMsg_PluginImeCompositionCompleted,
1475 OnPluginImeCompositionCompleted)
1476 IPC_MESSAGE_HANDLER(ViewMsg_SelectPopupMenuItem, OnSelectPopupMenuItem)
1477 IPC_MESSAGE_HANDLER(ViewMsg_SetInLiveResize, OnSetInLiveResize)
1478 IPC_MESSAGE_HANDLER(ViewMsg_SetWindowVisibility, OnSetWindowVisibility)
1479 IPC_MESSAGE_HANDLER(ViewMsg_WindowFrameChanged, OnWindowFrameChanged)
1480 #endif
1481 IPC_MESSAGE_HANDLER(ViewMsg_ReleaseDisambiguationPopupDIB,
1482 OnReleaseDisambiguationPopupDIB)
1483 IPC_MESSAGE_HANDLER(ViewMsg_WindowSnapshotCompleted,
1484 OnWindowSnapshotCompleted)
1486 // Have the super handle all other messages.
1487 IPC_MESSAGE_UNHANDLED(handled = RenderWidget::OnMessageReceived(message))
1488 IPC_END_MESSAGE_MAP()
1490 if (!msg_is_ok) {
1491 // The message had a handler, but its deserialization failed.
1492 // Kill the renderer to avoid potential spoofing attacks.
1493 CHECK(false) << "Unable to deserialize message in RenderViewImpl.";
1496 return handled;
1499 void RenderViewImpl::OnNavigate(const ViewMsg_Navigate_Params& params) {
1500 MaybeHandleDebugURL(params.url);
1501 if (!webview())
1502 return;
1504 FOR_EACH_OBSERVER(RenderViewObserver, observers_, Navigate(params.url));
1506 bool is_reload = IsReload(params);
1508 // If this is a stale back/forward (due to a recent navigation the browser
1509 // didn't know about), ignore it.
1510 if (IsBackForwardToStaleEntry(params, is_reload))
1511 return;
1513 // Swap this renderer back in if necessary.
1514 if (is_swapped_out_) {
1515 // We marked the view as hidden when swapping the view out, so be sure to
1516 // reset the visibility state before navigating to the new URL.
1517 webview()->setVisibilityState(visibilityState(), false);
1519 // If this is an attempt to reload while we are swapped out, we should not
1520 // reload swappedout://, but the previous page, which is stored in
1521 // params.state. Setting is_reload to false will treat this like a back
1522 // navigation to accomplish that.
1523 is_reload = false;
1525 // We refresh timezone when a view is swapped in since timezone
1526 // can get out of sync when the system timezone is updated while
1527 // the view is swapped out.
1528 NotifyTimezoneChange(webview()->mainFrame());
1530 SetSwappedOut(false);
1533 if (params.should_clear_history_list) {
1534 CHECK_EQ(params.pending_history_list_offset, -1);
1535 CHECK_EQ(params.current_history_list_offset, -1);
1536 CHECK_EQ(params.current_history_list_length, 0);
1538 history_list_offset_ = params.current_history_list_offset;
1539 history_list_length_ = params.current_history_list_length;
1540 if (history_list_length_ >= 0)
1541 history_page_ids_.resize(history_list_length_, -1);
1542 if (params.pending_history_list_offset >= 0 &&
1543 params.pending_history_list_offset < history_list_length_)
1544 history_page_ids_[params.pending_history_list_offset] = params.page_id;
1546 GetContentClient()->SetActiveURL(params.url);
1548 WebFrame* frame = webview()->mainFrame();
1549 if (!params.frame_to_navigate.empty()) {
1550 frame = webview()->findFrameByName(
1551 WebString::fromUTF8(params.frame_to_navigate));
1552 CHECK(frame) << "Invalid frame name passed: " << params.frame_to_navigate;
1555 if (is_reload && frame->currentHistoryItem().isNull()) {
1556 // We cannot reload if we do not have any history state. This happens, for
1557 // example, when recovering from a crash. Our workaround here is a bit of
1558 // a hack since it means that reload after a crashed tab does not cause an
1559 // end-to-end cache validation.
1560 is_reload = false;
1563 pending_navigation_params_.reset(new ViewMsg_Navigate_Params(params));
1565 // If we are reloading, then WebKit will use the history state of the current
1566 // page, so we should just ignore any given history state. Otherwise, if we
1567 // have history state, then we need to navigate to it, which corresponds to a
1568 // back/forward navigation event.
1569 if (is_reload) {
1570 bool reload_original_url =
1571 (params.navigation_type ==
1572 ViewMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
1573 bool ignore_cache = (params.navigation_type ==
1574 ViewMsg_Navigate_Type::RELOAD_IGNORING_CACHE);
1576 if (reload_original_url)
1577 frame->reloadWithOverrideURL(params.url, true);
1578 else
1579 frame->reload(ignore_cache);
1580 } else if (params.page_state.IsValid()) {
1581 // We must know the page ID of the page we are navigating back to.
1582 DCHECK_NE(params.page_id, -1);
1583 WebHistoryItem item = PageStateToHistoryItem(params.page_state);
1584 if (!item.isNull()) {
1585 // Ensure we didn't save the swapped out URL in UpdateState, since the
1586 // browser should never be telling us to navigate to swappedout://.
1587 CHECK(item.urlString() != WebString::fromUTF8(kSwappedOutURL));
1588 frame->loadHistoryItem(item);
1590 } else if (!params.base_url_for_data_url.is_empty()) {
1591 // A loadData request with a specified base URL.
1592 std::string mime_type, charset, data;
1593 if (net::DataURL::Parse(params.url, &mime_type, &charset, &data)) {
1594 frame->loadData(
1595 WebData(data.c_str(), data.length()),
1596 WebString::fromUTF8(mime_type),
1597 WebString::fromUTF8(charset),
1598 params.base_url_for_data_url,
1599 params.history_url_for_data_url,
1600 false);
1601 } else {
1602 CHECK(false) <<
1603 "Invalid URL passed: " << params.url.possibly_invalid_spec();
1605 } else {
1606 // Navigate to the given URL.
1607 WebURLRequest request(params.url);
1609 // A session history navigation should have been accompanied by state.
1610 CHECK_EQ(params.page_id, -1);
1612 if (frame->isViewSourceModeEnabled())
1613 request.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad);
1615 if (params.referrer.url.is_valid()) {
1616 WebString referrer = WebSecurityPolicy::generateReferrerHeader(
1617 params.referrer.policy,
1618 params.url,
1619 WebString::fromUTF8(params.referrer.url.spec()));
1620 if (!referrer.isEmpty())
1621 request.setHTTPHeaderField(WebString::fromUTF8("Referer"), referrer);
1624 if (!params.extra_headers.empty()) {
1625 for (net::HttpUtil::HeadersIterator i(params.extra_headers.begin(),
1626 params.extra_headers.end(), "\n");
1627 i.GetNext(); ) {
1628 request.addHTTPHeaderField(WebString::fromUTF8(i.name()),
1629 WebString::fromUTF8(i.values()));
1633 if (params.is_post) {
1634 request.setHTTPMethod(WebString::fromUTF8("POST"));
1636 // Set post data.
1637 WebHTTPBody http_body;
1638 http_body.initialize();
1639 http_body.appendData(WebData(
1640 reinterpret_cast<const char*>(
1641 &params.browser_initiated_post_data.front()),
1642 params.browser_initiated_post_data.size()));
1643 request.setHTTPBody(http_body);
1646 frame->loadRequest(request);
1648 // If this is a cross-process navigation, the browser process will send
1649 // along the proper navigation start value.
1650 if (!params.browser_navigation_start.is_null() &&
1651 frame->provisionalDataSource()) {
1652 // browser_navigation_start is likely before this process existed, so we
1653 // can't use InterProcessTimeTicksConverter. Instead, the best we can do
1654 // is just ensure we don't report a bogus value in the future.
1655 base::TimeTicks navigation_start = std::min(
1656 base::TimeTicks::Now(), params.browser_navigation_start);
1657 double navigation_start_seconds =
1658 (navigation_start - base::TimeTicks()).InSecondsF();
1659 frame->provisionalDataSource()->setNavigationStartTime(
1660 navigation_start_seconds);
1664 // In case LoadRequest failed before DidCreateDataSource was called.
1665 pending_navigation_params_.reset();
1668 bool RenderViewImpl::IsBackForwardToStaleEntry(
1669 const ViewMsg_Navigate_Params& params,
1670 bool is_reload) {
1671 // Make sure this isn't a back/forward to an entry we have already cropped
1672 // or replaced from our history, before the browser knew about it. If so,
1673 // a new navigation has committed in the mean time, and we can ignore this.
1674 bool is_back_forward = !is_reload && params.page_state.IsValid();
1676 // Note: if the history_list_length_ is 0 for a back/forward, we must be
1677 // restoring from a previous session. We'll update our state in OnNavigate.
1678 if (!is_back_forward || history_list_length_ <= 0)
1679 return false;
1681 DCHECK_EQ(static_cast<int>(history_page_ids_.size()), history_list_length_);
1683 // Check for whether the forward history has been cropped due to a recent
1684 // navigation the browser didn't know about.
1685 if (params.pending_history_list_offset >= history_list_length_)
1686 return true;
1688 // Check for whether this entry has been replaced with a new one.
1689 int expected_page_id =
1690 history_page_ids_[params.pending_history_list_offset];
1691 if (expected_page_id > 0 && params.page_id != expected_page_id) {
1692 if (params.page_id < expected_page_id)
1693 return true;
1695 // Otherwise we've removed an earlier entry and should have shifted all
1696 // entries left. For now, it's ok to lazily update the list.
1697 // TODO(creis): Notify all live renderers when we remove entries from
1698 // the front of the list, so that we don't hit this case.
1699 history_page_ids_[params.pending_history_list_offset] = params.page_id;
1702 return false;
1705 // Stop loading the current page
1706 void RenderViewImpl::OnStop() {
1707 if (webview()) {
1708 WebFrame* main_frame = webview()->mainFrame();
1709 // Stop the alt error page fetcher. If we let it continue it may complete
1710 // and cause RenderViewHostManager to swap to this RenderView, even though
1711 // it may no longer be active.
1712 StopAltErrorPageFetcher(main_frame->provisionalDataSource());
1713 StopAltErrorPageFetcher(main_frame->dataSource());
1714 main_frame->stopLoading();
1718 // Reload current focused frame.
1719 // E.g. called by right-clicking on the frame and picking "reload this frame".
1720 void RenderViewImpl::OnReloadFrame() {
1721 if (webview() && webview()->focusedFrame()) {
1722 // We always obey the cache (ignore_cache=false) here.
1723 // TODO(evanm): perhaps we could allow shift-clicking the menu item to do
1724 // a cache-ignoring reload of the frame.
1725 webview()->focusedFrame()->reload(false);
1729 void RenderViewImpl::OnCopyImageAt(int x, int y) {
1730 webview()->copyImageAt(WebPoint(x, y));
1733 void RenderViewImpl::OnUpdateTargetURLAck() {
1734 // Check if there is a targeturl waiting to be sent.
1735 if (target_url_status_ == TARGET_PENDING) {
1736 Send(new ViewHostMsg_UpdateTargetURL(routing_id_, page_id_,
1737 pending_target_url_));
1740 target_url_status_ = TARGET_NONE;
1743 void RenderViewImpl::OnCopy() {
1744 if (!webview())
1745 return;
1747 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1748 WebNode current_node = context_menu_node_.isNull() ?
1749 GetFocusedNode() : context_menu_node_;
1750 webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Copy"),
1751 current_node);
1754 void RenderViewImpl::OnCut() {
1755 if (!webview())
1756 return;
1758 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1759 webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Cut"),
1760 GetFocusedNode());
1763 void RenderViewImpl::OnDelete() {
1764 if (!webview())
1765 return;
1767 webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Delete"),
1768 GetFocusedNode());
1771 void RenderViewImpl::OnExecuteEditCommand(const std::string& name,
1772 const std::string& value) {
1773 if (!webview() || !webview()->focusedFrame())
1774 return;
1776 webview()->focusedFrame()->executeCommand(
1777 WebString::fromUTF8(name), WebString::fromUTF8(value));
1780 void RenderViewImpl::OnMoveCaret(const gfx::Point& point) {
1781 if (!webview())
1782 return;
1784 Send(new ViewHostMsg_MoveCaret_ACK(routing_id_));
1786 webview()->focusedFrame()->moveCaretSelectionTowardsWindowPoint(point);
1789 void RenderViewImpl::OnPaste() {
1790 if (!webview())
1791 return;
1793 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1794 webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Paste"),
1795 GetFocusedNode());
1798 void RenderViewImpl::OnPasteAndMatchStyle() {
1799 if (!webview())
1800 return;
1802 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1803 webview()->focusedFrame()->executeCommand(
1804 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedNode());
1807 void RenderViewImpl::OnRedo() {
1808 if (!webview())
1809 return;
1811 webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Redo"),
1812 GetFocusedNode());
1815 void RenderViewImpl::OnReplace(const string16& text) {
1816 if (!webview())
1817 return;
1819 WebFrame* frame = webview()->focusedFrame();
1820 if (!frame->hasSelection())
1821 frame->selectWordAroundCaret();
1823 frame->replaceSelection(text);
1826 void RenderViewImpl::OnReplaceMisspelling(const string16& text) {
1827 if (!webview())
1828 return;
1830 WebFrame* frame = webview()->focusedFrame();
1831 if (!frame->hasSelection())
1832 return;
1834 frame->replaceMisspelledRange(text);
1837 void RenderViewImpl::OnScrollFocusedEditableNodeIntoRect(
1838 const gfx::Rect& rect) {
1839 WebKit::WebNode node = GetFocusedNode();
1840 if (!node.isNull()) {
1841 if (IsEditableNode(node)) {
1842 webview()->saveScrollAndScaleState();
1843 webview()->scrollFocusedNodeIntoRect(rect);
1848 void RenderViewImpl::OnSelectAll() {
1849 if (!webview())
1850 return;
1852 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1853 webview()->focusedFrame()->executeCommand(
1854 WebString::fromUTF8("SelectAll"), GetFocusedNode());
1857 void RenderViewImpl::OnSelectRange(const gfx::Point& start,
1858 const gfx::Point& end) {
1859 if (!webview())
1860 return;
1862 Send(new ViewHostMsg_SelectRange_ACK(routing_id_));
1864 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1865 webview()->focusedFrame()->selectRange(start, end);
1868 void RenderViewImpl::OnSetEditCommandsForNextKeyEvent(
1869 const EditCommands& edit_commands) {
1870 edit_commands_ = edit_commands;
1873 void RenderViewImpl::OnUndo() {
1874 if (!webview())
1875 return;
1877 webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Undo"),
1878 GetFocusedNode());
1881 void RenderViewImpl::OnUnselect() {
1882 if (!webview())
1883 return;
1885 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1886 webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Unselect"),
1887 GetFocusedNode());
1890 #if defined(OS_MACOSX)
1891 void RenderViewImpl::OnCopyToFindPboard() {
1892 if (!webview())
1893 return;
1895 // Since the find pasteboard supports only plain text, this can be simpler
1896 // than the |OnCopy()| case.
1897 WebFrame* frame = webview()->focusedFrame();
1898 if (frame->hasSelection()) {
1899 string16 selection = frame->selectionAsText();
1900 RenderThread::Get()->Send(
1901 new ClipboardHostMsg_FindPboardWriteStringAsync(selection));
1904 #endif
1906 void RenderViewImpl::OnSetName(const std::string& name) {
1907 if (!webview())
1908 return;
1910 webview()->mainFrame()->setName(WebString::fromUTF8(name));
1913 void RenderViewImpl::OnSetEditableSelectionOffsets(int start, int end) {
1914 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1915 if (!ShouldHandleImeEvent())
1916 return;
1917 ImeEventGuard guard(this);
1918 webview()->setEditableSelectionOffsets(start, end);
1921 void RenderViewImpl::OnSetCompositionFromExistingText(
1922 int start, int end,
1923 const std::vector<WebKit::WebCompositionUnderline>& underlines) {
1924 if (!ShouldHandleImeEvent())
1925 return;
1926 ImeEventGuard guard(this);
1927 webview()->setCompositionFromExistingText(start, end, underlines);
1930 void RenderViewImpl::OnExtendSelectionAndDelete(int before, int after) {
1931 if (!ShouldHandleImeEvent())
1932 return;
1933 ImeEventGuard guard(this);
1934 webview()->extendSelectionAndDelete(before, after);
1937 void RenderViewImpl::OnSetHistoryLengthAndPrune(int history_length,
1938 int32 minimum_page_id) {
1939 DCHECK_GE(history_length, 0);
1940 DCHECK(history_list_offset_ == history_list_length_ - 1);
1941 DCHECK_GE(minimum_page_id, -1);
1943 // Generate the new list.
1944 std::vector<int32> new_history_page_ids(history_length, -1);
1945 for (size_t i = 0; i < history_page_ids_.size(); ++i) {
1946 if (minimum_page_id >= 0 && history_page_ids_[i] < minimum_page_id)
1947 continue;
1948 new_history_page_ids.push_back(history_page_ids_[i]);
1950 new_history_page_ids.swap(history_page_ids_);
1952 // Update indexes.
1953 history_list_length_ = history_page_ids_.size();
1954 history_list_offset_ = history_list_length_ - 1;
1958 void RenderViewImpl::OnSetInitialFocus(bool reverse) {
1959 if (!webview())
1960 return;
1961 webview()->setInitialFocus(reverse);
1964 #if defined(OS_MACOSX)
1965 void RenderViewImpl::OnSetInLiveResize(bool in_live_resize) {
1966 if (!webview())
1967 return;
1968 if (in_live_resize)
1969 webview()->willStartLiveResize();
1970 else
1971 webview()->willEndLiveResize();
1973 #endif
1975 #if defined(OS_ANDROID)
1976 void RenderViewImpl::OnUndoScrollFocusedEditableNodeIntoRect() {
1977 const WebNode node = GetFocusedNode();
1978 if (!node.isNull() && IsEditableNode(node))
1979 webview()->restoreScrollAndScaleState();
1982 void RenderViewImpl::OnPauseVideo() {
1983 // Inform RendererMediaPlayerManager to release all video player resources.
1984 // If something is in progress the resource will not be freed, it will
1985 // only be freed once the tab is destroyed or if the user navigates away
1986 // via WebMediaPlayerAndroid::Destroy.
1987 media_player_manager_->ReleaseVideoResources();
1989 #endif
1991 ///////////////////////////////////////////////////////////////////////////////
1993 // Tell the embedding application that the URL of the active page has changed
1994 void RenderViewImpl::UpdateURL(WebFrame* frame) {
1995 WebDataSource* ds = frame->dataSource();
1996 DCHECK(ds);
1998 const WebURLRequest& request = ds->request();
1999 const WebURLRequest& original_request = ds->originalRequest();
2000 const WebURLResponse& response = ds->response();
2002 DocumentState* document_state = DocumentState::FromDataSource(ds);
2003 NavigationState* navigation_state = document_state->navigation_state();
2004 InternalDocumentStateData* internal_data =
2005 InternalDocumentStateData::FromDocumentState(document_state);
2007 ViewHostMsg_FrameNavigate_Params params;
2008 params.http_status_code = response.httpStatusCode();
2009 params.is_post = false;
2010 params.post_id = -1;
2011 params.page_id = page_id_;
2012 params.frame_id = frame->identifier();
2013 params.frame_unique_name = frame->uniqueName();
2014 params.socket_address.set_host(response.remoteIPAddress().utf8());
2015 params.socket_address.set_port(response.remotePort());
2016 WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response);
2017 if (extra_data) {
2018 params.was_fetched_via_proxy = extra_data->was_fetched_via_proxy();
2020 params.was_within_same_page = navigation_state->was_within_same_page();
2021 params.security_info = response.securityInfo();
2023 // Set the URL to be displayed in the browser UI to the user.
2024 params.url = GetLoadingUrl(frame);
2025 DCHECK(!is_swapped_out_ || params.url == GURL(kSwappedOutURL));
2027 if (frame->document().baseURL() != params.url)
2028 params.base_url = frame->document().baseURL();
2030 GetRedirectChain(ds, &params.redirects);
2031 params.should_update_history = !ds->hasUnreachableURL() &&
2032 !response.isMultipartPayload() && (response.httpStatusCode() != 404);
2034 params.searchable_form_url = internal_data->searchable_form_url();
2035 params.searchable_form_encoding = internal_data->searchable_form_encoding();
2037 params.gesture = navigation_gesture_;
2038 navigation_gesture_ = NavigationGestureUnknown;
2040 // Make navigation state a part of the FrameNavigate message so that commited
2041 // entry had it at all times.
2042 WebHistoryItem item = frame->currentHistoryItem();
2043 if (item.isNull()) {
2044 item.initialize();
2045 item.setURLString(request.url().spec().utf16());
2047 params.page_state = HistoryItemToPageState(item);
2049 if (!frame->parent()) {
2050 // Top-level navigation.
2052 // Reset the zoom limits in case a plugin had changed them previously. This
2053 // will also call us back which will cause us to send a message to
2054 // update WebContentsImpl.
2055 webview()->zoomLimitsChanged(ZoomFactorToZoomLevel(kMinimumZoomFactor),
2056 ZoomFactorToZoomLevel(kMaximumZoomFactor));
2058 // Set zoom level, but don't do it for full-page plugin since they don't use
2059 // the same zoom settings.
2060 HostZoomLevels::iterator host_zoom =
2061 host_zoom_levels_.find(GURL(request.url()));
2062 if (webview()->mainFrame()->document().isPluginDocument()) {
2063 // Reset the zoom levels for plugins.
2064 webview()->setZoomLevel(0);
2065 } else {
2066 if (host_zoom != host_zoom_levels_.end())
2067 webview()->setZoomLevel(host_zoom->second);
2070 if (host_zoom != host_zoom_levels_.end()) {
2071 // This zoom level was merely recorded transiently for this load. We can
2072 // erase it now. If at some point we reload this page, the browser will
2073 // send us a new, up-to-date zoom level.
2074 host_zoom_levels_.erase(host_zoom);
2077 // Update contents MIME type for main frame.
2078 params.contents_mime_type = ds->response().mimeType().utf8();
2080 params.transition = navigation_state->transition_type();
2081 if (!PageTransitionIsMainFrame(params.transition)) {
2082 // If the main frame does a load, it should not be reported as a subframe
2083 // navigation. This can occur in the following case:
2084 // 1. You're on a site with frames.
2085 // 2. You do a subframe navigation. This is stored with transition type
2086 // MANUAL_SUBFRAME.
2087 // 3. You navigate to some non-frame site, say, google.com.
2088 // 4. You navigate back to the page from step 2. Since it was initially
2089 // MANUAL_SUBFRAME, it will be that same transition type here.
2090 // We don't want that, because any navigation that changes the toplevel
2091 // frame should be tracked as a toplevel navigation (this allows us to
2092 // update the URL bar, etc).
2093 params.transition = PAGE_TRANSITION_LINK;
2096 // If the page contained a client redirect (meta refresh, document.loc...),
2097 // set the referrer and transition appropriately.
2098 if (ds->isClientRedirect()) {
2099 params.referrer = Referrer(params.redirects[0],
2100 GetReferrerPolicyFromRequest(frame, ds->request()));
2101 params.transition = static_cast<PageTransition>(
2102 params.transition | PAGE_TRANSITION_CLIENT_REDIRECT);
2103 } else {
2104 // Bug 654101: the referrer will be empty on https->http transitions. It
2105 // would be nice if we could get the real referrer from somewhere.
2106 params.referrer = GetReferrerFromRequest(frame, original_request);
2109 string16 method = request.httpMethod();
2110 if (EqualsASCII(method, "POST")) {
2111 params.is_post = true;
2112 params.post_id = ExtractPostId(item);
2115 // Send the user agent override back.
2116 params.is_overriding_user_agent = internal_data->is_overriding_user_agent();
2118 // Track the URL of the original request.
2119 params.original_request_url = original_request.url();
2121 params.history_list_was_cleared =
2122 navigation_state->history_list_was_cleared();
2124 // Save some histogram data so we can compute the average memory used per
2125 // page load of the glyphs.
2126 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
2127 WebKit::WebGlyphCache::pageCount());
2129 // This message needs to be sent before any of allowScripts(),
2130 // allowImages(), allowPlugins() is called for the new page, so that when
2131 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
2132 // after the ViewHostMsg_FrameNavigate message.
2133 Send(new ViewHostMsg_FrameNavigate(routing_id_, params));
2134 } else {
2135 // Subframe navigation: the type depends on whether this navigation
2136 // generated a new session history entry. When they do generate a session
2137 // history entry, it means the user initiated the navigation and we should
2138 // mark it as such. This test checks if this is the first time UpdateURL
2139 // has been called since WillNavigateToURL was called to initiate the load.
2140 if (page_id_ > last_page_id_sent_to_browser_)
2141 params.transition = PAGE_TRANSITION_MANUAL_SUBFRAME;
2142 else
2143 params.transition = PAGE_TRANSITION_AUTO_SUBFRAME;
2145 DCHECK(!navigation_state->history_list_was_cleared());
2146 params.history_list_was_cleared = false;
2148 Send(new ViewHostMsg_FrameNavigate(routing_id_, params));
2151 last_page_id_sent_to_browser_ =
2152 std::max(last_page_id_sent_to_browser_, page_id_);
2154 // If we end up reusing this WebRequest (for example, due to a #ref click),
2155 // we don't want the transition type to persist. Just clear it.
2156 navigation_state->set_transition_type(PAGE_TRANSITION_LINK);
2159 // Tell the embedding application that the title of the active page has changed
2160 void RenderViewImpl::UpdateTitle(WebFrame* frame,
2161 const string16& title,
2162 WebTextDirection title_direction) {
2163 // Ignore all but top level navigations.
2164 if (frame->parent())
2165 return;
2167 base::debug::TraceLog::GetInstance()->UpdateProcessLabel(
2168 routing_id_, UTF16ToUTF8(title));
2170 string16 shortened_title = title.substr(0, kMaxTitleChars);
2171 Send(new ViewHostMsg_UpdateTitle(routing_id_, page_id_, shortened_title,
2172 title_direction));
2175 void RenderViewImpl::UpdateEncoding(WebFrame* frame,
2176 const std::string& encoding_name) {
2177 // Only update main frame's encoding_name.
2178 if (webview()->mainFrame() == frame &&
2179 last_encoding_name_ != encoding_name) {
2180 // Save the encoding name for later comparing.
2181 last_encoding_name_ = encoding_name;
2183 Send(new ViewHostMsg_UpdateEncoding(routing_id_, last_encoding_name_));
2187 // Sends the last committed session history state to the browser so it will be
2188 // saved before we navigate to a new page. This must be called *before* the
2189 // page ID has been updated so we know what it was.
2190 void RenderViewImpl::UpdateSessionHistory(WebFrame* frame) {
2191 // If we have a valid page ID at this point, then it corresponds to the page
2192 // we are navigating away from. Otherwise, this is the first navigation, so
2193 // there is no past session history to record.
2194 if (page_id_ == -1)
2195 return;
2197 const WebHistoryItem& item =
2198 webview()->mainFrame()->previousHistoryItem();
2199 SendUpdateState(item);
2202 void RenderViewImpl::SendUpdateState(const WebHistoryItem& item) {
2203 if (item.isNull())
2204 return;
2206 // Don't send state updates for kSwappedOutURL.
2207 if (item.urlString() == WebString::fromUTF8(kSwappedOutURL))
2208 return;
2210 Send(new ViewHostMsg_UpdateState(
2211 routing_id_, page_id_, HistoryItemToPageState(item)));
2214 void RenderViewImpl::OpenURL(WebFrame* frame,
2215 const GURL& url,
2216 const Referrer& referrer,
2217 WebNavigationPolicy policy) {
2218 ViewHostMsg_OpenURL_Params params;
2219 params.url = url;
2220 params.referrer = referrer;
2221 params.disposition = NavigationPolicyToDisposition(policy);
2222 params.frame_id = frame->identifier();
2223 WebDataSource* ds = frame->provisionalDataSource();
2224 if (ds) {
2225 params.should_replace_current_entry = ds->replacesCurrentHistoryItem();
2226 } else {
2227 params.should_replace_current_entry = false;
2229 params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
2230 if (GetContentClient()->renderer()->AllowPopup())
2231 params.user_gesture = true;
2233 if (policy == WebKit::WebNavigationPolicyNewBackgroundTab ||
2234 policy == WebKit::WebNavigationPolicyNewForegroundTab ||
2235 policy == WebKit::WebNavigationPolicyNewWindow ||
2236 policy == WebKit::WebNavigationPolicyNewPopup) {
2237 WebUserGestureIndicator::consumeUserGesture();
2240 Send(new ViewHostMsg_OpenURL(routing_id_, params));
2243 // WebViewDelegate ------------------------------------------------------------
2245 void RenderViewImpl::LoadNavigationErrorPage(
2246 WebFrame* frame,
2247 const WebURLRequest& failed_request,
2248 const WebURLError& error,
2249 const std::string& html,
2250 bool replace) {
2251 std::string alt_html;
2252 const std::string* error_html;
2254 if (!html.empty()) {
2255 error_html = &html;
2256 } else {
2257 GetContentClient()->renderer()->GetNavigationErrorStrings(
2258 frame, failed_request, error, renderer_preferences_.accept_languages,
2259 &alt_html, NULL);
2260 error_html = &alt_html;
2263 frame->loadHTMLString(*error_html,
2264 GURL(kUnreachableWebDataURL),
2265 error.unreachableURL,
2266 replace);
2269 bool RenderViewImpl::RunJavaScriptMessage(JavaScriptMessageType type,
2270 const string16& message,
2271 const string16& default_value,
2272 const GURL& frame_url,
2273 string16* result) {
2274 bool success = false;
2275 string16 result_temp;
2276 if (!result)
2277 result = &result_temp;
2279 SendAndRunNestedMessageLoop(new ViewHostMsg_RunJavaScriptMessage(
2280 routing_id_, message, default_value, frame_url, type, &success, result));
2281 return success;
2284 bool RenderViewImpl::SendAndRunNestedMessageLoop(IPC::SyncMessage* message) {
2285 // Before WebKit asks us to show an alert (etc.), it takes care of doing the
2286 // equivalent of WebView::willEnterModalLoop. In the case of showModalDialog
2287 // it is particularly important that we do not call willEnterModalLoop as
2288 // that would defer resource loads for the dialog itself.
2289 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
2290 RenderThreadImpl::current()->DoNotNotifyWebKitOfModalLoop();
2292 message->EnableMessagePumping(); // Runs a nested message loop.
2293 return Send(message);
2296 void RenderViewImpl::GetWindowSnapshot(const WindowSnapshotCallback& callback) {
2297 int id = next_snapshot_id_++;
2298 pending_snapshots_.insert(std::make_pair(id, callback));
2299 ui::LatencyInfo latency_info;
2300 latency_info.AddLatencyNumber(ui::WINDOW_SNAPSHOT_FRAME_NUMBER_COMPONENT,
2301 GetLatencyComponentId(),
2302 id);
2303 if (RenderWidgetCompositor* rwc = compositor()) {
2304 rwc->SetLatencyInfo(latency_info);
2305 } else {
2306 latency_info_.MergeWith(latency_info);
2308 ScheduleCompositeWithForcedRedraw();
2311 void RenderViewImpl::OnWindowSnapshotCompleted(const int snapshot_id,
2312 const gfx::Size& size, const std::vector<unsigned char>& png) {
2314 // Any pending snapshots with a lower ID than the one received are considered
2315 // to be implicitly complete, and returned the same snapshot data.
2316 PendingSnapshotMap::iterator it = pending_snapshots_.begin();
2317 while(it != pending_snapshots_.end()) {
2318 if (it->first <= snapshot_id) {
2319 it->second.Run(size, png);
2320 pending_snapshots_.erase(it++);
2321 } else {
2322 ++it;
2327 // WebKit::WebViewClient ------------------------------------------------------
2329 WebView* RenderViewImpl::createView(
2330 WebFrame* creator,
2331 const WebURLRequest& request,
2332 const WebWindowFeatures& features,
2333 const WebString& frame_name,
2334 WebNavigationPolicy policy) {
2335 ViewHostMsg_CreateWindow_Params params;
2336 params.opener_id = routing_id_;
2337 params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
2338 if (GetContentClient()->renderer()->AllowPopup())
2339 params.user_gesture = true;
2340 params.window_container_type = WindowFeaturesToContainerType(features);
2341 params.session_storage_namespace_id = session_storage_namespace_id_;
2342 if (frame_name != "_blank")
2343 params.frame_name = frame_name;
2344 params.opener_frame_id = creator->identifier();
2345 params.opener_url = creator->document().url();
2346 params.opener_top_level_frame_url = creator->top()->document().url();
2347 GURL security_url(creator->document().securityOrigin().toString().utf8());
2348 if (!security_url.is_valid())
2349 security_url = GURL();
2350 params.opener_security_origin = security_url;
2351 params.opener_suppressed = creator->willSuppressOpenerInNewFrame();
2352 params.disposition = NavigationPolicyToDisposition(policy);
2353 if (!request.isNull()) {
2354 params.target_url = request.url();
2355 params.referrer = GetReferrerFromRequest(creator, request);
2357 params.features = features;
2359 int32 routing_id = MSG_ROUTING_NONE;
2360 int32 main_frame_routing_id = MSG_ROUTING_NONE;
2361 int32 surface_id = 0;
2362 int64 cloned_session_storage_namespace_id;
2364 RenderThread::Get()->Send(
2365 new ViewHostMsg_CreateWindow(params,
2366 &routing_id,
2367 &main_frame_routing_id,
2368 &surface_id,
2369 &cloned_session_storage_namespace_id));
2370 if (routing_id == MSG_ROUTING_NONE)
2371 return NULL;
2373 WebUserGestureIndicator::consumeUserGesture();
2375 WebPreferences transferred_preferences = webkit_preferences_;
2377 // Unless accelerated compositing has been explicitly disabled from the
2378 // command line (e.g. via the blacklist or about:flags) re-enable it for
2379 // new views that get spawned by this view. This gets around the issue that
2380 // background extension pages disable accelerated compositing via web prefs
2381 // but can themselves spawn a visible render view which should be allowed
2382 // use gpu acceleration.
2383 if (!webkit_preferences_.accelerated_compositing_enabled) {
2384 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
2385 if (!command_line.HasSwitch(switches::kDisableAcceleratedCompositing))
2386 transferred_preferences.accelerated_compositing_enabled = true;
2389 // The initial hidden state for the RenderViewImpl here has to match what the
2390 // browser will eventually decide for the given disposition. Since we have to
2391 // return from this call synchronously, we just have to make our best guess
2392 // and rely on the browser sending a WasHidden / WasShown message if it
2393 // disagrees.
2394 RenderViewImpl* view = RenderViewImpl::Create(
2395 routing_id_,
2396 renderer_preferences_,
2397 transferred_preferences,
2398 routing_id,
2399 main_frame_routing_id,
2400 surface_id,
2401 cloned_session_storage_namespace_id,
2402 string16(), // WebCore will take care of setting the correct name.
2403 true, // is_renderer_created
2404 false, // swapped_out
2405 params.disposition == NEW_BACKGROUND_TAB, // hidden
2406 1, // next_page_id
2407 screen_info_,
2408 accessibility_mode_,
2409 allow_partial_swap_);
2410 view->opened_by_user_gesture_ = params.user_gesture;
2412 // Record whether the creator frame is trying to suppress the opener field.
2413 view->opener_suppressed_ = params.opener_suppressed;
2415 // Copy over the alternate error page URL so we can have alt error pages in
2416 // the new render view (we don't need the browser to send the URL back down).
2417 view->alternate_error_page_url_ = alternate_error_page_url_;
2419 return view->webview();
2422 WebWidget* RenderViewImpl::createPopupMenu(WebKit::WebPopupType popup_type) {
2423 RenderWidget* widget =
2424 RenderWidget::Create(routing_id_, popup_type, screen_info_);
2425 if (screen_metrics_emulator_) {
2426 widget->SetPopupOriginAdjustmentsForEmulation(
2427 screen_metrics_emulator_.get());
2429 return widget->webwidget();
2432 WebExternalPopupMenu* RenderViewImpl::createExternalPopupMenu(
2433 const WebPopupMenuInfo& popup_menu_info,
2434 WebExternalPopupMenuClient* popup_menu_client) {
2435 // An IPC message is sent to the browser to build and display the actual
2436 // popup. The user could have time to click a different select by the time
2437 // the popup is shown. In that case external_popup_menu_ is non NULL.
2438 // By returning NULL in that case, we instruct WebKit to cancel that new
2439 // popup. So from the user perspective, only the first one will show, and
2440 // will have to close the first one before another one can be shown.
2441 if (external_popup_menu_)
2442 return NULL;
2443 external_popup_menu_.reset(
2444 new ExternalPopupMenu(this, popup_menu_info, popup_menu_client));
2445 if (screen_metrics_emulator_) {
2446 SetExternalPopupOriginAdjustmentsForEmulation(
2447 external_popup_menu_.get(), screen_metrics_emulator_.get());
2449 return external_popup_menu_.get();
2452 WebStorageNamespace* RenderViewImpl::createSessionStorageNamespace() {
2453 CHECK(session_storage_namespace_id_ != kInvalidSessionStorageNamespaceId);
2454 return new WebStorageNamespaceImpl(session_storage_namespace_id_);
2457 bool RenderViewImpl::shouldReportDetailedMessageForSource(
2458 const WebString& source) {
2459 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2460 source);
2463 void RenderViewImpl::didAddMessageToConsole(
2464 const WebConsoleMessage& message, const WebString& source_name,
2465 unsigned source_line, const WebString& stack_trace) {
2466 logging::LogSeverity log_severity = logging::LOG_VERBOSE;
2467 switch (message.level) {
2468 case WebConsoleMessage::LevelDebug:
2469 log_severity = logging::LOG_VERBOSE;
2470 break;
2471 case WebConsoleMessage::LevelLog:
2472 log_severity = logging::LOG_INFO;
2473 break;
2474 case WebConsoleMessage::LevelWarning:
2475 log_severity = logging::LOG_WARNING;
2476 break;
2477 case WebConsoleMessage::LevelError:
2478 log_severity = logging::LOG_ERROR;
2479 break;
2480 default:
2481 NOTREACHED();
2484 if (shouldReportDetailedMessageForSource(source_name)) {
2485 FOR_EACH_OBSERVER(
2486 RenderViewObserver,
2487 observers_,
2488 DetailedConsoleMessageAdded(message.text,
2489 source_name,
2490 stack_trace,
2491 source_line,
2492 static_cast<int32>(log_severity)));
2495 Send(new ViewHostMsg_AddMessageToConsole(routing_id_,
2496 static_cast<int32>(log_severity),
2497 message.text,
2498 static_cast<int32>(source_line),
2499 source_name));
2502 void RenderViewImpl::printPage(WebFrame* frame) {
2503 FOR_EACH_OBSERVER(RenderViewObserver, observers_,
2504 PrintPage(frame, handling_input_event_));
2507 WebKit::WebNotificationPresenter* RenderViewImpl::notificationPresenter() {
2508 return notification_provider_;
2511 bool RenderViewImpl::enumerateChosenDirectory(
2512 const WebString& path,
2513 WebFileChooserCompletion* chooser_completion) {
2514 int id = enumeration_completion_id_++;
2515 enumeration_completions_[id] = chooser_completion;
2516 return Send(new ViewHostMsg_EnumerateDirectory(
2517 routing_id_,
2519 base::FilePath::FromUTF16Unsafe(path)));
2522 void RenderViewImpl::initializeHelperPluginWebFrame(
2523 WebKit::WebHelperPlugin* plugin) {
2524 plugin->initializeFrame(main_render_frame_.get());
2527 void RenderViewImpl::didStartLoading() {
2528 if (is_loading_) {
2529 DVLOG(1) << "didStartLoading called while loading";
2530 return;
2533 is_loading_ = true;
2535 Send(new ViewHostMsg_DidStartLoading(routing_id_));
2537 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStartLoading());
2540 void RenderViewImpl::didStopLoading() {
2541 if (!is_loading_) {
2542 DVLOG(1) << "DidStopLoading called while not loading";
2543 return;
2546 is_loading_ = false;
2548 // NOTE: For now we're doing the safest thing, and sending out notification
2549 // when done loading. This currently isn't an issue as the favicon is only
2550 // displayed when done loading. Ideally we would send notification when
2551 // finished parsing the head, but webkit doesn't support that yet.
2552 // The feed discovery code would also benefit from access to the head.
2553 Send(new ViewHostMsg_DidStopLoading(routing_id_));
2555 if (load_progress_tracker_ != NULL)
2556 load_progress_tracker_->DidStopLoading();
2558 DidStopLoadingIcons();
2560 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStopLoading());
2563 void RenderViewImpl::didChangeLoadProgress(WebFrame* frame,
2564 double load_progress) {
2565 if (load_progress_tracker_ != NULL)
2566 load_progress_tracker_->DidChangeLoadProgress(frame, load_progress);
2569 void RenderViewImpl::didCancelCompositionOnSelectionChange() {
2570 Send(new ViewHostMsg_ImeCancelComposition(routing_id()));
2573 void RenderViewImpl::didChangeSelection(bool is_empty_selection) {
2574 if (!handling_input_event_ && !handling_select_range_)
2575 return;
2577 if (is_empty_selection)
2578 selection_text_.clear();
2580 SyncSelectionIfRequired();
2581 UpdateTextInputType();
2582 #if defined(OS_ANDROID)
2583 UpdateTextInputState(false, true);
2584 #endif
2587 void RenderViewImpl::didExecuteCommand(const WebString& command_name) {
2588 const std::string& name = UTF16ToUTF8(command_name);
2589 if (StartsWithASCII(name, "Move", true) ||
2590 StartsWithASCII(name, "Insert", true) ||
2591 StartsWithASCII(name, "Delete", true))
2592 return;
2593 RenderThreadImpl::current()->RecordUserMetrics(name);
2596 bool RenderViewImpl::handleCurrentKeyboardEvent() {
2597 if (edit_commands_.empty())
2598 return false;
2600 WebFrame* frame = webview()->focusedFrame();
2601 if (!frame)
2602 return false;
2604 EditCommands::iterator it = edit_commands_.begin();
2605 EditCommands::iterator end = edit_commands_.end();
2607 bool did_execute_command = false;
2608 for (; it != end; ++it) {
2609 // In gtk and cocoa, it's possible to bind multiple edit commands to one
2610 // key (but it's the exception). Once one edit command is not executed, it
2611 // seems safest to not execute the rest.
2612 if (!frame->executeCommand(WebString::fromUTF8(it->name),
2613 WebString::fromUTF8(it->value),
2614 GetFocusedNode()))
2615 break;
2616 did_execute_command = true;
2619 return did_execute_command;
2622 WebKit::WebColorChooser* RenderViewImpl::createColorChooser(
2623 WebKit::WebColorChooserClient* client,
2624 const WebKit::WebColor& initial_color) {
2625 RendererWebColorChooserImpl* color_chooser =
2626 new RendererWebColorChooserImpl(this, client);
2627 color_chooser->Open(static_cast<SkColor>(initial_color));
2628 return color_chooser;
2631 bool RenderViewImpl::runFileChooser(
2632 const WebKit::WebFileChooserParams& params,
2633 WebFileChooserCompletion* chooser_completion) {
2634 // Do not open the file dialog in a hidden RenderView.
2635 if (is_hidden())
2636 return false;
2637 FileChooserParams ipc_params;
2638 if (params.directory)
2639 ipc_params.mode = FileChooserParams::UploadFolder;
2640 else if (params.multiSelect)
2641 ipc_params.mode = FileChooserParams::OpenMultiple;
2642 else if (params.saveAs)
2643 ipc_params.mode = FileChooserParams::Save;
2644 else
2645 ipc_params.mode = FileChooserParams::Open;
2646 ipc_params.title = params.title;
2647 ipc_params.default_file_name =
2648 base::FilePath::FromUTF16Unsafe(params.initialValue);
2649 ipc_params.accept_types.reserve(params.acceptTypes.size());
2650 for (size_t i = 0; i < params.acceptTypes.size(); ++i)
2651 ipc_params.accept_types.push_back(params.acceptTypes[i]);
2652 #if defined(OS_ANDROID)
2653 ipc_params.capture = params.useMediaCapture;
2654 #endif
2656 return ScheduleFileChooser(ipc_params, chooser_completion);
2659 void RenderViewImpl::runModalAlertDialog(WebFrame* frame,
2660 const WebString& message) {
2661 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT,
2662 message,
2663 string16(),
2664 frame->document().url(),
2665 NULL);
2668 bool RenderViewImpl::runModalConfirmDialog(WebFrame* frame,
2669 const WebString& message) {
2670 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM,
2671 message,
2672 string16(),
2673 frame->document().url(),
2674 NULL);
2677 bool RenderViewImpl::runModalPromptDialog(WebFrame* frame,
2678 const WebString& message,
2679 const WebString& default_value,
2680 WebString* actual_value) {
2681 string16 result;
2682 bool ok = RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT,
2683 message,
2684 default_value,
2685 frame->document().url(),
2686 &result);
2687 if (ok)
2688 actual_value->assign(result);
2689 return ok;
2692 bool RenderViewImpl::runModalBeforeUnloadDialog(
2693 WebFrame* frame, const WebString& message) {
2694 bool is_reload = false;
2695 WebDataSource* ds = frame->provisionalDataSource();
2696 if (ds)
2697 is_reload = (ds->navigationType() == WebKit::WebNavigationTypeReload);
2698 return runModalBeforeUnloadDialog(frame, is_reload, message);
2701 bool RenderViewImpl::runModalBeforeUnloadDialog(
2702 WebFrame* frame, bool is_reload, const WebString& message) {
2703 // If we are swapping out, we have already run the beforeunload handler.
2704 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
2705 // at all, to avoid running it twice.
2706 if (is_swapped_out_)
2707 return true;
2709 bool success = false;
2710 // This is an ignored return value, but is included so we can accept the same
2711 // response as RunJavaScriptMessage.
2712 string16 ignored_result;
2713 SendAndRunNestedMessageLoop(new ViewHostMsg_RunBeforeUnloadConfirm(
2714 routing_id_, frame->document().url(), message, is_reload,
2715 &success, &ignored_result));
2716 return success;
2719 void RenderViewImpl::showContextMenu(
2720 WebFrame* frame, const WebContextMenuData& data) {
2721 ContextMenuParams params = ContextMenuParamsBuilder::Build(data);
2722 params.source_type = context_menu_source_type_;
2723 if (context_menu_source_type_ == ui::MENU_SOURCE_TOUCH_EDIT_MENU) {
2724 params.x = touch_editing_context_menu_location_.x();
2725 params.y = touch_editing_context_menu_location_.y();
2727 OnShowHostContextMenu(&params);
2729 // Plugins, e.g. PDF, don't currently update the render view when their
2730 // selected text changes, but the context menu params do contain the updated
2731 // selection. If that's the case, update the render view's state just prior
2732 // to showing the context menu.
2733 // TODO(asvitkine): http://crbug.com/152432
2734 if (ShouldUpdateSelectionTextFromContextMenuParams(selection_text_,
2735 selection_text_offset_,
2736 selection_range_,
2737 params)) {
2738 selection_text_ = params.selection_text;
2739 // TODO(asvitkine): Text offset and range is not available in this case.
2740 selection_text_offset_ = 0;
2741 selection_range_ = gfx::Range(0, selection_text_.length());
2742 Send(new ViewHostMsg_SelectionChanged(routing_id_,
2743 selection_text_,
2744 selection_text_offset_,
2745 selection_range_));
2748 // frame is NULL if invoked by BlockedPlugin.
2749 if (frame)
2750 params.frame_id = frame->identifier();
2752 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
2753 // it. We replace it with an empty GURL so the appropriate items are disabled
2754 // in the context menu.
2755 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
2756 // data encoded images. We should have a way to save them.
2757 if (params.src_url.spec().size() > kMaxURLChars)
2758 params.src_url = GURL();
2759 context_menu_node_ = data.node;
2761 #if defined(OS_ANDROID)
2762 gfx::Rect start_rect;
2763 gfx::Rect end_rect;
2764 GetSelectionBounds(&start_rect, &end_rect);
2765 params.selection_start = gfx::Point(start_rect.x(), start_rect.bottom());
2766 params.selection_end = gfx::Point(end_rect.right(), end_rect.bottom());
2767 #endif
2769 Send(new ViewHostMsg_ContextMenu(routing_id_, params));
2771 FOR_EACH_OBSERVER(
2772 RenderViewObserver, observers_, DidRequestShowContextMenu(frame, data));
2775 void RenderViewImpl::clearContextMenu() {
2776 context_menu_node_.reset();
2779 void RenderViewImpl::setStatusText(const WebString& text) {
2782 void RenderViewImpl::UpdateTargetURL(const GURL& url,
2783 const GURL& fallback_url) {
2784 GURL latest_url = url.is_empty() ? fallback_url : url;
2785 if (latest_url == target_url_)
2786 return;
2788 // Tell the browser to display a destination link.
2789 if (target_url_status_ == TARGET_INFLIGHT ||
2790 target_url_status_ == TARGET_PENDING) {
2791 // If we have a request in-flight, save the URL to be sent when we
2792 // receive an ACK to the in-flight request. We can happily overwrite
2793 // any existing pending sends.
2794 pending_target_url_ = latest_url;
2795 target_url_status_ = TARGET_PENDING;
2796 } else {
2797 // URLs larger than |kMaxURLChars| cannot be sent through IPC -
2798 // see |ParamTraits<GURL>|.
2799 if (latest_url.possibly_invalid_spec().size() > kMaxURLChars)
2800 latest_url = GURL();
2801 Send(new ViewHostMsg_UpdateTargetURL(routing_id_, page_id_, latest_url));
2802 target_url_ = latest_url;
2803 target_url_status_ = TARGET_INFLIGHT;
2807 gfx::RectF RenderViewImpl::ClientRectToPhysicalWindowRect(
2808 const gfx::RectF& rect) const {
2809 gfx::RectF window_rect = rect;
2810 window_rect.Scale(device_scale_factor_ * webview()->pageScaleFactor());
2811 return window_rect;
2814 int64 RenderViewImpl::GetLatencyComponentId() {
2815 // Note: this must match the logic in RenderWidgetHostImpl.
2816 return GetRoutingID() | (static_cast<int64>(
2817 RenderThreadImpl::current()->renderer_process_id()) << 32);
2820 void RenderViewImpl::StartNavStateSyncTimerIfNecessary() {
2821 // No need to update state if no page has committed yet.
2822 if (page_id_ == -1)
2823 return;
2825 int delay;
2826 if (send_content_state_immediately_)
2827 delay = 0;
2828 else if (is_hidden())
2829 delay = kDelaySecondsForContentStateSyncHidden;
2830 else
2831 delay = kDelaySecondsForContentStateSync;
2833 if (nav_state_sync_timer_.IsRunning()) {
2834 // The timer is already running. If the delay of the timer maches the amount
2835 // we want to delay by, then return. Otherwise stop the timer so that it
2836 // gets started with the right delay.
2837 if (nav_state_sync_timer_.GetCurrentDelay().InSeconds() == delay)
2838 return;
2839 nav_state_sync_timer_.Stop();
2842 nav_state_sync_timer_.Start(FROM_HERE, TimeDelta::FromSeconds(delay), this,
2843 &RenderViewImpl::SyncNavigationState);
2846 void RenderViewImpl::setMouseOverURL(const WebURL& url) {
2847 mouse_over_url_ = GURL(url);
2848 UpdateTargetURL(mouse_over_url_, focus_url_);
2851 void RenderViewImpl::setKeyboardFocusURL(const WebURL& url) {
2852 focus_url_ = GURL(url);
2853 UpdateTargetURL(focus_url_, mouse_over_url_);
2856 void RenderViewImpl::startDragging(WebFrame* frame,
2857 const WebDragData& data,
2858 WebDragOperationsMask mask,
2859 const WebImage& image,
2860 const WebPoint& webImageOffset) {
2861 DropData drop_data(DropDataBuilder::Build(data));
2862 drop_data.referrer_policy = frame->document().referrerPolicy();
2863 gfx::Vector2d imageOffset(webImageOffset.x, webImageOffset.y);
2864 Send(new DragHostMsg_StartDragging(routing_id_,
2865 drop_data,
2866 mask,
2867 image.getSkBitmap(),
2868 imageOffset,
2869 possible_drag_event_info_));
2872 bool RenderViewImpl::acceptsLoadDrops() {
2873 return renderer_preferences_.can_accept_load_drops;
2876 void RenderViewImpl::focusNext() {
2877 Send(new ViewHostMsg_TakeFocus(routing_id_, false));
2880 void RenderViewImpl::focusPrevious() {
2881 Send(new ViewHostMsg_TakeFocus(routing_id_, true));
2884 void RenderViewImpl::focusedNodeChanged(const WebNode& node) {
2885 Send(new ViewHostMsg_FocusedNodeChanged(routing_id_, IsEditableNode(node)));
2887 FOR_EACH_OBSERVER(RenderViewObserver, observers_, FocusedNodeChanged(node));
2890 void RenderViewImpl::numberOfWheelEventHandlersChanged(unsigned num_handlers) {
2891 Send(new ViewHostMsg_DidChangeNumWheelEvents(routing_id_, num_handlers));
2894 void RenderViewImpl::didUpdateLayout() {
2895 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidUpdateLayout());
2897 // We don't always want to set up a timer, only if we've been put in that
2898 // mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
2899 // message.
2900 if (!send_preferred_size_changes_ || !webview())
2901 return;
2903 if (check_preferred_size_timer_.IsRunning())
2904 return;
2905 check_preferred_size_timer_.Start(FROM_HERE,
2906 TimeDelta::FromMilliseconds(0), this,
2907 &RenderViewImpl::CheckPreferredSize);
2910 void RenderViewImpl::navigateBackForwardSoon(int offset) {
2911 Send(new ViewHostMsg_GoToEntryAtOffset(routing_id_, offset));
2914 int RenderViewImpl::historyBackListCount() {
2915 return history_list_offset_ < 0 ? 0 : history_list_offset_;
2918 int RenderViewImpl::historyForwardListCount() {
2919 return history_list_length_ - historyBackListCount() - 1;
2922 void RenderViewImpl::postAccessibilityEvent(
2923 const WebAXObject& obj, WebKit::WebAXEvent event) {
2924 if (renderer_accessibility_) {
2925 renderer_accessibility_->HandleWebAccessibilityEvent(obj, event);
2929 void RenderViewImpl::didUpdateInspectorSetting(const WebString& key,
2930 const WebString& value) {
2931 Send(new ViewHostMsg_UpdateInspectorSetting(routing_id_,
2932 key.utf8(),
2933 value.utf8()));
2936 // WebKit::WebWidgetClient ----------------------------------------------------
2938 void RenderViewImpl::didFocus() {
2939 // TODO(jcivelli): when https://bugs.webkit.org/show_bug.cgi?id=33389 is fixed
2940 // we won't have to test for user gesture anymore and we can
2941 // move that code back to render_widget.cc
2942 if (WebUserGestureIndicator::isProcessingUserGesture() &&
2943 !RenderThreadImpl::current()->layout_test_mode()) {
2944 Send(new ViewHostMsg_Focus(routing_id_));
2948 void RenderViewImpl::didBlur() {
2949 // TODO(jcivelli): see TODO above in didFocus().
2950 if (WebUserGestureIndicator::isProcessingUserGesture() &&
2951 !RenderThreadImpl::current()->layout_test_mode()) {
2952 Send(new ViewHostMsg_Blur(routing_id_));
2956 // We are supposed to get a single call to Show for a newly created RenderView
2957 // that was created via RenderViewImpl::CreateWebView. So, we wait until this
2958 // point to dispatch the ShowView message.
2960 // This method provides us with the information about how to display the newly
2961 // created RenderView (i.e., as a blocked popup or as a new tab).
2963 void RenderViewImpl::show(WebNavigationPolicy policy) {
2964 if (did_show_) {
2965 // When supports_multiple_windows is disabled, popups are reusing
2966 // the same view. In some scenarios, this makes WebKit to call show() twice.
2967 if (webkit_preferences_.supports_multiple_windows)
2968 NOTREACHED() << "received extraneous Show call";
2969 return;
2971 did_show_ = true;
2973 DCHECK(opener_id_ != MSG_ROUTING_NONE);
2975 // Force new windows to a popup if they were not opened with a user gesture.
2976 if (!opened_by_user_gesture_) {
2977 // We exempt background tabs for compat with older versions of Chrome.
2978 // TODO(darin): This seems bogus. These should have a user gesture, so
2979 // we probably don't need this check.
2980 if (policy != WebKit::WebNavigationPolicyNewBackgroundTab)
2981 policy = WebKit::WebNavigationPolicyNewPopup;
2984 // NOTE: initial_pos_ may still have its default values at this point, but
2985 // that's okay. It'll be ignored if disposition is not NEW_POPUP, or the
2986 // browser process will impose a default position otherwise.
2987 Send(new ViewHostMsg_ShowView(opener_id_, routing_id_,
2988 NavigationPolicyToDisposition(policy), initial_pos_,
2989 opened_by_user_gesture_));
2990 SetPendingWindowRect(initial_pos_);
2993 void RenderViewImpl::runModal() {
2994 DCHECK(did_show_) << "should already have shown the view";
2996 // We must keep WebKit's shared timer running in this case in order to allow
2997 // showModalDialog to function properly.
2999 // TODO(darin): WebKit should really be smarter about suppressing events and
3000 // timers so that we do not need to manage the shared timer in such a heavy
3001 // handed manner.
3003 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
3004 RenderThreadImpl::current()->DoNotSuspendWebKitSharedTimer();
3006 SendAndRunNestedMessageLoop(new ViewHostMsg_RunModal(
3007 routing_id_, opener_id_));
3010 bool RenderViewImpl::enterFullScreen() {
3011 Send(new ViewHostMsg_ToggleFullscreen(routing_id_, true));
3012 return true;
3015 void RenderViewImpl::exitFullScreen() {
3016 Send(new ViewHostMsg_ToggleFullscreen(routing_id_, false));
3019 bool RenderViewImpl::requestPointerLock() {
3020 return mouse_lock_dispatcher_->LockMouse(webwidget_mouse_lock_target_.get());
3023 void RenderViewImpl::requestPointerUnlock() {
3024 mouse_lock_dispatcher_->UnlockMouse(webwidget_mouse_lock_target_.get());
3027 bool RenderViewImpl::isPointerLocked() {
3028 return mouse_lock_dispatcher_->IsMouseLockedTo(
3029 webwidget_mouse_lock_target_.get());
3032 void RenderViewImpl::didActivateCompositor(int input_handler_identifier) {
3033 #if !defined(OS_MACOSX) // many events are unhandled - http://crbug.com/138003
3034 InputHandlerManager* input_handler_manager =
3035 RenderThreadImpl::current()->input_handler_manager();
3036 if (input_handler_manager) {
3037 input_handler_manager->AddInputHandler(
3038 routing_id_,
3039 compositor_->GetInputHandler(),
3040 AsWeakPtr());
3042 #endif
3044 RenderWidget::didActivateCompositor(input_handler_identifier);
3047 void RenderViewImpl::didHandleGestureEvent(
3048 const WebGestureEvent& event,
3049 bool event_cancelled) {
3050 RenderWidget::didHandleGestureEvent(event, event_cancelled);
3051 FOR_EACH_OBSERVER(RenderViewObserver, observers_,
3052 DidHandleGestureEvent(event));
3055 void RenderViewImpl::initializeLayerTreeView() {
3056 RenderWidget::initializeLayerTreeView();
3057 RenderWidgetCompositor* rwc = compositor();
3058 if (!rwc || !webview() || !webview()->devToolsAgent())
3059 return;
3060 webview()->devToolsAgent()->setLayerTreeId(rwc->GetLayerTreeId());
3063 // WebKit::WebFrameClient -----------------------------------------------------
3065 WebMediaPlayer* RenderViewImpl::createMediaPlayer(
3066 WebFrame* frame, const WebKit::WebURL& url, WebMediaPlayerClient* client) {
3067 FOR_EACH_OBSERVER(
3068 RenderViewObserver, observers_, WillCreateMediaPlayer(frame, client));
3070 const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
3071 #if defined(ENABLE_WEBRTC)
3072 if (!InitializeMediaStreamClient())
3073 return NULL;
3075 #if !defined(GOOGLE_TV)
3076 if (media_stream_client_->IsMediaStream(url)) {
3077 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
3078 bool found_neon =
3079 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0;
3080 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon);
3081 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
3082 return new WebMediaPlayerMS(
3083 frame, client, AsWeakPtr(), media_stream_client_, new RenderMediaLog());
3085 #endif // !defined(GOOGLE_TV)
3086 #endif // defined(ENABLE_WEBRTC)
3088 #if defined(OS_ANDROID)
3089 GpuChannelHost* gpu_channel_host =
3090 RenderThreadImpl::current()->EstablishGpuChannelSync(
3091 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE);
3092 if (!gpu_channel_host) {
3093 LOG(ERROR) << "Failed to establish GPU channel for media player";
3094 return NULL;
3097 scoped_ptr<StreamTextureFactory> stream_texture_factory;
3098 if (UsingSynchronousRendererCompositor()) {
3099 SynchronousCompositorFactory* factory =
3100 SynchronousCompositorFactory::GetInstance();
3101 stream_texture_factory = factory->CreateStreamTextureFactory(routing_id_);
3102 } else {
3103 scoped_refptr<cc::ContextProvider> context_provider =
3104 RenderThreadImpl::current()->SharedMainThreadContextProvider();
3106 if (!context_provider.get()) {
3107 LOG(ERROR) << "Failed to get context3d for media player";
3108 return NULL;
3111 stream_texture_factory.reset(new StreamTextureFactoryImpl(
3112 context_provider->Context3d(), gpu_channel_host, routing_id_));
3115 if (!media_player_proxy_) {
3116 media_player_proxy_ = new WebMediaPlayerProxyAndroid(
3117 this, media_player_manager_.get());
3120 scoped_ptr<WebMediaPlayerAndroid> web_media_player_android(
3121 new WebMediaPlayerAndroid(
3122 frame,
3123 client,
3124 AsWeakPtr(),
3125 media_player_manager_.get(),
3126 media_player_proxy_,
3127 stream_texture_factory.release(),
3128 RenderThreadImpl::current()->GetMediaThreadMessageLoopProxy(),
3129 new RenderMediaLog()));
3130 #if defined(ENABLE_WEBRTC) && defined(GOOGLE_TV)
3131 if (media_stream_client_->IsMediaStream(url)) {
3132 RTCVideoDecoderFactoryTv* factory = RenderThreadImpl::current()
3133 ->GetMediaStreamDependencyFactory()->decoder_factory_tv();
3134 // |media_stream_client| and |factory| outlives |web_media_player_android|.
3135 if (!factory->AcquireDemuxer() ||
3136 !web_media_player_android->InjectMediaStream(
3137 media_stream_client_,
3138 factory,
3139 base::Bind(
3140 base::IgnoreResult(&RTCVideoDecoderFactoryTv::ReleaseDemuxer),
3141 base::Unretained(factory)))) {
3142 LOG(ERROR) << "Failed to inject media stream.";
3143 return NULL;
3146 #endif // defined(ENABLE_WEBRTC) && defined(GOOGLE_TV)
3147 return web_media_player_android.release();
3148 #endif // defined(OS_ANDROID)
3150 scoped_refptr<media::AudioRendererSink> sink;
3151 if (!cmd_line->HasSwitch(switches::kDisableAudio)) {
3152 sink = RenderThreadImpl::current()->GetAudioRendererMixerManager()->
3153 CreateInput(routing_id_);
3154 DVLOG(1) << "Using AudioRendererMixerManager-provided sink: " << sink.get();
3157 WebMediaPlayerParams params(
3158 RenderThreadImpl::current()->GetMediaThreadMessageLoopProxy(),
3159 base::Bind(&ContentRendererClient::DeferMediaLoad,
3160 base::Unretained(GetContentClient()->renderer()),
3161 static_cast<RenderView*>(this)),
3162 sink,
3163 RenderThreadImpl::current()->GetGpuFactories(),
3164 new RenderMediaLog());
3165 return new WebMediaPlayerImpl(frame, client, AsWeakPtr(), params);
3168 WebCookieJar* RenderViewImpl::cookieJar(WebFrame* frame) {
3169 return &cookie_jar_;
3172 void RenderViewImpl::didAccessInitialDocument(WebFrame* frame) {
3173 // Notify the browser process that it is no longer safe to show the pending
3174 // URL of the main frame, since a URL spoof is now possible.
3175 if (!frame->parent() && page_id_ == -1)
3176 Send(new ViewHostMsg_DidAccessInitialDocument(routing_id_));
3179 void RenderViewImpl::didDisownOpener(WebKit::WebFrame* frame) {
3180 // We only need to notify the browser if the active, top-level frame clears
3181 // its opener. We can ignore cases where a swapped out frame clears its
3182 // opener after hearing about it from the browser, and the browser does not
3183 // (yet) care about subframe openers.
3184 if (is_swapped_out_ || frame->parent())
3185 return;
3187 // Notify WebContents and all its swapped out RenderViews.
3188 Send(new ViewHostMsg_DidDisownOpener(routing_id_));
3191 void RenderViewImpl::frameDetached(WebFrame* frame) {
3192 FOR_EACH_OBSERVER(RenderViewObserver, observers_, FrameDetached(frame));
3195 void RenderViewImpl::willClose(WebFrame* frame) {
3196 FOR_EACH_OBSERVER(RenderViewObserver, observers_, FrameWillClose(frame));
3199 void RenderViewImpl::didMatchCSS(
3200 WebFrame* frame,
3201 const WebVector<WebString>& newly_matching_selectors,
3202 const WebVector<WebString>& stopped_matching_selectors) {
3203 FOR_EACH_OBSERVER(
3204 RenderViewObserver, observers_,
3205 DidMatchCSS(frame, newly_matching_selectors, stopped_matching_selectors));
3208 void RenderViewImpl::Repaint(const gfx::Size& size) {
3209 OnRepaint(size);
3212 void RenderViewImpl::SetEditCommandForNextKeyEvent(const std::string& name,
3213 const std::string& value) {
3214 EditCommands edit_commands;
3215 edit_commands.push_back(EditCommand(name, value));
3216 OnSetEditCommandsForNextKeyEvent(edit_commands);
3219 void RenderViewImpl::ClearEditCommands() {
3220 edit_commands_.clear();
3223 SSLStatus RenderViewImpl::GetSSLStatusOfFrame(WebKit::WebFrame* frame) const {
3224 std::string security_info;
3225 if (frame && frame->dataSource())
3226 security_info = frame->dataSource()->response().securityInfo();
3228 SSLStatus ssl_status;
3229 DeserializeSecurityInfo(security_info,
3230 &ssl_status.cert_id,
3231 &ssl_status.cert_status,
3232 &ssl_status.security_bits,
3233 &ssl_status.connection_status);
3234 return ssl_status;
3237 const std::string& RenderViewImpl::GetAcceptLanguages() const {
3238 return renderer_preferences_.accept_languages;
3241 WebNavigationPolicy RenderViewImpl::decidePolicyForNavigation(
3242 WebFrame* frame, WebDataSource::ExtraData* extraData,
3243 const WebURLRequest& request, WebNavigationType type,
3244 WebNavigationPolicy default_policy, bool is_redirect) {
3245 if (request.url() != GURL(kSwappedOutURL) &&
3246 GetContentClient()->renderer()->HandleNavigation(frame, request, type,
3247 default_policy,
3248 is_redirect)) {
3249 return WebKit::WebNavigationPolicyIgnore;
3252 Referrer referrer(GetReferrerFromRequest(frame, request));
3254 if (is_swapped_out_) {
3255 if (request.url() != GURL(kSwappedOutURL)) {
3256 // Targeted links may try to navigate a swapped out frame. Allow the
3257 // browser process to navigate the tab instead. Note that it is also
3258 // possible for non-targeted navigations (from this view) to arrive
3259 // here just after we are swapped out. It's ok to send them to the
3260 // browser, as long as they're for the top level frame.
3261 // TODO(creis): Ensure this supports targeted form submissions when
3262 // fixing http://crbug.com/101395.
3263 if (frame->parent() == NULL) {
3264 OpenURL(frame, request.url(), referrer, default_policy);
3265 return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
3268 // We should otherwise ignore in-process iframe navigations, if they
3269 // arrive just after we are swapped out.
3270 return WebKit::WebNavigationPolicyIgnore;
3273 // Allow kSwappedOutURL to complete.
3274 return default_policy;
3277 // Webkit is asking whether to navigate to a new URL.
3278 // This is fine normally, except if we're showing UI from one security
3279 // context and they're trying to navigate to a different context.
3280 const GURL& url = request.url();
3282 // A content initiated navigation may have originated from a link-click,
3283 // script, drag-n-drop operation, etc.
3284 bool is_content_initiated = static_cast<DocumentState*>(extraData)->
3285 navigation_state()->is_content_initiated();
3287 // Experimental:
3288 // If --enable-strict-site-isolation or --site-per-process is enabled, send
3289 // all top-level navigations to the browser to let it swap processes when
3290 // crossing site boundaries. This is currently expected to break some script
3291 // calls and navigations, such as form submissions.
3292 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
3293 bool force_swap_due_to_flag =
3294 command_line.HasSwitch(switches::kEnableStrictSiteIsolation) ||
3295 command_line.HasSwitch(switches::kSitePerProcess);
3296 if (force_swap_due_to_flag &&
3297 !frame->parent() && (is_content_initiated || is_redirect)) {
3298 WebString origin_str = frame->document().securityOrigin().toString();
3299 GURL frame_url(origin_str.utf8().data());
3300 // TODO(cevans): revisit whether this site check is still necessary once
3301 // crbug.com/101395 is fixed.
3302 bool same_domain_or_host =
3303 net::registry_controlled_domains::SameDomainOrHost(
3304 frame_url,
3305 url,
3306 net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES);
3307 if (!same_domain_or_host || frame_url.scheme() != url.scheme()) {
3308 OpenURL(frame, url, referrer, default_policy);
3309 return WebKit::WebNavigationPolicyIgnore;
3313 // If the browser is interested, then give it a chance to look at the request.
3314 if (is_content_initiated) {
3315 bool is_form_post = ((type == WebKit::WebNavigationTypeFormSubmitted) ||
3316 (type == WebKit::WebNavigationTypeFormResubmitted)) &&
3317 EqualsASCII(request.httpMethod(), "POST");
3318 bool browser_handles_request =
3319 renderer_preferences_.browser_handles_non_local_top_level_requests &&
3320 IsNonLocalTopLevelNavigation(url, frame, type, is_form_post);
3321 if (!browser_handles_request) {
3322 browser_handles_request =
3323 renderer_preferences_.browser_handles_all_top_level_requests &&
3324 IsTopLevelNavigation(frame);
3327 if (browser_handles_request) {
3328 // Reset these counters as the RenderView could be reused for the next
3329 // navigation.
3330 page_id_ = -1;
3331 last_page_id_sent_to_browser_ = -1;
3332 OpenURL(frame, url, referrer, default_policy);
3333 return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
3337 // Use the frame's original request's URL rather than the document's URL for
3338 // subsequent checks. For a popup, the document's URL may become the opener
3339 // window's URL if the opener has called document.write().
3340 // See http://crbug.com/93517.
3341 GURL old_url(frame->dataSource()->request().url());
3343 // Detect when we're crossing a permission-based boundary (e.g. into or out of
3344 // an extension or app origin, leaving a WebUI page, etc). We only care about
3345 // top-level navigations (not iframes). But we sometimes navigate to
3346 // about:blank to clear a tab, and we want to still allow that.
3348 // Note: this is known to break POST submissions when crossing process
3349 // boundaries until http://crbug.com/101395 is fixed. This is better for
3350 // security than loading a WebUI, extension or app page in the wrong process.
3351 // POST requests don't work because this mechanism does not preserve form
3352 // POST data. We will need to send the request's httpBody data up to the
3353 // browser process, and issue a special POST navigation in WebKit (via
3354 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
3355 // for examples of how to send the httpBody data.
3356 if (!frame->parent() && is_content_initiated &&
3357 !url.SchemeIs(chrome::kAboutScheme)) {
3358 bool send_referrer = false;
3360 // All navigations to or from WebUI URLs or within WebUI-enabled
3361 // RenderProcesses must be handled by the browser process so that the
3362 // correct bindings and data sources can be registered.
3363 // Similarly, navigations to view-source URLs or within ViewSource mode
3364 // must be handled by the browser process (except for reloads - those are
3365 // safe to leave within the renderer).
3366 // Lastly, access to file:// URLs from non-file:// URL pages must be
3367 // handled by the browser so that ordinary renderer processes don't get
3368 // blessed with file permissions.
3369 int cumulative_bindings = RenderProcess::current()->GetEnabledBindings();
3370 bool is_initial_navigation = page_id_ == -1;
3371 bool should_fork = HasWebUIScheme(url) || HasWebUIScheme(old_url) ||
3372 (cumulative_bindings & BINDINGS_POLICY_WEB_UI) ||
3373 url.SchemeIs(kViewSourceScheme) ||
3374 (frame->isViewSourceModeEnabled() &&
3375 type != WebKit::WebNavigationTypeReload);
3377 if (!should_fork && url.SchemeIs(chrome::kFileScheme)) {
3378 // Fork non-file to file opens. Check the opener URL if this is the
3379 // initial navigation in a newly opened window.
3380 GURL source_url(old_url);
3381 if (is_initial_navigation && source_url.is_empty() && frame->opener())
3382 source_url = frame->opener()->top()->document().url();
3383 DCHECK(!source_url.is_empty());
3384 should_fork = !source_url.SchemeIs(chrome::kFileScheme);
3387 if (!should_fork) {
3388 // Give the embedder a chance.
3389 should_fork = GetContentClient()->renderer()->ShouldFork(
3390 frame, url, request.httpMethod().utf8(), is_initial_navigation,
3391 is_redirect, &send_referrer);
3394 if (should_fork) {
3395 OpenURL(
3396 frame, url, send_referrer ? referrer : Referrer(), default_policy);
3397 return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
3401 // Detect when a page is "forking" a new tab that can be safely rendered in
3402 // its own process. This is done by sites like Gmail that try to open links
3403 // in new windows without script connections back to the original page. We
3404 // treat such cases as browser navigations (in which we will create a new
3405 // renderer for a cross-site navigation), rather than WebKit navigations.
3407 // We use the following heuristic to decide whether to fork a new page in its
3408 // own process:
3409 // The parent page must open a new tab to about:blank, set the new tab's
3410 // window.opener to null, and then redirect the tab to a cross-site URL using
3411 // JavaScript.
3413 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
3414 // (see below).
3415 bool is_fork =
3416 // Must start from a tab showing about:blank, which is later redirected.
3417 old_url == GURL(kAboutBlankURL) &&
3418 // Must be the first real navigation of the tab.
3419 historyBackListCount() < 1 &&
3420 historyForwardListCount() < 1 &&
3421 // The parent page must have set the child's window.opener to null before
3422 // redirecting to the desired URL.
3423 frame->opener() == NULL &&
3424 // Must be a top-level frame.
3425 frame->parent() == NULL &&
3426 // Must not have issued the request from this page.
3427 is_content_initiated &&
3428 // Must be targeted at the current tab.
3429 default_policy == WebKit::WebNavigationPolicyCurrentTab &&
3430 // Must be a JavaScript navigation, which appears as "other".
3431 type == WebKit::WebNavigationTypeOther;
3433 if (is_fork) {
3434 // Open the URL via the browser, not via WebKit.
3435 OpenURL(frame, url, Referrer(), default_policy);
3436 return WebKit::WebNavigationPolicyIgnore;
3439 return default_policy;
3442 WebNavigationPolicy RenderViewImpl::decidePolicyForNavigation(
3443 WebFrame* frame, const WebURLRequest& request, WebNavigationType type,
3444 WebNavigationPolicy default_policy, bool is_redirect) {
3445 return decidePolicyForNavigation(frame,
3446 frame->provisionalDataSource()->extraData(),
3447 request, type, default_policy, is_redirect);
3450 void RenderViewImpl::willSendSubmitEvent(WebKit::WebFrame* frame,
3451 const WebKit::WebFormElement& form) {
3452 FOR_EACH_OBSERVER(
3453 RenderViewObserver, observers_, WillSendSubmitEvent(frame, form));
3456 void RenderViewImpl::willSubmitForm(WebFrame* frame,
3457 const WebFormElement& form) {
3458 FOR_EACH_OBSERVER(
3459 RenderViewObserver, observers_, WillSubmitForm(frame, form));
3462 void RenderViewImpl::didCreateDataSource(WebFrame* frame, WebDataSource* ds) {
3463 bool content_initiated = !pending_navigation_params_.get();
3465 DocumentState* document_state = DocumentState::FromDataSource(ds);
3466 if (!document_state) {
3467 document_state = new DocumentState;
3468 ds->setExtraData(document_state);
3469 if (!content_initiated)
3470 PopulateDocumentStateFromPending(document_state);
3473 // Carry over the user agent override flag, if it exists.
3474 if (content_initiated && webview() && webview()->mainFrame() &&
3475 webview()->mainFrame()->dataSource()) {
3476 DocumentState* old_document_state =
3477 DocumentState::FromDataSource(webview()->mainFrame()->dataSource());
3478 if (old_document_state) {
3479 InternalDocumentStateData* internal_data =
3480 InternalDocumentStateData::FromDocumentState(document_state);
3481 InternalDocumentStateData* old_internal_data =
3482 InternalDocumentStateData::FromDocumentState(old_document_state);
3483 internal_data->set_is_overriding_user_agent(
3484 old_internal_data->is_overriding_user_agent());
3488 // The rest of RenderView assumes that a WebDataSource will always have a
3489 // non-null NavigationState.
3490 if (content_initiated) {
3491 document_state->set_navigation_state(
3492 NavigationState::CreateContentInitiated());
3493 } else {
3494 document_state->set_navigation_state(CreateNavigationStateFromPending());
3495 pending_navigation_params_.reset();
3498 // DocumentState::referred_by_prefetcher_ is true if we are
3499 // navigating from a page that used prefetching using a link on that
3500 // page. We are early enough in the request process here that we
3501 // can still see the DocumentState of the previous page and set
3502 // this value appropriately.
3503 // TODO(gavinp): catch the important case of navigation in a new
3504 // renderer process.
3505 if (webview()) {
3506 if (WebFrame* old_frame = webview()->mainFrame()) {
3507 const WebURLRequest& original_request = ds->originalRequest();
3508 const GURL referrer(
3509 original_request.httpHeaderField(WebString::fromUTF8("Referer")));
3510 if (!referrer.is_empty() &&
3511 DocumentState::FromDataSource(
3512 old_frame->dataSource())->was_prefetcher()) {
3513 for (; old_frame; old_frame = old_frame->traverseNext(false)) {
3514 WebDataSource* old_frame_ds = old_frame->dataSource();
3515 if (old_frame_ds && referrer == GURL(old_frame_ds->request().url())) {
3516 document_state->set_was_referred_by_prefetcher(true);
3517 break;
3524 if (content_initiated) {
3525 const WebURLRequest& request = ds->request();
3526 switch (request.cachePolicy()) {
3527 case WebURLRequest::UseProtocolCachePolicy: // normal load.
3528 document_state->set_load_type(DocumentState::LINK_LOAD_NORMAL);
3529 break;
3530 case WebURLRequest::ReloadIgnoringCacheData: // reload.
3531 document_state->set_load_type(DocumentState::LINK_LOAD_RELOAD);
3532 break;
3533 case WebURLRequest::ReturnCacheDataElseLoad: // allow stale data.
3534 document_state->set_load_type(
3535 DocumentState::LINK_LOAD_CACHE_STALE_OK);
3536 break;
3537 case WebURLRequest::ReturnCacheDataDontLoad: // Don't re-post.
3538 document_state->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY);
3539 break;
3543 FOR_EACH_OBSERVER(
3544 RenderViewObserver, observers_, DidCreateDataSource(frame, ds));
3547 void RenderViewImpl::PopulateDocumentStateFromPending(
3548 DocumentState* document_state) {
3549 const ViewMsg_Navigate_Params& params = *pending_navigation_params_.get();
3550 document_state->set_request_time(params.request_time);
3552 InternalDocumentStateData* internal_data =
3553 InternalDocumentStateData::FromDocumentState(document_state);
3555 if (!params.url.SchemeIs(kJavaScriptScheme) &&
3556 params.navigation_type == ViewMsg_Navigate_Type::RESTORE) {
3557 // We're doing a load of a page that was restored from the last session. By
3558 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
3559 // can result in stale data for pages that are set to expire. We explicitly
3560 // override that by setting the policy here so that as necessary we load
3561 // from the network.
3562 internal_data->set_cache_policy_override(
3563 WebURLRequest::UseProtocolCachePolicy);
3566 if (IsReload(params))
3567 document_state->set_load_type(DocumentState::RELOAD);
3568 else if (params.page_state.IsValid())
3569 document_state->set_load_type(DocumentState::HISTORY_LOAD);
3570 else
3571 document_state->set_load_type(DocumentState::NORMAL_LOAD);
3573 internal_data->set_referrer_policy(params.referrer.policy);
3574 internal_data->set_is_overriding_user_agent(params.is_overriding_user_agent);
3575 internal_data->set_must_reset_scroll_and_scale_state(
3576 params.navigation_type ==
3577 ViewMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
3578 document_state->set_can_load_local_resources(params.can_load_local_resources);
3581 NavigationState* RenderViewImpl::CreateNavigationStateFromPending() {
3582 const ViewMsg_Navigate_Params& params = *pending_navigation_params_.get();
3583 NavigationState* navigation_state = NULL;
3585 // A navigation resulting from loading a javascript URL should not be treated
3586 // as a browser initiated event. Instead, we want it to look as if the page
3587 // initiated any load resulting from JS execution.
3588 if (!params.url.SchemeIs(kJavaScriptScheme)) {
3589 navigation_state = NavigationState::CreateBrowserInitiated(
3590 params.page_id,
3591 params.pending_history_list_offset,
3592 params.should_clear_history_list,
3593 params.transition);
3594 navigation_state->set_transferred_request_child_id(
3595 params.transferred_request_child_id);
3596 navigation_state->set_transferred_request_request_id(
3597 params.transferred_request_request_id);
3598 navigation_state->set_allow_download(params.allow_download);
3599 navigation_state->set_extra_headers(params.extra_headers);
3600 } else {
3601 navigation_state = NavigationState::CreateContentInitiated();
3603 return navigation_state;
3606 void RenderViewImpl::ProcessViewLayoutFlags(const CommandLine& command_line) {
3607 bool enable_viewport =
3608 command_line.HasSwitch(switches::kEnableViewport);
3609 bool enable_fixed_layout =
3610 command_line.HasSwitch(switches::kEnableFixedLayout);
3612 webview()->enableFixedLayoutMode(enable_fixed_layout || enable_viewport);
3614 // If viewport tag is enabled, then the WebKit side will take care
3615 // of setting the fixed layout size and page scale limits.
3616 if (enable_viewport)
3617 return;
3619 // When navigating to a new page, reset the page scale factor to be 1.0.
3620 webview()->setInitialPageScaleOverride(1.f);
3622 if (enable_fixed_layout) {
3623 std::string str =
3624 command_line.GetSwitchValueASCII(switches::kEnableFixedLayout);
3625 std::vector<std::string> tokens;
3626 base::SplitString(str, ',', &tokens);
3627 if (tokens.size() == 2) {
3628 int width, height;
3629 if (base::StringToInt(tokens[0], &width) &&
3630 base::StringToInt(tokens[1], &height))
3631 webview()->setFixedLayoutSize(WebSize(width, height));
3634 float maxPageScaleFactor =
3635 command_line.HasSwitch(switches::kEnablePinch) ? 4.f : 1.f ;
3636 webview()->setPageScaleFactorLimits(1, maxPageScaleFactor);
3639 // TODO(nasko): Remove this method once WebTestProxy in Blink is fixed.
3640 void RenderViewImpl::didStartProvisionalLoad(WebFrame* frame) {
3643 void RenderViewImpl::didReceiveServerRedirectForProvisionalLoad(
3644 WebFrame* frame) {
3645 if (frame->parent())
3646 return;
3647 // Received a redirect on the main frame.
3648 WebDataSource* data_source = frame->provisionalDataSource();
3649 if (!data_source) {
3650 // Should only be invoked when we have a data source.
3651 NOTREACHED();
3652 return;
3654 std::vector<GURL> redirects;
3655 GetRedirectChain(data_source, &redirects);
3656 if (redirects.size() >= 2) {
3657 Send(new ViewHostMsg_DidRedirectProvisionalLoad(routing_id_, page_id_,
3658 redirects[redirects.size() - 2], redirects.back()));
3662 void RenderViewImpl::didFailProvisionalLoad(WebFrame* frame,
3663 const WebURLError& error) {
3664 // Notify the browser that we failed a provisional load with an error.
3666 // Note: It is important this notification occur before DidStopLoading so the
3667 // SSL manager can react to the provisional load failure before being
3668 // notified the load stopped.
3670 WebDataSource* ds = frame->provisionalDataSource();
3671 DCHECK(ds);
3673 const WebURLRequest& failed_request = ds->request();
3675 FOR_EACH_OBSERVER(
3676 RenderViewObserver, observers_, DidFailProvisionalLoad(frame, error));
3678 bool show_repost_interstitial =
3679 (error.reason == net::ERR_CACHE_MISS &&
3680 EqualsASCII(failed_request.httpMethod(), "POST"));
3682 ViewHostMsg_DidFailProvisionalLoadWithError_Params params;
3683 params.frame_id = frame->identifier();
3684 params.frame_unique_name = frame->uniqueName();
3685 params.is_main_frame = !frame->parent();
3686 params.error_code = error.reason;
3687 GetContentClient()->renderer()->GetNavigationErrorStrings(
3688 frame,
3689 failed_request,
3690 error,
3691 renderer_preferences_.accept_languages,
3692 NULL,
3693 &params.error_description);
3694 params.url = error.unreachableURL;
3695 params.showing_repost_interstitial = show_repost_interstitial;
3696 Send(new ViewHostMsg_DidFailProvisionalLoadWithError(
3697 routing_id_, params));
3699 // Don't display an error page if this is simply a cancelled load. Aside
3700 // from being dumb, WebCore doesn't expect it and it will cause a crash.
3701 if (error.reason == net::ERR_ABORTED)
3702 return;
3704 // Don't display "client blocked" error page if browser has asked us not to.
3705 if (error.reason == net::ERR_BLOCKED_BY_CLIENT &&
3706 renderer_preferences_.disable_client_blocked_error_page) {
3707 return;
3710 // Allow the embedder to suppress an error page.
3711 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(
3712 error.unreachableURL)) {
3713 return;
3716 if (RenderThreadImpl::current() &&
3717 RenderThreadImpl::current()->layout_test_mode()) {
3718 return;
3721 // Make sure we never show errors in view source mode.
3722 frame->enableViewSourceMode(false);
3724 DocumentState* document_state = DocumentState::FromDataSource(ds);
3725 NavigationState* navigation_state = document_state->navigation_state();
3727 // If this is a failed back/forward/reload navigation, then we need to do a
3728 // 'replace' load. This is necessary to avoid messing up session history.
3729 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
3730 // as session history is concerned.
3732 // AUTO_SUBFRAME loads should always be treated as loads that do not advance
3733 // the page id.
3735 bool replace =
3736 navigation_state->pending_page_id() != -1 ||
3737 PageTransitionCoreTypeIs(navigation_state->transition_type(),
3738 PAGE_TRANSITION_AUTO_SUBFRAME);
3740 // If we failed on a browser initiated request, then make sure that our error
3741 // page load is regarded as the same browser initiated request.
3742 if (!navigation_state->is_content_initiated()) {
3743 pending_navigation_params_.reset(new ViewMsg_Navigate_Params);
3744 pending_navigation_params_->page_id =
3745 navigation_state->pending_page_id();
3746 pending_navigation_params_->pending_history_list_offset =
3747 navigation_state->pending_history_list_offset();
3748 pending_navigation_params_->should_clear_history_list =
3749 navigation_state->history_list_was_cleared();
3750 pending_navigation_params_->transition =
3751 navigation_state->transition_type();
3752 pending_navigation_params_->request_time =
3753 document_state->request_time();
3756 // Provide the user with a more helpful error page?
3757 if (MaybeLoadAlternateErrorPage(frame, error, replace))
3758 return;
3760 // Fallback to a local error page.
3761 LoadNavigationErrorPage(frame, failed_request, error, std::string(), replace);
3764 void RenderViewImpl::didCommitProvisionalLoad(WebFrame* frame,
3765 bool is_new_navigation) {
3766 DocumentState* document_state =
3767 DocumentState::FromDataSource(frame->dataSource());
3768 NavigationState* navigation_state = document_state->navigation_state();
3769 InternalDocumentStateData* internal_data =
3770 InternalDocumentStateData::FromDocumentState(document_state);
3772 if (document_state->commit_load_time().is_null())
3773 document_state->set_commit_load_time(Time::Now());
3775 if (internal_data->must_reset_scroll_and_scale_state()) {
3776 webview()->resetScrollAndScaleState();
3777 internal_data->set_must_reset_scroll_and_scale_state(false);
3779 internal_data->set_use_error_page(false);
3781 if (is_new_navigation) {
3782 // When we perform a new navigation, we need to update the last committed
3783 // session history entry with state for the page we are leaving.
3784 UpdateSessionHistory(frame);
3786 // We bump our Page ID to correspond with the new session history entry.
3787 page_id_ = next_page_id_++;
3789 // Don't update history_page_ids_ (etc) for kSwappedOutURL, since
3790 // we don't want to forget the entry that was there, and since we will
3791 // never come back to kSwappedOutURL. Note that we have to call
3792 // UpdateSessionHistory and update page_id_ even in this case, so that
3793 // the current entry gets a state update and so that we don't send a
3794 // state update to the wrong entry when we swap back in.
3795 if (GetLoadingUrl(frame) != GURL(kSwappedOutURL)) {
3796 // Advance our offset in session history, applying the length limit.
3797 // There is now no forward history.
3798 history_list_offset_++;
3799 if (history_list_offset_ >= kMaxSessionHistoryEntries)
3800 history_list_offset_ = kMaxSessionHistoryEntries - 1;
3801 history_list_length_ = history_list_offset_ + 1;
3802 history_page_ids_.resize(history_list_length_, -1);
3803 history_page_ids_[history_list_offset_] = page_id_;
3805 } else {
3806 // Inspect the navigation_state on this frame to see if the navigation
3807 // corresponds to a session history navigation... Note: |frame| may or
3808 // may not be the toplevel frame, but for the case of capturing session
3809 // history, the first committed frame suffices. We keep track of whether
3810 // we've seen this commit before so that only capture session history once
3811 // per navigation.
3813 // Note that we need to check if the page ID changed. In the case of a
3814 // reload, the page ID doesn't change, and UpdateSessionHistory gets the
3815 // previous URL and the current page ID, which would be wrong.
3816 if (navigation_state->pending_page_id() != -1 &&
3817 navigation_state->pending_page_id() != page_id_ &&
3818 !navigation_state->request_committed()) {
3819 // This is a successful session history navigation!
3820 UpdateSessionHistory(frame);
3821 page_id_ = navigation_state->pending_page_id();
3823 history_list_offset_ = navigation_state->pending_history_list_offset();
3825 // If the history list is valid, our list of page IDs should be correct.
3826 DCHECK(history_list_length_ <= 0 ||
3827 history_list_offset_ < 0 ||
3828 history_list_offset_ >= history_list_length_ ||
3829 history_page_ids_[history_list_offset_] == page_id_);
3833 FOR_EACH_OBSERVER(RenderViewObserver, observers_,
3834 DidCommitProvisionalLoad(frame, is_new_navigation));
3836 // Remember that we've already processed this request, so we don't update
3837 // the session history again. We do this regardless of whether this is
3838 // a session history navigation, because if we attempted a session history
3839 // navigation without valid HistoryItem state, WebCore will think it is a
3840 // new navigation.
3841 navigation_state->set_request_committed(true);
3843 UpdateURL(frame);
3845 // Check whether we have new encoding name.
3846 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
3848 if (!frame->parent()) { // Only for top frames.
3849 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
3850 if (render_thread_impl) { // Can be NULL in tests.
3851 render_thread_impl->histogram_customizer()->
3852 RenderViewNavigatedToHost(GURL(GetLoadingUrl(frame)).host(),
3853 g_view_map.Get().size());
3858 void RenderViewImpl::didClearWindowObject(WebFrame* frame) {
3859 FOR_EACH_OBSERVER(RenderViewObserver, observers_,
3860 DidClearWindowObject(frame));
3862 if (enabled_bindings_ & BINDINGS_POLICY_DOM_AUTOMATION) {
3863 if (!dom_automation_controller_)
3864 dom_automation_controller_.reset(new DomAutomationController());
3865 dom_automation_controller_->set_message_sender(
3866 static_cast<RenderView*>(this));
3867 dom_automation_controller_->set_routing_id(routing_id());
3868 dom_automation_controller_->BindToJavascript(frame,
3869 "domAutomationController");
3872 if (enabled_bindings_ & BINDINGS_POLICY_STATS_COLLECTION) {
3873 if (!stats_collection_controller_.get())
3874 stats_collection_controller_.reset(new StatsCollectionController());
3875 stats_collection_controller_->set_message_sender(
3876 static_cast<RenderView*>(this));
3877 stats_collection_controller_->BindToJavascript(frame,
3878 "statsCollectionController");
3882 void RenderViewImpl::didCreateDocumentElement(WebFrame* frame) {
3883 FOR_EACH_OBSERVER(RenderViewObserver, observers_,
3884 DidCreateDocumentElement(frame));
3887 void RenderViewImpl::didReceiveTitle(WebFrame* frame, const WebString& title,
3888 WebTextDirection direction) {
3889 UpdateTitle(frame, title, direction);
3891 // Also check whether we have new encoding name.
3892 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
3895 void RenderViewImpl::didChangeIcon(WebFrame* frame,
3896 WebIconURL::Type icon_type) {
3897 if (frame->parent())
3898 return;
3900 if (!TouchEnabled() && icon_type != WebIconURL::TypeFavicon)
3901 return;
3903 WebVector<WebIconURL> icon_urls = frame->iconURLs(icon_type);
3904 std::vector<FaviconURL> urls;
3905 for (size_t i = 0; i < icon_urls.size(); i++) {
3906 urls.push_back(FaviconURL(icon_urls[i].iconURL(),
3907 ToFaviconType(icon_urls[i].iconType())));
3909 SendUpdateFaviconURL(urls);
3912 void RenderViewImpl::didFinishDocumentLoad(WebFrame* frame) {
3913 WebDataSource* ds = frame->dataSource();
3914 DocumentState* document_state = DocumentState::FromDataSource(ds);
3915 document_state->set_finish_document_load_time(Time::Now());
3917 Send(new ViewHostMsg_DocumentLoadedInFrame(routing_id_, frame->identifier()));
3919 FOR_EACH_OBSERVER(RenderViewObserver, observers_,
3920 DidFinishDocumentLoad(frame));
3922 // Check whether we have new encoding name.
3923 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
3926 void RenderViewImpl::didHandleOnloadEvents(WebFrame* frame) {
3927 if (webview()->mainFrame() == frame) {
3928 Send(new ViewHostMsg_DocumentOnLoadCompletedInMainFrame(routing_id_,
3929 page_id_));
3933 void RenderViewImpl::didFailLoad(WebFrame* frame, const WebURLError& error) {
3934 WebDataSource* ds = frame->dataSource();
3935 DCHECK(ds);
3938 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidFailLoad(frame, error));
3940 const WebURLRequest& failed_request = ds->request();
3941 string16 error_description;
3942 GetContentClient()->renderer()->GetNavigationErrorStrings(
3943 frame,
3944 failed_request,
3945 error,
3946 renderer_preferences_.accept_languages,
3947 NULL,
3948 &error_description);
3949 Send(new ViewHostMsg_DidFailLoadWithError(routing_id_,
3950 frame->identifier(),
3951 failed_request.url(),
3952 !frame->parent(),
3953 error.reason,
3954 error_description));
3957 void RenderViewImpl::didFinishLoad(WebFrame* frame) {
3958 WebDataSource* ds = frame->dataSource();
3959 DocumentState* document_state = DocumentState::FromDataSource(ds);
3960 if (document_state->finish_load_time().is_null()) {
3961 if (!frame->parent()) {
3962 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
3963 TRACE_EVENT_SCOPE_PROCESS);
3965 document_state->set_finish_load_time(Time::Now());
3968 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidFinishLoad(frame));
3970 Send(new ViewHostMsg_DidFinishLoad(routing_id_,
3971 frame->identifier(),
3972 ds->request().url(),
3973 !frame->parent()));
3976 void RenderViewImpl::didNavigateWithinPage(
3977 WebFrame* frame, bool is_new_navigation) {
3978 // If this was a reference fragment navigation that we initiated, then we
3979 // could end up having a non-null pending navigation params. We just need to
3980 // update the ExtraData on the datasource so that others who read the
3981 // ExtraData will get the new NavigationState. Similarly, if we did not
3982 // initiate this navigation, then we need to take care to reset any pre-
3983 // existing navigation state to a content-initiated navigation state.
3984 // DidCreateDataSource conveniently takes care of this for us.
3985 didCreateDataSource(frame, frame->dataSource());
3987 DocumentState* document_state =
3988 DocumentState::FromDataSource(frame->dataSource());
3989 NavigationState* new_state = document_state->navigation_state();
3990 new_state->set_was_within_same_page(true);
3992 didCommitProvisionalLoad(frame, is_new_navigation);
3995 void RenderViewImpl::didUpdateCurrentHistoryItem(WebFrame* frame) {
3996 StartNavStateSyncTimerIfNecessary();
3999 void RenderViewImpl::willSendRequest(WebFrame* frame,
4000 unsigned identifier,
4001 WebURLRequest& request,
4002 const WebURLResponse& redirect_response) {
4003 NOTREACHED();
4006 void RenderViewImpl::didReceiveResponse(
4007 WebFrame* frame, unsigned identifier, const WebURLResponse& response) {
4008 NOTREACHED();
4011 void RenderViewImpl::didFinishResourceLoad(
4012 WebFrame* frame, unsigned identifier) {
4013 InternalDocumentStateData* internal_data =
4014 InternalDocumentStateData::FromDataSource(frame->dataSource());
4015 if (!internal_data->use_error_page())
4016 return;
4018 // Do not show error page when DevTools is attached.
4019 if (devtools_agent_->IsAttached())
4020 return;
4022 // Display error page, if appropriate.
4023 int http_status_code = internal_data->http_status_code();
4024 if (http_status_code == 404) {
4025 // On 404s, try a remote search page as a fallback.
4026 const GURL& document_url = frame->document().url();
4028 const GURL& error_page_url =
4029 GetAlternateErrorPageURL(document_url, HTTP_404);
4030 if (error_page_url.is_valid()) {
4031 WebURLError original_error;
4032 original_error.domain = "http";
4033 original_error.reason = 404;
4034 original_error.unreachableURL = document_url;
4036 internal_data->set_alt_error_page_fetcher(
4037 new AltErrorPageResourceFetcher(
4038 error_page_url, frame, frame->dataSource()->request(),
4039 original_error,
4040 base::Bind(&RenderViewImpl::AltErrorPageFinished,
4041 base::Unretained(this))));
4042 return;
4046 std::string error_domain;
4047 if (GetContentClient()->renderer()->HasErrorPage(
4048 http_status_code, &error_domain)) {
4049 WebURLError error;
4050 error.unreachableURL = frame->document().url();
4051 error.domain = WebString::fromUTF8(error_domain);
4052 error.reason = http_status_code;
4054 LoadNavigationErrorPage(
4055 frame, frame->dataSource()->request(), error, std::string(), true);
4059 void RenderViewImpl::didLoadResourceFromMemoryCache(
4060 WebFrame* frame, const WebURLRequest& request,
4061 const WebURLResponse& response) {
4062 NOTREACHED();
4065 void RenderViewImpl::didDisplayInsecureContent(WebFrame* frame) {
4066 NOTREACHED();
4069 void RenderViewImpl::didRunInsecureContent(
4070 WebFrame* frame, const WebSecurityOrigin& origin, const WebURL& target) {
4071 NOTREACHED();
4074 void RenderViewImpl::didExhaustMemoryAvailableForScript(WebFrame* frame) {
4075 NOTREACHED();
4078 void RenderViewImpl::didCreateScriptContext(WebFrame* frame,
4079 v8::Handle<v8::Context> context,
4080 int extension_group,
4081 int world_id) {
4082 NOTREACHED();
4085 void RenderViewImpl::willReleaseScriptContext(WebFrame* frame,
4086 v8::Handle<v8::Context> context,
4087 int world_id) {
4088 NOTREACHED();
4091 void RenderViewImpl::CheckPreferredSize() {
4092 // We don't always want to send the change messages over IPC, only if we've
4093 // been put in that mode by getting a |ViewMsg_EnablePreferredSizeChangedMode|
4094 // message.
4095 if (!send_preferred_size_changes_ || !webview())
4096 return;
4098 gfx::Size size = webview()->contentsPreferredMinimumSize();
4100 // In the presence of zoom, these sizes are still reported as if unzoomed,
4101 // so we need to adjust.
4102 double zoom_factor = ZoomLevelToZoomFactor(webview()->zoomLevel());
4103 size.set_width(static_cast<int>(size.width() * zoom_factor));
4104 size.set_height(static_cast<int>(size.height() * zoom_factor));
4106 if (size == preferred_size_)
4107 return;
4109 preferred_size_ = size;
4110 Send(new ViewHostMsg_DidContentsPreferredSizeChange(routing_id_,
4111 preferred_size_));
4114 BrowserPluginManager* RenderViewImpl::GetBrowserPluginManager() {
4115 if (!browser_plugin_manager_.get())
4116 browser_plugin_manager_ = BrowserPluginManager::Create(this);
4117 return browser_plugin_manager_.get();
4120 bool RenderViewImpl::InitializeMediaStreamClient() {
4121 if (media_stream_client_)
4122 return true;
4124 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4125 return false;
4127 #if defined(OS_ANDROID)
4128 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableWebRTC))
4129 return false;
4130 #endif
4132 #if defined(ENABLE_WEBRTC)
4133 if (!media_stream_dispatcher_)
4134 media_stream_dispatcher_ = new MediaStreamDispatcher(this);
4136 MediaStreamImpl* media_stream_impl = new MediaStreamImpl(
4137 this,
4138 media_stream_dispatcher_,
4139 RenderThreadImpl::current()->GetMediaStreamDependencyFactory());
4140 media_stream_client_ = media_stream_impl;
4141 web_user_media_client_ = media_stream_impl;
4142 return true;
4143 #else
4144 return false;
4145 #endif
4148 void RenderViewImpl::didChangeContentsSize(WebFrame* frame,
4149 const WebSize& size) {
4150 if (webview()->mainFrame() != frame)
4151 return;
4152 WebView* frameView = frame->view();
4153 if (!frameView)
4154 return;
4156 bool has_horizontal_scrollbar = frame->hasHorizontalScrollbar();
4157 bool has_vertical_scrollbar = frame->hasVerticalScrollbar();
4159 if (has_horizontal_scrollbar != cached_has_main_frame_horizontal_scrollbar_ ||
4160 has_vertical_scrollbar != cached_has_main_frame_vertical_scrollbar_) {
4161 Send(new ViewHostMsg_DidChangeScrollbarsForMainFrame(
4162 routing_id_, has_horizontal_scrollbar, has_vertical_scrollbar));
4164 cached_has_main_frame_horizontal_scrollbar_ = has_horizontal_scrollbar;
4165 cached_has_main_frame_vertical_scrollbar_ = has_vertical_scrollbar;
4169 void RenderViewImpl::UpdateScrollState(WebFrame* frame) {
4170 WebSize offset = frame->scrollOffset();
4171 WebSize minimum_offset = frame->minimumScrollOffset();
4172 WebSize maximum_offset = frame->maximumScrollOffset();
4174 bool is_pinned_to_left = offset.width <= minimum_offset.width;
4175 bool is_pinned_to_right = offset.width >= maximum_offset.width;
4177 if (is_pinned_to_left != cached_is_main_frame_pinned_to_left_ ||
4178 is_pinned_to_right != cached_is_main_frame_pinned_to_right_) {
4179 Send(new ViewHostMsg_DidChangeScrollOffsetPinningForMainFrame(
4180 routing_id_, is_pinned_to_left, is_pinned_to_right));
4182 cached_is_main_frame_pinned_to_left_ = is_pinned_to_left;
4183 cached_is_main_frame_pinned_to_right_ = is_pinned_to_right;
4186 Send(new ViewHostMsg_DidChangeScrollOffset(routing_id_));
4189 void RenderViewImpl::didChangeScrollOffset(WebFrame* frame) {
4190 StartNavStateSyncTimerIfNecessary();
4192 if (webview()->mainFrame() == frame)
4193 UpdateScrollState(frame);
4195 FOR_EACH_OBSERVER(
4196 RenderViewObserver, observers_, DidChangeScrollOffset(frame));
4199 void RenderViewImpl::willInsertBody(WebKit::WebFrame* frame) {
4200 NOTREACHED();
4203 void RenderViewImpl::didFirstVisuallyNonEmptyLayout(WebFrame* frame) {
4204 if (frame != webview()->mainFrame())
4205 return;
4207 InternalDocumentStateData* data =
4208 InternalDocumentStateData::FromDataSource(frame->dataSource());
4209 data->set_did_first_visually_non_empty_layout(true);
4211 #if defined(OS_ANDROID)
4212 // Update body background color if necessary.
4213 SkColor bg_color = webwidget_->backgroundColor();
4215 // If not initialized, default to white. Note that 0 is different from black
4216 // as black still has alpha 0xFF.
4217 if (!bg_color)
4218 bg_color = SK_ColorWHITE;
4220 if (bg_color != body_background_color_) {
4221 body_background_color_ = bg_color;
4222 Send(new ViewHostMsg_DidChangeBodyBackgroundColor(
4223 GetRoutingID(), bg_color));
4225 #endif
4228 void RenderViewImpl::SendFindReply(int request_id,
4229 int match_count,
4230 int ordinal,
4231 const WebRect& selection_rect,
4232 bool final_status_update) {
4233 Send(new ViewHostMsg_Find_Reply(routing_id_,
4234 request_id,
4235 match_count,
4236 selection_rect,
4237 ordinal,
4238 final_status_update));
4241 // static
4242 bool RenderViewImpl::ShouldUpdateSelectionTextFromContextMenuParams(
4243 const string16& selection_text,
4244 size_t selection_text_offset,
4245 const gfx::Range& selection_range,
4246 const ContextMenuParams& params) {
4247 string16 trimmed_selection_text;
4248 if (!selection_text.empty() && !selection_range.is_empty()) {
4249 const int start = selection_range.GetMin() - selection_text_offset;
4250 const size_t length = selection_range.length();
4251 if (start >= 0 && start + length <= selection_text.length()) {
4252 TrimWhitespace(selection_text.substr(start, length), TRIM_ALL,
4253 &trimmed_selection_text);
4256 string16 trimmed_params_text;
4257 TrimWhitespace(params.selection_text, TRIM_ALL, &trimmed_params_text);
4258 return trimmed_params_text != trimmed_selection_text;
4261 void RenderViewImpl::reportFindInPageMatchCount(int request_id,
4262 int count,
4263 bool final_update) {
4264 // TODO(jam): switch PepperPluginInstanceImpl to take a RenderFrame
4265 main_render_frame_->reportFindInPageMatchCount(
4266 request_id, count, final_update);
4269 void RenderViewImpl::reportFindInPageSelection(int request_id,
4270 int active_match_ordinal,
4271 const WebRect& selection_rect) {
4272 // TODO(jam): switch PepperPluginInstanceImpl to take a RenderFrame
4273 main_render_frame_->reportFindInPageSelection(
4274 request_id, active_match_ordinal, selection_rect);
4277 void RenderViewImpl::requestStorageQuota(
4278 WebFrame* frame,
4279 WebStorageQuotaType type,
4280 unsigned long long requested_size,
4281 WebStorageQuotaCallbacks* callbacks) {
4282 NOTREACHED();
4285 bool RenderViewImpl::willCheckAndDispatchMessageEvent(
4286 WebKit::WebFrame* sourceFrame,
4287 WebKit::WebFrame* targetFrame,
4288 WebKit::WebSecurityOrigin target_origin,
4289 WebKit::WebDOMMessageEvent event) {
4290 if (!is_swapped_out_)
4291 return false;
4293 ViewMsg_PostMessage_Params params;
4294 params.data = event.data().toString();
4295 params.source_origin = event.origin();
4296 if (!target_origin.isNull())
4297 params.target_origin = target_origin.toString();
4299 WebKit::WebMessagePortChannelArray channels = event.releaseChannels();
4300 if (!channels.isEmpty()) {
4301 std::vector<int> message_port_ids(channels.size());
4302 // Extract the port IDs from the channel array.
4303 for (size_t i = 0; i < channels.size(); ++i) {
4304 WebMessagePortChannelImpl* webchannel =
4305 static_cast<WebMessagePortChannelImpl*>(channels[i]);
4306 message_port_ids[i] = webchannel->message_port_id();
4307 webchannel->QueueMessages();
4308 DCHECK_NE(message_port_ids[i], MSG_ROUTING_NONE);
4310 params.message_port_ids = message_port_ids;
4313 // Include the routing ID for the source frame, which the browser process
4314 // will translate into the routing ID for the equivalent frame in the target
4315 // process.
4316 params.source_routing_id = MSG_ROUTING_NONE;
4317 RenderViewImpl* source_view = FromWebView(sourceFrame->view());
4318 if (source_view)
4319 params.source_routing_id = source_view->routing_id();
4321 Send(new ViewHostMsg_RouteMessageEvent(routing_id_, params));
4322 return true;
4325 void RenderViewImpl::willOpenSocketStream(
4326 WebSocketStreamHandle* handle) {
4327 NOTREACHED();
4330 void RenderViewImpl::willStartUsingPeerConnectionHandler(
4331 WebKit::WebFrame* frame, WebKit::WebRTCPeerConnectionHandler* handler) {
4332 NOTREACHED();
4335 WebKit::WebString RenderViewImpl::acceptLanguages() {
4336 return WebString::fromUTF8(renderer_preferences_.accept_languages);
4339 WebKit::WebString RenderViewImpl::userAgentOverride(
4340 WebKit::WebFrame* frame,
4341 const WebKit::WebURL& url) {
4342 NOTREACHED();
4343 return WebKit::WebString();
4346 WebString RenderViewImpl::doNotTrackValue(WebFrame* frame) {
4347 NOTREACHED();
4348 return WebKit::WebString();
4351 bool RenderViewImpl::allowWebGL(WebFrame* frame, bool default_value) {
4352 NOTREACHED();
4353 return false;
4356 void RenderViewImpl::didLoseWebGLContext(
4357 WebKit::WebFrame* frame,
4358 int arb_robustness_status_code) {
4359 NOTREACHED();
4362 // WebKit::WebPageSerializerClient implementation ------------------------------
4364 void RenderViewImpl::didSerializeDataForFrame(
4365 const WebURL& frame_url,
4366 const WebCString& data,
4367 WebPageSerializerClient::PageSerializationStatus status) {
4368 Send(new ViewHostMsg_SendSerializedHtmlData(
4369 routing_id(),
4370 frame_url,
4371 data.data(),
4372 static_cast<int32>(status)));
4375 // RenderView implementation ---------------------------------------------------
4377 bool RenderViewImpl::Send(IPC::Message* message) {
4378 return RenderWidget::Send(message);
4381 int RenderViewImpl::GetRoutingID() const {
4382 return routing_id_;
4385 int RenderViewImpl::GetPageId() const {
4386 return page_id_;
4389 gfx::Size RenderViewImpl::GetSize() const {
4390 return size();
4393 WebPreferences& RenderViewImpl::GetWebkitPreferences() {
4394 return webkit_preferences_;
4397 void RenderViewImpl::SetWebkitPreferences(const WebPreferences& preferences) {
4398 OnUpdateWebPreferences(preferences);
4401 WebKit::WebView* RenderViewImpl::GetWebView() {
4402 return webview();
4405 WebKit::WebNode RenderViewImpl::GetFocusedNode() const {
4406 if (!webview())
4407 return WebNode();
4408 WebFrame* focused_frame = webview()->focusedFrame();
4409 if (focused_frame) {
4410 WebDocument doc = focused_frame->document();
4411 if (!doc.isNull())
4412 return doc.focusedNode();
4415 return WebNode();
4418 WebKit::WebNode RenderViewImpl::GetContextMenuNode() const {
4419 return context_menu_node_;
4422 bool RenderViewImpl::IsEditableNode(const WebNode& node) const {
4423 if (node.isNull())
4424 return false;
4426 if (node.isContentEditable())
4427 return true;
4429 if (node.isElementNode()) {
4430 const WebElement& element = node.toConst<WebElement>();
4431 if (element.isTextFormControlElement())
4432 return true;
4434 // Also return true if it has an ARIA role of 'textbox'.
4435 for (unsigned i = 0; i < element.attributeCount(); ++i) {
4436 if (LowerCaseEqualsASCII(element.attributeLocalName(i), "role")) {
4437 if (LowerCaseEqualsASCII(element.attributeValue(i), "textbox"))
4438 return true;
4439 break;
4444 return false;
4447 WebKit::WebPlugin* RenderViewImpl::CreatePlugin(
4448 WebKit::WebFrame* frame,
4449 const WebPluginInfo& info,
4450 const WebKit::WebPluginParams& params) {
4451 #if defined(ENABLE_PLUGINS)
4452 bool pepper_plugin_was_registered = false;
4453 scoped_refptr<PluginModule> pepper_module(PluginModule::Create(
4454 this, info, &pepper_plugin_was_registered));
4455 if (pepper_plugin_was_registered) {
4456 if (pepper_module.get())
4457 return new PepperWebPluginImpl(pepper_module.get(), params, AsWeakPtr());
4460 return new WebPluginImpl(frame, params, info.path, AsWeakPtr());
4461 #else
4462 return NULL;
4463 #endif
4466 void RenderViewImpl::EvaluateScript(const string16& frame_xpath,
4467 const string16& jscript,
4468 int id,
4469 bool notify_result) {
4470 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
4471 v8::Handle<v8::Value> result;
4472 WebFrame* web_frame = GetChildFrame(frame_xpath);
4473 if (web_frame)
4474 result = web_frame->executeScriptAndReturnValue(WebScriptSource(jscript));
4475 if (notify_result) {
4476 base::ListValue list;
4477 if (!result.IsEmpty() && web_frame) {
4478 v8::Local<v8::Context> context = web_frame->mainWorldScriptContext();
4479 v8::Context::Scope context_scope(context);
4480 V8ValueConverterImpl converter;
4481 converter.SetDateAllowed(true);
4482 converter.SetRegExpAllowed(true);
4483 base::Value* result_value = converter.FromV8Value(result, context);
4484 list.Set(0, result_value ? result_value : base::Value::CreateNullValue());
4485 } else {
4486 list.Set(0, base::Value::CreateNullValue());
4488 Send(new ViewHostMsg_ScriptEvalResponse(routing_id_, id, list));
4492 bool RenderViewImpl::ShouldDisplayScrollbars(int width, int height) const {
4493 return (!send_preferred_size_changes_ ||
4494 (disable_scrollbars_size_limit_.width() <= width ||
4495 disable_scrollbars_size_limit_.height() <= height));
4498 int RenderViewImpl::GetEnabledBindings() const {
4499 return enabled_bindings_;
4502 bool RenderViewImpl::GetContentStateImmediately() const {
4503 return send_content_state_immediately_;
4506 float RenderViewImpl::GetFilteredTimePerFrame() const {
4507 return filtered_time_per_frame();
4510 int RenderViewImpl::ShowContextMenu(ContextMenuClient* client,
4511 const ContextMenuParams& params) {
4512 DCHECK(client); // A null client means "internal" when we issue callbacks.
4513 ContextMenuParams our_params(params);
4514 our_params.custom_context.request_id = pending_context_menus_.Add(client);
4515 Send(new ViewHostMsg_ContextMenu(routing_id_, our_params));
4516 return our_params.custom_context.request_id;
4519 void RenderViewImpl::CancelContextMenu(int request_id) {
4520 DCHECK(pending_context_menus_.Lookup(request_id));
4521 pending_context_menus_.Remove(request_id);
4524 WebKit::WebPageVisibilityState RenderViewImpl::GetVisibilityState() const {
4525 return visibilityState();
4528 void RenderViewImpl::RunModalAlertDialog(WebKit::WebFrame* frame,
4529 const WebKit::WebString& message) {
4530 return runModalAlertDialog(frame, message);
4533 void RenderViewImpl::LoadURLExternally(
4534 WebKit::WebFrame* frame,
4535 const WebKit::WebURLRequest& request,
4536 WebKit::WebNavigationPolicy policy) {
4537 main_render_frame_->loadURLExternally(frame, request, policy);
4540 void RenderViewImpl::DidStartLoading() {
4541 didStartLoading();
4544 void RenderViewImpl::DidStopLoading() {
4545 didStopLoading();
4548 void RenderViewImpl::DidPlay(WebKit::WebMediaPlayer* player) {
4549 Send(new ViewHostMsg_MediaNotification(routing_id_,
4550 reinterpret_cast<int64>(player),
4551 player->hasVideo(),
4552 player->hasAudio(),
4553 true));
4556 void RenderViewImpl::DidPause(WebKit::WebMediaPlayer* player) {
4557 Send(new ViewHostMsg_MediaNotification(routing_id_,
4558 reinterpret_cast<int64>(player),
4559 player->hasVideo(),
4560 player->hasAudio(),
4561 false));
4564 void RenderViewImpl::PlayerGone(WebKit::WebMediaPlayer* player) {
4565 DidPause(player);
4568 void RenderViewImpl::SyncNavigationState() {
4569 if (!webview())
4570 return;
4572 const WebHistoryItem& item = webview()->mainFrame()->currentHistoryItem();
4573 SendUpdateState(item);
4576 void RenderViewImpl::SyncSelectionIfRequired() {
4577 WebFrame* frame = webview()->focusedFrame();
4578 if (!frame)
4579 return;
4581 string16 text;
4582 size_t offset;
4583 gfx::Range range;
4584 #if defined(ENABLE_PLUGINS)
4585 if (focused_pepper_plugin_) {
4586 focused_pepper_plugin_->GetSurroundingText(&text, &range);
4587 offset = 0; // Pepper API does not support offset reporting.
4588 // TODO(kinaba): cut as needed.
4589 } else
4590 #endif
4592 size_t location, length;
4593 if (!webview()->caretOrSelectionRange(&location, &length))
4594 return;
4596 range = gfx::Range(location, location + length);
4598 if (webview()->textInputInfo().type != WebKit::WebTextInputTypeNone) {
4599 // If current focused element is editable, we will send 100 more chars
4600 // before and after selection. It is for input method surrounding text
4601 // feature.
4602 if (location > kExtraCharsBeforeAndAfterSelection)
4603 offset = location - kExtraCharsBeforeAndAfterSelection;
4604 else
4605 offset = 0;
4606 length = location + length - offset + kExtraCharsBeforeAndAfterSelection;
4607 WebRange webrange = WebRange::fromDocumentRange(frame, offset, length);
4608 if (!webrange.isNull())
4609 text = WebRange::fromDocumentRange(frame, offset, length).toPlainText();
4610 } else {
4611 offset = location;
4612 text = frame->selectionAsText();
4613 // http://crbug.com/101435
4614 // In some case, frame->selectionAsText() returned text's length is not
4615 // equal to the length returned from webview()->caretOrSelectionRange().
4616 // So we have to set the range according to text.length().
4617 range.set_end(range.start() + text.length());
4621 // Sometimes we get repeated didChangeSelection calls from webkit when
4622 // the selection hasn't actually changed. We don't want to report these
4623 // because it will cause us to continually claim the X clipboard.
4624 if (selection_text_offset_ != offset ||
4625 selection_range_ != range ||
4626 selection_text_ != text) {
4627 selection_text_ = text;
4628 selection_text_offset_ = offset;
4629 selection_range_ = range;
4630 Send(new ViewHostMsg_SelectionChanged(routing_id_, text, offset, range));
4632 UpdateSelectionBounds();
4635 GURL RenderViewImpl::GetAlternateErrorPageURL(const GURL& failed_url,
4636 ErrorPageType error_type) {
4637 if (failed_url.SchemeIsSecure()) {
4638 // If the URL that failed was secure, then the embedding web page was not
4639 // expecting a network attacker to be able to manipulate its contents. As
4640 // we fetch alternate error pages over HTTP, we would be allowing a network
4641 // attacker to manipulate the contents of the response if we tried to use
4642 // the link doctor here.
4643 return GURL();
4646 // Grab the base URL from the browser process.
4647 if (!alternate_error_page_url_.is_valid())
4648 return GURL();
4650 // Strip query params from the failed URL.
4651 GURL::Replacements remove_params;
4652 remove_params.ClearUsername();
4653 remove_params.ClearPassword();
4654 remove_params.ClearQuery();
4655 remove_params.ClearRef();
4656 const GURL url_to_send = failed_url.ReplaceComponents(remove_params);
4657 // TODO(yuusuke): change to net::FormatUrl when link doctor
4658 // becomes unicode-capable.
4659 std::string spec_to_send = url_to_send.spec();
4660 // Notify link doctor of the url truncation by sending of "?" at the end.
4661 if (failed_url.has_query())
4662 spec_to_send.append("?");
4664 // Construct the query params to send to link doctor.
4665 std::string params(alternate_error_page_url_.query());
4666 params.append("&url=");
4667 params.append(net::EscapeQueryParamValue(spec_to_send, true));
4668 params.append("&sourceid=chrome");
4669 params.append("&error=");
4670 switch (error_type) {
4671 case DNS_ERROR:
4672 params.append("dnserror");
4673 break;
4675 case HTTP_404:
4676 params.append("http404");
4677 break;
4679 case CONNECTION_ERROR:
4680 params.append("connectionfailure");
4681 break;
4683 default:
4684 NOTREACHED() << "unknown ErrorPageType";
4687 // OK, build the final url to return.
4688 GURL::Replacements link_doctor_params;
4689 link_doctor_params.SetQueryStr(params);
4690 GURL url = alternate_error_page_url_.ReplaceComponents(link_doctor_params);
4691 return url;
4694 GURL RenderViewImpl::GetLoadingUrl(WebKit::WebFrame* frame) const {
4695 WebDataSource* ds = frame->dataSource();
4696 if (ds->hasUnreachableURL())
4697 return ds->unreachableURL();
4699 const WebURLRequest& request = ds->request();
4700 return request.url();
4703 WebKit::WebPlugin* RenderViewImpl::GetWebPluginFromPluginDocument() {
4704 return webview()->mainFrame()->document().to<WebPluginDocument>().plugin();
4707 void RenderViewImpl::OnFind(int request_id,
4708 const string16& search_text,
4709 const WebFindOptions& options) {
4710 WebFrame* main_frame = webview()->mainFrame();
4712 // Check if the plugin still exists in the document.
4713 if (main_frame->document().isPluginDocument() &&
4714 GetWebPluginFromPluginDocument()) {
4715 if (options.findNext) {
4716 // Just navigate back/forward.
4717 GetWebPluginFromPluginDocument()->selectFindResult(options.forward);
4718 } else {
4719 if (!GetWebPluginFromPluginDocument()->startFind(
4720 search_text, options.matchCase, request_id)) {
4721 // Send "no results".
4722 SendFindReply(request_id, 0, 0, gfx::Rect(), true);
4725 return;
4728 WebFrame* frame_after_main = main_frame->traverseNext(true);
4729 WebFrame* focused_frame = webview()->focusedFrame();
4730 WebFrame* search_frame = focused_frame; // start searching focused frame.
4732 bool multi_frame = (frame_after_main != main_frame);
4734 // If we have multiple frames, we don't want to wrap the search within the
4735 // frame, so we check here if we only have main_frame in the chain.
4736 bool wrap_within_frame = !multi_frame;
4738 WebRect selection_rect;
4739 bool result = false;
4741 // If something is selected when we start searching it means we cannot just
4742 // increment the current match ordinal; we need to re-generate it.
4743 WebRange current_selection = focused_frame->selectionRange();
4745 do {
4746 result = search_frame->find(
4747 request_id, search_text, options, wrap_within_frame, &selection_rect);
4749 if (!result) {
4750 // don't leave text selected as you move to the next frame.
4751 search_frame->executeCommand(WebString::fromUTF8("Unselect"),
4752 GetFocusedNode());
4754 // Find the next frame, but skip the invisible ones.
4755 do {
4756 // What is the next frame to search? (we might be going backwards). Note
4757 // that we specify wrap=true so that search_frame never becomes NULL.
4758 search_frame = options.forward ?
4759 search_frame->traverseNext(true) :
4760 search_frame->traversePrevious(true);
4761 } while (!search_frame->hasVisibleContent() &&
4762 search_frame != focused_frame);
4764 // Make sure selection doesn't affect the search operation in new frame.
4765 search_frame->executeCommand(WebString::fromUTF8("Unselect"),
4766 GetFocusedNode());
4768 // If we have multiple frames and we have wrapped back around to the
4769 // focused frame, we need to search it once more allowing wrap within
4770 // the frame, otherwise it will report 'no match' if the focused frame has
4771 // reported matches, but no frames after the focused_frame contain a
4772 // match for the search word(s).
4773 if (multi_frame && search_frame == focused_frame) {
4774 result = search_frame->find(
4775 request_id, search_text, options, true, // Force wrapping.
4776 &selection_rect);
4780 webview()->setFocusedFrame(search_frame);
4781 } while (!result && search_frame != focused_frame);
4783 if (options.findNext && current_selection.isNull()) {
4784 // Force the main_frame to report the actual count.
4785 main_frame->increaseMatchCount(0, request_id);
4786 } else {
4787 // If nothing is found, set result to "0 of 0", otherwise, set it to
4788 // "-1 of 1" to indicate that we found at least one item, but we don't know
4789 // yet what is active.
4790 int ordinal = result ? -1 : 0; // -1 here means, we might know more later.
4791 int match_count = result ? 1 : 0; // 1 here means possibly more coming.
4793 // If we find no matches then this will be our last status update.
4794 // Otherwise the scoping effort will send more results.
4795 bool final_status_update = !result;
4797 SendFindReply(request_id, match_count, ordinal, selection_rect,
4798 final_status_update);
4800 // Scoping effort begins, starting with the mainframe.
4801 search_frame = main_frame;
4803 main_frame->resetMatchCount();
4805 do {
4806 // Cancel all old scoping requests before starting a new one.
4807 search_frame->cancelPendingScopingEffort();
4809 // We don't start another scoping effort unless at least one match has
4810 // been found.
4811 if (result) {
4812 // Start new scoping request. If the scoping function determines that it
4813 // needs to scope, it will defer until later.
4814 search_frame->scopeStringMatches(request_id,
4815 search_text,
4816 options,
4817 true); // reset the tickmarks
4820 // Iterate to the next frame. The frame will not necessarily scope, for
4821 // example if it is not visible.
4822 search_frame = search_frame->traverseNext(true);
4823 } while (search_frame != main_frame);
4827 void RenderViewImpl::OnStopFinding(StopFindAction action) {
4828 WebView* view = webview();
4829 if (!view)
4830 return;
4832 WebDocument doc = view->mainFrame()->document();
4833 if (doc.isPluginDocument() && GetWebPluginFromPluginDocument()) {
4834 GetWebPluginFromPluginDocument()->stopFind();
4835 return;
4838 bool clear_selection = action == STOP_FIND_ACTION_CLEAR_SELECTION;
4839 if (clear_selection) {
4840 view->focusedFrame()->executeCommand(WebString::fromUTF8("Unselect"),
4841 GetFocusedNode());
4844 WebFrame* frame = view->mainFrame();
4845 while (frame) {
4846 frame->stopFinding(clear_selection);
4847 frame = frame->traverseNext(false);
4850 if (action == STOP_FIND_ACTION_ACTIVATE_SELECTION) {
4851 WebFrame* focused_frame = view->focusedFrame();
4852 if (focused_frame) {
4853 WebDocument doc = focused_frame->document();
4854 if (!doc.isNull()) {
4855 WebNode node = doc.focusedNode();
4856 if (!node.isNull())
4857 node.simulateClick();
4863 #if defined(OS_ANDROID)
4864 void RenderViewImpl::OnActivateNearestFindResult(int request_id,
4865 float x, float y) {
4866 if (!webview())
4867 return;
4869 WebFrame* main_frame = webview()->mainFrame();
4870 WebRect selection_rect;
4871 int ordinal = main_frame->selectNearestFindMatch(WebFloatPoint(x, y),
4872 &selection_rect);
4873 if (ordinal == -1) {
4874 // Something went wrong, so send a no-op reply (force the main_frame to
4875 // report the current match count) in case the host is waiting for a
4876 // response due to rate-limiting).
4877 main_frame->increaseMatchCount(0, request_id);
4878 return;
4881 SendFindReply(request_id,
4882 -1 /* number_of_matches */,
4883 ordinal,
4884 selection_rect,
4885 true /* final_update */);
4888 void RenderViewImpl::OnFindMatchRects(int current_version) {
4889 if (!webview())
4890 return;
4892 WebFrame* main_frame = webview()->mainFrame();
4893 std::vector<gfx::RectF> match_rects;
4895 int rects_version = main_frame->findMatchMarkersVersion();
4896 if (current_version != rects_version) {
4897 WebVector<WebFloatRect> web_match_rects;
4898 main_frame->findMatchRects(web_match_rects);
4899 match_rects.reserve(web_match_rects.size());
4900 for (size_t i = 0; i < web_match_rects.size(); ++i)
4901 match_rects.push_back(gfx::RectF(web_match_rects[i]));
4904 gfx::RectF active_rect = main_frame->activeFindMatchRect();
4905 Send(new ViewHostMsg_FindMatchRects_Reply(routing_id_,
4906 rects_version,
4907 match_rects,
4908 active_rect));
4910 #endif
4912 void RenderViewImpl::OnZoom(PageZoom zoom) {
4913 if (!webview()) // Not sure if this can happen, but no harm in being safe.
4914 return;
4916 webview()->hidePopups();
4918 double old_zoom_level = webview()->zoomLevel();
4919 double zoom_level;
4920 if (zoom == PAGE_ZOOM_RESET) {
4921 zoom_level = 0;
4922 } else if (static_cast<int>(old_zoom_level) == old_zoom_level) {
4923 // Previous zoom level is a whole number, so just increment/decrement.
4924 zoom_level = old_zoom_level + zoom;
4925 } else {
4926 // Either the user hit the zoom factor limit and thus the zoom level is now
4927 // not a whole number, or a plugin changed it to a custom value. We want
4928 // to go to the next whole number so that the user can always get back to
4929 // 100% with the keyboard/menu.
4930 if ((old_zoom_level > 1 && zoom > 0) ||
4931 (old_zoom_level < 1 && zoom < 0)) {
4932 zoom_level = static_cast<int>(old_zoom_level + zoom);
4933 } else {
4934 // We're going towards 100%, so first go to the next whole number.
4935 zoom_level = static_cast<int>(old_zoom_level);
4938 webview()->setZoomLevel(zoom_level);
4939 zoomLevelChanged();
4942 void RenderViewImpl::OnZoomFactor(PageZoom zoom, int zoom_center_x,
4943 int zoom_center_y) {
4944 ZoomFactorHelper(zoom, zoom_center_x, zoom_center_y,
4945 kScalingIncrementForGesture);
4948 void RenderViewImpl::ZoomFactorHelper(PageZoom zoom,
4949 int zoom_center_x,
4950 int zoom_center_y,
4951 float scaling_increment) {
4952 if (!webview()) // Not sure if this can happen, but no harm in being safe.
4953 return;
4955 double old_page_scale_factor = webview()->pageScaleFactor();
4956 double page_scale_factor;
4957 if (zoom == PAGE_ZOOM_RESET) {
4958 page_scale_factor = 1.0;
4959 } else {
4960 page_scale_factor = old_page_scale_factor +
4961 (zoom > 0 ? scaling_increment : -scaling_increment);
4963 if (page_scale_factor > 0) {
4964 webview()->setPageScaleFactor(page_scale_factor,
4965 WebPoint(zoom_center_x, zoom_center_y));
4969 void RenderViewImpl::OnSetZoomLevel(double zoom_level) {
4970 webview()->hidePopups();
4971 webview()->setZoomLevel(zoom_level);
4972 zoomLevelChanged();
4975 void RenderViewImpl::OnSetZoomLevelForLoadingURL(const GURL& url,
4976 double zoom_level) {
4977 #if !defined(OS_ANDROID)
4978 // On Android, page zoom isn't used, and in case of WebView, text zoom is used
4979 // for legacy WebView text scaling emulation. Thus, the code that resets
4980 // the zoom level from this map will be effectively resetting text zoom level.
4981 host_zoom_levels_[url] = zoom_level;
4982 #endif
4985 void RenderViewImpl::OnSetPageEncoding(const std::string& encoding_name) {
4986 webview()->setPageEncoding(WebString::fromUTF8(encoding_name));
4989 void RenderViewImpl::OnResetPageEncodingToDefault() {
4990 WebString no_encoding;
4991 webview()->setPageEncoding(no_encoding);
4994 WebFrame* RenderViewImpl::GetChildFrame(const string16& xpath) const {
4995 if (xpath.empty())
4996 return webview()->mainFrame();
4998 // xpath string can represent a frame deep down the tree (across multiple
4999 // frame DOMs).
5000 // Example, /html/body/table/tbody/tr/td/iframe\n/frameset/frame[0]
5001 // should break into 2 xpaths
5002 // /html/body/table/tbody/tr/td/iframe & /frameset/frame[0]
5003 std::vector<string16> xpaths;
5004 base::SplitString(xpath, '\n', &xpaths);
5006 WebFrame* frame = webview()->mainFrame();
5007 for (std::vector<string16>::const_iterator i = xpaths.begin();
5008 frame && i != xpaths.end(); ++i) {
5009 frame = frame->findChildByExpression(*i);
5012 return frame;
5015 void RenderViewImpl::OnScriptEvalRequest(const string16& frame_xpath,
5016 const string16& jscript,
5017 int id,
5018 bool notify_result) {
5019 TRACE_EVENT_INSTANT0("test_tracing", "OnScriptEvalRequest",
5020 TRACE_EVENT_SCOPE_THREAD);
5021 EvaluateScript(frame_xpath, jscript, id, notify_result);
5024 void RenderViewImpl::OnPostMessageEvent(
5025 const ViewMsg_PostMessage_Params& params) {
5026 // TODO(nasko): Support sending to subframes.
5027 WebFrame* frame = webview()->mainFrame();
5029 // Find the source frame if it exists.
5030 WebFrame* source_frame = NULL;
5031 if (params.source_routing_id != MSG_ROUTING_NONE) {
5032 RenderViewImpl* source_view = FromRoutingID(params.source_routing_id);
5033 if (source_view)
5034 source_frame = source_view->webview()->mainFrame();
5037 // If the message contained MessagePorts, create the corresponding endpoints.
5038 DCHECK_EQ(params.message_port_ids.size(), params.new_routing_ids.size());
5039 WebKit::WebMessagePortChannelArray channels(params.message_port_ids.size());
5040 for (size_t i = 0;
5041 i < params.message_port_ids.size() && i < params.new_routing_ids.size();
5042 ++i) {
5043 channels[i] =
5044 new WebMessagePortChannelImpl(params.new_routing_ids[i],
5045 params.message_port_ids[i],
5046 base::MessageLoopProxy::current().get());
5049 // Create an event with the message. The final parameter to initMessageEvent
5050 // is the last event ID, which is not used with postMessage.
5051 WebDOMEvent event = frame->document().createEvent("MessageEvent");
5052 WebDOMMessageEvent msg_event = event.to<WebDOMMessageEvent>();
5053 msg_event.initMessageEvent("message",
5054 // |canBubble| and |cancellable| are always false
5055 false, false,
5056 WebSerializedScriptValue::fromString(params.data),
5057 params.source_origin, source_frame, "", channels);
5059 // We must pass in the target_origin to do the security check on this side,
5060 // since it may have changed since the original postMessage call was made.
5061 WebSecurityOrigin target_origin;
5062 if (!params.target_origin.empty()) {
5063 target_origin =
5064 WebSecurityOrigin::createFromString(WebString(params.target_origin));
5066 frame->dispatchMessageEventWithOriginCheck(target_origin, msg_event);
5069 void RenderViewImpl::OnCSSInsertRequest(const string16& frame_xpath,
5070 const std::string& css) {
5071 WebFrame* frame = GetChildFrame(frame_xpath);
5072 if (!frame)
5073 return;
5075 frame->document().insertUserStyleSheet(
5076 WebString::fromUTF8(css),
5077 WebDocument::UserStyleAuthorLevel);
5080 void RenderViewImpl::OnAllowBindings(int enabled_bindings_flags) {
5081 if ((enabled_bindings_flags & BINDINGS_POLICY_WEB_UI) &&
5082 !(enabled_bindings_ & BINDINGS_POLICY_WEB_UI)) {
5083 // WebUI uses <dialog> which is not yet enabled by default in Chrome.
5084 WebRuntimeFeatures::enableDialogElement(true);
5086 RenderThread::Get()->RegisterExtension(WebUIExtension::Get());
5087 new WebUIExtensionData(this);
5090 enabled_bindings_ |= enabled_bindings_flags;
5092 // Keep track of the total bindings accumulated in this process.
5093 RenderProcess::current()->AddBindings(enabled_bindings_flags);
5096 void RenderViewImpl::OnDragTargetDragEnter(const DropData& drop_data,
5097 const gfx::Point& client_point,
5098 const gfx::Point& screen_point,
5099 WebDragOperationsMask ops,
5100 int key_modifiers) {
5101 WebDragOperation operation = webview()->dragTargetDragEnter(
5102 DropDataToWebDragData(drop_data),
5103 client_point,
5104 screen_point,
5105 ops,
5106 key_modifiers);
5108 Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
5111 void RenderViewImpl::OnDragTargetDragOver(const gfx::Point& client_point,
5112 const gfx::Point& screen_point,
5113 WebDragOperationsMask ops,
5114 int key_modifiers) {
5115 WebDragOperation operation = webview()->dragTargetDragOver(
5116 client_point,
5117 screen_point,
5118 ops,
5119 key_modifiers);
5121 Send(new DragHostMsg_UpdateDragCursor(routing_id_, operation));
5124 void RenderViewImpl::OnDragTargetDragLeave() {
5125 webview()->dragTargetDragLeave();
5128 void RenderViewImpl::OnDragTargetDrop(const gfx::Point& client_point,
5129 const gfx::Point& screen_point,
5130 int key_modifiers) {
5131 webview()->dragTargetDrop(client_point, screen_point, key_modifiers);
5133 Send(new DragHostMsg_TargetDrop_ACK(routing_id_));
5136 void RenderViewImpl::OnDragSourceEndedOrMoved(const gfx::Point& client_point,
5137 const gfx::Point& screen_point,
5138 bool ended,
5139 WebDragOperation op) {
5140 if (ended) {
5141 webview()->dragSourceEndedAt(client_point, screen_point, op);
5142 } else {
5143 webview()->dragSourceMovedTo(client_point, screen_point, op);
5147 void RenderViewImpl::OnDragSourceSystemDragEnded() {
5148 webview()->dragSourceSystemDragEnded();
5151 void RenderViewImpl::OnUpdateWebPreferences(const WebPreferences& prefs) {
5152 webkit_preferences_ = prefs;
5153 ApplyWebPreferences(webkit_preferences_, webview());
5156 void RenderViewImpl::OnUpdateTimezone() {
5157 if (webview())
5158 NotifyTimezoneChange(webview()->mainFrame());
5161 void RenderViewImpl::OnSetAltErrorPageURL(const GURL& url) {
5162 alternate_error_page_url_ = url;
5165 void RenderViewImpl::OnCustomContextMenuAction(
5166 const CustomContextMenuContext& custom_context,
5167 unsigned action) {
5168 if (custom_context.request_id) {
5169 // External context menu request, look in our map.
5170 ContextMenuClient* client =
5171 pending_context_menus_.Lookup(custom_context.request_id);
5172 if (client)
5173 client->OnMenuAction(custom_context.request_id, action);
5174 } else {
5175 // Internal request, forward to WebKit.
5176 webview()->performCustomContextMenuAction(action);
5180 void RenderViewImpl::OnEnumerateDirectoryResponse(
5181 int id,
5182 const std::vector<base::FilePath>& paths) {
5183 if (!enumeration_completions_[id])
5184 return;
5186 WebVector<WebString> ws_file_names(paths.size());
5187 for (size_t i = 0; i < paths.size(); ++i)
5188 ws_file_names[i] = paths[i].AsUTF16Unsafe();
5190 enumeration_completions_[id]->didChooseFile(ws_file_names);
5191 enumeration_completions_.erase(id);
5194 void RenderViewImpl::OnFileChooserResponse(
5195 const std::vector<ui::SelectedFileInfo>& files) {
5196 // This could happen if we navigated to a different page before the user
5197 // closed the chooser.
5198 if (file_chooser_completions_.empty())
5199 return;
5201 // Convert Chrome's SelectedFileInfo list to WebKit's.
5202 WebVector<WebFileChooserCompletion::SelectedFileInfo> selected_files(
5203 files.size());
5204 for (size_t i = 0; i < files.size(); ++i) {
5205 WebFileChooserCompletion::SelectedFileInfo selected_file;
5206 selected_file.path = files[i].local_path.AsUTF16Unsafe();
5207 selected_file.displayName =
5208 base::FilePath(files[i].display_name).AsUTF16Unsafe();
5209 selected_files[i] = selected_file;
5212 if (file_chooser_completions_.front()->completion)
5213 file_chooser_completions_.front()->completion->didChooseFile(
5214 selected_files);
5215 file_chooser_completions_.pop_front();
5217 // If there are more pending file chooser requests, schedule one now.
5218 if (!file_chooser_completions_.empty()) {
5219 Send(new ViewHostMsg_RunFileChooser(routing_id_,
5220 file_chooser_completions_.front()->params));
5224 void RenderViewImpl::OnEnableAutoResize(const gfx::Size& min_size,
5225 const gfx::Size& max_size) {
5226 DCHECK(disable_scrollbars_size_limit_.IsEmpty());
5227 if (!webview())
5228 return;
5229 auto_resize_mode_ = true;
5230 webview()->enableAutoResizeMode(min_size, max_size);
5233 void RenderViewImpl::OnDisableAutoResize(const gfx::Size& new_size) {
5234 DCHECK(disable_scrollbars_size_limit_.IsEmpty());
5235 if (!webview())
5236 return;
5237 auto_resize_mode_ = false;
5238 webview()->disableAutoResizeMode();
5240 if (!new_size.IsEmpty()) {
5241 Resize(new_size,
5242 physical_backing_size_,
5243 overdraw_bottom_height_,
5244 resizer_rect_,
5245 is_fullscreen_,
5246 NO_RESIZE_ACK);
5250 void RenderViewImpl::OnEnablePreferredSizeChangedMode() {
5251 if (send_preferred_size_changes_)
5252 return;
5253 send_preferred_size_changes_ = true;
5255 // Start off with an initial preferred size notification (in case
5256 // |didUpdateLayout| was already called).
5257 didUpdateLayout();
5260 void RenderViewImpl::OnDisableScrollbarsForSmallWindows(
5261 const gfx::Size& disable_scrollbar_size_limit) {
5262 disable_scrollbars_size_limit_ = disable_scrollbar_size_limit;
5265 void RenderViewImpl::OnSetRendererPrefs(
5266 const RendererPreferences& renderer_prefs) {
5267 double old_zoom_level = renderer_preferences_.default_zoom_level;
5268 renderer_preferences_ = renderer_prefs;
5269 UpdateFontRenderingFromRendererPrefs();
5271 #if defined(USE_DEFAULT_RENDER_THEME) || defined(TOOLKIT_GTK)
5272 if (renderer_prefs.use_custom_colors) {
5273 WebColorName name = WebKit::WebColorWebkitFocusRingColor;
5274 WebKit::setNamedColors(&name, &renderer_prefs.focus_ring_color, 1);
5275 WebKit::setCaretBlinkInterval(renderer_prefs.caret_blink_interval);
5276 #if defined(TOOLKIT_GTK)
5277 ui::NativeTheme::instance()->SetScrollbarColors(
5278 renderer_prefs.thumb_inactive_color,
5279 renderer_prefs.thumb_active_color,
5280 renderer_prefs.track_color);
5281 #endif // defined(TOOLKIT_GTK)
5283 if (webview()) {
5284 #if defined(TOOLKIT_GTK)
5285 webview()->setScrollbarColors(
5286 renderer_prefs.thumb_inactive_color,
5287 renderer_prefs.thumb_active_color,
5288 renderer_prefs.track_color);
5289 #endif // defined(TOOLKIT_GTK)
5290 webview()->setSelectionColors(
5291 renderer_prefs.active_selection_bg_color,
5292 renderer_prefs.active_selection_fg_color,
5293 renderer_prefs.inactive_selection_bg_color,
5294 renderer_prefs.inactive_selection_fg_color);
5295 webview()->themeChanged();
5298 #endif // defined(USE_DEFAULT_RENDER_THEME) || defined(TOOLKIT_GTK)
5300 if (RenderThreadImpl::current()) // Will be NULL during unit tests.
5301 RenderThreadImpl::current()->SetFlingCurveParameters(
5302 renderer_prefs.touchpad_fling_profile,
5303 renderer_prefs.touchscreen_fling_profile);
5305 // If the zoom level for this page matches the old zoom default, and this
5306 // is not a plugin, update the zoom level to match the new default.
5307 if (webview() && !webview()->mainFrame()->document().isPluginDocument() &&
5308 !ZoomValuesEqual(old_zoom_level,
5309 renderer_preferences_.default_zoom_level) &&
5310 ZoomValuesEqual(webview()->zoomLevel(), old_zoom_level)) {
5311 webview()->setZoomLevel(renderer_preferences_.default_zoom_level);
5312 zoomLevelChanged();
5316 void RenderViewImpl::OnMediaPlayerActionAt(const gfx::Point& location,
5317 const WebMediaPlayerAction& action) {
5318 if (webview())
5319 webview()->performMediaPlayerAction(action, location);
5322 void RenderViewImpl::OnOrientationChangeEvent(int orientation) {
5323 FOR_EACH_OBSERVER(RenderViewObserver,
5324 observers_,
5325 OrientationChangeEvent(orientation));
5326 webview()->mainFrame()->sendOrientationChangeEvent(orientation);
5329 void RenderViewImpl::OnPluginActionAt(const gfx::Point& location,
5330 const WebPluginAction& action) {
5331 if (webview())
5332 webview()->performPluginAction(action, location);
5335 void RenderViewImpl::OnGetAllSavableResourceLinksForCurrentPage(
5336 const GURL& page_url) {
5337 // Prepare list to storage all savable resource links.
5338 std::vector<GURL> resources_list;
5339 std::vector<GURL> referrer_urls_list;
5340 std::vector<WebKit::WebReferrerPolicy> referrer_policies_list;
5341 std::vector<GURL> frames_list;
5342 SavableResourcesResult result(&resources_list,
5343 &referrer_urls_list,
5344 &referrer_policies_list,
5345 &frames_list);
5347 // webkit/ doesn't know about Referrer.
5348 if (!GetAllSavableResourceLinksForCurrentPage(
5349 webview(),
5350 page_url,
5351 &result,
5352 const_cast<const char**>(GetSavableSchemes()))) {
5353 // If something is wrong when collecting all savable resource links,
5354 // send empty list to embedder(browser) to tell it failed.
5355 referrer_urls_list.clear();
5356 referrer_policies_list.clear();
5357 resources_list.clear();
5358 frames_list.clear();
5361 std::vector<Referrer> referrers_list;
5362 CHECK_EQ(referrer_urls_list.size(), referrer_policies_list.size());
5363 for (unsigned i = 0; i < referrer_urls_list.size(); ++i) {
5364 referrers_list.push_back(
5365 Referrer(referrer_urls_list[i], referrer_policies_list[i]));
5368 // Send result of all savable resource links to embedder.
5369 Send(new ViewHostMsg_SendCurrentPageAllSavableResourceLinks(routing_id(),
5370 resources_list,
5371 referrers_list,
5372 frames_list));
5375 void RenderViewImpl::OnGetSerializedHtmlDataForCurrentPageWithLocalLinks(
5376 const std::vector<GURL>& links,
5377 const std::vector<base::FilePath>& local_paths,
5378 const base::FilePath& local_directory_name) {
5380 // Convert std::vector of GURLs to WebVector<WebURL>
5381 WebVector<WebURL> weburl_links(links);
5383 // Convert std::vector of base::FilePath to WebVector<WebString>
5384 WebVector<WebString> webstring_paths(local_paths.size());
5385 for (size_t i = 0; i < local_paths.size(); i++)
5386 webstring_paths[i] = local_paths[i].AsUTF16Unsafe();
5388 WebPageSerializer::serialize(webview()->mainFrame(), true, this, weburl_links,
5389 webstring_paths,
5390 local_directory_name.AsUTF16Unsafe());
5393 void RenderViewImpl::OnShouldClose() {
5394 base::TimeTicks before_unload_start_time = base::TimeTicks::Now();
5395 bool should_close = webview()->dispatchBeforeUnloadEvent();
5396 base::TimeTicks before_unload_end_time = base::TimeTicks::Now();
5397 Send(new ViewHostMsg_ShouldClose_ACK(routing_id_, should_close,
5398 before_unload_start_time,
5399 before_unload_end_time));
5402 void RenderViewImpl::OnSwapOut() {
5403 // Only run unload if we're not swapped out yet, but send the ack either way.
5404 if (!is_swapped_out_) {
5405 // Swap this RenderView out so the tab can navigate to a page rendered by a
5406 // different process. This involves running the unload handler and clearing
5407 // the page. Once WasSwappedOut is called, we also allow this process to
5408 // exit if there are no other active RenderViews in it.
5410 // Send an UpdateState message before we get swapped out.
5411 SyncNavigationState();
5413 // Synchronously run the unload handler before sending the ACK.
5414 webview()->dispatchUnloadEvent();
5416 // Swap out and stop sending any IPC messages that are not ACKs.
5417 SetSwappedOut(true);
5419 // Now that we're swapped out and filtering IPC messages, stop loading to
5420 // ensure that no other in-progress navigation continues. We do this here
5421 // to avoid sending a DidStopLoading message to the browser process.
5422 OnStop();
5424 // Replace the page with a blank dummy URL. The unload handler will not be
5425 // run a second time, thanks to a check in FrameLoader::stopLoading.
5426 // TODO(creis): Need to add a better way to do this that avoids running the
5427 // beforeunload handler. For now, we just run it a second time silently.
5428 NavigateToSwappedOutURL(webview()->mainFrame());
5430 // Let WebKit know that this view is hidden so it can drop resources and
5431 // stop compositing.
5432 webview()->setVisibilityState(WebKit::WebPageVisibilityStateHidden, false);
5435 Send(new ViewHostMsg_SwapOut_ACK(routing_id_));
5438 void RenderViewImpl::NavigateToSwappedOutURL(WebKit::WebFrame* frame) {
5439 // We use loadRequest instead of loadHTMLString because the former commits
5440 // synchronously. Otherwise a new navigation can interrupt the navigation
5441 // to kSwappedOutURL. If that happens to be to the page we had been
5442 // showing, then WebKit will never send a commit and we'll be left spinning.
5443 CHECK(is_swapped_out_);
5444 GURL swappedOutURL(kSwappedOutURL);
5445 WebURLRequest request(swappedOutURL);
5446 frame->loadRequest(request);
5449 void RenderViewImpl::OnClosePage() {
5450 FOR_EACH_OBSERVER(RenderViewObserver, observers_, ClosePage());
5451 // TODO(creis): We'd rather use webview()->Close() here, but that currently
5452 // sets the WebView's delegate_ to NULL, preventing any JavaScript dialogs
5453 // in the onunload handler from appearing. For now, we're bypassing that and
5454 // calling the FrameLoader's CloseURL method directly. This should be
5455 // revisited to avoid having two ways to close a page. Having a single way
5456 // to close that can run onunload is also useful for fixing
5457 // http://b/issue?id=753080.
5458 webview()->dispatchUnloadEvent();
5460 Send(new ViewHostMsg_ClosePage_ACK(routing_id_));
5463 void RenderViewImpl::OnThemeChanged() {
5464 #if defined(USE_AURA)
5465 // Aura doesn't care if we switch themes.
5466 #elif defined(OS_WIN)
5467 ui::NativeThemeWin::instance()->CloseHandles();
5468 if (webview())
5469 webview()->themeChanged();
5470 #else // defined(OS_WIN)
5471 // TODO(port): we don't support theming on non-Windows platforms yet
5472 NOTIMPLEMENTED();
5473 #endif
5476 bool RenderViewImpl::MaybeLoadAlternateErrorPage(WebFrame* frame,
5477 const WebURLError& error,
5478 bool replace) {
5479 // We only show alternate error pages in the main frame. They are
5480 // intended to assist the user when navigating, so there is not much
5481 // value in showing them for failed subframes. Ideally, we would be
5482 // able to use the TYPED transition type for this, but that flag is
5483 // not preserved across page reloads.
5484 if (frame->parent())
5485 return false;
5487 // Use the alternate error page service if this is a DNS failure or
5488 // connection failure.
5489 int ec = error.reason;
5490 if (ec != net::ERR_NAME_NOT_RESOLVED &&
5491 ec != net::ERR_CONNECTION_FAILED &&
5492 ec != net::ERR_CONNECTION_REFUSED &&
5493 ec != net::ERR_ADDRESS_UNREACHABLE &&
5494 ec != net::ERR_CONNECTION_TIMED_OUT) {
5495 return false;
5498 const GURL& error_page_url = GetAlternateErrorPageURL(error.unreachableURL,
5499 ec == net::ERR_NAME_NOT_RESOLVED ? DNS_ERROR : CONNECTION_ERROR);
5500 if (!error_page_url.is_valid())
5501 return false;
5503 WebDataSource* ds = frame->provisionalDataSource();
5504 const WebURLRequest& failed_request = ds->request();
5506 // Load an empty page first so there is an immediate response to the error,
5507 // and then kick off a request for the alternate error page.
5508 frame->loadHTMLString(std::string(),
5509 GURL(kUnreachableWebDataURL),
5510 error.unreachableURL,
5511 replace);
5513 // Now, create a fetcher for the error page and associate it with the data
5514 // source we just created via the LoadHTMLString call. That way if another
5515 // navigation occurs, the fetcher will get destroyed.
5516 InternalDocumentStateData* internal_data =
5517 InternalDocumentStateData::FromDataSource(frame->provisionalDataSource());
5518 internal_data->set_alt_error_page_fetcher(
5519 new AltErrorPageResourceFetcher(
5520 error_page_url, frame, failed_request, error,
5521 base::Bind(&RenderViewImpl::AltErrorPageFinished,
5522 base::Unretained(this))));
5523 return true;
5526 void RenderViewImpl::AltErrorPageFinished(WebFrame* frame,
5527 const WebURLRequest& original_request,
5528 const WebURLError& original_error,
5529 const std::string& html) {
5530 // Here, we replace the blank page we loaded previously.
5531 // If we failed to download the alternate error page, LoadNavigationErrorPage
5532 // will simply display a default error page.
5533 LoadNavigationErrorPage(frame, original_request, original_error, html, true);
5536 void RenderViewImpl::OnMoveOrResizeStarted() {
5537 if (webview())
5538 webview()->hidePopups();
5541 void RenderViewImpl::OnResize(const ViewMsg_Resize_Params& params) {
5542 if (webview()) {
5543 webview()->hidePopups();
5544 if (send_preferred_size_changes_) {
5545 webview()->mainFrame()->setCanHaveScrollbars(
5546 ShouldDisplayScrollbars(params.new_size.width(),
5547 params.new_size.height()));
5549 UpdateScrollState(webview()->mainFrame());
5552 RenderWidget::OnResize(params);
5555 void RenderViewImpl::DidInitiatePaint() {
5556 #if defined(ENABLE_PLUGINS)
5557 // Notify all instances that we painted. The same caveats apply as for
5558 // ViewFlushedPaint regarding instances closing themselves, so we take
5559 // similar precautions.
5560 PepperPluginSet plugins = active_pepper_instances_;
5561 for (PepperPluginSet::iterator i = plugins.begin(); i != plugins.end(); ++i) {
5562 if (active_pepper_instances_.find(*i) != active_pepper_instances_.end())
5563 (*i)->ViewInitiatedPaint();
5565 #endif
5568 void RenderViewImpl::DidFlushPaint() {
5569 #if defined(ENABLE_PLUGINS)
5570 // Notify all instances that we flushed. This will call into the plugin, and
5571 // we it may ask to close itself as a result. This will, in turn, modify our
5572 // set, possibly invalidating the iterator. So we iterate on a copy that
5573 // won't change out from under us.
5574 PepperPluginSet plugins = active_pepper_instances_;
5575 for (PepperPluginSet::iterator i = plugins.begin(); i != plugins.end(); ++i) {
5576 // The copy above makes sure our iterator is never invalid if some plugins
5577 // are destroyed. But some plugin may decide to close all of its views in
5578 // response to a paint in one of them, so we need to make sure each one is
5579 // still "current" before using it.
5581 // It's possible that a plugin was destroyed, but another one was created
5582 // with the same address. In this case, we'll call ViewFlushedPaint on that
5583 // new plugin. But that's OK for this particular case since we're just
5584 // notifying all of our instances that the view flushed, and the new one is
5585 // one of our instances.
5587 // What about the case where a new one is created in a callback at a new
5588 // address and we don't issue the callback? We're still OK since this
5589 // callback is used for flush callbacks and we could not have possibly
5590 // started a new paint for the new plugin while processing a previous paint
5591 // for an existing one.
5592 if (active_pepper_instances_.find(*i) != active_pepper_instances_.end())
5593 (*i)->ViewFlushedPaint();
5595 #endif
5597 // If the RenderWidget is closing down then early-exit, otherwise we'll crash.
5598 // See crbug.com/112921.
5599 if (!webview())
5600 return;
5602 WebFrame* main_frame = webview()->mainFrame();
5604 // If we have a provisional frame we are between the start and commit stages
5605 // of loading and we don't want to save stats.
5606 if (!main_frame->provisionalDataSource()) {
5607 WebDataSource* ds = main_frame->dataSource();
5608 DocumentState* document_state = DocumentState::FromDataSource(ds);
5609 InternalDocumentStateData* data =
5610 InternalDocumentStateData::FromDocumentState(document_state);
5611 if (data->did_first_visually_non_empty_layout() &&
5612 !data->did_first_visually_non_empty_paint()) {
5613 data->set_did_first_visually_non_empty_paint(true);
5614 Send(new ViewHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_,
5615 page_id_));
5618 // TODO(jar): The following code should all be inside a method, probably in
5619 // NavigatorState.
5620 Time now = Time::Now();
5621 if (document_state->first_paint_time().is_null()) {
5622 document_state->set_first_paint_time(now);
5624 if (document_state->first_paint_after_load_time().is_null() &&
5625 !document_state->finish_load_time().is_null()) {
5626 document_state->set_first_paint_after_load_time(now);
5631 PepperPluginInstanceImpl* RenderViewImpl::GetBitmapForOptimizedPluginPaint(
5632 const gfx::Rect& paint_bounds,
5633 TransportDIB** dib,
5634 gfx::Rect* location,
5635 gfx::Rect* clip,
5636 float* scale_factor) {
5637 #if defined(ENABLE_PLUGINS)
5638 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
5639 i != active_pepper_instances_.end(); ++i) {
5640 PepperPluginInstanceImpl* instance = *i;
5641 // In Flash fullscreen , the plugin contents should be painted onto the
5642 // fullscreen widget instead of the web page.
5643 if (!instance->FlashIsFullscreenOrPending() &&
5644 instance->GetBitmapForOptimizedPluginPaint(paint_bounds, dib, location,
5645 clip, scale_factor))
5646 return *i;
5648 #endif
5649 return NULL;
5652 gfx::Vector2d RenderViewImpl::GetScrollOffset() {
5653 WebSize scroll_offset = webview()->mainFrame()->scrollOffset();
5654 return gfx::Vector2d(scroll_offset.width, scroll_offset.height);
5657 void RenderViewImpl::OnClearFocusedNode() {
5658 if (webview())
5659 webview()->clearFocusedNode();
5662 void RenderViewImpl::OnSetBackground(const SkBitmap& background) {
5663 if (webview())
5664 webview()->setIsTransparent(!background.empty());
5665 if (compositor_)
5666 compositor_->setHasTransparentBackground(!background.empty());
5668 SetBackground(background);
5671 void RenderViewImpl::OnSetAccessibilityMode(AccessibilityMode new_mode) {
5672 if (accessibility_mode_ == new_mode)
5673 return;
5674 accessibility_mode_ = new_mode;
5675 if (renderer_accessibility_) {
5676 delete renderer_accessibility_;
5677 renderer_accessibility_ = NULL;
5679 if (accessibility_mode_ == AccessibilityModeComplete)
5680 renderer_accessibility_ = new RendererAccessibilityComplete(this);
5681 #if !defined(OS_ANDROID)
5682 else if (accessibility_mode_ == AccessibilityModeEditableTextOnly)
5683 renderer_accessibility_ = new RendererAccessibilityFocusOnly(this);
5684 #endif
5687 void RenderViewImpl::OnSetActive(bool active) {
5688 if (webview())
5689 webview()->setIsActive(active);
5691 #if defined(ENABLE_PLUGINS) && defined(OS_MACOSX)
5692 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
5693 for (plugin_it = plugin_delegates_.begin();
5694 plugin_it != plugin_delegates_.end(); ++plugin_it) {
5695 (*plugin_it)->SetWindowFocus(active);
5697 #endif
5700 #if defined(OS_MACOSX)
5701 void RenderViewImpl::OnSetWindowVisibility(bool visible) {
5702 #if defined(ENABLE_PLUGINS)
5703 // Inform plugins that their container has changed visibility.
5704 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
5705 for (plugin_it = plugin_delegates_.begin();
5706 plugin_it != plugin_delegates_.end(); ++plugin_it) {
5707 (*plugin_it)->SetContainerVisibility(visible);
5709 #endif
5712 void RenderViewImpl::OnWindowFrameChanged(const gfx::Rect& window_frame,
5713 const gfx::Rect& view_frame) {
5714 #if defined(ENABLE_PLUGINS)
5715 // Inform plugins that their window's frame has changed.
5716 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
5717 for (plugin_it = plugin_delegates_.begin();
5718 plugin_it != plugin_delegates_.end(); ++plugin_it) {
5719 (*plugin_it)->WindowFrameChanged(window_frame, view_frame);
5721 #endif
5724 void RenderViewImpl::OnPluginImeCompositionCompleted(const string16& text,
5725 int plugin_id) {
5726 // WebPluginDelegateProxy is responsible for figuring out if this event
5727 // applies to it or not, so inform all the delegates.
5728 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
5729 for (plugin_it = plugin_delegates_.begin();
5730 plugin_it != plugin_delegates_.end(); ++plugin_it) {
5731 (*plugin_it)->ImeCompositionCompleted(text, plugin_id);
5734 #endif // OS_MACOSX
5736 void RenderViewImpl::Close() {
5737 // We need to grab a pointer to the doomed WebView before we destroy it.
5738 WebView* doomed = webview();
5739 RenderWidget::Close();
5740 g_view_map.Get().erase(doomed);
5741 g_routing_id_view_map.Get().erase(routing_id_);
5744 void RenderViewImpl::DidHandleKeyEvent() {
5745 ClearEditCommands();
5748 bool RenderViewImpl::WillHandleMouseEvent(const WebKit::WebMouseEvent& event) {
5749 context_menu_source_type_ = ui::MENU_SOURCE_MOUSE;
5750 possible_drag_event_info_.event_source =
5751 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE;
5752 possible_drag_event_info_.event_location =
5753 gfx::Point(event.globalX, event.globalY);
5755 #if defined(ENABLE_PLUGINS)
5756 // This method is called for every mouse event that the render view receives.
5757 // And then the mouse event is forwarded to WebKit, which dispatches it to the
5758 // event target. Potentially a Pepper plugin will receive the event.
5759 // In order to tell whether a plugin gets the last mouse event and which it
5760 // is, we set |pepper_last_mouse_event_target_| to NULL here. If a plugin gets
5761 // the event, it will notify us via DidReceiveMouseEvent() and set itself as
5762 // |pepper_last_mouse_event_target_|.
5763 pepper_last_mouse_event_target_ = NULL;
5764 #endif
5766 // If the mouse is locked, only the current owner of the mouse lock can
5767 // process mouse events.
5768 return mouse_lock_dispatcher_->WillHandleMouseEvent(event);
5771 bool RenderViewImpl::WillHandleKeyEvent(const WebKit::WebKeyboardEvent& event) {
5772 context_menu_source_type_ = ui::MENU_SOURCE_KEYBOARD;
5773 return false;
5776 bool RenderViewImpl::WillHandleGestureEvent(
5777 const WebKit::WebGestureEvent& event) {
5778 context_menu_source_type_ = ui::MENU_SOURCE_TOUCH;
5779 possible_drag_event_info_.event_source =
5780 ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH;
5781 possible_drag_event_info_.event_location =
5782 gfx::Point(event.globalX, event.globalY);
5783 return false;
5786 void RenderViewImpl::DidHandleMouseEvent(const WebMouseEvent& event) {
5787 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidHandleMouseEvent(event));
5790 void RenderViewImpl::DidHandleTouchEvent(const WebTouchEvent& event) {
5791 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidHandleTouchEvent(event));
5794 bool RenderViewImpl::HasTouchEventHandlersAt(const gfx::Point& point) const {
5795 if (!webview())
5796 return false;
5797 return webview()->hasTouchEventHandlersAt(point);
5800 void RenderViewImpl::OnWasHidden() {
5801 RenderWidget::OnWasHidden();
5803 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
5804 RenderThreadImpl::current()->video_capture_impl_manager()->
5805 SuspendDevices(true);
5806 #endif
5808 if (webview())
5809 webview()->setVisibilityState(visibilityState(), false);
5811 #if defined(ENABLE_PLUGINS)
5812 // Inform PPAPI plugins that their page is no longer visible.
5813 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
5814 i != active_pepper_instances_.end(); ++i)
5815 (*i)->PageVisibilityChanged(false);
5817 #if defined(OS_MACOSX)
5818 // Inform NPAPI plugins that their container is no longer visible.
5819 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
5820 for (plugin_it = plugin_delegates_.begin();
5821 plugin_it != plugin_delegates_.end(); ++plugin_it) {
5822 (*plugin_it)->SetContainerVisibility(false);
5824 #endif // OS_MACOSX
5825 #endif // ENABLE_PLUGINS
5828 void RenderViewImpl::OnWasShown(bool needs_repainting) {
5829 RenderWidget::OnWasShown(needs_repainting);
5831 #if defined(OS_ANDROID) && defined(ENABLE_WEBRTC)
5832 RenderThreadImpl::current()->video_capture_impl_manager()->
5833 SuspendDevices(false);
5834 #endif
5836 if (webview())
5837 webview()->setVisibilityState(visibilityState(), false);
5839 #if defined(ENABLE_PLUGINS)
5840 // Inform PPAPI plugins that their page is visible.
5841 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
5842 i != active_pepper_instances_.end(); ++i)
5843 (*i)->PageVisibilityChanged(true);
5845 #if defined(OS_MACOSX)
5846 // Inform NPAPI plugins that their container is now visible.
5847 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
5848 for (plugin_it = plugin_delegates_.begin();
5849 plugin_it != plugin_delegates_.end(); ++plugin_it) {
5850 (*plugin_it)->SetContainerVisibility(true);
5852 #endif // OS_MACOSX
5853 #endif // ENABLE_PLUGINS
5856 GURL RenderViewImpl::GetURLForGraphicsContext3D() {
5857 DCHECK(webview());
5858 if (webview()->mainFrame())
5859 return GURL(webview()->mainFrame()->document().url());
5860 else
5861 return GURL("chrome://gpu/RenderViewImpl::CreateGraphicsContext3D");
5864 bool RenderViewImpl::ForceCompositingModeEnabled() {
5865 return webkit_preferences_.force_compositing_mode;
5868 void RenderViewImpl::OnSetFocus(bool enable) {
5869 RenderWidget::OnSetFocus(enable);
5871 #if defined(ENABLE_PLUGINS)
5872 if (webview() && webview()->isActive()) {
5873 // Notify all NPAPI plugins.
5874 std::set<WebPluginDelegateProxy*>::iterator plugin_it;
5875 for (plugin_it = plugin_delegates_.begin();
5876 plugin_it != plugin_delegates_.end(); ++plugin_it) {
5877 #if defined(OS_MACOSX)
5878 // RenderWidget's call to setFocus can cause the underlying webview's
5879 // activation state to change just like a call to setIsActive.
5880 if (enable)
5881 (*plugin_it)->SetWindowFocus(true);
5882 #endif
5883 (*plugin_it)->SetContentAreaFocus(enable);
5886 // Notify all Pepper plugins.
5887 for (PepperPluginSet::iterator i = active_pepper_instances_.begin();
5888 i != active_pepper_instances_.end(); ++i)
5889 (*i)->SetContentAreaFocus(enable);
5890 #endif
5891 // Notify all BrowserPlugins of the RenderView's focus state.
5892 if (browser_plugin_manager_.get())
5893 browser_plugin_manager_->UpdateFocusState();
5896 void RenderViewImpl::OnImeSetComposition(
5897 const string16& text,
5898 const std::vector<WebKit::WebCompositionUnderline>& underlines,
5899 int selection_start,
5900 int selection_end) {
5901 #if defined(ENABLE_PLUGINS)
5902 if (focused_pepper_plugin_) {
5903 // When a PPAPI plugin has focus, we bypass WebKit.
5904 if (!IsPepperAcceptingCompositionEvents()) {
5905 pepper_composition_text_ = text;
5906 } else {
5907 // TODO(kinaba) currently all composition events are sent directly to
5908 // plugins. Use DOM event mechanism after WebKit is made aware about
5909 // plugins that support composition.
5910 // The code below mimics the behavior of WebCore::Editor::setComposition.
5912 // Empty -> nonempty: composition started.
5913 if (pepper_composition_text_.empty() && !text.empty())
5914 focused_pepper_plugin_->HandleCompositionStart(string16());
5915 // Nonempty -> empty: composition canceled.
5916 if (!pepper_composition_text_.empty() && text.empty())
5917 focused_pepper_plugin_->HandleCompositionEnd(string16());
5918 pepper_composition_text_ = text;
5919 // Nonempty: composition is ongoing.
5920 if (!pepper_composition_text_.empty()) {
5921 focused_pepper_plugin_->HandleCompositionUpdate(
5922 pepper_composition_text_, underlines, selection_start,
5923 selection_end);
5926 return;
5929 #if defined(OS_WIN)
5930 // When a plug-in has focus, we create platform-specific IME data used by
5931 // our IME emulator and send it directly to the focused plug-in, i.e. we
5932 // bypass WebKit. (WebPluginDelegate dispatches this IME data only when its
5933 // instance ID is the same one as the specified ID.)
5934 if (focused_plugin_id_ >= 0) {
5935 std::vector<int> clauses;
5936 std::vector<int> target;
5937 for (size_t i = 0; i < underlines.size(); ++i) {
5938 clauses.push_back(underlines[i].startOffset);
5939 clauses.push_back(underlines[i].endOffset);
5940 if (underlines[i].thick) {
5941 target.clear();
5942 target.push_back(underlines[i].startOffset);
5943 target.push_back(underlines[i].endOffset);
5946 std::set<WebPluginDelegateProxy*>::iterator it;
5947 for (it = plugin_delegates_.begin(); it != plugin_delegates_.end(); ++it) {
5948 (*it)->ImeCompositionUpdated(text, clauses, target, selection_end,
5949 focused_plugin_id_);
5951 return;
5953 #endif // OS_WIN
5954 #endif // ENABLE_PLUGINS
5955 RenderWidget::OnImeSetComposition(text,
5956 underlines,
5957 selection_start,
5958 selection_end);
5961 void RenderViewImpl::OnImeConfirmComposition(
5962 const string16& text,
5963 const gfx::Range& replacement_range,
5964 bool keep_selection) {
5965 #if defined(ENABLE_PLUGINS)
5966 if (focused_pepper_plugin_) {
5967 // When a PPAPI plugin has focus, we bypass WebKit.
5968 // Here, text.empty() has a special meaning. It means to commit the last
5969 // update of composition text (see
5970 // RenderWidgetHost::ImeConfirmComposition()).
5971 const string16& last_text = text.empty() ? pepper_composition_text_ : text;
5973 // last_text is empty only when both text and pepper_composition_text_ is.
5974 // Ignore it.
5975 if (last_text.empty())
5976 return;
5978 if (!IsPepperAcceptingCompositionEvents()) {
5979 base::i18n::UTF16CharIterator iterator(&last_text);
5980 int32 i = 0;
5981 while (iterator.Advance()) {
5982 WebKit::WebKeyboardEvent char_event;
5983 char_event.type = WebKit::WebInputEvent::Char;
5984 char_event.timeStampSeconds = base::Time::Now().ToDoubleT();
5985 char_event.modifiers = 0;
5986 char_event.windowsKeyCode = last_text[i];
5987 char_event.nativeKeyCode = last_text[i];
5989 const int32 char_start = i;
5990 for (; i < iterator.array_pos(); ++i) {
5991 char_event.text[i - char_start] = last_text[i];
5992 char_event.unmodifiedText[i - char_start] = last_text[i];
5995 if (webwidget())
5996 webwidget()->handleInputEvent(char_event);
5998 } else {
5999 // Mimics the order of events sent by WebKit.
6000 // See WebCore::Editor::setComposition() for the corresponding code.
6001 focused_pepper_plugin_->HandleCompositionEnd(last_text);
6002 focused_pepper_plugin_->HandleTextInput(last_text);
6004 pepper_composition_text_.clear();
6005 return;
6007 #if defined(OS_WIN)
6008 // Same as OnImeSetComposition(), we send the text from IMEs directly to
6009 // plug-ins. When we send IME text directly to plug-ins, we should not send
6010 // it to WebKit to prevent WebKit from controlling IMEs.
6011 // TODO(thakis): Honor |replacement_range| for plugins?
6012 if (focused_plugin_id_ >= 0) {
6013 std::set<WebPluginDelegateProxy*>::iterator it;
6014 for (it = plugin_delegates_.begin();
6015 it != plugin_delegates_.end(); ++it) {
6016 (*it)->ImeCompositionCompleted(text, focused_plugin_id_);
6018 return;
6020 #endif // OS_WIN
6021 #endif // ENABLE_PLUGINS
6022 if (replacement_range.IsValid() && webview()) {
6023 // Select the text in |replacement_range|, it will then be replaced by
6024 // text added by the call to RenderWidget::OnImeConfirmComposition().
6025 if (WebFrame* frame = webview()->focusedFrame()) {
6026 WebRange webrange = WebRange::fromDocumentRange(
6027 frame, replacement_range.start(), replacement_range.length());
6028 if (!webrange.isNull())
6029 frame->selectRange(webrange);
6032 RenderWidget::OnImeConfirmComposition(text,
6033 replacement_range,
6034 keep_selection);
6037 void RenderViewImpl::SetDeviceScaleFactor(float device_scale_factor) {
6038 RenderWidget::SetDeviceScaleFactor(device_scale_factor);
6039 if (webview()) {
6040 webview()->setDeviceScaleFactor(device_scale_factor);
6041 webview()->settings()->setAcceleratedCompositingForFixedPositionEnabled(
6042 ShouldUseFixedPositionCompositing(device_scale_factor_));
6043 webview()->settings()->setAcceleratedCompositingForOverflowScrollEnabled(
6044 ShouldUseAcceleratedCompositingForOverflowScroll(device_scale_factor_));
6045 webview()->settings()->setAcceleratedCompositingForTransitionEnabled(
6046 ShouldUseTransitionCompositing(device_scale_factor_));
6047 webview()->settings()->
6048 setAcceleratedCompositingForFixedRootBackgroundEnabled(
6049 ShouldUseAcceleratedFixedRootBackground(device_scale_factor_));
6050 webview()->settings()->setAcceleratedCompositingForScrollableFramesEnabled(
6051 ShouldUseAcceleratedCompositingForScrollableFrames(
6052 device_scale_factor_));
6053 webview()->settings()->setCompositedScrollingForFramesEnabled(
6054 ShouldUseCompositedScrollingForFrames(device_scale_factor_));
6056 if (auto_resize_mode_)
6057 AutoResizeCompositor();
6059 if (browser_plugin_manager_.get())
6060 browser_plugin_manager_->UpdateDeviceScaleFactor(device_scale_factor_);
6063 ui::TextInputType RenderViewImpl::GetTextInputType() {
6064 #if defined(ENABLE_PLUGINS)
6065 if (focused_pepper_plugin_)
6066 return focused_pepper_plugin_->text_input_type();
6067 #endif
6068 return RenderWidget::GetTextInputType();
6071 void RenderViewImpl::GetSelectionBounds(gfx::Rect* start, gfx::Rect* end) {
6072 #if defined(ENABLE_PLUGINS)
6073 if (focused_pepper_plugin_) {
6074 // TODO(kinaba) http://crbug.com/101101
6075 // Current Pepper IME API does not handle selection bounds. So we simply
6076 // use the caret position as an empty range for now. It will be updated
6077 // after Pepper API equips features related to surrounding text retrieval.
6078 gfx::Rect caret = focused_pepper_plugin_->GetCaretBounds();
6079 *start = caret;
6080 *end = caret;
6081 return;
6083 #endif
6084 RenderWidget::GetSelectionBounds(start, end);
6087 #if defined(OS_MACOSX) || defined(OS_WIN) || defined(USE_AURA)
6088 void RenderViewImpl::GetCompositionCharacterBounds(
6089 std::vector<gfx::Rect>* bounds) {
6090 DCHECK(bounds);
6091 bounds->clear();
6093 #if defined(ENABLE_PLUGINS)
6094 if (focused_pepper_plugin_) {
6095 return;
6097 #endif
6099 if (!webview())
6100 return;
6101 size_t start_offset = 0;
6102 size_t character_count = 0;
6103 if (!webview()->compositionRange(&start_offset, &character_count))
6104 return;
6105 if (character_count == 0)
6106 return;
6108 WebKit::WebFrame* frame = webview()->focusedFrame();
6109 if (!frame)
6110 return;
6112 bounds->reserve(character_count);
6113 WebKit::WebRect webrect;
6114 for (size_t i = 0; i < character_count; ++i) {
6115 if (!frame->firstRectForCharacterRange(start_offset + i, 1, webrect)) {
6116 DLOG(ERROR) << "Could not retrieve character rectangle at " << i;
6117 bounds->clear();
6118 return;
6120 bounds->push_back(webrect);
6124 void RenderViewImpl::GetCompositionRange(gfx::Range* range) {
6125 #if defined(ENABLE_PLUGINS)
6126 if (focused_pepper_plugin_) {
6127 return;
6129 #endif
6130 RenderWidget::GetCompositionRange(range);
6132 #endif
6134 bool RenderViewImpl::CanComposeInline() {
6135 #if defined(ENABLE_PLUGINS)
6136 if (focused_pepper_plugin_)
6137 return IsPepperAcceptingCompositionEvents();
6138 #endif
6139 return true;
6142 void RenderViewImpl::InstrumentWillBeginFrame() {
6143 if (!webview())
6144 return;
6145 if (!webview()->devToolsAgent())
6146 return;
6147 webview()->devToolsAgent()->didBeginFrame();
6150 void RenderViewImpl::InstrumentDidBeginFrame() {
6151 if (!webview())
6152 return;
6153 if (!webview()->devToolsAgent())
6154 return;
6155 // TODO(jamesr/caseq): Decide if this needs to be renamed.
6156 webview()->devToolsAgent()->didComposite();
6159 void RenderViewImpl::InstrumentDidCancelFrame() {
6160 if (!webview())
6161 return;
6162 if (!webview()->devToolsAgent())
6163 return;
6164 webview()->devToolsAgent()->didCancelFrame();
6167 void RenderViewImpl::InstrumentWillComposite() {
6168 if (!webview())
6169 return;
6170 if (!webview()->devToolsAgent())
6171 return;
6172 webview()->devToolsAgent()->willComposite();
6175 bool RenderViewImpl::AllowPartialSwap() const {
6176 return allow_partial_swap_;
6179 void RenderViewImpl::SetScreenMetricsEmulationParameters(
6180 float device_scale_factor, float root_layer_scale) {
6181 if (webview()) {
6182 webview()->setCompositorDeviceScaleFactorOverride(device_scale_factor);
6183 webview()->setRootLayerScaleTransform(root_layer_scale);
6187 bool RenderViewImpl::ScheduleFileChooser(
6188 const FileChooserParams& params,
6189 WebFileChooserCompletion* completion) {
6190 static const size_t kMaximumPendingFileChooseRequests = 4;
6191 if (file_chooser_completions_.size() > kMaximumPendingFileChooseRequests) {
6192 // This sanity check prevents too many file choose requests from getting
6193 // queued which could DoS the user. Getting these is most likely a
6194 // programming error (there are many ways to DoS the user so it's not
6195 // considered a "real" security check), either in JS requesting many file
6196 // choosers to pop up, or in a plugin.
6198 // TODO(brettw) we might possibly want to require a user gesture to open
6199 // a file picker, which will address this issue in a better way.
6200 return false;
6203 file_chooser_completions_.push_back(linked_ptr<PendingFileChooser>(
6204 new PendingFileChooser(params, completion)));
6205 if (file_chooser_completions_.size() == 1) {
6206 // Actually show the browse dialog when this is the first request.
6207 Send(new ViewHostMsg_RunFileChooser(routing_id_, params));
6209 return true;
6212 WebKit::WebGeolocationClient* RenderViewImpl::geolocationClient() {
6213 if (!geolocation_dispatcher_)
6214 geolocation_dispatcher_ = new GeolocationDispatcher(this);
6215 return geolocation_dispatcher_;
6218 WebKit::WebSpeechInputController* RenderViewImpl::speechInputController(
6219 WebKit::WebSpeechInputListener* listener) {
6220 #if defined(ENABLE_INPUT_SPEECH)
6221 if (!input_tag_speech_dispatcher_)
6222 input_tag_speech_dispatcher_ =
6223 new InputTagSpeechDispatcher(this, listener);
6224 #endif
6225 return input_tag_speech_dispatcher_;
6228 WebKit::WebSpeechRecognizer* RenderViewImpl::speechRecognizer() {
6229 if (!speech_recognition_dispatcher_)
6230 speech_recognition_dispatcher_ = new SpeechRecognitionDispatcher(this);
6231 return speech_recognition_dispatcher_;
6234 void RenderViewImpl::zoomLimitsChanged(double minimum_level,
6235 double maximum_level) {
6236 // For now, don't remember plugin zoom values. We don't want to mix them with
6237 // normal web content (i.e. a fixed layout plugin would usually want them
6238 // different).
6239 bool remember = !webview()->mainFrame()->document().isPluginDocument();
6241 int minimum_percent = static_cast<int>(
6242 ZoomLevelToZoomFactor(minimum_level) * 100);
6243 int maximum_percent = static_cast<int>(
6244 ZoomLevelToZoomFactor(maximum_level) * 100);
6246 Send(new ViewHostMsg_UpdateZoomLimits(
6247 routing_id_, minimum_percent, maximum_percent, remember));
6250 void RenderViewImpl::zoomLevelChanged() {
6251 bool remember = !webview()->mainFrame()->document().isPluginDocument();
6252 float zoom_level = webview()->zoomLevel();
6254 FOR_EACH_OBSERVER(RenderViewObserver, observers_, ZoomLevelChanged());
6256 // Tell the browser which url got zoomed so it can update the menu and the
6257 // saved values if necessary
6258 Send(new ViewHostMsg_DidZoomURL(
6259 routing_id_, zoom_level, remember,
6260 GURL(webview()->mainFrame()->document().url())));
6263 double RenderViewImpl::zoomLevelToZoomFactor(double zoom_level) const {
6264 return ZoomLevelToZoomFactor(zoom_level);
6267 double RenderViewImpl::zoomFactorToZoomLevel(double factor) const {
6268 return ZoomFactorToZoomLevel(factor);
6271 void RenderViewImpl::registerProtocolHandler(const WebString& scheme,
6272 const WebString& base_url,
6273 const WebString& url,
6274 const WebString& title) {
6275 bool user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
6276 GURL base(base_url);
6277 GURL absolute_url = base.Resolve(UTF16ToUTF8(url));
6278 if (base.GetOrigin() != absolute_url.GetOrigin()) {
6279 return;
6281 Send(new ViewHostMsg_RegisterProtocolHandler(routing_id_,
6282 UTF16ToUTF8(scheme),
6283 absolute_url,
6284 title,
6285 user_gesture));
6288 WebKit::WebPageVisibilityState RenderViewImpl::visibilityState() const {
6289 WebKit::WebPageVisibilityState current_state = is_hidden() ?
6290 WebKit::WebPageVisibilityStateHidden :
6291 WebKit::WebPageVisibilityStateVisible;
6292 WebKit::WebPageVisibilityState override_state = current_state;
6293 if (GetContentClient()->renderer()->
6294 ShouldOverridePageVisibilityState(this,
6295 &override_state))
6296 return override_state;
6297 return current_state;
6300 WebKit::WebUserMediaClient* RenderViewImpl::userMediaClient() {
6301 // This can happen in tests, in which case it's OK to return NULL.
6302 if (!InitializeMediaStreamClient())
6303 return NULL;
6305 return web_user_media_client_;
6308 WebKit::WebMIDIClient* RenderViewImpl::webMIDIClient() {
6309 if (!midi_dispatcher_)
6310 midi_dispatcher_ = new MIDIDispatcher(this);
6311 return midi_dispatcher_;
6314 void RenderViewImpl::draggableRegionsChanged() {
6315 FOR_EACH_OBSERVER(
6316 RenderViewObserver,
6317 observers_,
6318 DraggableRegionsChanged(webview()->mainFrame()));
6321 #if defined(OS_ANDROID)
6322 WebContentDetectionResult RenderViewImpl::detectContentAround(
6323 const WebHitTestResult& touch_hit) {
6324 DCHECK(!touch_hit.isNull());
6325 DCHECK(!touch_hit.node().isNull());
6326 DCHECK(touch_hit.node().isTextNode());
6328 // Process the position with all the registered content detectors until
6329 // a match is found. Priority is provided by their relative order.
6330 for (ContentDetectorList::const_iterator it = content_detectors_.begin();
6331 it != content_detectors_.end(); ++it) {
6332 ContentDetector::Result content = (*it)->FindTappedContent(touch_hit);
6333 if (content.valid) {
6334 return WebContentDetectionResult(content.content_boundaries,
6335 UTF8ToUTF16(content.text), content.intent_url);
6338 return WebContentDetectionResult();
6341 void RenderViewImpl::scheduleContentIntent(const WebURL& intent) {
6342 // Introduce a short delay so that the user can notice the content.
6343 base::MessageLoop::current()->PostDelayedTask(
6344 FROM_HERE,
6345 base::Bind(&RenderViewImpl::LaunchAndroidContentIntent,
6346 AsWeakPtr(),
6347 intent,
6348 expected_content_intent_id_),
6349 base::TimeDelta::FromMilliseconds(kContentIntentDelayMilliseconds));
6352 void RenderViewImpl::cancelScheduledContentIntents() {
6353 ++expected_content_intent_id_;
6356 void RenderViewImpl::LaunchAndroidContentIntent(const GURL& intent,
6357 size_t request_id) {
6358 if (request_id != expected_content_intent_id_)
6359 return;
6361 // Remove the content highlighting if any.
6362 scheduleComposite();
6364 if (!intent.is_empty())
6365 Send(new ViewHostMsg_StartContentIntent(routing_id_, intent));
6368 bool RenderViewImpl::openDateTimeChooser(
6369 const WebKit::WebDateTimeChooserParams& params,
6370 WebKit::WebDateTimeChooserCompletion* completion) {
6371 date_time_picker_client_.reset(
6372 new RendererDateTimePicker(this, params, completion));
6373 return date_time_picker_client_->Open();
6376 #endif // defined(OS_ANDROID)
6378 #if defined(OS_MACOSX)
6379 void RenderViewImpl::OnSelectPopupMenuItem(int selected_index) {
6380 if (external_popup_menu_ == NULL) {
6381 // Crash reports from the field indicate that we can be notified with a
6382 // NULL external popup menu (we probably get notified twice).
6383 // If you hit this please file a bug against jcivelli and include the page
6384 // and steps to repro.
6385 NOTREACHED();
6386 return;
6388 external_popup_menu_->DidSelectItem(selected_index);
6389 external_popup_menu_.reset();
6391 #endif
6393 #if defined(OS_ANDROID)
6394 void RenderViewImpl::OnSelectPopupMenuItems(
6395 bool canceled,
6396 const std::vector<int>& selected_indices) {
6397 // It is possible to receive more than one of these calls if the user presses
6398 // a select faster than it takes for the show-select-popup IPC message to make
6399 // it to the browser UI thread. Ignore the extra-messages.
6400 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
6401 if (!external_popup_menu_)
6402 return;
6404 external_popup_menu_->DidSelectItems(canceled, selected_indices);
6405 external_popup_menu_.reset();
6407 #endif
6409 void RenderViewImpl::OnContextMenuClosed(
6410 const CustomContextMenuContext& custom_context) {
6411 if (custom_context.request_id) {
6412 // External request, should be in our map.
6413 ContextMenuClient* client =
6414 pending_context_menus_.Lookup(custom_context.request_id);
6415 if (client) {
6416 client->OnMenuClosed(custom_context.request_id);
6417 pending_context_menus_.Remove(custom_context.request_id);
6419 } else {
6420 // Internal request, forward to WebKit.
6421 context_menu_node_.reset();
6425 void RenderViewImpl::OnShowContextMenu(const gfx::Point& location) {
6426 context_menu_source_type_ = ui::MENU_SOURCE_TOUCH_EDIT_MENU;
6427 touch_editing_context_menu_location_ = location;
6428 if (webview())
6429 webview()->showContextMenu();
6432 void RenderViewImpl::OnEnableViewSourceMode() {
6433 if (!webview())
6434 return;
6435 WebFrame* main_frame = webview()->mainFrame();
6436 if (!main_frame)
6437 return;
6438 main_frame->enableViewSourceMode(true);
6441 #if defined(OS_ANDROID)
6442 void RenderViewImpl::OnJavaBridgeInit() {
6443 DCHECK(!java_bridge_dispatcher_);
6444 java_bridge_dispatcher_ = new JavaBridgeDispatcher(this);
6446 #endif
6448 void RenderViewImpl::OnDisownOpener() {
6449 if (!webview())
6450 return;
6452 WebFrame* main_frame = webview()->mainFrame();
6453 if (main_frame && main_frame->opener())
6454 main_frame->setOpener(NULL);
6457 #if defined(OS_ANDROID)
6458 bool RenderViewImpl::didTapMultipleTargets(
6459 const WebKit::WebGestureEvent& event,
6460 const WebVector<WebRect>& target_rects) {
6461 // Never show a disambiguation popup when accessibility is enabled,
6462 // as this interferes with "touch exploration".
6463 if (accessibility_mode_ == AccessibilityModeComplete)
6464 return false;
6466 gfx::Rect finger_rect(
6467 event.x - event.data.tap.width / 2, event.y - event.data.tap.height / 2,
6468 event.data.tap.width, event.data.tap.height);
6469 gfx::Rect zoom_rect;
6470 float new_total_scale =
6471 DisambiguationPopupHelper::ComputeZoomAreaAndScaleFactor(
6472 finger_rect, target_rects, GetSize(),
6473 gfx::Rect(webview()->mainFrame()->visibleContentRect()).size(),
6474 device_scale_factor_ * webview()->pageScaleFactor(), &zoom_rect);
6475 if (!new_total_scale)
6476 return false;
6478 bool handled = false;
6479 switch (renderer_preferences_.tap_multiple_targets_strategy) {
6480 case TAP_MULTIPLE_TARGETS_STRATEGY_ZOOM:
6481 handled = webview()->zoomToMultipleTargetsRect(zoom_rect);
6482 break;
6483 case TAP_MULTIPLE_TARGETS_STRATEGY_POPUP: {
6484 gfx::Size canvas_size =
6485 gfx::ToCeiledSize(gfx::ScaleSize(zoom_rect.size(), new_total_scale));
6486 TransportDIB* transport_dib = NULL;
6488 scoped_ptr<skia::PlatformCanvas> canvas(
6489 RenderProcess::current()->GetDrawingCanvas(&transport_dib,
6490 gfx::Rect(canvas_size)));
6491 if (!canvas) {
6492 handled = false;
6493 break;
6496 // TODO(trchen): Cleanup the device scale factor mess.
6497 // device scale will be applied in WebKit
6498 // --> zoom_rect doesn't include device scale,
6499 // but WebKit will still draw on zoom_rect * device_scale_factor_
6500 canvas->scale(new_total_scale / device_scale_factor_,
6501 new_total_scale / device_scale_factor_);
6502 canvas->translate(-zoom_rect.x() * device_scale_factor_,
6503 -zoom_rect.y() * device_scale_factor_);
6505 webwidget_->paint(
6506 canvas.get(),
6507 zoom_rect,
6508 WebWidget::ForceSoftwareRenderingAndIgnoreGPUResidentContent);
6511 gfx::Rect physical_window_zoom_rect = gfx::ToEnclosingRect(
6512 ClientRectToPhysicalWindowRect(gfx::RectF(zoom_rect)));
6513 Send(new ViewHostMsg_ShowDisambiguationPopup(routing_id_,
6514 physical_window_zoom_rect,
6515 canvas_size,
6516 transport_dib->id()));
6517 handled = true;
6518 break;
6520 case TAP_MULTIPLE_TARGETS_STRATEGY_NONE:
6521 // No-op.
6522 break;
6525 return handled;
6527 #endif
6529 unsigned RenderViewImpl::GetLocalSessionHistoryLengthForTesting() const {
6530 return history_list_length_;
6533 void RenderViewImpl::SetFocusAndActivateForTesting(bool enable) {
6534 if (enable) {
6535 if (has_focus())
6536 return;
6537 OnSetActive(true);
6538 OnSetFocus(true);
6539 } else {
6540 if (!has_focus())
6541 return;
6542 OnSetFocus(false);
6543 OnSetActive(false);
6547 void RenderViewImpl::SetDeviceScaleFactorForTesting(float factor) {
6548 ViewMsg_Resize_Params params;
6549 params.screen_info = screen_info_;
6550 params.screen_info.deviceScaleFactor = factor;
6551 params.new_size = size();
6552 params.physical_backing_size =
6553 gfx::ToCeiledSize(gfx::ScaleSize(size(), factor));
6554 params.overdraw_bottom_height = 0.f;
6555 params.resizer_rect = WebRect();
6556 params.is_fullscreen = is_fullscreen();
6557 OnResize(params);
6560 void RenderViewImpl::EnableAutoResizeForTesting(const gfx::Size& min_size,
6561 const gfx::Size& max_size) {
6562 OnEnableAutoResize(min_size, max_size);
6565 void RenderViewImpl::DisableAutoResizeForTesting(const gfx::Size& new_size) {
6566 OnDisableAutoResize(new_size);
6569 void RenderViewImpl::SetMediaStreamClientForTesting(
6570 MediaStreamClient* media_stream_client) {
6571 DCHECK(!media_stream_client_);
6572 DCHECK(!web_user_media_client_);
6573 media_stream_client_ = media_stream_client;
6576 bool RenderViewImpl::IsPluginFullscreenAllowed() {
6577 return renderer_preferences_.plugin_fullscreen_allowed;
6580 void RenderViewImpl::OnReleaseDisambiguationPopupDIB(
6581 TransportDIB::Handle dib_handle) {
6582 TransportDIB* dib = TransportDIB::CreateWithHandle(dib_handle);
6583 RenderProcess::current()->ReleaseTransportDIB(dib);
6586 void RenderViewImpl::DidCommitCompositorFrame() {
6587 RenderWidget::DidCommitCompositorFrame();
6588 FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidCommitCompositorFrame());
6591 void RenderViewImpl::SendUpdateFaviconURL(const std::vector<FaviconURL>& urls) {
6592 if (!urls.empty())
6593 Send(new ViewHostMsg_UpdateFaviconURL(routing_id_, page_id_, urls));
6596 void RenderViewImpl::DidStopLoadingIcons() {
6597 int icon_types = WebIconURL::TypeFavicon;
6598 if (TouchEnabled())
6599 icon_types |= WebIconURL::TypeTouchPrecomposed | WebIconURL::TypeTouch;
6601 WebVector<WebIconURL> icon_urls =
6602 webview()->mainFrame()->iconURLs(icon_types);
6604 std::vector<FaviconURL> urls;
6605 for (size_t i = 0; i < icon_urls.size(); i++) {
6606 WebURL url = icon_urls[i].iconURL();
6607 if (!url.isEmpty())
6608 urls.push_back(FaviconURL(url,
6609 ToFaviconType(icon_urls[i].iconType())));
6611 SendUpdateFaviconURL(urls);
6614 } // namespace content