1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/web_contents/web_contents_impl.h"
9 #include "base/command_line.h"
10 #include "base/lazy_instance.h"
11 #include "base/logging.h"
12 #include "base/metrics/histogram.h"
13 #include "base/process/process.h"
14 #include "base/strings/string16.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/time/time.h"
19 #include "base/trace_event/trace_event.h"
20 #include "content/browser/accessibility/accessibility_mode_helper.h"
21 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
22 #include "content/browser/browser_plugin/browser_plugin_embedder.h"
23 #include "content/browser/browser_plugin/browser_plugin_guest.h"
24 #include "content/browser/child_process_security_policy_impl.h"
25 #include "content/browser/devtools/devtools_manager.h"
26 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
27 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
28 #include "content/browser/download/download_stats.h"
29 #include "content/browser/download/mhtml_generation_manager.h"
30 #include "content/browser/download/save_package.h"
31 #include "content/browser/frame_host/cross_process_frame_connector.h"
32 #include "content/browser/frame_host/interstitial_page_impl.h"
33 #include "content/browser/frame_host/navigation_entry_impl.h"
34 #include "content/browser/frame_host/navigator_impl.h"
35 #include "content/browser/frame_host/render_frame_host_impl.h"
36 #include "content/browser/frame_host/render_widget_host_view_child_frame.h"
37 #include "content/browser/geolocation/geolocation_service_context.h"
38 #include "content/browser/host_zoom_map_impl.h"
39 #include "content/browser/loader/resource_dispatcher_host_impl.h"
40 #include "content/browser/manifest/manifest_manager_host.h"
41 #include "content/browser/media/audio_stream_monitor.h"
42 #include "content/browser/media/capture/web_contents_audio_muter.h"
43 #include "content/browser/message_port_message_filter.h"
44 #include "content/browser/message_port_service.h"
45 #include "content/browser/plugin_content_origin_whitelist.h"
46 #include "content/browser/power_save_blocker_impl.h"
47 #include "content/browser/renderer_host/render_process_host_impl.h"
48 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
49 #include "content/browser/renderer_host/render_view_host_impl.h"
50 #include "content/browser/renderer_host/render_widget_host_impl.h"
51 #include "content/browser/renderer_host/render_widget_host_view_base.h"
52 #include "content/browser/screen_orientation/screen_orientation_dispatcher_host_impl.h"
53 #include "content/browser/site_instance_impl.h"
54 #include "content/browser/web_contents/web_contents_view_guest.h"
55 #include "content/browser/webui/generic_handler.h"
56 #include "content/browser/webui/web_ui_controller_factory_registry.h"
57 #include "content/browser/webui/web_ui_impl.h"
58 #include "content/common/browser_plugin/browser_plugin_constants.h"
59 #include "content/common/browser_plugin/browser_plugin_messages.h"
60 #include "content/common/frame_messages.h"
61 #include "content/common/image_messages.h"
62 #include "content/common/input_messages.h"
63 #include "content/common/ssl_status_serialization.h"
64 #include "content/common/view_messages.h"
65 #include "content/public/browser/ax_event_notification_details.h"
66 #include "content/public/browser/browser_context.h"
67 #include "content/public/browser/browser_plugin_guest_manager.h"
68 #include "content/public/browser/content_browser_client.h"
69 #include "content/public/browser/devtools_agent_host.h"
70 #include "content/public/browser/download_manager.h"
71 #include "content/public/browser/download_url_parameters.h"
72 #include "content/public/browser/invalidate_type.h"
73 #include "content/public/browser/javascript_dialog_manager.h"
74 #include "content/public/browser/load_from_memory_cache_details.h"
75 #include "content/public/browser/load_notification_details.h"
76 #include "content/public/browser/navigation_details.h"
77 #include "content/public/browser/notification_details.h"
78 #include "content/public/browser/notification_service.h"
79 #include "content/public/browser/render_widget_host_iterator.h"
80 #include "content/public/browser/resource_request_details.h"
81 #include "content/public/browser/screen_orientation_dispatcher_host.h"
82 #include "content/public/browser/storage_partition.h"
83 #include "content/public/browser/user_metrics.h"
84 #include "content/public/browser/web_contents_delegate.h"
85 #include "content/public/browser/web_contents_observer.h"
86 #include "content/public/common/bindings_policy.h"
87 #include "content/public/common/content_constants.h"
88 #include "content/public/common/content_switches.h"
89 #include "content/public/common/page_zoom.h"
90 #include "content/public/common/result_codes.h"
91 #include "content/public/common/url_constants.h"
92 #include "content/public/common/url_utils.h"
93 #include "content/public/common/web_preferences.h"
94 #include "net/base/mime_util.h"
95 #include "net/base/net_util.h"
96 #include "net/http/http_cache.h"
97 #include "net/http/http_transaction_factory.h"
98 #include "net/url_request/url_request_context.h"
99 #include "net/url_request/url_request_context_getter.h"
100 #include "ui/base/layout.h"
101 #include "ui/gfx/display.h"
102 #include "ui/gfx/screen.h"
103 #include "ui/gl/gl_switches.h"
105 #if defined(ENABLE_BROWSER_CDMS)
106 #include "content/browser/media/media_web_contents_observer.h"
109 #if defined(OS_ANDROID)
110 #include "content/browser/android/content_video_view.h"
111 #include "content/browser/android/date_time_chooser_android.h"
112 #include "content/browser/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
);
204 // Enable sudden termination for the current RenderFrameHost of
205 // |frame_tree_node| if the ID of its SiteInstance is |site_instance_id|. Used
206 // with FrameTree::ForEach.
207 bool EnableSuddenTermination(int32 site_instance_id
,
208 FrameTreeNode
* frame_tree_node
) {
209 if (frame_tree_node
->current_frame_host()->GetSiteInstance()->GetId()
210 == site_instance_id
) {
211 frame_tree_node
->current_frame_host()
212 ->set_override_sudden_termination_status(true);
217 // Returns false and sets |sudden_termination_allowed| to false if sudden
218 // termination is not allowed for the current RenderFrameHost of
219 // |frame_tree_node|. Used with FrameTree::ForEach.
220 bool SuddenTerminationAllowed(bool* sudden_termination_allowed
,
221 FrameTreeNode
* frame_tree_node
) {
222 if (frame_tree_node
->current_frame_host()->SuddenTerminationAllowed())
224 *sudden_termination_allowed
= false;
230 WebContents
* WebContents::Create(const WebContents::CreateParams
& params
) {
231 return WebContentsImpl::CreateWithOpener(
232 params
, static_cast<WebContentsImpl
*>(params
.opener
));
235 WebContents
* WebContents::CreateWithSessionStorage(
236 const WebContents::CreateParams
& params
,
237 const SessionStorageNamespaceMap
& session_storage_namespace_map
) {
238 WebContentsImpl
* new_contents
= new WebContentsImpl(
239 params
.browser_context
, NULL
);
241 for (SessionStorageNamespaceMap::const_iterator it
=
242 session_storage_namespace_map
.begin();
243 it
!= session_storage_namespace_map
.end();
245 new_contents
->GetController()
246 .SetSessionStorageNamespace(it
->first
, it
->second
.get());
249 new_contents
->Init(params
);
253 void WebContentsImpl::FriendZone::AddCreatedCallbackForTesting(
254 const CreatedCallback
& callback
) {
255 g_created_callbacks
.Get().push_back(callback
);
258 void WebContentsImpl::FriendZone::RemoveCreatedCallbackForTesting(
259 const CreatedCallback
& callback
) {
260 for (size_t i
= 0; i
< g_created_callbacks
.Get().size(); ++i
) {
261 if (g_created_callbacks
.Get().at(i
).Equals(callback
)) {
262 g_created_callbacks
.Get().erase(g_created_callbacks
.Get().begin() + i
);
268 WebContents
* WebContents::FromRenderViewHost(const RenderViewHost
* rvh
) {
269 return rvh
->GetDelegate()->GetAsWebContents();
272 WebContents
* WebContents::FromRenderFrameHost(RenderFrameHost
* rfh
) {
273 RenderFrameHostImpl
* rfh_impl
= static_cast<RenderFrameHostImpl
*>(rfh
);
276 return rfh_impl
->delegate()->GetAsWebContents();
279 // WebContentsImpl::DestructionObserver ----------------------------------------
281 class WebContentsImpl::DestructionObserver
: public WebContentsObserver
{
283 DestructionObserver(WebContentsImpl
* owner
, WebContents
* watched_contents
)
284 : WebContentsObserver(watched_contents
),
288 // WebContentsObserver:
289 void WebContentsDestroyed() override
{
290 owner_
->OnWebContentsDestroyed(
291 static_cast<WebContentsImpl
*>(web_contents()));
295 WebContentsImpl
* owner_
;
297 DISALLOW_COPY_AND_ASSIGN(DestructionObserver
);
300 WebContentsImpl::ColorChooserInfo::ColorChooserInfo(int render_process_id
,
302 ColorChooser
* chooser
,
304 : render_process_id(render_process_id
),
305 render_frame_id(render_frame_id
),
307 identifier(identifier
) {
310 WebContentsImpl::ColorChooserInfo::~ColorChooserInfo() {
313 // WebContentsImpl -------------------------------------------------------------
315 WebContentsImpl::WebContentsImpl(BrowserContext
* browser_context
,
316 WebContentsImpl
* opener
)
318 controller_(this, browser_context
),
319 render_view_host_delegate_view_(NULL
),
321 created_with_opener_(!!opener
),
323 accessible_parent_(NULL
),
325 frame_tree_(new NavigatorImpl(&controller_
, this),
331 is_load_to_different_document_(false),
332 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING
),
333 crashed_error_code_(0),
334 waiting_for_response_(false),
335 load_state_(net::LOAD_STATE_IDLE
, base::string16()),
336 loading_total_progress_(0.0),
337 loading_frames_in_progress_(0),
340 displayed_insecure_content_(false),
341 has_accessed_initial_document_(false),
343 should_normally_be_visible_(true),
344 is_being_destroyed_(false),
345 notify_disconnection_(false),
346 dialog_manager_(NULL
),
347 is_showing_before_unload_dialog_(false),
348 last_active_time_(base::TimeTicks::Now()),
349 closed_by_user_gesture_(false),
350 minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor
* 100)),
351 maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor
* 100)),
352 render_view_message_source_(NULL
),
353 render_frame_message_source_(NULL
),
354 fullscreen_widget_routing_id_(MSG_ROUTING_NONE
),
355 fullscreen_widget_had_focus_at_shutdown_(false),
357 force_disable_overscroll_content_(false),
358 last_dialog_suppressed_(false),
359 geolocation_service_context_(new GeolocationServiceContext()),
361 BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()),
362 audio_stream_monitor_(this),
363 virtual_keyboard_requested_(false),
364 loading_weak_factory_(this) {
365 frame_tree_
.SetFrameRemoveListener(
366 base::Bind(&WebContentsImpl::OnFrameRemoved
,
367 base::Unretained(this)));
368 #if defined(ENABLE_BROWSER_CDMS)
369 media_web_contents_observer_
.reset(new MediaWebContentsObserver(this));
373 WebContentsImpl::~WebContentsImpl() {
374 is_being_destroyed_
= true;
376 // Delete all RFH pending shutdown, which will lead the corresponding RVH to
377 // shutdown and be deleted as well.
379 base::Bind(&RenderFrameHostManager::ClearRFHsPendingShutdown
));
381 ClearAllPowerSaveBlockers();
383 for (std::set
<RenderWidgetHostImpl
*>::iterator iter
=
384 created_widgets_
.begin(); iter
!= created_widgets_
.end(); ++iter
) {
385 (*iter
)->DetachDelegate();
387 created_widgets_
.clear();
389 // Clear out any JavaScript state.
391 dialog_manager_
->WebContentsDestroyed(this);
393 if (color_chooser_info_
.get())
394 color_chooser_info_
->chooser
->End();
396 NotifyDisconnected();
398 // Notify any observer that have a reference on this WebContents.
399 NotificationService::current()->Notify(
400 NOTIFICATION_WEB_CONTENTS_DESTROYED
,
401 Source
<WebContents
>(this),
402 NotificationService::NoDetails());
404 // Destroy all frame tree nodes except for the root; this notifies observers.
405 frame_tree_
.ResetForMainFrameSwap();
406 GetRenderManager()->ResetProxyHosts();
408 // Manually call the observer methods for the root frame tree node.
409 RenderFrameHostManager
* root
= GetRenderManager();
410 if (root
->pending_frame_host()) {
411 FOR_EACH_OBSERVER(WebContentsObserver
,
413 RenderFrameDeleted(root
->pending_frame_host()));
415 FOR_EACH_OBSERVER(WebContentsObserver
,
417 RenderFrameDeleted(root
->current_frame_host()));
419 if (root
->pending_render_view_host()) {
420 FOR_EACH_OBSERVER(WebContentsObserver
,
422 RenderViewDeleted(root
->pending_render_view_host()));
425 FOR_EACH_OBSERVER(WebContentsObserver
,
427 RenderViewDeleted(root
->current_host()));
429 FOR_EACH_OBSERVER(WebContentsObserver
,
431 WebContentsDestroyed());
433 FOR_EACH_OBSERVER(WebContentsObserver
,
439 STLDeleteContainerPairSecondPointers(destruction_observers_
.begin(),
440 destruction_observers_
.end());
443 WebContentsImpl
* WebContentsImpl::CreateWithOpener(
444 const WebContents::CreateParams
& params
,
445 WebContentsImpl
* opener
) {
446 TRACE_EVENT0("browser", "WebContentsImpl::CreateWithOpener");
447 WebContentsImpl
* new_contents
= new WebContentsImpl(
448 params
.browser_context
, params
.opener_suppressed
? NULL
: opener
);
450 if (params
.guest_delegate
) {
451 // This makes |new_contents| act as a guest.
452 // For more info, see comment above class BrowserPluginGuest.
453 BrowserPluginGuest::Create(new_contents
, params
.guest_delegate
);
454 // We are instantiating a WebContents for browser plugin. Set its subframe
456 new_contents
->is_subframe_
= true;
458 new_contents
->Init(params
);
463 std::vector
<WebContentsImpl
*> WebContentsImpl::GetAllWebContents() {
464 std::vector
<WebContentsImpl
*> result
;
465 scoped_ptr
<RenderWidgetHostIterator
> widgets(
466 RenderWidgetHostImpl::GetRenderWidgetHosts());
467 std::set
<WebContentsImpl
*> web_contents_set
;
468 while (RenderWidgetHost
* rwh
= widgets
->GetNextHost()) {
469 if (!rwh
->IsRenderView())
471 RenderViewHost
* rvh
= RenderViewHost::From(rwh
);
474 WebContents
* web_contents
= WebContents::FromRenderViewHost(rvh
);
477 WebContentsImpl
* wci
= static_cast<WebContentsImpl
*>(web_contents
);
478 if (web_contents_set
.find(wci
) == web_contents_set
.end()) {
479 web_contents_set
.insert(wci
);
480 result
.push_back(wci
);
486 RenderFrameHostManager
* WebContentsImpl::GetRenderManagerForTesting() {
487 return GetRenderManager();
490 bool WebContentsImpl::OnMessageReceived(RenderViewHost
* render_view_host
,
491 const IPC::Message
& message
) {
492 return OnMessageReceived(render_view_host
, NULL
, message
);
495 bool WebContentsImpl::OnMessageReceived(RenderViewHost
* render_view_host
,
496 RenderFrameHost
* render_frame_host
,
497 const IPC::Message
& message
) {
498 DCHECK(render_view_host
|| render_frame_host
);
500 static_cast<WebUIImpl
*>(GetWebUI())->OnMessageReceived(message
)) {
504 ObserverListBase
<WebContentsObserver
>::Iterator
it(observers_
);
505 WebContentsObserver
* observer
;
506 if (render_frame_host
) {
507 while ((observer
= it
.GetNext()) != NULL
)
508 if (observer
->OnMessageReceived(message
, render_frame_host
))
511 while ((observer
= it
.GetNext()) != NULL
)
512 if (observer
->OnMessageReceived(message
))
516 // Message handlers should be aware of which
517 // RenderViewHost/RenderFrameHost sent the message, which is temporarily
518 // stored in render_(view|frame)_message_source_.
519 if (render_frame_host
)
520 render_frame_message_source_
= render_frame_host
;
522 render_view_message_source_
= render_view_host
;
525 IPC_BEGIN_MESSAGE_MAP(WebContentsImpl
, message
)
526 IPC_MESSAGE_HANDLER(FrameHostMsg_DomOperationResponse
,
527 OnDomOperationResponse
)
528 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeThemeColor
,
530 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishDocumentLoad
,
531 OnDocumentLoadedInFrame
)
532 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishLoad
, OnDidFinishLoad
)
533 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartLoading
, OnDidStartLoading
)
534 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading
, OnDidStopLoading
)
535 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress
,
536 OnDidChangeLoadProgress
)
537 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenColorChooser
, OnOpenColorChooser
)
538 IPC_MESSAGE_HANDLER(FrameHostMsg_EndColorChooser
, OnEndColorChooser
)
539 IPC_MESSAGE_HANDLER(FrameHostMsg_SetSelectedColorInColorChooser
,
540 OnSetSelectedColorInColorChooser
)
541 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPlayingNotification
,
542 OnMediaPlayingNotification
)
543 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPausedNotification
,
544 OnMediaPausedNotification
)
545 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFirstVisuallyNonEmptyPaint
,
546 OnFirstVisuallyNonEmptyPaint
)
547 IPC_MESSAGE_HANDLER(ViewHostMsg_DidLoadResourceFromMemoryCache
,
548 OnDidLoadResourceFromMemoryCache
)
549 IPC_MESSAGE_HANDLER(ViewHostMsg_DidDisplayInsecureContent
,
550 OnDidDisplayInsecureContent
)
551 IPC_MESSAGE_HANDLER(ViewHostMsg_DidRunInsecureContent
,
552 OnDidRunInsecureContent
)
553 IPC_MESSAGE_HANDLER(ViewHostMsg_GoToEntryAtOffset
, OnGoToEntryAtOffset
)
554 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateZoomLimits
, OnUpdateZoomLimits
)
555 IPC_MESSAGE_HANDLER(ViewHostMsg_EnumerateDirectory
, OnEnumerateDirectory
)
556 IPC_MESSAGE_HANDLER(ViewHostMsg_RegisterProtocolHandler
,
557 OnRegisterProtocolHandler
)
558 IPC_MESSAGE_HANDLER(ViewHostMsg_UnregisterProtocolHandler
,
559 OnUnregisterProtocolHandler
)
560 IPC_MESSAGE_HANDLER(ViewHostMsg_Find_Reply
, OnFindReply
)
561 IPC_MESSAGE_HANDLER(ViewHostMsg_AppCacheAccessed
, OnAppCacheAccessed
)
562 IPC_MESSAGE_HANDLER(ViewHostMsg_WebUISend
, OnWebUISend
)
563 #if defined(ENABLE_PLUGINS)
564 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung
, OnPepperPluginHung
)
565 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed
, OnPluginCrashed
)
566 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission
,
567 OnRequestPpapiBrokerPermission
)
568 IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_Attach
,
569 OnBrowserPluginMessage(message
))
571 IPC_MESSAGE_HANDLER(ImageHostMsg_DidDownloadImage
, OnDidDownloadImage
)
572 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateFaviconURL
, OnUpdateFaviconURL
)
573 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowValidationMessage
,
574 OnShowValidationMessage
)
575 IPC_MESSAGE_HANDLER(ViewHostMsg_HideValidationMessage
,
576 OnHideValidationMessage
)
577 IPC_MESSAGE_HANDLER(ViewHostMsg_MoveValidationMessage
,
578 OnMoveValidationMessage
)
579 #if defined(OS_ANDROID)
580 IPC_MESSAGE_HANDLER(ViewHostMsg_FindMatchRects_Reply
,
581 OnFindMatchRectsReply
)
582 IPC_MESSAGE_HANDLER(ViewHostMsg_OpenDateTimeDialog
,
583 OnOpenDateTimeDialog
)
585 IPC_MESSAGE_UNHANDLED(handled
= false)
586 IPC_END_MESSAGE_MAP()
587 render_view_message_source_
= NULL
;
588 render_frame_message_source_
= NULL
;
593 bool WebContentsImpl::HasValidFrameSource() {
594 if (!render_frame_message_source_
) {
595 DCHECK(render_view_message_source_
);
596 RecordAction(base::UserMetricsAction("BadMessageTerminate_WC"));
597 GetRenderProcessHost()->ReceivedBadMessage();
604 void WebContentsImpl::RunFileChooser(
605 RenderViewHost
* render_view_host
,
606 const FileChooserParams
& params
) {
608 delegate_
->RunFileChooser(this, params
);
611 NavigationControllerImpl
& WebContentsImpl::GetController() {
615 const NavigationControllerImpl
& WebContentsImpl::GetController() const {
619 BrowserContext
* WebContentsImpl::GetBrowserContext() const {
620 return controller_
.GetBrowserContext();
623 const GURL
& WebContentsImpl::GetURL() const {
624 // We may not have a navigation entry yet.
625 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
626 return entry
? entry
->GetVirtualURL() : GURL::EmptyGURL();
629 const GURL
& WebContentsImpl::GetVisibleURL() const {
630 // We may not have a navigation entry yet.
631 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
632 return entry
? entry
->GetVirtualURL() : GURL::EmptyGURL();
635 const GURL
& WebContentsImpl::GetLastCommittedURL() const {
636 // We may not have a navigation entry yet.
637 NavigationEntry
* entry
= controller_
.GetLastCommittedEntry();
638 return entry
? entry
->GetVirtualURL() : GURL::EmptyGURL();
641 WebContentsDelegate
* WebContentsImpl::GetDelegate() {
645 void WebContentsImpl::SetDelegate(WebContentsDelegate
* delegate
) {
646 // TODO(cbentzel): remove this debugging code?
647 if (delegate
== delegate_
)
650 delegate_
->Detach(this);
651 delegate_
= delegate
;
653 delegate_
->Attach(this);
654 // Ensure the visible RVH reflects the new delegate's preferences.
656 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
660 RenderProcessHost
* WebContentsImpl::GetRenderProcessHost() const {
661 RenderViewHostImpl
* host
= GetRenderManager()->current_host();
662 return host
? host
->GetProcess() : NULL
;
665 RenderFrameHostImpl
* WebContentsImpl::GetMainFrame() {
666 return frame_tree_
.root()->current_frame_host();
669 RenderFrameHost
* WebContentsImpl::GetFocusedFrame() {
670 if (!frame_tree_
.GetFocusedFrame())
672 return frame_tree_
.GetFocusedFrame()->current_frame_host();
675 void WebContentsImpl::ForEachFrame(
676 const base::Callback
<void(RenderFrameHost
*)>& on_frame
) {
677 frame_tree_
.ForEach(base::Bind(&ForEachFrameInternal
, on_frame
));
680 void WebContentsImpl::SendToAllFrames(IPC::Message
* message
) {
681 ForEachFrame(base::Bind(&SendToAllFramesInternal
, message
));
685 RenderViewHost
* WebContentsImpl::GetRenderViewHost() const {
686 return GetRenderManager()->current_host();
689 int WebContentsImpl::GetRoutingID() const {
690 if (!GetRenderViewHost())
691 return MSG_ROUTING_NONE
;
693 return GetRenderViewHost()->GetRoutingID();
696 int WebContentsImpl::GetFullscreenWidgetRoutingID() const {
697 return fullscreen_widget_routing_id_
;
700 RenderWidgetHostView
* WebContentsImpl::GetRenderWidgetHostView() const {
701 return GetRenderManager()->GetRenderWidgetHostView();
704 RenderWidgetHostView
* WebContentsImpl::GetFullscreenRenderWidgetHostView()
706 RenderWidgetHost
* const widget_host
=
707 RenderWidgetHostImpl::FromID(GetRenderProcessHost()->GetID(),
708 GetFullscreenWidgetRoutingID());
709 return widget_host
? widget_host
->GetView() : NULL
;
712 WebContentsView
* WebContentsImpl::GetView() const {
716 void WebContentsImpl::SetAccessibilityMode(AccessibilityMode mode
) {
717 if (mode
== accessibility_mode_
)
720 accessibility_mode_
= mode
;
722 base::Bind(&ForEachFrameInternal
,
723 base::Bind(&SetAccessibilityModeOnFrame
, mode
)));
725 base::Bind(&ForEachPendingFrameInternal
,
726 base::Bind(&SetAccessibilityModeOnFrame
, mode
)));
729 void WebContentsImpl::AddAccessibilityMode(AccessibilityMode mode
) {
730 SetAccessibilityMode(AddAccessibilityModeTo(accessibility_mode_
, mode
));
733 void WebContentsImpl::RemoveAccessibilityMode(AccessibilityMode mode
) {
734 SetAccessibilityMode(RemoveAccessibilityModeFrom(accessibility_mode_
, mode
));
737 void WebContentsImpl::ClearNavigationTransitionData() {
738 FrameTreeNode
* node
= frame_tree_
.root();
739 node
->render_manager()->ClearNavigationTransitionData();
742 WebUI
* WebContentsImpl::CreateWebUI(const GURL
& url
) {
743 WebUIImpl
* web_ui
= new WebUIImpl(this);
744 WebUIController
* controller
= WebUIControllerFactoryRegistry::GetInstance()->
745 CreateWebUIControllerForURL(web_ui
, url
);
747 web_ui
->AddMessageHandler(new GenericHandler());
748 web_ui
->SetController(controller
);
756 WebUI
* WebContentsImpl::GetWebUI() const {
757 return GetRenderManager()->web_ui() ? GetRenderManager()->web_ui()
758 : GetRenderManager()->pending_web_ui();
761 WebUI
* WebContentsImpl::GetCommittedWebUI() const {
762 return GetRenderManager()->web_ui();
765 void WebContentsImpl::SetUserAgentOverride(const std::string
& override
) {
766 if (GetUserAgentOverride() == override
)
769 renderer_preferences_
.user_agent_override
= override
;
771 // Send the new override string to the renderer.
772 RenderViewHost
* host
= GetRenderViewHost();
774 host
->SyncRendererPrefs();
776 // Reload the page if a load is currently in progress to avoid having
777 // different parts of the page loaded using different user agents.
778 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
779 if (is_loading_
&& entry
!= NULL
&& entry
->GetIsOverridingUserAgent())
780 controller_
.ReloadIgnoringCache(true);
782 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
783 UserAgentOverrideSet(override
));
786 const std::string
& WebContentsImpl::GetUserAgentOverride() const {
787 return renderer_preferences_
.user_agent_override
;
790 void WebContentsImpl::EnableTreeOnlyAccessibilityMode() {
791 AddAccessibilityMode(AccessibilityModeTreeOnly
);
794 bool WebContentsImpl::IsTreeOnlyAccessibilityModeForTesting() const {
795 return accessibility_mode_
== AccessibilityModeTreeOnly
;
798 bool WebContentsImpl::IsFullAccessibilityModeForTesting() const {
799 return accessibility_mode_
== AccessibilityModeComplete
;
803 void WebContentsImpl::SetParentNativeViewAccessible(
804 gfx::NativeViewAccessible accessible_parent
) {
805 accessible_parent_
= accessible_parent
;
806 RenderFrameHostImpl
* rfh
= GetMainFrame();
808 rfh
->SetParentNativeViewAccessible(accessible_parent
);
812 const base::string16
& WebContentsImpl::GetTitle() const {
813 // Transient entries take precedence. They are used for interstitial pages
814 // that are shown on top of existing pages.
815 NavigationEntry
* entry
= controller_
.GetTransientEntry();
816 std::string accept_languages
=
817 GetContentClient()->browser()->GetAcceptLangs(
818 GetBrowserContext());
820 return entry
->GetTitleForDisplay(accept_languages
);
822 WebUI
* our_web_ui
= GetRenderManager()->pending_web_ui() ?
823 GetRenderManager()->pending_web_ui() : GetRenderManager()->web_ui();
825 // Don't override the title in view source mode.
826 entry
= controller_
.GetVisibleEntry();
827 if (!(entry
&& entry
->IsViewSourceMode())) {
828 // Give the Web UI the chance to override our title.
829 const base::string16
& title
= our_web_ui
->GetOverriddenTitle();
835 // We use the title for the last committed entry rather than a pending
836 // navigation entry. For example, when the user types in a URL, we want to
837 // keep the old page's title until the new load has committed and we get a new
839 entry
= controller_
.GetLastCommittedEntry();
841 // We make an exception for initial navigations.
842 if (controller_
.IsInitialNavigation()) {
843 // We only want to use the title from the visible entry in one of two cases:
844 // 1. There's already a committed entry for an initial navigation, in which
845 // case we are doing a history navigation in a new tab (e.g., Ctrl+Back).
846 // 2. The pending entry has been explicitly assigned a title to display.
848 // If there's no last committed entry and no assigned title, we should fall
849 // back to |page_title_when_no_navigation_entry_| rather than showing the
852 (controller_
.GetVisibleEntry() &&
853 !controller_
.GetVisibleEntry()->GetTitle().empty())) {
854 entry
= controller_
.GetVisibleEntry();
859 return entry
->GetTitleForDisplay(accept_languages
);
862 // |page_title_when_no_navigation_entry_| is finally used
863 // if no title cannot be retrieved.
864 return page_title_when_no_navigation_entry_
;
867 int32
WebContentsImpl::GetMaxPageID() {
868 return GetMaxPageIDForSiteInstance(GetSiteInstance());
871 int32
WebContentsImpl::GetMaxPageIDForSiteInstance(
872 SiteInstance
* site_instance
) {
873 if (max_page_ids_
.find(site_instance
->GetId()) == max_page_ids_
.end())
874 max_page_ids_
[site_instance
->GetId()] = -1;
876 return max_page_ids_
[site_instance
->GetId()];
879 void WebContentsImpl::UpdateMaxPageID(int32 page_id
) {
880 UpdateMaxPageIDForSiteInstance(GetSiteInstance(), page_id
);
883 void WebContentsImpl::UpdateMaxPageIDForSiteInstance(
884 SiteInstance
* site_instance
, int32 page_id
) {
885 if (GetMaxPageIDForSiteInstance(site_instance
) < page_id
)
886 max_page_ids_
[site_instance
->GetId()] = page_id
;
889 void WebContentsImpl::CopyMaxPageIDsFrom(WebContents
* web_contents
) {
890 WebContentsImpl
* contents
= static_cast<WebContentsImpl
*>(web_contents
);
891 max_page_ids_
= contents
->max_page_ids_
;
894 SiteInstanceImpl
* WebContentsImpl::GetSiteInstance() const {
895 return GetRenderManager()->current_host()->GetSiteInstance();
898 SiteInstanceImpl
* WebContentsImpl::GetPendingSiteInstance() const {
899 RenderViewHostImpl
* dest_rvh
=
900 GetRenderManager()->pending_render_view_host() ?
901 GetRenderManager()->pending_render_view_host() :
902 GetRenderManager()->current_host();
903 return dest_rvh
->GetSiteInstance();
906 bool WebContentsImpl::IsLoading() const {
910 bool WebContentsImpl::IsLoadingToDifferentDocument() const {
911 return is_loading_
&& is_load_to_different_document_
;
914 bool WebContentsImpl::IsWaitingForResponse() const {
915 return waiting_for_response_
&& is_load_to_different_document_
;
918 const net::LoadStateWithParam
& WebContentsImpl::GetLoadState() const {
922 const base::string16
& WebContentsImpl::GetLoadStateHost() const {
923 return load_state_host_
;
926 uint64
WebContentsImpl::GetUploadSize() const {
930 uint64
WebContentsImpl::GetUploadPosition() const {
931 return upload_position_
;
934 std::set
<GURL
> WebContentsImpl::GetSitesInTab() const {
935 std::set
<GURL
> sites
;
936 frame_tree_
.ForEach(base::Bind(&CollectSites
,
937 base::Unretained(GetBrowserContext()),
938 base::Unretained(&sites
)));
942 const std::string
& WebContentsImpl::GetEncoding() const {
943 return canonical_encoding_
;
946 bool WebContentsImpl::DisplayedInsecureContent() const {
947 return displayed_insecure_content_
;
950 void WebContentsImpl::IncrementCapturerCount(const gfx::Size
& capture_size
) {
951 DCHECK(!is_being_destroyed_
);
953 DVLOG(1) << "There are now " << capturer_count_
954 << " capturing(s) of WebContentsImpl@" << this;
956 // Note: This provides a hint to upstream code to size the views optimally
957 // for quality (e.g., to avoid scaling).
958 if (!capture_size
.IsEmpty() && preferred_size_for_capture_
.IsEmpty()) {
959 preferred_size_for_capture_
= capture_size
;
960 OnPreferredSizeChanged(preferred_size_
);
963 // Ensure that all views are un-occluded before capture begins.
967 void WebContentsImpl::DecrementCapturerCount() {
969 DVLOG(1) << "There are now " << capturer_count_
970 << " capturing(s) of WebContentsImpl@" << this;
971 DCHECK_LE(0, capturer_count_
);
973 if (is_being_destroyed_
)
976 if (capturer_count_
== 0) {
977 const gfx::Size old_size
= preferred_size_for_capture_
;
978 preferred_size_for_capture_
= gfx::Size();
979 OnPreferredSizeChanged(old_size
);
983 DVLOG(1) << "Executing delayed WasHidden().";
988 int WebContentsImpl::GetCapturerCount() const {
989 return capturer_count_
;
992 bool WebContentsImpl::IsAudioMuted() const {
993 return audio_muter_
.get() && audio_muter_
->is_muting();
996 void WebContentsImpl::SetAudioMuted(bool mute
) {
997 DVLOG(1) << "SetAudioMuted(mute=" << mute
<< "), was " << IsAudioMuted()
998 << " for WebContentsImpl@" << this;
1000 if (mute
== IsAudioMuted())
1005 audio_muter_
.reset(new WebContentsAudioMuter(this));
1006 audio_muter_
->StartMuting();
1008 DCHECK(audio_muter_
);
1009 audio_muter_
->StopMuting();
1012 // Notification for UI updates in response to the changed muting state.
1013 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB
);
1016 bool WebContentsImpl::IsCrashed() const {
1017 return (crashed_status_
== base::TERMINATION_STATUS_PROCESS_CRASHED
||
1018 crashed_status_
== base::TERMINATION_STATUS_ABNORMAL_TERMINATION
||
1019 crashed_status_
== base::TERMINATION_STATUS_PROCESS_WAS_KILLED
);
1022 void WebContentsImpl::SetIsCrashed(base::TerminationStatus status
,
1024 if (status
== crashed_status_
)
1027 crashed_status_
= status
;
1028 crashed_error_code_
= error_code
;
1029 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB
);
1032 base::TerminationStatus
WebContentsImpl::GetCrashedStatus() const {
1033 return crashed_status_
;
1036 bool WebContentsImpl::IsBeingDestroyed() const {
1037 return is_being_destroyed_
;
1040 void WebContentsImpl::NotifyNavigationStateChanged(
1041 InvalidateTypes changed_flags
) {
1042 // Create and release the audio power save blocker depending on whether the
1043 // tab is actively producing audio or not.
1044 if ((changed_flags
& INVALIDATE_TYPE_TAB
) &&
1045 AudioStreamMonitor::monitoring_available()) {
1046 if (WasRecentlyAudible()) {
1047 if (!audio_power_save_blocker_
)
1048 CreateAudioPowerSaveBlocker();
1050 audio_power_save_blocker_
.reset();
1055 delegate_
->NavigationStateChanged(this, changed_flags
);
1058 base::TimeTicks
WebContentsImpl::GetLastActiveTime() const {
1059 return last_active_time_
;
1062 void WebContentsImpl::WasShown() {
1063 controller_
.SetActive(true);
1065 for (RenderWidgetHostView
* view
: GetRenderWidgetHostViewsInTree()) {
1068 #if defined(OS_MACOSX)
1069 view
->SetActive(true);
1074 last_active_time_
= base::TimeTicks::Now();
1076 // The resize rect might have changed while this was inactive -- send the new
1077 // one to make sure it's up to date.
1078 RenderViewHostImpl
* rvh
=
1079 static_cast<RenderViewHostImpl
*>(GetRenderViewHost());
1081 rvh
->ResizeRectChanged(GetRootWindowResizerRect());
1084 // Restore power save blocker if there are active video players running.
1085 if (!active_video_players_
.empty() && !video_power_save_blocker_
)
1086 CreateVideoPowerSaveBlocker();
1088 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, WasShown());
1090 should_normally_be_visible_
= true;
1093 void WebContentsImpl::WasHidden() {
1094 // If there are entities capturing screenshots or video (e.g., mirroring),
1095 // don't activate the "disable rendering" optimization.
1096 if (capturer_count_
== 0) {
1097 // |GetRenderViewHost()| can be NULL if the user middle clicks a link to
1098 // open a tab in the background, then closes the tab before selecting it.
1099 // This is because closing the tab calls WebContentsImpl::Destroy(), which
1100 // removes the |GetRenderViewHost()|; then when we actually destroy the
1101 // window, OnWindowPosChanged() notices and calls WasHidden() (which
1103 for (RenderWidgetHostView
* view
: GetRenderWidgetHostViewsInTree()) {
1108 // Release any video power save blockers held as video is not visible.
1109 video_power_save_blocker_
.reset();
1112 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, WasHidden());
1114 should_normally_be_visible_
= false;
1117 void WebContentsImpl::WasOccluded() {
1118 if (capturer_count_
> 0)
1121 for (RenderWidgetHostView
* view
: GetRenderWidgetHostViewsInTree()) {
1123 view
->WasOccluded();
1127 void WebContentsImpl::WasUnOccluded() {
1128 for (RenderWidgetHostView
* view
: GetRenderWidgetHostViewsInTree()) {
1130 view
->WasUnOccluded();
1134 bool WebContentsImpl::NeedToFireBeforeUnload() {
1135 bool sudden_termination_allowed
= true;
1136 frame_tree_
.ForEach(base::Bind(
1137 &SuddenTerminationAllowed
, &sudden_termination_allowed
));
1138 // TODO(creis): Should we fire even for interstitial pages?
1139 return WillNotifyDisconnection() &&
1140 !ShowingInterstitialPage() &&
1141 !sudden_termination_allowed
;
1144 void WebContentsImpl::DispatchBeforeUnload(bool for_cross_site_transition
) {
1145 GetMainFrame()->DispatchBeforeUnload(for_cross_site_transition
);
1148 void WebContentsImpl::Stop() {
1149 GetRenderManager()->Stop();
1150 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, NavigationStopped());
1153 WebContents
* WebContentsImpl::Clone() {
1154 // We use our current SiteInstance since the cloned entry will use it anyway.
1155 // We pass our own opener so that the cloned page can access it if it was
1157 CreateParams
create_params(GetBrowserContext(), GetSiteInstance());
1158 create_params
.initial_size
= GetContainerBounds().size();
1159 WebContentsImpl
* tc
= CreateWithOpener(create_params
, opener_
);
1160 tc
->GetController().CopyStateFrom(controller_
);
1161 FOR_EACH_OBSERVER(WebContentsObserver
,
1163 DidCloneToNewWebContents(this, tc
));
1167 void WebContentsImpl::Observe(int type
,
1168 const NotificationSource
& source
,
1169 const NotificationDetails
& details
) {
1171 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED
: {
1172 RenderWidgetHost
* host
= Source
<RenderWidgetHost
>(source
).ptr();
1173 RenderWidgetHostView
* view
= host
->GetView();
1174 if (view
== GetFullscreenRenderWidgetHostView()) {
1175 // We cannot just call view_->RestoreFocus() here. On some platforms,
1176 // attempting to focus the currently-invisible WebContentsView will be
1177 // flat-out ignored. Therefore, this boolean is used to track whether
1178 // we will request focus after the fullscreen widget has been
1180 fullscreen_widget_had_focus_at_shutdown_
= (view
&& view
->HasFocus());
1182 for (PendingWidgetViews::iterator i
= pending_widget_views_
.begin();
1183 i
!= pending_widget_views_
.end(); ++i
) {
1184 if (host
->GetView() == i
->second
) {
1185 pending_widget_views_
.erase(i
);
1197 WebContents
* WebContentsImpl::GetWebContents() {
1201 void WebContentsImpl::Init(const WebContents::CreateParams
& params
) {
1202 // This is set before initializing the render manager since
1203 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
1204 // it should be hidden.
1205 should_normally_be_visible_
= !params
.initially_hidden
;
1207 // Either both routing ids can be given, or neither can be.
1208 DCHECK((params
.routing_id
== MSG_ROUTING_NONE
&&
1209 params
.main_frame_routing_id
== MSG_ROUTING_NONE
) ||
1210 (params
.routing_id
!= MSG_ROUTING_NONE
&&
1211 params
.main_frame_routing_id
!= MSG_ROUTING_NONE
));
1212 GetRenderManager()->Init(
1213 params
.browser_context
, params
.site_instance
, params
.routing_id
,
1214 params
.main_frame_routing_id
);
1216 WebContentsViewDelegate
* delegate
=
1217 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
1219 if (browser_plugin_guest_
) {
1220 scoped_ptr
<WebContentsView
> platform_view(CreateWebContentsView(
1221 this, delegate
, &render_view_host_delegate_view_
));
1223 WebContentsViewGuest
* rv
= new WebContentsViewGuest(
1224 this, browser_plugin_guest_
.get(), platform_view
.Pass(),
1225 render_view_host_delegate_view_
);
1226 render_view_host_delegate_view_
= rv
;
1229 // Regular WebContentsView.
1230 view_
.reset(CreateWebContentsView(
1231 this, delegate
, &render_view_host_delegate_view_
));
1233 CHECK(render_view_host_delegate_view_
);
1236 gfx::Size initial_size
= params
.initial_size
;
1237 view_
->CreateView(initial_size
, params
.context
);
1239 // Listen for whether our opener gets destroyed.
1241 AddDestructionObserver(opener_
);
1243 #if defined(ENABLE_PLUGINS)
1244 plugin_content_origin_whitelist_
.reset(
1245 new PluginContentOriginWhitelist(this));
1248 registrar_
.Add(this,
1249 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED
,
1250 NotificationService::AllBrowserContextsAndSources());
1252 screen_orientation_dispatcher_host_
.reset(
1253 new ScreenOrientationDispatcherHostImpl(this));
1255 manifest_manager_host_
.reset(new ManifestManagerHost(this));
1257 #if defined(OS_ANDROID)
1258 date_time_chooser_
.reset(new DateTimeChooserAndroid());
1261 // BrowserPluginGuest::Init needs to be called after this WebContents has
1262 // a RenderWidgetHostViewGuest. That is, |view_->CreateView| above.
1263 if (browser_plugin_guest_
)
1264 browser_plugin_guest_
->Init();
1266 for (size_t i
= 0; i
< g_created_callbacks
.Get().size(); i
++)
1267 g_created_callbacks
.Get().at(i
).Run(this);
1270 void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl
* web_contents
) {
1271 RemoveDestructionObserver(web_contents
);
1273 // Clear the opener if it has been closed.
1274 if (web_contents
== opener_
) {
1278 // Clear a pending contents that has been closed before being shown.
1279 for (PendingContents::iterator iter
= pending_contents_
.begin();
1280 iter
!= pending_contents_
.end();
1282 if (iter
->second
!= web_contents
)
1284 pending_contents_
.erase(iter
);
1290 void WebContentsImpl::AddDestructionObserver(WebContentsImpl
* web_contents
) {
1291 if (!ContainsKey(destruction_observers_
, web_contents
)) {
1292 destruction_observers_
[web_contents
] =
1293 new DestructionObserver(this, web_contents
);
1297 void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl
* web_contents
) {
1298 DestructionObservers::iterator iter
=
1299 destruction_observers_
.find(web_contents
);
1300 if (iter
!= destruction_observers_
.end()) {
1301 delete destruction_observers_
[web_contents
];
1302 destruction_observers_
.erase(iter
);
1306 void WebContentsImpl::AddObserver(WebContentsObserver
* observer
) {
1307 observers_
.AddObserver(observer
);
1310 void WebContentsImpl::RemoveObserver(WebContentsObserver
* observer
) {
1311 observers_
.RemoveObserver(observer
);
1314 std::set
<RenderWidgetHostView
*>
1315 WebContentsImpl::GetRenderWidgetHostViewsInTree() {
1316 std::set
<RenderWidgetHostView
*> set
;
1317 if (ShowingInterstitialPage()) {
1318 set
.insert(GetRenderWidgetHostView());
1321 base::Bind(&AddRenderWidgetHostViewToSet
, base::Unretained(&set
)));
1326 void WebContentsImpl::Activate() {
1328 delegate_
->ActivateContents(this);
1331 void WebContentsImpl::Deactivate() {
1333 delegate_
->DeactivateContents(this);
1336 void WebContentsImpl::LostCapture() {
1338 delegate_
->LostCapture();
1341 void WebContentsImpl::RenderWidgetDeleted(
1342 RenderWidgetHostImpl
* render_widget_host
) {
1343 if (is_being_destroyed_
) {
1344 // |created_widgets_| might have been destroyed.
1348 std::set
<RenderWidgetHostImpl
*>::iterator iter
=
1349 created_widgets_
.find(render_widget_host
);
1350 if (iter
!= created_widgets_
.end())
1351 created_widgets_
.erase(iter
);
1353 if (render_widget_host
&&
1354 render_widget_host
->GetRoutingID() == fullscreen_widget_routing_id_
) {
1355 if (delegate_
&& delegate_
->EmbedsFullscreenWidget())
1356 delegate_
->ExitFullscreenModeForTab(this);
1357 FOR_EACH_OBSERVER(WebContentsObserver
,
1359 DidDestroyFullscreenWidget(
1360 fullscreen_widget_routing_id_
));
1361 fullscreen_widget_routing_id_
= MSG_ROUTING_NONE
;
1362 if (fullscreen_widget_had_focus_at_shutdown_
)
1363 view_
->RestoreFocus();
1367 void WebContentsImpl::RenderWidgetGotFocus(
1368 RenderWidgetHostImpl
* render_widget_host
) {
1369 // Notify the delegate if an embedded fullscreen widget was focused.
1370 if (delegate_
&& render_widget_host
&&
1371 delegate_
->EmbedsFullscreenWidget() &&
1372 render_widget_host
->GetView() == GetFullscreenRenderWidgetHostView())
1373 delegate_
->WebContentsFocused(this);
1376 void WebContentsImpl::RenderWidgetWasResized(
1377 RenderWidgetHostImpl
* render_widget_host
,
1378 bool width_changed
) {
1379 RenderFrameHostImpl
* rfh
= GetMainFrame();
1380 if (!rfh
|| render_widget_host
!= rfh
->GetRenderWidgetHost())
1383 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1384 MainFrameWasResized(width_changed
));
1387 bool WebContentsImpl::PreHandleKeyboardEvent(
1388 const NativeWebKeyboardEvent
& event
,
1389 bool* is_keyboard_shortcut
) {
1391 delegate_
->PreHandleKeyboardEvent(this, event
, is_keyboard_shortcut
);
1394 void WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent
& event
) {
1395 if (browser_plugin_embedder_
&&
1396 browser_plugin_embedder_
->HandleKeyboardEvent(event
)) {
1400 delegate_
->HandleKeyboardEvent(this, event
);
1403 bool WebContentsImpl::HandleWheelEvent(
1404 const blink::WebMouseWheelEvent
& event
) {
1405 #if !defined(OS_MACOSX)
1406 // On platforms other than Mac, control+mousewheel may change zoom. On Mac,
1407 // this isn't done for two reasons:
1408 // -the OS already has a gesture to do this through pinch-zoom
1409 // -if a user starts an inertial scroll, let's go, and presses control
1410 // (i.e. control+tab) then the OS's buffered scroll events will come in
1411 // with control key set which isn't what the user wants
1412 if (delegate_
&& event
.wheelTicksY
&&
1413 (event
.modifiers
& blink::WebInputEvent::ControlKey
) &&
1415 delegate_
->ContentsZoomChange(event
.wheelTicksY
> 0);
1422 bool WebContentsImpl::PreHandleGestureEvent(
1423 const blink::WebGestureEvent
& event
) {
1424 return delegate_
&& delegate_
->PreHandleGestureEvent(this, event
);
1427 void WebContentsImpl::HandleMouseDown() {
1429 delegate_
->HandleMouseDown();
1432 void WebContentsImpl::HandleMouseUp() {
1434 delegate_
->HandleMouseUp();
1437 void WebContentsImpl::HandlePointerActivate() {
1439 delegate_
->HandlePointerActivate();
1442 void WebContentsImpl::HandleGestureBegin() {
1444 delegate_
->HandleGestureBegin();
1447 void WebContentsImpl::HandleGestureEnd() {
1449 delegate_
->HandleGestureEnd();
1452 void WebContentsImpl::EnterFullscreenMode(const GURL
& origin
) {
1453 // This method is being called to enter renderer-initiated fullscreen mode.
1454 // Make sure any existing fullscreen widget is shut down first.
1455 RenderWidgetHostView
* const widget_view
= GetFullscreenRenderWidgetHostView();
1457 RenderWidgetHostImpl::From(widget_view
->GetRenderWidgetHost())->Shutdown();
1460 delegate_
->EnterFullscreenModeForTab(this, origin
);
1462 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1463 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1466 void WebContentsImpl::ExitFullscreenMode() {
1467 // This method is being called to leave renderer-initiated fullscreen mode.
1468 // Make sure any existing fullscreen widget is shut down first.
1469 RenderWidgetHostView
* const widget_view
= GetFullscreenRenderWidgetHostView();
1471 RenderWidgetHostImpl::From(widget_view
->GetRenderWidgetHost())->Shutdown();
1473 #if defined(OS_ANDROID)
1474 ContentVideoView
* video_view
= ContentVideoView::GetInstance();
1475 if (video_view
!= NULL
)
1476 video_view
->OnExitFullscreen();
1480 delegate_
->ExitFullscreenModeForTab(this);
1482 FOR_EACH_OBSERVER(WebContentsObserver
,
1484 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1487 bool WebContentsImpl::IsFullscreenForCurrentTab() const {
1488 return delegate_
? delegate_
->IsFullscreenForTabOrPending(this) : false;
1491 void WebContentsImpl::RequestToLockMouse(bool user_gesture
,
1492 bool last_unlocked_by_target
) {
1494 delegate_
->RequestToLockMouse(this, user_gesture
, last_unlocked_by_target
);
1496 GotResponseToLockMouseRequest(false);
1500 void WebContentsImpl::LostMouseLock() {
1502 delegate_
->LostMouseLock();
1505 void WebContentsImpl::CreateNewWindow(
1506 int render_process_id
,
1508 int main_frame_route_id
,
1509 const ViewHostMsg_CreateWindow_Params
& params
,
1510 SessionStorageNamespace
* session_storage_namespace
) {
1511 // We usually create the new window in the same BrowsingInstance (group of
1512 // script-related windows), by passing in the current SiteInstance. However,
1513 // if the opener is being suppressed (in a non-guest), we create a new
1514 // SiteInstance in its own BrowsingInstance.
1515 bool is_guest
= BrowserPluginGuest::IsGuest(this);
1517 // If the opener is to be suppressed, the new window can be in any process.
1518 // Since routing ids are process specific, we must not have one passed in
1519 // as argument here.
1520 DCHECK(!params
.opener_suppressed
|| route_id
== MSG_ROUTING_NONE
);
1522 scoped_refptr
<SiteInstance
> site_instance
=
1523 params
.opener_suppressed
&& !is_guest
?
1524 SiteInstance::CreateForURL(GetBrowserContext(), params
.target_url
) :
1527 // A message to create a new window can only come from the active process for
1528 // this WebContentsImpl instance. If any other process sends the request,
1529 // it is invalid and the process must be terminated.
1530 if (GetRenderProcessHost()->GetID() != render_process_id
) {
1531 RenderProcessHost
* rph
= RenderProcessHost::FromID(render_process_id
);
1532 base::ProcessHandle process_handle
= rph
->GetHandle();
1533 if (process_handle
!= base::kNullProcessHandle
) {
1535 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWindow"));
1536 rph
->Shutdown(RESULT_CODE_KILLED
, false);
1541 // We must assign the SessionStorageNamespace before calling Init().
1543 // http://crbug.com/142685
1544 const std::string
& partition_id
=
1545 GetContentClient()->browser()->
1546 GetStoragePartitionIdForSite(GetBrowserContext(),
1547 site_instance
->GetSiteURL());
1548 StoragePartition
* partition
= BrowserContext::GetStoragePartition(
1549 GetBrowserContext(), site_instance
.get());
1550 DOMStorageContextWrapper
* dom_storage_context
=
1551 static_cast<DOMStorageContextWrapper
*>(partition
->GetDOMStorageContext());
1552 SessionStorageNamespaceImpl
* session_storage_namespace_impl
=
1553 static_cast<SessionStorageNamespaceImpl
*>(session_storage_namespace
);
1554 CHECK(session_storage_namespace_impl
->IsFromContext(dom_storage_context
));
1557 !delegate_
->ShouldCreateWebContents(this,
1559 main_frame_route_id
,
1560 params
.window_container_type
,
1564 session_storage_namespace
)) {
1565 if (route_id
!= MSG_ROUTING_NONE
&&
1566 !RenderViewHost::FromID(render_process_id
, route_id
)) {
1567 // If the embedder didn't create a WebContents for this route, we need to
1568 // delete the RenderView that had already been created.
1569 Send(new ViewMsg_Close(route_id
));
1571 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(route_id
);
1572 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(
1573 main_frame_route_id
);
1577 // Create the new web contents. This will automatically create the new
1578 // WebContentsView. In the future, we may want to create the view separately.
1579 CreateParams
create_params(GetBrowserContext(), site_instance
.get());
1580 create_params
.routing_id
= route_id
;
1581 create_params
.main_frame_routing_id
= main_frame_route_id
;
1582 create_params
.opener
= this;
1583 create_params
.opener_suppressed
= params
.opener_suppressed
;
1584 if (params
.disposition
== NEW_BACKGROUND_TAB
)
1585 create_params
.initially_hidden
= true;
1587 WebContentsImpl
* new_contents
= NULL
;
1589 create_params
.context
= view_
->GetNativeView();
1590 create_params
.initial_size
= GetContainerBounds().size();
1591 new_contents
= static_cast<WebContentsImpl
*>(
1592 WebContents::Create(create_params
));
1594 new_contents
= GetBrowserPluginGuest()->CreateNewGuestWindow(create_params
);
1596 new_contents
->GetController().SetSessionStorageNamespace(
1598 session_storage_namespace
);
1599 new_contents
->RenderViewCreated(new_contents
->GetRenderViewHost());
1601 // Save the window for later if we're not suppressing the opener (since it
1602 // will be shown immediately).
1603 if (!params
.opener_suppressed
) {
1605 WebContentsView
* new_view
= new_contents
->view_
.get();
1607 // TODO(brettw): It seems bogus that we have to call this function on the
1608 // newly created object and give it one of its own member variables.
1609 new_view
->CreateViewForWidget(new_contents
->GetRenderViewHost(), false);
1611 // Save the created window associated with the route so we can show it
1613 DCHECK_NE(MSG_ROUTING_NONE
, route_id
);
1614 pending_contents_
[route_id
] = new_contents
;
1615 AddDestructionObserver(new_contents
);
1619 delegate_
->WebContentsCreated(
1620 this, params
.opener_render_frame_id
, params
.frame_name
,
1621 params
.target_url
, new_contents
);
1624 if (params
.opener_suppressed
) {
1625 // When the opener is suppressed, the original renderer cannot access the
1626 // new window. As a result, we need to show and navigate the window here.
1627 bool was_blocked
= false;
1629 gfx::Rect initial_rect
;
1630 delegate_
->AddNewContents(
1631 this, new_contents
, params
.disposition
, initial_rect
,
1632 params
.user_gesture
, &was_blocked
);
1635 OpenURLParams
open_params(params
.target_url
,
1638 ui::PAGE_TRANSITION_LINK
,
1639 true /* is_renderer_initiated */);
1640 open_params
.user_gesture
= params
.user_gesture
;
1641 new_contents
->OpenURL(open_params
);
1646 void WebContentsImpl::CreateNewWidget(int render_process_id
,
1648 blink::WebPopupType popup_type
) {
1649 CreateNewWidget(render_process_id
, route_id
, false, popup_type
);
1652 void WebContentsImpl::CreateNewFullscreenWidget(int render_process_id
,
1654 CreateNewWidget(render_process_id
, route_id
, true, blink::WebPopupTypeNone
);
1657 void WebContentsImpl::CreateNewWidget(int render_process_id
,
1660 blink::WebPopupType popup_type
) {
1661 RenderProcessHost
* process
= GetRenderProcessHost();
1662 // A message to create a new widget can only come from the active process for
1663 // this WebContentsImpl instance. If any other process sends the request,
1664 // it is invalid and the process must be terminated.
1665 if (process
->GetID() != render_process_id
) {
1666 RenderProcessHost
* rph
= RenderProcessHost::FromID(render_process_id
);
1667 base::ProcessHandle process_handle
= rph
->GetHandle();
1668 if (process_handle
!= base::kNullProcessHandle
) {
1670 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWidget"));
1671 rph
->Shutdown(RESULT_CODE_KILLED
, false);
1676 RenderWidgetHostImpl
* widget_host
=
1677 new RenderWidgetHostImpl(this, process
, route_id
, IsHidden());
1678 created_widgets_
.insert(widget_host
);
1680 RenderWidgetHostViewBase
* widget_view
=
1681 static_cast<RenderWidgetHostViewBase
*>(
1682 view_
->CreateViewForPopupWidget(widget_host
));
1685 if (!is_fullscreen
) {
1686 // Popups should not get activated.
1687 widget_view
->SetPopupType(popup_type
);
1689 // Save the created widget associated with the route so we can show it later.
1690 pending_widget_views_
[route_id
] = widget_view
;
1692 #if defined(OS_MACOSX)
1693 // A RenderWidgetHostViewMac has lifetime scoped to the view. We'll retain it
1694 // to allow it to survive the trip without being hosted.
1695 base::mac::NSObjectRetain(widget_view
->GetNativeView());
1699 void WebContentsImpl::ShowCreatedWindow(int route_id
,
1700 WindowOpenDisposition disposition
,
1701 const gfx::Rect
& initial_rect
,
1702 bool user_gesture
) {
1703 WebContentsImpl
* contents
= GetCreatedWindow(route_id
);
1705 WebContentsDelegate
* delegate
= GetDelegate();
1707 delegate
->AddNewContents(
1708 this, contents
, disposition
, initial_rect
, user_gesture
, NULL
);
1713 void WebContentsImpl::ShowCreatedWidget(int route_id
,
1714 const gfx::Rect
& initial_rect
) {
1715 ShowCreatedWidget(route_id
, false, initial_rect
);
1718 void WebContentsImpl::ShowCreatedFullscreenWidget(int route_id
) {
1719 ShowCreatedWidget(route_id
, true, gfx::Rect());
1722 void WebContentsImpl::ShowCreatedWidget(int route_id
,
1724 const gfx::Rect
& initial_rect
) {
1725 RenderWidgetHostViewBase
* widget_host_view
=
1726 static_cast<RenderWidgetHostViewBase
*>(GetCreatedWidget(route_id
));
1727 if (!widget_host_view
)
1730 RenderWidgetHostView
* view
= NULL
;
1731 BrowserPluginGuest
* guest
= GetBrowserPluginGuest();
1732 if (guest
&& guest
->embedder_web_contents()) {
1733 view
= guest
->embedder_web_contents()->GetRenderWidgetHostView();
1735 view
= GetRenderWidgetHostView();
1738 if (is_fullscreen
) {
1739 DCHECK_EQ(MSG_ROUTING_NONE
, fullscreen_widget_routing_id_
);
1740 view_
->StoreFocus();
1741 fullscreen_widget_routing_id_
= route_id
;
1742 if (delegate_
&& delegate_
->EmbedsFullscreenWidget()) {
1743 widget_host_view
->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
1744 delegate_
->EnterFullscreenModeForTab(this, GURL());
1746 widget_host_view
->InitAsFullscreen(view
);
1748 FOR_EACH_OBSERVER(WebContentsObserver
,
1750 DidShowFullscreenWidget(route_id
));
1751 if (!widget_host_view
->HasFocus())
1752 widget_host_view
->Focus();
1754 widget_host_view
->InitAsPopup(view
, initial_rect
);
1757 RenderWidgetHostImpl
* render_widget_host_impl
=
1758 RenderWidgetHostImpl::From(widget_host_view
->GetRenderWidgetHost());
1759 render_widget_host_impl
->Init();
1760 // Only allow privileged mouse lock for fullscreen render widget, which is
1761 // used to implement Pepper Flash fullscreen.
1762 render_widget_host_impl
->set_allow_privileged_mouse_lock(is_fullscreen
);
1764 #if defined(OS_MACOSX)
1765 // A RenderWidgetHostViewMac has lifetime scoped to the view. Now that it's
1766 // properly embedded (or purposefully ignored) we can release the retain we
1767 // took in CreateNewWidget().
1768 base::mac::NSObjectRelease(widget_host_view
->GetNativeView());
1772 WebContentsImpl
* WebContentsImpl::GetCreatedWindow(int route_id
) {
1773 PendingContents::iterator iter
= pending_contents_
.find(route_id
);
1775 // Certain systems can block the creation of new windows. If we didn't succeed
1776 // in creating one, just return NULL.
1777 if (iter
== pending_contents_
.end()) {
1781 WebContentsImpl
* new_contents
= iter
->second
;
1782 pending_contents_
.erase(route_id
);
1783 RemoveDestructionObserver(new_contents
);
1785 // Don't initialize the guest WebContents immediately.
1786 if (BrowserPluginGuest::IsGuest(new_contents
))
1787 return new_contents
;
1789 if (!new_contents
->GetRenderProcessHost()->HasConnection() ||
1790 !new_contents
->GetRenderViewHost()->GetView())
1793 // Resume blocked requests for both the RenderViewHost and RenderFrameHost.
1794 // TODO(brettw): It seems bogus to reach into here and initialize the host.
1795 static_cast<RenderViewHostImpl
*>(new_contents
->GetRenderViewHost())->Init();
1796 new_contents
->GetMainFrame()->Init();
1798 return new_contents
;
1801 RenderWidgetHostView
* WebContentsImpl::GetCreatedWidget(int route_id
) {
1802 PendingWidgetViews::iterator iter
= pending_widget_views_
.find(route_id
);
1803 if (iter
== pending_widget_views_
.end()) {
1808 RenderWidgetHostView
* widget_host_view
= iter
->second
;
1809 pending_widget_views_
.erase(route_id
);
1811 RenderWidgetHost
* widget_host
= widget_host_view
->GetRenderWidgetHost();
1812 if (!widget_host
->GetProcess()->HasConnection()) {
1813 // The view has gone away or the renderer crashed. Nothing to do.
1817 return widget_host_view
;
1820 void WebContentsImpl::RequestMediaAccessPermission(
1821 const MediaStreamRequest
& request
,
1822 const MediaResponseCallback
& callback
) {
1824 delegate_
->RequestMediaAccessPermission(this, request
, callback
);
1826 callback
.Run(MediaStreamDevices(),
1827 MEDIA_DEVICE_FAILED_DUE_TO_SHUTDOWN
,
1828 scoped_ptr
<MediaStreamUI
>());
1832 bool WebContentsImpl::CheckMediaAccessPermission(const GURL
& security_origin
,
1833 MediaStreamType type
) {
1834 DCHECK(type
== MEDIA_DEVICE_AUDIO_CAPTURE
||
1835 type
== MEDIA_DEVICE_VIDEO_CAPTURE
);
1837 delegate_
->CheckMediaAccessPermission(this, security_origin
, type
);
1840 SessionStorageNamespace
* WebContentsImpl::GetSessionStorageNamespace(
1841 SiteInstance
* instance
) {
1842 return controller_
.GetSessionStorageNamespace(instance
);
1845 SessionStorageNamespaceMap
WebContentsImpl::GetSessionStorageNamespaceMap() {
1846 return controller_
.GetSessionStorageNamespaceMap();
1849 FrameTree
* WebContentsImpl::GetFrameTree() {
1850 return &frame_tree_
;
1853 void WebContentsImpl::SetIsVirtualKeyboardRequested(bool requested
) {
1854 virtual_keyboard_requested_
= requested
;
1857 bool WebContentsImpl::IsVirtualKeyboardRequested() {
1858 return virtual_keyboard_requested_
;
1861 AccessibilityMode
WebContentsImpl::GetAccessibilityMode() const {
1862 return accessibility_mode_
;
1865 void WebContentsImpl::AccessibilityEventReceived(
1866 const std::vector
<AXEventNotificationDetails
>& details
) {
1868 WebContentsObserver
, observers_
, AccessibilityEventReceived(details
));
1871 RenderFrameHost
* WebContentsImpl::GetGuestByInstanceID(
1872 int browser_plugin_instance_id
) {
1873 BrowserPluginGuestManager
* guest_manager
=
1874 GetBrowserContext()->GetGuestManager();
1875 WebContents
* guest
= guest_manager
->GetGuestByInstanceID(
1876 this, browser_plugin_instance_id
);
1879 return guest
->GetMainFrame();
1882 GeolocationServiceContext
* WebContentsImpl::GetGeolocationServiceContext() {
1883 return geolocation_service_context_
.get();
1886 void WebContentsImpl::OnShowValidationMessage(
1887 const gfx::Rect
& anchor_in_root_view
,
1888 const base::string16
& main_text
,
1889 const base::string16
& sub_text
) {
1891 delegate_
->ShowValidationMessage(
1892 this, anchor_in_root_view
, main_text
, sub_text
);
1895 void WebContentsImpl::OnHideValidationMessage() {
1897 delegate_
->HideValidationMessage(this);
1900 void WebContentsImpl::OnMoveValidationMessage(
1901 const gfx::Rect
& anchor_in_root_view
) {
1903 delegate_
->MoveValidationMessage(this, anchor_in_root_view
);
1906 void WebContentsImpl::DidSendScreenRects(RenderWidgetHostImpl
* rwh
) {
1907 if (browser_plugin_embedder_
)
1908 browser_plugin_embedder_
->DidSendScreenRects();
1911 BrowserAccessibilityManager
*
1912 WebContentsImpl::GetRootBrowserAccessibilityManager() {
1913 RenderFrameHostImpl
* rfh
= GetMainFrame();
1914 return rfh
? rfh
->browser_accessibility_manager() : NULL
;
1917 BrowserAccessibilityManager
*
1918 WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
1919 RenderFrameHostImpl
* rfh
= GetMainFrame();
1920 return rfh
? rfh
->GetOrCreateBrowserAccessibilityManager() : NULL
;
1923 void WebContentsImpl::UpdatePreferredSize(const gfx::Size
& pref_size
) {
1924 const gfx::Size old_size
= GetPreferredSize();
1925 preferred_size_
= pref_size
;
1926 OnPreferredSizeChanged(old_size
);
1929 void WebContentsImpl::ResizeDueToAutoResize(const gfx::Size
& new_size
) {
1931 delegate_
->ResizeDueToAutoResize(this, new_size
);
1934 WebContents
* WebContentsImpl::OpenURL(const OpenURLParams
& params
) {
1938 WebContents
* new_contents
= delegate_
->OpenURLFromTab(this, params
);
1939 return new_contents
;
1942 bool WebContentsImpl::Send(IPC::Message
* message
) {
1943 if (!GetRenderViewHost()) {
1948 return GetRenderViewHost()->Send(message
);
1951 bool WebContentsImpl::NavigateToPendingEntry(
1952 NavigationController::ReloadType reload_type
) {
1953 FrameTreeNode
* node
= frame_tree_
.root();
1955 // Navigate in the FrameTreeNode specified in the pending entry, if any. This
1956 // is currently only used in --site-per-process and tests.
1957 NavigationEntryImpl
* pending_entry
=
1958 NavigationEntryImpl::FromNavigationEntry(controller_
.GetPendingEntry());
1959 if (pending_entry
->frame_tree_node_id() != -1) {
1960 FrameTreeNode
* subframe
=
1961 frame_tree_
.FindByID(pending_entry
->frame_tree_node_id());
1967 return node
->navigator()->NavigateToPendingEntry(
1968 node
->current_frame_host(), reload_type
);
1971 void WebContentsImpl::RenderFrameForInterstitialPageCreated(
1972 RenderFrameHost
* render_frame_host
) {
1973 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1974 RenderFrameForInterstitialPageCreated(render_frame_host
));
1977 void WebContentsImpl::AttachInterstitialPage(
1978 InterstitialPageImpl
* interstitial_page
) {
1979 DCHECK(interstitial_page
);
1980 GetRenderManager()->set_interstitial_page(interstitial_page
);
1982 // Cancel any visible dialogs so that they don't interfere with the
1984 if (dialog_manager_
)
1985 dialog_manager_
->CancelActiveAndPendingDialogs(this);
1987 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1988 DidAttachInterstitialPage());
1991 void WebContentsImpl::DetachInterstitialPage() {
1992 if (ShowingInterstitialPage())
1993 GetRenderManager()->remove_interstitial_page();
1994 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1995 DidDetachInterstitialPage());
1998 void WebContentsImpl::SetHistoryOffsetAndLength(int history_offset
,
1999 int history_length
) {
2000 SetHistoryOffsetAndLengthForView(
2001 GetRenderViewHost(), history_offset
, history_length
);
2004 void WebContentsImpl::SetHistoryOffsetAndLengthForView(
2005 RenderViewHost
* render_view_host
,
2007 int history_length
) {
2008 render_view_host
->Send(new ViewMsg_SetHistoryOffsetAndLength(
2009 render_view_host
->GetRoutingID(), history_offset
, history_length
));
2012 void WebContentsImpl::ReloadFocusedFrame(bool ignore_cache
) {
2013 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2017 focused_frame
->Send(new FrameMsg_Reload(
2018 focused_frame
->GetRoutingID(), ignore_cache
));
2021 void WebContentsImpl::Undo() {
2022 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2026 focused_frame
->Send(new InputMsg_Undo(focused_frame
->GetRoutingID()));
2027 RecordAction(base::UserMetricsAction("Undo"));
2030 void WebContentsImpl::Redo() {
2031 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2034 focused_frame
->Send(new InputMsg_Redo(focused_frame
->GetRoutingID()));
2035 RecordAction(base::UserMetricsAction("Redo"));
2038 void WebContentsImpl::Cut() {
2039 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2043 focused_frame
->Send(new InputMsg_Cut(focused_frame
->GetRoutingID()));
2044 RecordAction(base::UserMetricsAction("Cut"));
2047 void WebContentsImpl::Copy() {
2048 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2052 focused_frame
->Send(new InputMsg_Copy(focused_frame
->GetRoutingID()));
2053 RecordAction(base::UserMetricsAction("Copy"));
2056 void WebContentsImpl::CopyToFindPboard() {
2057 #if defined(OS_MACOSX)
2058 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2062 // Windows/Linux don't have the concept of a find pasteboard.
2063 focused_frame
->Send(
2064 new InputMsg_CopyToFindPboard(focused_frame
->GetRoutingID()));
2065 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
2069 void WebContentsImpl::Paste() {
2070 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2074 focused_frame
->Send(new InputMsg_Paste(focused_frame
->GetRoutingID()));
2075 RecordAction(base::UserMetricsAction("Paste"));
2078 void WebContentsImpl::PasteAndMatchStyle() {
2079 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2083 focused_frame
->Send(new InputMsg_PasteAndMatchStyle(
2084 focused_frame
->GetRoutingID()));
2085 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
2088 void WebContentsImpl::Delete() {
2089 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2093 focused_frame
->Send(new InputMsg_Delete(focused_frame
->GetRoutingID()));
2094 RecordAction(base::UserMetricsAction("DeleteSelection"));
2097 void WebContentsImpl::SelectAll() {
2098 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2102 focused_frame
->Send(new InputMsg_SelectAll(focused_frame
->GetRoutingID()));
2103 RecordAction(base::UserMetricsAction("SelectAll"));
2106 void WebContentsImpl::Unselect() {
2107 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2111 focused_frame
->Send(new InputMsg_Unselect(focused_frame
->GetRoutingID()));
2112 RecordAction(base::UserMetricsAction("Unselect"));
2115 void WebContentsImpl::Replace(const base::string16
& word
) {
2116 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2120 focused_frame
->Send(new InputMsg_Replace(
2121 focused_frame
->GetRoutingID(), word
));
2124 void WebContentsImpl::ReplaceMisspelling(const base::string16
& word
) {
2125 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2129 focused_frame
->Send(new InputMsg_ReplaceMisspelling(
2130 focused_frame
->GetRoutingID(), word
));
2133 void WebContentsImpl::NotifyContextMenuClosed(
2134 const CustomContextMenuContext
& context
) {
2135 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2139 focused_frame
->Send(new FrameMsg_ContextMenuClosed(
2140 focused_frame
->GetRoutingID(), context
));
2143 void WebContentsImpl::ExecuteCustomContextMenuCommand(
2144 int action
, const CustomContextMenuContext
& context
) {
2145 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2149 focused_frame
->Send(new FrameMsg_CustomContextMenuAction(
2150 focused_frame
->GetRoutingID(), context
, action
));
2153 gfx::NativeView
WebContentsImpl::GetNativeView() {
2154 return view_
->GetNativeView();
2157 gfx::NativeView
WebContentsImpl::GetContentNativeView() {
2158 return view_
->GetContentNativeView();
2161 gfx::NativeWindow
WebContentsImpl::GetTopLevelNativeWindow() {
2162 return view_
->GetTopLevelNativeWindow();
2165 gfx::Rect
WebContentsImpl::GetViewBounds() {
2166 return view_
->GetViewBounds();
2169 gfx::Rect
WebContentsImpl::GetContainerBounds() {
2171 view_
->GetContainerBounds(&rv
);
2175 DropData
* WebContentsImpl::GetDropData() {
2176 return view_
->GetDropData();
2179 void WebContentsImpl::Focus() {
2183 void WebContentsImpl::SetInitialFocus() {
2184 view_
->SetInitialFocus();
2187 void WebContentsImpl::StoreFocus() {
2188 view_
->StoreFocus();
2191 void WebContentsImpl::RestoreFocus() {
2192 view_
->RestoreFocus();
2195 void WebContentsImpl::FocusThroughTabTraversal(bool reverse
) {
2196 if (ShowingInterstitialPage()) {
2197 GetRenderManager()->interstitial_page()->FocusThroughTabTraversal(reverse
);
2200 RenderWidgetHostView
* const fullscreen_view
=
2201 GetFullscreenRenderWidgetHostView();
2202 if (fullscreen_view
) {
2203 fullscreen_view
->Focus();
2206 GetRenderViewHostImpl()->SetInitialFocus(reverse
);
2209 bool WebContentsImpl::ShowingInterstitialPage() const {
2210 return GetRenderManager()->interstitial_page() != NULL
;
2213 InterstitialPage
* WebContentsImpl::GetInterstitialPage() const {
2214 return GetRenderManager()->interstitial_page();
2217 bool WebContentsImpl::IsSavable() {
2218 // WebKit creates Document object when MIME type is application/xhtml+xml,
2219 // so we also support this MIME type.
2220 return contents_mime_type_
== "text/html" ||
2221 contents_mime_type_
== "text/xml" ||
2222 contents_mime_type_
== "application/xhtml+xml" ||
2223 contents_mime_type_
== "text/plain" ||
2224 contents_mime_type_
== "text/css" ||
2225 net::IsSupportedJavascriptMimeType(contents_mime_type_
.c_str());
2228 void WebContentsImpl::OnSavePage() {
2229 // If we can not save the page, try to download it.
2231 RecordDownloadSource(INITIATED_BY_SAVE_PACKAGE_ON_NON_HTML
);
2232 SaveFrame(GetURL(), Referrer());
2238 // Create the save package and possibly prompt the user for the name to save
2239 // the page as. The user prompt is an asynchronous operation that runs on
2241 save_package_
= new SavePackage(this);
2242 save_package_
->GetSaveInfo();
2245 // Used in automated testing to bypass prompting the user for file names.
2246 // Instead, the names and paths are hard coded rather than running them through
2247 // file name sanitation and extension / mime checking.
2248 bool WebContentsImpl::SavePage(const base::FilePath
& main_file
,
2249 const base::FilePath
& dir_path
,
2250 SavePageType save_type
) {
2251 // Stop the page from navigating.
2254 save_package_
= new SavePackage(this, save_type
, main_file
, dir_path
);
2255 return save_package_
->Init(SavePackageDownloadCreatedCallback());
2258 void WebContentsImpl::SaveFrame(const GURL
& url
,
2259 const Referrer
& referrer
) {
2260 if (!GetURL().is_valid())
2262 if (delegate_
&& delegate_
->SaveFrame(url
, referrer
))
2265 bool is_main_frame
= (url
== GetURL());
2267 DownloadManager
* dlm
=
2268 BrowserContext::GetDownloadManager(GetBrowserContext());
2272 if (is_main_frame
) {
2273 const NavigationEntry
* entry
= controller_
.GetLastCommittedEntry();
2275 post_id
= entry
->GetPostID();
2277 scoped_ptr
<DownloadUrlParameters
> params(
2278 DownloadUrlParameters::FromWebContents(this, url
));
2279 params
->set_referrer(referrer
);
2280 params
->set_post_id(post_id
);
2281 params
->set_prefer_cache(true);
2283 params
->set_method("POST");
2284 params
->set_prompt(true);
2285 dlm
->DownloadUrl(params
.Pass());
2288 void WebContentsImpl::GenerateMHTML(
2289 const base::FilePath
& file
,
2290 const base::Callback
<void(int64
)>& callback
) {
2291 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, file
, callback
);
2294 const std::string
& WebContentsImpl::GetContentsMimeType() const {
2295 return contents_mime_type_
;
2298 bool WebContentsImpl::WillNotifyDisconnection() const {
2299 return notify_disconnection_
;
2302 void WebContentsImpl::SetOverrideEncoding(const std::string
& encoding
) {
2303 SetEncoding(encoding
);
2304 Send(new ViewMsg_SetPageEncoding(GetRoutingID(), encoding
));
2307 void WebContentsImpl::ResetOverrideEncoding() {
2308 canonical_encoding_
.clear();
2309 Send(new ViewMsg_ResetPageEncodingToDefault(GetRoutingID()));
2312 RendererPreferences
* WebContentsImpl::GetMutableRendererPrefs() {
2313 return &renderer_preferences_
;
2316 void WebContentsImpl::Close() {
2317 Close(GetRenderViewHost());
2320 void WebContentsImpl::DragSourceEndedAt(int client_x
, int client_y
,
2321 int screen_x
, int screen_y
, blink::WebDragOperation operation
) {
2322 if (browser_plugin_embedder_
.get())
2323 browser_plugin_embedder_
->DragSourceEndedAt(client_x
, client_y
,
2324 screen_x
, screen_y
, operation
);
2325 if (GetRenderViewHost())
2326 GetRenderViewHostImpl()->DragSourceEndedAt(client_x
, client_y
,
2327 screen_x
, screen_y
, operation
);
2330 void WebContentsImpl::DidGetResourceResponseStart(
2331 const ResourceRequestDetails
& details
) {
2332 controller_
.ssl_manager()->DidStartResourceResponse(details
);
2334 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2335 DidGetResourceResponseStart(details
));
2337 // TODO(avi): Remove. http://crbug.com/170921
2338 NotificationService::current()->Notify(
2339 NOTIFICATION_RESOURCE_RESPONSE_STARTED
,
2340 Source
<WebContents
>(this),
2341 Details
<const ResourceRequestDetails
>(&details
));
2344 void WebContentsImpl::DidGetRedirectForResourceRequest(
2345 RenderFrameHost
* render_frame_host
,
2346 const ResourceRedirectDetails
& details
) {
2347 controller_
.ssl_manager()->DidReceiveResourceRedirect(details
);
2350 WebContentsObserver
,
2352 DidGetRedirectForResourceRequest(render_frame_host
, details
));
2354 // TODO(avi): Remove. http://crbug.com/170921
2355 NotificationService::current()->Notify(
2356 NOTIFICATION_RESOURCE_RECEIVED_REDIRECT
,
2357 Source
<WebContents
>(this),
2358 Details
<const ResourceRedirectDetails
>(&details
));
2361 void WebContentsImpl::SystemDragEnded() {
2362 if (GetRenderViewHost())
2363 GetRenderViewHostImpl()->DragSourceSystemDragEnded();
2365 delegate_
->DragEnded();
2366 if (browser_plugin_embedder_
.get())
2367 browser_plugin_embedder_
->SystemDragEnded();
2370 void WebContentsImpl::UserGestureDone() {
2374 void WebContentsImpl::SetClosedByUserGesture(bool value
) {
2375 closed_by_user_gesture_
= value
;
2378 bool WebContentsImpl::GetClosedByUserGesture() const {
2379 return closed_by_user_gesture_
;
2382 void WebContentsImpl::ViewSource() {
2386 NavigationEntry
* entry
= GetController().GetLastCommittedEntry();
2390 delegate_
->ViewSourceForTab(this, entry
->GetURL());
2393 void WebContentsImpl::ViewFrameSource(const GURL
& url
,
2394 const PageState
& page_state
) {
2398 delegate_
->ViewSourceForFrame(this, url
, page_state
);
2401 int WebContentsImpl::GetMinimumZoomPercent() const {
2402 return minimum_zoom_percent_
;
2405 int WebContentsImpl::GetMaximumZoomPercent() const {
2406 return maximum_zoom_percent_
;
2409 gfx::Size
WebContentsImpl::GetPreferredSize() const {
2410 return capturer_count_
== 0 ? preferred_size_
: preferred_size_for_capture_
;
2413 bool WebContentsImpl::GotResponseToLockMouseRequest(bool allowed
) {
2414 if (GetBrowserPluginGuest())
2415 return GetBrowserPluginGuest()->LockMouse(allowed
);
2417 return GetRenderViewHost() ?
2418 GetRenderViewHostImpl()->GotResponseToLockMouseRequest(allowed
) : false;
2421 bool WebContentsImpl::HasOpener() const {
2422 return opener_
!= NULL
;
2425 WebContents
* WebContentsImpl::GetOpener() const {
2426 return static_cast<WebContents
*>(opener_
);
2429 void WebContentsImpl::DidChooseColorInColorChooser(SkColor color
) {
2430 if (!color_chooser_info_
.get())
2432 RenderFrameHost
* rfh
= RenderFrameHost::FromID(
2433 color_chooser_info_
->render_process_id
,
2434 color_chooser_info_
->render_frame_id
);
2438 rfh
->Send(new FrameMsg_DidChooseColorResponse(
2439 rfh
->GetRoutingID(), color_chooser_info_
->identifier
, color
));
2442 void WebContentsImpl::DidEndColorChooser() {
2443 if (!color_chooser_info_
.get())
2445 RenderFrameHost
* rfh
= RenderFrameHost::FromID(
2446 color_chooser_info_
->render_process_id
,
2447 color_chooser_info_
->render_frame_id
);
2451 rfh
->Send(new FrameMsg_DidEndColorChooser(
2452 rfh
->GetRoutingID(), color_chooser_info_
->identifier
));
2453 color_chooser_info_
.reset();
2456 int WebContentsImpl::DownloadImage(const GURL
& url
,
2458 uint32_t max_bitmap_size
,
2459 const ImageDownloadCallback
& callback
) {
2460 int id
= StartDownload(GetMainFrame(), url
, is_favicon
, max_bitmap_size
);
2461 image_download_map_
[id
] = callback
;
2465 bool WebContentsImpl::IsSubframe() const {
2466 return is_subframe_
;
2469 void WebContentsImpl::Find(int request_id
,
2470 const base::string16
& search_text
,
2471 const blink::WebFindOptions
& options
) {
2472 // See if a top level browser plugin handles the find request first.
2473 if (browser_plugin_embedder_
&&
2474 browser_plugin_embedder_
->Find(request_id
, search_text
, options
)) {
2477 Send(new ViewMsg_Find(GetRoutingID(), request_id
, search_text
, options
));
2480 void WebContentsImpl::StopFinding(StopFindAction action
) {
2481 // See if a top level browser plugin handles the stop finding request first.
2482 if (browser_plugin_embedder_
&&
2483 browser_plugin_embedder_
->StopFinding(action
)) {
2486 Send(new ViewMsg_StopFinding(GetRoutingID(), action
));
2489 void WebContentsImpl::InsertCSS(const std::string
& css
) {
2490 GetMainFrame()->Send(new FrameMsg_CSSInsertRequest(
2491 GetMainFrame()->GetRoutingID(), css
));
2494 bool WebContentsImpl::WasRecentlyAudible() {
2495 return audio_stream_monitor_
.WasRecentlyAudible();
2498 void WebContentsImpl::GetManifest(const GetManifestCallback
& callback
) {
2499 manifest_manager_host_
->GetManifest(GetMainFrame(), callback
);
2502 void WebContentsImpl::ExitFullscreen() {
2503 // Clean up related state and initiate the fullscreen exit.
2504 GetRenderViewHostImpl()->RejectMouseLockOrUnlockIfNecessary();
2505 ExitFullscreenMode();
2508 bool WebContentsImpl::FocusLocationBarByDefault() {
2509 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
2510 if (entry
&& entry
->GetURL() == GURL(url::kAboutBlankURL
))
2512 return delegate_
&& delegate_
->ShouldFocusLocationBarByDefault(this);
2515 void WebContentsImpl::SetFocusToLocationBar(bool select_all
) {
2517 delegate_
->SetFocusToLocationBar(select_all
);
2520 void WebContentsImpl::DidStartProvisionalLoad(
2521 RenderFrameHostImpl
* render_frame_host
,
2522 const GURL
& validated_url
,
2524 bool is_iframe_srcdoc
) {
2525 // Notify observers about the start of the provisional load.
2527 WebContentsObserver
,
2529 DidStartProvisionalLoadForFrame(
2530 render_frame_host
, validated_url
, is_error_page
, is_iframe_srcdoc
));
2532 // Notify accessibility if this is a reload.
2533 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
2534 if (entry
&& ui::PageTransitionCoreTypeIs(
2535 entry
->GetTransitionType(), ui::PAGE_TRANSITION_RELOAD
)) {
2536 FrameTreeNode
* ftn
= render_frame_host
->frame_tree_node();
2537 BrowserAccessibilityManager
* manager
=
2538 ftn
->current_frame_host()->browser_accessibility_manager();
2540 manager
->UserIsReloading();
2544 void WebContentsImpl::DidStartNavigationTransition(
2545 RenderFrameHostImpl
* render_frame_host
) {
2546 #if defined(OS_ANDROID)
2547 int render_frame_id
= render_frame_host
->GetRoutingID();
2548 GetWebContentsAndroid()->DidStartNavigationTransitionForFrame(
2553 void WebContentsImpl::DidFailProvisionalLoadWithError(
2554 RenderFrameHostImpl
* render_frame_host
,
2555 const FrameHostMsg_DidFailProvisionalLoadWithError_Params
& params
) {
2556 GURL
validated_url(params
.url
);
2557 FOR_EACH_OBSERVER(WebContentsObserver
,
2559 DidFailProvisionalLoad(render_frame_host
,
2562 params
.error_description
));
2564 FrameTreeNode
* ftn
= render_frame_host
->frame_tree_node();
2565 BrowserAccessibilityManager
* manager
=
2566 ftn
->current_frame_host()->browser_accessibility_manager();
2568 manager
->NavigationFailed();
2571 void WebContentsImpl::DidFailLoadWithError(
2572 RenderFrameHostImpl
* render_frame_host
,
2575 const base::string16
& error_description
) {
2577 WebContentsObserver
,
2579 DidFailLoad(render_frame_host
, url
, error_code
, error_description
));
2582 void WebContentsImpl::NotifyChangedNavigationState(
2583 InvalidateTypes changed_flags
) {
2584 NotifyNavigationStateChanged(changed_flags
);
2587 void WebContentsImpl::AboutToNavigateRenderFrame(
2588 RenderFrameHostImpl
* old_host
,
2589 RenderFrameHostImpl
* new_host
) {
2590 // Notify observers that we will navigate in this RenderFrame.
2592 WebContentsObserver
,
2594 AboutToNavigateRenderFrame(old_host
, new_host
));
2597 void WebContentsImpl::DidStartNavigationToPendingEntry(
2598 RenderFrameHostImpl
* render_frame_host
,
2600 NavigationController::ReloadType reload_type
) {
2601 // Notify observers about navigation.
2603 WebContentsObserver
,
2605 DidStartNavigationToPendingEntry(url
, reload_type
));
2608 void WebContentsImpl::RequestOpenURL(RenderFrameHostImpl
* render_frame_host
,
2609 const OpenURLParams
& params
) {
2610 // OpenURL can blow away the source RFH. Use the process/frame routing ID as a
2611 // weak pointer of sorts.
2612 const int32_t process_id
= render_frame_host
->GetProcess()->GetID();
2613 const int32_t frame_id
= render_frame_host
->GetRoutingID();
2615 WebContents
* new_contents
= OpenURL(params
);
2617 if (new_contents
&& RenderFrameHost::FromID(process_id
, frame_id
)) {
2618 // Notify observers.
2619 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2620 DidOpenRequestedURL(new_contents
,
2625 params
.transition
));
2629 bool WebContentsImpl::ShouldPreserveAbortedURLs() {
2632 return delegate_
->ShouldPreserveAbortedURLs(this);
2635 void WebContentsImpl::DidCommitProvisionalLoad(
2636 RenderFrameHostImpl
* render_frame_host
,
2638 ui::PageTransition transition_type
) {
2639 // Notify observers about the commit of the provisional load.
2640 FOR_EACH_OBSERVER(WebContentsObserver
,
2642 DidCommitProvisionalLoadForFrame(
2643 render_frame_host
, url
, transition_type
));
2645 BrowserAccessibilityManager
* manager
=
2646 render_frame_host
->browser_accessibility_manager();
2648 manager
->NavigationSucceeded();
2651 void WebContentsImpl::DidNavigateMainFramePreCommit(
2652 bool navigation_is_within_page
) {
2653 // Ensure fullscreen mode is exited before committing the navigation to a
2654 // different page. The next page will not start out assuming it is in
2656 if (navigation_is_within_page
) {
2657 // No page change? Then, the renderer and browser can remain in fullscreen.
2660 if (IsFullscreenForCurrentTab())
2662 DCHECK(!IsFullscreenForCurrentTab());
2665 void WebContentsImpl::DidNavigateMainFramePostCommit(
2666 RenderFrameHostImpl
* render_frame_host
,
2667 const LoadCommittedDetails
& details
,
2668 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) {
2669 if (details
.is_navigation_to_different_page()) {
2670 // Clear the status bubble. This is a workaround for a bug where WebKit
2671 // doesn't let us know that the cursor left an element during a
2672 // transition (this is also why the mouse cursor remains as a hand after
2673 // clicking on a link); see bugs 1184641 and 980803. We don't want to
2674 // clear the bubble when a user navigates to a named anchor in the same
2676 UpdateTargetURL(render_frame_host
->GetRenderViewHost(), GURL());
2678 RenderWidgetHostViewBase
* rwhvb
=
2679 static_cast<RenderWidgetHostViewBase
*>(GetRenderWidgetHostView());
2681 rwhvb
->OnDidNavigateMainFrameToNewPage();
2684 if (!details
.is_in_page
) {
2685 // Once the main frame is navigated, we're no longer considered to have
2686 // displayed insecure content.
2687 displayed_insecure_content_
= false;
2688 SSLManager::NotifySSLInternalStateChanged(
2689 GetController().GetBrowserContext());
2692 // Notify observers about navigation.
2693 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2694 DidNavigateMainFrame(details
, params
));
2697 delegate_
->DidNavigateMainFramePostCommit(this);
2698 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
2701 void WebContentsImpl::DidNavigateAnyFramePostCommit(
2702 RenderFrameHostImpl
* render_frame_host
,
2703 const LoadCommittedDetails
& details
,
2704 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) {
2705 // Now that something has committed, we don't need to track whether the
2706 // initial page has been accessed.
2707 has_accessed_initial_document_
= false;
2709 // If we navigate off the page, close all JavaScript dialogs.
2710 if (dialog_manager_
&& !details
.is_in_page
)
2711 dialog_manager_
->CancelActiveAndPendingDialogs(this);
2713 // Notify observers about navigation.
2714 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2715 DidNavigateAnyFrame(render_frame_host
, details
, params
));
2718 void WebContentsImpl::SetMainFrameMimeType(const std::string
& mime_type
) {
2719 contents_mime_type_
= mime_type
;
2722 bool WebContentsImpl::CanOverscrollContent() const {
2723 // Disable overscroll when touch emulation is on. See crbug.com/369938.
2724 if (force_disable_overscroll_content_
)
2728 return delegate_
->CanOverscrollContent();
2733 void WebContentsImpl::OnThemeColorChanged(SkColor theme_color
) {
2734 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2735 DidChangeThemeColor(theme_color
));
2738 void WebContentsImpl::OnDidLoadResourceFromMemoryCache(
2740 const std::string
& security_info
,
2741 const std::string
& http_method
,
2742 const std::string
& mime_type
,
2743 ResourceType resource_type
) {
2745 // Send out a notification that we loaded a resource from our memory cache.
2747 net::CertStatus cert_status
= 0;
2748 int security_bits
= -1;
2749 int connection_status
= 0;
2750 SignedCertificateTimestampIDStatusList signed_certificate_timestamp_ids
;
2751 DeserializeSecurityInfo(security_info
, &cert_id
, &cert_status
,
2752 &security_bits
, &connection_status
,
2753 &signed_certificate_timestamp_ids
);
2754 // TODO(alcutter,eranm): Pass signed_certificate_timestamp_ids into details
2755 LoadFromMemoryCacheDetails
details(
2756 url
, GetRenderProcessHost()->GetID(), cert_id
, cert_status
, http_method
,
2757 mime_type
, resource_type
);
2759 controller_
.ssl_manager()->DidLoadFromMemoryCache(details
);
2761 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2762 DidLoadResourceFromMemoryCache(details
));
2764 if (url
.is_valid() && url
.SchemeIsHTTPOrHTTPS()) {
2765 scoped_refptr
<net::URLRequestContextGetter
> request_context(
2766 resource_type
== RESOURCE_TYPE_MEDIA
?
2767 GetBrowserContext()->GetMediaRequestContextForRenderProcess(
2768 GetRenderProcessHost()->GetID()) :
2769 GetBrowserContext()->GetRequestContextForRenderProcess(
2770 GetRenderProcessHost()->GetID()));
2771 BrowserThread::PostTask(
2774 base::Bind(&NotifyCacheOnIO
, request_context
, url
, http_method
));
2778 void WebContentsImpl::OnDidDisplayInsecureContent() {
2779 RecordAction(base::UserMetricsAction("SSL.DisplayedInsecureContent"));
2780 displayed_insecure_content_
= true;
2781 SSLManager::NotifySSLInternalStateChanged(
2782 GetController().GetBrowserContext());
2785 void WebContentsImpl::OnDidRunInsecureContent(
2786 const std::string
& security_origin
, const GURL
& target_url
) {
2787 LOG(WARNING
) << security_origin
<< " ran insecure content from "
2788 << target_url
.possibly_invalid_spec();
2789 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
2790 if (EndsWith(security_origin
, kDotGoogleDotCom
, false))
2791 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
2792 controller_
.ssl_manager()->DidRunInsecureContent(security_origin
);
2793 displayed_insecure_content_
= true;
2794 SSLManager::NotifySSLInternalStateChanged(
2795 GetController().GetBrowserContext());
2798 void WebContentsImpl::OnDocumentLoadedInFrame() {
2799 if (!HasValidFrameSource())
2802 RenderFrameHostImpl
* rfh
=
2803 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2805 WebContentsObserver
, observers_
, DocumentLoadedInFrame(rfh
));
2808 void WebContentsImpl::OnDidFinishLoad(const GURL
& url
) {
2809 if (!HasValidFrameSource())
2812 GURL
validated_url(url
);
2813 RenderProcessHost
* render_process_host
=
2814 render_frame_message_source_
->GetProcess();
2815 render_process_host
->FilterURL(false, &validated_url
);
2817 RenderFrameHostImpl
* rfh
=
2818 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2820 WebContentsObserver
, observers_
, DidFinishLoad(rfh
, validated_url
));
2823 void WebContentsImpl::OnDidStartLoading(bool to_different_document
) {
2824 if (!HasValidFrameSource())
2827 RenderFrameHostImpl
* rfh
=
2828 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2829 int64 render_frame_id
= rfh
->frame_tree_node()->frame_tree_node_id();
2831 // Any main frame load to a new document should reset the load progress, since
2832 // it will replace the current page and any frames.
2833 if (to_different_document
&& !rfh
->GetParent()) {
2834 ResetLoadProgressState();
2835 loading_frames_in_progress_
= 0;
2836 rfh
->frame_tree_node()->set_is_loading(false);
2839 // It is possible to get multiple calls to OnDidStartLoading that don't have
2840 // corresponding calls to OnDidStopLoading:
2841 // - With "swappedout://" URLs, this happens when a RenderView gets swapped
2842 // out for a cross-process navigation, and it turns into a placeholder for
2843 // one being rendered in a different process.
2844 // - Also, there might be more than one RenderFrameHost sharing the same
2845 // FrameTreeNode (and thus sharing its ID) each sending a start.
2846 // - But in the future, once clamy@ moves navigation network requests to the
2847 // browser process, there's a good chance that callbacks about starting and
2848 // stopping will all be handled by the browser. When that happens, there
2849 // should no longer be a start/stop call imbalance. TODO(avi): When this
2850 // future arrives, update this code to not allow this case.
2851 if (rfh
->frame_tree_node()->is_loading())
2854 DCHECK_GE(loading_frames_in_progress_
, 0);
2855 if (loading_frames_in_progress_
== 0)
2856 DidStartLoading(rfh
, to_different_document
);
2858 ++loading_frames_in_progress_
;
2859 rfh
->frame_tree_node()->set_is_loading(true);
2861 // Notify the RenderFrameHostManager of the event.
2862 rfh
->frame_tree_node()->render_manager()->OnDidStartLoading();
2864 loading_progresses_
[render_frame_id
] = kMinimumLoadingProgress
;
2865 SendLoadProgressChanged();
2868 void WebContentsImpl::OnDidStopLoading() {
2869 if (!HasValidFrameSource())
2872 RenderFrameHostImpl
* rfh
=
2873 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2874 int64 render_frame_id
= rfh
->frame_tree_node()->frame_tree_node_id();
2875 rfh
->frame_tree_node()->set_is_loading(false);
2877 if (loading_progresses_
.find(render_frame_id
) != loading_progresses_
.end()) {
2878 // Load stopped while we were still tracking load. Make sure we update
2879 // progress based on this frame's completion.
2880 loading_progresses_
[render_frame_id
] = 1.0;
2881 SendLoadProgressChanged();
2882 // Then we clean-up our states.
2883 if (loading_total_progress_
== 1.0)
2884 ResetLoadProgressState();
2887 // Notify the RenderFrameHostManager of the event.
2888 rfh
->frame_tree_node()->render_manager()->OnDidStopLoading();
2890 // TODO(japhet): This should be a DCHECK, but the pdf plugin sometimes
2891 // calls DidStopLoading() without a matching DidStartLoading().
2892 if (loading_frames_in_progress_
== 0)
2894 --loading_frames_in_progress_
;
2895 if (loading_frames_in_progress_
== 0)
2896 DidStopLoading(rfh
);
2899 void WebContentsImpl::OnDidChangeLoadProgress(double load_progress
) {
2900 if (!HasValidFrameSource())
2903 RenderFrameHostImpl
* rfh
=
2904 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2905 int64 render_frame_id
= rfh
->frame_tree_node()->frame_tree_node_id();
2907 loading_progresses_
[render_frame_id
] = load_progress
;
2909 // We notify progress change immediately for the first and last updates.
2910 // Also, since the message loop may be pretty busy when a page is loaded, it
2911 // might not execute a posted task in a timely manner so we make sure to
2912 // immediately send progress report if enough time has passed.
2913 base::TimeDelta min_delay
=
2914 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS
);
2915 if (load_progress
== 1.0 || loading_last_progress_update_
.is_null() ||
2916 base::TimeTicks::Now() - loading_last_progress_update_
> min_delay
) {
2917 // If there is a pending task to send progress, it is now obsolete.
2918 loading_weak_factory_
.InvalidateWeakPtrs();
2919 SendLoadProgressChanged();
2920 if (loading_total_progress_
== 1.0)
2921 ResetLoadProgressState();
2925 if (loading_weak_factory_
.HasWeakPtrs())
2928 base::MessageLoop::current()->PostDelayedTask(
2930 base::Bind(&WebContentsImpl::SendLoadProgressChanged
,
2931 loading_weak_factory_
.GetWeakPtr()),
2935 void WebContentsImpl::OnGoToEntryAtOffset(int offset
) {
2936 if (!delegate_
|| delegate_
->OnGoToEntryOffset(offset
))
2937 controller_
.GoToOffset(offset
);
2940 void WebContentsImpl::OnUpdateZoomLimits(int minimum_percent
,
2941 int maximum_percent
) {
2942 minimum_zoom_percent_
= minimum_percent
;
2943 maximum_zoom_percent_
= maximum_percent
;
2946 void WebContentsImpl::OnEnumerateDirectory(int request_id
,
2947 const base::FilePath
& path
) {
2951 ChildProcessSecurityPolicyImpl
* policy
=
2952 ChildProcessSecurityPolicyImpl::GetInstance();
2953 if (policy
->CanReadFile(GetRenderProcessHost()->GetID(), path
))
2954 delegate_
->EnumerateDirectory(this, request_id
, path
);
2957 void WebContentsImpl::OnRegisterProtocolHandler(const std::string
& protocol
,
2959 const base::string16
& title
,
2960 bool user_gesture
) {
2964 ChildProcessSecurityPolicyImpl
* policy
=
2965 ChildProcessSecurityPolicyImpl::GetInstance();
2966 if (policy
->IsPseudoScheme(protocol
))
2969 delegate_
->RegisterProtocolHandler(this, protocol
, url
, user_gesture
);
2972 void WebContentsImpl::OnUnregisterProtocolHandler(const std::string
& protocol
,
2974 bool user_gesture
) {
2978 ChildProcessSecurityPolicyImpl
* policy
=
2979 ChildProcessSecurityPolicyImpl::GetInstance();
2980 if (policy
->IsPseudoScheme(protocol
))
2983 delegate_
->UnregisterProtocolHandler(this, protocol
, url
, user_gesture
);
2986 void WebContentsImpl::OnFindReply(int request_id
,
2987 int number_of_matches
,
2988 const gfx::Rect
& selection_rect
,
2989 int active_match_ordinal
,
2990 bool final_update
) {
2992 delegate_
->FindReply(this, request_id
, number_of_matches
, selection_rect
,
2993 active_match_ordinal
, final_update
);
2997 #if defined(OS_ANDROID)
2998 void WebContentsImpl::OnFindMatchRectsReply(
3000 const std::vector
<gfx::RectF
>& rects
,
3001 const gfx::RectF
& active_rect
) {
3003 delegate_
->FindMatchRectsReply(this, version
, rects
, active_rect
);
3006 void WebContentsImpl::OnOpenDateTimeDialog(
3007 const ViewHostMsg_DateTimeDialogValue_Params
& value
) {
3008 date_time_chooser_
->ShowDialog(GetTopLevelNativeWindow(),
3009 GetRenderViewHost(),
3019 void WebContentsImpl::OnDomOperationResponse(const std::string
& json_string
,
3020 int automation_id
) {
3021 DomOperationNotificationDetails
details(json_string
, automation_id
);
3022 NotificationService::current()->Notify(
3023 NOTIFICATION_DOM_OPERATION_RESPONSE
,
3024 Source
<WebContents
>(this),
3025 Details
<DomOperationNotificationDetails
>(&details
));
3028 void WebContentsImpl::OnAppCacheAccessed(const GURL
& manifest_url
,
3029 bool blocked_by_policy
) {
3030 // Notify observers about navigation.
3031 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3032 AppCacheAccessed(manifest_url
, blocked_by_policy
));
3035 void WebContentsImpl::OnOpenColorChooser(
3036 int color_chooser_id
,
3038 const std::vector
<ColorSuggestion
>& suggestions
) {
3039 if (!HasValidFrameSource())
3042 ColorChooser
* new_color_chooser
= delegate_
?
3043 delegate_
->OpenColorChooser(this, color
, suggestions
) :
3045 if (!new_color_chooser
)
3047 if (color_chooser_info_
.get())
3048 color_chooser_info_
->chooser
->End();
3050 color_chooser_info_
.reset(new ColorChooserInfo(
3051 render_frame_message_source_
->GetProcess()->GetID(),
3052 render_frame_message_source_
->GetRoutingID(),
3057 void WebContentsImpl::OnEndColorChooser(int color_chooser_id
) {
3058 if (color_chooser_info_
&&
3059 color_chooser_id
== color_chooser_info_
->identifier
)
3060 color_chooser_info_
->chooser
->End();
3063 void WebContentsImpl::OnSetSelectedColorInColorChooser(int color_chooser_id
,
3065 if (color_chooser_info_
&&
3066 color_chooser_id
== color_chooser_info_
->identifier
)
3067 color_chooser_info_
->chooser
->SetSelectedColor(color
);
3070 // This exists for render views that don't have a WebUI, but do have WebUI
3071 // bindings enabled.
3072 void WebContentsImpl::OnWebUISend(const GURL
& source_url
,
3073 const std::string
& name
,
3074 const base::ListValue
& args
) {
3076 delegate_
->WebUISend(this, source_url
, name
, args
);
3079 #if defined(ENABLE_PLUGINS)
3080 void WebContentsImpl::OnPepperPluginHung(int plugin_child_id
,
3081 const base::FilePath
& path
,
3083 UMA_HISTOGRAM_COUNTS("Pepper.PluginHung", 1);
3085 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3086 PluginHungStatusChanged(plugin_child_id
, path
, is_hung
));
3089 void WebContentsImpl::OnPluginCrashed(const base::FilePath
& plugin_path
,
3090 base::ProcessId plugin_pid
) {
3091 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3092 PluginCrashed(plugin_path
, plugin_pid
));
3095 void WebContentsImpl::OnRequestPpapiBrokerPermission(
3098 const base::FilePath
& plugin_path
) {
3100 OnPpapiBrokerPermissionResult(routing_id
, false);
3104 if (!delegate_
->RequestPpapiBrokerPermission(
3105 this, url
, plugin_path
,
3106 base::Bind(&WebContentsImpl::OnPpapiBrokerPermissionResult
,
3107 base::Unretained(this), routing_id
))) {
3109 OnPpapiBrokerPermissionResult(routing_id
, false);
3113 void WebContentsImpl::OnPpapiBrokerPermissionResult(int routing_id
,
3115 Send(new ViewMsg_PpapiBrokerPermissionResult(routing_id
, result
));
3118 void WebContentsImpl::OnBrowserPluginMessage(const IPC::Message
& message
) {
3119 // This creates a BrowserPluginEmbedder, which handles all the BrowserPlugin
3120 // specific messages for this WebContents. This means that any message from
3121 // a BrowserPlugin prior to this will be ignored.
3122 // For more info, see comment above classes BrowserPluginEmbedder and
3123 // BrowserPluginGuest.
3124 CHECK(!browser_plugin_embedder_
.get());
3125 browser_plugin_embedder_
.reset(BrowserPluginEmbedder::Create(this));
3126 browser_plugin_embedder_
->OnMessageReceived(message
);
3128 #endif // defined(ENABLE_PLUGINS)
3130 void WebContentsImpl::OnDidDownloadImage(
3132 int http_status_code
,
3133 const GURL
& image_url
,
3134 const std::vector
<SkBitmap
>& bitmaps
,
3135 const std::vector
<gfx::Size
>& original_bitmap_sizes
) {
3136 if (bitmaps
.size() != original_bitmap_sizes
.size())
3139 ImageDownloadMap::iterator iter
= image_download_map_
.find(id
);
3140 if (iter
== image_download_map_
.end()) {
3141 // Currently WebContents notifies us of ANY downloads so that it is
3142 // possible to get here.
3145 if (!iter
->second
.is_null()) {
3147 id
, http_status_code
, image_url
, bitmaps
, original_bitmap_sizes
);
3149 image_download_map_
.erase(id
);
3152 void WebContentsImpl::OnUpdateFaviconURL(
3153 const std::vector
<FaviconURL
>& candidates
) {
3154 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3155 DidUpdateFaviconURL(candidates
));
3158 void WebContentsImpl::CreateAudioPowerSaveBlocker() {
3159 // ChromeOS has its own way of handling power save blocks for media.
3160 #if !defined(OS_CHROMEOS)
3161 DCHECK(!audio_power_save_blocker_
);
3162 audio_power_save_blocker_
= PowerSaveBlocker::Create(
3163 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension
, "Playing Audio");
3167 void WebContentsImpl::CreateVideoPowerSaveBlocker() {
3168 // ChromeOS has its own way of handling power save blocks for media.
3169 #if !defined(OS_CHROMEOS)
3170 DCHECK(!video_power_save_blocker_
);
3171 DCHECK(!active_video_players_
.empty());
3172 video_power_save_blocker_
= PowerSaveBlocker::Create(
3173 PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep
, "Playing Video");
3174 #if defined(OS_ANDROID)
3175 static_cast<PowerSaveBlockerImpl
*>(video_power_save_blocker_
.get())
3176 ->InitDisplaySleepBlocker(GetView()->GetNativeView());
3181 void WebContentsImpl::MaybeReleasePowerSaveBlockers() {
3182 // If there are no more audio players and we don't have audio stream
3183 // monitoring, release the audio power save blocker here instead of during
3184 // NotifyNavigationStateChanged().
3185 if (active_audio_players_
.empty() &&
3186 !AudioStreamMonitor::monitoring_available()) {
3187 audio_power_save_blocker_
.reset();
3190 // If there are no more video players, clear the video power save blocker.
3191 if (active_video_players_
.empty())
3192 video_power_save_blocker_
.reset();
3195 void WebContentsImpl::OnMediaPlayingNotification(int64 player_cookie
,
3199 // Ignore the videos playing remotely and don't hold the wake lock for the
3201 if (is_remote
) return;
3204 AddMediaPlayerEntry(player_cookie
, &active_audio_players_
);
3206 // If we don't have audio stream monitoring, allocate the audio power save
3207 // blocker here instead of during NotifyNavigationStateChanged().
3208 if (!audio_power_save_blocker_
&&
3209 !AudioStreamMonitor::monitoring_available()) {
3210 CreateAudioPowerSaveBlocker();
3215 AddMediaPlayerEntry(player_cookie
, &active_video_players_
);
3217 // If we're not hidden and have just created a player, create a blocker.
3218 if (!video_power_save_blocker_
&& !IsHidden())
3219 CreateVideoPowerSaveBlocker();
3223 void WebContentsImpl::OnMediaPausedNotification(int64 player_cookie
) {
3224 RemoveMediaPlayerEntry(player_cookie
, &active_audio_players_
);
3225 RemoveMediaPlayerEntry(player_cookie
, &active_video_players_
);
3226 MaybeReleasePowerSaveBlockers();
3229 void WebContentsImpl::OnFirstVisuallyNonEmptyPaint() {
3230 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3231 DidFirstVisuallyNonEmptyPaint());
3234 void WebContentsImpl::DidChangeVisibleSSLState() {
3236 delegate_
->VisibleSSLStateChanged(this);
3239 void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
3240 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3241 BeforeFormRepostWarningShow());
3244 void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
3247 delegate_
->ShowRepostFormWarningDialog(this);
3250 bool WebContentsImpl::HasAccessedInitialDocument() {
3251 return has_accessed_initial_document_
;
3254 // Notifies the RenderWidgetHost instance about the fact that the page is
3255 // loading, or done loading.
3256 void WebContentsImpl::SetIsLoading(RenderViewHost
* render_view_host
,
3258 bool to_different_document
,
3259 LoadNotificationDetails
* details
) {
3260 if (is_loading
== is_loading_
)
3264 load_state_
= net::LoadStateWithParam(net::LOAD_STATE_IDLE
,
3266 load_state_host_
.clear();
3268 upload_position_
= 0;
3271 GetRenderManager()->SetIsLoading(is_loading
);
3273 is_loading_
= is_loading
;
3274 waiting_for_response_
= is_loading
;
3275 is_load_to_different_document_
= to_different_document
;
3278 delegate_
->LoadingStateChanged(this, to_different_document
);
3279 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD
);
3281 std::string url
= (details
? details
->url
.possibly_invalid_spec() : "NULL");
3283 TRACE_EVENT_ASYNC_BEGIN1("browser,navigation", "WebContentsImpl Loading",
3285 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3286 DidStartLoading(render_view_host
));
3288 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
3290 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3291 DidStopLoading(render_view_host
));
3294 // TODO(avi): Remove. http://crbug.com/170921
3295 int type
= is_loading
? NOTIFICATION_LOAD_START
: NOTIFICATION_LOAD_STOP
;
3296 NotificationDetails det
= NotificationService::NoDetails();
3298 det
= Details
<LoadNotificationDetails
>(details
);
3299 NotificationService::current()->Notify(
3300 type
, Source
<NavigationController
>(&controller_
), det
);
3303 void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point
& extent
) {
3304 RenderFrameHost
* focused_frame
= GetFocusedFrame();
3308 focused_frame
->Send(new InputMsg_MoveRangeSelectionExtent(
3309 focused_frame
->GetRoutingID(), extent
));
3312 void WebContentsImpl::SelectRange(const gfx::Point
& base
,
3313 const gfx::Point
& extent
) {
3314 RenderFrameHost
* focused_frame
= GetFocusedFrame();
3318 focused_frame
->Send(
3319 new InputMsg_SelectRange(focused_frame
->GetRoutingID(), base
, extent
));
3322 void WebContentsImpl::UpdateMaxPageIDIfNecessary(RenderViewHost
* rvh
) {
3323 // If we are creating a RVH for a restored controller, then we need to make
3324 // sure the RenderView starts with a next_page_id_ larger than the number
3325 // of restored entries. This must be called before the RenderView starts
3326 // navigating (to avoid a race between the browser updating max_page_id and
3327 // the renderer updating next_page_id_). Because of this, we only call this
3328 // from CreateRenderView and allow that to notify the RenderView for us.
3329 int max_restored_page_id
= controller_
.GetMaxRestoredPageID();
3330 if (max_restored_page_id
>
3331 GetMaxPageIDForSiteInstance(rvh
->GetSiteInstance()))
3332 UpdateMaxPageIDForSiteInstance(rvh
->GetSiteInstance(),
3333 max_restored_page_id
);
3336 bool WebContentsImpl::UpdateTitleForEntry(NavigationEntryImpl
* entry
,
3337 const base::string16
& title
) {
3338 // For file URLs without a title, use the pathname instead. In the case of a
3339 // synthesized title, we don't want the update to count toward the "one set
3340 // per page of the title to history."
3341 base::string16 final_title
;
3343 if (entry
&& entry
->GetURL().SchemeIsFile() && title
.empty()) {
3344 final_title
= base::UTF8ToUTF16(entry
->GetURL().ExtractFileName());
3345 explicit_set
= false; // Don't count synthetic titles toward the set limit.
3347 base::TrimWhitespace(title
, base::TRIM_ALL
, &final_title
);
3348 explicit_set
= true;
3351 // If a page is created via window.open and never navigated,
3352 // there will be no navigation entry. In this situation,
3353 // |page_title_when_no_navigation_entry_| will be used for page title.
3355 if (final_title
== entry
->GetTitle())
3356 return false; // Nothing changed, don't bother.
3358 entry
->SetTitle(final_title
);
3360 if (page_title_when_no_navigation_entry_
== final_title
)
3361 return false; // Nothing changed, don't bother.
3363 page_title_when_no_navigation_entry_
= final_title
;
3366 // Lastly, set the title for the view.
3367 view_
->SetPageTitle(final_title
);
3369 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3370 TitleWasSet(entry
, explicit_set
));
3372 // TODO(avi): Remove. http://crbug.com/170921
3373 std::pair
<NavigationEntry
*, bool> details
=
3374 std::make_pair(entry
, explicit_set
);
3375 NotificationService::current()->Notify(
3376 NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED
,
3377 Source
<WebContents
>(this),
3378 Details
<std::pair
<NavigationEntry
*, bool> >(&details
));
3383 void WebContentsImpl::SendLoadProgressChanged() {
3384 loading_last_progress_update_
= base::TimeTicks::Now();
3385 double progress
= 0.0;
3386 int frame_count
= 0;
3388 for (LoadingProgressMap::iterator it
= loading_progresses_
.begin();
3389 it
!= loading_progresses_
.end();
3391 progress
+= it
->second
;
3394 if (frame_count
== 0)
3396 progress
/= frame_count
;
3397 DCHECK(progress
<= 1.0);
3399 if (progress
<= loading_total_progress_
)
3401 loading_total_progress_
= progress
;
3404 delegate_
->LoadProgressChanged(this, progress
);
3407 void WebContentsImpl::ResetLoadProgressState() {
3408 loading_progresses_
.clear();
3409 loading_total_progress_
= 0.0;
3410 loading_weak_factory_
.InvalidateWeakPtrs();
3411 loading_last_progress_update_
= base::TimeTicks();
3414 void WebContentsImpl::NotifyViewSwapped(RenderViewHost
* old_host
,
3415 RenderViewHost
* new_host
) {
3416 // After sending out a swap notification, we need to send a disconnect
3417 // notification so that clients that pick up a pointer to |this| can NULL the
3418 // pointer. See Bug 1230284.
3419 notify_disconnection_
= true;
3420 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3421 RenderViewHostChanged(old_host
, new_host
));
3423 // TODO(avi): Remove. http://crbug.com/170921
3424 std::pair
<RenderViewHost
*, RenderViewHost
*> details
=
3425 std::make_pair(old_host
, new_host
);
3426 NotificationService::current()->Notify(
3427 NOTIFICATION_RENDER_VIEW_HOST_CHANGED
,
3428 Source
<WebContents
>(this),
3429 Details
<std::pair
<RenderViewHost
*, RenderViewHost
*> >(&details
));
3431 // Ensure that the associated embedder gets cleared after a RenderViewHost
3432 // gets swapped, so we don't reuse the same embedder next time a
3433 // RenderViewHost is attached to this WebContents.
3434 RemoveBrowserPluginEmbedder();
3437 void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost
* old_host
,
3438 RenderFrameHost
* new_host
) {
3439 FOR_EACH_OBSERVER(WebContentsObserver
,
3441 RenderFrameHostChanged(old_host
, new_host
));
3444 // TODO(avi): Remove this entire function because this notification is already
3445 // covered by two observer functions. http://crbug.com/170921
3446 void WebContentsImpl::NotifyDisconnected() {
3447 if (!notify_disconnection_
)
3450 notify_disconnection_
= false;
3451 NotificationService::current()->Notify(
3452 NOTIFICATION_WEB_CONTENTS_DISCONNECTED
,
3453 Source
<WebContents
>(this),
3454 NotificationService::NoDetails());
3457 void WebContentsImpl::NotifyNavigationEntryCommitted(
3458 const LoadCommittedDetails
& load_details
) {
3460 WebContentsObserver
, observers_
, NavigationEntryCommitted(load_details
));
3463 bool WebContentsImpl::OnMessageReceived(RenderFrameHost
* render_frame_host
,
3464 const IPC::Message
& message
) {
3465 return OnMessageReceived(NULL
, render_frame_host
, message
);
3468 const GURL
& WebContentsImpl::GetMainFrameLastCommittedURL() const {
3469 return GetLastCommittedURL();
3472 void WebContentsImpl::RenderFrameCreated(RenderFrameHost
* render_frame_host
) {
3473 // Note this is only for subframes, the notification for the main frame
3474 // happens in RenderViewCreated.
3475 FOR_EACH_OBSERVER(WebContentsObserver
,
3477 RenderFrameCreated(render_frame_host
));
3478 SetAccessibilityModeOnFrame(accessibility_mode_
, render_frame_host
);
3481 void WebContentsImpl::RenderFrameDeleted(RenderFrameHost
* render_frame_host
) {
3482 ClearPowerSaveBlockers(render_frame_host
);
3483 FOR_EACH_OBSERVER(WebContentsObserver
,
3485 RenderFrameDeleted(render_frame_host
));
3488 void WebContentsImpl::WorkerCrashed(RenderFrameHost
* render_frame_host
) {
3490 delegate_
->WorkerCrashed(this);
3493 void WebContentsImpl::ShowContextMenu(RenderFrameHost
* render_frame_host
,
3494 const ContextMenuParams
& params
) {
3495 ContextMenuParams
context_menu_params(params
);
3496 // Allow WebContentsDelegates to handle the context menu operation first.
3497 if (GetBrowserPluginGuest()) {
3498 WebContentsViewGuest
* view_guest
=
3499 static_cast<WebContentsViewGuest
*>(GetView());
3500 context_menu_params
= view_guest
->ConvertContextMenuParams(params
);
3502 if (delegate_
&& delegate_
->HandleContextMenu(context_menu_params
))
3505 render_view_host_delegate_view_
->ShowContextMenu(render_frame_host
,
3506 context_menu_params
);
3509 void WebContentsImpl::RunJavaScriptMessage(
3510 RenderFrameHost
* render_frame_host
,
3511 const base::string16
& message
,
3512 const base::string16
& default_prompt
,
3513 const GURL
& frame_url
,
3514 JavaScriptMessageType javascript_message_type
,
3515 IPC::Message
* reply_msg
) {
3516 // Suppress JavaScript dialogs when requested. Also suppress messages when
3517 // showing an interstitial as it's shown over the previous page and we don't
3518 // want the hidden page's dialogs to interfere with the interstitial.
3519 bool suppress_this_message
=
3520 static_cast<RenderFrameHostImpl
*>(render_frame_host
)->is_swapped_out() ||
3521 ShowingInterstitialPage() || !delegate_
||
3522 delegate_
->ShouldSuppressDialogs(this) ||
3523 !delegate_
->GetJavaScriptDialogManager(this);
3525 if (!suppress_this_message
) {
3526 std::string accept_lang
= GetContentClient()->browser()->
3527 GetAcceptLangs(GetBrowserContext());
3528 dialog_manager_
= delegate_
->GetJavaScriptDialogManager(this);
3529 dialog_manager_
->RunJavaScriptDialog(
3531 frame_url
.GetOrigin(),
3533 javascript_message_type
,
3536 base::Bind(&WebContentsImpl::OnDialogClosed
,
3537 base::Unretained(this),
3538 render_frame_host
->GetProcess()->GetID(),
3539 render_frame_host
->GetRoutingID(),
3542 &suppress_this_message
);
3545 if (suppress_this_message
) {
3546 // If we are suppressing messages, just reply as if the user immediately
3547 // pressed "Cancel", passing true to |dialog_was_suppressed|.
3548 OnDialogClosed(render_frame_host
->GetProcess()->GetID(),
3549 render_frame_host
->GetRoutingID(), reply_msg
,
3550 true, false, base::string16());
3553 // OnDialogClosed (two lines up) may have caused deletion of this object (see
3554 // http://crbug.com/288961 ). The only safe thing to do here is return.
3557 void WebContentsImpl::RunBeforeUnloadConfirm(
3558 RenderFrameHost
* render_frame_host
,
3559 const base::string16
& message
,
3561 IPC::Message
* reply_msg
) {
3562 RenderFrameHostImpl
* rfhi
=
3563 static_cast<RenderFrameHostImpl
*>(render_frame_host
);
3565 delegate_
->WillRunBeforeUnloadConfirm();
3567 bool suppress_this_message
=
3568 rfhi
->rfh_state() != RenderFrameHostImpl::STATE_DEFAULT
|| !delegate_
||
3569 delegate_
->ShouldSuppressDialogs(this) ||
3570 !delegate_
->GetJavaScriptDialogManager(this);
3571 if (suppress_this_message
) {
3572 rfhi
->JavaScriptDialogClosed(reply_msg
, true, base::string16(), true);
3576 is_showing_before_unload_dialog_
= true;
3577 dialog_manager_
= delegate_
->GetJavaScriptDialogManager(this);
3578 dialog_manager_
->RunBeforeUnloadDialog(
3579 this, message
, is_reload
,
3580 base::Bind(&WebContentsImpl::OnDialogClosed
, base::Unretained(this),
3581 render_frame_host
->GetProcess()->GetID(),
3582 render_frame_host
->GetRoutingID(), reply_msg
,
3586 WebContents
* WebContentsImpl::GetAsWebContents() {
3590 bool WebContentsImpl::IsNeverVisible() {
3593 return delegate_
->IsNeverVisible(this);
3597 gfx::NativeViewAccessible
WebContentsImpl::GetParentNativeViewAccessible() {
3598 return accessible_parent_
;
3602 RenderViewHostDelegateView
* WebContentsImpl::GetDelegateView() {
3603 return render_view_host_delegate_view_
;
3606 RendererPreferences
WebContentsImpl::GetRendererPrefs(
3607 BrowserContext
* browser_context
) const {
3608 return renderer_preferences_
;
3611 gfx::Rect
WebContentsImpl::GetRootWindowResizerRect() const {
3613 return delegate_
->GetRootWindowResizerRect();
3617 void WebContentsImpl::RemoveBrowserPluginEmbedder() {
3618 if (browser_plugin_embedder_
)
3619 browser_plugin_embedder_
.reset();
3622 void WebContentsImpl::RenderViewCreated(RenderViewHost
* render_view_host
) {
3623 // Don't send notifications if we are just creating a swapped-out RVH for
3624 // the opener chain. These won't be used for view-source or WebUI, so it's
3625 // ok to return early.
3626 if (!static_cast<RenderViewHostImpl
*>(render_view_host
)->is_active())
3630 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
3632 NotificationService::current()->Notify(
3633 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED
,
3634 Source
<WebContents
>(this),
3635 Details
<RenderViewHost
>(render_view_host
));
3637 // When we're creating views, we're still doing initial setup, so we always
3638 // use the pending Web UI rather than any possibly existing committed one.
3639 if (GetRenderManager()->pending_web_ui())
3640 GetRenderManager()->pending_web_ui()->RenderViewCreated(render_view_host
);
3642 NavigationEntry
* entry
= controller_
.GetPendingEntry();
3643 if (entry
&& entry
->IsViewSourceMode()) {
3644 // Put the renderer in view source mode.
3645 render_view_host
->Send(
3646 new ViewMsg_EnableViewSourceMode(render_view_host
->GetRoutingID()));
3649 view_
->RenderViewCreated(render_view_host
);
3652 WebContentsObserver
, observers_
, RenderViewCreated(render_view_host
));
3654 // We tell the observers now instead of when the main RenderFrameHostImpl is
3655 // constructed because otherwise it would be too early (i.e. IPCs sent to the
3656 // frame would be dropped because it's not created yet).
3657 RenderFrameHost
* main_frame
= render_view_host
->GetMainFrame();
3659 WebContentsObserver
, observers_
, RenderFrameCreated(main_frame
));
3660 SetAccessibilityModeOnFrame(accessibility_mode_
, main_frame
);
3662 DevToolsManager::GetInstance()->RenderViewCreated(this, render_view_host
);
3665 void WebContentsImpl::RenderViewReady(RenderViewHost
* rvh
) {
3666 if (rvh
!= GetRenderViewHost()) {
3667 // Don't notify the world, since this came from a renderer in the
3672 notify_disconnection_
= true;
3673 // TODO(avi): Remove. http://crbug.com/170921
3674 NotificationService::current()->Notify(
3675 NOTIFICATION_WEB_CONTENTS_CONNECTED
,
3676 Source
<WebContents
>(this),
3677 NotificationService::NoDetails());
3679 bool was_crashed
= IsCrashed();
3680 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING
, 0);
3682 // Restore the focus to the tab (otherwise the focus will be on the top
3684 if (was_crashed
&& !FocusLocationBarByDefault() &&
3685 (!delegate_
|| delegate_
->ShouldFocusPageAfterCrash())) {
3689 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, RenderViewReady());
3692 void WebContentsImpl::RenderViewTerminated(RenderViewHost
* rvh
,
3693 base::TerminationStatus status
,
3695 // TODO(nasko): This isn't ideal; the termination process should be handled by
3696 // RenderFrameDeleted(). See http://crbug.com/455943.
3697 ClearPowerSaveBlockers(rvh
->GetMainFrame());
3699 if (rvh
!= GetRenderViewHost()) {
3700 // The pending page's RenderViewHost is gone.
3704 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
3705 // renderer may not have made a clean exit.
3706 if (IsFullscreenForCurrentTab())
3707 ExitFullscreenMode();
3709 // Cancel any visible dialogs so they are not left dangling over the sad tab.
3710 if (dialog_manager_
)
3711 dialog_manager_
->CancelActiveAndPendingDialogs(this);
3714 delegate_
->HideValidationMessage(this);
3716 SetIsLoading(rvh
, false, true, NULL
);
3717 NotifyDisconnected();
3718 SetIsCrashed(status
, error_code
);
3720 // Reset the loading progress. TODO(avi): What does it mean to have a
3721 // "renderer crash" when there is more than one renderer process serving a
3722 // webpage? Once this function is called at a more granular frame level, we
3723 // probably will need to more granularly reset the state here.
3724 ResetLoadProgressState();
3725 loading_frames_in_progress_
= 0;
3727 FOR_EACH_OBSERVER(WebContentsObserver
,
3729 RenderProcessGone(GetCrashedStatus()));
3732 void WebContentsImpl::RenderViewDeleted(RenderViewHost
* rvh
) {
3733 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, RenderViewDeleted(rvh
));
3736 void WebContentsImpl::UpdateState(RenderViewHost
* rvh
,
3738 const PageState
& page_state
) {
3739 // Ensure that this state update comes from a RenderViewHost that belongs to
3740 // this WebContents.
3741 // TODO(nasko): This should go through RenderFrameHost.
3742 // TODO(creis): We can't update state for cross-process subframes until we
3743 // have FrameNavigationEntries. Once we do, this should be a DCHECK.
3744 if (rvh
->GetDelegate()->GetAsWebContents() != this)
3747 // We must be prepared to handle state updates for any page, these occur
3748 // when the user is scrolling and entering form data, as well as when we're
3749 // leaving a page, in which case our state may have already been moved to
3750 // the next page. The navigation controller will look up the appropriate
3751 // NavigationEntry and update it when it is notified via the delegate.
3753 int entry_index
= controller_
.GetEntryIndexWithPageID(
3754 rvh
->GetSiteInstance(), page_id
);
3755 if (entry_index
< 0)
3757 NavigationEntry
* entry
= controller_
.GetEntryAtIndex(entry_index
);
3759 if (page_state
== entry
->GetPageState())
3760 return; // Nothing to update.
3761 entry
->SetPageState(page_state
);
3762 controller_
.NotifyEntryChanged(entry
, entry_index
);
3765 void WebContentsImpl::UpdateTargetURL(RenderViewHost
* render_view_host
,
3767 if (fullscreen_widget_routing_id_
!= MSG_ROUTING_NONE
) {
3768 // If we're fullscreen only update the url if it's from the fullscreen
3770 RenderWidgetHostView
* fs
= GetFullscreenRenderWidgetHostView();
3771 if (fs
&& fs
->GetRenderWidgetHost() != render_view_host
)
3775 delegate_
->UpdateTargetURL(this, url
);
3778 void WebContentsImpl::Close(RenderViewHost
* rvh
) {
3779 #if defined(OS_MACOSX)
3780 // The UI may be in an event-tracking loop, such as between the
3781 // mouse-down and mouse-up in text selection or a button click.
3782 // Defer the close until after tracking is complete, so that we
3783 // don't free objects out from under the UI.
3784 // TODO(shess): This could get more fine-grained. For instance,
3785 // closing a tab in another window while selecting text in the
3786 // current window's Omnibox should be just fine.
3787 if (view_
->IsEventTracking()) {
3788 view_
->CloseTabAfterEventTracking();
3793 // Ignore this if it comes from a RenderViewHost that we aren't showing.
3794 if (delegate_
&& rvh
== GetRenderViewHost())
3795 delegate_
->CloseContents(this);
3798 void WebContentsImpl::SwappedOut(RenderFrameHost
* rfh
) {
3799 if (delegate_
&& rfh
->GetRenderViewHost() == GetRenderViewHost())
3800 delegate_
->SwappedOut(this);
3803 void WebContentsImpl::DidDeferAfterResponseStarted(
3804 const TransitionLayerData
& transition_data
) {
3805 #if defined(OS_ANDROID)
3806 GetWebContentsAndroid()->DidDeferAfterResponseStarted(transition_data
);
3810 bool WebContentsImpl::WillHandleDeferAfterResponseStarted() {
3811 #if defined(OS_ANDROID)
3812 return GetWebContentsAndroid()->WillHandleDeferAfterResponseStarted();
3818 void WebContentsImpl::RequestMove(const gfx::Rect
& new_bounds
) {
3819 if (delegate_
&& delegate_
->IsPopupOrPanel(this))
3820 delegate_
->MoveContents(this, new_bounds
);
3823 void WebContentsImpl::DidStartLoading(RenderFrameHost
* render_frame_host
,
3824 bool to_different_document
) {
3825 SetIsLoading(render_frame_host
->GetRenderViewHost(), true,
3826 to_different_document
, NULL
);
3828 // Notify accessibility that the user is navigating away from the
3829 // current document.
3831 // TODO(dmazzoni): do this using a WebContentsObserver.
3832 FrameTreeNode
* ftn
= static_cast<RenderFrameHostImpl
*>(render_frame_host
)->
3834 BrowserAccessibilityManager
* manager
=
3835 ftn
->current_frame_host()->browser_accessibility_manager();
3837 manager
->UserIsNavigatingAway();
3840 void WebContentsImpl::DidStopLoading(RenderFrameHost
* render_frame_host
) {
3841 scoped_ptr
<LoadNotificationDetails
> details
;
3843 // Use the last committed entry rather than the active one, in case a
3844 // pending entry has been created.
3845 NavigationEntry
* entry
= controller_
.GetLastCommittedEntry();
3846 Navigator
* navigator
= frame_tree_
.root()->navigator();
3848 // An entry may not exist for a stop when loading an initial blank page or
3849 // if an iframe injected by script into a blank page finishes loading.
3851 base::TimeDelta elapsed
=
3852 base::TimeTicks::Now() - navigator
->GetCurrentLoadStart();
3854 details
.reset(new LoadNotificationDetails(
3855 entry
->GetVirtualURL(),
3856 entry
->GetTransitionType(),
3859 controller_
.GetCurrentEntryIndex()));
3862 SetIsLoading(render_frame_host
->GetRenderViewHost(), false, true,
3866 void WebContentsImpl::DidCancelLoading() {
3867 controller_
.DiscardNonCommittedEntries();
3869 // Update the URL display.
3870 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL
);
3873 void WebContentsImpl::DidAccessInitialDocument() {
3874 has_accessed_initial_document_
= true;
3876 // We may have left a failed browser-initiated navigation in the address bar
3877 // to let the user edit it and try again. Clear it now that content might
3878 // show up underneath it.
3879 if (!IsLoading() && controller_
.GetPendingEntry())
3880 controller_
.DiscardPendingEntry();
3882 // Update the URL display.
3883 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL
);
3886 void WebContentsImpl::DidDisownOpener(RenderFrameHost
* render_frame_host
) {
3887 // No action is necessary if the opener has already been cleared.
3891 // Clear our opener so that future cross-process navigations don't have an
3893 RemoveDestructionObserver(opener_
);
3896 // Notify all swapped out RenderViewHosts for this tab. This is important
3897 // in case we go back to them, or if another window in those processes tries
3898 // to access window.opener.
3899 GetRenderManager()->DidDisownOpener(render_frame_host
);
3902 void WebContentsImpl::DocumentOnLoadCompleted(
3903 RenderFrameHost
* render_frame_host
) {
3904 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3905 DocumentOnLoadCompletedInMainFrame());
3907 // TODO(avi): Remove. http://crbug.com/170921
3908 NotificationService::current()->Notify(
3909 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
,
3910 Source
<WebContents
>(this),
3911 NotificationService::NoDetails());
3914 void WebContentsImpl::UpdateTitle(RenderFrameHost
* render_frame_host
,
3916 const base::string16
& title
,
3917 base::i18n::TextDirection title_direction
) {
3918 RenderViewHost
* rvh
= render_frame_host
->GetRenderViewHost();
3920 // If we have a title, that's a pretty good indication that we've started
3921 // getting useful data.
3922 SetNotWaitingForResponse();
3924 // Try to find the navigation entry, which might not be the current one.
3925 // For example, it might be from a pending RVH for the pending entry.
3926 NavigationEntryImpl
* entry
= controller_
.GetEntryWithPageID(
3927 rvh
->GetSiteInstance(), page_id
);
3929 // We can handle title updates when we don't have an entry in
3930 // UpdateTitleForEntry, but only if the update is from the current RVH.
3931 // TODO(avi): Change to make decisions based on the RenderFrameHost.
3932 if (!entry
&& rvh
!= GetRenderViewHost())
3935 // TODO(evan): make use of title_direction.
3936 // http://code.google.com/p/chromium/issues/detail?id=27094
3937 if (!UpdateTitleForEntry(entry
, title
))
3940 // Broadcast notifications when the UI should be updated.
3941 if (entry
== controller_
.GetEntryAtOffset(0))
3942 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE
);
3945 void WebContentsImpl::UpdateEncoding(RenderFrameHost
* render_frame_host
,
3946 const std::string
& encoding
) {
3947 SetEncoding(encoding
);
3950 void WebContentsImpl::DocumentAvailableInMainFrame(
3951 RenderViewHost
* render_view_host
) {
3952 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3953 DocumentAvailableInMainFrame());
3955 void WebContentsImpl::RouteCloseEvent(RenderViewHost
* rvh
) {
3956 // Tell the active RenderViewHost to run unload handlers and close, as long
3957 // as the request came from a RenderViewHost in the same BrowsingInstance.
3958 // In most cases, we receive this from a swapped out RenderViewHost.
3959 // It is possible to receive it from one that has just been swapped in,
3960 // in which case we might as well deliver the message anyway.
3961 if (rvh
->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()))
3962 GetRenderViewHost()->ClosePage();
3965 void WebContentsImpl::RouteMessageEvent(
3966 RenderViewHost
* rvh
,
3967 const ViewMsg_PostMessage_Params
& params
) {
3968 // Only deliver the message to the active RenderViewHost if the request
3969 // came from a RenderViewHost in the same BrowsingInstance or if this
3970 // WebContents is dedicated to a browser plugin guest.
3971 // Note: This check means that an embedder could theoretically receive a
3972 // postMessage from anyone (not just its own guests). However, this is
3973 // probably not a risk for apps since other pages won't have references
3975 if (!rvh
->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()) &&
3976 !GetBrowserPluginGuest() && !GetBrowserPluginEmbedder())
3979 ViewMsg_PostMessage_Params
new_params(params
);
3981 if (!params
.message_port_ids
.empty()) {
3982 MessagePortMessageFilter
* message_port_message_filter
=
3983 static_cast<RenderProcessHostImpl
*>(GetRenderProcessHost())
3984 ->message_port_message_filter();
3985 message_port_message_filter
->UpdateMessagePortsWithNewRoutes(
3986 params
.message_port_ids
,
3987 &new_params
.new_routing_ids
);
3990 // If there is a source_routing_id, translate it to the routing ID for
3991 // the equivalent swapped out RVH in the target process. If we need
3992 // to create a swapped out RVH for the source tab, we create its opener
3993 // chain as well, since those will also be accessible to the target page.
3994 if (new_params
.source_routing_id
!= MSG_ROUTING_NONE
) {
3995 // Try to look up the WebContents for the source page.
3996 WebContentsImpl
* source_contents
= NULL
;
3997 RenderViewHostImpl
* source_rvh
= RenderViewHostImpl::FromID(
3998 rvh
->GetProcess()->GetID(), params
.source_routing_id
);
4000 source_contents
= static_cast<WebContentsImpl
*>(
4001 source_rvh
->GetDelegate()->GetAsWebContents());
4004 if (source_contents
) {
4005 if (GetBrowserPluginGuest()) {
4006 // We create a swapped out RenderView for the embedder in the guest's
4007 // render process but we intentionally do not expose the embedder's
4008 // opener chain to it.
4009 new_params
.source_routing_id
=
4010 source_contents
->CreateSwappedOutRenderView(GetSiteInstance());
4012 new_params
.source_routing_id
=
4013 source_contents
->CreateOpenerRenderViews(GetSiteInstance());
4016 // We couldn't find it, so don't pass a source frame.
4017 new_params
.source_routing_id
= MSG_ROUTING_NONE
;
4021 // In most cases, we receive this from a swapped out RenderViewHost.
4022 // It is possible to receive it from one that has just been swapped in,
4023 // in which case we might as well deliver the message anyway.
4024 Send(new ViewMsg_PostMessageEvent(GetRoutingID(), new_params
));
4027 bool WebContentsImpl::AddMessageToConsole(int32 level
,
4028 const base::string16
& message
,
4030 const base::string16
& source_id
) {
4033 return delegate_
->AddMessageToConsole(this, level
, message
, line_no
,
4037 int WebContentsImpl::CreateSwappedOutRenderView(
4038 SiteInstance
* instance
) {
4039 int render_view_routing_id
= MSG_ROUTING_NONE
;
4040 GetRenderManager()->CreateRenderFrame(
4041 instance
, nullptr, MSG_ROUTING_NONE
,
4042 CREATE_RF_SWAPPED_OUT
| CREATE_RF_FOR_MAIN_FRAME_NAVIGATION
|
4044 &render_view_routing_id
);
4045 return render_view_routing_id
;
4048 void WebContentsImpl::OnUserGesture() {
4049 // Notify observers.
4050 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, DidGetUserGesture());
4052 ResourceDispatcherHostImpl
* rdh
= ResourceDispatcherHostImpl::Get();
4053 if (rdh
) // NULL in unittests.
4054 rdh
->OnUserGesture(this);
4057 void WebContentsImpl::OnIgnoredUIEvent() {
4058 // Notify observers.
4059 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, DidGetIgnoredUIEvent());
4062 void WebContentsImpl::RendererUnresponsive(RenderViewHost
* render_view_host
) {
4063 // Don't show hung renderer dialog for a swapped out RVH.
4064 if (render_view_host
!= GetRenderViewHost())
4067 RenderViewHostImpl
* rvhi
= static_cast<RenderViewHostImpl
*>(render_view_host
);
4068 RenderFrameHostImpl
* rfhi
=
4069 static_cast<RenderFrameHostImpl
*>(rvhi
->GetMainFrame());
4071 // Ignore renderer unresponsive event if debugger is attached to the tab
4072 // since the event may be a result of the renderer sitting on a breakpoint.
4073 // See http://crbug.com/65458
4074 if (DevToolsAgentHost::IsDebuggerAttached(this))
4077 if (rfhi
->IsWaitingForBeforeUnloadACK() ||
4078 rfhi
->IsWaitingForUnloadACK()) {
4079 // Hang occurred while firing the beforeunload/unload handler.
4080 // Pretend the handler fired so tab closing continues as if it had.
4081 frame_tree_
.ForEach(base::Bind(
4082 &EnableSuddenTermination
, rvhi
->GetSiteInstance()->GetId()));
4084 if (!GetRenderManager()->ShouldCloseTabOnUnresponsiveRenderer())
4087 // If the tab hangs in the beforeunload/unload handler there's really
4088 // nothing we can do to recover. If the hang is in the beforeunload handler,
4089 // pretend the beforeunload listeners have all fired and allow the delegate
4090 // to continue closing; the user will not have the option of cancelling the
4091 // close. Otherwise, pretend the unload listeners have all fired and close
4094 if (rfhi
->IsWaitingForBeforeUnloadACK() && delegate_
) {
4095 delegate_
->BeforeUnloadFired(this, true, &close
);
4102 if (!GetRenderViewHostImpl() || !GetRenderViewHostImpl()->IsRenderViewLive())
4106 delegate_
->RendererUnresponsive(this);
4109 void WebContentsImpl::RendererResponsive(RenderViewHost
* render_view_host
) {
4111 delegate_
->RendererResponsive(this);
4114 void WebContentsImpl::LoadStateChanged(
4116 const net::LoadStateWithParam
& load_state
,
4117 uint64 upload_position
,
4118 uint64 upload_size
) {
4119 load_state_
= load_state
;
4120 upload_position_
= upload_position
;
4121 upload_size_
= upload_size
;
4122 load_state_host_
= net::IDNToUnicode(url
.host(),
4123 GetContentClient()->browser()->GetAcceptLangs(
4124 GetBrowserContext()));
4125 if (load_state_
.state
== net::LOAD_STATE_READING_RESPONSE
)
4126 SetNotWaitingForResponse();
4128 NotifyNavigationStateChanged(static_cast<InvalidateTypes
>(
4129 INVALIDATE_TYPE_LOAD
| INVALIDATE_TYPE_TAB
));
4133 void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
4134 bool proceed
, const base::TimeTicks
& proceed_time
,
4135 bool* proceed_to_fire_unload
) {
4136 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
4137 BeforeUnloadFired(proceed_time
));
4139 delegate_
->BeforeUnloadFired(this, proceed
, proceed_to_fire_unload
);
4140 // Note: |this| might be deleted at this point.
4143 void WebContentsImpl::RenderProcessGoneFromRenderManager(
4144 RenderViewHost
* render_view_host
) {
4145 DCHECK(crashed_status_
!= base::TERMINATION_STATUS_STILL_RUNNING
);
4146 RenderViewTerminated(render_view_host
, crashed_status_
, crashed_error_code_
);
4149 void WebContentsImpl::UpdateRenderViewSizeForRenderManager() {
4150 // TODO(brettw) this is a hack. See WebContentsView::SizeContents.
4151 gfx::Size size
= GetSizeForNewRenderView();
4152 // 0x0 isn't a valid window size (minimal window size is 1x1) but it may be
4153 // here during container initialization and normal window size will be set
4154 // later. In case of tab duplication this resizing to 0x0 prevents setting
4155 // normal size later so just ignore it.
4156 if (!size
.IsEmpty())
4157 view_
->SizeContents(size
);
4160 void WebContentsImpl::CancelModalDialogsForRenderManager() {
4161 // We need to cancel modal dialogs when doing a process swap, since the load
4162 // deferrer would prevent us from swapping out.
4163 if (dialog_manager_
)
4164 dialog_manager_
->CancelActiveAndPendingDialogs(this);
4167 void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost
* old_host
,
4168 RenderFrameHost
* new_host
,
4169 bool is_main_frame
) {
4170 if (is_main_frame
) {
4171 NotifyViewSwapped(old_host
? old_host
->GetRenderViewHost() : NULL
,
4172 new_host
->GetRenderViewHost());
4174 // Make sure the visible RVH reflects the new delegate's preferences.
4176 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
4178 view_
->RenderViewSwappedIn(new_host
->GetRenderViewHost());
4181 NotifyFrameSwapped(old_host
, new_host
);
4184 int WebContentsImpl::CreateOpenerRenderViewsForRenderManager(
4185 SiteInstance
* instance
) {
4187 return MSG_ROUTING_NONE
;
4189 // Recursively create RenderViews for anything else in the opener chain.
4190 return opener_
->CreateOpenerRenderViews(instance
);
4193 int WebContentsImpl::CreateOpenerRenderViews(SiteInstance
* instance
) {
4194 int opener_route_id
= MSG_ROUTING_NONE
;
4196 // If this tab has an opener, ensure it has a RenderView in the given
4197 // SiteInstance as well.
4199 opener_route_id
= opener_
->CreateOpenerRenderViews(instance
);
4201 // If any of the renderers (current, pending, or swapped out) for this
4202 // WebContents has the same SiteInstance, use it.
4203 if (GetRenderManager()->current_host()->GetSiteInstance() == instance
)
4204 return GetRenderManager()->current_host()->GetRoutingID();
4206 if (GetRenderManager()->pending_render_view_host() &&
4207 GetRenderManager()->pending_render_view_host()->GetSiteInstance() ==
4209 return GetRenderManager()->pending_render_view_host()->GetRoutingID();
4211 RenderViewHostImpl
* rvh
= GetRenderManager()->GetSwappedOutRenderViewHost(
4214 return rvh
->GetRoutingID();
4216 // Create a swapped out RenderView in the given SiteInstance if none exists,
4217 // setting its opener to the given route_id. Return the new view's route_id.
4218 int render_view_routing_id
= MSG_ROUTING_NONE
;
4219 GetRenderManager()->CreateRenderFrame(instance
, nullptr, opener_route_id
,
4220 CREATE_RF_FOR_MAIN_FRAME_NAVIGATION
|
4221 CREATE_RF_SWAPPED_OUT
|
4223 &render_view_routing_id
);
4224 return render_view_routing_id
;
4227 NavigationControllerImpl
& WebContentsImpl::GetControllerForRenderManager() {
4228 return GetController();
4231 scoped_ptr
<WebUIImpl
> WebContentsImpl::CreateWebUIForRenderManager(
4233 return scoped_ptr
<WebUIImpl
>(static_cast<WebUIImpl
*>(CreateWebUI(url
)));
4237 WebContentsImpl::GetLastCommittedNavigationEntryForRenderManager() {
4238 return controller_
.GetLastCommittedEntry();
4241 bool WebContentsImpl::CreateRenderViewForRenderManager(
4242 RenderViewHost
* render_view_host
,
4243 int opener_route_id
,
4244 int proxy_routing_id
,
4245 bool for_main_frame_navigation
) {
4246 TRACE_EVENT0("browser,navigation",
4247 "WebContentsImpl::CreateRenderViewForRenderManager");
4248 // Can be NULL during tests.
4249 RenderWidgetHostViewBase
* rwh_view
;
4250 // TODO(kenrb): RenderWidgetHostViewChildFrame special casing is temporary
4251 // until RenderWidgetHost is attached to RenderFrameHost. We need to special
4252 // case this because RWH is still a base class of RenderViewHost, and child
4253 // frame RWHVs are unique in that they do not have their own WebContents.
4254 if (!for_main_frame_navigation
) {
4255 RenderWidgetHostViewChildFrame
* rwh_view_child
=
4256 new RenderWidgetHostViewChildFrame(render_view_host
);
4257 rwh_view
= rwh_view_child
;
4259 rwh_view
= view_
->CreateViewForWidget(render_view_host
, false);
4262 // Now that the RenderView has been created, we need to tell it its size.
4264 rwh_view
->SetSize(GetSizeForNewRenderView());
4266 // Make sure we use the correct starting page_id in the new RenderView.
4267 UpdateMaxPageIDIfNecessary(render_view_host
);
4269 GetMaxPageIDForSiteInstance(render_view_host
->GetSiteInstance());
4271 if (!static_cast<RenderViewHostImpl
*>(
4272 render_view_host
)->CreateRenderView(base::string16(),
4276 created_with_opener_
)) {
4280 SetHistoryOffsetAndLengthForView(render_view_host
,
4281 controller_
.GetLastCommittedEntryIndex(),
4282 controller_
.GetEntryCount());
4284 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
4285 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
4286 // linux. See crbug.com/83941.
4288 if (RenderWidgetHost
* render_widget_host
= rwh_view
->GetRenderWidgetHost())
4289 render_widget_host
->WasResized();
4296 bool WebContentsImpl::CreateRenderFrameForRenderManager(
4297 RenderFrameHost
* render_frame_host
,
4298 int parent_routing_id
,
4299 int proxy_routing_id
) {
4300 TRACE_EVENT0("browser,navigation",
4301 "WebContentsImpl::CreateRenderFrameForRenderManager");
4303 RenderFrameHostImpl
* rfh
=
4304 static_cast<RenderFrameHostImpl
*>(render_frame_host
);
4305 if (!rfh
->CreateRenderFrame(parent_routing_id
, proxy_routing_id
))
4308 // TODO(nasko): When RenderWidgetHost is owned by RenderFrameHost, the passed
4309 // RenderFrameHost will have to be associated with the appropriate
4310 // RenderWidgetHostView or a new one should be created here.
4315 #if defined(OS_ANDROID)
4317 base::android::ScopedJavaLocalRef
<jobject
>
4318 WebContentsImpl::GetJavaWebContents() {
4319 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
4320 return GetWebContentsAndroid()->GetJavaObject();
4323 WebContentsAndroid
* WebContentsImpl::GetWebContentsAndroid() {
4324 WebContentsAndroid
* web_contents_android
=
4325 static_cast<WebContentsAndroid
*>(GetUserData(kWebContentsAndroidKey
));
4326 if (!web_contents_android
) {
4327 web_contents_android
= new WebContentsAndroid(this);
4328 SetUserData(kWebContentsAndroidKey
, web_contents_android
);
4330 return web_contents_android
;
4333 bool WebContentsImpl::CreateRenderViewForInitialEmptyDocument() {
4334 return CreateRenderViewForRenderManager(GetRenderViewHost(),
4340 #elif defined(OS_MACOSX)
4342 void WebContentsImpl::SetAllowOtherViews(bool allow
) {
4343 view_
->SetAllowOtherViews(allow
);
4346 bool WebContentsImpl::GetAllowOtherViews() {
4347 return view_
->GetAllowOtherViews();
4352 void WebContentsImpl::OnDialogClosed(int render_process_id
,
4353 int render_frame_id
,
4354 IPC::Message
* reply_msg
,
4355 bool dialog_was_suppressed
,
4357 const base::string16
& user_input
) {
4358 RenderFrameHostImpl
* rfh
= RenderFrameHostImpl::FromID(render_process_id
,
4360 last_dialog_suppressed_
= dialog_was_suppressed
;
4362 if (is_showing_before_unload_dialog_
&& !success
) {
4363 // If a beforeunload dialog is canceled, we need to stop the throbber from
4364 // spinning, since we forced it to start spinning in Navigate.
4366 DidStopLoading(rfh
);
4367 controller_
.DiscardNonCommittedEntries();
4369 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
4370 BeforeUnloadDialogCancelled());
4373 is_showing_before_unload_dialog_
= false;
4375 rfh
->JavaScriptDialogClosed(reply_msg
, success
, user_input
,
4376 dialog_was_suppressed
);
4378 // Don't leak the sync IPC reply if the RFH or process is gone.
4383 void WebContentsImpl::SetEncoding(const std::string
& encoding
) {
4384 if (encoding
== last_reported_encoding_
)
4386 last_reported_encoding_
= encoding
;
4388 canonical_encoding_
= GetContentClient()->browser()->
4389 GetCanonicalEncodingNameByAliasName(encoding
);
4392 bool WebContentsImpl::IsHidden() {
4393 return capturer_count_
== 0 && !should_normally_be_visible_
;
4396 RenderFrameHostManager
* WebContentsImpl::GetRenderManager() const {
4397 return frame_tree_
.root()->render_manager();
4400 RenderViewHostImpl
* WebContentsImpl::GetRenderViewHostImpl() {
4401 return static_cast<RenderViewHostImpl
*>(GetRenderViewHost());
4404 BrowserPluginGuest
* WebContentsImpl::GetBrowserPluginGuest() const {
4405 return browser_plugin_guest_
.get();
4408 void WebContentsImpl::SetBrowserPluginGuest(BrowserPluginGuest
* guest
) {
4409 CHECK(!browser_plugin_guest_
);
4410 browser_plugin_guest_
.reset(guest
);
4413 BrowserPluginEmbedder
* WebContentsImpl::GetBrowserPluginEmbedder() const {
4414 return browser_plugin_embedder_
.get();
4417 void WebContentsImpl::ClearPowerSaveBlockers(
4418 RenderFrameHost
* render_frame_host
) {
4419 RemoveAllMediaPlayerEntries(render_frame_host
, &active_audio_players_
);
4420 RemoveAllMediaPlayerEntries(render_frame_host
, &active_video_players_
);
4421 MaybeReleasePowerSaveBlockers();
4424 void WebContentsImpl::ClearAllPowerSaveBlockers() {
4425 active_audio_players_
.clear();
4426 active_video_players_
.clear();
4427 audio_power_save_blocker_
.reset();
4428 video_power_save_blocker_
.reset();
4431 gfx::Size
WebContentsImpl::GetSizeForNewRenderView() {
4434 size
= delegate_
->GetSizeForNewRenderView(this);
4436 size
= GetContainerBounds().size();
4440 void WebContentsImpl::OnFrameRemoved(RenderFrameHost
* render_frame_host
) {
4442 WebContentsObserver
, observers_
, FrameDeleted(render_frame_host
));
4445 void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size
& old_size
) {
4448 const gfx::Size new_size
= GetPreferredSize();
4449 if (new_size
!= old_size
)
4450 delegate_
->UpdatePreferredSize(this, new_size
);
4453 void WebContentsImpl::AddMediaPlayerEntry(int64 player_cookie
,
4454 ActiveMediaPlayerMap
* player_map
) {
4455 if (!HasValidFrameSource())
4458 const uintptr_t key
=
4459 reinterpret_cast<uintptr_t>(render_frame_message_source_
);
4460 DCHECK(std::find((*player_map
)[key
].begin(),
4461 (*player_map
)[key
].end(),
4462 player_cookie
) == (*player_map
)[key
].end());
4463 (*player_map
)[key
].push_back(player_cookie
);
4466 void WebContentsImpl::RemoveMediaPlayerEntry(int64 player_cookie
,
4467 ActiveMediaPlayerMap
* player_map
) {
4468 if (!HasValidFrameSource())
4471 const uintptr_t key
=
4472 reinterpret_cast<uintptr_t>(render_frame_message_source_
);
4473 ActiveMediaPlayerMap::iterator it
= player_map
->find(key
);
4474 if (it
== player_map
->end())
4477 // Remove the player.
4478 PlayerList::iterator player_it
=
4479 std::find(it
->second
.begin(), it
->second
.end(), player_cookie
);
4480 if (player_it
!= it
->second
.end())
4481 it
->second
.erase(player_it
);
4483 // If there are no players left, remove the map entry.
4484 if (it
->second
.empty())
4485 player_map
->erase(it
);
4488 void WebContentsImpl::RemoveAllMediaPlayerEntries(
4489 RenderFrameHost
* render_frame_host
,
4490 ActiveMediaPlayerMap
* player_map
) {
4491 ActiveMediaPlayerMap::iterator it
=
4492 player_map
->find(reinterpret_cast<uintptr_t>(render_frame_host
));
4493 if (it
== player_map
->end())
4495 player_map
->erase(it
);
4498 void WebContentsImpl::ResumeResponseDeferredAtStart() {
4499 FrameTreeNode
* node
= frame_tree_
.root();
4500 node
->render_manager()->ResumeResponseDeferredAtStart();
4503 void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable
) {
4504 force_disable_overscroll_content_
= force_disable
;
4506 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
4509 } // namespace content