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/logging.h"
12 #include "base/metrics/histogram.h"
13 #include "base/process/process.h"
14 #include "base/profiler/scoped_tracker.h"
15 #include "base/strings/string16.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/string_util.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/time/time.h"
20 #include "base/trace_event/trace_event.h"
21 #include "content/browser/accessibility/accessibility_mode_helper.h"
22 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
23 #include "content/browser/bad_message.h"
24 #include "content/browser/browser_plugin/browser_plugin_embedder.h"
25 #include "content/browser/browser_plugin/browser_plugin_guest.h"
26 #include "content/browser/child_process_security_policy_impl.h"
27 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
28 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
29 #include "content/browser/download/download_stats.h"
30 #include "content/browser/download/mhtml_generation_manager.h"
31 #include "content/browser/download/save_package.h"
32 #include "content/browser/frame_host/cross_process_frame_connector.h"
33 #include "content/browser/frame_host/interstitial_page_impl.h"
34 #include "content/browser/frame_host/navigation_entry_impl.h"
35 #include "content/browser/frame_host/navigator_impl.h"
36 #include "content/browser/frame_host/render_frame_host_impl.h"
37 #include "content/browser/frame_host/render_widget_host_view_child_frame.h"
38 #include "content/browser/geolocation/geolocation_service_context.h"
39 #include "content/browser/host_zoom_map_impl.h"
40 #include "content/browser/loader/resource_dispatcher_host_impl.h"
41 #include "content/browser/manifest/manifest_manager_host.h"
42 #include "content/browser/media/audio_stream_monitor.h"
43 #include "content/browser/media/capture/web_contents_audio_muter.h"
44 #include "content/browser/message_port_message_filter.h"
45 #include "content/browser/plugin_content_origin_whitelist.h"
46 #include "content/browser/power_save_blocker_impl.h"
47 #include "content/browser/renderer_host/render_process_host_impl.h"
48 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
49 #include "content/browser/renderer_host/render_view_host_impl.h"
50 #include "content/browser/renderer_host/render_widget_host_impl.h"
51 #include "content/browser/renderer_host/render_widget_host_view_base.h"
52 #include "content/browser/screen_orientation/screen_orientation_dispatcher_host_impl.h"
53 #include "content/browser/site_instance_impl.h"
54 #include "content/browser/web_contents/web_contents_view_guest.h"
55 #include "content/browser/webui/generic_handler.h"
56 #include "content/browser/webui/web_ui_controller_factory_registry.h"
57 #include "content/browser/webui/web_ui_impl.h"
58 #include "content/common/browser_plugin/browser_plugin_constants.h"
59 #include "content/common/browser_plugin/browser_plugin_messages.h"
60 #include "content/common/frame_messages.h"
61 #include "content/common/image_messages.h"
62 #include "content/common/input_messages.h"
63 #include "content/common/ssl_status_serialization.h"
64 #include "content/common/view_messages.h"
65 #include "content/public/browser/ax_event_notification_details.h"
66 #include "content/public/browser/browser_context.h"
67 #include "content/public/browser/browser_plugin_guest_manager.h"
68 #include "content/public/browser/content_browser_client.h"
69 #include "content/public/browser/devtools_agent_host.h"
70 #include "content/public/browser/download_manager.h"
71 #include "content/public/browser/download_url_parameters.h"
72 #include "content/public/browser/invalidate_type.h"
73 #include "content/public/browser/javascript_dialog_manager.h"
74 #include "content/public/browser/load_from_memory_cache_details.h"
75 #include "content/public/browser/load_notification_details.h"
76 #include "content/public/browser/navigation_details.h"
77 #include "content/public/browser/notification_details.h"
78 #include "content/public/browser/notification_service.h"
79 #include "content/public/browser/render_widget_host_iterator.h"
80 #include "content/public/browser/resource_request_details.h"
81 #include "content/public/browser/screen_orientation_dispatcher_host.h"
82 #include "content/public/browser/storage_partition.h"
83 #include "content/public/browser/user_metrics.h"
84 #include "content/public/browser/web_contents_delegate.h"
85 #include "content/public/browser/web_contents_observer.h"
86 #include "content/public/common/bindings_policy.h"
87 #include "content/public/common/content_constants.h"
88 #include "content/public/common/content_switches.h"
89 #include "content/public/common/page_zoom.h"
90 #include "content/public/common/result_codes.h"
91 #include "content/public/common/url_constants.h"
92 #include "content/public/common/url_utils.h"
93 #include "content/public/common/web_preferences.h"
94 #include "net/base/mime_util.h"
95 #include "net/base/net_util.h"
96 #include "net/http/http_cache.h"
97 #include "net/http/http_transaction_factory.h"
98 #include "net/url_request/url_request_context.h"
99 #include "net/url_request/url_request_context_getter.h"
100 #include "ui/base/layout.h"
101 #include "ui/gfx/display.h"
102 #include "ui/gfx/screen.h"
103 #include "ui/gl/gl_switches.h"
105 #if defined(ENABLE_BROWSER_CDMS)
106 #include "content/browser/media/media_web_contents_observer.h"
109 #if defined(OS_ANDROID)
110 #include "content/browser/android/content_video_view.h"
111 #include "content/browser/android/date_time_chooser_android.h"
112 #include "content/browser/android/media_players_observer.h"
113 #include "content/browser/media/android/browser_media_player_manager.h"
114 #include "content/browser/web_contents/web_contents_android.h"
117 #if defined(OS_MACOSX)
118 #include "base/mac/foundation_util.h"
124 const int kMinimumDelayBetweenLoadingUpdatesMS
= 100;
125 const char kDotGoogleDotCom
[] = ".google.com";
127 #if defined(OS_ANDROID)
128 const char kWebContentsAndroidKey
[] = "web_contents_android";
131 base::LazyInstance
<std::vector
<WebContentsImpl::CreatedCallback
> >
132 g_created_callbacks
= LAZY_INSTANCE_INITIALIZER
;
134 static int StartDownload(RenderFrameHost
* rfh
,
137 uint32_t max_bitmap_size
,
139 static int g_next_image_download_id
= 0;
140 rfh
->Send(new ImageMsg_DownloadImage(rfh
->GetRoutingID(),
141 ++g_next_image_download_id
,
146 return g_next_image_download_id
;
149 void NotifyCacheOnIO(
150 scoped_refptr
<net::URLRequestContextGetter
> request_context
,
152 const std::string
& http_method
) {
153 net::HttpCache
* cache
= request_context
->GetURLRequestContext()->
154 http_transaction_factory()->GetCache();
156 cache
->OnExternalCacheHit(url
, http_method
);
159 // Helper function for retrieving all the sites in a frame tree.
160 bool CollectSites(BrowserContext
* context
,
161 std::set
<GURL
>* sites
,
162 FrameTreeNode
* node
) {
163 sites
->insert(SiteInstance::GetSiteForURL(context
, node
->current_url()));
167 bool ForEachFrameInternal(
168 const base::Callback
<void(RenderFrameHost
*)>& on_frame
,
169 FrameTreeNode
* node
) {
170 on_frame
.Run(node
->current_frame_host());
174 bool ForEachPendingFrameInternal(
175 const base::Callback
<void(RenderFrameHost
*)>& on_frame
,
176 FrameTreeNode
* node
) {
177 RenderFrameHost
* pending_frame_host
=
178 node
->render_manager()->pending_frame_host();
179 if (pending_frame_host
)
180 on_frame
.Run(pending_frame_host
);
184 void SendToAllFramesInternal(IPC::Message
* message
, RenderFrameHost
* rfh
) {
185 IPC::Message
* message_copy
= new IPC::Message(*message
);
186 message_copy
->set_routing_id(rfh
->GetRoutingID());
187 rfh
->Send(message_copy
);
190 void AddRenderWidgetHostViewToSet(std::set
<RenderWidgetHostView
*>* set
,
191 RenderFrameHost
* rfh
) {
192 RenderWidgetHostView
* rwhv
= static_cast<RenderFrameHostImpl
*>(rfh
)
195 ->GetRenderWidgetHostView();
199 void SetAccessibilityModeOnFrame(AccessibilityMode mode
,
200 RenderFrameHost
* frame_host
) {
201 static_cast<RenderFrameHostImpl
*>(frame_host
)->SetAccessibilityMode(mode
);
206 WebContents
* WebContents::Create(const WebContents::CreateParams
& params
) {
207 return WebContentsImpl::CreateWithOpener(
208 params
, static_cast<WebContentsImpl
*>(params
.opener
));
211 WebContents
* WebContents::CreateWithSessionStorage(
212 const WebContents::CreateParams
& params
,
213 const SessionStorageNamespaceMap
& session_storage_namespace_map
) {
214 WebContentsImpl
* new_contents
= new WebContentsImpl(
215 params
.browser_context
, NULL
);
217 for (SessionStorageNamespaceMap::const_iterator it
=
218 session_storage_namespace_map
.begin();
219 it
!= session_storage_namespace_map
.end();
221 new_contents
->GetController()
222 .SetSessionStorageNamespace(it
->first
, it
->second
.get());
225 new_contents
->Init(params
);
229 void WebContentsImpl::FriendZone::AddCreatedCallbackForTesting(
230 const CreatedCallback
& callback
) {
231 g_created_callbacks
.Get().push_back(callback
);
234 void WebContentsImpl::FriendZone::RemoveCreatedCallbackForTesting(
235 const CreatedCallback
& callback
) {
236 for (size_t i
= 0; i
< g_created_callbacks
.Get().size(); ++i
) {
237 if (g_created_callbacks
.Get().at(i
).Equals(callback
)) {
238 g_created_callbacks
.Get().erase(g_created_callbacks
.Get().begin() + i
);
244 WebContents
* WebContents::FromRenderViewHost(const RenderViewHost
* rvh
) {
245 return rvh
->GetDelegate()->GetAsWebContents();
248 WebContents
* WebContents::FromRenderFrameHost(RenderFrameHost
* rfh
) {
249 RenderFrameHostImpl
* rfh_impl
= static_cast<RenderFrameHostImpl
*>(rfh
);
252 return rfh_impl
->delegate()->GetAsWebContents();
255 // WebContentsImpl::DestructionObserver ----------------------------------------
257 class WebContentsImpl::DestructionObserver
: public WebContentsObserver
{
259 DestructionObserver(WebContentsImpl
* owner
, WebContents
* watched_contents
)
260 : WebContentsObserver(watched_contents
),
264 // WebContentsObserver:
265 void WebContentsDestroyed() override
{
266 owner_
->OnWebContentsDestroyed(
267 static_cast<WebContentsImpl
*>(web_contents()));
271 WebContentsImpl
* owner_
;
273 DISALLOW_COPY_AND_ASSIGN(DestructionObserver
);
276 WebContentsImpl::ColorChooserInfo::ColorChooserInfo(int render_process_id
,
278 ColorChooser
* chooser
,
280 : render_process_id(render_process_id
),
281 render_frame_id(render_frame_id
),
283 identifier(identifier
) {
286 WebContentsImpl::ColorChooserInfo::~ColorChooserInfo() {
289 // WebContentsImpl -------------------------------------------------------------
291 WebContentsImpl::WebContentsImpl(BrowserContext
* browser_context
,
292 WebContentsImpl
* opener
)
294 controller_(this, browser_context
),
295 render_view_host_delegate_view_(NULL
),
297 created_with_opener_(!!opener
),
299 accessible_parent_(NULL
),
301 frame_tree_(new NavigatorImpl(&controller_
, this),
307 is_load_to_different_document_(false),
308 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING
),
309 crashed_error_code_(0),
310 waiting_for_response_(false),
311 load_state_(net::LOAD_STATE_IDLE
, base::string16()),
314 displayed_insecure_content_(false),
315 has_accessed_initial_document_(false),
316 theme_color_(SK_ColorTRANSPARENT
),
317 last_sent_theme_color_(SK_ColorTRANSPARENT
),
319 should_normally_be_visible_(true),
320 is_being_destroyed_(false),
321 notify_disconnection_(false),
322 dialog_manager_(NULL
),
323 is_showing_before_unload_dialog_(false),
324 last_active_time_(base::TimeTicks::Now()),
325 closed_by_user_gesture_(false),
326 minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor
* 100)),
327 maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor
* 100)),
328 render_view_message_source_(NULL
),
329 render_frame_message_source_(NULL
),
330 fullscreen_widget_routing_id_(MSG_ROUTING_NONE
),
331 fullscreen_widget_had_focus_at_shutdown_(false),
333 force_disable_overscroll_content_(false),
334 last_dialog_suppressed_(false),
335 geolocation_service_context_(new GeolocationServiceContext()),
337 BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()),
338 virtual_keyboard_requested_(false),
339 loading_weak_factory_(this) {
340 frame_tree_
.SetFrameRemoveListener(
341 base::Bind(&WebContentsImpl::OnFrameRemoved
,
342 base::Unretained(this)));
343 #if defined(ENABLE_BROWSER_CDMS)
344 media_web_contents_observer_
.reset(new MediaWebContentsObserver(this));
347 #if defined(OS_ANDROID)
348 audio_state_provider_
.reset(new MediaPlayersObserver(this));
350 audio_state_provider_
.reset(new AudioStreamMonitor(this));
354 WebContentsImpl::~WebContentsImpl() {
355 is_being_destroyed_
= true;
357 // Delete all RFH pending shutdown, which will lead the corresponding RVH to
358 // shutdown and be deleted as well.
360 base::Bind(&RenderFrameHostManager::ClearRFHsPendingShutdown
));
362 ClearAllPowerSaveBlockers();
364 for (std::set
<RenderWidgetHostImpl
*>::iterator iter
=
365 created_widgets_
.begin(); iter
!= created_widgets_
.end(); ++iter
) {
366 (*iter
)->DetachDelegate();
368 created_widgets_
.clear();
370 // Clear out any JavaScript state.
372 dialog_manager_
->ResetDialogState(this);
374 if (color_chooser_info_
.get())
375 color_chooser_info_
->chooser
->End();
377 NotifyDisconnected();
379 // Notify any observer that have a reference on this WebContents.
380 NotificationService::current()->Notify(
381 NOTIFICATION_WEB_CONTENTS_DESTROYED
,
382 Source
<WebContents
>(this),
383 NotificationService::NoDetails());
385 // Destroy all frame tree nodes except for the root; this notifies observers.
386 frame_tree_
.ResetForMainFrameSwap();
387 GetRenderManager()->ResetProxyHosts();
389 // Manually call the observer methods for the root frame tree node.
390 RenderFrameHostManager
* root
= GetRenderManager();
392 if (root
->pending_frame_host())
393 root
->pending_frame_host()->SetRenderFrameCreated(false);
394 root
->current_frame_host()->SetRenderFrameCreated(false);
396 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
397 FrameDeleted(root
->current_frame_host()));
399 if (root
->pending_render_view_host()) {
400 FOR_EACH_OBSERVER(WebContentsObserver
,
402 RenderViewDeleted(root
->pending_render_view_host()));
405 FOR_EACH_OBSERVER(WebContentsObserver
,
407 RenderViewDeleted(root
->current_host()));
409 FOR_EACH_OBSERVER(WebContentsObserver
,
411 WebContentsDestroyed());
413 FOR_EACH_OBSERVER(WebContentsObserver
,
419 STLDeleteContainerPairSecondPointers(destruction_observers_
.begin(),
420 destruction_observers_
.end());
423 WebContentsImpl
* WebContentsImpl::CreateWithOpener(
424 const WebContents::CreateParams
& params
,
425 WebContentsImpl
* opener
) {
426 TRACE_EVENT0("browser", "WebContentsImpl::CreateWithOpener");
427 WebContentsImpl
* new_contents
= new WebContentsImpl(
428 params
.browser_context
, params
.opener_suppressed
? NULL
: opener
);
430 if (params
.guest_delegate
) {
431 // This makes |new_contents| act as a guest.
432 // For more info, see comment above class BrowserPluginGuest.
433 BrowserPluginGuest::Create(new_contents
, params
.guest_delegate
);
434 // We are instantiating a WebContents for browser plugin. Set its subframe
436 new_contents
->is_subframe_
= true;
438 new_contents
->Init(params
);
443 std::vector
<WebContentsImpl
*> WebContentsImpl::GetAllWebContents() {
444 std::vector
<WebContentsImpl
*> result
;
445 scoped_ptr
<RenderWidgetHostIterator
> widgets(
446 RenderWidgetHostImpl::GetRenderWidgetHosts());
447 std::set
<WebContentsImpl
*> web_contents_set
;
448 while (RenderWidgetHost
* rwh
= widgets
->GetNextHost()) {
449 if (!rwh
->IsRenderView())
451 RenderViewHost
* rvh
= RenderViewHost::From(rwh
);
454 WebContents
* web_contents
= WebContents::FromRenderViewHost(rvh
);
457 WebContentsImpl
* wci
= static_cast<WebContentsImpl
*>(web_contents
);
458 if (web_contents_set
.find(wci
) == web_contents_set
.end()) {
459 web_contents_set
.insert(wci
);
460 result
.push_back(wci
);
466 RenderFrameHostManager
* WebContentsImpl::GetRenderManagerForTesting() {
467 return GetRenderManager();
470 bool WebContentsImpl::OnMessageReceived(RenderViewHost
* render_view_host
,
471 const IPC::Message
& message
) {
472 return OnMessageReceived(render_view_host
, NULL
, message
);
475 bool WebContentsImpl::OnMessageReceived(RenderViewHost
* render_view_host
,
476 RenderFrameHost
* render_frame_host
,
477 const IPC::Message
& message
) {
478 DCHECK(render_view_host
|| render_frame_host
);
480 static_cast<WebUIImpl
*>(GetWebUI())->OnMessageReceived(message
)) {
484 ObserverListBase
<WebContentsObserver
>::Iterator
it(&observers_
);
485 WebContentsObserver
* observer
;
486 if (render_frame_host
) {
487 while ((observer
= it
.GetNext()) != NULL
)
488 if (observer
->OnMessageReceived(message
, render_frame_host
))
491 while ((observer
= it
.GetNext()) != NULL
)
492 if (observer
->OnMessageReceived(message
))
496 // Message handlers should be aware of which
497 // RenderViewHost/RenderFrameHost sent the message, which is temporarily
498 // stored in render_(view|frame)_message_source_.
499 if (render_frame_host
)
500 render_frame_message_source_
= render_frame_host
;
502 render_view_message_source_
= render_view_host
;
505 IPC_BEGIN_MESSAGE_MAP(WebContentsImpl
, message
)
506 IPC_MESSAGE_HANDLER(FrameHostMsg_DomOperationResponse
,
507 OnDomOperationResponse
)
508 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeThemeColor
,
510 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishDocumentLoad
,
511 OnDocumentLoadedInFrame
)
512 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishLoad
, OnDidFinishLoad
)
513 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenColorChooser
, OnOpenColorChooser
)
514 IPC_MESSAGE_HANDLER(FrameHostMsg_EndColorChooser
, OnEndColorChooser
)
515 IPC_MESSAGE_HANDLER(FrameHostMsg_SetSelectedColorInColorChooser
,
516 OnSetSelectedColorInColorChooser
)
517 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPlayingNotification
,
518 OnMediaPlayingNotification
)
519 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPausedNotification
,
520 OnMediaPausedNotification
)
521 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFirstVisuallyNonEmptyPaint
,
522 OnFirstVisuallyNonEmptyPaint
)
523 IPC_MESSAGE_HANDLER(ViewHostMsg_DidLoadResourceFromMemoryCache
,
524 OnDidLoadResourceFromMemoryCache
)
525 IPC_MESSAGE_HANDLER(ViewHostMsg_DidDisplayInsecureContent
,
526 OnDidDisplayInsecureContent
)
527 IPC_MESSAGE_HANDLER(ViewHostMsg_DidRunInsecureContent
,
528 OnDidRunInsecureContent
)
529 IPC_MESSAGE_HANDLER(ViewHostMsg_GoToEntryAtOffset
, OnGoToEntryAtOffset
)
530 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateZoomLimits
, OnUpdateZoomLimits
)
531 IPC_MESSAGE_HANDLER(ViewHostMsg_EnumerateDirectory
, OnEnumerateDirectory
)
532 IPC_MESSAGE_HANDLER(ViewHostMsg_RegisterProtocolHandler
,
533 OnRegisterProtocolHandler
)
534 IPC_MESSAGE_HANDLER(ViewHostMsg_UnregisterProtocolHandler
,
535 OnUnregisterProtocolHandler
)
536 IPC_MESSAGE_HANDLER(ViewHostMsg_Find_Reply
, OnFindReply
)
537 IPC_MESSAGE_HANDLER(ViewHostMsg_AppCacheAccessed
, OnAppCacheAccessed
)
538 IPC_MESSAGE_HANDLER(ViewHostMsg_WebUISend
, OnWebUISend
)
539 #if defined(ENABLE_PLUGINS)
540 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung
, OnPepperPluginHung
)
541 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed
, OnPluginCrashed
)
542 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission
,
543 OnRequestPpapiBrokerPermission
)
544 IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_Attach
,
545 OnBrowserPluginMessage(render_frame_host
,
548 IPC_MESSAGE_HANDLER(ImageHostMsg_DidDownloadImage
, OnDidDownloadImage
)
549 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateFaviconURL
, OnUpdateFaviconURL
)
550 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowValidationMessage
,
551 OnShowValidationMessage
)
552 IPC_MESSAGE_HANDLER(ViewHostMsg_HideValidationMessage
,
553 OnHideValidationMessage
)
554 IPC_MESSAGE_HANDLER(ViewHostMsg_MoveValidationMessage
,
555 OnMoveValidationMessage
)
556 #if defined(OS_ANDROID)
557 IPC_MESSAGE_HANDLER(ViewHostMsg_FindMatchRects_Reply
,
558 OnFindMatchRectsReply
)
559 IPC_MESSAGE_HANDLER(ViewHostMsg_OpenDateTimeDialog
,
560 OnOpenDateTimeDialog
)
562 IPC_MESSAGE_UNHANDLED(handled
= false)
563 IPC_END_MESSAGE_MAP()
564 render_view_message_source_
= NULL
;
565 render_frame_message_source_
= NULL
;
570 bool WebContentsImpl::HasValidFrameSource() {
571 if (!render_frame_message_source_
) {
572 DCHECK(render_view_message_source_
);
573 bad_message::ReceivedBadMessage(GetRenderProcessHost(),
574 bad_message::WC_INVALID_FRAME_SOURCE
);
581 void WebContentsImpl::RunFileChooser(
582 RenderViewHost
* render_view_host
,
583 const FileChooserParams
& params
) {
585 delegate_
->RunFileChooser(this, params
);
588 NavigationControllerImpl
& WebContentsImpl::GetController() {
592 const NavigationControllerImpl
& WebContentsImpl::GetController() const {
596 BrowserContext
* WebContentsImpl::GetBrowserContext() const {
597 return controller_
.GetBrowserContext();
600 const GURL
& WebContentsImpl::GetURL() const {
601 // We may not have a navigation entry yet.
602 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
603 return entry
? entry
->GetVirtualURL() : GURL::EmptyGURL();
606 const GURL
& WebContentsImpl::GetVisibleURL() const {
607 // We may not have a navigation entry yet.
608 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
609 return entry
? entry
->GetVirtualURL() : GURL::EmptyGURL();
612 const GURL
& WebContentsImpl::GetLastCommittedURL() const {
613 // We may not have a navigation entry yet.
614 NavigationEntry
* entry
= controller_
.GetLastCommittedEntry();
615 return entry
? entry
->GetVirtualURL() : GURL::EmptyGURL();
618 WebContentsDelegate
* WebContentsImpl::GetDelegate() {
622 void WebContentsImpl::SetDelegate(WebContentsDelegate
* delegate
) {
623 // TODO(cbentzel): remove this debugging code?
624 if (delegate
== delegate_
)
627 delegate_
->Detach(this);
628 delegate_
= delegate
;
630 delegate_
->Attach(this);
631 // Ensure the visible RVH reflects the new delegate's preferences.
633 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
637 RenderProcessHost
* WebContentsImpl::GetRenderProcessHost() const {
638 RenderViewHostImpl
* host
= GetRenderManager()->current_host();
639 return host
? host
->GetProcess() : NULL
;
642 RenderFrameHostImpl
* WebContentsImpl::GetMainFrame() {
643 return frame_tree_
.root()->current_frame_host();
646 RenderFrameHost
* WebContentsImpl::GetFocusedFrame() {
647 if (!frame_tree_
.GetFocusedFrame())
649 return frame_tree_
.GetFocusedFrame()->current_frame_host();
652 void WebContentsImpl::ForEachFrame(
653 const base::Callback
<void(RenderFrameHost
*)>& on_frame
) {
654 frame_tree_
.ForEach(base::Bind(&ForEachFrameInternal
, on_frame
));
657 void WebContentsImpl::SendToAllFrames(IPC::Message
* message
) {
658 ForEachFrame(base::Bind(&SendToAllFramesInternal
, message
));
662 RenderViewHostImpl
* WebContentsImpl::GetRenderViewHost() const {
663 return GetRenderManager()->current_host();
666 int WebContentsImpl::GetRoutingID() const {
667 if (!GetRenderViewHost())
668 return MSG_ROUTING_NONE
;
670 return GetRenderViewHost()->GetRoutingID();
673 int WebContentsImpl::GetFullscreenWidgetRoutingID() const {
674 return fullscreen_widget_routing_id_
;
677 RenderWidgetHostView
* WebContentsImpl::GetRenderWidgetHostView() const {
678 return GetRenderManager()->GetRenderWidgetHostView();
681 RenderWidgetHostView
* WebContentsImpl::GetFullscreenRenderWidgetHostView()
683 RenderWidgetHost
* const widget_host
=
684 RenderWidgetHostImpl::FromID(GetRenderProcessHost()->GetID(),
685 GetFullscreenWidgetRoutingID());
686 return widget_host
? widget_host
->GetView() : NULL
;
689 WebContentsView
* WebContentsImpl::GetView() const {
693 SkColor
WebContentsImpl::GetThemeColor() const {
697 void WebContentsImpl::SetAccessibilityMode(AccessibilityMode mode
) {
698 if (mode
== accessibility_mode_
)
701 accessibility_mode_
= mode
;
703 base::Bind(&ForEachFrameInternal
,
704 base::Bind(&SetAccessibilityModeOnFrame
, mode
)));
706 base::Bind(&ForEachPendingFrameInternal
,
707 base::Bind(&SetAccessibilityModeOnFrame
, mode
)));
710 void WebContentsImpl::AddAccessibilityMode(AccessibilityMode mode
) {
711 SetAccessibilityMode(AddAccessibilityModeTo(accessibility_mode_
, mode
));
714 void WebContentsImpl::RemoveAccessibilityMode(AccessibilityMode mode
) {
715 SetAccessibilityMode(RemoveAccessibilityModeFrom(accessibility_mode_
, mode
));
718 void WebContentsImpl::RequestAXTreeSnapshot(AXTreeSnapshotCallback callback
) {
719 // TODO(dmazzoni): http://crbug.com/475608 This only returns the
720 // accessibility tree from the main frame and everything in the
721 // same site instance.
722 GetMainFrame()->RequestAXTreeSnapshot(callback
);
725 void WebContentsImpl::ClearNavigationTransitionData() {
726 FrameTreeNode
* node
= frame_tree_
.root();
727 node
->render_manager()->ClearNavigationTransitionData();
730 WebUI
* WebContentsImpl::CreateWebUI(const GURL
& url
) {
731 WebUIImpl
* web_ui
= new WebUIImpl(this);
732 WebUIController
* controller
= WebUIControllerFactoryRegistry::GetInstance()->
733 CreateWebUIControllerForURL(web_ui
, url
);
735 web_ui
->AddMessageHandler(new GenericHandler());
736 web_ui
->SetController(controller
);
744 WebUI
* WebContentsImpl::GetWebUI() const {
745 return GetRenderManager()->web_ui() ? GetRenderManager()->web_ui()
746 : GetRenderManager()->pending_web_ui();
749 WebUI
* WebContentsImpl::GetCommittedWebUI() const {
750 return GetRenderManager()->web_ui();
753 void WebContentsImpl::SetUserAgentOverride(const std::string
& override
) {
754 if (GetUserAgentOverride() == override
)
757 renderer_preferences_
.user_agent_override
= override
;
759 // Send the new override string to the renderer.
760 RenderViewHost
* host
= GetRenderViewHost();
762 host
->SyncRendererPrefs();
764 // Reload the page if a load is currently in progress to avoid having
765 // different parts of the page loaded using different user agents.
766 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
767 if (is_loading_
&& entry
!= NULL
&& entry
->GetIsOverridingUserAgent())
768 controller_
.ReloadIgnoringCache(true);
770 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
771 UserAgentOverrideSet(override
));
774 const std::string
& WebContentsImpl::GetUserAgentOverride() const {
775 return renderer_preferences_
.user_agent_override
;
778 void WebContentsImpl::EnableTreeOnlyAccessibilityMode() {
779 AddAccessibilityMode(AccessibilityModeTreeOnly
);
782 bool WebContentsImpl::IsTreeOnlyAccessibilityModeForTesting() const {
783 return accessibility_mode_
== AccessibilityModeTreeOnly
;
786 bool WebContentsImpl::IsFullAccessibilityModeForTesting() const {
787 return accessibility_mode_
== AccessibilityModeComplete
;
791 void WebContentsImpl::SetParentNativeViewAccessible(
792 gfx::NativeViewAccessible accessible_parent
) {
793 accessible_parent_
= accessible_parent
;
794 RenderFrameHostImpl
* rfh
= GetMainFrame();
796 rfh
->SetParentNativeViewAccessible(accessible_parent
);
800 const base::string16
& WebContentsImpl::GetTitle() const {
801 // Transient entries take precedence. They are used for interstitial pages
802 // that are shown on top of existing pages.
803 NavigationEntry
* entry
= controller_
.GetTransientEntry();
804 std::string accept_languages
=
805 GetContentClient()->browser()->GetAcceptLangs(
806 GetBrowserContext());
808 return entry
->GetTitleForDisplay(accept_languages
);
810 WebUI
* our_web_ui
= GetRenderManager()->pending_web_ui() ?
811 GetRenderManager()->pending_web_ui() : GetRenderManager()->web_ui();
813 // Don't override the title in view source mode.
814 entry
= controller_
.GetVisibleEntry();
815 if (!(entry
&& entry
->IsViewSourceMode())) {
816 // Give the Web UI the chance to override our title.
817 const base::string16
& title
= our_web_ui
->GetOverriddenTitle();
823 // We use the title for the last committed entry rather than a pending
824 // navigation entry. For example, when the user types in a URL, we want to
825 // keep the old page's title until the new load has committed and we get a new
827 entry
= controller_
.GetLastCommittedEntry();
829 // We make an exception for initial navigations.
830 if (controller_
.IsInitialNavigation()) {
831 // We only want to use the title from the visible entry in one of two cases:
832 // 1. There's already a committed entry for an initial navigation, in which
833 // case we are doing a history navigation in a new tab (e.g., Ctrl+Back).
834 // 2. The pending entry has been explicitly assigned a title to display.
836 // If there's no last committed entry and no assigned title, we should fall
837 // back to |page_title_when_no_navigation_entry_| rather than showing the
840 (controller_
.GetVisibleEntry() &&
841 !controller_
.GetVisibleEntry()->GetTitle().empty())) {
842 entry
= controller_
.GetVisibleEntry();
847 return entry
->GetTitleForDisplay(accept_languages
);
850 // |page_title_when_no_navigation_entry_| is finally used
851 // if no title cannot be retrieved.
852 return page_title_when_no_navigation_entry_
;
855 int32
WebContentsImpl::GetMaxPageID() {
856 return GetMaxPageIDForSiteInstance(GetSiteInstance());
859 int32
WebContentsImpl::GetMaxPageIDForSiteInstance(
860 SiteInstance
* site_instance
) {
861 if (max_page_ids_
.find(site_instance
->GetId()) == max_page_ids_
.end())
862 max_page_ids_
[site_instance
->GetId()] = -1;
864 return max_page_ids_
[site_instance
->GetId()];
867 void WebContentsImpl::UpdateMaxPageID(int32 page_id
) {
868 UpdateMaxPageIDForSiteInstance(GetSiteInstance(), page_id
);
871 void WebContentsImpl::UpdateMaxPageIDForSiteInstance(
872 SiteInstance
* site_instance
, int32 page_id
) {
873 if (GetMaxPageIDForSiteInstance(site_instance
) < page_id
)
874 max_page_ids_
[site_instance
->GetId()] = page_id
;
877 void WebContentsImpl::CopyMaxPageIDsFrom(WebContents
* web_contents
) {
878 WebContentsImpl
* contents
= static_cast<WebContentsImpl
*>(web_contents
);
879 max_page_ids_
= contents
->max_page_ids_
;
882 SiteInstanceImpl
* WebContentsImpl::GetSiteInstance() const {
883 return GetRenderManager()->current_host()->GetSiteInstance();
886 SiteInstanceImpl
* WebContentsImpl::GetPendingSiteInstance() const {
887 RenderViewHostImpl
* dest_rvh
=
888 GetRenderManager()->pending_render_view_host() ?
889 GetRenderManager()->pending_render_view_host() :
890 GetRenderManager()->current_host();
891 return dest_rvh
->GetSiteInstance();
894 bool WebContentsImpl::IsLoading() const {
898 bool WebContentsImpl::IsLoadingToDifferentDocument() const {
899 return is_loading_
&& is_load_to_different_document_
;
902 bool WebContentsImpl::IsWaitingForResponse() const {
903 return waiting_for_response_
&& is_load_to_different_document_
;
906 const net::LoadStateWithParam
& WebContentsImpl::GetLoadState() const {
910 const base::string16
& WebContentsImpl::GetLoadStateHost() const {
911 return load_state_host_
;
914 uint64
WebContentsImpl::GetUploadSize() const {
918 uint64
WebContentsImpl::GetUploadPosition() const {
919 return upload_position_
;
922 std::set
<GURL
> WebContentsImpl::GetSitesInTab() const {
923 std::set
<GURL
> sites
;
924 frame_tree_
.ForEach(base::Bind(&CollectSites
,
925 base::Unretained(GetBrowserContext()),
926 base::Unretained(&sites
)));
930 const std::string
& WebContentsImpl::GetEncoding() const {
931 return canonical_encoding_
;
934 bool WebContentsImpl::DisplayedInsecureContent() const {
935 return displayed_insecure_content_
;
938 void WebContentsImpl::IncrementCapturerCount(const gfx::Size
& capture_size
) {
939 DCHECK(!is_being_destroyed_
);
941 DVLOG(1) << "There are now " << capturer_count_
942 << " capturing(s) of WebContentsImpl@" << this;
944 // Note: This provides a hint to upstream code to size the views optimally
945 // for quality (e.g., to avoid scaling).
946 if (!capture_size
.IsEmpty() && preferred_size_for_capture_
.IsEmpty()) {
947 preferred_size_for_capture_
= capture_size
;
948 OnPreferredSizeChanged(preferred_size_
);
951 // Ensure that all views are un-occluded before capture begins.
955 void WebContentsImpl::DecrementCapturerCount() {
957 DVLOG(1) << "There are now " << capturer_count_
958 << " capturing(s) of WebContentsImpl@" << this;
959 DCHECK_LE(0, capturer_count_
);
961 if (is_being_destroyed_
)
964 if (capturer_count_
== 0) {
965 const gfx::Size old_size
= preferred_size_for_capture_
;
966 preferred_size_for_capture_
= gfx::Size();
967 OnPreferredSizeChanged(old_size
);
971 DVLOG(1) << "Executing delayed WasHidden().";
976 int WebContentsImpl::GetCapturerCount() const {
977 return capturer_count_
;
980 bool WebContentsImpl::IsAudioMuted() const {
981 return audio_muter_
.get() && audio_muter_
->is_muting();
984 void WebContentsImpl::SetAudioMuted(bool mute
) {
985 DVLOG(1) << "SetAudioMuted(mute=" << mute
<< "), was " << IsAudioMuted()
986 << " for WebContentsImpl@" << this;
988 if (mute
== IsAudioMuted())
993 audio_muter_
.reset(new WebContentsAudioMuter(this));
994 audio_muter_
->StartMuting();
996 DCHECK(audio_muter_
);
997 audio_muter_
->StopMuting();
1000 // Notification for UI updates in response to the changed muting state.
1001 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB
);
1004 bool WebContentsImpl::IsCrashed() const {
1005 return (crashed_status_
== base::TERMINATION_STATUS_PROCESS_CRASHED
||
1006 crashed_status_
== base::TERMINATION_STATUS_ABNORMAL_TERMINATION
||
1007 crashed_status_
== base::TERMINATION_STATUS_PROCESS_WAS_KILLED
);
1010 void WebContentsImpl::SetIsCrashed(base::TerminationStatus status
,
1012 if (status
== crashed_status_
)
1015 crashed_status_
= status
;
1016 crashed_error_code_
= error_code
;
1017 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB
);
1020 base::TerminationStatus
WebContentsImpl::GetCrashedStatus() const {
1021 return crashed_status_
;
1024 bool WebContentsImpl::IsBeingDestroyed() const {
1025 return is_being_destroyed_
;
1028 void WebContentsImpl::NotifyNavigationStateChanged(
1029 InvalidateTypes changed_flags
) {
1030 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1032 tracked_objects::ScopedTracker
tracking_profile(
1033 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1034 "466285 WebContentsImpl::NotifyNavigationStateChanged"));
1035 // Create and release the audio power save blocker depending on whether the
1036 // tab is actively producing audio or not.
1037 if ((changed_flags
& INVALIDATE_TYPE_TAB
) &&
1038 audio_state_provider_
->IsAudioStateAvailable()) {
1039 if (WasRecentlyAudible()) {
1040 if (!audio_power_save_blocker_
)
1041 CreateAudioPowerSaveBlocker();
1043 audio_power_save_blocker_
.reset();
1048 delegate_
->NavigationStateChanged(this, changed_flags
);
1051 base::TimeTicks
WebContentsImpl::GetLastActiveTime() const {
1052 return last_active_time_
;
1055 void WebContentsImpl::WasShown() {
1056 controller_
.SetActive(true);
1058 for (RenderWidgetHostView
* view
: GetRenderWidgetHostViewsInTree()) {
1061 #if defined(OS_MACOSX)
1062 view
->SetActive(true);
1067 last_active_time_
= base::TimeTicks::Now();
1069 // The resize rect might have changed while this was inactive -- send the new
1070 // one to make sure it's up to date.
1071 RenderViewHostImpl
* rvh
= GetRenderViewHost();
1073 rvh
->ResizeRectChanged(GetRootWindowResizerRect());
1075 // Restore power save blocker if there are active video players running.
1076 if (!active_video_players_
.empty() && !video_power_save_blocker_
)
1077 CreateVideoPowerSaveBlocker();
1079 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, WasShown());
1081 should_normally_be_visible_
= true;
1084 void WebContentsImpl::WasHidden() {
1085 // If there are entities capturing screenshots or video (e.g., mirroring),
1086 // don't activate the "disable rendering" optimization.
1087 if (capturer_count_
== 0) {
1088 // |GetRenderViewHost()| can be NULL if the user middle clicks a link to
1089 // open a tab in the background, then closes the tab before selecting it.
1090 // This is because closing the tab calls WebContentsImpl::Destroy(), which
1091 // removes the |GetRenderViewHost()|; then when we actually destroy the
1092 // window, OnWindowPosChanged() notices and calls WasHidden() (which
1094 for (RenderWidgetHostView
* view
: GetRenderWidgetHostViewsInTree()) {
1099 // Release any video power save blockers held as video is not visible.
1100 video_power_save_blocker_
.reset();
1103 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, WasHidden());
1105 should_normally_be_visible_
= false;
1108 void WebContentsImpl::WasOccluded() {
1109 if (capturer_count_
> 0)
1112 for (RenderWidgetHostView
* view
: GetRenderWidgetHostViewsInTree()) {
1114 view
->WasOccluded();
1118 void WebContentsImpl::WasUnOccluded() {
1119 for (RenderWidgetHostView
* view
: GetRenderWidgetHostViewsInTree()) {
1121 view
->WasUnOccluded();
1125 bool WebContentsImpl::NeedToFireBeforeUnload() {
1126 // TODO(creis): Should we fire even for interstitial pages?
1127 return WillNotifyDisconnection() && !ShowingInterstitialPage() &&
1128 !GetRenderViewHost()->SuddenTerminationAllowed();
1131 void WebContentsImpl::DispatchBeforeUnload(bool for_cross_site_transition
) {
1132 GetMainFrame()->DispatchBeforeUnload(for_cross_site_transition
);
1135 void WebContentsImpl::Stop() {
1136 GetRenderManager()->Stop();
1137 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, NavigationStopped());
1140 WebContents
* WebContentsImpl::Clone() {
1141 // We use our current SiteInstance since the cloned entry will use it anyway.
1142 // We pass our own opener so that the cloned page can access it if it was
1144 CreateParams
create_params(GetBrowserContext(), GetSiteInstance());
1145 create_params
.initial_size
= GetContainerBounds().size();
1146 WebContentsImpl
* tc
= CreateWithOpener(create_params
, opener_
);
1147 tc
->GetController().CopyStateFrom(controller_
);
1148 FOR_EACH_OBSERVER(WebContentsObserver
,
1150 DidCloneToNewWebContents(this, tc
));
1154 void WebContentsImpl::Observe(int type
,
1155 const NotificationSource
& source
,
1156 const NotificationDetails
& details
) {
1158 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED
: {
1159 RenderWidgetHost
* host
= Source
<RenderWidgetHost
>(source
).ptr();
1160 RenderWidgetHostView
* view
= host
->GetView();
1161 if (view
== GetFullscreenRenderWidgetHostView()) {
1162 // We cannot just call view_->RestoreFocus() here. On some platforms,
1163 // attempting to focus the currently-invisible WebContentsView will be
1164 // flat-out ignored. Therefore, this boolean is used to track whether
1165 // we will request focus after the fullscreen widget has been
1167 fullscreen_widget_had_focus_at_shutdown_
= (view
&& view
->HasFocus());
1169 for (PendingWidgetViews::iterator i
= pending_widget_views_
.begin();
1170 i
!= pending_widget_views_
.end(); ++i
) {
1171 if (host
->GetView() == i
->second
) {
1172 pending_widget_views_
.erase(i
);
1184 WebContents
* WebContentsImpl::GetWebContents() {
1188 void WebContentsImpl::Init(const WebContents::CreateParams
& params
) {
1189 // This is set before initializing the render manager since
1190 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
1191 // it should be hidden.
1192 should_normally_be_visible_
= !params
.initially_hidden
;
1194 // Either both routing ids can be given, or neither can be.
1195 DCHECK((params
.routing_id
== MSG_ROUTING_NONE
&&
1196 params
.main_frame_routing_id
== MSG_ROUTING_NONE
) ||
1197 (params
.routing_id
!= MSG_ROUTING_NONE
&&
1198 params
.main_frame_routing_id
!= MSG_ROUTING_NONE
));
1199 GetRenderManager()->Init(
1200 params
.browser_context
, params
.site_instance
, params
.routing_id
,
1201 params
.main_frame_routing_id
);
1203 WebContentsViewDelegate
* delegate
=
1204 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
1206 if (browser_plugin_guest_
) {
1207 scoped_ptr
<WebContentsView
> platform_view(CreateWebContentsView(
1208 this, delegate
, &render_view_host_delegate_view_
));
1210 WebContentsViewGuest
* rv
= new WebContentsViewGuest(
1211 this, browser_plugin_guest_
.get(), platform_view
.Pass(),
1212 render_view_host_delegate_view_
);
1213 render_view_host_delegate_view_
= rv
;
1216 // Regular WebContentsView.
1217 view_
.reset(CreateWebContentsView(
1218 this, delegate
, &render_view_host_delegate_view_
));
1220 CHECK(render_view_host_delegate_view_
);
1223 gfx::Size initial_size
= params
.initial_size
;
1224 view_
->CreateView(initial_size
, params
.context
);
1226 // Listen for whether our opener gets destroyed.
1228 AddDestructionObserver(opener_
);
1230 #if defined(ENABLE_PLUGINS)
1231 plugin_content_origin_whitelist_
.reset(
1232 new PluginContentOriginWhitelist(this));
1235 registrar_
.Add(this,
1236 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED
,
1237 NotificationService::AllBrowserContextsAndSources());
1239 screen_orientation_dispatcher_host_
.reset(
1240 new ScreenOrientationDispatcherHostImpl(this));
1242 manifest_manager_host_
.reset(new ManifestManagerHost(this));
1244 #if defined(OS_ANDROID)
1245 date_time_chooser_
.reset(new DateTimeChooserAndroid());
1248 // BrowserPluginGuest::Init needs to be called after this WebContents has
1249 // a RenderWidgetHostViewGuest. That is, |view_->CreateView| above.
1250 if (browser_plugin_guest_
)
1251 browser_plugin_guest_
->Init();
1253 for (size_t i
= 0; i
< g_created_callbacks
.Get().size(); i
++)
1254 g_created_callbacks
.Get().at(i
).Run(this);
1256 // If the WebContents creation was renderer-initiated, it means that the
1257 // corresponding RenderView and main RenderFrame have already been created.
1258 // Ensure observers are notified about this.
1259 if (params
.renderer_initiated_creation
) {
1260 RenderViewCreated(GetRenderViewHost());
1261 GetRenderManager()->current_frame_host()->SetRenderFrameCreated(true);
1264 // Ensure that observers are notified of the creation of this WebContents's
1265 // main RenderFrameHost. It must be done here for main frames, since the
1266 // NotifySwappedFromRenderManager expects view_ to already be created and that
1267 // happens after RenderFrameHostManager::Init.
1268 NotifySwappedFromRenderManager(
1269 nullptr, GetRenderManager()->current_frame_host(), true);
1272 void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl
* web_contents
) {
1273 RemoveDestructionObserver(web_contents
);
1275 // Clear the opener if it has been closed.
1276 if (web_contents
== opener_
) {
1280 // Clear a pending contents that has been closed before being shown.
1281 for (PendingContents::iterator iter
= pending_contents_
.begin();
1282 iter
!= pending_contents_
.end();
1284 if (iter
->second
!= web_contents
)
1286 pending_contents_
.erase(iter
);
1292 void WebContentsImpl::AddDestructionObserver(WebContentsImpl
* web_contents
) {
1293 if (!ContainsKey(destruction_observers_
, web_contents
)) {
1294 destruction_observers_
[web_contents
] =
1295 new DestructionObserver(this, web_contents
);
1299 void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl
* web_contents
) {
1300 DestructionObservers::iterator iter
=
1301 destruction_observers_
.find(web_contents
);
1302 if (iter
!= destruction_observers_
.end()) {
1303 delete destruction_observers_
[web_contents
];
1304 destruction_observers_
.erase(iter
);
1308 void WebContentsImpl::AddObserver(WebContentsObserver
* observer
) {
1309 observers_
.AddObserver(observer
);
1312 void WebContentsImpl::RemoveObserver(WebContentsObserver
* observer
) {
1313 observers_
.RemoveObserver(observer
);
1316 std::set
<RenderWidgetHostView
*>
1317 WebContentsImpl::GetRenderWidgetHostViewsInTree() {
1318 std::set
<RenderWidgetHostView
*> set
;
1319 if (ShowingInterstitialPage()) {
1320 set
.insert(GetRenderWidgetHostView());
1323 base::Bind(&AddRenderWidgetHostViewToSet
, base::Unretained(&set
)));
1328 void WebContentsImpl::Activate() {
1330 delegate_
->ActivateContents(this);
1333 void WebContentsImpl::Deactivate() {
1335 delegate_
->DeactivateContents(this);
1338 void WebContentsImpl::LostCapture() {
1340 delegate_
->LostCapture();
1343 void WebContentsImpl::RenderWidgetDeleted(
1344 RenderWidgetHostImpl
* render_widget_host
) {
1345 if (is_being_destroyed_
) {
1346 // |created_widgets_| might have been destroyed.
1350 std::set
<RenderWidgetHostImpl
*>::iterator iter
=
1351 created_widgets_
.find(render_widget_host
);
1352 if (iter
!= created_widgets_
.end())
1353 created_widgets_
.erase(iter
);
1355 if (render_widget_host
&&
1356 render_widget_host
->GetRoutingID() == fullscreen_widget_routing_id_
) {
1357 if (delegate_
&& delegate_
->EmbedsFullscreenWidget())
1358 delegate_
->ExitFullscreenModeForTab(this);
1359 FOR_EACH_OBSERVER(WebContentsObserver
,
1361 DidDestroyFullscreenWidget(
1362 fullscreen_widget_routing_id_
));
1363 fullscreen_widget_routing_id_
= MSG_ROUTING_NONE
;
1364 if (fullscreen_widget_had_focus_at_shutdown_
)
1365 view_
->RestoreFocus();
1369 void WebContentsImpl::RenderWidgetGotFocus(
1370 RenderWidgetHostImpl
* render_widget_host
) {
1371 // Notify the observers if an embedded fullscreen widget was focused.
1372 if (delegate_
&& render_widget_host
&& delegate_
->EmbedsFullscreenWidget() &&
1373 render_widget_host
->GetView() == GetFullscreenRenderWidgetHostView()) {
1374 NotifyWebContentsFocused();
1378 void WebContentsImpl::RenderWidgetWasResized(
1379 RenderWidgetHostImpl
* render_widget_host
,
1380 bool width_changed
) {
1381 RenderFrameHostImpl
* rfh
= GetMainFrame();
1382 if (!rfh
|| render_widget_host
!= rfh
->GetRenderWidgetHost())
1385 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1386 MainFrameWasResized(width_changed
));
1389 void WebContentsImpl::ScreenInfoChanged() {
1390 if (browser_plugin_embedder_
)
1391 browser_plugin_embedder_
->ScreenInfoChanged();
1394 bool WebContentsImpl::PreHandleKeyboardEvent(
1395 const NativeWebKeyboardEvent
& event
,
1396 bool* is_keyboard_shortcut
) {
1398 delegate_
->PreHandleKeyboardEvent(this, event
, is_keyboard_shortcut
);
1401 void WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent
& event
) {
1402 if (browser_plugin_embedder_
&&
1403 browser_plugin_embedder_
->HandleKeyboardEvent(event
)) {
1407 delegate_
->HandleKeyboardEvent(this, event
);
1410 bool WebContentsImpl::HandleWheelEvent(
1411 const blink::WebMouseWheelEvent
& event
) {
1412 #if !defined(OS_MACOSX)
1413 // On platforms other than Mac, control+mousewheel may change zoom. On Mac,
1414 // this isn't done for two reasons:
1415 // -the OS already has a gesture to do this through pinch-zoom
1416 // -if a user starts an inertial scroll, let's go, and presses control
1417 // (i.e. control+tab) then the OS's buffered scroll events will come in
1418 // with control key set which isn't what the user wants
1419 if (delegate_
&& event
.wheelTicksY
&&
1420 (event
.modifiers
& blink::WebInputEvent::ControlKey
) &&
1422 delegate_
->ContentsZoomChange(event
.wheelTicksY
> 0);
1429 bool WebContentsImpl::PreHandleGestureEvent(
1430 const blink::WebGestureEvent
& event
) {
1431 return delegate_
&& delegate_
->PreHandleGestureEvent(this, event
);
1434 void WebContentsImpl::EnterFullscreenMode(const GURL
& origin
) {
1435 // This method is being called to enter renderer-initiated fullscreen mode.
1436 // Make sure any existing fullscreen widget is shut down first.
1437 RenderWidgetHostView
* const widget_view
= GetFullscreenRenderWidgetHostView();
1439 RenderWidgetHostImpl::From(widget_view
->GetRenderWidgetHost())->Shutdown();
1442 delegate_
->EnterFullscreenModeForTab(this, origin
);
1444 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1445 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1448 void WebContentsImpl::ExitFullscreenMode() {
1449 // This method is being called to leave renderer-initiated fullscreen mode.
1450 // Make sure any existing fullscreen widget is shut down first.
1451 RenderWidgetHostView
* const widget_view
= GetFullscreenRenderWidgetHostView();
1453 RenderWidgetHostImpl::From(widget_view
->GetRenderWidgetHost())->Shutdown();
1455 #if defined(OS_ANDROID)
1456 ContentVideoView
* video_view
= ContentVideoView::GetInstance();
1457 if (video_view
!= NULL
)
1458 video_view
->OnExitFullscreen();
1462 delegate_
->ExitFullscreenModeForTab(this);
1464 // Ensure web contents exit fullscreen state by sending a resize message,
1465 // which includes the fullscreen state. This is required for the situation
1466 // of the browser moving the view into a fullscreen state "browser fullscreen"
1467 // and then the contents entering "tab fullscreen". Exiting the contents
1468 // "tab fullscreen" then won't have the side effect of the view resizing,
1469 // hence the explicit call here is required.
1470 if (RenderWidgetHostView
* rwh_view
= GetRenderWidgetHostView()) {
1471 if (RenderWidgetHost
* render_widget_host
= rwh_view
->GetRenderWidgetHost())
1472 render_widget_host
->WasResized();
1475 FOR_EACH_OBSERVER(WebContentsObserver
,
1477 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1480 bool WebContentsImpl::IsFullscreenForCurrentTab() const {
1481 return delegate_
? delegate_
->IsFullscreenForTabOrPending(this) : false;
1484 blink::WebDisplayMode
WebContentsImpl::GetDisplayMode() const {
1485 return delegate_
? delegate_
->GetDisplayMode(this)
1486 : blink::WebDisplayModeBrowser
;
1489 void WebContentsImpl::RequestToLockMouse(bool user_gesture
,
1490 bool last_unlocked_by_target
) {
1492 delegate_
->RequestToLockMouse(this, user_gesture
, last_unlocked_by_target
);
1494 GotResponseToLockMouseRequest(false);
1498 void WebContentsImpl::LostMouseLock() {
1500 delegate_
->LostMouseLock();
1503 void WebContentsImpl::CreateNewWindow(
1504 int render_process_id
,
1506 int main_frame_route_id
,
1507 const ViewHostMsg_CreateWindow_Params
& params
,
1508 SessionStorageNamespace
* session_storage_namespace
) {
1509 // We usually create the new window in the same BrowsingInstance (group of
1510 // script-related windows), by passing in the current SiteInstance. However,
1511 // if the opener is being suppressed (in a non-guest), we create a new
1512 // SiteInstance in its own BrowsingInstance.
1513 bool is_guest
= BrowserPluginGuest::IsGuest(this);
1515 // If the opener is to be suppressed, the new window can be in any process.
1516 // Since routing ids are process specific, we must not have one passed in
1517 // as argument here.
1518 DCHECK(!params
.opener_suppressed
|| route_id
== MSG_ROUTING_NONE
);
1520 scoped_refptr
<SiteInstance
> site_instance
=
1521 params
.opener_suppressed
&& !is_guest
?
1522 SiteInstance::CreateForURL(GetBrowserContext(), params
.target_url
) :
1525 // A message to create a new window can only come from the active process for
1526 // this WebContentsImpl instance. If any other process sends the request,
1527 // it is invalid and the process must be terminated.
1528 if (GetRenderProcessHost()->GetID() != render_process_id
) {
1529 RenderProcessHost
* rph
= RenderProcessHost::FromID(render_process_id
);
1530 base::ProcessHandle process_handle
= rph
->GetHandle();
1531 if (process_handle
!= base::kNullProcessHandle
) {
1533 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWindow"));
1534 rph
->Shutdown(RESULT_CODE_KILLED
, false);
1539 // We must assign the SessionStorageNamespace before calling Init().
1541 // http://crbug.com/142685
1542 const std::string
& partition_id
=
1543 GetContentClient()->browser()->
1544 GetStoragePartitionIdForSite(GetBrowserContext(),
1545 site_instance
->GetSiteURL());
1546 StoragePartition
* partition
= BrowserContext::GetStoragePartition(
1547 GetBrowserContext(), site_instance
.get());
1548 DOMStorageContextWrapper
* dom_storage_context
=
1549 static_cast<DOMStorageContextWrapper
*>(partition
->GetDOMStorageContext());
1550 SessionStorageNamespaceImpl
* session_storage_namespace_impl
=
1551 static_cast<SessionStorageNamespaceImpl
*>(session_storage_namespace
);
1552 CHECK(session_storage_namespace_impl
->IsFromContext(dom_storage_context
));
1555 !delegate_
->ShouldCreateWebContents(this,
1557 main_frame_route_id
,
1558 params
.window_container_type
,
1562 session_storage_namespace
)) {
1563 if (route_id
!= MSG_ROUTING_NONE
&&
1564 !RenderViewHost::FromID(render_process_id
, route_id
)) {
1565 // If the embedder didn't create a WebContents for this route, we need to
1566 // delete the RenderView that had already been created.
1567 Send(new ViewMsg_Close(route_id
));
1569 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(route_id
);
1570 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(
1571 main_frame_route_id
);
1575 // Create the new web contents. This will automatically create the new
1576 // WebContentsView. In the future, we may want to create the view separately.
1577 CreateParams
create_params(GetBrowserContext(), site_instance
.get());
1578 create_params
.routing_id
= route_id
;
1579 create_params
.main_frame_routing_id
= main_frame_route_id
;
1580 create_params
.opener
= this;
1581 create_params
.opener_suppressed
= params
.opener_suppressed
;
1582 if (params
.disposition
== NEW_BACKGROUND_TAB
)
1583 create_params
.initially_hidden
= true;
1584 create_params
.renderer_initiated_creation
= true;
1586 WebContentsImpl
* new_contents
= NULL
;
1588 create_params
.context
= view_
->GetNativeView();
1589 create_params
.initial_size
= GetContainerBounds().size();
1590 new_contents
= static_cast<WebContentsImpl
*>(
1591 WebContents::Create(create_params
));
1593 new_contents
= GetBrowserPluginGuest()->CreateNewGuestWindow(create_params
);
1595 new_contents
->GetController().SetSessionStorageNamespace(
1597 session_storage_namespace
);
1599 // Save the window for later if we're not suppressing the opener (since it
1600 // will be shown immediately).
1601 if (!params
.opener_suppressed
) {
1603 WebContentsView
* new_view
= new_contents
->view_
.get();
1605 // TODO(brettw): It seems bogus that we have to call this function on the
1606 // newly created object and give it one of its own member variables.
1607 new_view
->CreateViewForWidget(new_contents
->GetRenderViewHost(), false);
1609 // Save the created window associated with the route so we can show it
1611 DCHECK_NE(MSG_ROUTING_NONE
, route_id
);
1612 pending_contents_
[route_id
] = new_contents
;
1613 AddDestructionObserver(new_contents
);
1617 delegate_
->WebContentsCreated(
1618 this, params
.opener_render_frame_id
, params
.frame_name
,
1619 params
.target_url
, new_contents
);
1622 if (params
.opener_suppressed
) {
1623 // When the opener is suppressed, the original renderer cannot access the
1624 // new window. As a result, we need to show and navigate the window here.
1625 bool was_blocked
= false;
1627 gfx::Rect initial_rect
;
1628 delegate_
->AddNewContents(
1629 this, new_contents
, params
.disposition
, initial_rect
,
1630 params
.user_gesture
, &was_blocked
);
1633 OpenURLParams
open_params(params
.target_url
,
1636 ui::PAGE_TRANSITION_LINK
,
1637 true /* is_renderer_initiated */);
1638 open_params
.user_gesture
= params
.user_gesture
;
1639 new_contents
->OpenURL(open_params
);
1644 void WebContentsImpl::CreateNewWidget(int render_process_id
,
1646 blink::WebPopupType popup_type
) {
1647 CreateNewWidget(render_process_id
, route_id
, false, popup_type
);
1650 void WebContentsImpl::CreateNewFullscreenWidget(int render_process_id
,
1652 CreateNewWidget(render_process_id
, route_id
, true, blink::WebPopupTypeNone
);
1655 void WebContentsImpl::CreateNewWidget(int render_process_id
,
1658 blink::WebPopupType popup_type
) {
1659 RenderProcessHost
* process
= GetRenderProcessHost();
1660 // A message to create a new widget can only come from the active process for
1661 // this WebContentsImpl instance. If any other process sends the request,
1662 // it is invalid and the process must be terminated.
1663 if (process
->GetID() != render_process_id
) {
1664 RenderProcessHost
* rph
= RenderProcessHost::FromID(render_process_id
);
1665 base::ProcessHandle process_handle
= rph
->GetHandle();
1666 if (process_handle
!= base::kNullProcessHandle
) {
1668 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWidget"));
1669 rph
->Shutdown(RESULT_CODE_KILLED
, false);
1674 RenderWidgetHostImpl
* widget_host
=
1675 new RenderWidgetHostImpl(this, process
, route_id
, IsHidden());
1676 created_widgets_
.insert(widget_host
);
1678 RenderWidgetHostViewBase
* widget_view
=
1679 static_cast<RenderWidgetHostViewBase
*>(
1680 view_
->CreateViewForPopupWidget(widget_host
));
1683 if (!is_fullscreen
) {
1684 // Popups should not get activated.
1685 widget_view
->SetPopupType(popup_type
);
1687 // Save the created widget associated with the route so we can show it later.
1688 pending_widget_views_
[route_id
] = widget_view
;
1690 #if defined(OS_MACOSX)
1691 // A RenderWidgetHostViewMac has lifetime scoped to the view. We'll retain it
1692 // to allow it to survive the trip without being hosted.
1693 base::mac::NSObjectRetain(widget_view
->GetNativeView());
1697 void WebContentsImpl::ShowCreatedWindow(int route_id
,
1698 WindowOpenDisposition disposition
,
1699 const gfx::Rect
& initial_rect
,
1700 bool user_gesture
) {
1701 WebContentsImpl
* contents
= GetCreatedWindow(route_id
);
1703 WebContentsDelegate
* delegate
= GetDelegate();
1705 delegate
->AddNewContents(
1706 this, contents
, disposition
, initial_rect
, user_gesture
, NULL
);
1711 void WebContentsImpl::ShowCreatedWidget(int route_id
,
1712 const gfx::Rect
& initial_rect
) {
1713 ShowCreatedWidget(route_id
, false, initial_rect
);
1716 void WebContentsImpl::ShowCreatedFullscreenWidget(int route_id
) {
1717 ShowCreatedWidget(route_id
, true, gfx::Rect());
1720 void WebContentsImpl::ShowCreatedWidget(int route_id
,
1722 const gfx::Rect
& initial_rect
) {
1723 RenderWidgetHostViewBase
* widget_host_view
=
1724 static_cast<RenderWidgetHostViewBase
*>(GetCreatedWidget(route_id
));
1725 if (!widget_host_view
)
1728 RenderWidgetHostView
* view
= NULL
;
1729 BrowserPluginGuest
* guest
= GetBrowserPluginGuest();
1730 if (guest
&& guest
->embedder_web_contents()) {
1731 view
= guest
->embedder_web_contents()->GetRenderWidgetHostView();
1733 view
= GetRenderWidgetHostView();
1736 if (is_fullscreen
) {
1737 DCHECK_EQ(MSG_ROUTING_NONE
, fullscreen_widget_routing_id_
);
1738 view_
->StoreFocus();
1739 fullscreen_widget_routing_id_
= route_id
;
1740 if (delegate_
&& delegate_
->EmbedsFullscreenWidget()) {
1741 widget_host_view
->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
1742 delegate_
->EnterFullscreenModeForTab(this, GURL());
1744 widget_host_view
->InitAsFullscreen(view
);
1746 FOR_EACH_OBSERVER(WebContentsObserver
,
1748 DidShowFullscreenWidget(route_id
));
1749 if (!widget_host_view
->HasFocus())
1750 widget_host_view
->Focus();
1752 widget_host_view
->InitAsPopup(view
, initial_rect
);
1755 RenderWidgetHostImpl
* render_widget_host_impl
=
1756 RenderWidgetHostImpl::From(widget_host_view
->GetRenderWidgetHost());
1757 render_widget_host_impl
->Init();
1758 // Only allow privileged mouse lock for fullscreen render widget, which is
1759 // used to implement Pepper Flash fullscreen.
1760 render_widget_host_impl
->set_allow_privileged_mouse_lock(is_fullscreen
);
1762 #if defined(OS_MACOSX)
1763 // A RenderWidgetHostViewMac has lifetime scoped to the view. Now that it's
1764 // properly embedded (or purposefully ignored) we can release the retain we
1765 // took in CreateNewWidget().
1766 base::mac::NSObjectRelease(widget_host_view
->GetNativeView());
1770 WebContentsImpl
* WebContentsImpl::GetCreatedWindow(int route_id
) {
1771 PendingContents::iterator iter
= pending_contents_
.find(route_id
);
1773 // Certain systems can block the creation of new windows. If we didn't succeed
1774 // in creating one, just return NULL.
1775 if (iter
== pending_contents_
.end()) {
1779 WebContentsImpl
* new_contents
= iter
->second
;
1780 pending_contents_
.erase(route_id
);
1781 RemoveDestructionObserver(new_contents
);
1783 // Don't initialize the guest WebContents immediately.
1784 if (BrowserPluginGuest::IsGuest(new_contents
))
1785 return new_contents
;
1787 if (!new_contents
->GetRenderProcessHost()->HasConnection() ||
1788 !new_contents
->GetRenderViewHost()->GetView())
1791 // Resume blocked requests for both the RenderViewHost and RenderFrameHost.
1792 // TODO(brettw): It seems bogus to reach into here and initialize the host.
1793 new_contents
->GetRenderViewHost()->Init();
1794 new_contents
->GetMainFrame()->Init();
1796 return new_contents
;
1799 RenderWidgetHostView
* WebContentsImpl::GetCreatedWidget(int route_id
) {
1800 PendingWidgetViews::iterator iter
= pending_widget_views_
.find(route_id
);
1801 if (iter
== pending_widget_views_
.end()) {
1806 RenderWidgetHostView
* widget_host_view
= iter
->second
;
1807 pending_widget_views_
.erase(route_id
);
1809 RenderWidgetHost
* widget_host
= widget_host_view
->GetRenderWidgetHost();
1810 if (!widget_host
->GetProcess()->HasConnection()) {
1811 // The view has gone away or the renderer crashed. Nothing to do.
1815 return widget_host_view
;
1818 void WebContentsImpl::RequestMediaAccessPermission(
1819 const MediaStreamRequest
& request
,
1820 const MediaResponseCallback
& callback
) {
1822 delegate_
->RequestMediaAccessPermission(this, request
, callback
);
1824 callback
.Run(MediaStreamDevices(),
1825 MEDIA_DEVICE_FAILED_DUE_TO_SHUTDOWN
,
1826 scoped_ptr
<MediaStreamUI
>());
1830 bool WebContentsImpl::CheckMediaAccessPermission(const GURL
& security_origin
,
1831 MediaStreamType type
) {
1832 DCHECK(type
== MEDIA_DEVICE_AUDIO_CAPTURE
||
1833 type
== MEDIA_DEVICE_VIDEO_CAPTURE
);
1835 delegate_
->CheckMediaAccessPermission(this, security_origin
, type
);
1838 SessionStorageNamespace
* WebContentsImpl::GetSessionStorageNamespace(
1839 SiteInstance
* instance
) {
1840 return controller_
.GetSessionStorageNamespace(instance
);
1843 SessionStorageNamespaceMap
WebContentsImpl::GetSessionStorageNamespaceMap() {
1844 return controller_
.GetSessionStorageNamespaceMap();
1847 FrameTree
* WebContentsImpl::GetFrameTree() {
1848 return &frame_tree_
;
1851 void WebContentsImpl::SetIsVirtualKeyboardRequested(bool requested
) {
1852 virtual_keyboard_requested_
= requested
;
1855 bool WebContentsImpl::IsVirtualKeyboardRequested() {
1856 return virtual_keyboard_requested_
;
1859 AccessibilityMode
WebContentsImpl::GetAccessibilityMode() const {
1860 return accessibility_mode_
;
1863 void WebContentsImpl::AccessibilityEventReceived(
1864 const std::vector
<AXEventNotificationDetails
>& details
) {
1866 WebContentsObserver
, observers_
, AccessibilityEventReceived(details
));
1869 RenderFrameHost
* WebContentsImpl::GetGuestByInstanceID(
1870 RenderFrameHost
* render_frame_host
,
1871 int browser_plugin_instance_id
) {
1872 BrowserPluginGuestManager
* guest_manager
=
1873 GetBrowserContext()->GetGuestManager();
1877 WebContents
* guest
= guest_manager
->GetGuestByInstanceID(
1878 render_frame_host
->GetProcess()->GetID(), browser_plugin_instance_id
);
1882 return guest
->GetMainFrame();
1885 GeolocationServiceContext
* WebContentsImpl::GetGeolocationServiceContext() {
1886 return geolocation_service_context_
.get();
1889 void WebContentsImpl::OnShowValidationMessage(
1890 const gfx::Rect
& anchor_in_root_view
,
1891 const base::string16
& main_text
,
1892 const base::string16
& sub_text
) {
1894 delegate_
->ShowValidationMessage(
1895 this, anchor_in_root_view
, main_text
, sub_text
);
1898 void WebContentsImpl::OnHideValidationMessage() {
1900 delegate_
->HideValidationMessage(this);
1903 void WebContentsImpl::OnMoveValidationMessage(
1904 const gfx::Rect
& anchor_in_root_view
) {
1906 delegate_
->MoveValidationMessage(this, anchor_in_root_view
);
1909 void WebContentsImpl::DidSendScreenRects(RenderWidgetHostImpl
* rwh
) {
1910 if (browser_plugin_embedder_
)
1911 browser_plugin_embedder_
->DidSendScreenRects();
1914 BrowserAccessibilityManager
*
1915 WebContentsImpl::GetRootBrowserAccessibilityManager() {
1916 RenderFrameHostImpl
* rfh
= GetMainFrame();
1917 return rfh
? rfh
->browser_accessibility_manager() : nullptr;
1920 BrowserAccessibilityManager
*
1921 WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
1922 RenderFrameHostImpl
* rfh
= GetMainFrame();
1923 return rfh
? rfh
->GetOrCreateBrowserAccessibilityManager() : nullptr;
1926 void WebContentsImpl::UpdatePreferredSize(const gfx::Size
& pref_size
) {
1927 const gfx::Size old_size
= GetPreferredSize();
1928 preferred_size_
= pref_size
;
1929 OnPreferredSizeChanged(old_size
);
1932 void WebContentsImpl::ResizeDueToAutoResize(const gfx::Size
& new_size
) {
1934 delegate_
->ResizeDueToAutoResize(this, new_size
);
1937 WebContents
* WebContentsImpl::OpenURL(const OpenURLParams
& params
) {
1941 WebContents
* new_contents
= delegate_
->OpenURLFromTab(this, params
);
1942 return new_contents
;
1945 bool WebContentsImpl::Send(IPC::Message
* message
) {
1946 if (!GetRenderViewHost()) {
1951 return GetRenderViewHost()->Send(message
);
1954 bool WebContentsImpl::NavigateToPendingEntry(
1955 NavigationController::ReloadType reload_type
) {
1956 FrameTreeNode
* node
= frame_tree_
.root();
1958 // Navigate in the FrameTreeNode specified in the pending entry, if any. This
1959 // is currently only used in --site-per-process and tests.
1960 // TODO(creis): Remove this method and NavigationEntryImpl::frame_tree_node_id
1961 // by using FrameNavigationEntries instead. See https://crbug.com/236848.
1962 NavigationEntryImpl
* pending_entry
= controller_
.GetPendingEntry();
1963 if (pending_entry
->frame_tree_node_id() != -1) {
1964 FrameTreeNode
* subframe
=
1965 frame_tree_
.FindByID(pending_entry
->frame_tree_node_id());
1971 return node
->navigator()->NavigateToPendingEntry(node
, reload_type
);
1974 void WebContentsImpl::RenderFrameForInterstitialPageCreated(
1975 RenderFrameHost
* render_frame_host
) {
1976 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1977 RenderFrameForInterstitialPageCreated(render_frame_host
));
1980 void WebContentsImpl::AttachInterstitialPage(
1981 InterstitialPageImpl
* interstitial_page
) {
1982 DCHECK(interstitial_page
);
1983 GetRenderManager()->set_interstitial_page(interstitial_page
);
1985 // Cancel any visible dialogs so that they don't interfere with the
1987 if (dialog_manager_
)
1988 dialog_manager_
->CancelActiveAndPendingDialogs(this);
1990 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1991 DidAttachInterstitialPage());
1994 void WebContentsImpl::DetachInterstitialPage() {
1995 if (ShowingInterstitialPage())
1996 GetRenderManager()->remove_interstitial_page();
1997 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1998 DidDetachInterstitialPage());
2001 void WebContentsImpl::SetHistoryOffsetAndLength(int history_offset
,
2002 int history_length
) {
2003 SetHistoryOffsetAndLengthForView(
2004 GetRenderViewHost(), history_offset
, history_length
);
2007 void WebContentsImpl::SetHistoryOffsetAndLengthForView(
2008 RenderViewHost
* render_view_host
,
2010 int history_length
) {
2011 render_view_host
->Send(new ViewMsg_SetHistoryOffsetAndLength(
2012 render_view_host
->GetRoutingID(), history_offset
, history_length
));
2015 void WebContentsImpl::ReloadFocusedFrame(bool ignore_cache
) {
2016 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2020 focused_frame
->Send(new FrameMsg_Reload(
2021 focused_frame
->GetRoutingID(), ignore_cache
));
2024 void WebContentsImpl::Undo() {
2025 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2029 focused_frame
->Send(new InputMsg_Undo(focused_frame
->GetRoutingID()));
2030 RecordAction(base::UserMetricsAction("Undo"));
2033 void WebContentsImpl::Redo() {
2034 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2037 focused_frame
->Send(new InputMsg_Redo(focused_frame
->GetRoutingID()));
2038 RecordAction(base::UserMetricsAction("Redo"));
2041 void WebContentsImpl::Cut() {
2042 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2046 focused_frame
->Send(new InputMsg_Cut(focused_frame
->GetRoutingID()));
2047 RecordAction(base::UserMetricsAction("Cut"));
2050 void WebContentsImpl::Copy() {
2051 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2055 focused_frame
->Send(new InputMsg_Copy(focused_frame
->GetRoutingID()));
2056 RecordAction(base::UserMetricsAction("Copy"));
2059 void WebContentsImpl::CopyToFindPboard() {
2060 #if defined(OS_MACOSX)
2061 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2065 // Windows/Linux don't have the concept of a find pasteboard.
2066 focused_frame
->Send(
2067 new InputMsg_CopyToFindPboard(focused_frame
->GetRoutingID()));
2068 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
2072 void WebContentsImpl::Paste() {
2073 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2077 focused_frame
->Send(new InputMsg_Paste(focused_frame
->GetRoutingID()));
2078 RecordAction(base::UserMetricsAction("Paste"));
2081 void WebContentsImpl::PasteAndMatchStyle() {
2082 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2086 focused_frame
->Send(new InputMsg_PasteAndMatchStyle(
2087 focused_frame
->GetRoutingID()));
2088 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
2091 void WebContentsImpl::Delete() {
2092 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2096 focused_frame
->Send(new InputMsg_Delete(focused_frame
->GetRoutingID()));
2097 RecordAction(base::UserMetricsAction("DeleteSelection"));
2100 void WebContentsImpl::SelectAll() {
2101 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2105 focused_frame
->Send(new InputMsg_SelectAll(focused_frame
->GetRoutingID()));
2106 RecordAction(base::UserMetricsAction("SelectAll"));
2109 void WebContentsImpl::Unselect() {
2110 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2114 focused_frame
->Send(new InputMsg_Unselect(focused_frame
->GetRoutingID()));
2115 RecordAction(base::UserMetricsAction("Unselect"));
2118 void WebContentsImpl::Replace(const base::string16
& word
) {
2119 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2123 focused_frame
->Send(new InputMsg_Replace(
2124 focused_frame
->GetRoutingID(), word
));
2127 void WebContentsImpl::ReplaceMisspelling(const base::string16
& word
) {
2128 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2132 focused_frame
->Send(new InputMsg_ReplaceMisspelling(
2133 focused_frame
->GetRoutingID(), word
));
2136 void WebContentsImpl::NotifyContextMenuClosed(
2137 const CustomContextMenuContext
& context
) {
2138 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2142 focused_frame
->Send(new FrameMsg_ContextMenuClosed(
2143 focused_frame
->GetRoutingID(), context
));
2146 void WebContentsImpl::ExecuteCustomContextMenuCommand(
2147 int action
, const CustomContextMenuContext
& context
) {
2148 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2152 focused_frame
->Send(new FrameMsg_CustomContextMenuAction(
2153 focused_frame
->GetRoutingID(), context
, action
));
2156 gfx::NativeView
WebContentsImpl::GetNativeView() {
2157 return view_
->GetNativeView();
2160 gfx::NativeView
WebContentsImpl::GetContentNativeView() {
2161 return view_
->GetContentNativeView();
2164 gfx::NativeWindow
WebContentsImpl::GetTopLevelNativeWindow() {
2165 return view_
->GetTopLevelNativeWindow();
2168 gfx::Rect
WebContentsImpl::GetViewBounds() {
2169 return view_
->GetViewBounds();
2172 gfx::Rect
WebContentsImpl::GetContainerBounds() {
2174 view_
->GetContainerBounds(&rv
);
2178 DropData
* WebContentsImpl::GetDropData() {
2179 return view_
->GetDropData();
2182 void WebContentsImpl::Focus() {
2186 void WebContentsImpl::SetInitialFocus() {
2187 view_
->SetInitialFocus();
2190 void WebContentsImpl::StoreFocus() {
2191 view_
->StoreFocus();
2194 void WebContentsImpl::RestoreFocus() {
2195 view_
->RestoreFocus();
2198 void WebContentsImpl::FocusThroughTabTraversal(bool reverse
) {
2199 if (ShowingInterstitialPage()) {
2200 GetRenderManager()->interstitial_page()->FocusThroughTabTraversal(reverse
);
2203 RenderWidgetHostView
* const fullscreen_view
=
2204 GetFullscreenRenderWidgetHostView();
2205 if (fullscreen_view
) {
2206 fullscreen_view
->Focus();
2209 GetRenderViewHost()->SetInitialFocus(reverse
);
2212 bool WebContentsImpl::ShowingInterstitialPage() const {
2213 return GetRenderManager()->interstitial_page() != NULL
;
2216 InterstitialPage
* WebContentsImpl::GetInterstitialPage() const {
2217 return GetRenderManager()->interstitial_page();
2220 bool WebContentsImpl::IsSavable() {
2221 // WebKit creates Document object when MIME type is application/xhtml+xml,
2222 // so we also support this MIME type.
2223 return contents_mime_type_
== "text/html" ||
2224 contents_mime_type_
== "text/xml" ||
2225 contents_mime_type_
== "application/xhtml+xml" ||
2226 contents_mime_type_
== "text/plain" ||
2227 contents_mime_type_
== "text/css" ||
2228 net::IsSupportedJavascriptMimeType(contents_mime_type_
.c_str());
2231 void WebContentsImpl::OnSavePage() {
2232 // If we can not save the page, try to download it.
2234 RecordDownloadSource(INITIATED_BY_SAVE_PACKAGE_ON_NON_HTML
);
2235 SaveFrame(GetLastCommittedURL(), Referrer());
2241 // Create the save package and possibly prompt the user for the name to save
2242 // the page as. The user prompt is an asynchronous operation that runs on
2244 save_package_
= new SavePackage(this);
2245 save_package_
->GetSaveInfo();
2248 // Used in automated testing to bypass prompting the user for file names.
2249 // Instead, the names and paths are hard coded rather than running them through
2250 // file name sanitation and extension / mime checking.
2251 bool WebContentsImpl::SavePage(const base::FilePath
& main_file
,
2252 const base::FilePath
& dir_path
,
2253 SavePageType save_type
) {
2254 // Stop the page from navigating.
2257 save_package_
= new SavePackage(this, save_type
, main_file
, dir_path
);
2258 return save_package_
->Init(SavePackageDownloadCreatedCallback());
2261 void WebContentsImpl::SaveFrame(const GURL
& url
,
2262 const Referrer
& referrer
) {
2263 SaveFrameWithHeaders(url
, referrer
, std::string());
2266 void WebContentsImpl::SaveFrameWithHeaders(const GURL
& url
,
2267 const Referrer
& referrer
,
2268 const std::string
& headers
) {
2269 if (!GetLastCommittedURL().is_valid())
2271 if (delegate_
&& delegate_
->SaveFrame(url
, referrer
))
2274 // TODO(nasko): This check for main frame is incorrect and should be fixed
2275 // by explicitly passing in which frame this method should target.
2276 bool is_main_frame
= (url
== GetLastCommittedURL());
2278 DownloadManager
* dlm
=
2279 BrowserContext::GetDownloadManager(GetBrowserContext());
2283 if (is_main_frame
) {
2284 const NavigationEntry
* entry
= controller_
.GetLastCommittedEntry();
2286 post_id
= entry
->GetPostID();
2288 scoped_ptr
<DownloadUrlParameters
> params(
2289 DownloadUrlParameters::FromWebContents(this, url
));
2290 params
->set_referrer(referrer
);
2291 params
->set_post_id(post_id
);
2293 params
->set_method("POST");
2294 params
->set_prompt(true);
2296 if (headers
.empty()) {
2297 params
->set_prefer_cache(true);
2299 std::vector
<std::string
> key_value_list
;
2300 base::SplitString(headers
, '\n', &key_value_list
);
2301 for (const auto& key_value
: key_value_list
) {
2302 std::vector
<std::string
> pair
;
2303 base::SplitString(key_value
, ':', &pair
);
2304 DCHECK_EQ(2ul, pair
.size());
2305 params
->add_request_header(pair
[0], pair
[1]);
2308 dlm
->DownloadUrl(params
.Pass());
2311 void WebContentsImpl::GenerateMHTML(
2312 const base::FilePath
& file
,
2313 const base::Callback
<void(int64
)>& callback
) {
2314 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, file
, callback
);
2317 const std::string
& WebContentsImpl::GetContentsMimeType() const {
2318 return contents_mime_type_
;
2321 bool WebContentsImpl::WillNotifyDisconnection() const {
2322 return notify_disconnection_
;
2325 void WebContentsImpl::SetOverrideEncoding(const std::string
& encoding
) {
2326 SetEncoding(encoding
);
2327 Send(new ViewMsg_SetPageEncoding(GetRoutingID(), encoding
));
2330 void WebContentsImpl::ResetOverrideEncoding() {
2331 canonical_encoding_
.clear();
2332 Send(new ViewMsg_ResetPageEncodingToDefault(GetRoutingID()));
2335 RendererPreferences
* WebContentsImpl::GetMutableRendererPrefs() {
2336 return &renderer_preferences_
;
2339 void WebContentsImpl::Close() {
2340 Close(GetRenderViewHost());
2343 void WebContentsImpl::DragSourceEndedAt(int client_x
, int client_y
,
2344 int screen_x
, int screen_y
, blink::WebDragOperation operation
) {
2345 if (browser_plugin_embedder_
.get())
2346 browser_plugin_embedder_
->DragSourceEndedAt(client_x
, client_y
,
2347 screen_x
, screen_y
, operation
);
2348 if (GetRenderViewHost())
2349 GetRenderViewHost()->DragSourceEndedAt(client_x
, client_y
, screen_x
,
2350 screen_y
, operation
);
2353 void WebContentsImpl::DidGetResourceResponseStart(
2354 const ResourceRequestDetails
& details
) {
2355 controller_
.ssl_manager()->DidStartResourceResponse(details
);
2357 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2358 DidGetResourceResponseStart(details
));
2360 // TODO(avi): Remove. http://crbug.com/170921
2361 NotificationService::current()->Notify(
2362 NOTIFICATION_RESOURCE_RESPONSE_STARTED
,
2363 Source
<WebContents
>(this),
2364 Details
<const ResourceRequestDetails
>(&details
));
2367 void WebContentsImpl::DidGetRedirectForResourceRequest(
2368 RenderFrameHost
* render_frame_host
,
2369 const ResourceRedirectDetails
& details
) {
2370 controller_
.ssl_manager()->DidReceiveResourceRedirect(details
);
2373 WebContentsObserver
,
2375 DidGetRedirectForResourceRequest(render_frame_host
, details
));
2377 // TODO(avi): Remove. http://crbug.com/170921
2378 NotificationService::current()->Notify(
2379 NOTIFICATION_RESOURCE_RECEIVED_REDIRECT
,
2380 Source
<WebContents
>(this),
2381 Details
<const ResourceRedirectDetails
>(&details
));
2384 void WebContentsImpl::NotifyWebContentsFocused() {
2385 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, OnWebContentsFocused());
2388 void WebContentsImpl::SystemDragEnded() {
2389 if (GetRenderViewHost())
2390 GetRenderViewHost()->DragSourceSystemDragEnded();
2391 if (browser_plugin_embedder_
.get())
2392 browser_plugin_embedder_
->SystemDragEnded();
2395 void WebContentsImpl::UserGestureDone() {
2399 void WebContentsImpl::SetClosedByUserGesture(bool value
) {
2400 closed_by_user_gesture_
= value
;
2403 bool WebContentsImpl::GetClosedByUserGesture() const {
2404 return closed_by_user_gesture_
;
2407 void WebContentsImpl::ViewSource() {
2411 NavigationEntry
* entry
= GetController().GetLastCommittedEntry();
2415 delegate_
->ViewSourceForTab(this, entry
->GetURL());
2418 void WebContentsImpl::ViewFrameSource(const GURL
& url
,
2419 const PageState
& page_state
) {
2423 delegate_
->ViewSourceForFrame(this, url
, page_state
);
2426 int WebContentsImpl::GetMinimumZoomPercent() const {
2427 return minimum_zoom_percent_
;
2430 int WebContentsImpl::GetMaximumZoomPercent() const {
2431 return maximum_zoom_percent_
;
2434 void WebContentsImpl::ResetPageScale() {
2435 Send(new ViewMsg_ResetPageScale(GetRoutingID()));
2438 gfx::Size
WebContentsImpl::GetPreferredSize() const {
2439 return capturer_count_
== 0 ? preferred_size_
: preferred_size_for_capture_
;
2442 bool WebContentsImpl::GotResponseToLockMouseRequest(bool allowed
) {
2443 if (GetBrowserPluginGuest())
2444 return GetBrowserPluginGuest()->LockMouse(allowed
);
2446 return GetRenderViewHost()
2447 ? GetRenderViewHost()->GotResponseToLockMouseRequest(allowed
)
2451 bool WebContentsImpl::HasOpener() const {
2452 return opener_
!= NULL
;
2455 WebContents
* WebContentsImpl::GetOpener() const {
2456 return static_cast<WebContents
*>(opener_
);
2459 void WebContentsImpl::DidChooseColorInColorChooser(SkColor color
) {
2460 if (!color_chooser_info_
.get())
2462 RenderFrameHost
* rfh
= RenderFrameHost::FromID(
2463 color_chooser_info_
->render_process_id
,
2464 color_chooser_info_
->render_frame_id
);
2468 rfh
->Send(new FrameMsg_DidChooseColorResponse(
2469 rfh
->GetRoutingID(), color_chooser_info_
->identifier
, color
));
2472 void WebContentsImpl::DidEndColorChooser() {
2473 if (!color_chooser_info_
.get())
2475 RenderFrameHost
* rfh
= RenderFrameHost::FromID(
2476 color_chooser_info_
->render_process_id
,
2477 color_chooser_info_
->render_frame_id
);
2481 rfh
->Send(new FrameMsg_DidEndColorChooser(
2482 rfh
->GetRoutingID(), color_chooser_info_
->identifier
));
2483 color_chooser_info_
.reset();
2486 int WebContentsImpl::DownloadImage(const GURL
& url
,
2488 uint32_t max_bitmap_size
,
2490 const ImageDownloadCallback
& callback
) {
2491 int id
= StartDownload(GetMainFrame(), url
, is_favicon
, max_bitmap_size
,
2493 image_download_map_
[id
] = callback
;
2497 bool WebContentsImpl::IsSubframe() const {
2498 return is_subframe_
;
2501 void WebContentsImpl::Find(int request_id
,
2502 const base::string16
& search_text
,
2503 const blink::WebFindOptions
& options
) {
2504 // See if a top level browser plugin handles the find request first.
2505 if (browser_plugin_embedder_
) {
2506 BrowserPluginGuest
* guest
= browser_plugin_embedder_
->GetFullPageGuest();
2507 if (guest
&& guest
->Find(request_id
, search_text
, options
))
2510 Send(new ViewMsg_Find(GetRoutingID(), request_id
, search_text
, options
));
2513 void WebContentsImpl::StopFinding(StopFindAction action
) {
2514 // See if a top level browser plugin handles the stop finding request first.
2515 if (browser_plugin_embedder_
) {
2516 BrowserPluginGuest
* guest
= browser_plugin_embedder_
->GetFullPageGuest();
2517 if (guest
&& guest
->StopFinding(action
))
2520 Send(new ViewMsg_StopFinding(GetRoutingID(), action
));
2523 void WebContentsImpl::InsertCSS(const std::string
& css
) {
2524 GetMainFrame()->Send(new FrameMsg_CSSInsertRequest(
2525 GetMainFrame()->GetRoutingID(), css
));
2528 bool WebContentsImpl::WasRecentlyAudible() {
2529 return audio_state_provider_
->WasRecentlyAudible();
2532 void WebContentsImpl::GetManifest(const GetManifestCallback
& callback
) {
2533 manifest_manager_host_
->GetManifest(GetMainFrame(), callback
);
2536 void WebContentsImpl::ExitFullscreen() {
2537 // Clean up related state and initiate the fullscreen exit.
2538 GetRenderViewHost()->RejectMouseLockOrUnlockIfNecessary();
2539 ExitFullscreenMode();
2542 bool WebContentsImpl::FocusLocationBarByDefault() {
2543 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
2544 if (entry
&& entry
->GetURL() == GURL(url::kAboutBlankURL
))
2546 return delegate_
&& delegate_
->ShouldFocusLocationBarByDefault(this);
2549 void WebContentsImpl::SetFocusToLocationBar(bool select_all
) {
2551 delegate_
->SetFocusToLocationBar(select_all
);
2554 void WebContentsImpl::DidStartProvisionalLoad(
2555 RenderFrameHostImpl
* render_frame_host
,
2556 const GURL
& validated_url
,
2558 bool is_iframe_srcdoc
) {
2559 // Notify observers about the start of the provisional load.
2561 WebContentsObserver
,
2563 DidStartProvisionalLoadForFrame(
2564 render_frame_host
, validated_url
, is_error_page
, is_iframe_srcdoc
));
2566 // Notify accessibility if this is a reload.
2567 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
2568 if (entry
&& ui::PageTransitionCoreTypeIs(
2569 entry
->GetTransitionType(), ui::PAGE_TRANSITION_RELOAD
)) {
2570 FrameTreeNode
* ftn
= render_frame_host
->frame_tree_node();
2571 BrowserAccessibilityManager
* manager
=
2572 ftn
->current_frame_host()->browser_accessibility_manager();
2574 manager
->UserIsReloading();
2578 void WebContentsImpl::DidStartNavigationTransition(
2579 RenderFrameHostImpl
* render_frame_host
) {
2580 #if defined(OS_ANDROID)
2581 int render_frame_id
= render_frame_host
->GetRoutingID();
2582 GetWebContentsAndroid()->DidStartNavigationTransitionForFrame(
2587 void WebContentsImpl::DidFailProvisionalLoadWithError(
2588 RenderFrameHostImpl
* render_frame_host
,
2589 const FrameHostMsg_DidFailProvisionalLoadWithError_Params
& params
) {
2590 GURL
validated_url(params
.url
);
2591 FOR_EACH_OBSERVER(WebContentsObserver
,
2593 DidFailProvisionalLoad(render_frame_host
,
2596 params
.error_description
));
2598 FrameTreeNode
* ftn
= render_frame_host
->frame_tree_node();
2599 BrowserAccessibilityManager
* manager
=
2600 ftn
->current_frame_host()->browser_accessibility_manager();
2602 manager
->NavigationFailed();
2605 void WebContentsImpl::DidFailLoadWithError(
2606 RenderFrameHostImpl
* render_frame_host
,
2609 const base::string16
& error_description
) {
2611 WebContentsObserver
,
2613 DidFailLoad(render_frame_host
, url
, error_code
, error_description
));
2616 void WebContentsImpl::NotifyChangedNavigationState(
2617 InvalidateTypes changed_flags
) {
2618 NotifyNavigationStateChanged(changed_flags
);
2621 void WebContentsImpl::AboutToNavigateRenderFrame(
2622 RenderFrameHostImpl
* old_host
,
2623 RenderFrameHostImpl
* new_host
) {
2624 // Notify observers that we will navigate in this RenderFrame.
2626 WebContentsObserver
,
2628 AboutToNavigateRenderFrame(old_host
, new_host
));
2631 void WebContentsImpl::DidStartNavigationToPendingEntry(
2633 NavigationController::ReloadType reload_type
) {
2634 // Notify observers about navigation.
2636 WebContentsObserver
,
2638 DidStartNavigationToPendingEntry(url
, reload_type
));
2641 void WebContentsImpl::RequestOpenURL(RenderFrameHostImpl
* render_frame_host
,
2642 const OpenURLParams
& params
) {
2643 // OpenURL can blow away the source RFH. Use the process/frame routing ID as a
2644 // weak pointer of sorts.
2645 const int32_t process_id
= render_frame_host
->GetProcess()->GetID();
2646 const int32_t frame_id
= render_frame_host
->GetRoutingID();
2648 WebContents
* new_contents
= OpenURL(params
);
2650 if (new_contents
&& RenderFrameHost::FromID(process_id
, frame_id
)) {
2651 // Notify observers.
2652 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2653 DidOpenRequestedURL(new_contents
,
2658 params
.transition
));
2662 bool WebContentsImpl::ShouldPreserveAbortedURLs() {
2665 return delegate_
->ShouldPreserveAbortedURLs(this);
2668 void WebContentsImpl::DidCommitProvisionalLoad(
2669 RenderFrameHostImpl
* render_frame_host
,
2671 ui::PageTransition transition_type
) {
2672 // Notify observers about the commit of the provisional load.
2673 FOR_EACH_OBSERVER(WebContentsObserver
,
2675 DidCommitProvisionalLoadForFrame(
2676 render_frame_host
, url
, transition_type
));
2678 BrowserAccessibilityManager
* manager
=
2679 render_frame_host
->browser_accessibility_manager();
2681 manager
->NavigationSucceeded();
2684 void WebContentsImpl::DidNavigateMainFramePreCommit(
2685 bool navigation_is_within_page
) {
2686 // Ensure fullscreen mode is exited before committing the navigation to a
2687 // different page. The next page will not start out assuming it is in
2689 if (navigation_is_within_page
) {
2690 // No page change? Then, the renderer and browser can remain in fullscreen.
2693 if (IsFullscreenForCurrentTab())
2695 DCHECK(!IsFullscreenForCurrentTab());
2698 void WebContentsImpl::DidNavigateMainFramePostCommit(
2699 RenderFrameHostImpl
* render_frame_host
,
2700 const LoadCommittedDetails
& details
,
2701 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) {
2702 if (details
.is_navigation_to_different_page()) {
2703 // Clear the status bubble. This is a workaround for a bug where WebKit
2704 // doesn't let us know that the cursor left an element during a
2705 // transition (this is also why the mouse cursor remains as a hand after
2706 // clicking on a link); see bugs 1184641 and 980803. We don't want to
2707 // clear the bubble when a user navigates to a named anchor in the same
2709 UpdateTargetURL(render_frame_host
->GetRenderViewHost(), GURL());
2711 RenderWidgetHostViewBase
* rwhvb
=
2712 static_cast<RenderWidgetHostViewBase
*>(GetRenderWidgetHostView());
2714 rwhvb
->OnDidNavigateMainFrameToNewPage();
2716 // Reset theme color on navigation to new page.
2717 theme_color_
= SK_ColorTRANSPARENT
;
2720 if (!details
.is_in_page
) {
2721 // Once the main frame is navigated, we're no longer considered to have
2722 // displayed insecure content.
2723 displayed_insecure_content_
= false;
2724 SSLManager::NotifySSLInternalStateChanged(
2725 GetController().GetBrowserContext());
2728 // Notify observers about navigation.
2729 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2730 DidNavigateMainFrame(details
, params
));
2733 delegate_
->DidNavigateMainFramePostCommit(this);
2734 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
2737 void WebContentsImpl::DidNavigateAnyFramePostCommit(
2738 RenderFrameHostImpl
* render_frame_host
,
2739 const LoadCommittedDetails
& details
,
2740 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) {
2741 // Now that something has committed, we don't need to track whether the
2742 // initial page has been accessed.
2743 has_accessed_initial_document_
= false;
2745 // If we navigate off the page, close all JavaScript dialogs.
2746 if (dialog_manager_
&& !details
.is_in_page
)
2747 dialog_manager_
->CancelActiveAndPendingDialogs(this);
2749 // Notify observers about navigation.
2750 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2751 DidNavigateAnyFrame(render_frame_host
, details
, params
));
2754 void WebContentsImpl::SetMainFrameMimeType(const std::string
& mime_type
) {
2755 contents_mime_type_
= mime_type
;
2758 bool WebContentsImpl::CanOverscrollContent() const {
2759 // Disable overscroll when touch emulation is on. See crbug.com/369938.
2760 if (force_disable_overscroll_content_
)
2764 return delegate_
->CanOverscrollContent();
2769 void WebContentsImpl::OnThemeColorChanged(SkColor theme_color
) {
2770 // Update the theme color. This is to be published to observers on visually
2772 theme_color_
= theme_color
;
2775 void WebContentsImpl::OnDidLoadResourceFromMemoryCache(
2777 const std::string
& security_info
,
2778 const std::string
& http_method
,
2779 const std::string
& mime_type
,
2780 ResourceType resource_type
) {
2782 // Send out a notification that we loaded a resource from our memory cache.
2784 net::CertStatus cert_status
= 0;
2785 int security_bits
= -1;
2786 int connection_status
= 0;
2787 SignedCertificateTimestampIDStatusList signed_certificate_timestamp_ids
;
2788 DeserializeSecurityInfo(security_info
, &cert_id
, &cert_status
,
2789 &security_bits
, &connection_status
,
2790 &signed_certificate_timestamp_ids
);
2791 // TODO(alcutter,eranm): Pass signed_certificate_timestamp_ids into details
2792 LoadFromMemoryCacheDetails
details(
2793 url
, GetRenderProcessHost()->GetID(), cert_id
, cert_status
, http_method
,
2794 mime_type
, resource_type
);
2796 controller_
.ssl_manager()->DidLoadFromMemoryCache(details
);
2798 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2799 DidLoadResourceFromMemoryCache(details
));
2801 if (url
.is_valid() && url
.SchemeIsHTTPOrHTTPS()) {
2802 scoped_refptr
<net::URLRequestContextGetter
> request_context(
2803 resource_type
== RESOURCE_TYPE_MEDIA
?
2804 GetBrowserContext()->GetMediaRequestContextForRenderProcess(
2805 GetRenderProcessHost()->GetID()) :
2806 GetBrowserContext()->GetRequestContextForRenderProcess(
2807 GetRenderProcessHost()->GetID()));
2808 BrowserThread::PostTask(
2811 base::Bind(&NotifyCacheOnIO
, request_context
, url
, http_method
));
2815 void WebContentsImpl::OnDidDisplayInsecureContent() {
2816 RecordAction(base::UserMetricsAction("SSL.DisplayedInsecureContent"));
2817 displayed_insecure_content_
= true;
2818 SSLManager::NotifySSLInternalStateChanged(
2819 GetController().GetBrowserContext());
2822 void WebContentsImpl::OnDidRunInsecureContent(
2823 const std::string
& security_origin
, const GURL
& target_url
) {
2824 LOG(WARNING
) << security_origin
<< " ran insecure content from "
2825 << target_url
.possibly_invalid_spec();
2826 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
2827 if (EndsWith(security_origin
, kDotGoogleDotCom
, false))
2828 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
2829 controller_
.ssl_manager()->DidRunInsecureContent(security_origin
);
2830 displayed_insecure_content_
= true;
2831 SSLManager::NotifySSLInternalStateChanged(
2832 GetController().GetBrowserContext());
2835 void WebContentsImpl::OnDocumentLoadedInFrame() {
2836 if (!HasValidFrameSource())
2839 RenderFrameHostImpl
* rfh
=
2840 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2842 WebContentsObserver
, observers_
, DocumentLoadedInFrame(rfh
));
2845 void WebContentsImpl::OnDidFinishLoad(const GURL
& url
) {
2846 if (!HasValidFrameSource())
2849 GURL
validated_url(url
);
2850 RenderProcessHost
* render_process_host
=
2851 render_frame_message_source_
->GetProcess();
2852 render_process_host
->FilterURL(false, &validated_url
);
2854 RenderFrameHostImpl
* rfh
=
2855 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2857 WebContentsObserver
, observers_
, DidFinishLoad(rfh
, validated_url
));
2860 void WebContentsImpl::OnGoToEntryAtOffset(int offset
) {
2861 if (!delegate_
|| delegate_
->OnGoToEntryOffset(offset
))
2862 controller_
.GoToOffset(offset
);
2865 void WebContentsImpl::OnUpdateZoomLimits(int minimum_percent
,
2866 int maximum_percent
) {
2867 minimum_zoom_percent_
= minimum_percent
;
2868 maximum_zoom_percent_
= maximum_percent
;
2871 void WebContentsImpl::OnEnumerateDirectory(int request_id
,
2872 const base::FilePath
& path
) {
2876 ChildProcessSecurityPolicyImpl
* policy
=
2877 ChildProcessSecurityPolicyImpl::GetInstance();
2878 if (policy
->CanReadFile(GetRenderProcessHost()->GetID(), path
))
2879 delegate_
->EnumerateDirectory(this, request_id
, path
);
2882 void WebContentsImpl::OnRegisterProtocolHandler(const std::string
& protocol
,
2884 const base::string16
& title
,
2885 bool user_gesture
) {
2889 ChildProcessSecurityPolicyImpl
* policy
=
2890 ChildProcessSecurityPolicyImpl::GetInstance();
2891 if (policy
->IsPseudoScheme(protocol
))
2894 delegate_
->RegisterProtocolHandler(this, protocol
, url
, user_gesture
);
2897 void WebContentsImpl::OnUnregisterProtocolHandler(const std::string
& protocol
,
2899 bool user_gesture
) {
2903 ChildProcessSecurityPolicyImpl
* policy
=
2904 ChildProcessSecurityPolicyImpl::GetInstance();
2905 if (policy
->IsPseudoScheme(protocol
))
2908 delegate_
->UnregisterProtocolHandler(this, protocol
, url
, user_gesture
);
2911 void WebContentsImpl::OnFindReply(int request_id
,
2912 int number_of_matches
,
2913 const gfx::Rect
& selection_rect
,
2914 int active_match_ordinal
,
2915 bool final_update
) {
2917 delegate_
->FindReply(this, request_id
, number_of_matches
, selection_rect
,
2918 active_match_ordinal
, final_update
);
2922 #if defined(OS_ANDROID)
2923 void WebContentsImpl::OnFindMatchRectsReply(
2925 const std::vector
<gfx::RectF
>& rects
,
2926 const gfx::RectF
& active_rect
) {
2928 delegate_
->FindMatchRectsReply(this, version
, rects
, active_rect
);
2931 void WebContentsImpl::OnOpenDateTimeDialog(
2932 const ViewHostMsg_DateTimeDialogValue_Params
& value
) {
2933 date_time_chooser_
->ShowDialog(GetTopLevelNativeWindow(),
2934 GetRenderViewHost(),
2944 void WebContentsImpl::OnDomOperationResponse(const std::string
& json_string
,
2945 int automation_id
) {
2946 DomOperationNotificationDetails
details(json_string
, automation_id
);
2947 NotificationService::current()->Notify(
2948 NOTIFICATION_DOM_OPERATION_RESPONSE
,
2949 Source
<WebContents
>(this),
2950 Details
<DomOperationNotificationDetails
>(&details
));
2953 void WebContentsImpl::OnAppCacheAccessed(const GURL
& manifest_url
,
2954 bool blocked_by_policy
) {
2955 // Notify observers about navigation.
2956 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2957 AppCacheAccessed(manifest_url
, blocked_by_policy
));
2960 void WebContentsImpl::OnOpenColorChooser(
2961 int color_chooser_id
,
2963 const std::vector
<ColorSuggestion
>& suggestions
) {
2964 if (!HasValidFrameSource())
2967 ColorChooser
* new_color_chooser
= delegate_
?
2968 delegate_
->OpenColorChooser(this, color
, suggestions
) :
2970 if (!new_color_chooser
)
2972 if (color_chooser_info_
.get())
2973 color_chooser_info_
->chooser
->End();
2975 color_chooser_info_
.reset(new ColorChooserInfo(
2976 render_frame_message_source_
->GetProcess()->GetID(),
2977 render_frame_message_source_
->GetRoutingID(),
2982 void WebContentsImpl::OnEndColorChooser(int color_chooser_id
) {
2983 if (color_chooser_info_
&&
2984 color_chooser_id
== color_chooser_info_
->identifier
)
2985 color_chooser_info_
->chooser
->End();
2988 void WebContentsImpl::OnSetSelectedColorInColorChooser(int color_chooser_id
,
2990 if (color_chooser_info_
&&
2991 color_chooser_id
== color_chooser_info_
->identifier
)
2992 color_chooser_info_
->chooser
->SetSelectedColor(color
);
2995 // This exists for render views that don't have a WebUI, but do have WebUI
2996 // bindings enabled.
2997 void WebContentsImpl::OnWebUISend(const GURL
& source_url
,
2998 const std::string
& name
,
2999 const base::ListValue
& args
) {
3001 delegate_
->WebUISend(this, source_url
, name
, args
);
3004 #if defined(ENABLE_PLUGINS)
3005 void WebContentsImpl::OnPepperPluginHung(int plugin_child_id
,
3006 const base::FilePath
& path
,
3008 UMA_HISTOGRAM_COUNTS("Pepper.PluginHung", 1);
3010 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3011 PluginHungStatusChanged(plugin_child_id
, path
, is_hung
));
3014 void WebContentsImpl::OnPluginCrashed(const base::FilePath
& plugin_path
,
3015 base::ProcessId plugin_pid
) {
3016 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3017 PluginCrashed(plugin_path
, plugin_pid
));
3020 void WebContentsImpl::OnRequestPpapiBrokerPermission(
3023 const base::FilePath
& plugin_path
) {
3025 OnPpapiBrokerPermissionResult(routing_id
, false);
3029 if (!delegate_
->RequestPpapiBrokerPermission(
3030 this, url
, plugin_path
,
3031 base::Bind(&WebContentsImpl::OnPpapiBrokerPermissionResult
,
3032 base::Unretained(this), routing_id
))) {
3034 OnPpapiBrokerPermissionResult(routing_id
, false);
3038 void WebContentsImpl::OnPpapiBrokerPermissionResult(int routing_id
,
3040 Send(new ViewMsg_PpapiBrokerPermissionResult(routing_id
, result
));
3043 void WebContentsImpl::OnBrowserPluginMessage(RenderFrameHost
* render_frame_host
,
3044 const IPC::Message
& message
) {
3045 CHECK(!browser_plugin_embedder_
.get());
3046 CreateBrowserPluginEmbedderIfNecessary();
3047 browser_plugin_embedder_
->OnMessageReceived(message
, render_frame_host
);
3049 #endif // defined(ENABLE_PLUGINS)
3051 void WebContentsImpl::OnDidDownloadImage(
3053 int http_status_code
,
3054 const GURL
& image_url
,
3055 const std::vector
<SkBitmap
>& bitmaps
,
3056 const std::vector
<gfx::Size
>& original_bitmap_sizes
) {
3057 if (bitmaps
.size() != original_bitmap_sizes
.size())
3060 ImageDownloadMap::iterator iter
= image_download_map_
.find(id
);
3061 if (iter
== image_download_map_
.end()) {
3062 // Currently WebContents notifies us of ANY downloads so that it is
3063 // possible to get here.
3066 if (!iter
->second
.is_null()) {
3068 id
, http_status_code
, image_url
, bitmaps
, original_bitmap_sizes
);
3070 image_download_map_
.erase(id
);
3073 void WebContentsImpl::OnUpdateFaviconURL(
3074 const std::vector
<FaviconURL
>& candidates
) {
3075 // We get updated favicon URLs after the page stops loading. If a cross-site
3076 // navigation occurs while a page is still loading, the initial page
3077 // may stop loading and send us updated favicon URLs after the navigation
3078 // for the new page has committed.
3079 RenderViewHostImpl
* rvhi
=
3080 static_cast<RenderViewHostImpl
*>(render_view_message_source_
);
3081 if (!rvhi
->is_active())
3084 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3085 DidUpdateFaviconURL(candidates
));
3088 void WebContentsImpl::CreateAudioPowerSaveBlocker() {
3089 DCHECK(!audio_power_save_blocker_
);
3090 audio_power_save_blocker_
= PowerSaveBlocker::Create(
3091 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension
,
3092 PowerSaveBlocker::kReasonAudioPlayback
, "Playing audio");
3095 void WebContentsImpl::CreateVideoPowerSaveBlocker() {
3096 DCHECK(!video_power_save_blocker_
);
3097 DCHECK(!active_video_players_
.empty());
3098 video_power_save_blocker_
= PowerSaveBlocker::Create(
3099 PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep
,
3100 PowerSaveBlocker::kReasonVideoPlayback
, "Playing video");
3101 #if defined(OS_ANDROID)
3102 static_cast<PowerSaveBlockerImpl
*>(video_power_save_blocker_
.get())
3103 ->InitDisplaySleepBlocker(this);
3107 void WebContentsImpl::MaybeReleasePowerSaveBlockers() {
3108 // If there are no more audio players and we don't have audio stream
3109 // monitoring, release the audio power save blocker here instead of during
3110 // NotifyNavigationStateChanged().
3111 if (active_audio_players_
.empty() &&
3112 !audio_state_provider_
->IsAudioStateAvailable()) {
3113 audio_power_save_blocker_
.reset();
3116 // If there are no more video players, clear the video power save blocker.
3117 if (active_video_players_
.empty())
3118 video_power_save_blocker_
.reset();
3121 void WebContentsImpl::OnMediaPlayingNotification(int64 player_cookie
,
3125 // Ignore the videos playing remotely and don't hold the wake lock for the
3127 if (is_remote
) return;
3130 AddMediaPlayerEntry(player_cookie
, &active_audio_players_
);
3132 // If we don't have audio stream monitoring, allocate the audio power save
3133 // blocker here instead of during NotifyNavigationStateChanged().
3134 if (!audio_power_save_blocker_
&&
3135 !audio_state_provider_
->IsAudioStateAvailable()) {
3136 CreateAudioPowerSaveBlocker();
3141 AddMediaPlayerEntry(player_cookie
, &active_video_players_
);
3143 // If we're not hidden and have just created a player, create a blocker.
3144 if (!video_power_save_blocker_
&& !IsHidden())
3145 CreateVideoPowerSaveBlocker();
3148 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, MediaStartedPlaying());
3151 void WebContentsImpl::OnMediaPausedNotification(int64 player_cookie
) {
3152 RemoveMediaPlayerEntry(player_cookie
, &active_audio_players_
);
3153 RemoveMediaPlayerEntry(player_cookie
, &active_video_players_
);
3154 MaybeReleasePowerSaveBlockers();
3156 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, MediaPaused());
3159 void WebContentsImpl::OnFirstVisuallyNonEmptyPaint() {
3160 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3161 DidFirstVisuallyNonEmptyPaint());
3163 if (theme_color_
!= last_sent_theme_color_
) {
3164 // Theme color should have updated by now if there was one.
3165 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3166 DidChangeThemeColor(theme_color_
));
3167 last_sent_theme_color_
= theme_color_
;
3171 void WebContentsImpl::DidChangeVisibleSSLState() {
3173 delegate_
->VisibleSSLStateChanged(this);
3176 void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
3177 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3178 BeforeFormRepostWarningShow());
3181 void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
3184 delegate_
->ShowRepostFormWarningDialog(this);
3187 bool WebContentsImpl::HasAccessedInitialDocument() {
3188 return has_accessed_initial_document_
;
3191 // Notifies the RenderWidgetHost instance about the fact that the page is
3192 // loading, or done loading.
3193 void WebContentsImpl::SetIsLoading(bool is_loading
,
3194 bool to_different_document
,
3195 LoadNotificationDetails
* details
) {
3196 if (is_loading
== is_loading_
)
3200 load_state_
= net::LoadStateWithParam(net::LOAD_STATE_IDLE
,
3202 load_state_host_
.clear();
3204 upload_position_
= 0;
3207 GetRenderManager()->SetIsLoading(is_loading
);
3209 is_loading_
= is_loading
;
3210 waiting_for_response_
= is_loading
;
3211 is_load_to_different_document_
= to_different_document
;
3214 delegate_
->LoadingStateChanged(this, to_different_document
);
3215 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD
);
3217 std::string url
= (details
? details
->url
.possibly_invalid_spec() : "NULL");
3219 TRACE_EVENT_ASYNC_BEGIN1("browser,navigation", "WebContentsImpl Loading",
3221 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, DidStartLoading());
3223 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
3225 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, DidStopLoading());
3228 // TODO(avi): Remove. http://crbug.com/170921
3229 int type
= is_loading
? NOTIFICATION_LOAD_START
: NOTIFICATION_LOAD_STOP
;
3230 NotificationDetails det
= NotificationService::NoDetails();
3232 det
= Details
<LoadNotificationDetails
>(details
);
3233 NotificationService::current()->Notify(
3234 type
, Source
<NavigationController
>(&controller_
), det
);
3237 void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point
& extent
) {
3238 RenderFrameHost
* focused_frame
= GetFocusedFrame();
3242 focused_frame
->Send(new InputMsg_MoveRangeSelectionExtent(
3243 focused_frame
->GetRoutingID(), extent
));
3246 void WebContentsImpl::SelectRange(const gfx::Point
& base
,
3247 const gfx::Point
& extent
) {
3248 RenderFrameHost
* focused_frame
= GetFocusedFrame();
3252 focused_frame
->Send(
3253 new InputMsg_SelectRange(focused_frame
->GetRoutingID(), base
, extent
));
3256 void WebContentsImpl::UpdateMaxPageIDIfNecessary(RenderViewHost
* rvh
) {
3257 // If we are creating a RVH for a restored controller, then we need to make
3258 // sure the RenderView starts with a next_page_id_ larger than the number
3259 // of restored entries. This must be called before the RenderView starts
3260 // navigating (to avoid a race between the browser updating max_page_id and
3261 // the renderer updating next_page_id_). Because of this, we only call this
3262 // from CreateRenderView and allow that to notify the RenderView for us.
3263 int max_restored_page_id
= controller_
.GetMaxRestoredPageID();
3264 if (max_restored_page_id
>
3265 GetMaxPageIDForSiteInstance(rvh
->GetSiteInstance()))
3266 UpdateMaxPageIDForSiteInstance(rvh
->GetSiteInstance(),
3267 max_restored_page_id
);
3270 bool WebContentsImpl::UpdateTitleForEntry(NavigationEntryImpl
* entry
,
3271 const base::string16
& title
) {
3272 // For file URLs without a title, use the pathname instead. In the case of a
3273 // synthesized title, we don't want the update to count toward the "one set
3274 // per page of the title to history."
3275 base::string16 final_title
;
3277 if (entry
&& entry
->GetURL().SchemeIsFile() && title
.empty()) {
3278 final_title
= base::UTF8ToUTF16(entry
->GetURL().ExtractFileName());
3279 explicit_set
= false; // Don't count synthetic titles toward the set limit.
3281 base::TrimWhitespace(title
, base::TRIM_ALL
, &final_title
);
3282 explicit_set
= true;
3285 // If a page is created via window.open and never navigated,
3286 // there will be no navigation entry. In this situation,
3287 // |page_title_when_no_navigation_entry_| will be used for page title.
3289 if (final_title
== entry
->GetTitle())
3290 return false; // Nothing changed, don't bother.
3292 entry
->SetTitle(final_title
);
3294 if (page_title_when_no_navigation_entry_
== final_title
)
3295 return false; // Nothing changed, don't bother.
3297 page_title_when_no_navigation_entry_
= final_title
;
3300 // Lastly, set the title for the view.
3301 view_
->SetPageTitle(final_title
);
3303 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3304 TitleWasSet(entry
, explicit_set
));
3306 // TODO(avi): Remove. http://crbug.com/170921
3307 std::pair
<NavigationEntry
*, bool> details
=
3308 std::make_pair(entry
, explicit_set
);
3309 NotificationService::current()->Notify(
3310 NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED
,
3311 Source
<WebContents
>(this),
3312 Details
<std::pair
<NavigationEntry
*, bool> >(&details
));
3317 void WebContentsImpl::SendChangeLoadProgress() {
3318 loading_last_progress_update_
= base::TimeTicks::Now();
3320 delegate_
->LoadProgressChanged(this, frame_tree_
.load_progress());
3323 void WebContentsImpl::ResetLoadProgressState() {
3324 frame_tree_
.ResetLoadProgress();
3325 loading_weak_factory_
.InvalidateWeakPtrs();
3326 loading_last_progress_update_
= base::TimeTicks();
3329 void WebContentsImpl::NotifyViewSwapped(RenderViewHost
* old_host
,
3330 RenderViewHost
* new_host
) {
3331 // After sending out a swap notification, we need to send a disconnect
3332 // notification so that clients that pick up a pointer to |this| can NULL the
3333 // pointer. See Bug 1230284.
3334 notify_disconnection_
= true;
3335 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3336 RenderViewHostChanged(old_host
, new_host
));
3338 // TODO(avi): Remove. http://crbug.com/170921
3339 std::pair
<RenderViewHost
*, RenderViewHost
*> details
=
3340 std::make_pair(old_host
, new_host
);
3341 NotificationService::current()->Notify(
3342 NOTIFICATION_RENDER_VIEW_HOST_CHANGED
,
3343 Source
<WebContents
>(this),
3344 Details
<std::pair
<RenderViewHost
*, RenderViewHost
*> >(&details
));
3346 // Ensure that the associated embedder gets cleared after a RenderViewHost
3347 // gets swapped, so we don't reuse the same embedder next time a
3348 // RenderViewHost is attached to this WebContents.
3349 RemoveBrowserPluginEmbedder();
3352 void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost
* old_host
,
3353 RenderFrameHost
* new_host
) {
3354 FOR_EACH_OBSERVER(WebContentsObserver
,
3356 RenderFrameHostChanged(old_host
, new_host
));
3359 // TODO(avi): Remove this entire function because this notification is already
3360 // covered by two observer functions. http://crbug.com/170921
3361 void WebContentsImpl::NotifyDisconnected() {
3362 if (!notify_disconnection_
)
3365 notify_disconnection_
= false;
3366 NotificationService::current()->Notify(
3367 NOTIFICATION_WEB_CONTENTS_DISCONNECTED
,
3368 Source
<WebContents
>(this),
3369 NotificationService::NoDetails());
3372 void WebContentsImpl::NotifyNavigationEntryCommitted(
3373 const LoadCommittedDetails
& load_details
) {
3375 WebContentsObserver
, observers_
, NavigationEntryCommitted(load_details
));
3378 bool WebContentsImpl::OnMessageReceived(RenderFrameHost
* render_frame_host
,
3379 const IPC::Message
& message
) {
3380 return OnMessageReceived(NULL
, render_frame_host
, message
);
3383 const GURL
& WebContentsImpl::GetMainFrameLastCommittedURL() const {
3384 return GetLastCommittedURL();
3387 void WebContentsImpl::RenderFrameCreated(RenderFrameHost
* render_frame_host
) {
3388 // Note this is only for subframes, the notification for the main frame
3389 // happens in RenderViewCreated.
3390 FOR_EACH_OBSERVER(WebContentsObserver
,
3392 RenderFrameCreated(render_frame_host
));
3393 SetAccessibilityModeOnFrame(accessibility_mode_
, render_frame_host
);
3396 void WebContentsImpl::RenderFrameDeleted(RenderFrameHost
* render_frame_host
) {
3397 ClearPowerSaveBlockers(render_frame_host
);
3398 FOR_EACH_OBSERVER(WebContentsObserver
,
3400 RenderFrameDeleted(render_frame_host
));
3403 void WebContentsImpl::WorkerCrashed(RenderFrameHost
* render_frame_host
) {
3405 delegate_
->WorkerCrashed(this);
3408 void WebContentsImpl::ShowContextMenu(RenderFrameHost
* render_frame_host
,
3409 const ContextMenuParams
& params
) {
3410 ContextMenuParams
context_menu_params(params
);
3411 // Allow WebContentsDelegates to handle the context menu operation first.
3412 if (GetBrowserPluginGuest()) {
3413 WebContentsViewGuest
* view_guest
=
3414 static_cast<WebContentsViewGuest
*>(GetView());
3415 context_menu_params
= view_guest
->ConvertContextMenuParams(params
);
3417 if (delegate_
&& delegate_
->HandleContextMenu(context_menu_params
))
3420 render_view_host_delegate_view_
->ShowContextMenu(render_frame_host
,
3421 context_menu_params
);
3424 void WebContentsImpl::RunJavaScriptMessage(
3425 RenderFrameHost
* render_frame_host
,
3426 const base::string16
& message
,
3427 const base::string16
& default_prompt
,
3428 const GURL
& frame_url
,
3429 JavaScriptMessageType javascript_message_type
,
3430 IPC::Message
* reply_msg
) {
3431 // Suppress JavaScript dialogs when requested. Also suppress messages when
3432 // showing an interstitial as it's shown over the previous page and we don't
3433 // want the hidden page's dialogs to interfere with the interstitial.
3434 bool suppress_this_message
=
3435 static_cast<RenderFrameHostImpl
*>(render_frame_host
)->is_swapped_out() ||
3436 ShowingInterstitialPage() || !delegate_
||
3437 delegate_
->ShouldSuppressDialogs(this) ||
3438 !delegate_
->GetJavaScriptDialogManager(this);
3440 if (!suppress_this_message
) {
3441 std::string accept_lang
= GetContentClient()->browser()->
3442 GetAcceptLangs(GetBrowserContext());
3443 dialog_manager_
= delegate_
->GetJavaScriptDialogManager(this);
3444 dialog_manager_
->RunJavaScriptDialog(
3446 frame_url
.GetOrigin(),
3448 javascript_message_type
,
3451 base::Bind(&WebContentsImpl::OnDialogClosed
,
3452 base::Unretained(this),
3453 render_frame_host
->GetProcess()->GetID(),
3454 render_frame_host
->GetRoutingID(),
3457 &suppress_this_message
);
3460 if (suppress_this_message
) {
3461 // If we are suppressing messages, just reply as if the user immediately
3462 // pressed "Cancel", passing true to |dialog_was_suppressed|.
3463 OnDialogClosed(render_frame_host
->GetProcess()->GetID(),
3464 render_frame_host
->GetRoutingID(), reply_msg
,
3465 true, false, base::string16());
3468 // OnDialogClosed (two lines up) may have caused deletion of this object (see
3469 // http://crbug.com/288961 ). The only safe thing to do here is return.
3472 void WebContentsImpl::RunBeforeUnloadConfirm(
3473 RenderFrameHost
* render_frame_host
,
3474 const base::string16
& message
,
3476 IPC::Message
* reply_msg
) {
3477 RenderFrameHostImpl
* rfhi
=
3478 static_cast<RenderFrameHostImpl
*>(render_frame_host
);
3480 delegate_
->WillRunBeforeUnloadConfirm();
3482 bool suppress_this_message
=
3483 rfhi
->rfh_state() != RenderFrameHostImpl::STATE_DEFAULT
|| !delegate_
||
3484 delegate_
->ShouldSuppressDialogs(this) ||
3485 !delegate_
->GetJavaScriptDialogManager(this);
3486 if (suppress_this_message
) {
3487 rfhi
->JavaScriptDialogClosed(reply_msg
, true, base::string16(), true);
3491 is_showing_before_unload_dialog_
= true;
3492 dialog_manager_
= delegate_
->GetJavaScriptDialogManager(this);
3493 dialog_manager_
->RunBeforeUnloadDialog(
3494 this, message
, is_reload
,
3495 base::Bind(&WebContentsImpl::OnDialogClosed
, base::Unretained(this),
3496 render_frame_host
->GetProcess()->GetID(),
3497 render_frame_host
->GetRoutingID(), reply_msg
,
3501 WebContents
* WebContentsImpl::GetAsWebContents() {
3505 bool WebContentsImpl::IsNeverVisible() {
3508 return delegate_
->IsNeverVisible(this);
3512 gfx::NativeViewAccessible
WebContentsImpl::GetParentNativeViewAccessible() {
3513 return accessible_parent_
;
3517 RenderViewHostDelegateView
* WebContentsImpl::GetDelegateView() {
3518 return render_view_host_delegate_view_
;
3521 RendererPreferences
WebContentsImpl::GetRendererPrefs(
3522 BrowserContext
* browser_context
) const {
3523 return renderer_preferences_
;
3526 gfx::Rect
WebContentsImpl::GetRootWindowResizerRect() const {
3528 return delegate_
->GetRootWindowResizerRect();
3532 void WebContentsImpl::RemoveBrowserPluginEmbedder() {
3533 if (browser_plugin_embedder_
)
3534 browser_plugin_embedder_
.reset();
3537 void WebContentsImpl::RenderViewCreated(RenderViewHost
* render_view_host
) {
3538 // Don't send notifications if we are just creating a swapped-out RVH for
3539 // the opener chain. These won't be used for view-source or WebUI, so it's
3540 // ok to return early.
3541 if (!static_cast<RenderViewHostImpl
*>(render_view_host
)->is_active())
3545 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
3547 NotificationService::current()->Notify(
3548 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED
,
3549 Source
<WebContents
>(this),
3550 Details
<RenderViewHost
>(render_view_host
));
3552 // When we're creating views, we're still doing initial setup, so we always
3553 // use the pending Web UI rather than any possibly existing committed one.
3554 if (GetRenderManager()->pending_web_ui())
3555 GetRenderManager()->pending_web_ui()->RenderViewCreated(render_view_host
);
3557 NavigationEntry
* entry
= controller_
.GetPendingEntry();
3558 if (entry
&& entry
->IsViewSourceMode()) {
3559 // Put the renderer in view source mode.
3560 render_view_host
->Send(
3561 new ViewMsg_EnableViewSourceMode(render_view_host
->GetRoutingID()));
3564 view_
->RenderViewCreated(render_view_host
);
3567 WebContentsObserver
, observers_
, RenderViewCreated(render_view_host
));
3570 void WebContentsImpl::RenderViewReady(RenderViewHost
* rvh
) {
3571 if (rvh
!= GetRenderViewHost()) {
3572 // Don't notify the world, since this came from a renderer in the
3577 notify_disconnection_
= true;
3578 // TODO(avi): Remove. http://crbug.com/170921
3579 NotificationService::current()->Notify(
3580 NOTIFICATION_WEB_CONTENTS_CONNECTED
,
3581 Source
<WebContents
>(this),
3582 NotificationService::NoDetails());
3584 bool was_crashed
= IsCrashed();
3585 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING
, 0);
3587 // Restore the focus to the tab (otherwise the focus will be on the top
3589 if (was_crashed
&& !FocusLocationBarByDefault() &&
3590 (!delegate_
|| delegate_
->ShouldFocusPageAfterCrash())) {
3594 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, RenderViewReady());
3597 void WebContentsImpl::RenderViewTerminated(RenderViewHost
* rvh
,
3598 base::TerminationStatus status
,
3600 if (rvh
!= GetRenderViewHost()) {
3601 // The pending page's RenderViewHost is gone.
3605 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
3606 // renderer may not have made a clean exit.
3607 if (IsFullscreenForCurrentTab())
3608 ExitFullscreenMode();
3610 // Cancel any visible dialogs so they are not left dangling over the sad tab.
3611 if (dialog_manager_
)
3612 dialog_manager_
->CancelActiveAndPendingDialogs(this);
3615 delegate_
->HideValidationMessage(this);
3617 SetIsLoading(false, true, nullptr);
3618 NotifyDisconnected();
3619 SetIsCrashed(status
, error_code
);
3621 // Reset the loading progress. TODO(avi): What does it mean to have a
3622 // "renderer crash" when there is more than one renderer process serving a
3623 // webpage? Once this function is called at a more granular frame level, we
3624 // probably will need to more granularly reset the state here.
3625 ResetLoadProgressState();
3627 FOR_EACH_OBSERVER(WebContentsObserver
,
3629 RenderProcessGone(GetCrashedStatus()));
3632 void WebContentsImpl::RenderViewDeleted(RenderViewHost
* rvh
) {
3633 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, RenderViewDeleted(rvh
));
3636 void WebContentsImpl::UpdateState(RenderViewHost
* rvh
,
3638 const PageState
& page_state
) {
3639 // Ensure that this state update comes from a RenderViewHost that belongs to
3640 // this WebContents.
3641 // TODO(nasko): This should go through RenderFrameHost.
3642 // TODO(creis): We can't update state for cross-process subframes until we
3643 // have FrameNavigationEntries. Once we do, this should be a DCHECK.
3644 if (rvh
->GetDelegate()->GetAsWebContents() != this)
3647 // We must be prepared to handle state updates for any page, these occur
3648 // when the user is scrolling and entering form data, as well as when we're
3649 // leaving a page, in which case our state may have already been moved to
3650 // the next page. The navigation controller will look up the appropriate
3651 // NavigationEntry and update it when it is notified via the delegate.
3653 int entry_index
= controller_
.GetEntryIndexWithPageID(
3654 rvh
->GetSiteInstance(), page_id
);
3655 if (entry_index
< 0)
3657 NavigationEntry
* entry
= controller_
.GetEntryAtIndex(entry_index
);
3659 if (page_state
== entry
->GetPageState())
3660 return; // Nothing to update.
3661 entry
->SetPageState(page_state
);
3662 controller_
.NotifyEntryChanged(entry
, entry_index
);
3665 void WebContentsImpl::UpdateTargetURL(RenderViewHost
* render_view_host
,
3667 if (fullscreen_widget_routing_id_
!= MSG_ROUTING_NONE
) {
3668 // If we're fullscreen only update the url if it's from the fullscreen
3670 RenderWidgetHostView
* fs
= GetFullscreenRenderWidgetHostView();
3671 if (fs
&& fs
->GetRenderWidgetHost() != render_view_host
)
3675 delegate_
->UpdateTargetURL(this, url
);
3678 void WebContentsImpl::Close(RenderViewHost
* rvh
) {
3679 #if defined(OS_MACOSX)
3680 // The UI may be in an event-tracking loop, such as between the
3681 // mouse-down and mouse-up in text selection or a button click.
3682 // Defer the close until after tracking is complete, so that we
3683 // don't free objects out from under the UI.
3684 // TODO(shess): This could get more fine-grained. For instance,
3685 // closing a tab in another window while selecting text in the
3686 // current window's Omnibox should be just fine.
3687 if (view_
->IsEventTracking()) {
3688 view_
->CloseTabAfterEventTracking();
3693 // Ignore this if it comes from a RenderViewHost that we aren't showing.
3694 if (delegate_
&& rvh
== GetRenderViewHost())
3695 delegate_
->CloseContents(this);
3698 void WebContentsImpl::SwappedOut(RenderFrameHost
* rfh
) {
3699 if (delegate_
&& rfh
->GetRenderViewHost() == GetRenderViewHost())
3700 delegate_
->SwappedOut(this);
3703 void WebContentsImpl::DidDeferAfterResponseStarted(
3704 const TransitionLayerData
& transition_data
) {
3705 #if defined(OS_ANDROID)
3706 GetWebContentsAndroid()->DidDeferAfterResponseStarted(transition_data
);
3710 bool WebContentsImpl::WillHandleDeferAfterResponseStarted() {
3711 #if defined(OS_ANDROID)
3712 return GetWebContentsAndroid()->WillHandleDeferAfterResponseStarted();
3718 void WebContentsImpl::RequestMove(const gfx::Rect
& new_bounds
) {
3719 if (delegate_
&& delegate_
->IsPopupOrPanel(this))
3720 delegate_
->MoveContents(this, new_bounds
);
3723 void WebContentsImpl::DidStartLoading(FrameTreeNode
* frame_tree_node
,
3724 bool to_different_document
) {
3725 SetIsLoading(true, to_different_document
, nullptr);
3727 // Notify accessibility that the user is navigating away from the
3728 // current document.
3730 // TODO(dmazzoni): do this using a WebContentsObserver.
3731 BrowserAccessibilityManager
* manager
=
3732 frame_tree_node
->current_frame_host()->browser_accessibility_manager();
3734 manager
->UserIsNavigatingAway();
3737 void WebContentsImpl::DidStopLoading() {
3738 scoped_ptr
<LoadNotificationDetails
> details
;
3740 // Use the last committed entry rather than the active one, in case a
3741 // pending entry has been created.
3742 NavigationEntry
* entry
= controller_
.GetLastCommittedEntry();
3743 Navigator
* navigator
= frame_tree_
.root()->navigator();
3745 // An entry may not exist for a stop when loading an initial blank page or
3746 // if an iframe injected by script into a blank page finishes loading.
3748 base::TimeDelta elapsed
=
3749 base::TimeTicks::Now() - navigator
->GetCurrentLoadStart();
3751 details
.reset(new LoadNotificationDetails(
3752 entry
->GetVirtualURL(),
3753 entry
->GetTransitionType(),
3756 controller_
.GetCurrentEntryIndex()));
3759 SetIsLoading(false, true, details
.get());
3762 void WebContentsImpl::DidChangeLoadProgress() {
3763 double load_progress
= frame_tree_
.load_progress();
3765 // The delegate is notified immediately for the first and last updates. Also,
3766 // since the message loop may be pretty busy when a page is loaded, it might
3767 // not execute a posted task in a timely manner so the progress report is sent
3768 // immediately if enough time has passed.
3769 base::TimeDelta min_delay
=
3770 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS
);
3771 bool delay_elapsed
= loading_last_progress_update_
.is_null() ||
3772 base::TimeTicks::Now() - loading_last_progress_update_
> min_delay
;
3774 if (load_progress
== 0.0 || load_progress
== 1.0 || delay_elapsed
) {
3775 // If there is a pending task to send progress, it is now obsolete.
3776 loading_weak_factory_
.InvalidateWeakPtrs();
3778 // Notify the load progress change.
3779 SendChangeLoadProgress();
3781 // Clean-up the states if needed.
3782 if (load_progress
== 1.0)
3783 ResetLoadProgressState();
3787 if (loading_weak_factory_
.HasWeakPtrs())
3790 base::MessageLoop::current()->PostDelayedTask(
3792 base::Bind(&WebContentsImpl::SendChangeLoadProgress
,
3793 loading_weak_factory_
.GetWeakPtr()),
3797 void WebContentsImpl::DidCancelLoading() {
3798 controller_
.DiscardNonCommittedEntries();
3800 // Update the URL display.
3801 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL
);
3804 void WebContentsImpl::DidAccessInitialDocument() {
3805 has_accessed_initial_document_
= true;
3807 // We may have left a failed browser-initiated navigation in the address bar
3808 // to let the user edit it and try again. Clear it now that content might
3809 // show up underneath it.
3810 if (!IsLoading() && controller_
.GetPendingEntry())
3811 controller_
.DiscardPendingEntry(false);
3813 // Update the URL display.
3814 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL
);
3817 void WebContentsImpl::DidChangeName(RenderFrameHost
* render_frame_host
,
3818 const std::string
& name
) {
3819 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3820 FrameNameChanged(render_frame_host
, name
));
3823 void WebContentsImpl::DidDisownOpener(RenderFrameHost
* render_frame_host
) {
3824 // No action is necessary if the opener has already been cleared.
3828 // Clear our opener so that future cross-process navigations don't have an
3830 RemoveDestructionObserver(opener_
);
3833 // Notify all swapped out RenderViewHosts for this tab. This is important
3834 // in case we go back to them, or if another window in those processes tries
3835 // to access window.opener.
3836 GetRenderManager()->DidDisownOpener(render_frame_host
);
3839 void WebContentsImpl::DocumentOnLoadCompleted(
3840 RenderFrameHost
* render_frame_host
) {
3841 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3842 DocumentOnLoadCompletedInMainFrame());
3844 // TODO(avi): Remove. http://crbug.com/170921
3845 NotificationService::current()->Notify(
3846 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
,
3847 Source
<WebContents
>(this),
3848 NotificationService::NoDetails());
3851 void WebContentsImpl::UpdateTitle(RenderFrameHost
* render_frame_host
,
3853 const base::string16
& title
,
3854 base::i18n::TextDirection title_direction
) {
3855 RenderViewHost
* rvh
= render_frame_host
->GetRenderViewHost();
3857 // If we have a title, that's a pretty good indication that we've started
3858 // getting useful data.
3859 SetNotWaitingForResponse();
3861 // Try to find the navigation entry, which might not be the current one.
3862 // For example, it might be from a pending RVH for the pending entry.
3863 NavigationEntryImpl
* entry
= controller_
.GetEntryWithPageID(
3864 rvh
->GetSiteInstance(), page_id
);
3866 // We can handle title updates when we don't have an entry in
3867 // UpdateTitleForEntry, but only if the update is from the current RVH.
3868 // TODO(avi): Change to make decisions based on the RenderFrameHost.
3869 if (!entry
&& rvh
!= GetRenderViewHost())
3872 // TODO(evan): make use of title_direction.
3873 // http://code.google.com/p/chromium/issues/detail?id=27094
3874 if (!UpdateTitleForEntry(entry
, title
))
3877 // Broadcast notifications when the UI should be updated.
3878 if (entry
== controller_
.GetEntryAtOffset(0))
3879 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE
);
3882 void WebContentsImpl::UpdateEncoding(RenderFrameHost
* render_frame_host
,
3883 const std::string
& encoding
) {
3884 SetEncoding(encoding
);
3887 void WebContentsImpl::DocumentAvailableInMainFrame(
3888 RenderViewHost
* render_view_host
) {
3889 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3890 DocumentAvailableInMainFrame());
3892 void WebContentsImpl::RouteCloseEvent(RenderViewHost
* rvh
) {
3893 // Tell the active RenderViewHost to run unload handlers and close, as long
3894 // as the request came from a RenderViewHost in the same BrowsingInstance.
3895 // In most cases, we receive this from a swapped out RenderViewHost.
3896 // It is possible to receive it from one that has just been swapped in,
3897 // in which case we might as well deliver the message anyway.
3898 if (rvh
->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()))
3899 GetRenderViewHost()->ClosePage();
3902 bool WebContentsImpl::ShouldRouteMessageEvent(
3903 RenderFrameHost
* target_rfh
,
3904 SiteInstance
* source_site_instance
) const {
3905 // Allow the message if this WebContents is dedicated to a browser plugin
3907 // Note: This check means that an embedder could theoretically receive a
3908 // postMessage from anyone (not just its own guests). However, this is
3909 // probably not a risk for apps since other pages won't have references
3911 return GetBrowserPluginGuest() || GetBrowserPluginEmbedder();
3914 int WebContentsImpl::EnsureOpenerRenderViewsExist(
3915 RenderFrameHost
* source_rfh
) {
3916 WebContentsImpl
* source_web_contents
= static_cast<WebContentsImpl
*>(
3917 WebContents::FromRenderFrameHost(source_rfh
));
3919 if (source_web_contents
) {
3920 if (GetBrowserPluginGuest()) {
3921 // We create a swapped out RenderView for the embedder in the guest's
3922 // render process but we intentionally do not expose the embedder's
3923 // opener chain to it.
3925 source_web_contents
->CreateSwappedOutRenderView(GetSiteInstance());
3927 return source_web_contents
->CreateOpenerRenderViews(GetSiteInstance());
3931 return MSG_ROUTING_NONE
;
3934 bool WebContentsImpl::AddMessageToConsole(int32 level
,
3935 const base::string16
& message
,
3937 const base::string16
& source_id
) {
3940 return delegate_
->AddMessageToConsole(this, level
, message
, line_no
,
3944 int WebContentsImpl::CreateSwappedOutRenderView(
3945 SiteInstance
* instance
) {
3946 int render_view_routing_id
= MSG_ROUTING_NONE
;
3947 GetRenderManager()->CreateRenderFrame(
3948 instance
, nullptr, MSG_ROUTING_NONE
,
3949 CREATE_RF_SWAPPED_OUT
| CREATE_RF_FOR_MAIN_FRAME_NAVIGATION
|
3951 &render_view_routing_id
);
3952 return render_view_routing_id
;
3955 void WebContentsImpl::OnUserGesture() {
3956 // Notify observers.
3957 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, DidGetUserGesture());
3959 ResourceDispatcherHostImpl
* rdh
= ResourceDispatcherHostImpl::Get();
3960 if (rdh
) // NULL in unittests.
3961 rdh
->OnUserGesture(this);
3964 void WebContentsImpl::OnIgnoredUIEvent() {
3965 // Notify observers.
3966 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, DidGetIgnoredUIEvent());
3969 void WebContentsImpl::RendererUnresponsive(RenderViewHost
* render_view_host
) {
3970 // Don't show hung renderer dialog for a swapped out RVH.
3971 if (render_view_host
!= GetRenderViewHost())
3974 RenderViewHostImpl
* rvhi
= static_cast<RenderViewHostImpl
*>(render_view_host
);
3975 RenderFrameHostImpl
* rfhi
=
3976 static_cast<RenderFrameHostImpl
*>(rvhi
->GetMainFrame());
3978 // Ignore renderer unresponsive event if debugger is attached to the tab
3979 // since the event may be a result of the renderer sitting on a breakpoint.
3980 // See http://crbug.com/65458
3981 if (DevToolsAgentHost::IsDebuggerAttached(this))
3984 if (rfhi
->IsWaitingForBeforeUnloadACK() ||
3985 rfhi
->IsWaitingForUnloadACK()) {
3986 // Hang occurred while firing the beforeunload/unload handler.
3987 // Pretend the handler fired so tab closing continues as if it had.
3988 rvhi
->set_sudden_termination_allowed(true);
3990 if (!GetRenderManager()->ShouldCloseTabOnUnresponsiveRenderer())
3993 // If the tab hangs in the beforeunload/unload handler there's really
3994 // nothing we can do to recover. If the hang is in the beforeunload handler,
3995 // pretend the beforeunload listeners have all fired and allow the delegate
3996 // to continue closing; the user will not have the option of cancelling the
3997 // close. Otherwise, pretend the unload listeners have all fired and close
4000 if (rfhi
->IsWaitingForBeforeUnloadACK() && delegate_
) {
4001 delegate_
->BeforeUnloadFired(this, true, &close
);
4008 if (!GetRenderViewHost() || !GetRenderViewHost()->IsRenderViewLive())
4012 delegate_
->RendererUnresponsive(this);
4015 void WebContentsImpl::RendererResponsive(RenderViewHost
* render_view_host
) {
4017 delegate_
->RendererResponsive(this);
4020 void WebContentsImpl::LoadStateChanged(
4022 const net::LoadStateWithParam
& load_state
,
4023 uint64 upload_position
,
4024 uint64 upload_size
) {
4025 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
4027 tracked_objects::ScopedTracker
tracking_profile1(
4028 FROM_HERE_WITH_EXPLICIT_FUNCTION(
4029 "466285 WebContentsImpl::LoadStateChanged::Start"));
4030 load_state_
= load_state
;
4031 upload_position_
= upload_position
;
4032 upload_size_
= upload_size
;
4033 load_state_host_
= net::IDNToUnicode(url
.host(),
4034 GetContentClient()->browser()->GetAcceptLangs(
4035 GetBrowserContext()));
4036 if (load_state_
.state
== net::LOAD_STATE_READING_RESPONSE
)
4037 SetNotWaitingForResponse();
4039 NotifyNavigationStateChanged(static_cast<InvalidateTypes
>(
4040 INVALIDATE_TYPE_LOAD
| INVALIDATE_TYPE_TAB
));
4044 void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
4045 bool proceed
, const base::TimeTicks
& proceed_time
,
4046 bool* proceed_to_fire_unload
) {
4047 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
4048 BeforeUnloadFired(proceed_time
));
4050 delegate_
->BeforeUnloadFired(this, proceed
, proceed_to_fire_unload
);
4051 // Note: |this| might be deleted at this point.
4054 void WebContentsImpl::RenderProcessGoneFromRenderManager(
4055 RenderViewHost
* render_view_host
) {
4056 DCHECK(crashed_status_
!= base::TERMINATION_STATUS_STILL_RUNNING
);
4057 RenderViewTerminated(render_view_host
, crashed_status_
, crashed_error_code_
);
4060 void WebContentsImpl::UpdateRenderViewSizeForRenderManager() {
4061 // TODO(brettw) this is a hack. See WebContentsView::SizeContents.
4062 gfx::Size size
= GetSizeForNewRenderView();
4063 // 0x0 isn't a valid window size (minimal window size is 1x1) but it may be
4064 // here during container initialization and normal window size will be set
4065 // later. In case of tab duplication this resizing to 0x0 prevents setting
4066 // normal size later so just ignore it.
4067 if (!size
.IsEmpty())
4068 view_
->SizeContents(size
);
4071 void WebContentsImpl::CancelModalDialogsForRenderManager() {
4072 // We need to cancel modal dialogs when doing a process swap, since the load
4073 // deferrer would prevent us from swapping out. We also clear the state
4074 // because this is a cross-process navigation, which means that it's a new
4075 // site that should not have to pay for the sins of its predecessor.
4076 if (dialog_manager_
)
4077 dialog_manager_
->ResetDialogState(this);
4080 void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost
* old_host
,
4081 RenderFrameHost
* new_host
,
4082 bool is_main_frame
) {
4083 if (is_main_frame
) {
4084 NotifyViewSwapped(old_host
? old_host
->GetRenderViewHost() : nullptr,
4085 new_host
->GetRenderViewHost());
4087 // Make sure the visible RVH reflects the new delegate's preferences.
4089 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
4091 view_
->RenderViewSwappedIn(new_host
->GetRenderViewHost());
4094 NotifyFrameSwapped(old_host
, new_host
);
4097 void WebContentsImpl::NotifyMainFrameSwappedFromRenderManager(
4098 RenderViewHost
* old_host
,
4099 RenderViewHost
* new_host
) {
4100 NotifyViewSwapped(old_host
, new_host
);
4103 int WebContentsImpl::CreateOpenerRenderViewsForRenderManager(
4104 SiteInstance
* instance
) {
4106 return MSG_ROUTING_NONE
;
4108 // Recursively create RenderViews for anything else in the opener chain.
4109 return opener_
->CreateOpenerRenderViews(instance
);
4112 int WebContentsImpl::CreateOpenerRenderViews(SiteInstance
* instance
) {
4113 int opener_route_id
= MSG_ROUTING_NONE
;
4115 // If this tab has an opener, ensure it has a RenderView in the given
4116 // SiteInstance as well.
4118 opener_route_id
= opener_
->CreateOpenerRenderViews(instance
);
4120 // If any of the renderers (current, pending, or swapped out) for this
4121 // WebContents has the same SiteInstance, use it.
4122 if (GetRenderManager()->current_host()->GetSiteInstance() == instance
)
4123 return GetRenderManager()->current_host()->GetRoutingID();
4125 if (GetRenderManager()->pending_render_view_host() &&
4126 GetRenderManager()->pending_render_view_host()->GetSiteInstance() ==
4128 return GetRenderManager()->pending_render_view_host()->GetRoutingID();
4130 RenderViewHostImpl
* rvh
= GetRenderManager()->GetSwappedOutRenderViewHost(
4133 return rvh
->GetRoutingID();
4135 // Create a swapped out RenderView in the given SiteInstance if none exists,
4136 // setting its opener to the given route_id. Return the new view's route_id.
4137 int render_view_routing_id
= MSG_ROUTING_NONE
;
4138 GetRenderManager()->CreateRenderFrame(instance
, nullptr, opener_route_id
,
4139 CREATE_RF_FOR_MAIN_FRAME_NAVIGATION
|
4140 CREATE_RF_SWAPPED_OUT
|
4142 &render_view_routing_id
);
4143 return render_view_routing_id
;
4146 NavigationControllerImpl
& WebContentsImpl::GetControllerForRenderManager() {
4147 return GetController();
4150 scoped_ptr
<WebUIImpl
> WebContentsImpl::CreateWebUIForRenderManager(
4152 return scoped_ptr
<WebUIImpl
>(static_cast<WebUIImpl
*>(CreateWebUI(url
)));
4156 WebContentsImpl::GetLastCommittedNavigationEntryForRenderManager() {
4157 return controller_
.GetLastCommittedEntry();
4160 bool WebContentsImpl::CreateRenderViewForRenderManager(
4161 RenderViewHost
* render_view_host
,
4162 int opener_route_id
,
4163 int proxy_routing_id
,
4164 bool for_main_frame_navigation
) {
4165 TRACE_EVENT0("browser,navigation",
4166 "WebContentsImpl::CreateRenderViewForRenderManager");
4167 // Can be NULL during tests.
4168 RenderWidgetHostViewBase
* rwh_view
;
4169 // TODO(kenrb): RenderWidgetHostViewChildFrame special casing is temporary
4170 // until RenderWidgetHost is attached to RenderFrameHost. We need to special
4171 // case this because RWH is still a base class of RenderViewHost, and child
4172 // frame RWHVs are unique in that they do not have their own WebContents.
4173 if (!for_main_frame_navigation
) {
4174 RenderWidgetHostViewChildFrame
* rwh_view_child
=
4175 new RenderWidgetHostViewChildFrame(render_view_host
);
4176 rwh_view
= rwh_view_child
;
4178 rwh_view
= view_
->CreateViewForWidget(render_view_host
, false);
4181 // Now that the RenderView has been created, we need to tell it its size.
4183 rwh_view
->SetSize(GetSizeForNewRenderView());
4185 // Make sure we use the correct starting page_id in the new RenderView.
4186 UpdateMaxPageIDIfNecessary(render_view_host
);
4188 GetMaxPageIDForSiteInstance(render_view_host
->GetSiteInstance());
4190 if (!static_cast<RenderViewHostImpl
*>(
4191 render_view_host
)->CreateRenderView(base::string16(),
4195 created_with_opener_
)) {
4199 SetHistoryOffsetAndLengthForView(render_view_host
,
4200 controller_
.GetLastCommittedEntryIndex(),
4201 controller_
.GetEntryCount());
4203 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
4204 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
4205 // linux. See crbug.com/83941.
4207 if (RenderWidgetHost
* render_widget_host
= rwh_view
->GetRenderWidgetHost())
4208 render_widget_host
->WasResized();
4215 bool WebContentsImpl::CreateRenderFrameForRenderManager(
4216 RenderFrameHost
* render_frame_host
,
4217 int parent_routing_id
,
4218 int proxy_routing_id
) {
4219 TRACE_EVENT0("browser,navigation",
4220 "WebContentsImpl::CreateRenderFrameForRenderManager");
4222 RenderFrameHostImpl
* rfh
=
4223 static_cast<RenderFrameHostImpl
*>(render_frame_host
);
4224 if (!rfh
->CreateRenderFrame(parent_routing_id
, proxy_routing_id
))
4227 // TODO(nasko): When RenderWidgetHost is owned by RenderFrameHost, the passed
4228 // RenderFrameHost will have to be associated with the appropriate
4229 // RenderWidgetHostView or a new one should be created here.
4234 #if defined(OS_ANDROID)
4236 base::android::ScopedJavaLocalRef
<jobject
>
4237 WebContentsImpl::GetJavaWebContents() {
4238 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
4239 return GetWebContentsAndroid()->GetJavaObject();
4242 WebContentsAndroid
* WebContentsImpl::GetWebContentsAndroid() {
4243 WebContentsAndroid
* web_contents_android
=
4244 static_cast<WebContentsAndroid
*>(GetUserData(kWebContentsAndroidKey
));
4245 if (!web_contents_android
) {
4246 web_contents_android
= new WebContentsAndroid(this);
4247 SetUserData(kWebContentsAndroidKey
, web_contents_android
);
4249 return web_contents_android
;
4252 bool WebContentsImpl::CreateRenderViewForInitialEmptyDocument() {
4253 return CreateRenderViewForRenderManager(GetRenderViewHost(),
4259 #elif defined(OS_MACOSX)
4261 void WebContentsImpl::SetAllowOtherViews(bool allow
) {
4262 view_
->SetAllowOtherViews(allow
);
4265 bool WebContentsImpl::GetAllowOtherViews() {
4266 return view_
->GetAllowOtherViews();
4271 void WebContentsImpl::OnDialogClosed(int render_process_id
,
4272 int render_frame_id
,
4273 IPC::Message
* reply_msg
,
4274 bool dialog_was_suppressed
,
4276 const base::string16
& user_input
) {
4277 RenderFrameHostImpl
* rfh
= RenderFrameHostImpl::FromID(render_process_id
,
4279 last_dialog_suppressed_
= dialog_was_suppressed
;
4281 if (is_showing_before_unload_dialog_
&& !success
) {
4282 // If a beforeunload dialog is canceled, we need to stop the throbber from
4283 // spinning, since we forced it to start spinning in Navigate.
4286 controller_
.DiscardNonCommittedEntries();
4288 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
4289 BeforeUnloadDialogCancelled());
4292 is_showing_before_unload_dialog_
= false;
4294 rfh
->JavaScriptDialogClosed(reply_msg
, success
, user_input
,
4295 dialog_was_suppressed
);
4297 // Don't leak the sync IPC reply if the RFH or process is gone.
4302 void WebContentsImpl::SetEncoding(const std::string
& encoding
) {
4303 if (encoding
== last_reported_encoding_
)
4305 last_reported_encoding_
= encoding
;
4307 canonical_encoding_
= GetContentClient()->browser()->
4308 GetCanonicalEncodingNameByAliasName(encoding
);
4311 bool WebContentsImpl::IsHidden() {
4312 return capturer_count_
== 0 && !should_normally_be_visible_
;
4315 RenderFrameHostManager
* WebContentsImpl::GetRenderManager() const {
4316 return frame_tree_
.root()->render_manager();
4319 BrowserPluginGuest
* WebContentsImpl::GetBrowserPluginGuest() const {
4320 return browser_plugin_guest_
.get();
4323 void WebContentsImpl::SetBrowserPluginGuest(BrowserPluginGuest
* guest
) {
4324 CHECK(!browser_plugin_guest_
);
4325 browser_plugin_guest_
.reset(guest
);
4328 BrowserPluginEmbedder
* WebContentsImpl::GetBrowserPluginEmbedder() const {
4329 return browser_plugin_embedder_
.get();
4332 void WebContentsImpl::CreateBrowserPluginEmbedderIfNecessary() {
4333 if (browser_plugin_embedder_
)
4335 browser_plugin_embedder_
.reset(BrowserPluginEmbedder::Create(this));
4338 void WebContentsImpl::ClearPowerSaveBlockers(
4339 RenderFrameHost
* render_frame_host
) {
4340 RemoveAllMediaPlayerEntries(render_frame_host
, &active_audio_players_
);
4341 RemoveAllMediaPlayerEntries(render_frame_host
, &active_video_players_
);
4342 MaybeReleasePowerSaveBlockers();
4345 void WebContentsImpl::ClearAllPowerSaveBlockers() {
4346 active_audio_players_
.clear();
4347 active_video_players_
.clear();
4348 audio_power_save_blocker_
.reset();
4349 video_power_save_blocker_
.reset();
4352 gfx::Size
WebContentsImpl::GetSizeForNewRenderView() {
4355 size
= delegate_
->GetSizeForNewRenderView(this);
4357 size
= GetContainerBounds().size();
4361 void WebContentsImpl::OnFrameRemoved(RenderFrameHost
* render_frame_host
) {
4363 WebContentsObserver
, observers_
, FrameDeleted(render_frame_host
));
4366 void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size
& old_size
) {
4369 const gfx::Size new_size
= GetPreferredSize();
4370 if (new_size
!= old_size
)
4371 delegate_
->UpdatePreferredSize(this, new_size
);
4374 void WebContentsImpl::AddMediaPlayerEntry(int64 player_cookie
,
4375 ActiveMediaPlayerMap
* player_map
) {
4376 if (!HasValidFrameSource())
4379 const uintptr_t key
=
4380 reinterpret_cast<uintptr_t>(render_frame_message_source_
);
4381 DCHECK(std::find((*player_map
)[key
].begin(),
4382 (*player_map
)[key
].end(),
4383 player_cookie
) == (*player_map
)[key
].end());
4384 (*player_map
)[key
].push_back(player_cookie
);
4387 void WebContentsImpl::RemoveMediaPlayerEntry(int64 player_cookie
,
4388 ActiveMediaPlayerMap
* player_map
) {
4389 if (!HasValidFrameSource())
4392 const uintptr_t key
=
4393 reinterpret_cast<uintptr_t>(render_frame_message_source_
);
4394 ActiveMediaPlayerMap::iterator it
= player_map
->find(key
);
4395 if (it
== player_map
->end())
4398 // Remove the player.
4399 PlayerList::iterator player_it
=
4400 std::find(it
->second
.begin(), it
->second
.end(), player_cookie
);
4401 if (player_it
!= it
->second
.end())
4402 it
->second
.erase(player_it
);
4404 // If there are no players left, remove the map entry.
4405 if (it
->second
.empty())
4406 player_map
->erase(it
);
4409 void WebContentsImpl::RemoveAllMediaPlayerEntries(
4410 RenderFrameHost
* render_frame_host
,
4411 ActiveMediaPlayerMap
* player_map
) {
4412 ActiveMediaPlayerMap::iterator it
=
4413 player_map
->find(reinterpret_cast<uintptr_t>(render_frame_host
));
4414 if (it
== player_map
->end())
4416 player_map
->erase(it
);
4419 void WebContentsImpl::ResumeResponseDeferredAtStart() {
4420 FrameTreeNode
* node
= frame_tree_
.root();
4421 node
->render_manager()->ResumeResponseDeferredAtStart();
4424 void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable
) {
4425 force_disable_overscroll_content_
= force_disable
;
4427 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
4430 } // namespace content