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/debug/trace_event.h"
11 #include "base/lazy_instance.h"
12 #include "base/logging.h"
13 #include "base/metrics/histogram.h"
14 #include "base/metrics/stats_counters.h"
15 #include "base/process/process.h"
16 #include "base/strings/string16.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/time/time.h"
21 #include "content/browser/accessibility/accessibility_mode_helper.h"
22 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
23 #include "content/browser/browser_plugin/browser_plugin_embedder.h"
24 #include "content/browser/browser_plugin/browser_plugin_guest.h"
25 #include "content/browser/child_process_security_policy_impl.h"
26 #include "content/browser/devtools/devtools_manager.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/message_port_service.h"
46 #include "content/browser/plugin_content_origin_whitelist.h"
47 #include "content/browser/power_save_blocker_impl.h"
48 #include "content/browser/renderer_host/render_process_host_impl.h"
49 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
50 #include "content/browser/renderer_host/render_view_host_impl.h"
51 #include "content/browser/renderer_host/render_widget_host_impl.h"
52 #include "content/browser/renderer_host/render_widget_host_view_base.h"
53 #include "content/browser/screen_orientation/screen_orientation_dispatcher_host_impl.h"
54 #include "content/browser/site_instance_impl.h"
55 #include "content/browser/web_contents/web_contents_view_guest.h"
56 #include "content/browser/webui/generic_handler.h"
57 #include "content/browser/webui/web_ui_controller_factory_registry.h"
58 #include "content/browser/webui/web_ui_impl.h"
59 #include "content/common/browser_plugin/browser_plugin_constants.h"
60 #include "content/common/browser_plugin/browser_plugin_messages.h"
61 #include "content/common/frame_messages.h"
62 #include "content/common/image_messages.h"
63 #include "content/common/input_messages.h"
64 #include "content/common/ssl_status_serialization.h"
65 #include "content/common/view_messages.h"
66 #include "content/public/browser/ax_event_notification_details.h"
67 #include "content/public/browser/browser_context.h"
68 #include "content/public/browser/browser_plugin_guest_manager.h"
69 #include "content/public/browser/content_browser_client.h"
70 #include "content/public/browser/devtools_agent_host.h"
71 #include "content/public/browser/download_manager.h"
72 #include "content/public/browser/download_url_parameters.h"
73 #include "content/public/browser/invalidate_type.h"
74 #include "content/public/browser/javascript_dialog_manager.h"
75 #include "content/public/browser/load_from_memory_cache_details.h"
76 #include "content/public/browser/load_notification_details.h"
77 #include "content/public/browser/navigation_details.h"
78 #include "content/public/browser/notification_details.h"
79 #include "content/public/browser/notification_service.h"
80 #include "content/public/browser/render_widget_host_iterator.h"
81 #include "content/public/browser/resource_request_details.h"
82 #include "content/public/browser/screen_orientation_dispatcher_host.h"
83 #include "content/public/browser/storage_partition.h"
84 #include "content/public/browser/user_metrics.h"
85 #include "content/public/browser/web_contents_delegate.h"
86 #include "content/public/browser/web_contents_observer.h"
87 #include "content/public/common/bindings_policy.h"
88 #include "content/public/common/content_constants.h"
89 #include "content/public/common/content_switches.h"
90 #include "content/public/common/page_zoom.h"
91 #include "content/public/common/result_codes.h"
92 #include "content/public/common/url_constants.h"
93 #include "content/public/common/url_utils.h"
94 #include "content/public/common/web_preferences.h"
95 #include "net/base/mime_util.h"
96 #include "net/base/net_util.h"
97 #include "net/http/http_cache.h"
98 #include "net/http/http_transaction_factory.h"
99 #include "net/url_request/url_request_context.h"
100 #include "net/url_request/url_request_context_getter.h"
101 #include "ui/base/layout.h"
102 #include "ui/gfx/display.h"
103 #include "ui/gfx/screen.h"
104 #include "ui/gl/gl_switches.h"
106 #if defined(ENABLE_BROWSER_CDMS)
107 #include "content/browser/media/media_web_contents_observer.h"
110 #if defined(OS_ANDROID)
111 #include "content/browser/android/date_time_chooser_android.h"
112 #include "content/browser/media/android/browser_media_player_manager.h"
113 #include "content/browser/web_contents/web_contents_android.h"
116 #if defined(OS_MACOSX)
117 #include "base/mac/foundation_util.h"
123 const int kMinimumDelayBetweenLoadingUpdatesMS
= 100;
125 // This matches what Blink's ProgressTracker has traditionally used for a
126 // minimum progress value.
127 const double kMinimumLoadingProgress
= 0.1;
129 const char kDotGoogleDotCom
[] = ".google.com";
131 #if defined(OS_ANDROID)
132 const char kWebContentsAndroidKey
[] = "web_contents_android";
135 base::LazyInstance
<std::vector
<WebContentsImpl::CreatedCallback
> >
136 g_created_callbacks
= LAZY_INSTANCE_INITIALIZER
;
138 static int StartDownload(RenderFrameHost
* rfh
,
141 uint32_t max_bitmap_size
) {
142 static int g_next_image_download_id
= 0;
143 rfh
->Send(new ImageMsg_DownloadImage(rfh
->GetRoutingID(),
144 ++g_next_image_download_id
,
148 return g_next_image_download_id
;
151 void NotifyCacheOnIO(
152 scoped_refptr
<net::URLRequestContextGetter
> request_context
,
154 const std::string
& http_method
) {
155 request_context
->GetURLRequestContext()->http_transaction_factory()->
156 GetCache()->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()),
312 loading_total_progress_(0.0),
313 loading_frames_in_progress_(0),
316 displayed_insecure_content_(false),
317 has_accessed_initial_document_(false),
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 totalPinchGestureAmount_(0),
329 currentPinchZoomStepDelta_(0),
330 render_view_message_source_(NULL
),
331 fullscreen_widget_routing_id_(MSG_ROUTING_NONE
),
332 fullscreen_widget_had_focus_at_shutdown_(false),
334 force_disable_overscroll_content_(false),
335 last_dialog_suppressed_(false),
336 geolocation_service_context_(new GeolocationServiceContext()),
338 BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()),
339 audio_stream_monitor_(this),
340 virtual_keyboard_requested_(false),
341 loading_weak_factory_(this) {
342 frame_tree_
.SetFrameRemoveListener(
343 base::Bind(&WebContentsImpl::OnFrameRemoved
,
344 base::Unretained(this)));
345 #if defined(ENABLE_BROWSER_CDMS)
346 media_web_contents_observer_
.reset(new MediaWebContentsObserver(this));
350 WebContentsImpl::~WebContentsImpl() {
351 is_being_destroyed_
= true;
353 // Delete all RFH pending shutdown, which will lead the corresponding RVH to
354 // shutdown and be deleted as well.
356 base::Bind(&RenderFrameHostManager::ClearRFHsPendingShutdown
));
358 ClearAllPowerSaveBlockers();
360 for (std::set
<RenderWidgetHostImpl
*>::iterator iter
=
361 created_widgets_
.begin(); iter
!= created_widgets_
.end(); ++iter
) {
362 (*iter
)->DetachDelegate();
364 created_widgets_
.clear();
366 // Clear out any JavaScript state.
368 dialog_manager_
->WebContentsDestroyed(this);
370 if (color_chooser_info_
.get())
371 color_chooser_info_
->chooser
->End();
373 NotifyDisconnected();
375 // Notify any observer that have a reference on this WebContents.
376 NotificationService::current()->Notify(
377 NOTIFICATION_WEB_CONTENTS_DESTROYED
,
378 Source
<WebContents
>(this),
379 NotificationService::NoDetails());
381 // Destroy all frame tree nodes except for the root; this notifies observers.
382 frame_tree_
.ResetForMainFrameSwap();
383 GetRenderManager()->ResetProxyHosts();
385 // Manually call the observer methods for the root frame tree node.
386 RenderFrameHostManager
* root
= GetRenderManager();
387 if (root
->pending_frame_host()) {
388 FOR_EACH_OBSERVER(WebContentsObserver
,
390 RenderFrameDeleted(root
->pending_frame_host()));
392 FOR_EACH_OBSERVER(WebContentsObserver
,
394 RenderFrameDeleted(root
->current_frame_host()));
396 if (root
->pending_render_view_host()) {
397 FOR_EACH_OBSERVER(WebContentsObserver
,
399 RenderViewDeleted(root
->pending_render_view_host()));
402 FOR_EACH_OBSERVER(WebContentsObserver
,
404 RenderViewDeleted(root
->current_host()));
406 FOR_EACH_OBSERVER(WebContentsObserver
,
408 WebContentsDestroyed());
410 FOR_EACH_OBSERVER(WebContentsObserver
,
416 STLDeleteContainerPairSecondPointers(destruction_observers_
.begin(),
417 destruction_observers_
.end());
420 WebContentsImpl
* WebContentsImpl::CreateWithOpener(
421 const WebContents::CreateParams
& params
,
422 WebContentsImpl
* opener
) {
423 TRACE_EVENT0("browser", "WebContentsImpl::CreateWithOpener");
424 WebContentsImpl
* new_contents
= new WebContentsImpl(
425 params
.browser_context
, params
.opener_suppressed
? NULL
: opener
);
427 if (params
.guest_delegate
) {
428 // This makes |new_contents| act as a guest.
429 // For more info, see comment above class BrowserPluginGuest.
430 BrowserPluginGuest::Create(new_contents
, params
.guest_delegate
);
431 // We are instantiating a WebContents for browser plugin. Set its subframe
433 new_contents
->is_subframe_
= true;
435 new_contents
->Init(params
);
440 std::vector
<WebContentsImpl
*> WebContentsImpl::GetAllWebContents() {
441 std::vector
<WebContentsImpl
*> result
;
442 scoped_ptr
<RenderWidgetHostIterator
> widgets(
443 RenderWidgetHostImpl::GetRenderWidgetHosts());
444 std::set
<WebContentsImpl
*> web_contents_set
;
445 while (RenderWidgetHost
* rwh
= widgets
->GetNextHost()) {
446 if (!rwh
->IsRenderView())
448 RenderViewHost
* rvh
= RenderViewHost::From(rwh
);
451 WebContents
* web_contents
= WebContents::FromRenderViewHost(rvh
);
454 WebContentsImpl
* wci
= static_cast<WebContentsImpl
*>(web_contents
);
455 if (web_contents_set
.find(wci
) == web_contents_set
.end()) {
456 web_contents_set
.insert(wci
);
457 result
.push_back(wci
);
463 RenderFrameHostManager
* WebContentsImpl::GetRenderManagerForTesting() {
464 return GetRenderManager();
467 bool WebContentsImpl::OnMessageReceived(RenderViewHost
* render_view_host
,
468 const IPC::Message
& message
) {
469 return OnMessageReceived(render_view_host
, NULL
, message
);
472 bool WebContentsImpl::OnMessageReceived(RenderViewHost
* render_view_host
,
473 RenderFrameHost
* render_frame_host
,
474 const IPC::Message
& message
) {
475 DCHECK(render_view_host
|| render_frame_host
);
477 static_cast<WebUIImpl
*>(GetWebUI())->OnMessageReceived(message
)) {
481 ObserverListBase
<WebContentsObserver
>::Iterator
it(observers_
);
482 WebContentsObserver
* observer
;
483 if (render_frame_host
) {
484 while ((observer
= it
.GetNext()) != NULL
)
485 if (observer
->OnMessageReceived(message
, render_frame_host
))
488 while ((observer
= it
.GetNext()) != NULL
)
489 if (observer
->OnMessageReceived(message
))
493 // Message handlers should be aware of which
494 // RenderViewHost/RenderFrameHost sent the message, which is temporarily
495 // stored in render_(view|frame)_message_source_.
496 if (render_frame_host
)
497 render_frame_message_source_
= render_frame_host
;
499 render_view_message_source_
= render_view_host
;
502 IPC_BEGIN_MESSAGE_MAP(WebContentsImpl
, message
)
503 IPC_MESSAGE_HANDLER(FrameHostMsg_DomOperationResponse
,
504 OnDomOperationResponse
)
505 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeThemeColor
,
507 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishDocumentLoad
,
508 OnDocumentLoadedInFrame
)
509 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishLoad
, OnDidFinishLoad
)
510 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartLoading
, OnDidStartLoading
)
511 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading
, OnDidStopLoading
)
512 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress
,
513 OnDidChangeLoadProgress
)
514 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenColorChooser
, OnOpenColorChooser
)
515 IPC_MESSAGE_HANDLER(FrameHostMsg_EndColorChooser
, OnEndColorChooser
)
516 IPC_MESSAGE_HANDLER(FrameHostMsg_SetSelectedColorInColorChooser
,
517 OnSetSelectedColorInColorChooser
)
518 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPlayingNotification
,
519 OnMediaPlayingNotification
)
520 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPausedNotification
,
521 OnMediaPausedNotification
)
522 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFirstVisuallyNonEmptyPaint
,
523 OnFirstVisuallyNonEmptyPaint
)
524 IPC_MESSAGE_HANDLER(ViewHostMsg_DidLoadResourceFromMemoryCache
,
525 OnDidLoadResourceFromMemoryCache
)
526 IPC_MESSAGE_HANDLER(ViewHostMsg_DidDisplayInsecureContent
,
527 OnDidDisplayInsecureContent
)
528 IPC_MESSAGE_HANDLER(ViewHostMsg_DidRunInsecureContent
,
529 OnDidRunInsecureContent
)
530 IPC_MESSAGE_HANDLER(ViewHostMsg_GoToEntryAtOffset
, OnGoToEntryAtOffset
)
531 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateZoomLimits
, OnUpdateZoomLimits
)
532 IPC_MESSAGE_HANDLER(ViewHostMsg_EnumerateDirectory
, OnEnumerateDirectory
)
533 IPC_MESSAGE_HANDLER(ViewHostMsg_RegisterProtocolHandler
,
534 OnRegisterProtocolHandler
)
535 IPC_MESSAGE_HANDLER(ViewHostMsg_UnregisterProtocolHandler
,
536 OnUnregisterProtocolHandler
)
537 IPC_MESSAGE_HANDLER(ViewHostMsg_Find_Reply
, OnFindReply
)
538 IPC_MESSAGE_HANDLER(ViewHostMsg_AppCacheAccessed
, OnAppCacheAccessed
)
539 IPC_MESSAGE_HANDLER(ViewHostMsg_WebUISend
, OnWebUISend
)
540 #if defined(ENABLE_PLUGINS)
541 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung
, OnPepperPluginHung
)
542 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed
, OnPluginCrashed
)
543 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission
,
544 OnRequestPpapiBrokerPermission
)
545 IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_Attach
,
546 OnBrowserPluginMessage(message
))
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 void WebContentsImpl::RunFileChooser(
571 RenderViewHost
* render_view_host
,
572 const FileChooserParams
& params
) {
574 delegate_
->RunFileChooser(this, params
);
577 NavigationControllerImpl
& WebContentsImpl::GetController() {
581 const NavigationControllerImpl
& WebContentsImpl::GetController() const {
585 BrowserContext
* WebContentsImpl::GetBrowserContext() const {
586 return controller_
.GetBrowserContext();
589 const GURL
& WebContentsImpl::GetURL() const {
590 // We may not have a navigation entry yet.
591 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
592 return entry
? entry
->GetVirtualURL() : GURL::EmptyGURL();
595 const GURL
& WebContentsImpl::GetVisibleURL() const {
596 // We may not have a navigation entry yet.
597 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
598 return entry
? entry
->GetVirtualURL() : GURL::EmptyGURL();
601 const GURL
& WebContentsImpl::GetLastCommittedURL() const {
602 // We may not have a navigation entry yet.
603 NavigationEntry
* entry
= controller_
.GetLastCommittedEntry();
604 return entry
? entry
->GetVirtualURL() : GURL::EmptyGURL();
607 WebContentsDelegate
* WebContentsImpl::GetDelegate() {
611 void WebContentsImpl::SetDelegate(WebContentsDelegate
* delegate
) {
612 // TODO(cbentzel): remove this debugging code?
613 if (delegate
== delegate_
)
616 delegate_
->Detach(this);
617 delegate_
= delegate
;
619 delegate_
->Attach(this);
620 // Ensure the visible RVH reflects the new delegate's preferences.
622 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
626 RenderProcessHost
* WebContentsImpl::GetRenderProcessHost() const {
627 RenderViewHostImpl
* host
= GetRenderManager()->current_host();
628 return host
? host
->GetProcess() : NULL
;
631 RenderFrameHost
* WebContentsImpl::GetMainFrame() {
632 return frame_tree_
.root()->current_frame_host();
635 RenderFrameHost
* WebContentsImpl::GetFocusedFrame() {
636 if (!frame_tree_
.GetFocusedFrame())
638 return frame_tree_
.GetFocusedFrame()->current_frame_host();
641 void WebContentsImpl::ForEachFrame(
642 const base::Callback
<void(RenderFrameHost
*)>& on_frame
) {
643 frame_tree_
.ForEach(base::Bind(&ForEachFrameInternal
, on_frame
));
646 void WebContentsImpl::SendToAllFrames(IPC::Message
* message
) {
647 ForEachFrame(base::Bind(&SendToAllFramesInternal
, message
));
651 RenderViewHost
* WebContentsImpl::GetRenderViewHost() const {
652 return GetRenderManager()->current_host();
655 int WebContentsImpl::GetRoutingID() const {
656 if (!GetRenderViewHost())
657 return MSG_ROUTING_NONE
;
659 return GetRenderViewHost()->GetRoutingID();
662 int WebContentsImpl::GetFullscreenWidgetRoutingID() const {
663 return fullscreen_widget_routing_id_
;
666 RenderWidgetHostView
* WebContentsImpl::GetRenderWidgetHostView() const {
667 return GetRenderManager()->GetRenderWidgetHostView();
670 RenderWidgetHostView
* WebContentsImpl::GetFullscreenRenderWidgetHostView()
672 RenderWidgetHost
* const widget_host
=
673 RenderWidgetHostImpl::FromID(GetRenderProcessHost()->GetID(),
674 GetFullscreenWidgetRoutingID());
675 return widget_host
? widget_host
->GetView() : NULL
;
678 WebContentsView
* WebContentsImpl::GetView() const {
682 void WebContentsImpl::SetAccessibilityMode(AccessibilityMode mode
) {
683 if (mode
== accessibility_mode_
)
686 accessibility_mode_
= mode
;
688 base::Bind(&ForEachFrameInternal
,
689 base::Bind(&SetAccessibilityModeOnFrame
, mode
)));
691 base::Bind(&ForEachPendingFrameInternal
,
692 base::Bind(&SetAccessibilityModeOnFrame
, mode
)));
695 void WebContentsImpl::AddAccessibilityMode(AccessibilityMode mode
) {
696 SetAccessibilityMode(AddAccessibilityModeTo(accessibility_mode_
, mode
));
699 void WebContentsImpl::RemoveAccessibilityMode(AccessibilityMode mode
) {
700 SetAccessibilityMode(RemoveAccessibilityModeFrom(accessibility_mode_
, mode
));
703 void WebContentsImpl::ClearNavigationTransitionData() {
704 FrameTreeNode
* node
= frame_tree_
.root();
705 node
->render_manager()->ClearNavigationTransitionData();
708 WebUI
* WebContentsImpl::CreateWebUI(const GURL
& url
) {
709 WebUIImpl
* web_ui
= new WebUIImpl(this);
710 WebUIController
* controller
= WebUIControllerFactoryRegistry::GetInstance()->
711 CreateWebUIControllerForURL(web_ui
, url
);
713 web_ui
->AddMessageHandler(new GenericHandler());
714 web_ui
->SetController(controller
);
722 WebUI
* WebContentsImpl::GetWebUI() const {
723 return GetRenderManager()->web_ui() ? GetRenderManager()->web_ui()
724 : GetRenderManager()->pending_web_ui();
727 WebUI
* WebContentsImpl::GetCommittedWebUI() const {
728 return GetRenderManager()->web_ui();
731 void WebContentsImpl::SetUserAgentOverride(const std::string
& override
) {
732 if (GetUserAgentOverride() == override
)
735 renderer_preferences_
.user_agent_override
= override
;
737 // Send the new override string to the renderer.
738 RenderViewHost
* host
= GetRenderViewHost();
740 host
->SyncRendererPrefs();
742 // Reload the page if a load is currently in progress to avoid having
743 // different parts of the page loaded using different user agents.
744 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
745 if (is_loading_
&& entry
!= NULL
&& entry
->GetIsOverridingUserAgent())
746 controller_
.ReloadIgnoringCache(true);
748 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
749 UserAgentOverrideSet(override
));
752 const std::string
& WebContentsImpl::GetUserAgentOverride() const {
753 return renderer_preferences_
.user_agent_override
;
756 void WebContentsImpl::EnableTreeOnlyAccessibilityMode() {
757 AddAccessibilityMode(AccessibilityModeTreeOnly
);
760 bool WebContentsImpl::IsTreeOnlyAccessibilityModeForTesting() const {
761 return accessibility_mode_
== AccessibilityModeTreeOnly
;
764 bool WebContentsImpl::IsFullAccessibilityModeForTesting() const {
765 return accessibility_mode_
== AccessibilityModeComplete
;
769 void WebContentsImpl::SetParentNativeViewAccessible(
770 gfx::NativeViewAccessible accessible_parent
) {
771 accessible_parent_
= accessible_parent
;
772 RenderFrameHostImpl
* rfh
= static_cast<RenderFrameHostImpl
*>(GetMainFrame());
774 rfh
->SetParentNativeViewAccessible(accessible_parent
);
778 const base::string16
& WebContentsImpl::GetTitle() const {
779 // Transient entries take precedence. They are used for interstitial pages
780 // that are shown on top of existing pages.
781 NavigationEntry
* entry
= controller_
.GetTransientEntry();
782 std::string accept_languages
=
783 GetContentClient()->browser()->GetAcceptLangs(
784 GetBrowserContext());
786 return entry
->GetTitleForDisplay(accept_languages
);
788 WebUI
* our_web_ui
= GetRenderManager()->pending_web_ui() ?
789 GetRenderManager()->pending_web_ui() : GetRenderManager()->web_ui();
791 // Don't override the title in view source mode.
792 entry
= controller_
.GetVisibleEntry();
793 if (!(entry
&& entry
->IsViewSourceMode())) {
794 // Give the Web UI the chance to override our title.
795 const base::string16
& title
= our_web_ui
->GetOverriddenTitle();
801 // We use the title for the last committed entry rather than a pending
802 // navigation entry. For example, when the user types in a URL, we want to
803 // keep the old page's title until the new load has committed and we get a new
805 entry
= controller_
.GetLastCommittedEntry();
807 // We make an exception for initial navigations.
808 if (controller_
.IsInitialNavigation()) {
809 // We only want to use the title from the visible entry in one of two cases:
810 // 1. There's already a committed entry for an initial navigation, in which
811 // case we are doing a history navigation in a new tab (e.g., Ctrl+Back).
812 // 2. The pending entry has been explicitly assigned a title to display.
814 // If there's no last committed entry and no assigned title, we should fall
815 // back to |page_title_when_no_navigation_entry_| rather than showing the
818 (controller_
.GetVisibleEntry() &&
819 !controller_
.GetVisibleEntry()->GetTitle().empty())) {
820 entry
= controller_
.GetVisibleEntry();
825 return entry
->GetTitleForDisplay(accept_languages
);
828 // |page_title_when_no_navigation_entry_| is finally used
829 // if no title cannot be retrieved.
830 return page_title_when_no_navigation_entry_
;
833 int32
WebContentsImpl::GetMaxPageID() {
834 return GetMaxPageIDForSiteInstance(GetSiteInstance());
837 int32
WebContentsImpl::GetMaxPageIDForSiteInstance(
838 SiteInstance
* site_instance
) {
839 if (max_page_ids_
.find(site_instance
->GetId()) == max_page_ids_
.end())
840 max_page_ids_
[site_instance
->GetId()] = -1;
842 return max_page_ids_
[site_instance
->GetId()];
845 void WebContentsImpl::UpdateMaxPageID(int32 page_id
) {
846 UpdateMaxPageIDForSiteInstance(GetSiteInstance(), page_id
);
849 void WebContentsImpl::UpdateMaxPageIDForSiteInstance(
850 SiteInstance
* site_instance
, int32 page_id
) {
851 if (GetMaxPageIDForSiteInstance(site_instance
) < page_id
)
852 max_page_ids_
[site_instance
->GetId()] = page_id
;
855 void WebContentsImpl::CopyMaxPageIDsFrom(WebContents
* web_contents
) {
856 WebContentsImpl
* contents
= static_cast<WebContentsImpl
*>(web_contents
);
857 max_page_ids_
= contents
->max_page_ids_
;
860 SiteInstanceImpl
* WebContentsImpl::GetSiteInstance() const {
861 return GetRenderManager()->current_host()->GetSiteInstance();
864 SiteInstanceImpl
* WebContentsImpl::GetPendingSiteInstance() const {
865 RenderViewHostImpl
* dest_rvh
=
866 GetRenderManager()->pending_render_view_host() ?
867 GetRenderManager()->pending_render_view_host() :
868 GetRenderManager()->current_host();
869 return dest_rvh
->GetSiteInstance();
872 bool WebContentsImpl::IsLoading() const {
876 bool WebContentsImpl::IsLoadingToDifferentDocument() const {
877 return is_loading_
&& is_load_to_different_document_
;
880 bool WebContentsImpl::IsWaitingForResponse() const {
881 return waiting_for_response_
&& is_load_to_different_document_
;
884 const net::LoadStateWithParam
& WebContentsImpl::GetLoadState() const {
888 const base::string16
& WebContentsImpl::GetLoadStateHost() const {
889 return load_state_host_
;
892 uint64
WebContentsImpl::GetUploadSize() const {
896 uint64
WebContentsImpl::GetUploadPosition() const {
897 return upload_position_
;
900 std::set
<GURL
> WebContentsImpl::GetSitesInTab() const {
901 std::set
<GURL
> sites
;
902 frame_tree_
.ForEach(base::Bind(&CollectSites
,
903 base::Unretained(GetBrowserContext()),
904 base::Unretained(&sites
)));
908 const std::string
& WebContentsImpl::GetEncoding() const {
909 return canonical_encoding_
;
912 bool WebContentsImpl::DisplayedInsecureContent() const {
913 return displayed_insecure_content_
;
916 void WebContentsImpl::IncrementCapturerCount(const gfx::Size
& capture_size
) {
917 DCHECK(!is_being_destroyed_
);
919 DVLOG(1) << "There are now " << capturer_count_
920 << " capturing(s) of WebContentsImpl@" << this;
922 // Note: This provides a hint to upstream code to size the views optimally
923 // for quality (e.g., to avoid scaling).
924 if (!capture_size
.IsEmpty() && preferred_size_for_capture_
.IsEmpty()) {
925 preferred_size_for_capture_
= capture_size
;
926 OnPreferredSizeChanged(preferred_size_
);
929 // Ensure that all views are un-occluded before capture begins.
933 void WebContentsImpl::DecrementCapturerCount() {
935 DVLOG(1) << "There are now " << capturer_count_
936 << " capturing(s) of WebContentsImpl@" << this;
937 DCHECK_LE(0, capturer_count_
);
939 if (is_being_destroyed_
)
942 if (capturer_count_
== 0) {
943 const gfx::Size old_size
= preferred_size_for_capture_
;
944 preferred_size_for_capture_
= gfx::Size();
945 OnPreferredSizeChanged(old_size
);
949 DVLOG(1) << "Executing delayed WasHidden().";
954 int WebContentsImpl::GetCapturerCount() const {
955 return capturer_count_
;
958 bool WebContentsImpl::IsAudioMuted() const {
959 return audio_muter_
.get() && audio_muter_
->is_muting();
962 void WebContentsImpl::SetAudioMuted(bool mute
) {
963 DVLOG(1) << "SetAudioMuted(mute=" << mute
<< "), was " << IsAudioMuted()
964 << " for WebContentsImpl@" << this;
966 if (mute
== IsAudioMuted())
971 audio_muter_
.reset(new WebContentsAudioMuter(this));
972 audio_muter_
->StartMuting();
974 DCHECK(audio_muter_
);
975 audio_muter_
->StopMuting();
978 // Notification for UI updates in response to the changed muting state.
979 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB
);
982 bool WebContentsImpl::IsCrashed() const {
983 return (crashed_status_
== base::TERMINATION_STATUS_PROCESS_CRASHED
||
984 crashed_status_
== base::TERMINATION_STATUS_ABNORMAL_TERMINATION
||
985 crashed_status_
== base::TERMINATION_STATUS_PROCESS_WAS_KILLED
);
988 void WebContentsImpl::SetIsCrashed(base::TerminationStatus status
,
990 if (status
== crashed_status_
)
993 crashed_status_
= status
;
994 crashed_error_code_
= error_code
;
995 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB
);
998 base::TerminationStatus
WebContentsImpl::GetCrashedStatus() const {
999 return crashed_status_
;
1002 bool WebContentsImpl::IsBeingDestroyed() const {
1003 return is_being_destroyed_
;
1006 void WebContentsImpl::NotifyNavigationStateChanged(
1007 InvalidateTypes changed_flags
) {
1008 // Create and release the audio power save blocker depending on whether the
1009 // tab is actively producing audio or not.
1010 if ((changed_flags
& INVALIDATE_TYPE_TAB
) &&
1011 AudioStreamMonitor::monitoring_available()) {
1012 if (WasRecentlyAudible()) {
1013 if (!audio_power_save_blocker_
)
1014 CreateAudioPowerSaveBlocker();
1016 audio_power_save_blocker_
.reset();
1021 delegate_
->NavigationStateChanged(this, changed_flags
);
1024 base::TimeTicks
WebContentsImpl::GetLastActiveTime() const {
1025 return last_active_time_
;
1028 void WebContentsImpl::WasShown() {
1029 controller_
.SetActive(true);
1031 for (RenderWidgetHostView
* view
: GetRenderWidgetHostViewsInTree()) {
1034 #if defined(OS_MACOSX)
1035 view
->SetActive(true);
1040 last_active_time_
= base::TimeTicks::Now();
1042 // The resize rect might have changed while this was inactive -- send the new
1043 // one to make sure it's up to date.
1044 RenderViewHostImpl
* rvh
=
1045 static_cast<RenderViewHostImpl
*>(GetRenderViewHost());
1047 rvh
->ResizeRectChanged(GetRootWindowResizerRect());
1050 // Restore power save blocker if there are active video players running.
1051 if (!active_video_players_
.empty() && !video_power_save_blocker_
)
1052 CreateVideoPowerSaveBlocker();
1054 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, WasShown());
1056 should_normally_be_visible_
= true;
1059 void WebContentsImpl::WasHidden() {
1060 // If there are entities capturing screenshots or video (e.g., mirroring),
1061 // don't activate the "disable rendering" optimization.
1062 if (capturer_count_
== 0) {
1063 // |GetRenderViewHost()| can be NULL if the user middle clicks a link to
1064 // open a tab in the background, then closes the tab before selecting it.
1065 // This is because closing the tab calls WebContentsImpl::Destroy(), which
1066 // removes the |GetRenderViewHost()|; then when we actually destroy the
1067 // window, OnWindowPosChanged() notices and calls WasHidden() (which
1069 for (RenderWidgetHostView
* view
: GetRenderWidgetHostViewsInTree()) {
1074 // Release any video power save blockers held as video is not visible.
1075 video_power_save_blocker_
.reset();
1078 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, WasHidden());
1080 should_normally_be_visible_
= false;
1083 void WebContentsImpl::WasOccluded() {
1084 if (capturer_count_
> 0)
1087 for (RenderWidgetHostView
* view
: GetRenderWidgetHostViewsInTree()) {
1089 view
->WasOccluded();
1093 void WebContentsImpl::WasUnOccluded() {
1094 for (RenderWidgetHostView
* view
: GetRenderWidgetHostViewsInTree()) {
1096 view
->WasUnOccluded();
1100 bool WebContentsImpl::NeedToFireBeforeUnload() {
1101 // TODO(creis): Should we fire even for interstitial pages?
1102 return WillNotifyDisconnection() &&
1103 !ShowingInterstitialPage() &&
1104 !static_cast<RenderViewHostImpl
*>(
1105 GetRenderViewHost())->SuddenTerminationAllowed();
1108 void WebContentsImpl::DispatchBeforeUnload(bool for_cross_site_transition
) {
1109 static_cast<RenderFrameHostImpl
*>(GetMainFrame())->DispatchBeforeUnload(
1110 for_cross_site_transition
);
1113 void WebContentsImpl::Stop() {
1114 GetRenderManager()->Stop();
1115 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, NavigationStopped());
1118 WebContents
* WebContentsImpl::Clone() {
1119 // We use our current SiteInstance since the cloned entry will use it anyway.
1120 // We pass our own opener so that the cloned page can access it if it was
1122 CreateParams
create_params(GetBrowserContext(), GetSiteInstance());
1123 create_params
.initial_size
= GetContainerBounds().size();
1124 WebContentsImpl
* tc
= CreateWithOpener(create_params
, opener_
);
1125 tc
->GetController().CopyStateFrom(controller_
);
1126 FOR_EACH_OBSERVER(WebContentsObserver
,
1128 DidCloneToNewWebContents(this, tc
));
1132 void WebContentsImpl::Observe(int type
,
1133 const NotificationSource
& source
,
1134 const NotificationDetails
& details
) {
1136 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED
: {
1137 RenderWidgetHost
* host
= Source
<RenderWidgetHost
>(source
).ptr();
1138 RenderWidgetHostView
* view
= host
->GetView();
1139 if (view
== GetFullscreenRenderWidgetHostView()) {
1140 // We cannot just call view_->RestoreFocus() here. On some platforms,
1141 // attempting to focus the currently-invisible WebContentsView will be
1142 // flat-out ignored. Therefore, this boolean is used to track whether
1143 // we will request focus after the fullscreen widget has been
1145 fullscreen_widget_had_focus_at_shutdown_
= (view
&& view
->HasFocus());
1147 for (PendingWidgetViews::iterator i
= pending_widget_views_
.begin();
1148 i
!= pending_widget_views_
.end(); ++i
) {
1149 if (host
->GetView() == i
->second
) {
1150 pending_widget_views_
.erase(i
);
1162 WebContents
* WebContentsImpl::GetWebContents() {
1166 void WebContentsImpl::Init(const WebContents::CreateParams
& params
) {
1167 // This is set before initializing the render manager since
1168 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
1169 // it should be hidden.
1170 should_normally_be_visible_
= !params
.initially_hidden
;
1172 // Either both routing ids can be given, or neither can be.
1173 DCHECK((params
.routing_id
== MSG_ROUTING_NONE
&&
1174 params
.main_frame_routing_id
== MSG_ROUTING_NONE
) ||
1175 (params
.routing_id
!= MSG_ROUTING_NONE
&&
1176 params
.main_frame_routing_id
!= MSG_ROUTING_NONE
));
1177 GetRenderManager()->Init(
1178 params
.browser_context
, params
.site_instance
, params
.routing_id
,
1179 params
.main_frame_routing_id
);
1181 WebContentsViewDelegate
* delegate
=
1182 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
1184 if (browser_plugin_guest_
) {
1185 scoped_ptr
<WebContentsView
> platform_view(CreateWebContentsView(
1186 this, delegate
, &render_view_host_delegate_view_
));
1188 WebContentsViewGuest
* rv
= new WebContentsViewGuest(
1189 this, browser_plugin_guest_
.get(), platform_view
.Pass(),
1190 render_view_host_delegate_view_
);
1191 render_view_host_delegate_view_
= rv
;
1194 // Regular WebContentsView.
1195 view_
.reset(CreateWebContentsView(
1196 this, delegate
, &render_view_host_delegate_view_
));
1198 CHECK(render_view_host_delegate_view_
);
1201 gfx::Size initial_size
= params
.initial_size
;
1202 view_
->CreateView(initial_size
, params
.context
);
1204 // Listen for whether our opener gets destroyed.
1206 AddDestructionObserver(opener_
);
1208 #if defined(ENABLE_PLUGINS)
1209 plugin_content_origin_whitelist_
.reset(
1210 new PluginContentOriginWhitelist(this));
1213 registrar_
.Add(this,
1214 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED
,
1215 NotificationService::AllBrowserContextsAndSources());
1217 screen_orientation_dispatcher_host_
.reset(
1218 new ScreenOrientationDispatcherHostImpl(this));
1220 manifest_manager_host_
.reset(new ManifestManagerHost(this));
1222 #if defined(OS_ANDROID)
1223 date_time_chooser_
.reset(new DateTimeChooserAndroid());
1226 // BrowserPluginGuest::Init needs to be called after this WebContents has
1227 // a RenderWidgetHostViewGuest. That is, |view_->CreateView| above.
1228 if (browser_plugin_guest_
)
1229 browser_plugin_guest_
->Init();
1231 for (size_t i
= 0; i
< g_created_callbacks
.Get().size(); i
++)
1232 g_created_callbacks
.Get().at(i
).Run(this);
1235 void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl
* web_contents
) {
1236 RemoveDestructionObserver(web_contents
);
1238 // Clear the opener if it has been closed.
1239 if (web_contents
== opener_
) {
1243 // Clear a pending contents that has been closed before being shown.
1244 for (PendingContents::iterator iter
= pending_contents_
.begin();
1245 iter
!= pending_contents_
.end();
1247 if (iter
->second
!= web_contents
)
1249 pending_contents_
.erase(iter
);
1255 void WebContentsImpl::AddDestructionObserver(WebContentsImpl
* web_contents
) {
1256 if (!ContainsKey(destruction_observers_
, web_contents
)) {
1257 destruction_observers_
[web_contents
] =
1258 new DestructionObserver(this, web_contents
);
1262 void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl
* web_contents
) {
1263 DestructionObservers::iterator iter
=
1264 destruction_observers_
.find(web_contents
);
1265 if (iter
!= destruction_observers_
.end()) {
1266 delete destruction_observers_
[web_contents
];
1267 destruction_observers_
.erase(iter
);
1271 void WebContentsImpl::AddObserver(WebContentsObserver
* observer
) {
1272 observers_
.AddObserver(observer
);
1275 void WebContentsImpl::RemoveObserver(WebContentsObserver
* observer
) {
1276 observers_
.RemoveObserver(observer
);
1279 std::set
<RenderWidgetHostView
*>
1280 WebContentsImpl::GetRenderWidgetHostViewsInTree() {
1281 std::set
<RenderWidgetHostView
*> set
;
1282 if (ShowingInterstitialPage()) {
1283 set
.insert(GetRenderWidgetHostView());
1286 base::Bind(&AddRenderWidgetHostViewToSet
, base::Unretained(&set
)));
1291 void WebContentsImpl::Activate() {
1293 delegate_
->ActivateContents(this);
1296 void WebContentsImpl::Deactivate() {
1298 delegate_
->DeactivateContents(this);
1301 void WebContentsImpl::LostCapture() {
1303 delegate_
->LostCapture();
1306 void WebContentsImpl::RenderWidgetDeleted(
1307 RenderWidgetHostImpl
* render_widget_host
) {
1308 if (is_being_destroyed_
) {
1309 // |created_widgets_| might have been destroyed.
1313 std::set
<RenderWidgetHostImpl
*>::iterator iter
=
1314 created_widgets_
.find(render_widget_host
);
1315 if (iter
!= created_widgets_
.end())
1316 created_widgets_
.erase(iter
);
1318 if (render_widget_host
&&
1319 render_widget_host
->GetRoutingID() == fullscreen_widget_routing_id_
) {
1320 if (delegate_
&& delegate_
->EmbedsFullscreenWidget())
1321 delegate_
->ExitFullscreenModeForTab(this);
1322 FOR_EACH_OBSERVER(WebContentsObserver
,
1324 DidDestroyFullscreenWidget(
1325 fullscreen_widget_routing_id_
));
1326 fullscreen_widget_routing_id_
= MSG_ROUTING_NONE
;
1327 if (fullscreen_widget_had_focus_at_shutdown_
)
1328 view_
->RestoreFocus();
1332 void WebContentsImpl::RenderWidgetGotFocus(
1333 RenderWidgetHostImpl
* render_widget_host
) {
1334 // Notify the delegate if an embedded fullscreen widget was focused.
1335 if (delegate_
&& render_widget_host
&&
1336 delegate_
->EmbedsFullscreenWidget() &&
1337 render_widget_host
->GetView() == GetFullscreenRenderWidgetHostView())
1338 delegate_
->WebContentsFocused(this);
1341 bool WebContentsImpl::PreHandleKeyboardEvent(
1342 const NativeWebKeyboardEvent
& event
,
1343 bool* is_keyboard_shortcut
) {
1345 delegate_
->PreHandleKeyboardEvent(this, event
, is_keyboard_shortcut
);
1348 void WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent
& event
) {
1349 if (browser_plugin_embedder_
&&
1350 browser_plugin_embedder_
->HandleKeyboardEvent(event
)) {
1354 delegate_
->HandleKeyboardEvent(this, event
);
1357 bool WebContentsImpl::HandleWheelEvent(
1358 const blink::WebMouseWheelEvent
& event
) {
1359 #if !defined(OS_MACOSX)
1360 // On platforms other than Mac, control+mousewheel changes zoom. On Mac, this
1361 // isn't done for two reasons:
1362 // -the OS already has a gesture to do this through pinch-zoom
1363 // -if a user starts an inertial scroll, let's go, and presses control
1364 // (i.e. control+tab) then the OS's buffered scroll events will come in
1365 // with control key set which isn't what the user wants
1367 event
.wheelTicksY
&&
1368 (event
.modifiers
& blink::WebInputEvent::ControlKey
) &&
1369 // Avoid adjusting the zoom in response to two-finger-scrolling touchpad
1370 // gestures, which are regrettably easy to trigger accidentally.
1371 !event
.hasPreciseScrollingDeltas
) {
1372 delegate_
->ContentsZoomChange(event
.wheelTicksY
> 0);
1379 bool WebContentsImpl::PreHandleGestureEvent(
1380 const blink::WebGestureEvent
& event
) {
1381 return delegate_
&& delegate_
->PreHandleGestureEvent(this, event
);
1384 bool WebContentsImpl::HandleGestureEvent(
1385 const blink::WebGestureEvent
& event
) {
1386 // Some platforms (eg. Mac) send GesturePinch events for trackpad pinch-zoom.
1387 // Use them to implement browser zoom, as for HandleWheelEvent above.
1388 if (event
.type
== blink::WebInputEvent::GesturePinchUpdate
&&
1389 event
.sourceDevice
== blink::WebGestureDeviceTouchpad
) {
1390 // The scale difference necessary to trigger a zoom action. Derived from
1391 // experimentation to find a value that feels reasonable.
1392 const float kZoomStepValue
= 0.6f
;
1394 // Find the (absolute) thresholds on either side of the current zoom factor,
1395 // then convert those to actual numbers to trigger a zoom in or out.
1396 // This logic deliberately makes the range around the starting zoom value
1397 // for the gesture twice as large as the other ranges (i.e., the notches are
1398 // at ..., -3*step, -2*step, -step, step, 2*step, 3*step, ... but not at 0)
1399 // so that it's easier to get back to your starting point than it is to
1401 float nextStep
= (abs(currentPinchZoomStepDelta_
) + 1) * kZoomStepValue
;
1402 float backStep
= abs(currentPinchZoomStepDelta_
) * kZoomStepValue
;
1403 float zoomInThreshold
= (currentPinchZoomStepDelta_
>= 0) ? nextStep
1405 float zoomOutThreshold
= (currentPinchZoomStepDelta_
<= 0) ? -nextStep
1408 totalPinchGestureAmount_
+= (event
.data
.pinchUpdate
.scale
- 1.0);
1409 if (totalPinchGestureAmount_
> zoomInThreshold
) {
1410 currentPinchZoomStepDelta_
++;
1412 delegate_
->ContentsZoomChange(true);
1413 } else if (totalPinchGestureAmount_
< zoomOutThreshold
) {
1414 currentPinchZoomStepDelta_
--;
1416 delegate_
->ContentsZoomChange(false);
1424 void WebContentsImpl::HandleMouseDown() {
1426 delegate_
->HandleMouseDown();
1429 void WebContentsImpl::HandleMouseUp() {
1431 delegate_
->HandleMouseUp();
1434 void WebContentsImpl::HandlePointerActivate() {
1436 delegate_
->HandlePointerActivate();
1439 void WebContentsImpl::HandleGestureBegin() {
1441 delegate_
->HandleGestureBegin();
1444 void WebContentsImpl::HandleGestureEnd() {
1446 delegate_
->HandleGestureEnd();
1449 void WebContentsImpl::EnterFullscreenMode(const GURL
& origin
) {
1450 // This method is being called to enter renderer-initiated fullscreen mode.
1451 // Make sure any existing fullscreen widget is shut down first.
1452 RenderWidgetHostView
* const widget_view
= GetFullscreenRenderWidgetHostView();
1454 RenderWidgetHostImpl::From(widget_view
->GetRenderWidgetHost())->Shutdown();
1457 delegate_
->EnterFullscreenModeForTab(this, origin
);
1459 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1460 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1463 void WebContentsImpl::ExitFullscreenMode() {
1464 // This method is being called to leave renderer-initiated fullscreen mode.
1465 // Make sure any existing fullscreen widget is shut down first.
1466 RenderWidgetHostView
* const widget_view
= GetFullscreenRenderWidgetHostView();
1468 RenderWidgetHostImpl::From(widget_view
->GetRenderWidgetHost())->Shutdown();
1471 delegate_
->ExitFullscreenModeForTab(this);
1473 FOR_EACH_OBSERVER(WebContentsObserver
,
1475 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1478 bool WebContentsImpl::IsFullscreenForCurrentTab() const {
1479 return delegate_
? delegate_
->IsFullscreenForTabOrPending(this) : false;
1482 void WebContentsImpl::RequestToLockMouse(bool user_gesture
,
1483 bool last_unlocked_by_target
) {
1485 delegate_
->RequestToLockMouse(this, user_gesture
, last_unlocked_by_target
);
1487 GotResponseToLockMouseRequest(false);
1491 void WebContentsImpl::LostMouseLock() {
1493 delegate_
->LostMouseLock();
1496 void WebContentsImpl::CreateNewWindow(
1497 int render_process_id
,
1499 int main_frame_route_id
,
1500 const ViewHostMsg_CreateWindow_Params
& params
,
1501 SessionStorageNamespace
* session_storage_namespace
) {
1502 // We usually create the new window in the same BrowsingInstance (group of
1503 // script-related windows), by passing in the current SiteInstance. However,
1504 // if the opener is being suppressed (in a non-guest), we create a new
1505 // SiteInstance in its own BrowsingInstance.
1506 bool is_guest
= BrowserPluginGuest::IsGuest(this);
1508 // If the opener is to be suppressed, the new window can be in any process.
1509 // Since routing ids are process specific, we must not have one passed in
1510 // as argument here.
1511 DCHECK(!params
.opener_suppressed
|| route_id
== MSG_ROUTING_NONE
);
1513 scoped_refptr
<SiteInstance
> site_instance
=
1514 params
.opener_suppressed
&& !is_guest
?
1515 SiteInstance::CreateForURL(GetBrowserContext(), params
.target_url
) :
1518 // A message to create a new window can only come from the active process for
1519 // this WebContentsImpl instance. If any other process sends the request,
1520 // it is invalid and the process must be terminated.
1521 if (GetRenderProcessHost()->GetID() != render_process_id
) {
1522 RenderProcessHost
* rph
= RenderProcessHost::FromID(render_process_id
);
1523 base::ProcessHandle process_handle
= rph
->GetHandle();
1524 if (process_handle
!= base::kNullProcessHandle
) {
1526 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWindow"));
1527 rph
->Shutdown(RESULT_CODE_KILLED
, false);
1532 // We must assign the SessionStorageNamespace before calling Init().
1534 // http://crbug.com/142685
1535 const std::string
& partition_id
=
1536 GetContentClient()->browser()->
1537 GetStoragePartitionIdForSite(GetBrowserContext(),
1538 site_instance
->GetSiteURL());
1539 StoragePartition
* partition
= BrowserContext::GetStoragePartition(
1540 GetBrowserContext(), site_instance
.get());
1541 DOMStorageContextWrapper
* dom_storage_context
=
1542 static_cast<DOMStorageContextWrapper
*>(partition
->GetDOMStorageContext());
1543 SessionStorageNamespaceImpl
* session_storage_namespace_impl
=
1544 static_cast<SessionStorageNamespaceImpl
*>(session_storage_namespace
);
1545 CHECK(session_storage_namespace_impl
->IsFromContext(dom_storage_context
));
1548 !delegate_
->ShouldCreateWebContents(this,
1550 main_frame_route_id
,
1551 params
.window_container_type
,
1555 session_storage_namespace
)) {
1556 if (route_id
!= MSG_ROUTING_NONE
&&
1557 !RenderViewHost::FromID(render_process_id
, route_id
)) {
1558 // If the embedder didn't create a WebContents for this route, we need to
1559 // delete the RenderView that had already been created.
1560 Send(new ViewMsg_Close(route_id
));
1562 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(route_id
);
1563 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(
1564 main_frame_route_id
);
1568 // Create the new web contents. This will automatically create the new
1569 // WebContentsView. In the future, we may want to create the view separately.
1570 CreateParams
create_params(GetBrowserContext(), site_instance
.get());
1571 create_params
.routing_id
= route_id
;
1572 create_params
.main_frame_routing_id
= main_frame_route_id
;
1573 create_params
.opener
= this;
1574 create_params
.opener_suppressed
= params
.opener_suppressed
;
1575 if (params
.disposition
== NEW_BACKGROUND_TAB
)
1576 create_params
.initially_hidden
= true;
1578 WebContentsImpl
* new_contents
= NULL
;
1580 create_params
.context
= view_
->GetNativeView();
1581 create_params
.initial_size
= GetContainerBounds().size();
1582 new_contents
= static_cast<WebContentsImpl
*>(
1583 WebContents::Create(create_params
));
1585 new_contents
= GetBrowserPluginGuest()->CreateNewGuestWindow(create_params
);
1587 new_contents
->GetController().SetSessionStorageNamespace(
1589 session_storage_namespace
);
1590 new_contents
->RenderViewCreated(new_contents
->GetRenderViewHost());
1592 // Save the window for later if we're not suppressing the opener (since it
1593 // will be shown immediately).
1594 if (!params
.opener_suppressed
) {
1596 WebContentsView
* new_view
= new_contents
->view_
.get();
1598 // TODO(brettw): It seems bogus that we have to call this function on the
1599 // newly created object and give it one of its own member variables.
1600 new_view
->CreateViewForWidget(new_contents
->GetRenderViewHost(), false);
1602 // Save the created window associated with the route so we can show it
1604 DCHECK_NE(MSG_ROUTING_NONE
, route_id
);
1605 pending_contents_
[route_id
] = new_contents
;
1606 AddDestructionObserver(new_contents
);
1610 delegate_
->WebContentsCreated(
1611 this, params
.opener_render_frame_id
, params
.frame_name
,
1612 params
.target_url
, new_contents
);
1615 if (params
.opener_suppressed
) {
1616 // When the opener is suppressed, the original renderer cannot access the
1617 // new window. As a result, we need to show and navigate the window here.
1618 bool was_blocked
= false;
1620 gfx::Rect initial_pos
;
1621 delegate_
->AddNewContents(
1622 this, new_contents
, params
.disposition
, initial_pos
,
1623 params
.user_gesture
, &was_blocked
);
1626 OpenURLParams
open_params(params
.target_url
,
1629 ui::PAGE_TRANSITION_LINK
,
1630 true /* is_renderer_initiated */);
1631 open_params
.user_gesture
= params
.user_gesture
;
1632 new_contents
->OpenURL(open_params
);
1637 void WebContentsImpl::CreateNewWidget(int render_process_id
,
1639 blink::WebPopupType popup_type
) {
1640 CreateNewWidget(render_process_id
, route_id
, false, popup_type
);
1643 void WebContentsImpl::CreateNewFullscreenWidget(int render_process_id
,
1645 CreateNewWidget(render_process_id
, route_id
, true, blink::WebPopupTypeNone
);
1648 void WebContentsImpl::CreateNewWidget(int render_process_id
,
1651 blink::WebPopupType popup_type
) {
1652 RenderProcessHost
* process
= GetRenderProcessHost();
1653 // A message to create a new widget can only come from the active process for
1654 // this WebContentsImpl instance. If any other process sends the request,
1655 // it is invalid and the process must be terminated.
1656 if (process
->GetID() != render_process_id
) {
1657 RenderProcessHost
* rph
= RenderProcessHost::FromID(render_process_id
);
1658 base::ProcessHandle process_handle
= rph
->GetHandle();
1659 if (process_handle
!= base::kNullProcessHandle
) {
1661 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWidget"));
1662 rph
->Shutdown(RESULT_CODE_KILLED
, false);
1667 RenderWidgetHostImpl
* widget_host
=
1668 new RenderWidgetHostImpl(this, process
, route_id
, IsHidden());
1669 created_widgets_
.insert(widget_host
);
1671 RenderWidgetHostViewBase
* widget_view
=
1672 static_cast<RenderWidgetHostViewBase
*>(
1673 view_
->CreateViewForPopupWidget(widget_host
));
1676 if (!is_fullscreen
) {
1677 // Popups should not get activated.
1678 widget_view
->SetPopupType(popup_type
);
1680 // Save the created widget associated with the route so we can show it later.
1681 pending_widget_views_
[route_id
] = widget_view
;
1683 #if defined(OS_MACOSX)
1684 // A RenderWidgetHostViewMac has lifetime scoped to the view. We'll retain it
1685 // to allow it to survive the trip without being hosted.
1686 base::mac::NSObjectRetain(widget_view
->GetNativeView());
1690 void WebContentsImpl::ShowCreatedWindow(int route_id
,
1691 WindowOpenDisposition disposition
,
1692 const gfx::Rect
& initial_pos
,
1693 bool user_gesture
) {
1694 WebContentsImpl
* contents
= GetCreatedWindow(route_id
);
1696 WebContentsDelegate
* delegate
= GetDelegate();
1698 delegate
->AddNewContents(
1699 this, contents
, disposition
, initial_pos
, user_gesture
, NULL
);
1704 void WebContentsImpl::ShowCreatedWidget(int route_id
,
1705 const gfx::Rect
& initial_pos
) {
1706 ShowCreatedWidget(route_id
, false, initial_pos
);
1709 void WebContentsImpl::ShowCreatedFullscreenWidget(int route_id
) {
1710 ShowCreatedWidget(route_id
, true, gfx::Rect());
1713 void WebContentsImpl::ShowCreatedWidget(int route_id
,
1715 const gfx::Rect
& initial_pos
) {
1716 RenderWidgetHostViewBase
* widget_host_view
=
1717 static_cast<RenderWidgetHostViewBase
*>(GetCreatedWidget(route_id
));
1718 if (!widget_host_view
)
1721 RenderWidgetHostView
* view
= NULL
;
1722 BrowserPluginGuest
* guest
= GetBrowserPluginGuest();
1723 if (guest
&& guest
->embedder_web_contents()) {
1724 view
= guest
->embedder_web_contents()->GetRenderWidgetHostView();
1726 view
= GetRenderWidgetHostView();
1729 if (is_fullscreen
) {
1730 DCHECK_EQ(MSG_ROUTING_NONE
, fullscreen_widget_routing_id_
);
1731 view_
->StoreFocus();
1732 fullscreen_widget_routing_id_
= route_id
;
1733 if (delegate_
&& delegate_
->EmbedsFullscreenWidget()) {
1734 widget_host_view
->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
1735 delegate_
->EnterFullscreenModeForTab(this, GURL());
1737 widget_host_view
->InitAsFullscreen(view
);
1739 FOR_EACH_OBSERVER(WebContentsObserver
,
1741 DidShowFullscreenWidget(route_id
));
1742 if (!widget_host_view
->HasFocus())
1743 widget_host_view
->Focus();
1745 widget_host_view
->InitAsPopup(view
, initial_pos
);
1748 RenderWidgetHostImpl
* render_widget_host_impl
=
1749 RenderWidgetHostImpl::From(widget_host_view
->GetRenderWidgetHost());
1750 render_widget_host_impl
->Init();
1751 // Only allow privileged mouse lock for fullscreen render widget, which is
1752 // used to implement Pepper Flash fullscreen.
1753 render_widget_host_impl
->set_allow_privileged_mouse_lock(is_fullscreen
);
1755 #if defined(OS_MACOSX)
1756 // A RenderWidgetHostViewMac has lifetime scoped to the view. Now that it's
1757 // properly embedded (or purposefully ignored) we can release the retain we
1758 // took in CreateNewWidget().
1759 base::mac::NSObjectRelease(widget_host_view
->GetNativeView());
1763 WebContentsImpl
* WebContentsImpl::GetCreatedWindow(int route_id
) {
1764 PendingContents::iterator iter
= pending_contents_
.find(route_id
);
1766 // Certain systems can block the creation of new windows. If we didn't succeed
1767 // in creating one, just return NULL.
1768 if (iter
== pending_contents_
.end()) {
1772 WebContentsImpl
* new_contents
= iter
->second
;
1773 pending_contents_
.erase(route_id
);
1774 RemoveDestructionObserver(new_contents
);
1776 // Don't initialize the guest WebContents immediately.
1777 if (BrowserPluginGuest::IsGuest(new_contents
))
1778 return new_contents
;
1780 if (!new_contents
->GetRenderProcessHost()->HasConnection() ||
1781 !new_contents
->GetRenderViewHost()->GetView())
1784 // Resume blocked requests for both the RenderViewHost and RenderFrameHost.
1785 // TODO(brettw): It seems bogus to reach into here and initialize the host.
1786 static_cast<RenderViewHostImpl
*>(new_contents
->GetRenderViewHost())->Init();
1787 static_cast<RenderFrameHostImpl
*>(new_contents
->GetMainFrame())->Init();
1789 return new_contents
;
1792 RenderWidgetHostView
* WebContentsImpl::GetCreatedWidget(int route_id
) {
1793 PendingWidgetViews::iterator iter
= pending_widget_views_
.find(route_id
);
1794 if (iter
== pending_widget_views_
.end()) {
1799 RenderWidgetHostView
* widget_host_view
= iter
->second
;
1800 pending_widget_views_
.erase(route_id
);
1802 RenderWidgetHost
* widget_host
= widget_host_view
->GetRenderWidgetHost();
1803 if (!widget_host
->GetProcess()->HasConnection()) {
1804 // The view has gone away or the renderer crashed. Nothing to do.
1808 return widget_host_view
;
1811 void WebContentsImpl::RequestMediaAccessPermission(
1812 const MediaStreamRequest
& request
,
1813 const MediaResponseCallback
& callback
) {
1815 delegate_
->RequestMediaAccessPermission(this, request
, callback
);
1817 callback
.Run(MediaStreamDevices(),
1818 MEDIA_DEVICE_FAILED_DUE_TO_SHUTDOWN
,
1819 scoped_ptr
<MediaStreamUI
>());
1823 bool WebContentsImpl::CheckMediaAccessPermission(const GURL
& security_origin
,
1824 MediaStreamType type
) {
1825 DCHECK(type
== MEDIA_DEVICE_AUDIO_CAPTURE
||
1826 type
== MEDIA_DEVICE_VIDEO_CAPTURE
);
1828 delegate_
->CheckMediaAccessPermission(this, security_origin
, type
);
1831 SessionStorageNamespace
* WebContentsImpl::GetSessionStorageNamespace(
1832 SiteInstance
* instance
) {
1833 return controller_
.GetSessionStorageNamespace(instance
);
1836 SessionStorageNamespaceMap
WebContentsImpl::GetSessionStorageNamespaceMap() {
1837 return controller_
.GetSessionStorageNamespaceMap();
1840 FrameTree
* WebContentsImpl::GetFrameTree() {
1841 return &frame_tree_
;
1844 void WebContentsImpl::SetIsVirtualKeyboardRequested(bool requested
) {
1845 virtual_keyboard_requested_
= requested
;
1848 bool WebContentsImpl::IsVirtualKeyboardRequested() {
1849 return virtual_keyboard_requested_
;
1852 AccessibilityMode
WebContentsImpl::GetAccessibilityMode() const {
1853 return accessibility_mode_
;
1856 void WebContentsImpl::AccessibilityEventReceived(
1857 const std::vector
<AXEventNotificationDetails
>& details
) {
1859 WebContentsObserver
, observers_
, AccessibilityEventReceived(details
));
1862 RenderFrameHost
* WebContentsImpl::GetGuestByInstanceID(
1863 int browser_plugin_instance_id
) {
1864 BrowserPluginGuestManager
* guest_manager
=
1865 GetBrowserContext()->GetGuestManager();
1866 WebContents
* guest
= guest_manager
->GetGuestByInstanceID(
1867 this, browser_plugin_instance_id
);
1870 return guest
->GetMainFrame();
1873 GeolocationServiceContext
* WebContentsImpl::GetGeolocationServiceContext() {
1874 return geolocation_service_context_
.get();
1877 void WebContentsImpl::OnShowValidationMessage(
1878 const gfx::Rect
& anchor_in_root_view
,
1879 const base::string16
& main_text
,
1880 const base::string16
& sub_text
) {
1882 delegate_
->ShowValidationMessage(
1883 this, anchor_in_root_view
, main_text
, sub_text
);
1886 void WebContentsImpl::OnHideValidationMessage() {
1888 delegate_
->HideValidationMessage(this);
1891 void WebContentsImpl::OnMoveValidationMessage(
1892 const gfx::Rect
& anchor_in_root_view
) {
1894 delegate_
->MoveValidationMessage(this, anchor_in_root_view
);
1897 void WebContentsImpl::DidSendScreenRects(RenderWidgetHostImpl
* rwh
) {
1898 if (browser_plugin_embedder_
)
1899 browser_plugin_embedder_
->DidSendScreenRects();
1902 BrowserAccessibilityManager
*
1903 WebContentsImpl::GetRootBrowserAccessibilityManager() {
1904 RenderFrameHostImpl
* rfh
= static_cast<RenderFrameHostImpl
*>(GetMainFrame());
1905 return rfh
? rfh
->browser_accessibility_manager() : NULL
;
1908 BrowserAccessibilityManager
*
1909 WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
1910 RenderFrameHostImpl
* rfh
= static_cast<RenderFrameHostImpl
*>(GetMainFrame());
1911 return rfh
? rfh
->GetOrCreateBrowserAccessibilityManager() : NULL
;
1914 void WebContentsImpl::UpdatePreferredSize(const gfx::Size
& pref_size
) {
1915 const gfx::Size old_size
= GetPreferredSize();
1916 preferred_size_
= pref_size
;
1917 OnPreferredSizeChanged(old_size
);
1920 void WebContentsImpl::ResizeDueToAutoResize(const gfx::Size
& new_size
) {
1922 delegate_
->ResizeDueToAutoResize(this, new_size
);
1925 WebContents
* WebContentsImpl::OpenURL(const OpenURLParams
& params
) {
1929 WebContents
* new_contents
= delegate_
->OpenURLFromTab(this, params
);
1930 return new_contents
;
1933 bool WebContentsImpl::Send(IPC::Message
* message
) {
1934 if (!GetRenderViewHost()) {
1939 return GetRenderViewHost()->Send(message
);
1942 bool WebContentsImpl::NavigateToPendingEntry(
1943 NavigationController::ReloadType reload_type
) {
1944 FrameTreeNode
* node
= frame_tree_
.root();
1946 // Navigate in the FrameTreeNode specified in the pending entry, if any. This
1947 // is currently only used in --site-per-process and tests.
1948 NavigationEntryImpl
* pending_entry
=
1949 NavigationEntryImpl::FromNavigationEntry(controller_
.GetPendingEntry());
1950 if (pending_entry
->frame_tree_node_id() != -1) {
1951 FrameTreeNode
* subframe
=
1952 frame_tree_
.FindByID(pending_entry
->frame_tree_node_id());
1958 return node
->navigator()->NavigateToPendingEntry(
1959 node
->current_frame_host(), reload_type
);
1962 void WebContentsImpl::RenderFrameForInterstitialPageCreated(
1963 RenderFrameHost
* render_frame_host
) {
1964 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1965 RenderFrameForInterstitialPageCreated(render_frame_host
));
1968 void WebContentsImpl::AttachInterstitialPage(
1969 InterstitialPageImpl
* interstitial_page
) {
1970 DCHECK(interstitial_page
);
1971 GetRenderManager()->set_interstitial_page(interstitial_page
);
1973 // Cancel any visible dialogs so that they don't interfere with the
1975 if (dialog_manager_
)
1976 dialog_manager_
->CancelActiveAndPendingDialogs(this);
1978 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1979 DidAttachInterstitialPage());
1982 void WebContentsImpl::DetachInterstitialPage() {
1983 if (ShowingInterstitialPage())
1984 GetRenderManager()->remove_interstitial_page();
1985 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1986 DidDetachInterstitialPage());
1989 void WebContentsImpl::SetHistoryOffsetAndLength(int history_offset
,
1990 int history_length
) {
1991 SetHistoryOffsetAndLengthForView(
1992 GetRenderViewHost(), history_offset
, history_length
);
1995 void WebContentsImpl::SetHistoryOffsetAndLengthForView(
1996 RenderViewHost
* render_view_host
,
1998 int history_length
) {
1999 render_view_host
->Send(new ViewMsg_SetHistoryOffsetAndLength(
2000 render_view_host
->GetRoutingID(), history_offset
, history_length
));
2003 void WebContentsImpl::ReloadFocusedFrame(bool ignore_cache
) {
2004 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2008 focused_frame
->Send(new FrameMsg_Reload(
2009 focused_frame
->GetRoutingID(), ignore_cache
));
2012 void WebContentsImpl::Undo() {
2013 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2017 focused_frame
->Send(new InputMsg_Undo(focused_frame
->GetRoutingID()));
2018 RecordAction(base::UserMetricsAction("Undo"));
2021 void WebContentsImpl::Redo() {
2022 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2025 focused_frame
->Send(new InputMsg_Redo(focused_frame
->GetRoutingID()));
2026 RecordAction(base::UserMetricsAction("Redo"));
2029 void WebContentsImpl::Cut() {
2030 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2034 focused_frame
->Send(new InputMsg_Cut(focused_frame
->GetRoutingID()));
2035 RecordAction(base::UserMetricsAction("Cut"));
2038 void WebContentsImpl::Copy() {
2039 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2043 focused_frame
->Send(new InputMsg_Copy(focused_frame
->GetRoutingID()));
2044 RecordAction(base::UserMetricsAction("Copy"));
2047 void WebContentsImpl::CopyToFindPboard() {
2048 #if defined(OS_MACOSX)
2049 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2053 // Windows/Linux don't have the concept of a find pasteboard.
2054 focused_frame
->Send(
2055 new InputMsg_CopyToFindPboard(focused_frame
->GetRoutingID()));
2056 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
2060 void WebContentsImpl::Paste() {
2061 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2065 focused_frame
->Send(new InputMsg_Paste(focused_frame
->GetRoutingID()));
2066 RecordAction(base::UserMetricsAction("Paste"));
2069 void WebContentsImpl::PasteAndMatchStyle() {
2070 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2074 focused_frame
->Send(new InputMsg_PasteAndMatchStyle(
2075 focused_frame
->GetRoutingID()));
2076 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
2079 void WebContentsImpl::Delete() {
2080 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2084 focused_frame
->Send(new InputMsg_Delete(focused_frame
->GetRoutingID()));
2085 RecordAction(base::UserMetricsAction("DeleteSelection"));
2088 void WebContentsImpl::SelectAll() {
2089 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2093 focused_frame
->Send(new InputMsg_SelectAll(focused_frame
->GetRoutingID()));
2094 RecordAction(base::UserMetricsAction("SelectAll"));
2097 void WebContentsImpl::Unselect() {
2098 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2102 focused_frame
->Send(new InputMsg_Unselect(focused_frame
->GetRoutingID()));
2103 RecordAction(base::UserMetricsAction("Unselect"));
2106 void WebContentsImpl::Replace(const base::string16
& word
) {
2107 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2111 focused_frame
->Send(new InputMsg_Replace(
2112 focused_frame
->GetRoutingID(), word
));
2115 void WebContentsImpl::ReplaceMisspelling(const base::string16
& word
) {
2116 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2120 focused_frame
->Send(new InputMsg_ReplaceMisspelling(
2121 focused_frame
->GetRoutingID(), word
));
2124 void WebContentsImpl::NotifyContextMenuClosed(
2125 const CustomContextMenuContext
& context
) {
2126 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2130 focused_frame
->Send(new FrameMsg_ContextMenuClosed(
2131 focused_frame
->GetRoutingID(), context
));
2134 void WebContentsImpl::ExecuteCustomContextMenuCommand(
2135 int action
, const CustomContextMenuContext
& context
) {
2136 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2140 focused_frame
->Send(new FrameMsg_CustomContextMenuAction(
2141 focused_frame
->GetRoutingID(), context
, action
));
2144 gfx::NativeView
WebContentsImpl::GetNativeView() {
2145 return view_
->GetNativeView();
2148 gfx::NativeView
WebContentsImpl::GetContentNativeView() {
2149 return view_
->GetContentNativeView();
2152 gfx::NativeWindow
WebContentsImpl::GetTopLevelNativeWindow() {
2153 return view_
->GetTopLevelNativeWindow();
2156 gfx::Rect
WebContentsImpl::GetViewBounds() {
2157 return view_
->GetViewBounds();
2160 gfx::Rect
WebContentsImpl::GetContainerBounds() {
2162 view_
->GetContainerBounds(&rv
);
2166 DropData
* WebContentsImpl::GetDropData() {
2167 return view_
->GetDropData();
2170 void WebContentsImpl::Focus() {
2174 void WebContentsImpl::SetInitialFocus() {
2175 view_
->SetInitialFocus();
2178 void WebContentsImpl::StoreFocus() {
2179 view_
->StoreFocus();
2182 void WebContentsImpl::RestoreFocus() {
2183 view_
->RestoreFocus();
2186 void WebContentsImpl::FocusThroughTabTraversal(bool reverse
) {
2187 if (ShowingInterstitialPage()) {
2188 GetRenderManager()->interstitial_page()->FocusThroughTabTraversal(reverse
);
2191 RenderWidgetHostView
* const fullscreen_view
=
2192 GetFullscreenRenderWidgetHostView();
2193 if (fullscreen_view
) {
2194 fullscreen_view
->Focus();
2197 GetRenderViewHostImpl()->SetInitialFocus(reverse
);
2200 bool WebContentsImpl::ShowingInterstitialPage() const {
2201 return GetRenderManager()->interstitial_page() != NULL
;
2204 InterstitialPage
* WebContentsImpl::GetInterstitialPage() const {
2205 return GetRenderManager()->interstitial_page();
2208 bool WebContentsImpl::IsSavable() {
2209 // WebKit creates Document object when MIME type is application/xhtml+xml,
2210 // so we also support this MIME type.
2211 return contents_mime_type_
== "text/html" ||
2212 contents_mime_type_
== "text/xml" ||
2213 contents_mime_type_
== "application/xhtml+xml" ||
2214 contents_mime_type_
== "text/plain" ||
2215 contents_mime_type_
== "text/css" ||
2216 net::IsSupportedJavascriptMimeType(contents_mime_type_
.c_str());
2219 void WebContentsImpl::OnSavePage() {
2220 // If we can not save the page, try to download it.
2222 RecordDownloadSource(INITIATED_BY_SAVE_PACKAGE_ON_NON_HTML
);
2223 SaveFrame(GetURL(), Referrer());
2229 // Create the save package and possibly prompt the user for the name to save
2230 // the page as. The user prompt is an asynchronous operation that runs on
2232 save_package_
= new SavePackage(this);
2233 save_package_
->GetSaveInfo();
2236 // Used in automated testing to bypass prompting the user for file names.
2237 // Instead, the names and paths are hard coded rather than running them through
2238 // file name sanitation and extension / mime checking.
2239 bool WebContentsImpl::SavePage(const base::FilePath
& main_file
,
2240 const base::FilePath
& dir_path
,
2241 SavePageType save_type
) {
2242 // Stop the page from navigating.
2245 save_package_
= new SavePackage(this, save_type
, main_file
, dir_path
);
2246 return save_package_
->Init(SavePackageDownloadCreatedCallback());
2249 void WebContentsImpl::SaveFrame(const GURL
& url
,
2250 const Referrer
& referrer
) {
2251 if (!GetURL().is_valid())
2253 if (delegate_
&& delegate_
->SaveFrame(url
, referrer
))
2256 bool is_main_frame
= (url
== GetURL());
2258 DownloadManager
* dlm
=
2259 BrowserContext::GetDownloadManager(GetBrowserContext());
2263 if (is_main_frame
) {
2264 const NavigationEntry
* entry
= controller_
.GetLastCommittedEntry();
2266 post_id
= entry
->GetPostID();
2268 scoped_ptr
<DownloadUrlParameters
> params(
2269 DownloadUrlParameters::FromWebContents(this, url
));
2270 params
->set_referrer(referrer
);
2271 params
->set_post_id(post_id
);
2272 params
->set_prefer_cache(true);
2274 params
->set_method("POST");
2275 params
->set_prompt(true);
2276 dlm
->DownloadUrl(params
.Pass());
2279 void WebContentsImpl::GenerateMHTML(
2280 const base::FilePath
& file
,
2281 const base::Callback
<void(int64
)>& callback
) {
2282 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, file
, callback
);
2285 const std::string
& WebContentsImpl::GetContentsMimeType() const {
2286 return contents_mime_type_
;
2289 bool WebContentsImpl::WillNotifyDisconnection() const {
2290 return notify_disconnection_
;
2293 void WebContentsImpl::SetOverrideEncoding(const std::string
& encoding
) {
2294 SetEncoding(encoding
);
2295 Send(new ViewMsg_SetPageEncoding(GetRoutingID(), encoding
));
2298 void WebContentsImpl::ResetOverrideEncoding() {
2299 canonical_encoding_
.clear();
2300 Send(new ViewMsg_ResetPageEncodingToDefault(GetRoutingID()));
2303 RendererPreferences
* WebContentsImpl::GetMutableRendererPrefs() {
2304 return &renderer_preferences_
;
2307 void WebContentsImpl::Close() {
2308 Close(GetRenderViewHost());
2311 void WebContentsImpl::DragSourceEndedAt(int client_x
, int client_y
,
2312 int screen_x
, int screen_y
, blink::WebDragOperation operation
) {
2313 if (browser_plugin_embedder_
.get())
2314 browser_plugin_embedder_
->DragSourceEndedAt(client_x
, client_y
,
2315 screen_x
, screen_y
, operation
);
2316 if (GetRenderViewHost())
2317 GetRenderViewHostImpl()->DragSourceEndedAt(client_x
, client_y
,
2318 screen_x
, screen_y
, operation
);
2321 void WebContentsImpl::DidGetResourceResponseStart(
2322 const ResourceRequestDetails
& details
) {
2323 controller_
.ssl_manager()->DidStartResourceResponse(details
);
2325 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2326 DidGetResourceResponseStart(details
));
2328 // TODO(avi): Remove. http://crbug.com/170921
2329 NotificationService::current()->Notify(
2330 NOTIFICATION_RESOURCE_RESPONSE_STARTED
,
2331 Source
<WebContents
>(this),
2332 Details
<const ResourceRequestDetails
>(&details
));
2335 void WebContentsImpl::DidGetRedirectForResourceRequest(
2336 RenderFrameHost
* render_frame_host
,
2337 const ResourceRedirectDetails
& details
) {
2338 controller_
.ssl_manager()->DidReceiveResourceRedirect(details
);
2341 WebContentsObserver
,
2343 DidGetRedirectForResourceRequest(render_frame_host
, details
));
2345 // TODO(avi): Remove. http://crbug.com/170921
2346 NotificationService::current()->Notify(
2347 NOTIFICATION_RESOURCE_RECEIVED_REDIRECT
,
2348 Source
<WebContents
>(this),
2349 Details
<const ResourceRedirectDetails
>(&details
));
2352 void WebContentsImpl::SystemDragEnded() {
2353 if (GetRenderViewHost())
2354 GetRenderViewHostImpl()->DragSourceSystemDragEnded();
2356 delegate_
->DragEnded();
2357 if (browser_plugin_embedder_
.get())
2358 browser_plugin_embedder_
->SystemDragEnded();
2361 void WebContentsImpl::UserGestureDone() {
2365 void WebContentsImpl::SetClosedByUserGesture(bool value
) {
2366 closed_by_user_gesture_
= value
;
2369 bool WebContentsImpl::GetClosedByUserGesture() const {
2370 return closed_by_user_gesture_
;
2373 void WebContentsImpl::ViewSource() {
2377 NavigationEntry
* entry
= GetController().GetLastCommittedEntry();
2381 delegate_
->ViewSourceForTab(this, entry
->GetURL());
2384 void WebContentsImpl::ViewFrameSource(const GURL
& url
,
2385 const PageState
& page_state
) {
2389 delegate_
->ViewSourceForFrame(this, url
, page_state
);
2392 int WebContentsImpl::GetMinimumZoomPercent() const {
2393 return minimum_zoom_percent_
;
2396 int WebContentsImpl::GetMaximumZoomPercent() const {
2397 return maximum_zoom_percent_
;
2400 gfx::Size
WebContentsImpl::GetPreferredSize() const {
2401 return capturer_count_
== 0 ? preferred_size_
: preferred_size_for_capture_
;
2404 bool WebContentsImpl::GotResponseToLockMouseRequest(bool allowed
) {
2405 if (GetBrowserPluginGuest())
2406 return GetBrowserPluginGuest()->LockMouse(allowed
);
2408 return GetRenderViewHost() ?
2409 GetRenderViewHostImpl()->GotResponseToLockMouseRequest(allowed
) : false;
2412 bool WebContentsImpl::HasOpener() const {
2413 return opener_
!= NULL
;
2416 WebContents
* WebContentsImpl::GetOpener() const {
2417 return static_cast<WebContents
*>(opener_
);
2420 void WebContentsImpl::DidChooseColorInColorChooser(SkColor color
) {
2421 if (!color_chooser_info_
.get())
2423 RenderFrameHost
* rfh
= RenderFrameHost::FromID(
2424 color_chooser_info_
->render_process_id
,
2425 color_chooser_info_
->render_frame_id
);
2429 rfh
->Send(new FrameMsg_DidChooseColorResponse(
2430 rfh
->GetRoutingID(), color_chooser_info_
->identifier
, color
));
2433 void WebContentsImpl::DidEndColorChooser() {
2434 if (!color_chooser_info_
.get())
2436 RenderFrameHost
* rfh
= RenderFrameHost::FromID(
2437 color_chooser_info_
->render_process_id
,
2438 color_chooser_info_
->render_frame_id
);
2442 rfh
->Send(new FrameMsg_DidEndColorChooser(
2443 rfh
->GetRoutingID(), color_chooser_info_
->identifier
));
2444 color_chooser_info_
.reset();
2447 int WebContentsImpl::DownloadImage(const GURL
& url
,
2449 uint32_t max_bitmap_size
,
2450 const ImageDownloadCallback
& callback
) {
2451 int id
= StartDownload(GetMainFrame(), url
, is_favicon
, max_bitmap_size
);
2452 image_download_map_
[id
] = callback
;
2456 bool WebContentsImpl::IsSubframe() const {
2457 return is_subframe_
;
2460 void WebContentsImpl::Find(int request_id
,
2461 const base::string16
& search_text
,
2462 const blink::WebFindOptions
& options
) {
2463 // See if a top level browser plugin handles the find request first.
2464 if (browser_plugin_embedder_
&&
2465 browser_plugin_embedder_
->Find(request_id
, search_text
, options
)) {
2468 Send(new ViewMsg_Find(GetRoutingID(), request_id
, search_text
, options
));
2471 void WebContentsImpl::StopFinding(StopFindAction action
) {
2472 Send(new ViewMsg_StopFinding(GetRoutingID(), action
));
2475 void WebContentsImpl::InsertCSS(const std::string
& css
) {
2476 GetMainFrame()->Send(new FrameMsg_CSSInsertRequest(
2477 GetMainFrame()->GetRoutingID(), css
));
2480 bool WebContentsImpl::WasRecentlyAudible() {
2481 return audio_stream_monitor_
.WasRecentlyAudible();
2484 void WebContentsImpl::GetManifest(const GetManifestCallback
& callback
) {
2485 manifest_manager_host_
->GetManifest(GetMainFrame(), callback
);
2488 void WebContentsImpl::ExitFullscreen() {
2489 // Clean up related state and initiate the fullscreen exit.
2490 GetRenderViewHostImpl()->RejectMouseLockOrUnlockIfNecessary();
2491 ExitFullscreenMode();
2494 bool WebContentsImpl::FocusLocationBarByDefault() {
2495 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
2496 if (entry
&& entry
->GetURL() == GURL(url::kAboutBlankURL
))
2498 return delegate_
&& delegate_
->ShouldFocusLocationBarByDefault(this);
2501 void WebContentsImpl::SetFocusToLocationBar(bool select_all
) {
2503 delegate_
->SetFocusToLocationBar(select_all
);
2506 void WebContentsImpl::DidStartProvisionalLoad(
2507 RenderFrameHostImpl
* render_frame_host
,
2508 const GURL
& validated_url
,
2510 bool is_iframe_srcdoc
) {
2511 // Notify observers about the start of the provisional load.
2513 WebContentsObserver
,
2515 DidStartProvisionalLoadForFrame(
2516 render_frame_host
, validated_url
, is_error_page
, is_iframe_srcdoc
));
2519 void WebContentsImpl::DidStartNavigationTransition(
2520 RenderFrameHostImpl
* render_frame_host
) {
2521 #if defined(OS_ANDROID)
2522 int render_frame_id
= render_frame_host
->GetRoutingID();
2523 GetWebContentsAndroid()->DidStartNavigationTransitionForFrame(
2528 void WebContentsImpl::DidFailProvisionalLoadWithError(
2529 RenderFrameHostImpl
* render_frame_host
,
2530 const FrameHostMsg_DidFailProvisionalLoadWithError_Params
& params
) {
2531 GURL
validated_url(params
.url
);
2532 FOR_EACH_OBSERVER(WebContentsObserver
,
2534 DidFailProvisionalLoad(render_frame_host
,
2537 params
.error_description
));
2540 void WebContentsImpl::DidFailLoadWithError(
2541 RenderFrameHostImpl
* render_frame_host
,
2544 const base::string16
& error_description
) {
2546 WebContentsObserver
,
2548 DidFailLoad(render_frame_host
, url
, error_code
, error_description
));
2551 void WebContentsImpl::NotifyChangedNavigationState(
2552 InvalidateTypes changed_flags
) {
2553 NotifyNavigationStateChanged(changed_flags
);
2556 void WebContentsImpl::AboutToNavigateRenderFrame(
2557 RenderFrameHostImpl
* render_frame_host
) {
2558 // Notify observers that we will navigate in this RenderFrame.
2560 WebContentsObserver
,
2562 AboutToNavigateRenderFrame(render_frame_host
));
2565 void WebContentsImpl::DidStartNavigationToPendingEntry(
2566 RenderFrameHostImpl
* render_frame_host
,
2568 NavigationController::ReloadType reload_type
) {
2569 // Notify observers about navigation.
2571 WebContentsObserver
,
2573 DidStartNavigationToPendingEntry(url
, reload_type
));
2576 void WebContentsImpl::RequestOpenURL(RenderFrameHostImpl
* render_frame_host
,
2577 const OpenURLParams
& params
) {
2578 // OpenURL can blow away the source RFH. Use the process/frame routing ID as a
2579 // weak pointer of sorts.
2580 const int32_t process_id
= render_frame_host
->GetProcess()->GetID();
2581 const int32_t frame_id
= render_frame_host
->GetRoutingID();
2583 WebContents
* new_contents
= OpenURL(params
);
2585 if (new_contents
&& RenderFrameHost::FromID(process_id
, frame_id
)) {
2586 // Notify observers.
2587 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2588 DidOpenRequestedURL(new_contents
,
2593 params
.transition
));
2597 bool WebContentsImpl::ShouldPreserveAbortedURLs() {
2600 return delegate_
->ShouldPreserveAbortedURLs(this);
2603 void WebContentsImpl::DidCommitProvisionalLoad(
2604 RenderFrameHostImpl
* render_frame_host
,
2606 ui::PageTransition transition_type
) {
2607 // Notify observers about the commit of the provisional load.
2608 FOR_EACH_OBSERVER(WebContentsObserver
,
2610 DidCommitProvisionalLoadForFrame(
2611 render_frame_host
, url
, transition_type
));
2614 void WebContentsImpl::DidNavigateMainFramePreCommit(
2615 bool navigation_is_within_page
) {
2616 // Ensure fullscreen mode is exited before committing the navigation to a
2617 // different page. The next page will not start out assuming it is in
2619 if (navigation_is_within_page
) {
2620 // No page change? Then, the renderer and browser can remain in fullscreen.
2623 if (IsFullscreenForCurrentTab())
2625 DCHECK(!IsFullscreenForCurrentTab());
2628 void WebContentsImpl::DidNavigateMainFramePostCommit(
2629 RenderFrameHostImpl
* render_frame_host
,
2630 const LoadCommittedDetails
& details
,
2631 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) {
2632 if (details
.is_navigation_to_different_page()) {
2633 // Clear the status bubble. This is a workaround for a bug where WebKit
2634 // doesn't let us know that the cursor left an element during a
2635 // transition (this is also why the mouse cursor remains as a hand after
2636 // clicking on a link); see bugs 1184641 and 980803. We don't want to
2637 // clear the bubble when a user navigates to a named anchor in the same
2639 UpdateTargetURL(render_frame_host
->GetRenderViewHost(), GURL());
2642 if (!details
.is_in_page
) {
2643 // Once the main frame is navigated, we're no longer considered to have
2644 // displayed insecure content.
2645 displayed_insecure_content_
= false;
2646 SSLManager::NotifySSLInternalStateChanged(
2647 GetController().GetBrowserContext());
2650 // Notify observers about navigation.
2651 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2652 DidNavigateMainFrame(details
, params
));
2655 delegate_
->DidNavigateMainFramePostCommit(this);
2656 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
2659 void WebContentsImpl::DidNavigateAnyFramePostCommit(
2660 RenderFrameHostImpl
* render_frame_host
,
2661 const LoadCommittedDetails
& details
,
2662 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) {
2663 // Now that something has committed, we don't need to track whether the
2664 // initial page has been accessed.
2665 has_accessed_initial_document_
= false;
2667 // If we navigate off the page, close all JavaScript dialogs.
2668 if (dialog_manager_
&& !details
.is_in_page
)
2669 dialog_manager_
->CancelActiveAndPendingDialogs(this);
2671 // Notify observers about navigation.
2672 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2673 DidNavigateAnyFrame(render_frame_host
, details
, params
));
2676 void WebContentsImpl::SetMainFrameMimeType(const std::string
& mime_type
) {
2677 contents_mime_type_
= mime_type
;
2680 bool WebContentsImpl::CanOverscrollContent() const {
2681 // Disable overscroll when touch emulation is on. See crbug.com/369938.
2682 if (force_disable_overscroll_content_
)
2686 return delegate_
->CanOverscrollContent();
2691 void WebContentsImpl::OnThemeColorChanged(SkColor theme_color
) {
2692 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2693 DidChangeThemeColor(theme_color
));
2696 void WebContentsImpl::OnDidLoadResourceFromMemoryCache(
2698 const std::string
& security_info
,
2699 const std::string
& http_method
,
2700 const std::string
& mime_type
,
2701 ResourceType resource_type
) {
2702 base::StatsCounter
cache("WebKit.CacheHit");
2705 // Send out a notification that we loaded a resource from our memory cache.
2707 net::CertStatus cert_status
= 0;
2708 int security_bits
= -1;
2709 int connection_status
= 0;
2710 SignedCertificateTimestampIDStatusList signed_certificate_timestamp_ids
;
2711 DeserializeSecurityInfo(security_info
, &cert_id
, &cert_status
,
2712 &security_bits
, &connection_status
,
2713 &signed_certificate_timestamp_ids
);
2714 // TODO(alcutter,eranm): Pass signed_certificate_timestamp_ids into details
2715 LoadFromMemoryCacheDetails
details(
2716 url
, GetRenderProcessHost()->GetID(), cert_id
, cert_status
, http_method
,
2717 mime_type
, resource_type
);
2719 controller_
.ssl_manager()->DidLoadFromMemoryCache(details
);
2721 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2722 DidLoadResourceFromMemoryCache(details
));
2724 if (url
.is_valid() && url
.SchemeIsHTTPOrHTTPS()) {
2725 scoped_refptr
<net::URLRequestContextGetter
> request_context(
2726 resource_type
== RESOURCE_TYPE_MEDIA
?
2727 GetBrowserContext()->GetMediaRequestContextForRenderProcess(
2728 GetRenderProcessHost()->GetID()) :
2729 GetBrowserContext()->GetRequestContextForRenderProcess(
2730 GetRenderProcessHost()->GetID()));
2731 BrowserThread::PostTask(
2734 base::Bind(&NotifyCacheOnIO
, request_context
, url
, http_method
));
2738 void WebContentsImpl::OnDidDisplayInsecureContent() {
2739 RecordAction(base::UserMetricsAction("SSL.DisplayedInsecureContent"));
2740 displayed_insecure_content_
= true;
2741 SSLManager::NotifySSLInternalStateChanged(
2742 GetController().GetBrowserContext());
2745 void WebContentsImpl::OnDidRunInsecureContent(
2746 const std::string
& security_origin
, const GURL
& target_url
) {
2747 LOG(WARNING
) << security_origin
<< " ran insecure content from "
2748 << target_url
.possibly_invalid_spec();
2749 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
2750 if (EndsWith(security_origin
, kDotGoogleDotCom
, false))
2751 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
2752 controller_
.ssl_manager()->DidRunInsecureContent(security_origin
);
2753 displayed_insecure_content_
= true;
2754 SSLManager::NotifySSLInternalStateChanged(
2755 GetController().GetBrowserContext());
2758 void WebContentsImpl::OnDocumentLoadedInFrame() {
2759 CHECK(render_frame_message_source_
);
2760 CHECK(!render_view_message_source_
);
2761 RenderFrameHostImpl
* rfh
=
2762 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2764 WebContentsObserver
, observers_
, DocumentLoadedInFrame(rfh
));
2767 void WebContentsImpl::OnDidFinishLoad(
2769 if (!render_frame_message_source_
) {
2770 RecordAction(base::UserMetricsAction("BadMessageTerminate_RVD2"));
2771 GetRenderProcessHost()->ReceivedBadMessage();
2775 GURL
validated_url(url
);
2776 RenderProcessHost
* render_process_host
=
2777 render_frame_message_source_
->GetProcess();
2778 render_process_host
->FilterURL(false, &validated_url
);
2780 RenderFrameHostImpl
* rfh
=
2781 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2783 WebContentsObserver
, observers_
, DidFinishLoad(rfh
, validated_url
));
2786 void WebContentsImpl::OnDidStartLoading(bool to_different_document
) {
2787 RenderFrameHostImpl
* rfh
=
2788 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2789 int64 render_frame_id
= rfh
->frame_tree_node()->frame_tree_node_id();
2791 // Any main frame load to a new document should reset the load progress, since
2792 // it will replace the current page and any frames.
2793 if (to_different_document
&& !rfh
->GetParent()) {
2794 ResetLoadProgressState();
2795 loading_frames_in_progress_
= 0;
2796 rfh
->frame_tree_node()->set_is_loading(false);
2799 // It is possible to get multiple calls to OnDidStartLoading that don't have
2800 // corresponding calls to OnDidStopLoading:
2801 // - With "swappedout://" URLs, this happens when a RenderView gets swapped
2802 // out for a cross-process navigation, and it turns into a placeholder for
2803 // one being rendered in a different process.
2804 // - Also, there might be more than one RenderFrameHost sharing the same
2805 // FrameTreeNode (and thus sharing its ID) each sending a start.
2806 // - But in the future, once clamy@ moves navigation network requests to the
2807 // browser process, there's a good chance that callbacks about starting and
2808 // stopping will all be handled by the browser. When that happens, there
2809 // should no longer be a start/stop call imbalance. TODO(avi): When this
2810 // future arrives, update this code to not allow this case.
2811 if (rfh
->frame_tree_node()->is_loading())
2814 DCHECK_GE(loading_frames_in_progress_
, 0);
2815 if (loading_frames_in_progress_
== 0)
2816 DidStartLoading(rfh
, to_different_document
);
2818 ++loading_frames_in_progress_
;
2819 rfh
->frame_tree_node()->set_is_loading(true);
2821 // Notify the RenderFrameHostManager of the event.
2822 rfh
->frame_tree_node()->render_manager()->OnDidStartLoading();
2824 loading_progresses_
[render_frame_id
] = kMinimumLoadingProgress
;
2825 SendLoadProgressChanged();
2828 void WebContentsImpl::OnDidStopLoading() {
2829 RenderFrameHostImpl
* rfh
=
2830 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2831 int64 render_frame_id
= rfh
->frame_tree_node()->frame_tree_node_id();
2832 rfh
->frame_tree_node()->set_is_loading(false);
2834 if (loading_progresses_
.find(render_frame_id
) != loading_progresses_
.end()) {
2835 // Load stopped while we were still tracking load. Make sure we update
2836 // progress based on this frame's completion.
2837 loading_progresses_
[render_frame_id
] = 1.0;
2838 SendLoadProgressChanged();
2839 // Then we clean-up our states.
2840 if (loading_total_progress_
== 1.0)
2841 ResetLoadProgressState();
2844 // Notify the RenderFrameHostManager of the event.
2845 rfh
->frame_tree_node()->render_manager()->OnDidStopLoading();
2847 // TODO(japhet): This should be a DCHECK, but the pdf plugin sometimes
2848 // calls DidStopLoading() without a matching DidStartLoading().
2849 if (loading_frames_in_progress_
== 0)
2851 --loading_frames_in_progress_
;
2852 if (loading_frames_in_progress_
== 0)
2853 DidStopLoading(rfh
);
2856 void WebContentsImpl::OnDidChangeLoadProgress(double load_progress
) {
2857 RenderFrameHostImpl
* rfh
=
2858 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2859 int64 render_frame_id
= rfh
->frame_tree_node()->frame_tree_node_id();
2861 loading_progresses_
[render_frame_id
] = load_progress
;
2863 // We notify progress change immediately for the first and last updates.
2864 // Also, since the message loop may be pretty busy when a page is loaded, it
2865 // might not execute a posted task in a timely manner so we make sure to
2866 // immediately send progress report if enough time has passed.
2867 base::TimeDelta min_delay
=
2868 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS
);
2869 if (load_progress
== 1.0 || loading_last_progress_update_
.is_null() ||
2870 base::TimeTicks::Now() - loading_last_progress_update_
> min_delay
) {
2871 // If there is a pending task to send progress, it is now obsolete.
2872 loading_weak_factory_
.InvalidateWeakPtrs();
2873 SendLoadProgressChanged();
2874 if (loading_total_progress_
== 1.0)
2875 ResetLoadProgressState();
2879 if (loading_weak_factory_
.HasWeakPtrs())
2882 base::MessageLoop::current()->PostDelayedTask(
2884 base::Bind(&WebContentsImpl::SendLoadProgressChanged
,
2885 loading_weak_factory_
.GetWeakPtr()),
2889 void WebContentsImpl::OnGoToEntryAtOffset(int offset
) {
2890 if (!delegate_
|| delegate_
->OnGoToEntryOffset(offset
))
2891 controller_
.GoToOffset(offset
);
2894 void WebContentsImpl::OnUpdateZoomLimits(int minimum_percent
,
2895 int maximum_percent
) {
2896 minimum_zoom_percent_
= minimum_percent
;
2897 maximum_zoom_percent_
= maximum_percent
;
2900 void WebContentsImpl::OnEnumerateDirectory(int request_id
,
2901 const base::FilePath
& path
) {
2905 ChildProcessSecurityPolicyImpl
* policy
=
2906 ChildProcessSecurityPolicyImpl::GetInstance();
2907 if (policy
->CanReadFile(GetRenderProcessHost()->GetID(), path
))
2908 delegate_
->EnumerateDirectory(this, request_id
, path
);
2911 void WebContentsImpl::OnRegisterProtocolHandler(const std::string
& protocol
,
2913 const base::string16
& title
,
2914 bool user_gesture
) {
2918 ChildProcessSecurityPolicyImpl
* policy
=
2919 ChildProcessSecurityPolicyImpl::GetInstance();
2920 if (policy
->IsPseudoScheme(protocol
))
2923 delegate_
->RegisterProtocolHandler(this, protocol
, url
, user_gesture
);
2926 void WebContentsImpl::OnUnregisterProtocolHandler(const std::string
& protocol
,
2928 bool user_gesture
) {
2932 ChildProcessSecurityPolicyImpl
* policy
=
2933 ChildProcessSecurityPolicyImpl::GetInstance();
2934 if (policy
->IsPseudoScheme(protocol
))
2937 delegate_
->UnregisterProtocolHandler(this, protocol
, url
, user_gesture
);
2940 void WebContentsImpl::OnFindReply(int request_id
,
2941 int number_of_matches
,
2942 const gfx::Rect
& selection_rect
,
2943 int active_match_ordinal
,
2944 bool final_update
) {
2946 delegate_
->FindReply(this, request_id
, number_of_matches
, selection_rect
,
2947 active_match_ordinal
, final_update
);
2951 #if defined(OS_ANDROID)
2952 void WebContentsImpl::OnFindMatchRectsReply(
2954 const std::vector
<gfx::RectF
>& rects
,
2955 const gfx::RectF
& active_rect
) {
2957 delegate_
->FindMatchRectsReply(this, version
, rects
, active_rect
);
2960 void WebContentsImpl::OnOpenDateTimeDialog(
2961 const ViewHostMsg_DateTimeDialogValue_Params
& value
) {
2962 date_time_chooser_
->ShowDialog(GetTopLevelNativeWindow(),
2963 GetRenderViewHost(),
2973 void WebContentsImpl::OnDomOperationResponse(const std::string
& json_string
,
2974 int automation_id
) {
2975 DomOperationNotificationDetails
details(json_string
, automation_id
);
2976 NotificationService::current()->Notify(
2977 NOTIFICATION_DOM_OPERATION_RESPONSE
,
2978 Source
<WebContents
>(this),
2979 Details
<DomOperationNotificationDetails
>(&details
));
2982 void WebContentsImpl::OnAppCacheAccessed(const GURL
& manifest_url
,
2983 bool blocked_by_policy
) {
2984 // Notify observers about navigation.
2985 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2986 AppCacheAccessed(manifest_url
, blocked_by_policy
));
2989 void WebContentsImpl::OnOpenColorChooser(
2990 int color_chooser_id
,
2992 const std::vector
<ColorSuggestion
>& suggestions
) {
2993 ColorChooser
* new_color_chooser
= delegate_
?
2994 delegate_
->OpenColorChooser(this, color
, suggestions
) :
2996 if (!new_color_chooser
)
2998 if (color_chooser_info_
.get())
2999 color_chooser_info_
->chooser
->End();
3001 color_chooser_info_
.reset(new ColorChooserInfo(
3002 render_frame_message_source_
->GetProcess()->GetID(),
3003 render_frame_message_source_
->GetRoutingID(),
3008 void WebContentsImpl::OnEndColorChooser(int color_chooser_id
) {
3009 if (color_chooser_info_
&&
3010 color_chooser_id
== color_chooser_info_
->identifier
)
3011 color_chooser_info_
->chooser
->End();
3014 void WebContentsImpl::OnSetSelectedColorInColorChooser(int color_chooser_id
,
3016 if (color_chooser_info_
&&
3017 color_chooser_id
== color_chooser_info_
->identifier
)
3018 color_chooser_info_
->chooser
->SetSelectedColor(color
);
3021 // This exists for render views that don't have a WebUI, but do have WebUI
3022 // bindings enabled.
3023 void WebContentsImpl::OnWebUISend(const GURL
& source_url
,
3024 const std::string
& name
,
3025 const base::ListValue
& args
) {
3027 delegate_
->WebUISend(this, source_url
, name
, args
);
3030 #if defined(ENABLE_PLUGINS)
3031 void WebContentsImpl::OnPepperPluginHung(int plugin_child_id
,
3032 const base::FilePath
& path
,
3034 UMA_HISTOGRAM_COUNTS("Pepper.PluginHung", 1);
3036 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3037 PluginHungStatusChanged(plugin_child_id
, path
, is_hung
));
3040 void WebContentsImpl::OnPluginCrashed(const base::FilePath
& plugin_path
,
3041 base::ProcessId plugin_pid
) {
3042 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3043 PluginCrashed(plugin_path
, plugin_pid
));
3046 void WebContentsImpl::OnRequestPpapiBrokerPermission(
3049 const base::FilePath
& plugin_path
) {
3051 OnPpapiBrokerPermissionResult(routing_id
, false);
3055 if (!delegate_
->RequestPpapiBrokerPermission(
3056 this, url
, plugin_path
,
3057 base::Bind(&WebContentsImpl::OnPpapiBrokerPermissionResult
,
3058 base::Unretained(this), routing_id
))) {
3060 OnPpapiBrokerPermissionResult(routing_id
, false);
3064 void WebContentsImpl::OnPpapiBrokerPermissionResult(int routing_id
,
3066 Send(new ViewMsg_PpapiBrokerPermissionResult(routing_id
, result
));
3069 void WebContentsImpl::OnBrowserPluginMessage(const IPC::Message
& message
) {
3070 // This creates a BrowserPluginEmbedder, which handles all the BrowserPlugin
3071 // specific messages for this WebContents. This means that any message from
3072 // a BrowserPlugin prior to this will be ignored.
3073 // For more info, see comment above classes BrowserPluginEmbedder and
3074 // BrowserPluginGuest.
3075 CHECK(!browser_plugin_embedder_
.get());
3076 browser_plugin_embedder_
.reset(BrowserPluginEmbedder::Create(this));
3077 browser_plugin_embedder_
->OnMessageReceived(message
);
3079 #endif // defined(ENABLE_PLUGINS)
3081 void WebContentsImpl::OnDidDownloadImage(
3083 int http_status_code
,
3084 const GURL
& image_url
,
3085 const std::vector
<SkBitmap
>& bitmaps
,
3086 const std::vector
<gfx::Size
>& original_bitmap_sizes
) {
3087 if (bitmaps
.size() != original_bitmap_sizes
.size())
3090 ImageDownloadMap::iterator iter
= image_download_map_
.find(id
);
3091 if (iter
== image_download_map_
.end()) {
3092 // Currently WebContents notifies us of ANY downloads so that it is
3093 // possible to get here.
3096 if (!iter
->second
.is_null()) {
3098 id
, http_status_code
, image_url
, bitmaps
, original_bitmap_sizes
);
3100 image_download_map_
.erase(id
);
3103 void WebContentsImpl::OnUpdateFaviconURL(
3104 const std::vector
<FaviconURL
>& candidates
) {
3105 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3106 DidUpdateFaviconURL(candidates
));
3109 void WebContentsImpl::CreateAudioPowerSaveBlocker() {
3110 // ChromeOS has its own way of handling power save blocks for media.
3111 #if !defined(OS_CHROMEOS)
3112 DCHECK(!audio_power_save_blocker_
);
3113 audio_power_save_blocker_
= PowerSaveBlocker::Create(
3114 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension
, "Playing Audio");
3118 void WebContentsImpl::CreateVideoPowerSaveBlocker() {
3119 // ChromeOS has its own way of handling power save blocks for media.
3120 #if !defined(OS_CHROMEOS)
3121 DCHECK(!video_power_save_blocker_
);
3122 DCHECK(!active_video_players_
.empty());
3123 video_power_save_blocker_
= PowerSaveBlocker::Create(
3124 PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep
, "Playing Video");
3125 #if defined(OS_ANDROID)
3126 static_cast<PowerSaveBlockerImpl
*>(video_power_save_blocker_
.get())
3127 ->InitDisplaySleepBlocker(GetView()->GetNativeView());
3132 void WebContentsImpl::MaybeReleasePowerSaveBlockers() {
3133 // If there are no more audio players and we don't have audio stream
3134 // monitoring, release the audio power save blocker here instead of during
3135 // NotifyNavigationStateChanged().
3136 if (active_audio_players_
.empty() &&
3137 !AudioStreamMonitor::monitoring_available()) {
3138 audio_power_save_blocker_
.reset();
3141 // If there are no more video players, clear the video power save blocker.
3142 if (active_video_players_
.empty())
3143 video_power_save_blocker_
.reset();
3146 void WebContentsImpl::OnMediaPlayingNotification(int64 player_cookie
,
3150 // Ignore the videos playing remotely and don't hold the wake lock for the
3152 if (is_remote
) return;
3155 AddMediaPlayerEntry(player_cookie
, &active_audio_players_
);
3157 // If we don't have audio stream monitoring, allocate the audio power save
3158 // blocker here instead of during NotifyNavigationStateChanged().
3159 if (!audio_power_save_blocker_
&&
3160 !AudioStreamMonitor::monitoring_available()) {
3161 CreateAudioPowerSaveBlocker();
3166 AddMediaPlayerEntry(player_cookie
, &active_video_players_
);
3168 // If we're not hidden and have just created a player, create a blocker.
3169 if (!video_power_save_blocker_
&& !IsHidden())
3170 CreateVideoPowerSaveBlocker();
3174 void WebContentsImpl::OnMediaPausedNotification(int64 player_cookie
) {
3175 RemoveMediaPlayerEntry(player_cookie
, &active_audio_players_
);
3176 RemoveMediaPlayerEntry(player_cookie
, &active_video_players_
);
3177 MaybeReleasePowerSaveBlockers();
3180 void WebContentsImpl::OnFirstVisuallyNonEmptyPaint() {
3181 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3182 DidFirstVisuallyNonEmptyPaint());
3185 void WebContentsImpl::DidChangeVisibleSSLState() {
3187 delegate_
->VisibleSSLStateChanged(this);
3190 void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
3191 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3192 BeforeFormRepostWarningShow());
3195 void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
3198 delegate_
->ShowRepostFormWarningDialog(this);
3201 bool WebContentsImpl::HasAccessedInitialDocument() {
3202 return has_accessed_initial_document_
;
3205 // Notifies the RenderWidgetHost instance about the fact that the page is
3206 // loading, or done loading.
3207 void WebContentsImpl::SetIsLoading(RenderViewHost
* render_view_host
,
3209 bool to_different_document
,
3210 LoadNotificationDetails
* details
) {
3211 if (is_loading
== is_loading_
)
3215 load_state_
= net::LoadStateWithParam(net::LOAD_STATE_IDLE
,
3217 load_state_host_
.clear();
3219 upload_position_
= 0;
3222 GetRenderManager()->SetIsLoading(is_loading
);
3224 is_loading_
= is_loading
;
3225 waiting_for_response_
= is_loading
;
3226 is_load_to_different_document_
= to_different_document
;
3229 delegate_
->LoadingStateChanged(this, to_different_document
);
3230 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD
);
3232 std::string url
= (details
? details
->url
.possibly_invalid_spec() : "NULL");
3234 TRACE_EVENT_ASYNC_BEGIN1("browser,navigation", "WebContentsImpl Loading",
3236 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3237 DidStartLoading(render_view_host
));
3239 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
3241 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3242 DidStopLoading(render_view_host
));
3245 // TODO(avi): Remove. http://crbug.com/170921
3246 int type
= is_loading
? NOTIFICATION_LOAD_START
: NOTIFICATION_LOAD_STOP
;
3247 NotificationDetails det
= NotificationService::NoDetails();
3249 det
= Details
<LoadNotificationDetails
>(details
);
3250 NotificationService::current()->Notify(
3251 type
, Source
<NavigationController
>(&controller_
), det
);
3254 void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point
& extent
) {
3255 RenderFrameHost
* focused_frame
= GetFocusedFrame();
3259 focused_frame
->Send(new InputMsg_MoveRangeSelectionExtent(
3260 focused_frame
->GetRoutingID(), extent
));
3263 void WebContentsImpl::SelectRange(const gfx::Point
& base
,
3264 const gfx::Point
& extent
) {
3265 RenderFrameHost
* focused_frame
= GetFocusedFrame();
3269 focused_frame
->Send(
3270 new InputMsg_SelectRange(focused_frame
->GetRoutingID(), base
, extent
));
3273 void WebContentsImpl::UpdateMaxPageIDIfNecessary(RenderViewHost
* rvh
) {
3274 // If we are creating a RVH for a restored controller, then we need to make
3275 // sure the RenderView starts with a next_page_id_ larger than the number
3276 // of restored entries. This must be called before the RenderView starts
3277 // navigating (to avoid a race between the browser updating max_page_id and
3278 // the renderer updating next_page_id_). Because of this, we only call this
3279 // from CreateRenderView and allow that to notify the RenderView for us.
3280 int max_restored_page_id
= controller_
.GetMaxRestoredPageID();
3281 if (max_restored_page_id
>
3282 GetMaxPageIDForSiteInstance(rvh
->GetSiteInstance()))
3283 UpdateMaxPageIDForSiteInstance(rvh
->GetSiteInstance(),
3284 max_restored_page_id
);
3287 bool WebContentsImpl::UpdateTitleForEntry(NavigationEntryImpl
* entry
,
3288 const base::string16
& title
) {
3289 // For file URLs without a title, use the pathname instead. In the case of a
3290 // synthesized title, we don't want the update to count toward the "one set
3291 // per page of the title to history."
3292 base::string16 final_title
;
3294 if (entry
&& entry
->GetURL().SchemeIsFile() && title
.empty()) {
3295 final_title
= base::UTF8ToUTF16(entry
->GetURL().ExtractFileName());
3296 explicit_set
= false; // Don't count synthetic titles toward the set limit.
3298 base::TrimWhitespace(title
, base::TRIM_ALL
, &final_title
);
3299 explicit_set
= true;
3302 // If a page is created via window.open and never navigated,
3303 // there will be no navigation entry. In this situation,
3304 // |page_title_when_no_navigation_entry_| will be used for page title.
3306 if (final_title
== entry
->GetTitle())
3307 return false; // Nothing changed, don't bother.
3309 entry
->SetTitle(final_title
);
3311 if (page_title_when_no_navigation_entry_
== final_title
)
3312 return false; // Nothing changed, don't bother.
3314 page_title_when_no_navigation_entry_
= final_title
;
3317 // Lastly, set the title for the view.
3318 view_
->SetPageTitle(final_title
);
3320 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3321 TitleWasSet(entry
, explicit_set
));
3323 // TODO(avi): Remove. http://crbug.com/170921
3324 std::pair
<NavigationEntry
*, bool> details
=
3325 std::make_pair(entry
, explicit_set
);
3326 NotificationService::current()->Notify(
3327 NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED
,
3328 Source
<WebContents
>(this),
3329 Details
<std::pair
<NavigationEntry
*, bool> >(&details
));
3334 void WebContentsImpl::SendLoadProgressChanged() {
3335 loading_last_progress_update_
= base::TimeTicks::Now();
3336 double progress
= 0.0;
3337 int frame_count
= 0;
3339 for (LoadingProgressMap::iterator it
= loading_progresses_
.begin();
3340 it
!= loading_progresses_
.end();
3342 progress
+= it
->second
;
3345 if (frame_count
== 0)
3347 progress
/= frame_count
;
3348 DCHECK(progress
<= 1.0);
3350 if (progress
<= loading_total_progress_
)
3352 loading_total_progress_
= progress
;
3355 delegate_
->LoadProgressChanged(this, progress
);
3358 void WebContentsImpl::ResetLoadProgressState() {
3359 loading_progresses_
.clear();
3360 loading_total_progress_
= 0.0;
3361 loading_weak_factory_
.InvalidateWeakPtrs();
3362 loading_last_progress_update_
= base::TimeTicks();
3365 void WebContentsImpl::NotifyViewSwapped(RenderViewHost
* old_host
,
3366 RenderViewHost
* new_host
) {
3367 // After sending out a swap notification, we need to send a disconnect
3368 // notification so that clients that pick up a pointer to |this| can NULL the
3369 // pointer. See Bug 1230284.
3370 notify_disconnection_
= true;
3371 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3372 RenderViewHostChanged(old_host
, new_host
));
3374 // TODO(avi): Remove. http://crbug.com/170921
3375 std::pair
<RenderViewHost
*, RenderViewHost
*> details
=
3376 std::make_pair(old_host
, new_host
);
3377 NotificationService::current()->Notify(
3378 NOTIFICATION_RENDER_VIEW_HOST_CHANGED
,
3379 Source
<WebContents
>(this),
3380 Details
<std::pair
<RenderViewHost
*, RenderViewHost
*> >(&details
));
3382 // Ensure that the associated embedder gets cleared after a RenderViewHost
3383 // gets swapped, so we don't reuse the same embedder next time a
3384 // RenderViewHost is attached to this WebContents.
3385 RemoveBrowserPluginEmbedder();
3388 void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost
* old_host
,
3389 RenderFrameHost
* new_host
) {
3390 FOR_EACH_OBSERVER(WebContentsObserver
,
3392 RenderFrameHostChanged(old_host
, new_host
));
3395 // TODO(avi): Remove this entire function because this notification is already
3396 // covered by two observer functions. http://crbug.com/170921
3397 void WebContentsImpl::NotifyDisconnected() {
3398 if (!notify_disconnection_
)
3401 notify_disconnection_
= false;
3402 NotificationService::current()->Notify(
3403 NOTIFICATION_WEB_CONTENTS_DISCONNECTED
,
3404 Source
<WebContents
>(this),
3405 NotificationService::NoDetails());
3408 void WebContentsImpl::NotifyNavigationEntryCommitted(
3409 const LoadCommittedDetails
& load_details
) {
3411 WebContentsObserver
, observers_
, NavigationEntryCommitted(load_details
));
3414 bool WebContentsImpl::OnMessageReceived(RenderFrameHost
* render_frame_host
,
3415 const IPC::Message
& message
) {
3416 return OnMessageReceived(NULL
, render_frame_host
, message
);
3419 const GURL
& WebContentsImpl::GetMainFrameLastCommittedURL() const {
3420 return GetLastCommittedURL();
3423 void WebContentsImpl::RenderFrameCreated(RenderFrameHost
* render_frame_host
) {
3424 // Note this is only for subframes, the notification for the main frame
3425 // happens in RenderViewCreated.
3426 FOR_EACH_OBSERVER(WebContentsObserver
,
3428 RenderFrameCreated(render_frame_host
));
3429 SetAccessibilityModeOnFrame(accessibility_mode_
, render_frame_host
);
3432 void WebContentsImpl::RenderFrameDeleted(RenderFrameHost
* render_frame_host
) {
3433 ClearPowerSaveBlockers(render_frame_host
);
3434 FOR_EACH_OBSERVER(WebContentsObserver
,
3436 RenderFrameDeleted(render_frame_host
));
3439 void WebContentsImpl::WorkerCrashed(RenderFrameHost
* render_frame_host
) {
3441 delegate_
->WorkerCrashed(this);
3444 void WebContentsImpl::ShowContextMenu(RenderFrameHost
* render_frame_host
,
3445 const ContextMenuParams
& params
) {
3446 ContextMenuParams
context_menu_params(params
);
3447 // Allow WebContentsDelegates to handle the context menu operation first.
3448 if (GetBrowserPluginGuest()) {
3449 WebContentsViewGuest
* view_guest
=
3450 static_cast<WebContentsViewGuest
*>(GetView());
3451 context_menu_params
= view_guest
->ConvertContextMenuParams(params
);
3453 if (delegate_
&& delegate_
->HandleContextMenu(context_menu_params
))
3456 render_view_host_delegate_view_
->ShowContextMenu(render_frame_host
,
3457 context_menu_params
);
3460 void WebContentsImpl::RunJavaScriptMessage(
3461 RenderFrameHost
* render_frame_host
,
3462 const base::string16
& message
,
3463 const base::string16
& default_prompt
,
3464 const GURL
& frame_url
,
3465 JavaScriptMessageType javascript_message_type
,
3466 IPC::Message
* reply_msg
) {
3467 // Suppress JavaScript dialogs when requested. Also suppress messages when
3468 // showing an interstitial as it's shown over the previous page and we don't
3469 // want the hidden page's dialogs to interfere with the interstitial.
3470 bool suppress_this_message
=
3471 static_cast<RenderFrameHostImpl
*>(render_frame_host
)->is_swapped_out() ||
3472 ShowingInterstitialPage() || !delegate_
||
3473 delegate_
->ShouldSuppressDialogs(this) ||
3474 !delegate_
->GetJavaScriptDialogManager(this);
3476 if (!suppress_this_message
) {
3477 std::string accept_lang
= GetContentClient()->browser()->
3478 GetAcceptLangs(GetBrowserContext());
3479 dialog_manager_
= delegate_
->GetJavaScriptDialogManager(this);
3480 dialog_manager_
->RunJavaScriptDialog(
3482 frame_url
.GetOrigin(),
3484 javascript_message_type
,
3487 base::Bind(&WebContentsImpl::OnDialogClosed
,
3488 base::Unretained(this),
3489 render_frame_host
->GetProcess()->GetID(),
3490 render_frame_host
->GetRoutingID(),
3493 &suppress_this_message
);
3496 if (suppress_this_message
) {
3497 // If we are suppressing messages, just reply as if the user immediately
3498 // pressed "Cancel", passing true to |dialog_was_suppressed|.
3499 OnDialogClosed(render_frame_host
->GetProcess()->GetID(),
3500 render_frame_host
->GetRoutingID(), reply_msg
,
3501 true, false, base::string16());
3504 // OnDialogClosed (two lines up) may have caused deletion of this object (see
3505 // http://crbug.com/288961 ). The only safe thing to do here is return.
3508 void WebContentsImpl::RunBeforeUnloadConfirm(
3509 RenderFrameHost
* render_frame_host
,
3510 const base::string16
& message
,
3512 IPC::Message
* reply_msg
) {
3513 RenderFrameHostImpl
* rfhi
=
3514 static_cast<RenderFrameHostImpl
*>(render_frame_host
);
3516 delegate_
->WillRunBeforeUnloadConfirm();
3518 bool suppress_this_message
=
3519 rfhi
->rfh_state() != RenderFrameHostImpl::STATE_DEFAULT
|| !delegate_
||
3520 delegate_
->ShouldSuppressDialogs(this) ||
3521 !delegate_
->GetJavaScriptDialogManager(this);
3522 if (suppress_this_message
) {
3523 rfhi
->JavaScriptDialogClosed(reply_msg
, true, base::string16(), true);
3527 is_showing_before_unload_dialog_
= true;
3528 dialog_manager_
= delegate_
->GetJavaScriptDialogManager(this);
3529 dialog_manager_
->RunBeforeUnloadDialog(
3530 this, message
, is_reload
,
3531 base::Bind(&WebContentsImpl::OnDialogClosed
, base::Unretained(this),
3532 render_frame_host
->GetProcess()->GetID(),
3533 render_frame_host
->GetRoutingID(), reply_msg
,
3537 WebContents
* WebContentsImpl::GetAsWebContents() {
3541 bool WebContentsImpl::IsNeverVisible() {
3544 return delegate_
->IsNeverVisible(this);
3548 gfx::NativeViewAccessible
WebContentsImpl::GetParentNativeViewAccessible() {
3549 return accessible_parent_
;
3553 RenderViewHostDelegateView
* WebContentsImpl::GetDelegateView() {
3554 return render_view_host_delegate_view_
;
3557 RendererPreferences
WebContentsImpl::GetRendererPrefs(
3558 BrowserContext
* browser_context
) const {
3559 return renderer_preferences_
;
3562 gfx::Rect
WebContentsImpl::GetRootWindowResizerRect() const {
3564 return delegate_
->GetRootWindowResizerRect();
3568 void WebContentsImpl::RemoveBrowserPluginEmbedder() {
3569 if (browser_plugin_embedder_
)
3570 browser_plugin_embedder_
.reset();
3573 void WebContentsImpl::RenderViewCreated(RenderViewHost
* render_view_host
) {
3574 // Don't send notifications if we are just creating a swapped-out RVH for
3575 // the opener chain. These won't be used for view-source or WebUI, so it's
3576 // ok to return early.
3577 if (!static_cast<RenderViewHostImpl
*>(render_view_host
)->is_active())
3581 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
3583 NotificationService::current()->Notify(
3584 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED
,
3585 Source
<WebContents
>(this),
3586 Details
<RenderViewHost
>(render_view_host
));
3588 // When we're creating views, we're still doing initial setup, so we always
3589 // use the pending Web UI rather than any possibly existing committed one.
3590 if (GetRenderManager()->pending_web_ui())
3591 GetRenderManager()->pending_web_ui()->RenderViewCreated(render_view_host
);
3593 NavigationEntry
* entry
= controller_
.GetPendingEntry();
3594 if (entry
&& entry
->IsViewSourceMode()) {
3595 // Put the renderer in view source mode.
3596 render_view_host
->Send(
3597 new ViewMsg_EnableViewSourceMode(render_view_host
->GetRoutingID()));
3600 view_
->RenderViewCreated(render_view_host
);
3603 WebContentsObserver
, observers_
, RenderViewCreated(render_view_host
));
3605 // We tell the observers now instead of when the main RenderFrameHostImpl is
3606 // constructed because otherwise it would be too early (i.e. IPCs sent to the
3607 // frame would be dropped because it's not created yet).
3608 RenderFrameHost
* main_frame
= render_view_host
->GetMainFrame();
3610 WebContentsObserver
, observers_
, RenderFrameCreated(main_frame
));
3611 SetAccessibilityModeOnFrame(accessibility_mode_
, main_frame
);
3613 DevToolsManager::GetInstance()->RenderViewCreated(this, render_view_host
);
3616 void WebContentsImpl::RenderViewReady(RenderViewHost
* rvh
) {
3617 if (rvh
!= GetRenderViewHost()) {
3618 // Don't notify the world, since this came from a renderer in the
3623 notify_disconnection_
= true;
3624 // TODO(avi): Remove. http://crbug.com/170921
3625 NotificationService::current()->Notify(
3626 NOTIFICATION_WEB_CONTENTS_CONNECTED
,
3627 Source
<WebContents
>(this),
3628 NotificationService::NoDetails());
3630 bool was_crashed
= IsCrashed();
3631 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING
, 0);
3633 // Restore the focus to the tab (otherwise the focus will be on the top
3635 if (was_crashed
&& !FocusLocationBarByDefault() &&
3636 (!delegate_
|| delegate_
->ShouldFocusPageAfterCrash())) {
3640 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, RenderViewReady());
3643 void WebContentsImpl::RenderViewTerminated(RenderViewHost
* rvh
,
3644 base::TerminationStatus status
,
3646 if (rvh
!= GetRenderViewHost()) {
3647 // The pending page's RenderViewHost is gone.
3651 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
3652 // renderer may not have made a clean exit.
3653 if (IsFullscreenForCurrentTab())
3654 ExitFullscreenMode();
3656 // Cancel any visible dialogs so they are not left dangling over the sad tab.
3657 if (dialog_manager_
)
3658 dialog_manager_
->CancelActiveAndPendingDialogs(this);
3661 delegate_
->HideValidationMessage(this);
3663 SetIsLoading(rvh
, false, true, NULL
);
3664 NotifyDisconnected();
3665 SetIsCrashed(status
, error_code
);
3667 // Reset the loading progress. TODO(avi): What does it mean to have a
3668 // "renderer crash" when there is more than one renderer process serving a
3669 // webpage? Once this function is called at a more granular frame level, we
3670 // probably will need to more granularly reset the state here.
3671 ResetLoadProgressState();
3672 loading_frames_in_progress_
= 0;
3674 FOR_EACH_OBSERVER(WebContentsObserver
,
3676 RenderProcessGone(GetCrashedStatus()));
3679 void WebContentsImpl::RenderViewDeleted(RenderViewHost
* rvh
) {
3680 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, RenderViewDeleted(rvh
));
3683 void WebContentsImpl::UpdateState(RenderViewHost
* rvh
,
3685 const PageState
& page_state
) {
3686 // Ensure that this state update comes from a RenderViewHost that belongs to
3687 // this WebContents.
3688 // TODO(nasko): This should go through RenderFrameHost.
3689 // TODO(creis): We can't update state for cross-process subframes until we
3690 // have FrameNavigationEntries. Once we do, this should be a DCHECK.
3691 if (rvh
->GetDelegate()->GetAsWebContents() != this)
3694 // We must be prepared to handle state updates for any page, these occur
3695 // when the user is scrolling and entering form data, as well as when we're
3696 // leaving a page, in which case our state may have already been moved to
3697 // the next page. The navigation controller will look up the appropriate
3698 // NavigationEntry and update it when it is notified via the delegate.
3700 int entry_index
= controller_
.GetEntryIndexWithPageID(
3701 rvh
->GetSiteInstance(), page_id
);
3702 if (entry_index
< 0)
3704 NavigationEntry
* entry
= controller_
.GetEntryAtIndex(entry_index
);
3706 if (page_state
== entry
->GetPageState())
3707 return; // Nothing to update.
3708 entry
->SetPageState(page_state
);
3709 controller_
.NotifyEntryChanged(entry
, entry_index
);
3712 void WebContentsImpl::UpdateTargetURL(RenderViewHost
* render_view_host
,
3714 if (fullscreen_widget_routing_id_
!= MSG_ROUTING_NONE
) {
3715 // If we're fullscreen only update the url if it's from the fullscreen
3717 RenderWidgetHostView
* fs
= GetFullscreenRenderWidgetHostView();
3718 if (fs
&& fs
->GetRenderWidgetHost() != render_view_host
)
3722 delegate_
->UpdateTargetURL(this, url
);
3725 void WebContentsImpl::Close(RenderViewHost
* rvh
) {
3726 #if defined(OS_MACOSX)
3727 // The UI may be in an event-tracking loop, such as between the
3728 // mouse-down and mouse-up in text selection or a button click.
3729 // Defer the close until after tracking is complete, so that we
3730 // don't free objects out from under the UI.
3731 // TODO(shess): This could get more fine-grained. For instance,
3732 // closing a tab in another window while selecting text in the
3733 // current window's Omnibox should be just fine.
3734 if (view_
->IsEventTracking()) {
3735 view_
->CloseTabAfterEventTracking();
3740 // Ignore this if it comes from a RenderViewHost that we aren't showing.
3741 if (delegate_
&& rvh
== GetRenderViewHost())
3742 delegate_
->CloseContents(this);
3745 void WebContentsImpl::SwappedOut(RenderFrameHost
* rfh
) {
3746 if (delegate_
&& rfh
->GetRenderViewHost() == GetRenderViewHost())
3747 delegate_
->SwappedOut(this);
3750 void WebContentsImpl::DidDeferAfterResponseStarted(
3751 const TransitionLayerData
& transition_data
) {
3752 #if defined(OS_ANDROID)
3753 GetWebContentsAndroid()->DidDeferAfterResponseStarted(transition_data
);
3757 bool WebContentsImpl::WillHandleDeferAfterResponseStarted() {
3758 #if defined(OS_ANDROID)
3759 return GetWebContentsAndroid()->WillHandleDeferAfterResponseStarted();
3765 void WebContentsImpl::RequestMove(const gfx::Rect
& new_bounds
) {
3766 if (delegate_
&& delegate_
->IsPopupOrPanel(this))
3767 delegate_
->MoveContents(this, new_bounds
);
3770 void WebContentsImpl::DidStartLoading(RenderFrameHost
* render_frame_host
,
3771 bool to_different_document
) {
3772 SetIsLoading(render_frame_host
->GetRenderViewHost(), true,
3773 to_different_document
, NULL
);
3776 void WebContentsImpl::DidStopLoading(RenderFrameHost
* render_frame_host
) {
3777 scoped_ptr
<LoadNotificationDetails
> details
;
3779 // Use the last committed entry rather than the active one, in case a
3780 // pending entry has been created.
3781 NavigationEntry
* entry
= controller_
.GetLastCommittedEntry();
3782 Navigator
* navigator
= frame_tree_
.root()->navigator();
3784 // An entry may not exist for a stop when loading an initial blank page or
3785 // if an iframe injected by script into a blank page finishes loading.
3787 base::TimeDelta elapsed
=
3788 base::TimeTicks::Now() - navigator
->GetCurrentLoadStart();
3790 details
.reset(new LoadNotificationDetails(
3791 entry
->GetVirtualURL(),
3792 entry
->GetTransitionType(),
3795 controller_
.GetCurrentEntryIndex()));
3798 SetIsLoading(render_frame_host
->GetRenderViewHost(), false, true,
3802 void WebContentsImpl::DidCancelLoading() {
3803 controller_
.DiscardNonCommittedEntries();
3805 // Update the URL display.
3806 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL
);
3809 void WebContentsImpl::DidAccessInitialDocument() {
3810 has_accessed_initial_document_
= true;
3812 // We may have left a failed browser-initiated navigation in the address bar
3813 // to let the user edit it and try again. Clear it now that content might
3814 // show up underneath it.
3815 if (!IsLoading() && controller_
.GetPendingEntry())
3816 controller_
.DiscardPendingEntry();
3818 // Update the URL display.
3819 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL
);
3822 void WebContentsImpl::DidDisownOpener(RenderFrameHost
* render_frame_host
) {
3823 // No action is necessary if the opener has already been cleared.
3827 // Clear our opener so that future cross-process navigations don't have an
3829 RemoveDestructionObserver(opener_
);
3832 // Notify all swapped out RenderViewHosts for this tab. This is important
3833 // in case we go back to them, or if another window in those processes tries
3834 // to access window.opener.
3835 GetRenderManager()->DidDisownOpener(render_frame_host
);
3838 void WebContentsImpl::DocumentOnLoadCompleted(
3839 RenderFrameHost
* render_frame_host
) {
3840 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3841 DocumentOnLoadCompletedInMainFrame());
3843 // TODO(avi): Remove. http://crbug.com/170921
3844 NotificationService::current()->Notify(
3845 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
,
3846 Source
<WebContents
>(this),
3847 NotificationService::NoDetails());
3850 void WebContentsImpl::UpdateTitle(RenderFrameHost
* render_frame_host
,
3852 const base::string16
& title
,
3853 base::i18n::TextDirection title_direction
) {
3854 RenderViewHost
* rvh
= render_frame_host
->GetRenderViewHost();
3856 // If we have a title, that's a pretty good indication that we've started
3857 // getting useful data.
3858 SetNotWaitingForResponse();
3860 // Try to find the navigation entry, which might not be the current one.
3861 // For example, it might be from a pending RVH for the pending entry.
3862 NavigationEntryImpl
* entry
= controller_
.GetEntryWithPageID(
3863 rvh
->GetSiteInstance(), page_id
);
3865 // We can handle title updates when we don't have an entry in
3866 // UpdateTitleForEntry, but only if the update is from the current RVH.
3867 // TODO(avi): Change to make decisions based on the RenderFrameHost.
3868 if (!entry
&& rvh
!= GetRenderViewHost())
3871 // TODO(evan): make use of title_direction.
3872 // http://code.google.com/p/chromium/issues/detail?id=27094
3873 if (!UpdateTitleForEntry(entry
, title
))
3876 // Broadcast notifications when the UI should be updated.
3877 if (entry
== controller_
.GetEntryAtOffset(0))
3878 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE
);
3881 void WebContentsImpl::UpdateEncoding(RenderFrameHost
* render_frame_host
,
3882 const std::string
& encoding
) {
3883 SetEncoding(encoding
);
3886 void WebContentsImpl::DocumentAvailableInMainFrame(
3887 RenderViewHost
* render_view_host
) {
3888 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3889 DocumentAvailableInMainFrame());
3891 void WebContentsImpl::RouteCloseEvent(RenderViewHost
* rvh
) {
3892 // Tell the active RenderViewHost to run unload handlers and close, as long
3893 // as the request came from a RenderViewHost in the same BrowsingInstance.
3894 // In most cases, we receive this from a swapped out RenderViewHost.
3895 // It is possible to receive it from one that has just been swapped in,
3896 // in which case we might as well deliver the message anyway.
3897 if (rvh
->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()))
3898 GetRenderViewHost()->ClosePage();
3901 void WebContentsImpl::RouteMessageEvent(
3902 RenderViewHost
* rvh
,
3903 const ViewMsg_PostMessage_Params
& params
) {
3904 // Only deliver the message to the active RenderViewHost if the request
3905 // came from a RenderViewHost in the same BrowsingInstance or if this
3906 // WebContents is dedicated to a browser plugin guest.
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 if (!rvh
->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()) &&
3912 !GetBrowserPluginGuest() && !GetBrowserPluginEmbedder())
3915 ViewMsg_PostMessage_Params
new_params(params
);
3917 if (!params
.message_port_ids
.empty()) {
3918 MessagePortMessageFilter
* message_port_message_filter
=
3919 static_cast<RenderProcessHostImpl
*>(GetRenderProcessHost())
3920 ->message_port_message_filter();
3921 message_port_message_filter
->UpdateMessagePortsWithNewRoutes(
3922 params
.message_port_ids
,
3923 &new_params
.new_routing_ids
);
3926 // If there is a source_routing_id, translate it to the routing ID for
3927 // the equivalent swapped out RVH in the target process. If we need
3928 // to create a swapped out RVH for the source tab, we create its opener
3929 // chain as well, since those will also be accessible to the target page.
3930 if (new_params
.source_routing_id
!= MSG_ROUTING_NONE
) {
3931 // Try to look up the WebContents for the source page.
3932 WebContentsImpl
* source_contents
= NULL
;
3933 RenderViewHostImpl
* source_rvh
= RenderViewHostImpl::FromID(
3934 rvh
->GetProcess()->GetID(), params
.source_routing_id
);
3936 source_contents
= static_cast<WebContentsImpl
*>(
3937 source_rvh
->GetDelegate()->GetAsWebContents());
3940 if (source_contents
) {
3941 if (GetBrowserPluginGuest()) {
3942 // We create a swapped out RenderView for the embedder in the guest's
3943 // render process but we intentionally do not expose the embedder's
3944 // opener chain to it.
3945 new_params
.source_routing_id
=
3946 source_contents
->CreateSwappedOutRenderView(GetSiteInstance());
3948 new_params
.source_routing_id
=
3949 source_contents
->CreateOpenerRenderViews(GetSiteInstance());
3952 // We couldn't find it, so don't pass a source frame.
3953 new_params
.source_routing_id
= MSG_ROUTING_NONE
;
3957 // In most cases, we receive this from a swapped out RenderViewHost.
3958 // It is possible to receive it from one that has just been swapped in,
3959 // in which case we might as well deliver the message anyway.
3960 Send(new ViewMsg_PostMessageEvent(GetRoutingID(), new_params
));
3963 bool WebContentsImpl::AddMessageToConsole(int32 level
,
3964 const base::string16
& message
,
3966 const base::string16
& source_id
) {
3969 return delegate_
->AddMessageToConsole(this, level
, message
, line_no
,
3973 WebPreferences
WebContentsImpl::ComputeWebkitPrefs() {
3974 // We want to base the page config off of the actual URL, rather than the
3976 // TODO(nasko): Investigate how to remove the GetActiveEntry usage here,
3977 // as it is deprecated and can be out of sync with GetRenderViewHost().
3978 GURL url
= controller_
.GetActiveEntry()
3979 ? controller_
.GetActiveEntry()->GetURL() : GURL::EmptyGURL();
3981 return GetRenderManager()->current_host()->ComputeWebkitPrefs(url
);
3984 int WebContentsImpl::CreateSwappedOutRenderView(
3985 SiteInstance
* instance
) {
3986 int render_view_routing_id
= MSG_ROUTING_NONE
;
3987 GetRenderManager()->CreateRenderFrame(
3988 instance
, nullptr, MSG_ROUTING_NONE
,
3989 CREATE_RF_SWAPPED_OUT
| CREATE_RF_FOR_MAIN_FRAME_NAVIGATION
|
3991 &render_view_routing_id
);
3992 return render_view_routing_id
;
3995 void WebContentsImpl::OnUserGesture() {
3996 // Notify observers.
3997 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, DidGetUserGesture());
3999 ResourceDispatcherHostImpl
* rdh
= ResourceDispatcherHostImpl::Get();
4000 if (rdh
) // NULL in unittests.
4001 rdh
->OnUserGesture(this);
4004 void WebContentsImpl::OnIgnoredUIEvent() {
4005 // Notify observers.
4006 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, DidGetIgnoredUIEvent());
4009 void WebContentsImpl::RendererUnresponsive(RenderViewHost
* render_view_host
) {
4010 // Don't show hung renderer dialog for a swapped out RVH.
4011 if (render_view_host
!= GetRenderViewHost())
4014 RenderViewHostImpl
* rvhi
= static_cast<RenderViewHostImpl
*>(render_view_host
);
4015 RenderFrameHostImpl
* rfhi
=
4016 static_cast<RenderFrameHostImpl
*>(rvhi
->GetMainFrame());
4018 // Ignore renderer unresponsive event if debugger is attached to the tab
4019 // since the event may be a result of the renderer sitting on a breakpoint.
4020 // See http://crbug.com/65458
4021 if (DevToolsAgentHost::IsDebuggerAttached(this))
4024 if (rfhi
->is_waiting_for_beforeunload_ack() ||
4025 rfhi
->IsWaitingForUnloadACK()) {
4026 // Hang occurred while firing the beforeunload/unload handler.
4027 // Pretend the handler fired so tab closing continues as if it had.
4028 rvhi
->set_sudden_termination_allowed(true);
4030 if (!GetRenderManager()->ShouldCloseTabOnUnresponsiveRenderer())
4033 // If the tab hangs in the beforeunload/unload handler there's really
4034 // nothing we can do to recover. If the hang is in the beforeunload handler,
4035 // pretend the beforeunload listeners have all fired and allow the delegate
4036 // to continue closing; the user will not have the option of cancelling the
4037 // close. Otherwise, pretend the unload listeners have all fired and close
4040 if (rfhi
->is_waiting_for_beforeunload_ack() && delegate_
) {
4041 delegate_
->BeforeUnloadFired(this, true, &close
);
4048 if (!GetRenderViewHostImpl() || !GetRenderViewHostImpl()->IsRenderViewLive())
4052 delegate_
->RendererUnresponsive(this);
4055 void WebContentsImpl::RendererResponsive(RenderViewHost
* render_view_host
) {
4057 delegate_
->RendererResponsive(this);
4060 void WebContentsImpl::LoadStateChanged(
4062 const net::LoadStateWithParam
& load_state
,
4063 uint64 upload_position
,
4064 uint64 upload_size
) {
4065 load_state_
= load_state
;
4066 upload_position_
= upload_position
;
4067 upload_size_
= upload_size
;
4068 load_state_host_
= net::IDNToUnicode(url
.host(),
4069 GetContentClient()->browser()->GetAcceptLangs(
4070 GetBrowserContext()));
4071 if (load_state_
.state
== net::LOAD_STATE_READING_RESPONSE
)
4072 SetNotWaitingForResponse();
4074 NotifyNavigationStateChanged(static_cast<InvalidateTypes
>(
4075 INVALIDATE_TYPE_LOAD
| INVALIDATE_TYPE_TAB
));
4079 void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
4080 bool proceed
, const base::TimeTicks
& proceed_time
,
4081 bool* proceed_to_fire_unload
) {
4082 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
4083 BeforeUnloadFired(proceed_time
));
4085 delegate_
->BeforeUnloadFired(this, proceed
, proceed_to_fire_unload
);
4086 // Note: |this| might be deleted at this point.
4089 void WebContentsImpl::RenderProcessGoneFromRenderManager(
4090 RenderViewHost
* render_view_host
) {
4091 DCHECK(crashed_status_
!= base::TERMINATION_STATUS_STILL_RUNNING
);
4092 RenderViewTerminated(render_view_host
, crashed_status_
, crashed_error_code_
);
4095 void WebContentsImpl::UpdateRenderViewSizeForRenderManager() {
4096 // TODO(brettw) this is a hack. See WebContentsView::SizeContents.
4097 gfx::Size size
= GetSizeForNewRenderView();
4098 // 0x0 isn't a valid window size (minimal window size is 1x1) but it may be
4099 // here during container initialization and normal window size will be set
4100 // later. In case of tab duplication this resizing to 0x0 prevents setting
4101 // normal size later so just ignore it.
4102 if (!size
.IsEmpty())
4103 view_
->SizeContents(size
);
4106 void WebContentsImpl::CancelModalDialogsForRenderManager() {
4107 // We need to cancel modal dialogs when doing a process swap, since the load
4108 // deferrer would prevent us from swapping out.
4109 if (dialog_manager_
)
4110 dialog_manager_
->CancelActiveAndPendingDialogs(this);
4113 void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost
* old_host
,
4114 RenderFrameHost
* new_host
,
4115 bool is_main_frame
) {
4116 if (is_main_frame
) {
4117 NotifyViewSwapped(old_host
? old_host
->GetRenderViewHost() : NULL
,
4118 new_host
->GetRenderViewHost());
4120 // Make sure the visible RVH reflects the new delegate's preferences.
4122 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
4124 view_
->RenderViewSwappedIn(new_host
->GetRenderViewHost());
4127 NotifyFrameSwapped(old_host
, new_host
);
4130 int WebContentsImpl::CreateOpenerRenderViewsForRenderManager(
4131 SiteInstance
* instance
) {
4133 return MSG_ROUTING_NONE
;
4135 // Recursively create RenderViews for anything else in the opener chain.
4136 return opener_
->CreateOpenerRenderViews(instance
);
4139 int WebContentsImpl::CreateOpenerRenderViews(SiteInstance
* instance
) {
4140 int opener_route_id
= MSG_ROUTING_NONE
;
4142 // If this tab has an opener, ensure it has a RenderView in the given
4143 // SiteInstance as well.
4145 opener_route_id
= opener_
->CreateOpenerRenderViews(instance
);
4147 // If any of the renderers (current, pending, or swapped out) for this
4148 // WebContents has the same SiteInstance, use it.
4149 if (GetRenderManager()->current_host()->GetSiteInstance() == instance
)
4150 return GetRenderManager()->current_host()->GetRoutingID();
4152 if (GetRenderManager()->pending_render_view_host() &&
4153 GetRenderManager()->pending_render_view_host()->GetSiteInstance() ==
4155 return GetRenderManager()->pending_render_view_host()->GetRoutingID();
4157 RenderViewHostImpl
* rvh
= GetRenderManager()->GetSwappedOutRenderViewHost(
4160 return rvh
->GetRoutingID();
4162 // Create a swapped out RenderView in the given SiteInstance if none exists,
4163 // setting its opener to the given route_id. Return the new view's route_id.
4164 int render_view_routing_id
= MSG_ROUTING_NONE
;
4165 GetRenderManager()->CreateRenderFrame(instance
, nullptr, opener_route_id
,
4166 CREATE_RF_FOR_MAIN_FRAME_NAVIGATION
|
4167 CREATE_RF_SWAPPED_OUT
|
4169 &render_view_routing_id
);
4170 return render_view_routing_id
;
4173 NavigationControllerImpl
& WebContentsImpl::GetControllerForRenderManager() {
4174 return GetController();
4177 scoped_ptr
<WebUIImpl
> WebContentsImpl::CreateWebUIForRenderManager(
4179 return scoped_ptr
<WebUIImpl
>(static_cast<WebUIImpl
*>(CreateWebUI(url
)));
4183 WebContentsImpl::GetLastCommittedNavigationEntryForRenderManager() {
4184 return controller_
.GetLastCommittedEntry();
4187 bool WebContentsImpl::CreateRenderViewForRenderManager(
4188 RenderViewHost
* render_view_host
,
4189 int opener_route_id
,
4190 int proxy_routing_id
,
4191 bool for_main_frame_navigation
) {
4192 TRACE_EVENT0("browser,navigation",
4193 "WebContentsImpl::CreateRenderViewForRenderManager");
4194 // Can be NULL during tests.
4195 RenderWidgetHostViewBase
* rwh_view
;
4196 // TODO(kenrb): RenderWidgetHostViewChildFrame special casing is temporary
4197 // until RenderWidgetHost is attached to RenderFrameHost. We need to special
4198 // case this because RWH is still a base class of RenderViewHost, and child
4199 // frame RWHVs are unique in that they do not have their own WebContents.
4200 if (!for_main_frame_navigation
) {
4201 RenderWidgetHostViewChildFrame
* rwh_view_child
=
4202 new RenderWidgetHostViewChildFrame(render_view_host
);
4203 rwh_view
= rwh_view_child
;
4205 rwh_view
= view_
->CreateViewForWidget(render_view_host
, false);
4208 // Now that the RenderView has been created, we need to tell it its size.
4210 rwh_view
->SetSize(GetSizeForNewRenderView());
4212 // Make sure we use the correct starting page_id in the new RenderView.
4213 UpdateMaxPageIDIfNecessary(render_view_host
);
4215 GetMaxPageIDForSiteInstance(render_view_host
->GetSiteInstance());
4217 if (!static_cast<RenderViewHostImpl
*>(
4218 render_view_host
)->CreateRenderView(base::string16(),
4222 created_with_opener_
)) {
4226 SetHistoryOffsetAndLengthForView(render_view_host
,
4227 controller_
.GetLastCommittedEntryIndex(),
4228 controller_
.GetEntryCount());
4230 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
4231 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
4232 // linux. See crbug.com/83941.
4234 if (RenderWidgetHost
* render_widget_host
= rwh_view
->GetRenderWidgetHost())
4235 render_widget_host
->WasResized();
4242 bool WebContentsImpl::CreateRenderFrameForRenderManager(
4243 RenderFrameHost
* render_frame_host
,
4244 int parent_routing_id
,
4245 int proxy_routing_id
) {
4246 TRACE_EVENT0("browser,navigation",
4247 "WebContentsImpl::CreateRenderFrameForRenderManager");
4249 RenderFrameHostImpl
* rfh
=
4250 static_cast<RenderFrameHostImpl
*>(render_frame_host
);
4251 if (!rfh
->CreateRenderFrame(parent_routing_id
, proxy_routing_id
))
4254 // TODO(nasko): When RenderWidgetHost is owned by RenderFrameHost, the passed
4255 // RenderFrameHost will have to be associated with the appropriate
4256 // RenderWidgetHostView or a new one should be created here.
4261 #if defined(OS_ANDROID)
4263 base::android::ScopedJavaLocalRef
<jobject
>
4264 WebContentsImpl::GetJavaWebContents() {
4265 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
4266 return GetWebContentsAndroid()->GetJavaObject();
4269 WebContentsAndroid
* WebContentsImpl::GetWebContentsAndroid() {
4270 WebContentsAndroid
* web_contents_android
=
4271 static_cast<WebContentsAndroid
*>(GetUserData(kWebContentsAndroidKey
));
4272 if (!web_contents_android
) {
4273 web_contents_android
= new WebContentsAndroid(this);
4274 SetUserData(kWebContentsAndroidKey
, web_contents_android
);
4276 return web_contents_android
;
4279 bool WebContentsImpl::CreateRenderViewForInitialEmptyDocument() {
4280 return CreateRenderViewForRenderManager(GetRenderViewHost(),
4286 #elif defined(OS_MACOSX)
4288 void WebContentsImpl::SetAllowOtherViews(bool allow
) {
4289 view_
->SetAllowOtherViews(allow
);
4292 bool WebContentsImpl::GetAllowOtherViews() {
4293 return view_
->GetAllowOtherViews();
4298 void WebContentsImpl::OnDialogClosed(int render_process_id
,
4299 int render_frame_id
,
4300 IPC::Message
* reply_msg
,
4301 bool dialog_was_suppressed
,
4303 const base::string16
& user_input
) {
4304 RenderFrameHostImpl
* rfh
= RenderFrameHostImpl::FromID(render_process_id
,
4306 last_dialog_suppressed_
= dialog_was_suppressed
;
4308 if (is_showing_before_unload_dialog_
&& !success
) {
4309 // If a beforeunload dialog is canceled, we need to stop the throbber from
4310 // spinning, since we forced it to start spinning in Navigate.
4312 DidStopLoading(rfh
);
4313 controller_
.DiscardNonCommittedEntries();
4315 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
4316 BeforeUnloadDialogCancelled());
4319 is_showing_before_unload_dialog_
= false;
4321 rfh
->JavaScriptDialogClosed(reply_msg
, success
, user_input
,
4322 dialog_was_suppressed
);
4324 // Don't leak the sync IPC reply if the RFH or process is gone.
4329 void WebContentsImpl::SetEncoding(const std::string
& encoding
) {
4330 if (encoding
== last_reported_encoding_
)
4332 last_reported_encoding_
= encoding
;
4334 canonical_encoding_
= GetContentClient()->browser()->
4335 GetCanonicalEncodingNameByAliasName(encoding
);
4338 bool WebContentsImpl::IsHidden() {
4339 return capturer_count_
== 0 && !should_normally_be_visible_
;
4342 RenderFrameHostManager
* WebContentsImpl::GetRenderManager() const {
4343 return frame_tree_
.root()->render_manager();
4346 RenderViewHostImpl
* WebContentsImpl::GetRenderViewHostImpl() {
4347 return static_cast<RenderViewHostImpl
*>(GetRenderViewHost());
4350 BrowserPluginGuest
* WebContentsImpl::GetBrowserPluginGuest() const {
4351 return browser_plugin_guest_
.get();
4354 void WebContentsImpl::SetBrowserPluginGuest(BrowserPluginGuest
* guest
) {
4355 CHECK(!browser_plugin_guest_
);
4356 browser_plugin_guest_
.reset(guest
);
4359 BrowserPluginEmbedder
* WebContentsImpl::GetBrowserPluginEmbedder() const {
4360 return browser_plugin_embedder_
.get();
4363 void WebContentsImpl::ClearPowerSaveBlockers(
4364 RenderFrameHost
* render_frame_host
) {
4365 RemoveAllMediaPlayerEntries(render_frame_host
, &active_audio_players_
);
4366 RemoveAllMediaPlayerEntries(render_frame_host
, &active_video_players_
);
4367 MaybeReleasePowerSaveBlockers();
4370 void WebContentsImpl::ClearAllPowerSaveBlockers() {
4371 active_audio_players_
.clear();
4372 active_video_players_
.clear();
4373 audio_power_save_blocker_
.reset();
4374 video_power_save_blocker_
.reset();
4377 gfx::Size
WebContentsImpl::GetSizeForNewRenderView() {
4380 size
= delegate_
->GetSizeForNewRenderView(this);
4382 size
= GetContainerBounds().size();
4386 void WebContentsImpl::OnFrameRemoved(RenderFrameHost
* render_frame_host
) {
4388 WebContentsObserver
, observers_
, FrameDetached(render_frame_host
));
4391 void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size
& old_size
) {
4394 const gfx::Size new_size
= GetPreferredSize();
4395 if (new_size
!= old_size
)
4396 delegate_
->UpdatePreferredSize(this, new_size
);
4399 void WebContentsImpl::AddMediaPlayerEntry(int64 player_cookie
,
4400 ActiveMediaPlayerMap
* player_map
) {
4401 const uintptr_t key
=
4402 reinterpret_cast<uintptr_t>(render_frame_message_source_
);
4403 DCHECK(std::find((*player_map
)[key
].begin(),
4404 (*player_map
)[key
].end(),
4405 player_cookie
) == (*player_map
)[key
].end());
4406 (*player_map
)[key
].push_back(player_cookie
);
4409 void WebContentsImpl::RemoveMediaPlayerEntry(int64 player_cookie
,
4410 ActiveMediaPlayerMap
* player_map
) {
4411 const uintptr_t key
=
4412 reinterpret_cast<uintptr_t>(render_frame_message_source_
);
4413 ActiveMediaPlayerMap::iterator it
= player_map
->find(key
);
4414 if (it
== player_map
->end())
4417 // Remove the player.
4418 PlayerList::iterator player_it
=
4419 std::find(it
->second
.begin(), it
->second
.end(), player_cookie
);
4420 if (player_it
!= it
->second
.end())
4421 it
->second
.erase(player_it
);
4423 // If there are no players left, remove the map entry.
4424 if (it
->second
.empty())
4425 player_map
->erase(it
);
4428 void WebContentsImpl::RemoveAllMediaPlayerEntries(
4429 RenderFrameHost
* render_frame_host
,
4430 ActiveMediaPlayerMap
* player_map
) {
4431 ActiveMediaPlayerMap::iterator it
=
4432 player_map
->find(reinterpret_cast<uintptr_t>(render_frame_host
));
4433 if (it
== player_map
->end())
4435 player_map
->erase(it
);
4438 void WebContentsImpl::ResumeResponseDeferredAtStart() {
4439 FrameTreeNode
* node
= frame_tree_
.root();
4440 node
->render_manager()->ResumeResponseDeferredAtStart();
4443 void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable
) {
4444 force_disable_overscroll_content_
= force_disable
;
4446 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
4449 } // namespace content