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/browser/web_contents/web_contents_impl.h"
9 #include "base/command_line.h"
10 #include "base/lazy_instance.h"
11 #include "base/location.h"
12 #include "base/logging.h"
13 #include "base/metrics/histogram.h"
14 #include "base/process/process.h"
15 #include "base/profiler/scoped_tracker.h"
16 #include "base/single_thread_task_runner.h"
17 #include "base/strings/string16.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/thread_task_runner_handle.h"
22 #include "base/time/time.h"
23 #include "base/trace_event/trace_event.h"
24 #include "components/mime_util/mime_util.h"
25 #include "content/browser/accessibility/accessibility_mode_helper.h"
26 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
27 #include "content/browser/bad_message.h"
28 #include "content/browser/browser_plugin/browser_plugin_embedder.h"
29 #include "content/browser/browser_plugin/browser_plugin_guest.h"
30 #include "content/browser/child_process_security_policy_impl.h"
31 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
32 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
33 #include "content/browser/download/download_stats.h"
34 #include "content/browser/download/mhtml_generation_manager.h"
35 #include "content/browser/download/save_package.h"
36 #include "content/browser/frame_host/cross_process_frame_connector.h"
37 #include "content/browser/frame_host/interstitial_page_impl.h"
38 #include "content/browser/frame_host/navigation_entry_impl.h"
39 #include "content/browser/frame_host/navigator_impl.h"
40 #include "content/browser/frame_host/render_frame_host_impl.h"
41 #include "content/browser/frame_host/render_widget_host_view_child_frame.h"
42 #include "content/browser/geolocation/geolocation_service_context.h"
43 #include "content/browser/host_zoom_map_impl.h"
44 #include "content/browser/loader/resource_dispatcher_host_impl.h"
45 #include "content/browser/manifest/manifest_manager_host.h"
46 #include "content/browser/media/audio_stream_monitor.h"
47 #include "content/browser/media/capture/web_contents_audio_muter.h"
48 #include "content/browser/message_port_message_filter.h"
49 #include "content/browser/plugin_content_origin_whitelist.h"
50 #include "content/browser/power_save_blocker_impl.h"
51 #include "content/browser/renderer_host/render_process_host_impl.h"
52 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
53 #include "content/browser/renderer_host/render_view_host_impl.h"
54 #include "content/browser/renderer_host/render_widget_host_impl.h"
55 #include "content/browser/renderer_host/render_widget_host_view_base.h"
56 #include "content/browser/screen_orientation/screen_orientation_dispatcher_host_impl.h"
57 #include "content/browser/site_instance_impl.h"
58 #include "content/browser/web_contents/web_contents_view_guest.h"
59 #include "content/browser/webui/generic_handler.h"
60 #include "content/browser/webui/web_ui_controller_factory_registry.h"
61 #include "content/browser/webui/web_ui_impl.h"
62 #include "content/common/browser_plugin/browser_plugin_constants.h"
63 #include "content/common/browser_plugin/browser_plugin_messages.h"
64 #include "content/common/frame_messages.h"
65 #include "content/common/image_messages.h"
66 #include "content/common/input_messages.h"
67 #include "content/common/ssl_status_serialization.h"
68 #include "content/common/view_messages.h"
69 #include "content/public/browser/ax_event_notification_details.h"
70 #include "content/public/browser/browser_context.h"
71 #include "content/public/browser/browser_plugin_guest_manager.h"
72 #include "content/public/browser/content_browser_client.h"
73 #include "content/public/browser/devtools_agent_host.h"
74 #include "content/public/browser/download_manager.h"
75 #include "content/public/browser/download_url_parameters.h"
76 #include "content/public/browser/invalidate_type.h"
77 #include "content/public/browser/javascript_dialog_manager.h"
78 #include "content/public/browser/load_from_memory_cache_details.h"
79 #include "content/public/browser/load_notification_details.h"
80 #include "content/public/browser/navigation_details.h"
81 #include "content/public/browser/notification_details.h"
82 #include "content/public/browser/notification_service.h"
83 #include "content/public/browser/render_widget_host_iterator.h"
84 #include "content/public/browser/resource_request_details.h"
85 #include "content/public/browser/screen_orientation_dispatcher_host.h"
86 #include "content/public/browser/storage_partition.h"
87 #include "content/public/browser/user_metrics.h"
88 #include "content/public/browser/web_contents_delegate.h"
89 #include "content/public/browser/web_contents_observer.h"
90 #include "content/public/common/bindings_policy.h"
91 #include "content/public/common/content_constants.h"
92 #include "content/public/common/content_switches.h"
93 #include "content/public/common/page_zoom.h"
94 #include "content/public/common/result_codes.h"
95 #include "content/public/common/security_style.h"
96 #include "content/public/common/url_constants.h"
97 #include "content/public/common/url_utils.h"
98 #include "content/public/common/web_preferences.h"
99 #include "net/base/net_util.h"
100 #include "net/http/http_cache.h"
101 #include "net/http/http_transaction_factory.h"
102 #include "net/url_request/url_request_context.h"
103 #include "net/url_request/url_request_context_getter.h"
104 #include "ui/base/layout.h"
105 #include "ui/gfx/display.h"
106 #include "ui/gfx/screen.h"
107 #include "ui/gl/gl_switches.h"
109 #if defined(ENABLE_BROWSER_CDMS)
110 #include "content/browser/media/media_web_contents_observer.h"
113 #if defined(OS_ANDROID)
114 #include "content/browser/android/content_video_view.h"
115 #include "content/browser/android/date_time_chooser_android.h"
116 #include "content/browser/android/media_players_observer.h"
117 #include "content/browser/media/android/browser_media_player_manager.h"
118 #include "content/browser/web_contents/web_contents_android.h"
121 #if defined(OS_MACOSX)
122 #include "base/mac/foundation_util.h"
128 const int kMinimumDelayBetweenLoadingUpdatesMS
= 100;
129 const char kDotGoogleDotCom
[] = ".google.com";
131 #if defined(OS_ANDROID)
132 const char kWebContentsAndroidKey
[] = "web_contents_android";
135 base::LazyInstance
<std::vector
<WebContentsImpl::CreatedCallback
> >
136 g_created_callbacks
= LAZY_INSTANCE_INITIALIZER
;
138 static int StartDownload(RenderFrameHost
* rfh
,
141 uint32_t max_bitmap_size
,
143 static int g_next_image_download_id
= 0;
144 rfh
->Send(new ImageMsg_DownloadImage(rfh
->GetRoutingID(),
145 ++g_next_image_download_id
,
150 return g_next_image_download_id
;
153 void NotifyCacheOnIO(
154 scoped_refptr
<net::URLRequestContextGetter
> request_context
,
156 const std::string
& http_method
) {
157 net::HttpCache
* cache
= request_context
->GetURLRequestContext()->
158 http_transaction_factory()->GetCache();
160 cache
->OnExternalCacheHit(url
, http_method
);
163 // Helper function for retrieving all the sites in a frame tree.
164 bool CollectSites(BrowserContext
* context
,
165 std::set
<GURL
>* sites
,
166 FrameTreeNode
* node
) {
167 sites
->insert(SiteInstance::GetSiteForURL(context
, node
->current_url()));
171 bool ForEachFrameInternal(
172 const base::Callback
<void(RenderFrameHost
*)>& on_frame
,
173 FrameTreeNode
* node
) {
174 on_frame
.Run(node
->current_frame_host());
178 bool ForEachPendingFrameInternal(
179 const base::Callback
<void(RenderFrameHost
*)>& on_frame
,
180 FrameTreeNode
* node
) {
181 RenderFrameHost
* pending_frame_host
=
182 node
->render_manager()->pending_frame_host();
183 if (pending_frame_host
)
184 on_frame
.Run(pending_frame_host
);
188 void SendToAllFramesInternal(IPC::Message
* message
, RenderFrameHost
* rfh
) {
189 IPC::Message
* message_copy
= new IPC::Message(*message
);
190 message_copy
->set_routing_id(rfh
->GetRoutingID());
191 rfh
->Send(message_copy
);
194 void AddRenderWidgetHostViewToSet(std::set
<RenderWidgetHostView
*>* set
,
195 RenderFrameHost
* rfh
) {
196 RenderWidgetHostView
* rwhv
= static_cast<RenderFrameHostImpl
*>(rfh
)
199 ->GetRenderWidgetHostView();
203 void SetAccessibilityModeOnFrame(AccessibilityMode mode
,
204 RenderFrameHost
* frame_host
) {
205 static_cast<RenderFrameHostImpl
*>(frame_host
)->SetAccessibilityMode(mode
);
210 WebContents
* WebContents::Create(const WebContents::CreateParams
& params
) {
211 FrameTreeNode
* opener_node
= nullptr;
212 if (params
.opener_render_frame_id
!= MSG_ROUTING_NONE
) {
213 RenderFrameHostImpl
* opener_rfh
= RenderFrameHostImpl::FromID(
214 params
.opener_render_process_id
, params
.opener_render_frame_id
);
216 opener_node
= opener_rfh
->frame_tree_node();
218 return WebContentsImpl::CreateWithOpener(params
, opener_node
);
221 WebContents
* WebContents::CreateWithSessionStorage(
222 const WebContents::CreateParams
& params
,
223 const SessionStorageNamespaceMap
& session_storage_namespace_map
) {
224 WebContentsImpl
* new_contents
= new WebContentsImpl(params
.browser_context
);
226 for (SessionStorageNamespaceMap::const_iterator it
=
227 session_storage_namespace_map
.begin();
228 it
!= session_storage_namespace_map
.end();
230 new_contents
->GetController()
231 .SetSessionStorageNamespace(it
->first
, it
->second
.get());
234 new_contents
->Init(params
);
238 void WebContentsImpl::FriendZone::AddCreatedCallbackForTesting(
239 const CreatedCallback
& callback
) {
240 g_created_callbacks
.Get().push_back(callback
);
243 void WebContentsImpl::FriendZone::RemoveCreatedCallbackForTesting(
244 const CreatedCallback
& callback
) {
245 for (size_t i
= 0; i
< g_created_callbacks
.Get().size(); ++i
) {
246 if (g_created_callbacks
.Get().at(i
).Equals(callback
)) {
247 g_created_callbacks
.Get().erase(g_created_callbacks
.Get().begin() + i
);
253 WebContents
* WebContents::FromRenderViewHost(const RenderViewHost
* rvh
) {
254 return rvh
->GetDelegate()->GetAsWebContents();
257 WebContents
* WebContents::FromRenderFrameHost(RenderFrameHost
* rfh
) {
258 RenderFrameHostImpl
* rfh_impl
= static_cast<RenderFrameHostImpl
*>(rfh
);
261 return rfh_impl
->delegate()->GetAsWebContents();
264 // WebContentsImpl::DestructionObserver ----------------------------------------
266 class WebContentsImpl::DestructionObserver
: public WebContentsObserver
{
268 DestructionObserver(WebContentsImpl
* owner
, WebContents
* watched_contents
)
269 : WebContentsObserver(watched_contents
),
273 // WebContentsObserver:
274 void WebContentsDestroyed() override
{
275 owner_
->OnWebContentsDestroyed(
276 static_cast<WebContentsImpl
*>(web_contents()));
280 WebContentsImpl
* owner_
;
282 DISALLOW_COPY_AND_ASSIGN(DestructionObserver
);
285 WebContentsImpl::ColorChooserInfo::ColorChooserInfo(int render_process_id
,
287 ColorChooser
* chooser
,
289 : render_process_id(render_process_id
),
290 render_frame_id(render_frame_id
),
292 identifier(identifier
) {
295 WebContentsImpl::ColorChooserInfo::~ColorChooserInfo() {
298 // WebContentsImpl -------------------------------------------------------------
300 WebContentsImpl::WebContentsImpl(BrowserContext
* browser_context
)
302 controller_(this, browser_context
),
303 render_view_host_delegate_view_(NULL
),
304 created_with_opener_(false),
306 accessible_parent_(NULL
),
308 frame_tree_(new NavigatorImpl(&controller_
, this),
314 is_load_to_different_document_(false),
315 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING
),
316 crashed_error_code_(0),
317 waiting_for_response_(false),
318 load_state_(net::LOAD_STATE_IDLE
, base::string16()),
321 displayed_insecure_content_(false),
322 has_accessed_initial_document_(false),
323 theme_color_(SK_ColorTRANSPARENT
),
324 last_sent_theme_color_(SK_ColorTRANSPARENT
),
325 did_first_visually_non_empty_paint_(false),
327 should_normally_be_visible_(true),
328 is_being_destroyed_(false),
329 notify_disconnection_(false),
330 dialog_manager_(NULL
),
331 is_showing_before_unload_dialog_(false),
332 last_active_time_(base::TimeTicks::Now()),
333 closed_by_user_gesture_(false),
334 minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor
* 100)),
335 maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor
* 100)),
336 render_view_message_source_(NULL
),
337 render_frame_message_source_(NULL
),
338 fullscreen_widget_routing_id_(MSG_ROUTING_NONE
),
339 fullscreen_widget_had_focus_at_shutdown_(false),
341 force_disable_overscroll_content_(false),
342 last_dialog_suppressed_(false),
343 geolocation_service_context_(new GeolocationServiceContext()),
345 BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()),
346 virtual_keyboard_requested_(false),
347 loading_weak_factory_(this) {
348 frame_tree_
.SetFrameRemoveListener(
349 base::Bind(&WebContentsImpl::OnFrameRemoved
,
350 base::Unretained(this)));
351 #if defined(ENABLE_BROWSER_CDMS)
352 media_web_contents_observer_
.reset(new MediaWebContentsObserver(this));
355 #if defined(OS_ANDROID)
356 audio_state_provider_
.reset(new MediaPlayersObserver(this));
358 audio_state_provider_
.reset(new AudioStreamMonitor(this));
362 WebContentsImpl::~WebContentsImpl() {
363 is_being_destroyed_
= true;
365 // Delete all RFH pending shutdown, which will lead the corresponding RVH to
366 // shutdown and be deleted as well.
368 base::Bind(&RenderFrameHostManager::ClearRFHsPendingShutdown
));
370 ClearAllPowerSaveBlockers();
372 for (std::set
<RenderWidgetHostImpl
*>::iterator iter
=
373 created_widgets_
.begin(); iter
!= created_widgets_
.end(); ++iter
) {
374 (*iter
)->DetachDelegate();
376 created_widgets_
.clear();
378 // Clear out any JavaScript state.
380 dialog_manager_
->ResetDialogState(this);
382 if (color_chooser_info_
.get())
383 color_chooser_info_
->chooser
->End();
385 NotifyDisconnected();
387 // Notify any observer that have a reference on this WebContents.
388 NotificationService::current()->Notify(
389 NOTIFICATION_WEB_CONTENTS_DESTROYED
,
390 Source
<WebContents
>(this),
391 NotificationService::NoDetails());
393 // Destroy all frame tree nodes except for the root; this notifies observers.
394 frame_tree_
.root()->ResetForNewProcess();
395 GetRenderManager()->ResetProxyHosts();
397 // Manually call the observer methods for the root frame tree node.
398 RenderFrameHostManager
* root
= GetRenderManager();
400 if (root
->pending_frame_host())
401 root
->pending_frame_host()->SetRenderFrameCreated(false);
402 root
->current_frame_host()->SetRenderFrameCreated(false);
404 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
405 FrameDeleted(root
->current_frame_host()));
407 if (root
->pending_render_view_host()) {
408 FOR_EACH_OBSERVER(WebContentsObserver
,
410 RenderViewDeleted(root
->pending_render_view_host()));
413 FOR_EACH_OBSERVER(WebContentsObserver
,
415 RenderViewDeleted(root
->current_host()));
417 FOR_EACH_OBSERVER(WebContentsObserver
,
419 WebContentsDestroyed());
421 FOR_EACH_OBSERVER(WebContentsObserver
,
427 STLDeleteContainerPairSecondPointers(destruction_observers_
.begin(),
428 destruction_observers_
.end());
431 WebContentsImpl
* WebContentsImpl::CreateWithOpener(
432 const WebContents::CreateParams
& params
,
433 FrameTreeNode
* opener
) {
434 TRACE_EVENT0("browser", "WebContentsImpl::CreateWithOpener");
435 WebContentsImpl
* new_contents
= new WebContentsImpl(params
.browser_context
);
437 if (!params
.opener_suppressed
&& opener
) {
438 new_contents
->GetFrameTree()->root()->SetOpener(opener
);
439 new_contents
->created_with_opener_
= true;
442 // This may be true even when opener is null, such as when opening blocked
444 if (params
.created_with_opener
)
445 new_contents
->created_with_opener_
= true;
447 if (params
.guest_delegate
) {
448 // This makes |new_contents| act as a guest.
449 // For more info, see comment above class BrowserPluginGuest.
450 BrowserPluginGuest::Create(new_contents
, params
.guest_delegate
);
451 // We are instantiating a WebContents for browser plugin. Set its subframe
453 new_contents
->is_subframe_
= true;
455 new_contents
->Init(params
);
460 std::vector
<WebContentsImpl
*> WebContentsImpl::GetAllWebContents() {
461 std::vector
<WebContentsImpl
*> result
;
462 scoped_ptr
<RenderWidgetHostIterator
> widgets(
463 RenderWidgetHostImpl::GetRenderWidgetHosts());
464 std::set
<WebContentsImpl
*> web_contents_set
;
465 while (RenderWidgetHost
* rwh
= widgets
->GetNextHost()) {
466 if (!rwh
->IsRenderView())
468 RenderViewHost
* rvh
= RenderViewHost::From(rwh
);
471 WebContents
* web_contents
= WebContents::FromRenderViewHost(rvh
);
474 WebContentsImpl
* wci
= static_cast<WebContentsImpl
*>(web_contents
);
475 if (web_contents_set
.find(wci
) == web_contents_set
.end()) {
476 web_contents_set
.insert(wci
);
477 result
.push_back(wci
);
484 WebContentsImpl
* WebContentsImpl::FromFrameTreeNode(
485 FrameTreeNode
* frame_tree_node
) {
486 return static_cast<WebContentsImpl
*>(
487 WebContents::FromRenderFrameHost(frame_tree_node
->current_frame_host()));
490 RenderFrameHostManager
* WebContentsImpl::GetRenderManagerForTesting() {
491 return GetRenderManager();
494 bool WebContentsImpl::OnMessageReceived(RenderViewHost
* render_view_host
,
495 const IPC::Message
& message
) {
496 return OnMessageReceived(render_view_host
, NULL
, message
);
499 bool WebContentsImpl::OnMessageReceived(RenderViewHost
* render_view_host
,
500 RenderFrameHost
* render_frame_host
,
501 const IPC::Message
& message
) {
502 DCHECK(render_view_host
|| render_frame_host
);
504 static_cast<WebUIImpl
*>(GetWebUI())->OnMessageReceived(message
)) {
508 base::ObserverListBase
<WebContentsObserver
>::Iterator
it(&observers_
);
509 WebContentsObserver
* observer
;
510 if (render_frame_host
) {
511 while ((observer
= it
.GetNext()) != NULL
)
512 if (observer
->OnMessageReceived(message
, render_frame_host
))
515 while ((observer
= it
.GetNext()) != NULL
)
516 if (observer
->OnMessageReceived(message
))
520 // Message handlers should be aware of which
521 // RenderViewHost/RenderFrameHost sent the message, which is temporarily
522 // stored in render_(view|frame)_message_source_.
523 if (render_frame_host
)
524 render_frame_message_source_
= render_frame_host
;
526 render_view_message_source_
= render_view_host
;
529 IPC_BEGIN_MESSAGE_MAP(WebContentsImpl
, message
)
530 IPC_MESSAGE_HANDLER(FrameHostMsg_DomOperationResponse
,
531 OnDomOperationResponse
)
532 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeThemeColor
,
534 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishDocumentLoad
,
535 OnDocumentLoadedInFrame
)
536 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishLoad
, OnDidFinishLoad
)
537 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenColorChooser
, OnOpenColorChooser
)
538 IPC_MESSAGE_HANDLER(FrameHostMsg_EndColorChooser
, OnEndColorChooser
)
539 IPC_MESSAGE_HANDLER(FrameHostMsg_SetSelectedColorInColorChooser
,
540 OnSetSelectedColorInColorChooser
)
541 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPlayingNotification
,
542 OnMediaPlayingNotification
)
543 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPausedNotification
,
544 OnMediaPausedNotification
)
545 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFirstVisuallyNonEmptyPaint
,
546 OnFirstVisuallyNonEmptyPaint
)
547 IPC_MESSAGE_HANDLER(ViewHostMsg_DidLoadResourceFromMemoryCache
,
548 OnDidLoadResourceFromMemoryCache
)
549 IPC_MESSAGE_HANDLER(ViewHostMsg_DidDisplayInsecureContent
,
550 OnDidDisplayInsecureContent
)
551 IPC_MESSAGE_HANDLER(ViewHostMsg_DidRunInsecureContent
,
552 OnDidRunInsecureContent
)
553 IPC_MESSAGE_HANDLER(ViewHostMsg_GoToEntryAtOffset
, OnGoToEntryAtOffset
)
554 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateZoomLimits
, OnUpdateZoomLimits
)
555 IPC_MESSAGE_HANDLER(ViewHostMsg_EnumerateDirectory
, OnEnumerateDirectory
)
556 IPC_MESSAGE_HANDLER(ViewHostMsg_RegisterProtocolHandler
,
557 OnRegisterProtocolHandler
)
558 IPC_MESSAGE_HANDLER(ViewHostMsg_UnregisterProtocolHandler
,
559 OnUnregisterProtocolHandler
)
560 IPC_MESSAGE_HANDLER(ViewHostMsg_Find_Reply
, OnFindReply
)
561 IPC_MESSAGE_HANDLER(ViewHostMsg_AppCacheAccessed
, OnAppCacheAccessed
)
562 IPC_MESSAGE_HANDLER(ViewHostMsg_WebUISend
, OnWebUISend
)
563 #if defined(ENABLE_PLUGINS)
564 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceCreated
,
565 OnPepperInstanceCreated
)
566 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceDeleted
,
567 OnPepperInstanceDeleted
)
568 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung
, OnPepperPluginHung
)
569 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed
, OnPluginCrashed
)
570 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission
,
571 OnRequestPpapiBrokerPermission
)
572 IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_Attach
,
573 OnBrowserPluginMessage(render_frame_host
,
576 IPC_MESSAGE_HANDLER(ImageHostMsg_DidDownloadImage
, OnDidDownloadImage
)
577 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateFaviconURL
, OnUpdateFaviconURL
)
578 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowValidationMessage
,
579 OnShowValidationMessage
)
580 IPC_MESSAGE_HANDLER(ViewHostMsg_HideValidationMessage
,
581 OnHideValidationMessage
)
582 IPC_MESSAGE_HANDLER(ViewHostMsg_MoveValidationMessage
,
583 OnMoveValidationMessage
)
584 #if defined(OS_ANDROID)
585 IPC_MESSAGE_HANDLER(ViewHostMsg_FindMatchRects_Reply
,
586 OnFindMatchRectsReply
)
587 IPC_MESSAGE_HANDLER(ViewHostMsg_OpenDateTimeDialog
,
588 OnOpenDateTimeDialog
)
590 IPC_MESSAGE_UNHANDLED(handled
= false)
591 IPC_END_MESSAGE_MAP()
592 render_view_message_source_
= NULL
;
593 render_frame_message_source_
= NULL
;
598 bool WebContentsImpl::HasValidFrameSource() {
599 if (!render_frame_message_source_
) {
600 DCHECK(render_view_message_source_
);
601 bad_message::ReceivedBadMessage(GetRenderProcessHost(),
602 bad_message::WC_INVALID_FRAME_SOURCE
);
609 void WebContentsImpl::RunFileChooser(
610 RenderViewHost
* render_view_host
,
611 const FileChooserParams
& params
) {
613 delegate_
->RunFileChooser(this, params
);
616 NavigationControllerImpl
& WebContentsImpl::GetController() {
620 const NavigationControllerImpl
& WebContentsImpl::GetController() const {
624 BrowserContext
* WebContentsImpl::GetBrowserContext() const {
625 return controller_
.GetBrowserContext();
628 const GURL
& WebContentsImpl::GetURL() const {
629 // We may not have a navigation entry yet.
630 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
631 return entry
? entry
->GetVirtualURL() : GURL::EmptyGURL();
634 const GURL
& WebContentsImpl::GetVisibleURL() const {
635 // We may not have a navigation entry yet.
636 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
637 return entry
? entry
->GetVirtualURL() : GURL::EmptyGURL();
640 const GURL
& WebContentsImpl::GetLastCommittedURL() const {
641 // We may not have a navigation entry yet.
642 NavigationEntry
* entry
= controller_
.GetLastCommittedEntry();
643 return entry
? entry
->GetVirtualURL() : GURL::EmptyGURL();
646 WebContentsDelegate
* WebContentsImpl::GetDelegate() {
650 void WebContentsImpl::SetDelegate(WebContentsDelegate
* delegate
) {
651 // TODO(cbentzel): remove this debugging code?
652 if (delegate
== delegate_
)
655 delegate_
->Detach(this);
656 delegate_
= delegate
;
658 delegate_
->Attach(this);
659 // Ensure the visible RVH reflects the new delegate's preferences.
661 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
665 RenderProcessHost
* WebContentsImpl::GetRenderProcessHost() const {
666 RenderViewHostImpl
* host
= GetRenderManager()->current_host();
667 return host
? host
->GetProcess() : NULL
;
670 RenderFrameHostImpl
* WebContentsImpl::GetMainFrame() {
671 return frame_tree_
.root()->current_frame_host();
674 RenderFrameHostImpl
* WebContentsImpl::GetFocusedFrame() {
675 FrameTreeNode
* focused_node
= frame_tree_
.GetFocusedFrame();
678 return focused_node
->current_frame_host();
681 void WebContentsImpl::ForEachFrame(
682 const base::Callback
<void(RenderFrameHost
*)>& on_frame
) {
683 frame_tree_
.ForEach(base::Bind(&ForEachFrameInternal
, on_frame
));
686 void WebContentsImpl::SendToAllFrames(IPC::Message
* message
) {
687 ForEachFrame(base::Bind(&SendToAllFramesInternal
, message
));
691 RenderViewHostImpl
* WebContentsImpl::GetRenderViewHost() const {
692 return GetRenderManager()->current_host();
695 int WebContentsImpl::GetRoutingID() const {
696 if (!GetRenderViewHost())
697 return MSG_ROUTING_NONE
;
699 return GetRenderViewHost()->GetRoutingID();
702 void WebContentsImpl::CancelActiveAndPendingDialogs() {
704 dialog_manager_
->CancelActiveAndPendingDialogs(this);
705 if (browser_plugin_embedder_
)
706 browser_plugin_embedder_
->CancelGuestDialogs();
709 int WebContentsImpl::GetFullscreenWidgetRoutingID() const {
710 return fullscreen_widget_routing_id_
;
713 void WebContentsImpl::ClosePage() {
714 GetRenderViewHost()->ClosePage();
717 RenderWidgetHostView
* WebContentsImpl::GetRenderWidgetHostView() const {
718 return GetRenderManager()->GetRenderWidgetHostView();
721 RenderWidgetHostView
* WebContentsImpl::GetFullscreenRenderWidgetHostView()
723 RenderWidgetHost
* const widget_host
=
724 RenderWidgetHostImpl::FromID(GetRenderProcessHost()->GetID(),
725 GetFullscreenWidgetRoutingID());
726 return widget_host
? widget_host
->GetView() : NULL
;
729 WebContentsView
* WebContentsImpl::GetView() const {
733 SkColor
WebContentsImpl::GetThemeColor() const {
737 void WebContentsImpl::SetAccessibilityMode(AccessibilityMode mode
) {
738 if (mode
== accessibility_mode_
)
741 accessibility_mode_
= mode
;
743 base::Bind(&ForEachFrameInternal
,
744 base::Bind(&SetAccessibilityModeOnFrame
, mode
)));
746 base::Bind(&ForEachPendingFrameInternal
,
747 base::Bind(&SetAccessibilityModeOnFrame
, mode
)));
750 void WebContentsImpl::AddAccessibilityMode(AccessibilityMode mode
) {
751 SetAccessibilityMode(AddAccessibilityModeTo(accessibility_mode_
, mode
));
754 void WebContentsImpl::RemoveAccessibilityMode(AccessibilityMode mode
) {
755 SetAccessibilityMode(RemoveAccessibilityModeFrom(accessibility_mode_
, mode
));
758 void WebContentsImpl::RequestAXTreeSnapshot(AXTreeSnapshotCallback callback
) {
759 // TODO(dmazzoni): http://crbug.com/475608 This only returns the
760 // accessibility tree from the main frame and everything in the
761 // same site instance.
762 GetMainFrame()->RequestAXTreeSnapshot(callback
);
765 WebUI
* WebContentsImpl::CreateWebUI(const GURL
& url
) {
766 WebUIImpl
* web_ui
= new WebUIImpl(this);
767 WebUIController
* controller
= WebUIControllerFactoryRegistry::GetInstance()->
768 CreateWebUIControllerForURL(web_ui
, url
);
770 web_ui
->AddMessageHandler(new GenericHandler());
771 web_ui
->SetController(controller
);
779 WebUI
* WebContentsImpl::GetWebUI() const {
780 return GetRenderManager()->web_ui() ? GetRenderManager()->web_ui()
781 : GetRenderManager()->pending_web_ui();
784 WebUI
* WebContentsImpl::GetCommittedWebUI() const {
785 return GetRenderManager()->web_ui();
788 void WebContentsImpl::SetUserAgentOverride(const std::string
& override
) {
789 if (GetUserAgentOverride() == override
)
792 renderer_preferences_
.user_agent_override
= override
;
794 // Send the new override string to the renderer.
795 RenderViewHost
* host
= GetRenderViewHost();
797 host
->SyncRendererPrefs();
799 // Reload the page if a load is currently in progress to avoid having
800 // different parts of the page loaded using different user agents.
801 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
802 if (is_loading_
&& entry
!= NULL
&& entry
->GetIsOverridingUserAgent())
803 controller_
.ReloadIgnoringCache(true);
805 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
806 UserAgentOverrideSet(override
));
809 const std::string
& WebContentsImpl::GetUserAgentOverride() const {
810 return renderer_preferences_
.user_agent_override
;
813 void WebContentsImpl::EnableTreeOnlyAccessibilityMode() {
814 AddAccessibilityMode(AccessibilityModeTreeOnly
);
817 bool WebContentsImpl::IsTreeOnlyAccessibilityModeForTesting() const {
818 return accessibility_mode_
== AccessibilityModeTreeOnly
;
821 bool WebContentsImpl::IsFullAccessibilityModeForTesting() const {
822 return accessibility_mode_
== AccessibilityModeComplete
;
826 void WebContentsImpl::SetParentNativeViewAccessible(
827 gfx::NativeViewAccessible accessible_parent
) {
828 accessible_parent_
= accessible_parent
;
829 RenderFrameHostImpl
* rfh
= GetMainFrame();
831 rfh
->SetParentNativeViewAccessible(accessible_parent
);
835 const base::string16
& WebContentsImpl::GetTitle() const {
836 // Transient entries take precedence. They are used for interstitial pages
837 // that are shown on top of existing pages.
838 NavigationEntry
* entry
= controller_
.GetTransientEntry();
839 std::string accept_languages
=
840 GetContentClient()->browser()->GetAcceptLangs(
841 GetBrowserContext());
843 return entry
->GetTitleForDisplay(accept_languages
);
845 WebUI
* our_web_ui
= GetRenderManager()->pending_web_ui() ?
846 GetRenderManager()->pending_web_ui() : GetRenderManager()->web_ui();
848 // Don't override the title in view source mode.
849 entry
= controller_
.GetVisibleEntry();
850 if (!(entry
&& entry
->IsViewSourceMode())) {
851 // Give the Web UI the chance to override our title.
852 const base::string16
& title
= our_web_ui
->GetOverriddenTitle();
858 // We use the title for the last committed entry rather than a pending
859 // navigation entry. For example, when the user types in a URL, we want to
860 // keep the old page's title until the new load has committed and we get a new
862 entry
= controller_
.GetLastCommittedEntry();
864 // We make an exception for initial navigations.
865 if (controller_
.IsInitialNavigation()) {
866 // We only want to use the title from the visible entry in one of two cases:
867 // 1. There's already a committed entry for an initial navigation, in which
868 // case we are doing a history navigation in a new tab (e.g., Ctrl+Back).
869 // 2. The pending entry has been explicitly assigned a title to display.
871 // If there's no last committed entry and no assigned title, we should fall
872 // back to |page_title_when_no_navigation_entry_| rather than showing the
875 (controller_
.GetVisibleEntry() &&
876 !controller_
.GetVisibleEntry()->GetTitle().empty())) {
877 entry
= controller_
.GetVisibleEntry();
882 return entry
->GetTitleForDisplay(accept_languages
);
885 // |page_title_when_no_navigation_entry_| is finally used
886 // if no title cannot be retrieved.
887 return page_title_when_no_navigation_entry_
;
890 int32
WebContentsImpl::GetMaxPageID() {
891 return GetMaxPageIDForSiteInstance(GetSiteInstance());
894 int32
WebContentsImpl::GetMaxPageIDForSiteInstance(
895 SiteInstance
* site_instance
) {
896 if (max_page_ids_
.find(site_instance
->GetId()) == max_page_ids_
.end())
897 max_page_ids_
[site_instance
->GetId()] = -1;
899 return max_page_ids_
[site_instance
->GetId()];
902 void WebContentsImpl::UpdateMaxPageID(int32 page_id
) {
903 UpdateMaxPageIDForSiteInstance(GetSiteInstance(), page_id
);
906 void WebContentsImpl::UpdateMaxPageIDForSiteInstance(
907 SiteInstance
* site_instance
, int32 page_id
) {
908 if (GetMaxPageIDForSiteInstance(site_instance
) < page_id
)
909 max_page_ids_
[site_instance
->GetId()] = page_id
;
912 void WebContentsImpl::CopyMaxPageIDsFrom(WebContents
* web_contents
) {
913 WebContentsImpl
* contents
= static_cast<WebContentsImpl
*>(web_contents
);
914 max_page_ids_
= contents
->max_page_ids_
;
917 SiteInstanceImpl
* WebContentsImpl::GetSiteInstance() const {
918 return GetRenderManager()->current_host()->GetSiteInstance();
921 SiteInstanceImpl
* WebContentsImpl::GetPendingSiteInstance() const {
922 RenderViewHostImpl
* dest_rvh
=
923 GetRenderManager()->pending_render_view_host() ?
924 GetRenderManager()->pending_render_view_host() :
925 GetRenderManager()->current_host();
926 return dest_rvh
->GetSiteInstance();
929 bool WebContentsImpl::IsLoading() const {
933 bool WebContentsImpl::IsLoadingToDifferentDocument() const {
934 return is_loading_
&& is_load_to_different_document_
;
937 bool WebContentsImpl::IsWaitingForResponse() const {
938 return waiting_for_response_
&& is_load_to_different_document_
;
941 const net::LoadStateWithParam
& WebContentsImpl::GetLoadState() const {
945 const base::string16
& WebContentsImpl::GetLoadStateHost() const {
946 return load_state_host_
;
949 uint64
WebContentsImpl::GetUploadSize() const {
953 uint64
WebContentsImpl::GetUploadPosition() const {
954 return upload_position_
;
957 std::set
<GURL
> WebContentsImpl::GetSitesInTab() const {
958 std::set
<GURL
> sites
;
959 frame_tree_
.ForEach(base::Bind(&CollectSites
,
960 base::Unretained(GetBrowserContext()),
961 base::Unretained(&sites
)));
965 const std::string
& WebContentsImpl::GetEncoding() const {
966 return canonical_encoding_
;
969 bool WebContentsImpl::DisplayedInsecureContent() const {
970 return displayed_insecure_content_
;
973 void WebContentsImpl::IncrementCapturerCount(const gfx::Size
& capture_size
) {
974 DCHECK(!is_being_destroyed_
);
976 DVLOG(1) << "There are now " << capturer_count_
977 << " capturing(s) of WebContentsImpl@" << this;
979 // Note: This provides a hint to upstream code to size the views optimally
980 // for quality (e.g., to avoid scaling).
981 if (!capture_size
.IsEmpty() && preferred_size_for_capture_
.IsEmpty()) {
982 preferred_size_for_capture_
= capture_size
;
983 OnPreferredSizeChanged(preferred_size_
);
986 // Ensure that all views are un-occluded before capture begins.
990 void WebContentsImpl::DecrementCapturerCount() {
992 DVLOG(1) << "There are now " << capturer_count_
993 << " capturing(s) of WebContentsImpl@" << this;
994 DCHECK_LE(0, capturer_count_
);
996 if (is_being_destroyed_
)
999 if (capturer_count_
== 0) {
1000 const gfx::Size old_size
= preferred_size_for_capture_
;
1001 preferred_size_for_capture_
= gfx::Size();
1002 OnPreferredSizeChanged(old_size
);
1006 DVLOG(1) << "Executing delayed WasHidden().";
1011 int WebContentsImpl::GetCapturerCount() const {
1012 return capturer_count_
;
1015 bool WebContentsImpl::IsAudioMuted() const {
1016 return audio_muter_
.get() && audio_muter_
->is_muting();
1019 void WebContentsImpl::SetAudioMuted(bool mute
) {
1020 DVLOG(1) << "SetAudioMuted(mute=" << mute
<< "), was " << IsAudioMuted()
1021 << " for WebContentsImpl@" << this;
1023 if (mute
== IsAudioMuted())
1028 audio_muter_
.reset(new WebContentsAudioMuter(this));
1029 audio_muter_
->StartMuting();
1031 DCHECK(audio_muter_
);
1032 audio_muter_
->StopMuting();
1035 // Notification for UI updates in response to the changed muting state.
1036 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB
);
1039 bool WebContentsImpl::IsCrashed() const {
1040 return (crashed_status_
== base::TERMINATION_STATUS_PROCESS_CRASHED
||
1041 crashed_status_
== base::TERMINATION_STATUS_ABNORMAL_TERMINATION
||
1042 crashed_status_
== base::TERMINATION_STATUS_PROCESS_WAS_KILLED
1043 #if defined(OS_CHROMEOS)
1045 crashed_status_
== base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM
1050 void WebContentsImpl::SetIsCrashed(base::TerminationStatus status
,
1052 if (status
== crashed_status_
)
1055 crashed_status_
= status
;
1056 crashed_error_code_
= error_code
;
1057 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB
);
1060 base::TerminationStatus
WebContentsImpl::GetCrashedStatus() const {
1061 return crashed_status_
;
1064 bool WebContentsImpl::IsBeingDestroyed() const {
1065 return is_being_destroyed_
;
1068 void WebContentsImpl::NotifyNavigationStateChanged(
1069 InvalidateTypes changed_flags
) {
1070 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1072 tracked_objects::ScopedTracker
tracking_profile(
1073 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1074 "466285 WebContentsImpl::NotifyNavigationStateChanged"));
1075 // Create and release the audio power save blocker depending on whether the
1076 // tab is actively producing audio or not.
1077 if ((changed_flags
& INVALIDATE_TYPE_TAB
) &&
1078 audio_state_provider_
->IsAudioStateAvailable()) {
1079 if (WasRecentlyAudible()) {
1080 if (!audio_power_save_blocker_
)
1081 CreateAudioPowerSaveBlocker();
1083 audio_power_save_blocker_
.reset();
1088 delegate_
->NavigationStateChanged(this, changed_flags
);
1091 base::TimeTicks
WebContentsImpl::GetLastActiveTime() const {
1092 return last_active_time_
;
1095 void WebContentsImpl::SetLastActiveTime(base::TimeTicks last_active_time
) {
1096 last_active_time_
= last_active_time
;
1099 void WebContentsImpl::WasShown() {
1100 controller_
.SetActive(true);
1102 for (RenderWidgetHostView
* view
: GetRenderWidgetHostViewsInTree()) {
1105 #if defined(OS_MACOSX)
1106 view
->SetActive(true);
1111 last_active_time_
= base::TimeTicks::Now();
1113 // The resize rect might have changed while this was inactive -- send the new
1114 // one to make sure it's up to date.
1115 RenderViewHostImpl
* rvh
= GetRenderViewHost();
1117 rvh
->ResizeRectChanged(GetRootWindowResizerRect());
1119 // Restore power save blocker if there are active video players running.
1120 if (!active_video_players_
.empty() && !video_power_save_blocker_
)
1121 CreateVideoPowerSaveBlocker();
1123 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, WasShown());
1125 should_normally_be_visible_
= true;
1128 void WebContentsImpl::WasHidden() {
1129 // If there are entities capturing screenshots or video (e.g., mirroring),
1130 // don't activate the "disable rendering" optimization.
1131 if (capturer_count_
== 0) {
1132 // |GetRenderViewHost()| can be NULL if the user middle clicks a link to
1133 // open a tab in the background, then closes the tab before selecting it.
1134 // This is because closing the tab calls WebContentsImpl::Destroy(), which
1135 // removes the |GetRenderViewHost()|; then when we actually destroy the
1136 // window, OnWindowPosChanged() notices and calls WasHidden() (which
1138 for (RenderWidgetHostView
* view
: GetRenderWidgetHostViewsInTree()) {
1143 // Release any video power save blockers held as video is not visible.
1144 video_power_save_blocker_
.reset();
1147 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, WasHidden());
1149 should_normally_be_visible_
= false;
1152 void WebContentsImpl::WasOccluded() {
1153 if (capturer_count_
> 0)
1156 for (RenderWidgetHostView
* view
: GetRenderWidgetHostViewsInTree()) {
1158 view
->WasOccluded();
1162 void WebContentsImpl::WasUnOccluded() {
1163 for (RenderWidgetHostView
* view
: GetRenderWidgetHostViewsInTree()) {
1165 view
->WasUnOccluded();
1169 bool WebContentsImpl::NeedToFireBeforeUnload() {
1170 // TODO(creis): Should we fire even for interstitial pages?
1171 return WillNotifyDisconnection() && !ShowingInterstitialPage() &&
1172 !GetRenderViewHost()->SuddenTerminationAllowed();
1175 void WebContentsImpl::DispatchBeforeUnload(bool for_cross_site_transition
) {
1176 GetMainFrame()->DispatchBeforeUnload(for_cross_site_transition
);
1179 void WebContentsImpl::Stop() {
1180 GetRenderManager()->Stop();
1181 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, NavigationStopped());
1184 WebContents
* WebContentsImpl::Clone() {
1185 // We use our current SiteInstance since the cloned entry will use it anyway.
1186 // We pass our own opener so that the cloned page can access it if it was set
1188 CreateParams
create_params(GetBrowserContext(), GetSiteInstance());
1189 create_params
.initial_size
= GetContainerBounds().size();
1190 WebContentsImpl
* tc
=
1191 CreateWithOpener(create_params
, frame_tree_
.root()->opener());
1192 tc
->GetController().CopyStateFrom(controller_
);
1193 FOR_EACH_OBSERVER(WebContentsObserver
,
1195 DidCloneToNewWebContents(this, tc
));
1199 void WebContentsImpl::Observe(int type
,
1200 const NotificationSource
& source
,
1201 const NotificationDetails
& details
) {
1203 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED
: {
1204 RenderWidgetHost
* host
= Source
<RenderWidgetHost
>(source
).ptr();
1205 RenderWidgetHostView
* view
= host
->GetView();
1206 if (view
== GetFullscreenRenderWidgetHostView()) {
1207 // We cannot just call view_->RestoreFocus() here. On some platforms,
1208 // attempting to focus the currently-invisible WebContentsView will be
1209 // flat-out ignored. Therefore, this boolean is used to track whether
1210 // we will request focus after the fullscreen widget has been
1212 fullscreen_widget_had_focus_at_shutdown_
= (view
&& view
->HasFocus());
1214 for (PendingWidgetViews::iterator i
= pending_widget_views_
.begin();
1215 i
!= pending_widget_views_
.end(); ++i
) {
1216 if (host
->GetView() == i
->second
) {
1217 pending_widget_views_
.erase(i
);
1229 WebContents
* WebContentsImpl::GetWebContents() {
1233 void WebContentsImpl::Init(const WebContents::CreateParams
& params
) {
1234 // This is set before initializing the render manager since
1235 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
1236 // it should be hidden.
1237 should_normally_be_visible_
= !params
.initially_hidden
;
1239 // Either both routing ids can be given, or neither can be.
1240 DCHECK((params
.routing_id
== MSG_ROUTING_NONE
&&
1241 params
.main_frame_routing_id
== MSG_ROUTING_NONE
) ||
1242 (params
.routing_id
!= MSG_ROUTING_NONE
&&
1243 params
.main_frame_routing_id
!= MSG_ROUTING_NONE
));
1244 GetRenderManager()->Init(
1245 params
.browser_context
, params
.site_instance
, params
.routing_id
,
1246 params
.main_frame_routing_id
);
1247 frame_tree_
.root()->SetFrameName(params
.main_frame_name
);
1249 WebContentsViewDelegate
* delegate
=
1250 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
1252 if (browser_plugin_guest_
) {
1253 scoped_ptr
<WebContentsView
> platform_view(CreateWebContentsView(
1254 this, delegate
, &render_view_host_delegate_view_
));
1256 WebContentsViewGuest
* rv
= new WebContentsViewGuest(
1257 this, browser_plugin_guest_
.get(), platform_view
.Pass(),
1258 render_view_host_delegate_view_
);
1259 render_view_host_delegate_view_
= rv
;
1262 // Regular WebContentsView.
1263 view_
.reset(CreateWebContentsView(
1264 this, delegate
, &render_view_host_delegate_view_
));
1266 CHECK(render_view_host_delegate_view_
);
1269 gfx::Size initial_size
= params
.initial_size
;
1270 view_
->CreateView(initial_size
, params
.context
);
1272 #if defined(ENABLE_PLUGINS)
1273 plugin_content_origin_whitelist_
.reset(
1274 new PluginContentOriginWhitelist(this));
1277 registrar_
.Add(this,
1278 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED
,
1279 NotificationService::AllBrowserContextsAndSources());
1281 screen_orientation_dispatcher_host_
.reset(
1282 new ScreenOrientationDispatcherHostImpl(this));
1284 manifest_manager_host_
.reset(new ManifestManagerHost(this));
1286 #if defined(OS_ANDROID)
1287 date_time_chooser_
.reset(new DateTimeChooserAndroid());
1290 // BrowserPluginGuest::Init needs to be called after this WebContents has
1291 // a RenderWidgetHostViewGuest. That is, |view_->CreateView| above.
1292 if (browser_plugin_guest_
)
1293 browser_plugin_guest_
->Init();
1295 for (size_t i
= 0; i
< g_created_callbacks
.Get().size(); i
++)
1296 g_created_callbacks
.Get().at(i
).Run(this);
1298 // If the WebContents creation was renderer-initiated, it means that the
1299 // corresponding RenderView and main RenderFrame have already been created.
1300 // Ensure observers are notified about this.
1301 if (params
.renderer_initiated_creation
) {
1302 GetRenderViewHost()->set_renderer_initialized(true);
1303 RenderViewCreated(GetRenderViewHost());
1304 GetRenderManager()->current_frame_host()->SetRenderFrameCreated(true);
1307 // Ensure that observers are notified of the creation of this WebContents's
1308 // main RenderFrameHost. It must be done here for main frames, since the
1309 // NotifySwappedFromRenderManager expects view_ to already be created and that
1310 // happens after RenderFrameHostManager::Init.
1311 NotifySwappedFromRenderManager(
1312 nullptr, GetRenderManager()->current_frame_host(), true);
1315 void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl
* web_contents
) {
1316 RemoveDestructionObserver(web_contents
);
1318 // Clear a pending contents that has been closed before being shown.
1319 for (PendingContents::iterator iter
= pending_contents_
.begin();
1320 iter
!= pending_contents_
.end();
1322 if (iter
->second
!= web_contents
)
1324 pending_contents_
.erase(iter
);
1330 void WebContentsImpl::AddDestructionObserver(WebContentsImpl
* web_contents
) {
1331 if (!ContainsKey(destruction_observers_
, web_contents
)) {
1332 destruction_observers_
[web_contents
] =
1333 new DestructionObserver(this, web_contents
);
1337 void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl
* web_contents
) {
1338 DestructionObservers::iterator iter
=
1339 destruction_observers_
.find(web_contents
);
1340 if (iter
!= destruction_observers_
.end()) {
1341 delete destruction_observers_
[web_contents
];
1342 destruction_observers_
.erase(iter
);
1346 void WebContentsImpl::AddObserver(WebContentsObserver
* observer
) {
1347 observers_
.AddObserver(observer
);
1350 void WebContentsImpl::RemoveObserver(WebContentsObserver
* observer
) {
1351 observers_
.RemoveObserver(observer
);
1354 std::set
<RenderWidgetHostView
*>
1355 WebContentsImpl::GetRenderWidgetHostViewsInTree() {
1356 std::set
<RenderWidgetHostView
*> set
;
1357 if (ShowingInterstitialPage()) {
1358 set
.insert(GetRenderWidgetHostView());
1361 base::Bind(&AddRenderWidgetHostViewToSet
, base::Unretained(&set
)));
1366 void WebContentsImpl::Activate() {
1368 delegate_
->ActivateContents(this);
1371 void WebContentsImpl::Deactivate() {
1373 delegate_
->DeactivateContents(this);
1376 void WebContentsImpl::LostCapture() {
1378 delegate_
->LostCapture();
1381 void WebContentsImpl::RenderWidgetDeleted(
1382 RenderWidgetHostImpl
* render_widget_host
) {
1383 if (is_being_destroyed_
) {
1384 // |created_widgets_| might have been destroyed.
1388 std::set
<RenderWidgetHostImpl
*>::iterator iter
=
1389 created_widgets_
.find(render_widget_host
);
1390 if (iter
!= created_widgets_
.end())
1391 created_widgets_
.erase(iter
);
1393 if (render_widget_host
&&
1394 render_widget_host
->GetRoutingID() == fullscreen_widget_routing_id_
) {
1395 if (delegate_
&& delegate_
->EmbedsFullscreenWidget())
1396 delegate_
->ExitFullscreenModeForTab(this);
1397 FOR_EACH_OBSERVER(WebContentsObserver
,
1399 DidDestroyFullscreenWidget(
1400 fullscreen_widget_routing_id_
));
1401 fullscreen_widget_routing_id_
= MSG_ROUTING_NONE
;
1402 if (fullscreen_widget_had_focus_at_shutdown_
)
1403 view_
->RestoreFocus();
1407 void WebContentsImpl::RenderWidgetGotFocus(
1408 RenderWidgetHostImpl
* render_widget_host
) {
1409 // Notify the observers if an embedded fullscreen widget was focused.
1410 if (delegate_
&& render_widget_host
&& delegate_
->EmbedsFullscreenWidget() &&
1411 render_widget_host
->GetView() == GetFullscreenRenderWidgetHostView()) {
1412 NotifyWebContentsFocused();
1416 void WebContentsImpl::RenderWidgetWasResized(
1417 RenderWidgetHostImpl
* render_widget_host
,
1418 bool width_changed
) {
1419 RenderFrameHostImpl
* rfh
= GetMainFrame();
1420 if (!rfh
|| render_widget_host
!= rfh
->GetRenderWidgetHost())
1423 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1424 MainFrameWasResized(width_changed
));
1427 void WebContentsImpl::ScreenInfoChanged() {
1428 if (browser_plugin_embedder_
)
1429 browser_plugin_embedder_
->ScreenInfoChanged();
1432 bool WebContentsImpl::PreHandleKeyboardEvent(
1433 const NativeWebKeyboardEvent
& event
,
1434 bool* is_keyboard_shortcut
) {
1436 delegate_
->PreHandleKeyboardEvent(this, event
, is_keyboard_shortcut
);
1439 void WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent
& event
) {
1440 if (browser_plugin_embedder_
&&
1441 browser_plugin_embedder_
->HandleKeyboardEvent(event
)) {
1445 delegate_
->HandleKeyboardEvent(this, event
);
1448 bool WebContentsImpl::HandleWheelEvent(
1449 const blink::WebMouseWheelEvent
& event
) {
1450 #if !defined(OS_MACOSX)
1451 // On platforms other than Mac, control+mousewheel may change zoom. On Mac,
1452 // this isn't done for two reasons:
1453 // -the OS already has a gesture to do this through pinch-zoom
1454 // -if a user starts an inertial scroll, let's go, and presses control
1455 // (i.e. control+tab) then the OS's buffered scroll events will come in
1456 // with control key set which isn't what the user wants
1457 if (delegate_
&& event
.wheelTicksY
&&
1458 (event
.modifiers
& blink::WebInputEvent::ControlKey
) &&
1460 delegate_
->ContentsZoomChange(event
.wheelTicksY
> 0);
1467 bool WebContentsImpl::PreHandleGestureEvent(
1468 const blink::WebGestureEvent
& event
) {
1469 return delegate_
&& delegate_
->PreHandleGestureEvent(this, event
);
1472 void WebContentsImpl::EnterFullscreenMode(const GURL
& origin
) {
1473 // This method is being called to enter renderer-initiated fullscreen mode.
1474 // Make sure any existing fullscreen widget is shut down first.
1475 RenderWidgetHostView
* const widget_view
= GetFullscreenRenderWidgetHostView();
1477 RenderWidgetHostImpl::From(widget_view
->GetRenderWidgetHost())->Shutdown();
1480 delegate_
->EnterFullscreenModeForTab(this, origin
);
1482 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1483 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1486 void WebContentsImpl::ExitFullscreenMode() {
1487 // This method is being called to leave renderer-initiated fullscreen mode.
1488 // Make sure any existing fullscreen widget is shut down first.
1489 RenderWidgetHostView
* const widget_view
= GetFullscreenRenderWidgetHostView();
1491 RenderWidgetHostImpl::From(widget_view
->GetRenderWidgetHost())->Shutdown();
1493 #if defined(OS_ANDROID)
1494 ContentVideoView
* video_view
= ContentVideoView::GetInstance();
1495 if (video_view
!= NULL
)
1496 video_view
->OnExitFullscreen();
1500 delegate_
->ExitFullscreenModeForTab(this);
1502 // Ensure web contents exit fullscreen state by sending a resize message,
1503 // which includes the fullscreen state. This is required for the situation
1504 // of the browser moving the view into a fullscreen state "browser fullscreen"
1505 // and then the contents entering "tab fullscreen". Exiting the contents
1506 // "tab fullscreen" then won't have the side effect of the view resizing,
1507 // hence the explicit call here is required.
1508 if (RenderWidgetHostView
* rwh_view
= GetRenderWidgetHostView()) {
1509 if (RenderWidgetHost
* render_widget_host
= rwh_view
->GetRenderWidgetHost())
1510 render_widget_host
->WasResized();
1513 FOR_EACH_OBSERVER(WebContentsObserver
,
1515 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1518 bool WebContentsImpl::IsFullscreenForCurrentTab() const {
1519 return delegate_
? delegate_
->IsFullscreenForTabOrPending(this) : false;
1522 blink::WebDisplayMode
WebContentsImpl::GetDisplayMode() const {
1523 return delegate_
? delegate_
->GetDisplayMode(this)
1524 : blink::WebDisplayModeBrowser
;
1527 void WebContentsImpl::RequestToLockMouse(bool user_gesture
,
1528 bool last_unlocked_by_target
) {
1530 delegate_
->RequestToLockMouse(this, user_gesture
, last_unlocked_by_target
);
1532 GotResponseToLockMouseRequest(false);
1536 void WebContentsImpl::LostMouseLock() {
1538 delegate_
->LostMouseLock();
1541 void WebContentsImpl::CreateNewWindow(
1542 int render_process_id
,
1544 int main_frame_route_id
,
1545 const ViewHostMsg_CreateWindow_Params
& params
,
1546 SessionStorageNamespace
* session_storage_namespace
) {
1547 // We usually create the new window in the same BrowsingInstance (group of
1548 // script-related windows), by passing in the current SiteInstance. However,
1549 // if the opener is being suppressed (in a non-guest), we create a new
1550 // SiteInstance in its own BrowsingInstance.
1551 bool is_guest
= BrowserPluginGuest::IsGuest(this);
1553 // If the opener is to be suppressed, the new window can be in any process.
1554 // Since routing ids are process specific, we must not have one passed in
1555 // as argument here.
1556 DCHECK(!params
.opener_suppressed
|| route_id
== MSG_ROUTING_NONE
);
1558 scoped_refptr
<SiteInstance
> site_instance
=
1559 params
.opener_suppressed
&& !is_guest
?
1560 SiteInstance::CreateForURL(GetBrowserContext(), params
.target_url
) :
1563 // A message to create a new window can only come from the active process for
1564 // this WebContentsImpl instance. If any other process sends the request,
1565 // it is invalid and the process must be terminated.
1566 if (GetRenderProcessHost()->GetID() != render_process_id
) {
1567 RenderProcessHost
* rph
= RenderProcessHost::FromID(render_process_id
);
1568 base::ProcessHandle process_handle
= rph
->GetHandle();
1569 if (process_handle
!= base::kNullProcessHandle
) {
1571 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWindow"));
1572 rph
->Shutdown(RESULT_CODE_KILLED
, false);
1577 // We must assign the SessionStorageNamespace before calling Init().
1579 // http://crbug.com/142685
1580 const std::string
& partition_id
=
1581 GetContentClient()->browser()->
1582 GetStoragePartitionIdForSite(GetBrowserContext(),
1583 site_instance
->GetSiteURL());
1584 StoragePartition
* partition
= BrowserContext::GetStoragePartition(
1585 GetBrowserContext(), site_instance
.get());
1586 DOMStorageContextWrapper
* dom_storage_context
=
1587 static_cast<DOMStorageContextWrapper
*>(partition
->GetDOMStorageContext());
1588 SessionStorageNamespaceImpl
* session_storage_namespace_impl
=
1589 static_cast<SessionStorageNamespaceImpl
*>(session_storage_namespace
);
1590 CHECK(session_storage_namespace_impl
->IsFromContext(dom_storage_context
));
1593 !delegate_
->ShouldCreateWebContents(this,
1595 main_frame_route_id
,
1596 params
.window_container_type
,
1600 session_storage_namespace
)) {
1601 if (route_id
!= MSG_ROUTING_NONE
&&
1602 !RenderViewHost::FromID(render_process_id
, route_id
)) {
1603 // If the embedder didn't create a WebContents for this route, we need to
1604 // delete the RenderView that had already been created.
1605 Send(new ViewMsg_Close(route_id
));
1607 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(route_id
);
1608 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(
1609 main_frame_route_id
);
1613 // Create the new web contents. This will automatically create the new
1614 // WebContentsView. In the future, we may want to create the view separately.
1615 CreateParams
create_params(GetBrowserContext(), site_instance
.get());
1616 create_params
.routing_id
= route_id
;
1617 create_params
.main_frame_routing_id
= main_frame_route_id
;
1618 create_params
.main_frame_name
= base::UTF16ToUTF8(params
.frame_name
);
1619 create_params
.opener_render_process_id
= GetRenderProcessHost()->GetID();
1620 create_params
.opener_render_frame_id
= params
.opener_render_frame_id
;
1621 create_params
.opener_suppressed
= params
.opener_suppressed
;
1622 if (params
.disposition
== NEW_BACKGROUND_TAB
)
1623 create_params
.initially_hidden
= true;
1624 create_params
.renderer_initiated_creation
=
1625 main_frame_route_id
!= MSG_ROUTING_NONE
;
1627 WebContentsImpl
* new_contents
= NULL
;
1629 create_params
.context
= view_
->GetNativeView();
1630 create_params
.initial_size
= GetContainerBounds().size();
1631 new_contents
= static_cast<WebContentsImpl
*>(
1632 WebContents::Create(create_params
));
1634 new_contents
= GetBrowserPluginGuest()->CreateNewGuestWindow(create_params
);
1636 new_contents
->GetController().SetSessionStorageNamespace(
1638 session_storage_namespace
);
1640 // Save the window for later if we're not suppressing the opener (since it
1641 // will be shown immediately).
1642 if (!params
.opener_suppressed
) {
1644 WebContentsView
* new_view
= new_contents
->view_
.get();
1646 // TODO(brettw): It seems bogus that we have to call this function on the
1647 // newly created object and give it one of its own member variables.
1648 new_view
->CreateViewForWidget(new_contents
->GetRenderViewHost(), false);
1650 // Save the created window associated with the route so we can show it
1652 DCHECK_NE(MSG_ROUTING_NONE
, route_id
);
1653 pending_contents_
[route_id
] = new_contents
;
1654 AddDestructionObserver(new_contents
);
1658 delegate_
->WebContentsCreated(
1659 this, params
.opener_render_frame_id
, params
.frame_name
,
1660 params
.target_url
, new_contents
);
1663 if (params
.opener_suppressed
) {
1664 // When the opener is suppressed, the original renderer cannot access the
1665 // new window. As a result, we need to show and navigate the window here.
1666 bool was_blocked
= false;
1668 gfx::Rect initial_rect
;
1669 delegate_
->AddNewContents(
1670 this, new_contents
, params
.disposition
, initial_rect
,
1671 params
.user_gesture
, &was_blocked
);
1674 OpenURLParams
open_params(params
.target_url
,
1677 ui::PAGE_TRANSITION_LINK
,
1678 true /* is_renderer_initiated */);
1679 open_params
.user_gesture
= params
.user_gesture
;
1680 new_contents
->OpenURL(open_params
);
1685 void WebContentsImpl::CreateNewWidget(int render_process_id
,
1687 blink::WebPopupType popup_type
) {
1688 CreateNewWidget(render_process_id
, route_id
, false, popup_type
);
1691 void WebContentsImpl::CreateNewFullscreenWidget(int render_process_id
,
1693 CreateNewWidget(render_process_id
, route_id
, true, blink::WebPopupTypeNone
);
1696 void WebContentsImpl::CreateNewWidget(int render_process_id
,
1699 blink::WebPopupType popup_type
) {
1700 RenderProcessHost
* process
= GetRenderProcessHost();
1701 // A message to create a new widget can only come from the active process for
1702 // this WebContentsImpl instance. If any other process sends the request,
1703 // it is invalid and the process must be terminated.
1704 if (process
->GetID() != render_process_id
) {
1705 RenderProcessHost
* rph
= RenderProcessHost::FromID(render_process_id
);
1706 base::ProcessHandle process_handle
= rph
->GetHandle();
1707 if (process_handle
!= base::kNullProcessHandle
) {
1709 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWidget"));
1710 rph
->Shutdown(RESULT_CODE_KILLED
, false);
1715 RenderWidgetHostImpl
* widget_host
=
1716 new RenderWidgetHostImpl(this, process
, route_id
, IsHidden());
1717 created_widgets_
.insert(widget_host
);
1719 RenderWidgetHostViewBase
* widget_view
=
1720 static_cast<RenderWidgetHostViewBase
*>(
1721 view_
->CreateViewForPopupWidget(widget_host
));
1724 if (!is_fullscreen
) {
1725 // Popups should not get activated.
1726 widget_view
->SetPopupType(popup_type
);
1728 // Save the created widget associated with the route so we can show it later.
1729 pending_widget_views_
[route_id
] = widget_view
;
1731 #if defined(OS_MACOSX)
1732 // A RenderWidgetHostViewMac has lifetime scoped to the view. We'll retain it
1733 // to allow it to survive the trip without being hosted.
1734 base::mac::NSObjectRetain(widget_view
->GetNativeView());
1738 void WebContentsImpl::ShowCreatedWindow(int route_id
,
1739 WindowOpenDisposition disposition
,
1740 const gfx::Rect
& initial_rect
,
1741 bool user_gesture
) {
1742 WebContentsImpl
* contents
= GetCreatedWindow(route_id
);
1744 WebContentsDelegate
* delegate
= GetDelegate();
1745 if (!delegate
|| delegate
->ShouldResumeRequestsForCreatedWindow())
1746 contents
->ResumeLoadingCreatedWebContents();
1749 delegate
->AddNewContents(
1750 this, contents
, disposition
, initial_rect
, user_gesture
, NULL
);
1755 void WebContentsImpl::ShowCreatedWidget(int route_id
,
1756 const gfx::Rect
& initial_rect
) {
1757 ShowCreatedWidget(route_id
, false, initial_rect
);
1760 void WebContentsImpl::ShowCreatedFullscreenWidget(int route_id
) {
1761 ShowCreatedWidget(route_id
, true, gfx::Rect());
1764 void WebContentsImpl::ShowCreatedWidget(int route_id
,
1766 const gfx::Rect
& initial_rect
) {
1767 RenderWidgetHostViewBase
* widget_host_view
=
1768 static_cast<RenderWidgetHostViewBase
*>(GetCreatedWidget(route_id
));
1769 if (!widget_host_view
)
1772 RenderWidgetHostView
* view
= NULL
;
1773 BrowserPluginGuest
* guest
= GetBrowserPluginGuest();
1774 if (guest
&& guest
->embedder_web_contents()) {
1775 view
= guest
->embedder_web_contents()->GetRenderWidgetHostView();
1777 view
= GetRenderWidgetHostView();
1780 if (is_fullscreen
) {
1781 DCHECK_EQ(MSG_ROUTING_NONE
, fullscreen_widget_routing_id_
);
1782 view_
->StoreFocus();
1783 fullscreen_widget_routing_id_
= route_id
;
1784 if (delegate_
&& delegate_
->EmbedsFullscreenWidget()) {
1785 widget_host_view
->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
1786 delegate_
->EnterFullscreenModeForTab(this, GURL());
1788 widget_host_view
->InitAsFullscreen(view
);
1790 FOR_EACH_OBSERVER(WebContentsObserver
,
1792 DidShowFullscreenWidget(route_id
));
1793 if (!widget_host_view
->HasFocus())
1794 widget_host_view
->Focus();
1796 widget_host_view
->InitAsPopup(view
, initial_rect
);
1799 RenderWidgetHostImpl
* render_widget_host_impl
=
1800 RenderWidgetHostImpl::From(widget_host_view
->GetRenderWidgetHost());
1801 render_widget_host_impl
->Init();
1802 // Only allow privileged mouse lock for fullscreen render widget, which is
1803 // used to implement Pepper Flash fullscreen.
1804 render_widget_host_impl
->set_allow_privileged_mouse_lock(is_fullscreen
);
1806 #if defined(OS_MACOSX)
1807 // A RenderWidgetHostViewMac has lifetime scoped to the view. Now that it's
1808 // properly embedded (or purposefully ignored) we can release the retain we
1809 // took in CreateNewWidget().
1810 base::mac::NSObjectRelease(widget_host_view
->GetNativeView());
1814 WebContentsImpl
* WebContentsImpl::GetCreatedWindow(int route_id
) {
1815 PendingContents::iterator iter
= pending_contents_
.find(route_id
);
1817 // Certain systems can block the creation of new windows. If we didn't succeed
1818 // in creating one, just return NULL.
1819 if (iter
== pending_contents_
.end()) {
1823 WebContentsImpl
* new_contents
= iter
->second
;
1824 pending_contents_
.erase(route_id
);
1825 RemoveDestructionObserver(new_contents
);
1827 // Don't initialize the guest WebContents immediately.
1828 if (BrowserPluginGuest::IsGuest(new_contents
))
1829 return new_contents
;
1831 if (!new_contents
->GetRenderProcessHost()->HasConnection() ||
1832 !new_contents
->GetRenderViewHost()->GetView())
1835 return new_contents
;
1838 RenderWidgetHostView
* WebContentsImpl::GetCreatedWidget(int route_id
) {
1839 PendingWidgetViews::iterator iter
= pending_widget_views_
.find(route_id
);
1840 if (iter
== pending_widget_views_
.end()) {
1845 RenderWidgetHostView
* widget_host_view
= iter
->second
;
1846 pending_widget_views_
.erase(route_id
);
1848 RenderWidgetHost
* widget_host
= widget_host_view
->GetRenderWidgetHost();
1849 if (!widget_host
->GetProcess()->HasConnection()) {
1850 // The view has gone away or the renderer crashed. Nothing to do.
1854 return widget_host_view
;
1857 void WebContentsImpl::RequestMediaAccessPermission(
1858 const MediaStreamRequest
& request
,
1859 const MediaResponseCallback
& callback
) {
1861 delegate_
->RequestMediaAccessPermission(this, request
, callback
);
1863 callback
.Run(MediaStreamDevices(),
1864 MEDIA_DEVICE_FAILED_DUE_TO_SHUTDOWN
,
1865 scoped_ptr
<MediaStreamUI
>());
1869 bool WebContentsImpl::CheckMediaAccessPermission(const GURL
& security_origin
,
1870 MediaStreamType type
) {
1871 DCHECK(type
== MEDIA_DEVICE_AUDIO_CAPTURE
||
1872 type
== MEDIA_DEVICE_VIDEO_CAPTURE
);
1874 delegate_
->CheckMediaAccessPermission(this, security_origin
, type
);
1877 SessionStorageNamespace
* WebContentsImpl::GetSessionStorageNamespace(
1878 SiteInstance
* instance
) {
1879 return controller_
.GetSessionStorageNamespace(instance
);
1882 SessionStorageNamespaceMap
WebContentsImpl::GetSessionStorageNamespaceMap() {
1883 return controller_
.GetSessionStorageNamespaceMap();
1886 FrameTree
* WebContentsImpl::GetFrameTree() {
1887 return &frame_tree_
;
1890 void WebContentsImpl::SetIsVirtualKeyboardRequested(bool requested
) {
1891 virtual_keyboard_requested_
= requested
;
1894 bool WebContentsImpl::IsVirtualKeyboardRequested() {
1895 return virtual_keyboard_requested_
;
1898 AccessibilityMode
WebContentsImpl::GetAccessibilityMode() const {
1899 return accessibility_mode_
;
1902 void WebContentsImpl::AccessibilityEventReceived(
1903 const std::vector
<AXEventNotificationDetails
>& details
) {
1905 WebContentsObserver
, observers_
, AccessibilityEventReceived(details
));
1908 RenderFrameHost
* WebContentsImpl::GetGuestByInstanceID(
1909 RenderFrameHost
* render_frame_host
,
1910 int browser_plugin_instance_id
) {
1911 BrowserPluginGuestManager
* guest_manager
=
1912 GetBrowserContext()->GetGuestManager();
1916 WebContents
* guest
= guest_manager
->GetGuestByInstanceID(
1917 render_frame_host
->GetProcess()->GetID(), browser_plugin_instance_id
);
1921 return guest
->GetMainFrame();
1924 GeolocationServiceContext
* WebContentsImpl::GetGeolocationServiceContext() {
1925 return geolocation_service_context_
.get();
1928 void WebContentsImpl::OnShowValidationMessage(
1929 const gfx::Rect
& anchor_in_root_view
,
1930 const base::string16
& main_text
,
1931 const base::string16
& sub_text
) {
1933 delegate_
->ShowValidationMessage(
1934 this, anchor_in_root_view
, main_text
, sub_text
);
1937 void WebContentsImpl::OnHideValidationMessage() {
1939 delegate_
->HideValidationMessage(this);
1942 void WebContentsImpl::OnMoveValidationMessage(
1943 const gfx::Rect
& anchor_in_root_view
) {
1945 delegate_
->MoveValidationMessage(this, anchor_in_root_view
);
1948 void WebContentsImpl::DidSendScreenRects(RenderWidgetHostImpl
* rwh
) {
1949 if (browser_plugin_embedder_
)
1950 browser_plugin_embedder_
->DidSendScreenRects();
1953 BrowserAccessibilityManager
*
1954 WebContentsImpl::GetRootBrowserAccessibilityManager() {
1955 RenderFrameHostImpl
* rfh
= GetMainFrame();
1956 return rfh
? rfh
->browser_accessibility_manager() : nullptr;
1959 BrowserAccessibilityManager
*
1960 WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
1961 RenderFrameHostImpl
* rfh
= GetMainFrame();
1962 return rfh
? rfh
->GetOrCreateBrowserAccessibilityManager() : nullptr;
1965 void WebContentsImpl::UpdatePreferredSize(const gfx::Size
& pref_size
) {
1966 const gfx::Size old_size
= GetPreferredSize();
1967 preferred_size_
= pref_size
;
1968 OnPreferredSizeChanged(old_size
);
1971 void WebContentsImpl::ResizeDueToAutoResize(const gfx::Size
& new_size
) {
1973 delegate_
->ResizeDueToAutoResize(this, new_size
);
1976 WebContents
* WebContentsImpl::OpenURL(const OpenURLParams
& params
) {
1980 WebContents
* new_contents
= delegate_
->OpenURLFromTab(this, params
);
1981 return new_contents
;
1984 bool WebContentsImpl::Send(IPC::Message
* message
) {
1985 if (!GetRenderViewHost()) {
1990 return GetRenderViewHost()->Send(message
);
1993 bool WebContentsImpl::NavigateToPendingEntry(
1994 NavigationController::ReloadType reload_type
) {
1995 FrameTreeNode
* node
= frame_tree_
.root();
1997 // Navigate in the FrameTreeNode specified in the pending entry, if any. This
1998 // is currently only used in --site-per-process and tests.
1999 // TODO(creis): Remove this method and NavigationEntryImpl::frame_tree_node_id
2000 // by using FrameNavigationEntries instead. See https://crbug.com/236848.
2001 NavigationEntryImpl
* pending_entry
= controller_
.GetPendingEntry();
2002 if (pending_entry
->frame_tree_node_id() != -1) {
2003 FrameTreeNode
* subframe
=
2004 frame_tree_
.FindByID(pending_entry
->frame_tree_node_id());
2010 return node
->navigator()->NavigateToPendingEntry(node
, reload_type
);
2013 void WebContentsImpl::RenderFrameForInterstitialPageCreated(
2014 RenderFrameHost
* render_frame_host
) {
2015 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2016 RenderFrameForInterstitialPageCreated(render_frame_host
));
2019 void WebContentsImpl::AttachInterstitialPage(
2020 InterstitialPageImpl
* interstitial_page
) {
2021 DCHECK(interstitial_page
);
2022 GetRenderManager()->set_interstitial_page(interstitial_page
);
2024 // Cancel any visible dialogs so that they don't interfere with the
2026 CancelActiveAndPendingDialogs();
2028 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2029 DidAttachInterstitialPage());
2032 void WebContentsImpl::DetachInterstitialPage() {
2033 if (ShowingInterstitialPage())
2034 GetRenderManager()->remove_interstitial_page();
2035 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2036 DidDetachInterstitialPage());
2039 void WebContentsImpl::SetHistoryOffsetAndLength(int history_offset
,
2040 int history_length
) {
2041 SetHistoryOffsetAndLengthForView(
2042 GetRenderViewHost(), history_offset
, history_length
);
2045 void WebContentsImpl::SetHistoryOffsetAndLengthForView(
2046 RenderViewHost
* render_view_host
,
2048 int history_length
) {
2049 render_view_host
->Send(new ViewMsg_SetHistoryOffsetAndLength(
2050 render_view_host
->GetRoutingID(), history_offset
, history_length
));
2053 void WebContentsImpl::ReloadFocusedFrame(bool ignore_cache
) {
2054 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2058 focused_frame
->Send(new FrameMsg_Reload(
2059 focused_frame
->GetRoutingID(), ignore_cache
));
2062 void WebContentsImpl::Undo() {
2063 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2067 focused_frame
->Send(new InputMsg_Undo(focused_frame
->GetRoutingID()));
2068 RecordAction(base::UserMetricsAction("Undo"));
2071 void WebContentsImpl::Redo() {
2072 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2075 focused_frame
->Send(new InputMsg_Redo(focused_frame
->GetRoutingID()));
2076 RecordAction(base::UserMetricsAction("Redo"));
2079 void WebContentsImpl::Cut() {
2080 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2084 focused_frame
->Send(new InputMsg_Cut(focused_frame
->GetRoutingID()));
2085 RecordAction(base::UserMetricsAction("Cut"));
2088 void WebContentsImpl::Copy() {
2089 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2093 focused_frame
->Send(new InputMsg_Copy(focused_frame
->GetRoutingID()));
2094 RecordAction(base::UserMetricsAction("Copy"));
2097 void WebContentsImpl::CopyToFindPboard() {
2098 #if defined(OS_MACOSX)
2099 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2103 // Windows/Linux don't have the concept of a find pasteboard.
2104 focused_frame
->Send(
2105 new InputMsg_CopyToFindPboard(focused_frame
->GetRoutingID()));
2106 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
2110 void WebContentsImpl::Paste() {
2111 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2115 focused_frame
->Send(new InputMsg_Paste(focused_frame
->GetRoutingID()));
2116 RecordAction(base::UserMetricsAction("Paste"));
2119 void WebContentsImpl::PasteAndMatchStyle() {
2120 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2124 focused_frame
->Send(new InputMsg_PasteAndMatchStyle(
2125 focused_frame
->GetRoutingID()));
2126 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
2129 void WebContentsImpl::Delete() {
2130 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2134 focused_frame
->Send(new InputMsg_Delete(focused_frame
->GetRoutingID()));
2135 RecordAction(base::UserMetricsAction("DeleteSelection"));
2138 void WebContentsImpl::SelectAll() {
2139 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2143 focused_frame
->Send(new InputMsg_SelectAll(focused_frame
->GetRoutingID()));
2144 RecordAction(base::UserMetricsAction("SelectAll"));
2147 void WebContentsImpl::Unselect() {
2148 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2152 focused_frame
->Send(new InputMsg_Unselect(focused_frame
->GetRoutingID()));
2153 RecordAction(base::UserMetricsAction("Unselect"));
2156 void WebContentsImpl::Replace(const base::string16
& word
) {
2157 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2161 focused_frame
->Send(new InputMsg_Replace(
2162 focused_frame
->GetRoutingID(), word
));
2165 void WebContentsImpl::ReplaceMisspelling(const base::string16
& word
) {
2166 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2170 focused_frame
->Send(new InputMsg_ReplaceMisspelling(
2171 focused_frame
->GetRoutingID(), word
));
2174 void WebContentsImpl::NotifyContextMenuClosed(
2175 const CustomContextMenuContext
& context
) {
2176 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2180 focused_frame
->Send(new FrameMsg_ContextMenuClosed(
2181 focused_frame
->GetRoutingID(), context
));
2184 void WebContentsImpl::ExecuteCustomContextMenuCommand(
2185 int action
, const CustomContextMenuContext
& context
) {
2186 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2190 focused_frame
->Send(new FrameMsg_CustomContextMenuAction(
2191 focused_frame
->GetRoutingID(), context
, action
));
2194 gfx::NativeView
WebContentsImpl::GetNativeView() {
2195 return view_
->GetNativeView();
2198 gfx::NativeView
WebContentsImpl::GetContentNativeView() {
2199 return view_
->GetContentNativeView();
2202 gfx::NativeWindow
WebContentsImpl::GetTopLevelNativeWindow() {
2203 return view_
->GetTopLevelNativeWindow();
2206 gfx::Rect
WebContentsImpl::GetViewBounds() {
2207 return view_
->GetViewBounds();
2210 gfx::Rect
WebContentsImpl::GetContainerBounds() {
2212 view_
->GetContainerBounds(&rv
);
2216 DropData
* WebContentsImpl::GetDropData() {
2217 return view_
->GetDropData();
2220 void WebContentsImpl::Focus() {
2224 void WebContentsImpl::SetInitialFocus() {
2225 view_
->SetInitialFocus();
2228 void WebContentsImpl::StoreFocus() {
2229 view_
->StoreFocus();
2232 void WebContentsImpl::RestoreFocus() {
2233 view_
->RestoreFocus();
2236 void WebContentsImpl::FocusThroughTabTraversal(bool reverse
) {
2237 if (ShowingInterstitialPage()) {
2238 GetRenderManager()->interstitial_page()->FocusThroughTabTraversal(reverse
);
2241 RenderWidgetHostView
* const fullscreen_view
=
2242 GetFullscreenRenderWidgetHostView();
2243 if (fullscreen_view
) {
2244 fullscreen_view
->Focus();
2247 GetRenderViewHost()->SetInitialFocus(reverse
);
2250 bool WebContentsImpl::ShowingInterstitialPage() const {
2251 return GetRenderManager()->interstitial_page() != NULL
;
2254 InterstitialPage
* WebContentsImpl::GetInterstitialPage() const {
2255 return GetRenderManager()->interstitial_page();
2258 bool WebContentsImpl::IsSavable() {
2259 // WebKit creates Document object when MIME type is application/xhtml+xml,
2260 // so we also support this MIME type.
2261 return contents_mime_type_
== "text/html" ||
2262 contents_mime_type_
== "text/xml" ||
2263 contents_mime_type_
== "application/xhtml+xml" ||
2264 contents_mime_type_
== "text/plain" ||
2265 contents_mime_type_
== "text/css" ||
2266 mime_util::IsSupportedJavascriptMimeType(contents_mime_type_
);
2269 void WebContentsImpl::OnSavePage() {
2270 // If we can not save the page, try to download it.
2272 RecordDownloadSource(INITIATED_BY_SAVE_PACKAGE_ON_NON_HTML
);
2273 SaveFrame(GetLastCommittedURL(), Referrer());
2279 // Create the save package and possibly prompt the user for the name to save
2280 // the page as. The user prompt is an asynchronous operation that runs on
2282 save_package_
= new SavePackage(this);
2283 save_package_
->GetSaveInfo();
2286 // Used in automated testing to bypass prompting the user for file names.
2287 // Instead, the names and paths are hard coded rather than running them through
2288 // file name sanitation and extension / mime checking.
2289 bool WebContentsImpl::SavePage(const base::FilePath
& main_file
,
2290 const base::FilePath
& dir_path
,
2291 SavePageType save_type
) {
2292 // Stop the page from navigating.
2295 save_package_
= new SavePackage(this, save_type
, main_file
, dir_path
);
2296 return save_package_
->Init(SavePackageDownloadCreatedCallback());
2299 void WebContentsImpl::SaveFrame(const GURL
& url
,
2300 const Referrer
& referrer
) {
2301 SaveFrameWithHeaders(url
, referrer
, std::string());
2304 void WebContentsImpl::SaveFrameWithHeaders(const GURL
& url
,
2305 const Referrer
& referrer
,
2306 const std::string
& headers
) {
2307 if (!GetLastCommittedURL().is_valid())
2309 if (delegate_
&& delegate_
->SaveFrame(url
, referrer
))
2312 // TODO(nasko): This check for main frame is incorrect and should be fixed
2313 // by explicitly passing in which frame this method should target.
2314 bool is_main_frame
= (url
== GetLastCommittedURL());
2316 DownloadManager
* dlm
=
2317 BrowserContext::GetDownloadManager(GetBrowserContext());
2321 if (is_main_frame
) {
2322 const NavigationEntry
* entry
= controller_
.GetLastCommittedEntry();
2324 post_id
= entry
->GetPostID();
2326 scoped_ptr
<DownloadUrlParameters
> params(
2327 DownloadUrlParameters::FromWebContents(this, url
));
2328 params
->set_referrer(referrer
);
2329 params
->set_post_id(post_id
);
2331 params
->set_method("POST");
2332 params
->set_prompt(true);
2334 if (headers
.empty()) {
2335 params
->set_prefer_cache(true);
2337 std::vector
<std::string
> key_value_list
;
2338 base::SplitString(headers
, '\n', &key_value_list
);
2339 for (const auto& key_value
: key_value_list
) {
2340 std::vector
<std::string
> pair
;
2341 base::SplitString(key_value
, ':', &pair
);
2342 DCHECK_EQ(2ul, pair
.size());
2343 params
->add_request_header(pair
[0], pair
[1]);
2346 dlm
->DownloadUrl(params
.Pass());
2349 void WebContentsImpl::GenerateMHTML(
2350 const base::FilePath
& file
,
2351 const base::Callback
<void(int64
)>& callback
) {
2352 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, file
, callback
);
2355 const std::string
& WebContentsImpl::GetContentsMimeType() const {
2356 return contents_mime_type_
;
2359 bool WebContentsImpl::WillNotifyDisconnection() const {
2360 return notify_disconnection_
;
2363 void WebContentsImpl::SetOverrideEncoding(const std::string
& encoding
) {
2364 SetEncoding(encoding
);
2365 Send(new ViewMsg_SetPageEncoding(GetRoutingID(), encoding
));
2368 void WebContentsImpl::ResetOverrideEncoding() {
2369 canonical_encoding_
.clear();
2370 Send(new ViewMsg_ResetPageEncodingToDefault(GetRoutingID()));
2373 RendererPreferences
* WebContentsImpl::GetMutableRendererPrefs() {
2374 return &renderer_preferences_
;
2377 void WebContentsImpl::Close() {
2378 Close(GetRenderViewHost());
2381 void WebContentsImpl::DragSourceEndedAt(int client_x
, int client_y
,
2382 int screen_x
, int screen_y
, blink::WebDragOperation operation
) {
2383 if (browser_plugin_embedder_
.get())
2384 browser_plugin_embedder_
->DragSourceEndedAt(client_x
, client_y
,
2385 screen_x
, screen_y
, operation
);
2386 if (GetRenderViewHost())
2387 GetRenderViewHost()->DragSourceEndedAt(client_x
, client_y
, screen_x
,
2388 screen_y
, operation
);
2391 void WebContentsImpl::DidGetResourceResponseStart(
2392 const ResourceRequestDetails
& details
) {
2393 controller_
.ssl_manager()->DidStartResourceResponse(details
);
2395 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2396 DidGetResourceResponseStart(details
));
2398 // TODO(avi): Remove. http://crbug.com/170921
2399 NotificationService::current()->Notify(
2400 NOTIFICATION_RESOURCE_RESPONSE_STARTED
,
2401 Source
<WebContents
>(this),
2402 Details
<const ResourceRequestDetails
>(&details
));
2405 void WebContentsImpl::DidGetRedirectForResourceRequest(
2406 RenderFrameHost
* render_frame_host
,
2407 const ResourceRedirectDetails
& details
) {
2408 controller_
.ssl_manager()->DidReceiveResourceRedirect(details
);
2411 WebContentsObserver
,
2413 DidGetRedirectForResourceRequest(render_frame_host
, details
));
2415 // TODO(avi): Remove. http://crbug.com/170921
2416 NotificationService::current()->Notify(
2417 NOTIFICATION_RESOURCE_RECEIVED_REDIRECT
,
2418 Source
<WebContents
>(this),
2419 Details
<const ResourceRedirectDetails
>(&details
));
2422 void WebContentsImpl::NotifyWebContentsFocused() {
2423 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, OnWebContentsFocused());
2426 void WebContentsImpl::SystemDragEnded() {
2427 if (GetRenderViewHost())
2428 GetRenderViewHost()->DragSourceSystemDragEnded();
2429 if (browser_plugin_embedder_
.get())
2430 browser_plugin_embedder_
->SystemDragEnded();
2433 void WebContentsImpl::UserGestureDone() {
2437 void WebContentsImpl::SetClosedByUserGesture(bool value
) {
2438 closed_by_user_gesture_
= value
;
2441 bool WebContentsImpl::GetClosedByUserGesture() const {
2442 return closed_by_user_gesture_
;
2445 void WebContentsImpl::ViewSource() {
2449 NavigationEntry
* entry
= GetController().GetLastCommittedEntry();
2453 delegate_
->ViewSourceForTab(this, entry
->GetURL());
2456 void WebContentsImpl::ViewFrameSource(const GURL
& url
,
2457 const PageState
& page_state
) {
2461 delegate_
->ViewSourceForFrame(this, url
, page_state
);
2464 int WebContentsImpl::GetMinimumZoomPercent() const {
2465 return minimum_zoom_percent_
;
2468 int WebContentsImpl::GetMaximumZoomPercent() const {
2469 return maximum_zoom_percent_
;
2472 void WebContentsImpl::ResetPageScale() {
2473 Send(new ViewMsg_ResetPageScale(GetRoutingID()));
2476 gfx::Size
WebContentsImpl::GetPreferredSize() const {
2477 return capturer_count_
== 0 ? preferred_size_
: preferred_size_for_capture_
;
2480 bool WebContentsImpl::GotResponseToLockMouseRequest(bool allowed
) {
2481 if (GetBrowserPluginGuest())
2482 return GetBrowserPluginGuest()->LockMouse(allowed
);
2484 return GetRenderViewHost()
2485 ? GetRenderViewHost()->GotResponseToLockMouseRequest(allowed
)
2489 bool WebContentsImpl::HasOpener() const {
2490 return GetOpener() != NULL
;
2493 WebContentsImpl
* WebContentsImpl::GetOpener() const {
2494 FrameTreeNode
* opener_ftn
= frame_tree_
.root()->opener();
2495 return opener_ftn
? FromFrameTreeNode(opener_ftn
) : nullptr;
2498 void WebContentsImpl::DidChooseColorInColorChooser(SkColor color
) {
2499 if (!color_chooser_info_
.get())
2501 RenderFrameHost
* rfh
= RenderFrameHost::FromID(
2502 color_chooser_info_
->render_process_id
,
2503 color_chooser_info_
->render_frame_id
);
2507 rfh
->Send(new FrameMsg_DidChooseColorResponse(
2508 rfh
->GetRoutingID(), color_chooser_info_
->identifier
, color
));
2511 void WebContentsImpl::DidEndColorChooser() {
2512 if (!color_chooser_info_
.get())
2514 RenderFrameHost
* rfh
= RenderFrameHost::FromID(
2515 color_chooser_info_
->render_process_id
,
2516 color_chooser_info_
->render_frame_id
);
2520 rfh
->Send(new FrameMsg_DidEndColorChooser(
2521 rfh
->GetRoutingID(), color_chooser_info_
->identifier
));
2522 color_chooser_info_
.reset();
2525 int WebContentsImpl::DownloadImage(const GURL
& url
,
2527 uint32_t max_bitmap_size
,
2529 const ImageDownloadCallback
& callback
) {
2530 int id
= StartDownload(GetMainFrame(), url
, is_favicon
, max_bitmap_size
,
2532 image_download_map_
[id
] = callback
;
2536 bool WebContentsImpl::IsSubframe() const {
2537 return is_subframe_
;
2540 void WebContentsImpl::Find(int request_id
,
2541 const base::string16
& search_text
,
2542 const blink::WebFindOptions
& options
) {
2543 // See if a top level browser plugin handles the find request first.
2544 if (browser_plugin_embedder_
) {
2545 BrowserPluginGuest
* guest
= browser_plugin_embedder_
->GetFullPageGuest();
2546 if (guest
&& guest
->Find(request_id
, search_text
, options
))
2549 Send(new ViewMsg_Find(GetRoutingID(), request_id
, search_text
, options
));
2552 void WebContentsImpl::StopFinding(StopFindAction action
) {
2553 // See if a top level browser plugin handles the stop finding request first.
2554 if (browser_plugin_embedder_
) {
2555 BrowserPluginGuest
* guest
= browser_plugin_embedder_
->GetFullPageGuest();
2556 if (guest
&& guest
->StopFinding(action
))
2559 Send(new ViewMsg_StopFinding(GetRoutingID(), action
));
2562 void WebContentsImpl::InsertCSS(const std::string
& css
) {
2563 GetMainFrame()->Send(new FrameMsg_CSSInsertRequest(
2564 GetMainFrame()->GetRoutingID(), css
));
2567 bool WebContentsImpl::WasRecentlyAudible() {
2568 return audio_state_provider_
->WasRecentlyAudible();
2571 void WebContentsImpl::GetManifest(const GetManifestCallback
& callback
) {
2572 manifest_manager_host_
->GetManifest(GetMainFrame(), callback
);
2575 void WebContentsImpl::ExitFullscreen() {
2576 // Clean up related state and initiate the fullscreen exit.
2577 GetRenderViewHost()->RejectMouseLockOrUnlockIfNecessary();
2578 ExitFullscreenMode();
2581 void WebContentsImpl::ResumeLoadingCreatedWebContents() {
2582 // Resume blocked requests for both the RenderViewHost and RenderFrameHost.
2583 // TODO(brettw): It seems bogus to reach into here and initialize the host.
2584 GetRenderViewHost()->Init();
2585 GetMainFrame()->Init();
2588 bool WebContentsImpl::FocusLocationBarByDefault() {
2589 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
2590 if (entry
&& entry
->GetURL() == GURL(url::kAboutBlankURL
))
2592 return delegate_
&& delegate_
->ShouldFocusLocationBarByDefault(this);
2595 void WebContentsImpl::SetFocusToLocationBar(bool select_all
) {
2597 delegate_
->SetFocusToLocationBar(select_all
);
2600 void WebContentsImpl::DidStartProvisionalLoad(
2601 RenderFrameHostImpl
* render_frame_host
,
2602 const GURL
& validated_url
,
2604 bool is_iframe_srcdoc
) {
2605 // Notify observers about the start of the provisional load.
2607 WebContentsObserver
,
2609 DidStartProvisionalLoadForFrame(
2610 render_frame_host
, validated_url
, is_error_page
, is_iframe_srcdoc
));
2612 // Notify accessibility if this is a reload.
2613 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
2614 if (entry
&& ui::PageTransitionCoreTypeIs(
2615 entry
->GetTransitionType(), ui::PAGE_TRANSITION_RELOAD
)) {
2616 FrameTreeNode
* ftn
= render_frame_host
->frame_tree_node();
2617 BrowserAccessibilityManager
* manager
=
2618 ftn
->current_frame_host()->browser_accessibility_manager();
2620 manager
->UserIsReloading();
2624 void WebContentsImpl::DidFailProvisionalLoadWithError(
2625 RenderFrameHostImpl
* render_frame_host
,
2626 const FrameHostMsg_DidFailProvisionalLoadWithError_Params
& params
) {
2627 GURL
validated_url(params
.url
);
2628 FOR_EACH_OBSERVER(WebContentsObserver
,
2630 DidFailProvisionalLoad(render_frame_host
,
2633 params
.error_description
));
2635 FrameTreeNode
* ftn
= render_frame_host
->frame_tree_node();
2636 BrowserAccessibilityManager
* manager
=
2637 ftn
->current_frame_host()->browser_accessibility_manager();
2639 manager
->NavigationFailed();
2642 void WebContentsImpl::DidFailLoadWithError(
2643 RenderFrameHostImpl
* render_frame_host
,
2646 const base::string16
& error_description
) {
2648 WebContentsObserver
,
2650 DidFailLoad(render_frame_host
, url
, error_code
, error_description
));
2653 void WebContentsImpl::NotifyChangedNavigationState(
2654 InvalidateTypes changed_flags
) {
2655 NotifyNavigationStateChanged(changed_flags
);
2658 void WebContentsImpl::AboutToNavigateRenderFrame(
2659 RenderFrameHostImpl
* old_host
,
2660 RenderFrameHostImpl
* new_host
) {
2661 // Notify observers that we will navigate in this RenderFrame.
2663 WebContentsObserver
,
2665 AboutToNavigateRenderFrame(old_host
, new_host
));
2668 void WebContentsImpl::DidStartNavigationToPendingEntry(
2670 NavigationController::ReloadType reload_type
) {
2671 // Notify observers about navigation.
2673 WebContentsObserver
,
2675 DidStartNavigationToPendingEntry(url
, reload_type
));
2678 void WebContentsImpl::RequestOpenURL(RenderFrameHostImpl
* render_frame_host
,
2679 const OpenURLParams
& params
) {
2680 // OpenURL can blow away the source RFH. Use the process/frame routing ID as a
2681 // weak pointer of sorts.
2682 const int32_t process_id
= render_frame_host
->GetProcess()->GetID();
2683 const int32_t frame_id
= render_frame_host
->GetRoutingID();
2685 WebContents
* new_contents
= OpenURL(params
);
2687 if (new_contents
&& RenderFrameHost::FromID(process_id
, frame_id
)) {
2688 // Notify observers.
2689 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2690 DidOpenRequestedURL(new_contents
,
2695 params
.transition
));
2699 bool WebContentsImpl::ShouldPreserveAbortedURLs() {
2702 return delegate_
->ShouldPreserveAbortedURLs(this);
2705 void WebContentsImpl::DidCommitProvisionalLoad(
2706 RenderFrameHostImpl
* render_frame_host
,
2708 ui::PageTransition transition_type
) {
2709 // Notify observers about the commit of the provisional load.
2710 FOR_EACH_OBSERVER(WebContentsObserver
,
2712 DidCommitProvisionalLoadForFrame(
2713 render_frame_host
, url
, transition_type
));
2715 BrowserAccessibilityManager
* manager
=
2716 render_frame_host
->browser_accessibility_manager();
2718 manager
->NavigationSucceeded();
2721 void WebContentsImpl::DidNavigateMainFramePreCommit(
2722 bool navigation_is_within_page
) {
2723 // Ensure fullscreen mode is exited before committing the navigation to a
2724 // different page. The next page will not start out assuming it is in
2726 if (navigation_is_within_page
) {
2727 // No page change? Then, the renderer and browser can remain in fullscreen.
2730 if (IsFullscreenForCurrentTab())
2732 DCHECK(!IsFullscreenForCurrentTab());
2735 void WebContentsImpl::DidNavigateMainFramePostCommit(
2736 RenderFrameHostImpl
* render_frame_host
,
2737 const LoadCommittedDetails
& details
,
2738 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) {
2739 if (details
.is_navigation_to_different_page()) {
2740 // Clear the status bubble. This is a workaround for a bug where WebKit
2741 // doesn't let us know that the cursor left an element during a
2742 // transition (this is also why the mouse cursor remains as a hand after
2743 // clicking on a link); see bugs 1184641 and 980803. We don't want to
2744 // clear the bubble when a user navigates to a named anchor in the same
2746 UpdateTargetURL(render_frame_host
->GetRenderViewHost(), GURL());
2748 RenderWidgetHostViewBase
* rwhvb
=
2749 static_cast<RenderWidgetHostViewBase
*>(GetRenderWidgetHostView());
2751 rwhvb
->OnDidNavigateMainFrameToNewPage();
2753 did_first_visually_non_empty_paint_
= false;
2755 // Reset theme color on navigation to new page.
2756 theme_color_
= SK_ColorTRANSPARENT
;
2759 if (!details
.is_in_page
) {
2760 // Once the main frame is navigated, we're no longer considered to have
2761 // displayed insecure content.
2762 displayed_insecure_content_
= false;
2763 SSLManager::NotifySSLInternalStateChanged(
2764 GetController().GetBrowserContext());
2767 // Notify observers about navigation.
2768 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2769 DidNavigateMainFrame(details
, params
));
2772 delegate_
->DidNavigateMainFramePostCommit(this);
2773 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
2776 void WebContentsImpl::DidNavigateAnyFramePostCommit(
2777 RenderFrameHostImpl
* render_frame_host
,
2778 const LoadCommittedDetails
& details
,
2779 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) {
2780 // Now that something has committed, we don't need to track whether the
2781 // initial page has been accessed.
2782 has_accessed_initial_document_
= false;
2784 // If we navigate off the page, close all JavaScript dialogs.
2785 if (!details
.is_in_page
)
2786 CancelActiveAndPendingDialogs();
2788 // Notify observers about navigation.
2789 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2790 DidNavigateAnyFrame(render_frame_host
, details
, params
));
2793 void WebContentsImpl::SetMainFrameMimeType(const std::string
& mime_type
) {
2794 contents_mime_type_
= mime_type
;
2797 bool WebContentsImpl::CanOverscrollContent() const {
2798 // Disable overscroll when touch emulation is on. See crbug.com/369938.
2799 if (force_disable_overscroll_content_
)
2803 return delegate_
->CanOverscrollContent();
2808 void WebContentsImpl::OnThemeColorChanged(SkColor theme_color
) {
2809 // Update the theme color. This is to be published to observers after the
2810 // first visually non-empty paint.
2811 theme_color_
= theme_color
;
2813 if (did_first_visually_non_empty_paint_
&&
2814 last_sent_theme_color_
!= theme_color_
) {
2815 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2816 DidChangeThemeColor(theme_color_
));
2817 last_sent_theme_color_
= theme_color_
;
2821 void WebContentsImpl::OnDidLoadResourceFromMemoryCache(
2823 const std::string
& security_info
,
2824 const std::string
& http_method
,
2825 const std::string
& mime_type
,
2826 ResourceType resource_type
) {
2828 // Send out a notification that we loaded a resource from our memory cache.
2830 net::CertStatus cert_status
= 0;
2831 int security_bits
= -1;
2832 int connection_status
= 0;
2833 SignedCertificateTimestampIDStatusList signed_certificate_timestamp_ids
;
2834 DeserializeSecurityInfo(security_info
, &cert_id
, &cert_status
,
2835 &security_bits
, &connection_status
,
2836 &signed_certificate_timestamp_ids
);
2837 // TODO(alcutter,eranm): Pass signed_certificate_timestamp_ids into details
2838 LoadFromMemoryCacheDetails
details(
2839 url
, GetRenderProcessHost()->GetID(), cert_id
, cert_status
, http_method
,
2840 mime_type
, resource_type
);
2842 controller_
.ssl_manager()->DidLoadFromMemoryCache(details
);
2844 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2845 DidLoadResourceFromMemoryCache(details
));
2847 if (url
.is_valid() && url
.SchemeIsHTTPOrHTTPS()) {
2848 scoped_refptr
<net::URLRequestContextGetter
> request_context(
2849 resource_type
== RESOURCE_TYPE_MEDIA
?
2850 GetBrowserContext()->GetMediaRequestContextForRenderProcess(
2851 GetRenderProcessHost()->GetID()) :
2852 GetBrowserContext()->GetRequestContextForRenderProcess(
2853 GetRenderProcessHost()->GetID()));
2854 BrowserThread::PostTask(
2857 base::Bind(&NotifyCacheOnIO
, request_context
, url
, http_method
));
2861 void WebContentsImpl::OnDidDisplayInsecureContent() {
2862 RecordAction(base::UserMetricsAction("SSL.DisplayedInsecureContent"));
2863 displayed_insecure_content_
= true;
2864 SSLManager::NotifySSLInternalStateChanged(
2865 GetController().GetBrowserContext());
2868 void WebContentsImpl::OnDidRunInsecureContent(
2869 const std::string
& security_origin
, const GURL
& target_url
) {
2870 LOG(WARNING
) << security_origin
<< " ran insecure content from "
2871 << target_url
.possibly_invalid_spec();
2872 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
2873 if (EndsWith(security_origin
, kDotGoogleDotCom
, false))
2874 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
2875 controller_
.ssl_manager()->DidRunInsecureContent(security_origin
);
2876 displayed_insecure_content_
= true;
2877 SSLManager::NotifySSLInternalStateChanged(
2878 GetController().GetBrowserContext());
2881 void WebContentsImpl::OnDocumentLoadedInFrame() {
2882 if (!HasValidFrameSource())
2885 RenderFrameHostImpl
* rfh
=
2886 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2888 WebContentsObserver
, observers_
, DocumentLoadedInFrame(rfh
));
2891 void WebContentsImpl::OnDidFinishLoad(const GURL
& url
) {
2892 if (!HasValidFrameSource())
2895 GURL
validated_url(url
);
2896 RenderProcessHost
* render_process_host
=
2897 render_frame_message_source_
->GetProcess();
2898 render_process_host
->FilterURL(false, &validated_url
);
2900 RenderFrameHostImpl
* rfh
=
2901 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2903 WebContentsObserver
, observers_
, DidFinishLoad(rfh
, validated_url
));
2906 void WebContentsImpl::OnGoToEntryAtOffset(int offset
) {
2907 if (!delegate_
|| delegate_
->OnGoToEntryOffset(offset
))
2908 controller_
.GoToOffset(offset
);
2911 void WebContentsImpl::OnUpdateZoomLimits(int minimum_percent
,
2912 int maximum_percent
) {
2913 minimum_zoom_percent_
= minimum_percent
;
2914 maximum_zoom_percent_
= maximum_percent
;
2917 void WebContentsImpl::OnEnumerateDirectory(int request_id
,
2918 const base::FilePath
& path
) {
2922 ChildProcessSecurityPolicyImpl
* policy
=
2923 ChildProcessSecurityPolicyImpl::GetInstance();
2924 if (policy
->CanReadFile(GetRenderProcessHost()->GetID(), path
))
2925 delegate_
->EnumerateDirectory(this, request_id
, path
);
2928 void WebContentsImpl::OnRegisterProtocolHandler(const std::string
& protocol
,
2930 const base::string16
& title
,
2931 bool user_gesture
) {
2935 ChildProcessSecurityPolicyImpl
* policy
=
2936 ChildProcessSecurityPolicyImpl::GetInstance();
2937 if (policy
->IsPseudoScheme(protocol
))
2940 delegate_
->RegisterProtocolHandler(this, protocol
, url
, user_gesture
);
2943 void WebContentsImpl::OnUnregisterProtocolHandler(const std::string
& protocol
,
2945 bool user_gesture
) {
2949 ChildProcessSecurityPolicyImpl
* policy
=
2950 ChildProcessSecurityPolicyImpl::GetInstance();
2951 if (policy
->IsPseudoScheme(protocol
))
2954 delegate_
->UnregisterProtocolHandler(this, protocol
, url
, user_gesture
);
2957 void WebContentsImpl::OnFindReply(int request_id
,
2958 int number_of_matches
,
2959 const gfx::Rect
& selection_rect
,
2960 int active_match_ordinal
,
2961 bool final_update
) {
2963 delegate_
->FindReply(this, request_id
, number_of_matches
, selection_rect
,
2964 active_match_ordinal
, final_update
);
2968 #if defined(OS_ANDROID)
2969 void WebContentsImpl::OnFindMatchRectsReply(
2971 const std::vector
<gfx::RectF
>& rects
,
2972 const gfx::RectF
& active_rect
) {
2974 delegate_
->FindMatchRectsReply(this, version
, rects
, active_rect
);
2977 void WebContentsImpl::OnOpenDateTimeDialog(
2978 const ViewHostMsg_DateTimeDialogValue_Params
& value
) {
2979 date_time_chooser_
->ShowDialog(GetTopLevelNativeWindow(),
2980 GetRenderViewHost(),
2990 void WebContentsImpl::OnDomOperationResponse(const std::string
& json_string
,
2991 int automation_id
) {
2992 DomOperationNotificationDetails
details(json_string
, automation_id
);
2993 NotificationService::current()->Notify(
2994 NOTIFICATION_DOM_OPERATION_RESPONSE
,
2995 Source
<WebContents
>(this),
2996 Details
<DomOperationNotificationDetails
>(&details
));
2999 void WebContentsImpl::OnAppCacheAccessed(const GURL
& manifest_url
,
3000 bool blocked_by_policy
) {
3001 // Notify observers about navigation.
3002 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3003 AppCacheAccessed(manifest_url
, blocked_by_policy
));
3006 void WebContentsImpl::OnOpenColorChooser(
3007 int color_chooser_id
,
3009 const std::vector
<ColorSuggestion
>& suggestions
) {
3010 if (!HasValidFrameSource())
3013 ColorChooser
* new_color_chooser
= delegate_
?
3014 delegate_
->OpenColorChooser(this, color
, suggestions
) :
3016 if (!new_color_chooser
)
3018 if (color_chooser_info_
.get())
3019 color_chooser_info_
->chooser
->End();
3021 color_chooser_info_
.reset(new ColorChooserInfo(
3022 render_frame_message_source_
->GetProcess()->GetID(),
3023 render_frame_message_source_
->GetRoutingID(),
3028 void WebContentsImpl::OnEndColorChooser(int color_chooser_id
) {
3029 if (color_chooser_info_
&&
3030 color_chooser_id
== color_chooser_info_
->identifier
)
3031 color_chooser_info_
->chooser
->End();
3034 void WebContentsImpl::OnSetSelectedColorInColorChooser(int color_chooser_id
,
3036 if (color_chooser_info_
&&
3037 color_chooser_id
== color_chooser_info_
->identifier
)
3038 color_chooser_info_
->chooser
->SetSelectedColor(color
);
3041 // This exists for render views that don't have a WebUI, but do have WebUI
3042 // bindings enabled.
3043 void WebContentsImpl::OnWebUISend(const GURL
& source_url
,
3044 const std::string
& name
,
3045 const base::ListValue
& args
) {
3047 delegate_
->WebUISend(this, source_url
, name
, args
);
3050 #if defined(ENABLE_PLUGINS)
3051 void WebContentsImpl::OnPepperInstanceCreated() {
3052 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, PepperInstanceCreated());
3055 void WebContentsImpl::OnPepperInstanceDeleted() {
3056 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, PepperInstanceDeleted());
3059 void WebContentsImpl::OnPepperPluginHung(int plugin_child_id
,
3060 const base::FilePath
& path
,
3062 UMA_HISTOGRAM_COUNTS("Pepper.PluginHung", 1);
3064 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3065 PluginHungStatusChanged(plugin_child_id
, path
, is_hung
));
3068 void WebContentsImpl::OnPluginCrashed(const base::FilePath
& plugin_path
,
3069 base::ProcessId plugin_pid
) {
3070 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3071 PluginCrashed(plugin_path
, plugin_pid
));
3074 void WebContentsImpl::OnRequestPpapiBrokerPermission(
3077 const base::FilePath
& plugin_path
) {
3079 OnPpapiBrokerPermissionResult(routing_id
, false);
3083 if (!delegate_
->RequestPpapiBrokerPermission(
3084 this, url
, plugin_path
,
3085 base::Bind(&WebContentsImpl::OnPpapiBrokerPermissionResult
,
3086 base::Unretained(this), routing_id
))) {
3088 OnPpapiBrokerPermissionResult(routing_id
, false);
3092 void WebContentsImpl::OnPpapiBrokerPermissionResult(int routing_id
,
3094 Send(new ViewMsg_PpapiBrokerPermissionResult(routing_id
, result
));
3097 void WebContentsImpl::OnBrowserPluginMessage(RenderFrameHost
* render_frame_host
,
3098 const IPC::Message
& message
) {
3099 CHECK(!browser_plugin_embedder_
.get());
3100 CreateBrowserPluginEmbedderIfNecessary();
3101 browser_plugin_embedder_
->OnMessageReceived(message
, render_frame_host
);
3103 #endif // defined(ENABLE_PLUGINS)
3105 void WebContentsImpl::OnDidDownloadImage(
3107 int http_status_code
,
3108 const GURL
& image_url
,
3109 const std::vector
<SkBitmap
>& bitmaps
,
3110 const std::vector
<gfx::Size
>& original_bitmap_sizes
) {
3111 if (bitmaps
.size() != original_bitmap_sizes
.size())
3114 ImageDownloadMap::iterator iter
= image_download_map_
.find(id
);
3115 if (iter
== image_download_map_
.end()) {
3116 // Currently WebContents notifies us of ANY downloads so that it is
3117 // possible to get here.
3120 if (!iter
->second
.is_null()) {
3122 id
, http_status_code
, image_url
, bitmaps
, original_bitmap_sizes
);
3124 image_download_map_
.erase(id
);
3127 void WebContentsImpl::OnUpdateFaviconURL(
3128 const std::vector
<FaviconURL
>& candidates
) {
3129 // We get updated favicon URLs after the page stops loading. If a cross-site
3130 // navigation occurs while a page is still loading, the initial page
3131 // may stop loading and send us updated favicon URLs after the navigation
3132 // for the new page has committed.
3133 RenderViewHostImpl
* rvhi
=
3134 static_cast<RenderViewHostImpl
*>(render_view_message_source_
);
3135 if (!rvhi
->is_active())
3138 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3139 DidUpdateFaviconURL(candidates
));
3142 void WebContentsImpl::CreateAudioPowerSaveBlocker() {
3143 DCHECK(!audio_power_save_blocker_
);
3144 audio_power_save_blocker_
= PowerSaveBlocker::Create(
3145 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension
,
3146 PowerSaveBlocker::kReasonAudioPlayback
, "Playing audio");
3149 void WebContentsImpl::CreateVideoPowerSaveBlocker() {
3150 DCHECK(!video_power_save_blocker_
);
3151 DCHECK(!active_video_players_
.empty());
3152 video_power_save_blocker_
= PowerSaveBlocker::Create(
3153 PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep
,
3154 PowerSaveBlocker::kReasonVideoPlayback
, "Playing video");
3155 #if defined(OS_ANDROID)
3156 static_cast<PowerSaveBlockerImpl
*>(video_power_save_blocker_
.get())
3157 ->InitDisplaySleepBlocker(this);
3161 void WebContentsImpl::MaybeReleasePowerSaveBlockers() {
3162 // If there are no more audio players and we don't have audio stream
3163 // monitoring, release the audio power save blocker here instead of during
3164 // NotifyNavigationStateChanged().
3165 if (active_audio_players_
.empty() &&
3166 !audio_state_provider_
->IsAudioStateAvailable()) {
3167 audio_power_save_blocker_
.reset();
3170 // If there are no more video players, clear the video power save blocker.
3171 if (active_video_players_
.empty())
3172 video_power_save_blocker_
.reset();
3175 void WebContentsImpl::OnMediaPlayingNotification(int64 player_cookie
,
3179 // Ignore the videos playing remotely and don't hold the wake lock for the
3181 if (is_remote
) return;
3184 AddMediaPlayerEntry(player_cookie
, &active_audio_players_
);
3186 // If we don't have audio stream monitoring, allocate the audio power save
3187 // blocker here instead of during NotifyNavigationStateChanged().
3188 if (!audio_power_save_blocker_
&&
3189 !audio_state_provider_
->IsAudioStateAvailable()) {
3190 CreateAudioPowerSaveBlocker();
3195 AddMediaPlayerEntry(player_cookie
, &active_video_players_
);
3197 // If we're not hidden and have just created a player, create a blocker.
3198 if (!video_power_save_blocker_
&& !IsHidden())
3199 CreateVideoPowerSaveBlocker();
3202 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, MediaStartedPlaying());
3205 void WebContentsImpl::OnMediaPausedNotification(int64 player_cookie
) {
3206 RemoveMediaPlayerEntry(player_cookie
, &active_audio_players_
);
3207 RemoveMediaPlayerEntry(player_cookie
, &active_video_players_
);
3208 MaybeReleasePowerSaveBlockers();
3210 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, MediaPaused());
3213 void WebContentsImpl::OnFirstVisuallyNonEmptyPaint() {
3214 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3215 DidFirstVisuallyNonEmptyPaint());
3217 did_first_visually_non_empty_paint_
= true;
3219 if (theme_color_
!= last_sent_theme_color_
) {
3220 // Theme color should have updated by now if there was one.
3221 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3222 DidChangeThemeColor(theme_color_
));
3223 last_sent_theme_color_
= theme_color_
;
3227 void WebContentsImpl::DidChangeVisibleSSLState() {
3229 delegate_
->VisibleSSLStateChanged(this);
3231 content::SecurityStyle security_style
= delegate_
->GetSecurityStyle(this);
3232 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3233 SecurityStyleChanged(security_style
));
3237 void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
3238 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3239 BeforeFormRepostWarningShow());
3242 void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
3245 delegate_
->ShowRepostFormWarningDialog(this);
3248 bool WebContentsImpl::HasAccessedInitialDocument() {
3249 return has_accessed_initial_document_
;
3252 // Notifies the RenderWidgetHost instance about the fact that the page is
3253 // loading, or done loading.
3254 void WebContentsImpl::SetIsLoading(bool is_loading
,
3255 bool to_different_document
,
3256 LoadNotificationDetails
* details
) {
3257 if (is_loading
== is_loading_
)
3261 load_state_
= net::LoadStateWithParam(net::LOAD_STATE_IDLE
,
3263 load_state_host_
.clear();
3265 upload_position_
= 0;
3268 GetRenderManager()->SetIsLoading(is_loading
);
3270 is_loading_
= is_loading
;
3271 waiting_for_response_
= is_loading
;
3272 is_load_to_different_document_
= to_different_document
;
3275 delegate_
->LoadingStateChanged(this, to_different_document
);
3276 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD
);
3278 std::string url
= (details
? details
->url
.possibly_invalid_spec() : "NULL");
3280 TRACE_EVENT_ASYNC_BEGIN1("browser,navigation", "WebContentsImpl Loading",
3282 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, DidStartLoading());
3284 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
3286 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, DidStopLoading());
3289 // TODO(avi): Remove. http://crbug.com/170921
3290 int type
= is_loading
? NOTIFICATION_LOAD_START
: NOTIFICATION_LOAD_STOP
;
3291 NotificationDetails det
= NotificationService::NoDetails();
3293 det
= Details
<LoadNotificationDetails
>(details
);
3294 NotificationService::current()->Notify(
3295 type
, Source
<NavigationController
>(&controller_
), det
);
3298 void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point
& extent
) {
3299 RenderFrameHost
* focused_frame
= GetFocusedFrame();
3303 focused_frame
->Send(new InputMsg_MoveRangeSelectionExtent(
3304 focused_frame
->GetRoutingID(), extent
));
3307 void WebContentsImpl::SelectRange(const gfx::Point
& base
,
3308 const gfx::Point
& extent
) {
3309 RenderFrameHost
* focused_frame
= GetFocusedFrame();
3313 focused_frame
->Send(
3314 new InputMsg_SelectRange(focused_frame
->GetRoutingID(), base
, extent
));
3317 void WebContentsImpl::UpdateMaxPageIDIfNecessary(RenderViewHost
* rvh
) {
3318 // If we are creating a RVH for a restored controller, then we need to make
3319 // sure the RenderView starts with a next_page_id_ larger than the number
3320 // of restored entries. This must be called before the RenderView starts
3321 // navigating (to avoid a race between the browser updating max_page_id and
3322 // the renderer updating next_page_id_). Because of this, we only call this
3323 // from CreateRenderView and allow that to notify the RenderView for us.
3324 int max_restored_page_id
= controller_
.GetMaxRestoredPageID();
3325 if (max_restored_page_id
>
3326 GetMaxPageIDForSiteInstance(rvh
->GetSiteInstance()))
3327 UpdateMaxPageIDForSiteInstance(rvh
->GetSiteInstance(),
3328 max_restored_page_id
);
3331 bool WebContentsImpl::UpdateTitleForEntry(NavigationEntryImpl
* entry
,
3332 const base::string16
& title
) {
3333 // For file URLs without a title, use the pathname instead. In the case of a
3334 // synthesized title, we don't want the update to count toward the "one set
3335 // per page of the title to history."
3336 base::string16 final_title
;
3338 if (entry
&& entry
->GetURL().SchemeIsFile() && title
.empty()) {
3339 final_title
= base::UTF8ToUTF16(entry
->GetURL().ExtractFileName());
3340 explicit_set
= false; // Don't count synthetic titles toward the set limit.
3342 base::TrimWhitespace(title
, base::TRIM_ALL
, &final_title
);
3343 explicit_set
= true;
3346 // If a page is created via window.open and never navigated,
3347 // there will be no navigation entry. In this situation,
3348 // |page_title_when_no_navigation_entry_| will be used for page title.
3350 if (final_title
== entry
->GetTitle())
3351 return false; // Nothing changed, don't bother.
3353 entry
->SetTitle(final_title
);
3355 if (page_title_when_no_navigation_entry_
== final_title
)
3356 return false; // Nothing changed, don't bother.
3358 page_title_when_no_navigation_entry_
= final_title
;
3361 // Lastly, set the title for the view.
3362 view_
->SetPageTitle(final_title
);
3364 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3365 TitleWasSet(entry
, explicit_set
));
3367 // TODO(avi): Remove. http://crbug.com/170921
3368 std::pair
<NavigationEntry
*, bool> details
=
3369 std::make_pair(entry
, explicit_set
);
3370 NotificationService::current()->Notify(
3371 NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED
,
3372 Source
<WebContents
>(this),
3373 Details
<std::pair
<NavigationEntry
*, bool> >(&details
));
3378 void WebContentsImpl::SendChangeLoadProgress() {
3379 loading_last_progress_update_
= base::TimeTicks::Now();
3381 delegate_
->LoadProgressChanged(this, frame_tree_
.load_progress());
3384 void WebContentsImpl::ResetLoadProgressState() {
3385 frame_tree_
.ResetLoadProgress();
3386 loading_weak_factory_
.InvalidateWeakPtrs();
3387 loading_last_progress_update_
= base::TimeTicks();
3390 void WebContentsImpl::NotifyViewSwapped(RenderViewHost
* old_host
,
3391 RenderViewHost
* new_host
) {
3392 // After sending out a swap notification, we need to send a disconnect
3393 // notification so that clients that pick up a pointer to |this| can NULL the
3394 // pointer. See Bug 1230284.
3395 notify_disconnection_
= true;
3396 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3397 RenderViewHostChanged(old_host
, new_host
));
3399 // Ensure that the associated embedder gets cleared after a RenderViewHost
3400 // gets swapped, so we don't reuse the same embedder next time a
3401 // RenderViewHost is attached to this WebContents.
3402 RemoveBrowserPluginEmbedder();
3405 void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost
* old_host
,
3406 RenderFrameHost
* new_host
) {
3407 FOR_EACH_OBSERVER(WebContentsObserver
,
3409 RenderFrameHostChanged(old_host
, new_host
));
3412 // TODO(avi): Remove this entire function because this notification is already
3413 // covered by two observer functions. http://crbug.com/170921
3414 void WebContentsImpl::NotifyDisconnected() {
3415 if (!notify_disconnection_
)
3418 notify_disconnection_
= false;
3419 NotificationService::current()->Notify(
3420 NOTIFICATION_WEB_CONTENTS_DISCONNECTED
,
3421 Source
<WebContents
>(this),
3422 NotificationService::NoDetails());
3425 void WebContentsImpl::NotifyNavigationEntryCommitted(
3426 const LoadCommittedDetails
& load_details
) {
3428 WebContentsObserver
, observers_
, NavigationEntryCommitted(load_details
));
3431 bool WebContentsImpl::OnMessageReceived(RenderFrameHost
* render_frame_host
,
3432 const IPC::Message
& message
) {
3433 return OnMessageReceived(NULL
, render_frame_host
, message
);
3436 const GURL
& WebContentsImpl::GetMainFrameLastCommittedURL() const {
3437 return GetLastCommittedURL();
3440 void WebContentsImpl::RenderFrameCreated(RenderFrameHost
* render_frame_host
) {
3441 // Note this is only for subframes, the notification for the main frame
3442 // happens in RenderViewCreated.
3443 FOR_EACH_OBSERVER(WebContentsObserver
,
3445 RenderFrameCreated(render_frame_host
));
3446 SetAccessibilityModeOnFrame(accessibility_mode_
, render_frame_host
);
3449 void WebContentsImpl::RenderFrameDeleted(RenderFrameHost
* render_frame_host
) {
3450 ClearPowerSaveBlockers(render_frame_host
);
3451 FOR_EACH_OBSERVER(WebContentsObserver
,
3453 RenderFrameDeleted(render_frame_host
));
3456 void WebContentsImpl::WorkerCrashed(RenderFrameHost
* render_frame_host
) {
3458 delegate_
->WorkerCrashed(this);
3461 void WebContentsImpl::ShowContextMenu(RenderFrameHost
* render_frame_host
,
3462 const ContextMenuParams
& params
) {
3463 ContextMenuParams
context_menu_params(params
);
3464 // Allow WebContentsDelegates to handle the context menu operation first.
3465 if (delegate_
&& delegate_
->HandleContextMenu(context_menu_params
))
3468 render_view_host_delegate_view_
->ShowContextMenu(render_frame_host
,
3469 context_menu_params
);
3472 void WebContentsImpl::RunJavaScriptMessage(
3473 RenderFrameHost
* render_frame_host
,
3474 const base::string16
& message
,
3475 const base::string16
& default_prompt
,
3476 const GURL
& frame_url
,
3477 JavaScriptMessageType javascript_message_type
,
3478 IPC::Message
* reply_msg
) {
3479 // Suppress JavaScript dialogs when requested. Also suppress messages when
3480 // showing an interstitial as it's shown over the previous page and we don't
3481 // want the hidden page's dialogs to interfere with the interstitial.
3482 bool suppress_this_message
=
3483 static_cast<RenderFrameHostImpl
*>(render_frame_host
)->is_swapped_out() ||
3484 ShowingInterstitialPage() || !delegate_
||
3485 delegate_
->ShouldSuppressDialogs(this) ||
3486 !delegate_
->GetJavaScriptDialogManager(this);
3488 if (!suppress_this_message
) {
3489 std::string accept_lang
= GetContentClient()->browser()->
3490 GetAcceptLangs(GetBrowserContext());
3491 dialog_manager_
= delegate_
->GetJavaScriptDialogManager(this);
3492 dialog_manager_
->RunJavaScriptDialog(
3494 frame_url
.GetOrigin(),
3496 javascript_message_type
,
3499 base::Bind(&WebContentsImpl::OnDialogClosed
,
3500 base::Unretained(this),
3501 render_frame_host
->GetProcess()->GetID(),
3502 render_frame_host
->GetRoutingID(),
3505 &suppress_this_message
);
3508 if (suppress_this_message
) {
3509 // If we are suppressing messages, just reply as if the user immediately
3510 // pressed "Cancel", passing true to |dialog_was_suppressed|.
3511 OnDialogClosed(render_frame_host
->GetProcess()->GetID(),
3512 render_frame_host
->GetRoutingID(), reply_msg
,
3513 true, false, base::string16());
3516 // OnDialogClosed (two lines up) may have caused deletion of this object (see
3517 // http://crbug.com/288961 ). The only safe thing to do here is return.
3520 void WebContentsImpl::RunBeforeUnloadConfirm(
3521 RenderFrameHost
* render_frame_host
,
3522 const base::string16
& message
,
3524 IPC::Message
* reply_msg
) {
3525 RenderFrameHostImpl
* rfhi
=
3526 static_cast<RenderFrameHostImpl
*>(render_frame_host
);
3528 delegate_
->WillRunBeforeUnloadConfirm();
3530 bool suppress_this_message
=
3531 rfhi
->rfh_state() != RenderFrameHostImpl::STATE_DEFAULT
||
3532 ShowingInterstitialPage() || !delegate_
||
3533 delegate_
->ShouldSuppressDialogs(this) ||
3534 !delegate_
->GetJavaScriptDialogManager(this);
3535 if (suppress_this_message
) {
3536 rfhi
->JavaScriptDialogClosed(reply_msg
, true, base::string16(), true);
3540 is_showing_before_unload_dialog_
= true;
3541 dialog_manager_
= delegate_
->GetJavaScriptDialogManager(this);
3542 dialog_manager_
->RunBeforeUnloadDialog(
3543 this, message
, is_reload
,
3544 base::Bind(&WebContentsImpl::OnDialogClosed
, base::Unretained(this),
3545 render_frame_host
->GetProcess()->GetID(),
3546 render_frame_host
->GetRoutingID(), reply_msg
,
3550 WebContents
* WebContentsImpl::GetAsWebContents() {
3554 bool WebContentsImpl::IsNeverVisible() {
3557 return delegate_
->IsNeverVisible(this);
3561 gfx::NativeViewAccessible
WebContentsImpl::GetParentNativeViewAccessible() {
3562 return accessible_parent_
;
3566 RenderViewHostDelegateView
* WebContentsImpl::GetDelegateView() {
3567 return render_view_host_delegate_view_
;
3570 RendererPreferences
WebContentsImpl::GetRendererPrefs(
3571 BrowserContext
* browser_context
) const {
3572 return renderer_preferences_
;
3575 gfx::Rect
WebContentsImpl::GetRootWindowResizerRect() const {
3577 return delegate_
->GetRootWindowResizerRect();
3581 void WebContentsImpl::RemoveBrowserPluginEmbedder() {
3582 if (browser_plugin_embedder_
)
3583 browser_plugin_embedder_
.reset();
3586 void WebContentsImpl::RenderViewCreated(RenderViewHost
* render_view_host
) {
3587 // Don't send notifications if we are just creating a swapped-out RVH for
3588 // the opener chain. These won't be used for view-source or WebUI, so it's
3589 // ok to return early.
3590 if (!static_cast<RenderViewHostImpl
*>(render_view_host
)->is_active())
3594 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
3596 NotificationService::current()->Notify(
3597 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED
,
3598 Source
<WebContents
>(this),
3599 Details
<RenderViewHost
>(render_view_host
));
3601 // When we're creating views, we're still doing initial setup, so we always
3602 // use the pending Web UI rather than any possibly existing committed one.
3603 if (GetRenderManager()->pending_web_ui())
3604 GetRenderManager()->pending_web_ui()->RenderViewCreated(render_view_host
);
3606 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
3607 switches::kEnableBrowserSideNavigation
) &&
3608 GetRenderManager()->speculative_web_ui()) {
3609 GetRenderManager()->speculative_web_ui()->RenderViewCreated(
3613 NavigationEntry
* entry
= controller_
.GetPendingEntry();
3614 if (entry
&& entry
->IsViewSourceMode()) {
3615 // Put the renderer in view source mode.
3616 render_view_host
->Send(
3617 new ViewMsg_EnableViewSourceMode(render_view_host
->GetRoutingID()));
3620 view_
->RenderViewCreated(render_view_host
);
3623 WebContentsObserver
, observers_
, RenderViewCreated(render_view_host
));
3626 void WebContentsImpl::RenderViewReady(RenderViewHost
* rvh
) {
3627 if (rvh
!= GetRenderViewHost()) {
3628 // Don't notify the world, since this came from a renderer in the
3633 notify_disconnection_
= true;
3634 // TODO(avi): Remove. http://crbug.com/170921
3635 NotificationService::current()->Notify(
3636 NOTIFICATION_WEB_CONTENTS_CONNECTED
,
3637 Source
<WebContents
>(this),
3638 NotificationService::NoDetails());
3640 bool was_crashed
= IsCrashed();
3641 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING
, 0);
3643 // Restore the focus to the tab (otherwise the focus will be on the top
3645 if (was_crashed
&& !FocusLocationBarByDefault() &&
3646 (!delegate_
|| delegate_
->ShouldFocusPageAfterCrash())) {
3650 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, RenderViewReady());
3653 void WebContentsImpl::RenderViewTerminated(RenderViewHost
* rvh
,
3654 base::TerminationStatus status
,
3656 if (rvh
!= GetRenderViewHost()) {
3657 // The pending page's RenderViewHost is gone.
3661 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
3662 // renderer may not have made a clean exit.
3663 if (IsFullscreenForCurrentTab())
3664 ExitFullscreenMode();
3666 // Cancel any visible dialogs so they are not left dangling over the sad tab.
3667 CancelActiveAndPendingDialogs();
3670 delegate_
->HideValidationMessage(this);
3672 SetIsLoading(false, true, nullptr);
3673 NotifyDisconnected();
3674 SetIsCrashed(status
, error_code
);
3676 // Reset the loading progress. TODO(avi): What does it mean to have a
3677 // "renderer crash" when there is more than one renderer process serving a
3678 // webpage? Once this function is called at a more granular frame level, we
3679 // probably will need to more granularly reset the state here.
3680 ResetLoadProgressState();
3682 FOR_EACH_OBSERVER(WebContentsObserver
,
3684 RenderProcessGone(GetCrashedStatus()));
3687 void WebContentsImpl::RenderViewDeleted(RenderViewHost
* rvh
) {
3688 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, RenderViewDeleted(rvh
));
3691 void WebContentsImpl::UpdateState(RenderViewHost
* rvh
,
3693 const PageState
& page_state
) {
3694 // Ensure that this state update comes from a RenderViewHost that belongs to
3695 // this WebContents.
3696 // TODO(nasko): This should go through RenderFrameHost.
3697 // TODO(creis): We can't update state for cross-process subframes until we
3698 // have FrameNavigationEntries. Once we do, this should be a DCHECK.
3699 if (rvh
->GetDelegate()->GetAsWebContents() != this)
3702 // We must be prepared to handle state updates for any page, these occur
3703 // when the user is scrolling and entering form data, as well as when we're
3704 // leaving a page, in which case our state may have already been moved to
3705 // the next page. The navigation controller will look up the appropriate
3706 // NavigationEntry and update it when it is notified via the delegate.
3707 NavigationEntryImpl
* entry
= controller_
.GetEntryWithPageID(
3708 rvh
->GetSiteInstance(), page_id
);
3713 if (page_state
== entry
->GetPageState())
3714 return; // Nothing to update.
3715 entry
->SetPageState(page_state
);
3716 controller_
.NotifyEntryChanged(entry
);
3719 void WebContentsImpl::UpdateTargetURL(RenderViewHost
* render_view_host
,
3721 if (fullscreen_widget_routing_id_
!= MSG_ROUTING_NONE
) {
3722 // If we're fullscreen only update the url if it's from the fullscreen
3724 RenderWidgetHostView
* fs
= GetFullscreenRenderWidgetHostView();
3725 if (fs
&& fs
->GetRenderWidgetHost() != render_view_host
)
3729 delegate_
->UpdateTargetURL(this, url
);
3732 void WebContentsImpl::Close(RenderViewHost
* rvh
) {
3733 #if defined(OS_MACOSX)
3734 // The UI may be in an event-tracking loop, such as between the
3735 // mouse-down and mouse-up in text selection or a button click.
3736 // Defer the close until after tracking is complete, so that we
3737 // don't free objects out from under the UI.
3738 // TODO(shess): This could get more fine-grained. For instance,
3739 // closing a tab in another window while selecting text in the
3740 // current window's Omnibox should be just fine.
3741 if (view_
->IsEventTracking()) {
3742 view_
->CloseTabAfterEventTracking();
3747 // Ignore this if it comes from a RenderViewHost that we aren't showing.
3748 if (delegate_
&& rvh
== GetRenderViewHost())
3749 delegate_
->CloseContents(this);
3752 void WebContentsImpl::SwappedOut(RenderFrameHost
* rfh
) {
3753 if (delegate_
&& rfh
->GetRenderViewHost() == GetRenderViewHost())
3754 delegate_
->SwappedOut(this);
3757 void WebContentsImpl::RequestMove(const gfx::Rect
& new_bounds
) {
3758 if (delegate_
&& delegate_
->IsPopupOrPanel(this))
3759 delegate_
->MoveContents(this, new_bounds
);
3762 void WebContentsImpl::DidStartLoading(FrameTreeNode
* frame_tree_node
,
3763 bool to_different_document
) {
3764 SetIsLoading(true, to_different_document
, nullptr);
3766 // Notify accessibility that the user is navigating away from the
3767 // current document.
3769 // TODO(dmazzoni): do this using a WebContentsObserver.
3770 BrowserAccessibilityManager
* manager
=
3771 frame_tree_node
->current_frame_host()->browser_accessibility_manager();
3773 manager
->UserIsNavigatingAway();
3776 void WebContentsImpl::DidStopLoading() {
3777 scoped_ptr
<LoadNotificationDetails
> details
;
3779 // Use the last committed entry rather than the active one, in case a
3780 // pending entry has been created.
3781 NavigationEntry
* entry
= controller_
.GetLastCommittedEntry();
3782 Navigator
* navigator
= frame_tree_
.root()->navigator();
3784 // An entry may not exist for a stop when loading an initial blank page or
3785 // if an iframe injected by script into a blank page finishes loading.
3787 base::TimeDelta elapsed
=
3788 base::TimeTicks::Now() - navigator
->GetCurrentLoadStart();
3790 details
.reset(new LoadNotificationDetails(
3791 entry
->GetVirtualURL(),
3792 entry
->GetTransitionType(),
3795 controller_
.GetCurrentEntryIndex()));
3798 SetIsLoading(false, true, details
.get());
3801 void WebContentsImpl::DidChangeLoadProgress() {
3802 double load_progress
= frame_tree_
.load_progress();
3804 // The delegate is notified immediately for the first and last updates. Also,
3805 // since the message loop may be pretty busy when a page is loaded, it might
3806 // not execute a posted task in a timely manner so the progress report is sent
3807 // immediately if enough time has passed.
3808 base::TimeDelta min_delay
=
3809 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS
);
3810 bool delay_elapsed
= loading_last_progress_update_
.is_null() ||
3811 base::TimeTicks::Now() - loading_last_progress_update_
> min_delay
;
3813 if (load_progress
== 0.0 || load_progress
== 1.0 || delay_elapsed
) {
3814 // If there is a pending task to send progress, it is now obsolete.
3815 loading_weak_factory_
.InvalidateWeakPtrs();
3817 // Notify the load progress change.
3818 SendChangeLoadProgress();
3820 // Clean-up the states if needed.
3821 if (load_progress
== 1.0)
3822 ResetLoadProgressState();
3826 if (loading_weak_factory_
.HasWeakPtrs())
3829 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
3830 FROM_HERE
, base::Bind(&WebContentsImpl::SendChangeLoadProgress
,
3831 loading_weak_factory_
.GetWeakPtr()),
3835 void WebContentsImpl::DidCancelLoading() {
3836 controller_
.DiscardNonCommittedEntries();
3838 // Update the URL display.
3839 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL
);
3842 void WebContentsImpl::DidAccessInitialDocument() {
3843 has_accessed_initial_document_
= true;
3845 // We may have left a failed browser-initiated navigation in the address bar
3846 // to let the user edit it and try again. Clear it now that content might
3847 // show up underneath it.
3848 if (!IsLoading() && controller_
.GetPendingEntry())
3849 controller_
.DiscardPendingEntry(false);
3851 // Update the URL display.
3852 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL
);
3855 void WebContentsImpl::DidChangeName(RenderFrameHost
* render_frame_host
,
3856 const std::string
& name
) {
3857 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3858 FrameNameChanged(render_frame_host
, name
));
3861 void WebContentsImpl::DocumentOnLoadCompleted(
3862 RenderFrameHost
* render_frame_host
) {
3863 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3864 DocumentOnLoadCompletedInMainFrame());
3866 // TODO(avi): Remove. http://crbug.com/170921
3867 NotificationService::current()->Notify(
3868 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
,
3869 Source
<WebContents
>(this),
3870 NotificationService::NoDetails());
3873 void WebContentsImpl::UpdateTitle(RenderFrameHost
* render_frame_host
,
3875 const base::string16
& title
,
3876 base::i18n::TextDirection title_direction
) {
3877 RenderViewHost
* rvh
= render_frame_host
->GetRenderViewHost();
3879 // If we have a title, that's a pretty good indication that we've started
3880 // getting useful data.
3881 SetNotWaitingForResponse();
3883 // Try to find the navigation entry, which might not be the current one.
3884 // For example, it might be from a pending RVH for the pending entry.
3885 NavigationEntryImpl
* entry
= controller_
.GetEntryWithPageID(
3886 rvh
->GetSiteInstance(), page_id
);
3888 // We can handle title updates when we don't have an entry in
3889 // UpdateTitleForEntry, but only if the update is from the current RVH.
3890 // TODO(avi): Change to make decisions based on the RenderFrameHost.
3891 if (!entry
&& rvh
!= GetRenderViewHost())
3894 // TODO(evan): make use of title_direction.
3895 // http://code.google.com/p/chromium/issues/detail?id=27094
3896 if (!UpdateTitleForEntry(entry
, title
))
3899 // Broadcast notifications when the UI should be updated.
3900 if (entry
== controller_
.GetEntryAtOffset(0))
3901 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE
);
3904 void WebContentsImpl::UpdateEncoding(RenderFrameHost
* render_frame_host
,
3905 const std::string
& encoding
) {
3906 SetEncoding(encoding
);
3909 void WebContentsImpl::DocumentAvailableInMainFrame(
3910 RenderViewHost
* render_view_host
) {
3911 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3912 DocumentAvailableInMainFrame());
3915 void WebContentsImpl::RouteCloseEvent(RenderViewHost
* rvh
) {
3916 // Tell the active RenderViewHost to run unload handlers and close, as long
3917 // as the request came from a RenderViewHost in the same BrowsingInstance.
3918 // In most cases, we receive this from a swapped out RenderViewHost.
3919 // It is possible to receive it from one that has just been swapped in,
3920 // in which case we might as well deliver the message anyway.
3921 if (rvh
->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()))
3925 bool WebContentsImpl::ShouldRouteMessageEvent(
3926 RenderFrameHost
* target_rfh
,
3927 SiteInstance
* source_site_instance
) const {
3928 // Allow the message if this WebContents is dedicated to a browser plugin
3930 // Note: This check means that an embedder could theoretically receive a
3931 // postMessage from anyone (not just its own guests). However, this is
3932 // probably not a risk for apps since other pages won't have references
3934 return GetBrowserPluginGuest() || GetBrowserPluginEmbedder();
3937 int WebContentsImpl::EnsureOpenerRenderViewsExist(
3938 RenderFrameHost
* source_rfh
) {
3939 WebContentsImpl
* source_web_contents
= static_cast<WebContentsImpl
*>(
3940 WebContents::FromRenderFrameHost(source_rfh
));
3942 if (source_web_contents
) {
3943 if (GetBrowserPluginGuest()) {
3944 // We create a swapped out RenderView for the embedder in the guest's
3945 // render process but we intentionally do not expose the embedder's
3946 // opener chain to it.
3948 source_web_contents
->CreateSwappedOutRenderView(GetSiteInstance());
3950 return source_web_contents
->CreateOpenerRenderViews(GetSiteInstance());
3954 return MSG_ROUTING_NONE
;
3957 bool WebContentsImpl::AddMessageToConsole(int32 level
,
3958 const base::string16
& message
,
3960 const base::string16
& source_id
) {
3963 return delegate_
->AddMessageToConsole(this, level
, message
, line_no
,
3967 int WebContentsImpl::CreateSwappedOutRenderView(
3968 SiteInstance
* instance
) {
3969 int render_view_routing_id
= MSG_ROUTING_NONE
;
3970 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
3971 switches::kSitePerProcess
)) {
3972 GetRenderManager()->CreateRenderFrameProxy(instance
);
3974 GetRenderManager()->CreateRenderFrame(
3975 instance
, nullptr, MSG_ROUTING_NONE
,
3976 CREATE_RF_SWAPPED_OUT
| CREATE_RF_FOR_MAIN_FRAME_NAVIGATION
|
3978 &render_view_routing_id
);
3980 return render_view_routing_id
;
3983 void WebContentsImpl::OnUserGesture() {
3984 // Notify observers.
3985 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, DidGetUserGesture());
3987 ResourceDispatcherHostImpl
* rdh
= ResourceDispatcherHostImpl::Get();
3988 if (rdh
) // NULL in unittests.
3989 rdh
->OnUserGesture(this);
3992 void WebContentsImpl::OnIgnoredUIEvent() {
3993 // Notify observers.
3994 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, DidGetIgnoredUIEvent());
3997 void WebContentsImpl::RendererUnresponsive(RenderViewHost
* render_view_host
) {
3998 // Don't show hung renderer dialog for a swapped out RVH.
3999 if (render_view_host
!= GetRenderViewHost())
4002 RenderViewHostImpl
* rvhi
= static_cast<RenderViewHostImpl
*>(render_view_host
);
4003 RenderFrameHostImpl
* rfhi
=
4004 static_cast<RenderFrameHostImpl
*>(rvhi
->GetMainFrame());
4006 // Ignore renderer unresponsive event if debugger is attached to the tab
4007 // since the event may be a result of the renderer sitting on a breakpoint.
4008 // See http://crbug.com/65458
4009 if (DevToolsAgentHost::IsDebuggerAttached(this))
4012 if (rfhi
->IsWaitingForBeforeUnloadACK() ||
4013 rfhi
->IsWaitingForUnloadACK()) {
4014 // Hang occurred while firing the beforeunload/unload handler.
4015 // Pretend the handler fired so tab closing continues as if it had.
4016 rvhi
->set_sudden_termination_allowed(true);
4018 if (!GetRenderManager()->ShouldCloseTabOnUnresponsiveRenderer())
4021 // If the tab hangs in the beforeunload/unload handler there's really
4022 // nothing we can do to recover. If the hang is in the beforeunload handler,
4023 // pretend the beforeunload listeners have all fired and allow the delegate
4024 // to continue closing; the user will not have the option of cancelling the
4025 // close. Otherwise, pretend the unload listeners have all fired and close
4028 if (rfhi
->IsWaitingForBeforeUnloadACK() && delegate_
) {
4029 delegate_
->BeforeUnloadFired(this, true, &close
);
4036 if (!GetRenderViewHost() || !GetRenderViewHost()->IsRenderViewLive())
4040 delegate_
->RendererUnresponsive(this);
4043 void WebContentsImpl::RendererResponsive(RenderViewHost
* render_view_host
) {
4045 delegate_
->RendererResponsive(this);
4048 void WebContentsImpl::LoadStateChanged(
4050 const net::LoadStateWithParam
& load_state
,
4051 uint64 upload_position
,
4052 uint64 upload_size
) {
4053 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
4055 tracked_objects::ScopedTracker
tracking_profile1(
4056 FROM_HERE_WITH_EXPLICIT_FUNCTION(
4057 "466285 WebContentsImpl::LoadStateChanged::Start"));
4058 load_state_
= load_state
;
4059 upload_position_
= upload_position
;
4060 upload_size_
= upload_size
;
4061 load_state_host_
= net::IDNToUnicode(url
.host(),
4062 GetContentClient()->browser()->GetAcceptLangs(
4063 GetBrowserContext()));
4064 if (load_state_
.state
== net::LOAD_STATE_READING_RESPONSE
)
4065 SetNotWaitingForResponse();
4067 NotifyNavigationStateChanged(static_cast<InvalidateTypes
>(
4068 INVALIDATE_TYPE_LOAD
| INVALIDATE_TYPE_TAB
));
4072 void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
4073 bool proceed
, const base::TimeTicks
& proceed_time
,
4074 bool* proceed_to_fire_unload
) {
4075 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
4076 BeforeUnloadFired(proceed_time
));
4078 delegate_
->BeforeUnloadFired(this, proceed
, proceed_to_fire_unload
);
4079 // Note: |this| might be deleted at this point.
4082 void WebContentsImpl::RenderProcessGoneFromRenderManager(
4083 RenderViewHost
* render_view_host
) {
4084 DCHECK(crashed_status_
!= base::TERMINATION_STATUS_STILL_RUNNING
);
4085 RenderViewTerminated(render_view_host
, crashed_status_
, crashed_error_code_
);
4088 void WebContentsImpl::UpdateRenderViewSizeForRenderManager() {
4089 // TODO(brettw) this is a hack. See WebContentsView::SizeContents.
4090 gfx::Size size
= GetSizeForNewRenderView();
4091 // 0x0 isn't a valid window size (minimal window size is 1x1) but it may be
4092 // here during container initialization and normal window size will be set
4093 // later. In case of tab duplication this resizing to 0x0 prevents setting
4094 // normal size later so just ignore it.
4095 if (!size
.IsEmpty())
4096 view_
->SizeContents(size
);
4099 void WebContentsImpl::CancelModalDialogsForRenderManager() {
4100 // We need to cancel modal dialogs when doing a process swap, since the load
4101 // deferrer would prevent us from swapping out. We also clear the state
4102 // because this is a cross-process navigation, which means that it's a new
4103 // site that should not have to pay for the sins of its predecessor.
4105 // Note that we don't bother telling browser_plugin_embedder_ because the
4106 // cross-process navigation will either destroy the browser plugins or not
4107 // require their dialogs to close.
4108 if (dialog_manager_
)
4109 dialog_manager_
->ResetDialogState(this);
4112 void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost
* old_host
,
4113 RenderFrameHost
* new_host
,
4114 bool is_main_frame
) {
4115 if (is_main_frame
) {
4116 NotifyViewSwapped(old_host
? old_host
->GetRenderViewHost() : nullptr,
4117 new_host
->GetRenderViewHost());
4119 // Make sure the visible RVH reflects the new delegate's preferences.
4121 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
4123 view_
->RenderViewSwappedIn(new_host
->GetRenderViewHost());
4126 NotifyFrameSwapped(old_host
, new_host
);
4129 void WebContentsImpl::NotifyMainFrameSwappedFromRenderManager(
4130 RenderViewHost
* old_host
,
4131 RenderViewHost
* new_host
) {
4132 NotifyViewSwapped(old_host
, new_host
);
4135 int WebContentsImpl::CreateOpenerRenderViewsForRenderManager(
4136 SiteInstance
* instance
) {
4137 WebContentsImpl
* opener
= GetOpener();
4139 return MSG_ROUTING_NONE
;
4141 // Recursively create RenderViews for anything else in the opener chain.
4142 return opener
->CreateOpenerRenderViews(instance
);
4145 int WebContentsImpl::CreateOpenerRenderViews(SiteInstance
* instance
) {
4146 int opener_route_id
= MSG_ROUTING_NONE
;
4148 // If this tab has an opener, ensure it has a RenderView in the given
4149 // SiteInstance as well.
4150 WebContentsImpl
* opener
= GetOpener();
4152 opener_route_id
= opener
->CreateOpenerRenderViews(instance
);
4154 // If any of the renderers (current, pending, or swapped out) for this
4155 // WebContents has the same SiteInstance, use it.
4156 if (GetRenderManager()->current_host()->GetSiteInstance() == instance
)
4157 return GetRenderManager()->current_host()->GetRoutingID();
4159 if (GetRenderManager()->pending_render_view_host() &&
4160 GetRenderManager()->pending_render_view_host()->GetSiteInstance() ==
4162 return GetRenderManager()->pending_render_view_host()->GetRoutingID();
4164 RenderViewHostImpl
* rvh
= GetRenderManager()->GetSwappedOutRenderViewHost(
4167 return rvh
->GetRoutingID();
4169 // Create a swapped out RenderView in the given SiteInstance if none exists,
4170 // setting its opener to the given route_id. Return the new view's route_id.
4171 int render_view_routing_id
= MSG_ROUTING_NONE
;
4172 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4173 switches::kSitePerProcess
)) {
4174 GetRenderManager()->CreateRenderFrameProxy(instance
);
4175 render_view_routing_id
=
4176 frame_tree_
.GetRenderViewHost(instance
)->GetRoutingID();
4178 GetRenderManager()->CreateRenderFrame(instance
, nullptr, opener_route_id
,
4179 CREATE_RF_FOR_MAIN_FRAME_NAVIGATION
|
4180 CREATE_RF_SWAPPED_OUT
|
4182 &render_view_routing_id
);
4184 return render_view_routing_id
;
4187 NavigationControllerImpl
& WebContentsImpl::GetControllerForRenderManager() {
4188 return GetController();
4191 scoped_ptr
<WebUIImpl
> WebContentsImpl::CreateWebUIForRenderManager(
4193 return scoped_ptr
<WebUIImpl
>(static_cast<WebUIImpl
*>(CreateWebUI(url
)));
4197 WebContentsImpl::GetLastCommittedNavigationEntryForRenderManager() {
4198 return controller_
.GetLastCommittedEntry();
4201 bool WebContentsImpl::CreateRenderViewForRenderManager(
4202 RenderViewHost
* render_view_host
,
4203 int opener_route_id
,
4204 int proxy_routing_id
,
4205 const FrameReplicationState
& replicated_frame_state
,
4206 bool for_main_frame_navigation
) {
4207 TRACE_EVENT0("browser,navigation",
4208 "WebContentsImpl::CreateRenderViewForRenderManager");
4209 // Can be NULL during tests.
4210 RenderWidgetHostViewBase
* rwh_view
;
4211 // TODO(kenrb): RenderWidgetHostViewChildFrame special casing is temporary
4212 // until RenderWidgetHost is attached to RenderFrameHost. We need to special
4213 // case this because RWH is still a base class of RenderViewHost, and child
4214 // frame RWHVs are unique in that they do not have their own WebContents.
4215 if (!for_main_frame_navigation
) {
4216 RenderWidgetHostViewChildFrame
* rwh_view_child
=
4217 new RenderWidgetHostViewChildFrame(render_view_host
);
4218 rwh_view
= rwh_view_child
;
4220 rwh_view
= view_
->CreateViewForWidget(render_view_host
, false);
4223 // Now that the RenderView has been created, we need to tell it its size.
4225 rwh_view
->SetSize(GetSizeForNewRenderView());
4227 // Make sure we use the correct starting page_id in the new RenderView.
4228 UpdateMaxPageIDIfNecessary(render_view_host
);
4230 GetMaxPageIDForSiteInstance(render_view_host
->GetSiteInstance());
4232 if (!static_cast<RenderViewHostImpl
*>(
4233 render_view_host
)->CreateRenderView(base::string16(),
4237 replicated_frame_state
,
4238 created_with_opener_
)) {
4242 SetHistoryOffsetAndLengthForView(render_view_host
,
4243 controller_
.GetLastCommittedEntryIndex(),
4244 controller_
.GetEntryCount());
4246 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
4247 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
4248 // linux. See crbug.com/83941.
4250 if (RenderWidgetHost
* render_widget_host
= rwh_view
->GetRenderWidgetHost())
4251 render_widget_host
->WasResized();
4258 bool WebContentsImpl::CreateRenderFrameForRenderManager(
4259 RenderFrameHost
* render_frame_host
,
4260 int parent_routing_id
,
4261 int previous_sibling_routing_id
,
4262 int proxy_routing_id
) {
4263 TRACE_EVENT0("browser,navigation",
4264 "WebContentsImpl::CreateRenderFrameForRenderManager");
4266 RenderFrameHostImpl
* rfh
=
4267 static_cast<RenderFrameHostImpl
*>(render_frame_host
);
4268 if (!rfh
->CreateRenderFrame(parent_routing_id
, previous_sibling_routing_id
,
4272 // TODO(nasko): When RenderWidgetHost is owned by RenderFrameHost, the passed
4273 // RenderFrameHost will have to be associated with the appropriate
4274 // RenderWidgetHostView or a new one should be created here.
4279 #if defined(OS_ANDROID)
4281 base::android::ScopedJavaLocalRef
<jobject
>
4282 WebContentsImpl::GetJavaWebContents() {
4283 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
4284 return GetWebContentsAndroid()->GetJavaObject();
4287 WebContentsAndroid
* WebContentsImpl::GetWebContentsAndroid() {
4288 WebContentsAndroid
* web_contents_android
=
4289 static_cast<WebContentsAndroid
*>(GetUserData(kWebContentsAndroidKey
));
4290 if (!web_contents_android
) {
4291 web_contents_android
= new WebContentsAndroid(this);
4292 SetUserData(kWebContentsAndroidKey
, web_contents_android
);
4294 return web_contents_android
;
4297 bool WebContentsImpl::CreateRenderViewForInitialEmptyDocument() {
4298 return CreateRenderViewForRenderManager(
4299 GetRenderViewHost(), MSG_ROUTING_NONE
, MSG_ROUTING_NONE
,
4300 frame_tree_
.root()->current_replication_state(), true);
4303 #elif defined(OS_MACOSX)
4305 void WebContentsImpl::SetAllowOtherViews(bool allow
) {
4306 view_
->SetAllowOtherViews(allow
);
4309 bool WebContentsImpl::GetAllowOtherViews() {
4310 return view_
->GetAllowOtherViews();
4315 void WebContentsImpl::OnDialogClosed(int render_process_id
,
4316 int render_frame_id
,
4317 IPC::Message
* reply_msg
,
4318 bool dialog_was_suppressed
,
4320 const base::string16
& user_input
) {
4321 RenderFrameHostImpl
* rfh
= RenderFrameHostImpl::FromID(render_process_id
,
4323 last_dialog_suppressed_
= dialog_was_suppressed
;
4325 if (is_showing_before_unload_dialog_
&& !success
) {
4326 // If a beforeunload dialog is canceled, we need to stop the throbber from
4327 // spinning, since we forced it to start spinning in Navigate.
4330 controller_
.DiscardNonCommittedEntries();
4332 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
4333 BeforeUnloadDialogCancelled());
4336 is_showing_before_unload_dialog_
= false;
4338 rfh
->JavaScriptDialogClosed(reply_msg
, success
, user_input
,
4339 dialog_was_suppressed
);
4341 // Don't leak the sync IPC reply if the RFH or process is gone.
4346 void WebContentsImpl::SetEncoding(const std::string
& encoding
) {
4347 if (encoding
== last_reported_encoding_
)
4349 last_reported_encoding_
= encoding
;
4351 canonical_encoding_
= GetContentClient()->browser()->
4352 GetCanonicalEncodingNameByAliasName(encoding
);
4355 bool WebContentsImpl::IsHidden() {
4356 return capturer_count_
== 0 && !should_normally_be_visible_
;
4359 RenderFrameHostManager
* WebContentsImpl::GetRenderManager() const {
4360 return frame_tree_
.root()->render_manager();
4363 BrowserPluginGuest
* WebContentsImpl::GetBrowserPluginGuest() const {
4364 return browser_plugin_guest_
.get();
4367 void WebContentsImpl::SetBrowserPluginGuest(BrowserPluginGuest
* guest
) {
4368 CHECK(!browser_plugin_guest_
);
4369 browser_plugin_guest_
.reset(guest
);
4372 BrowserPluginEmbedder
* WebContentsImpl::GetBrowserPluginEmbedder() const {
4373 return browser_plugin_embedder_
.get();
4376 void WebContentsImpl::CreateBrowserPluginEmbedderIfNecessary() {
4377 if (browser_plugin_embedder_
)
4379 browser_plugin_embedder_
.reset(BrowserPluginEmbedder::Create(this));
4382 void WebContentsImpl::ClearPowerSaveBlockers(
4383 RenderFrameHost
* render_frame_host
) {
4384 RemoveAllMediaPlayerEntries(render_frame_host
, &active_audio_players_
);
4385 RemoveAllMediaPlayerEntries(render_frame_host
, &active_video_players_
);
4386 MaybeReleasePowerSaveBlockers();
4389 void WebContentsImpl::ClearAllPowerSaveBlockers() {
4390 active_audio_players_
.clear();
4391 active_video_players_
.clear();
4392 audio_power_save_blocker_
.reset();
4393 video_power_save_blocker_
.reset();
4396 gfx::Size
WebContentsImpl::GetSizeForNewRenderView() {
4399 size
= delegate_
->GetSizeForNewRenderView(this);
4401 size
= GetContainerBounds().size();
4405 void WebContentsImpl::OnFrameRemoved(RenderFrameHost
* render_frame_host
) {
4407 WebContentsObserver
, observers_
, FrameDeleted(render_frame_host
));
4410 void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size
& old_size
) {
4413 const gfx::Size new_size
= GetPreferredSize();
4414 if (new_size
!= old_size
)
4415 delegate_
->UpdatePreferredSize(this, new_size
);
4418 void WebContentsImpl::AddMediaPlayerEntry(int64 player_cookie
,
4419 ActiveMediaPlayerMap
* player_map
) {
4420 if (!HasValidFrameSource())
4423 const uintptr_t key
=
4424 reinterpret_cast<uintptr_t>(render_frame_message_source_
);
4425 DCHECK(std::find((*player_map
)[key
].begin(),
4426 (*player_map
)[key
].end(),
4427 player_cookie
) == (*player_map
)[key
].end());
4428 (*player_map
)[key
].push_back(player_cookie
);
4431 void WebContentsImpl::RemoveMediaPlayerEntry(int64 player_cookie
,
4432 ActiveMediaPlayerMap
* player_map
) {
4433 if (!HasValidFrameSource())
4436 const uintptr_t key
=
4437 reinterpret_cast<uintptr_t>(render_frame_message_source_
);
4438 ActiveMediaPlayerMap::iterator it
= player_map
->find(key
);
4439 if (it
== player_map
->end())
4442 // Remove the player.
4443 PlayerList::iterator player_it
=
4444 std::find(it
->second
.begin(), it
->second
.end(), player_cookie
);
4445 if (player_it
!= it
->second
.end())
4446 it
->second
.erase(player_it
);
4448 // If there are no players left, remove the map entry.
4449 if (it
->second
.empty())
4450 player_map
->erase(it
);
4453 void WebContentsImpl::RemoveAllMediaPlayerEntries(
4454 RenderFrameHost
* render_frame_host
,
4455 ActiveMediaPlayerMap
* player_map
) {
4456 ActiveMediaPlayerMap::iterator it
=
4457 player_map
->find(reinterpret_cast<uintptr_t>(render_frame_host
));
4458 if (it
== player_map
->end())
4460 player_map
->erase(it
);
4463 void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable
) {
4464 force_disable_overscroll_content_
= force_disable
;
4466 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
4469 } // namespace content