1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/web_contents/web_contents_impl.h"
9 #include "base/command_line.h"
10 #include "base/debug/trace_event.h"
11 #include "base/lazy_instance.h"
12 #include "base/logging.h"
13 #include "base/metrics/histogram.h"
14 #include "base/metrics/stats_counters.h"
15 #include "base/process/process.h"
16 #include "base/strings/string16.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/time/time.h"
21 #include "content/browser/accessibility/accessibility_mode_helper.h"
22 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
23 #include "content/browser/browser_plugin/browser_plugin_embedder.h"
24 #include "content/browser/browser_plugin/browser_plugin_guest.h"
25 #include "content/browser/child_process_security_policy_impl.h"
26 #include "content/browser/devtools/devtools_manager.h"
27 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
28 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
29 #include "content/browser/download/download_stats.h"
30 #include "content/browser/download/mhtml_generation_manager.h"
31 #include "content/browser/download/save_package.h"
32 #include "content/browser/frame_host/cross_process_frame_connector.h"
33 #include "content/browser/frame_host/interstitial_page_impl.h"
34 #include "content/browser/frame_host/navigation_entry_impl.h"
35 #include "content/browser/frame_host/navigator_impl.h"
36 #include "content/browser/frame_host/render_frame_host_impl.h"
37 #include "content/browser/frame_host/render_widget_host_view_child_frame.h"
38 #include "content/browser/geolocation/geolocation_service_context.h"
39 #include "content/browser/host_zoom_map_impl.h"
40 #include "content/browser/loader/resource_dispatcher_host_impl.h"
41 #include "content/browser/manifest/manifest_manager_host.h"
42 #include "content/browser/media/audio_stream_monitor.h"
43 #include "content/browser/media/capture/web_contents_audio_muter.h"
44 #include "content/browser/message_port_message_filter.h"
45 #include "content/browser/message_port_service.h"
46 #include "content/browser/plugin_content_origin_whitelist.h"
47 #include "content/browser/power_save_blocker_impl.h"
48 #include "content/browser/renderer_host/render_process_host_impl.h"
49 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
50 #include "content/browser/renderer_host/render_view_host_impl.h"
51 #include "content/browser/renderer_host/render_widget_host_impl.h"
52 #include "content/browser/renderer_host/render_widget_host_view_base.h"
53 #include "content/browser/screen_orientation/screen_orientation_dispatcher_host_impl.h"
54 #include "content/browser/site_instance_impl.h"
55 #include "content/browser/web_contents/web_contents_view_guest.h"
56 #include "content/browser/webui/generic_handler.h"
57 #include "content/browser/webui/web_ui_controller_factory_registry.h"
58 #include "content/browser/webui/web_ui_impl.h"
59 #include "content/common/browser_plugin/browser_plugin_constants.h"
60 #include "content/common/browser_plugin/browser_plugin_messages.h"
61 #include "content/common/frame_messages.h"
62 #include "content/common/image_messages.h"
63 #include "content/common/input_messages.h"
64 #include "content/common/ssl_status_serialization.h"
65 #include "content/common/view_messages.h"
66 #include "content/public/browser/ax_event_notification_details.h"
67 #include "content/public/browser/browser_context.h"
68 #include "content/public/browser/browser_plugin_guest_manager.h"
69 #include "content/public/browser/content_browser_client.h"
70 #include "content/public/browser/devtools_agent_host.h"
71 #include "content/public/browser/download_manager.h"
72 #include "content/public/browser/download_url_parameters.h"
73 #include "content/public/browser/invalidate_type.h"
74 #include "content/public/browser/javascript_dialog_manager.h"
75 #include "content/public/browser/load_from_memory_cache_details.h"
76 #include "content/public/browser/load_notification_details.h"
77 #include "content/public/browser/navigation_details.h"
78 #include "content/public/browser/notification_details.h"
79 #include "content/public/browser/notification_service.h"
80 #include "content/public/browser/render_widget_host_iterator.h"
81 #include "content/public/browser/resource_request_details.h"
82 #include "content/public/browser/screen_orientation_dispatcher_host.h"
83 #include "content/public/browser/storage_partition.h"
84 #include "content/public/browser/user_metrics.h"
85 #include "content/public/browser/web_contents_delegate.h"
86 #include "content/public/browser/web_contents_observer.h"
87 #include "content/public/common/bindings_policy.h"
88 #include "content/public/common/content_constants.h"
89 #include "content/public/common/content_switches.h"
90 #include "content/public/common/page_zoom.h"
91 #include "content/public/common/result_codes.h"
92 #include "content/public/common/url_constants.h"
93 #include "content/public/common/url_utils.h"
94 #include "content/public/common/web_preferences.h"
95 #include "net/base/mime_util.h"
96 #include "net/base/net_util.h"
97 #include "net/http/http_cache.h"
98 #include "net/http/http_transaction_factory.h"
99 #include "net/url_request/url_request_context.h"
100 #include "net/url_request/url_request_context_getter.h"
101 #include "ui/base/layout.h"
102 #include "ui/gfx/display.h"
103 #include "ui/gfx/screen.h"
104 #include "ui/gl/gl_switches.h"
106 #if defined(OS_ANDROID)
107 #include "content/browser/android/date_time_chooser_android.h"
108 #include "content/browser/media/android/browser_media_player_manager.h"
109 #include "content/browser/web_contents/web_contents_android.h"
112 #if defined(OS_MACOSX)
113 #include "base/mac/foundation_util.h"
119 const int kMinimumDelayBetweenLoadingUpdatesMS
= 100;
121 // This matches what Blink's ProgressTracker has traditionally used for a
122 // minimum progress value.
123 const double kMinimumLoadingProgress
= 0.1;
125 const char kDotGoogleDotCom
[] = ".google.com";
127 #if defined(OS_ANDROID)
128 const char kWebContentsAndroidKey
[] = "web_contents_android";
131 base::LazyInstance
<std::vector
<WebContentsImpl::CreatedCallback
> >
132 g_created_callbacks
= LAZY_INSTANCE_INITIALIZER
;
134 static int StartDownload(RenderFrameHost
* rfh
,
137 uint32_t max_bitmap_size
) {
138 static int g_next_image_download_id
= 0;
139 rfh
->Send(new ImageMsg_DownloadImage(rfh
->GetRoutingID(),
140 ++g_next_image_download_id
,
144 return g_next_image_download_id
;
147 void NotifyCacheOnIO(
148 scoped_refptr
<net::URLRequestContextGetter
> request_context
,
150 const std::string
& http_method
) {
151 request_context
->GetURLRequestContext()->http_transaction_factory()->
152 GetCache()->OnExternalCacheHit(url
, http_method
);
155 // Helper function for retrieving all the sites in a frame tree.
156 bool CollectSites(BrowserContext
* context
,
157 std::set
<GURL
>* sites
,
158 FrameTreeNode
* node
) {
159 sites
->insert(SiteInstance::GetSiteForURL(context
, node
->current_url()));
163 bool ForEachFrameInternal(
164 const base::Callback
<void(RenderFrameHost
*)>& on_frame
,
165 FrameTreeNode
* node
) {
166 on_frame
.Run(node
->current_frame_host());
170 bool ForEachPendingFrameInternal(
171 const base::Callback
<void(RenderFrameHost
*)>& on_frame
,
172 FrameTreeNode
* node
) {
173 RenderFrameHost
* pending_frame_host
=
174 node
->render_manager()->pending_frame_host();
175 if (pending_frame_host
)
176 on_frame
.Run(pending_frame_host
);
180 void SendToAllFramesInternal(IPC::Message
* message
, RenderFrameHost
* rfh
) {
181 IPC::Message
* message_copy
= new IPC::Message(*message
);
182 message_copy
->set_routing_id(rfh
->GetRoutingID());
183 rfh
->Send(message_copy
);
186 void AddRenderWidgetHostViewToSet(std::set
<RenderWidgetHostView
*>* set
,
187 RenderFrameHost
* rfh
) {
188 RenderWidgetHostView
* rwhv
= static_cast<RenderFrameHostImpl
*>(rfh
)
191 ->GetRenderWidgetHostView();
195 void SetAccessibilityModeOnFrame(AccessibilityMode mode
,
196 RenderFrameHost
* frame_host
) {
197 static_cast<RenderFrameHostImpl
*>(frame_host
)->SetAccessibilityMode(mode
);
202 WebContents
* WebContents::Create(const WebContents::CreateParams
& params
) {
203 return WebContentsImpl::CreateWithOpener(
204 params
, static_cast<WebContentsImpl
*>(params
.opener
));
207 WebContents
* WebContents::CreateWithSessionStorage(
208 const WebContents::CreateParams
& params
,
209 const SessionStorageNamespaceMap
& session_storage_namespace_map
) {
210 WebContentsImpl
* new_contents
= new WebContentsImpl(
211 params
.browser_context
, NULL
);
213 for (SessionStorageNamespaceMap::const_iterator it
=
214 session_storage_namespace_map
.begin();
215 it
!= session_storage_namespace_map
.end();
217 new_contents
->GetController()
218 .SetSessionStorageNamespace(it
->first
, it
->second
.get());
221 new_contents
->Init(params
);
225 void WebContentsImpl::AddCreatedCallback(const CreatedCallback
& callback
) {
226 g_created_callbacks
.Get().push_back(callback
);
229 void WebContentsImpl::RemoveCreatedCallback(const CreatedCallback
& callback
) {
230 for (size_t i
= 0; i
< g_created_callbacks
.Get().size(); ++i
) {
231 if (g_created_callbacks
.Get().at(i
).Equals(callback
)) {
232 g_created_callbacks
.Get().erase(g_created_callbacks
.Get().begin() + i
);
238 WebContents
* WebContents::FromRenderViewHost(const RenderViewHost
* rvh
) {
239 return rvh
->GetDelegate()->GetAsWebContents();
242 WebContents
* WebContents::FromRenderFrameHost(RenderFrameHost
* rfh
) {
243 RenderFrameHostImpl
* rfh_impl
= static_cast<RenderFrameHostImpl
*>(rfh
);
246 return rfh_impl
->delegate()->GetAsWebContents();
249 // WebContentsImpl::DestructionObserver ----------------------------------------
251 class WebContentsImpl::DestructionObserver
: public WebContentsObserver
{
253 DestructionObserver(WebContentsImpl
* owner
, WebContents
* watched_contents
)
254 : WebContentsObserver(watched_contents
),
258 // WebContentsObserver:
259 void WebContentsDestroyed() override
{
260 owner_
->OnWebContentsDestroyed(
261 static_cast<WebContentsImpl
*>(web_contents()));
265 WebContentsImpl
* owner_
;
267 DISALLOW_COPY_AND_ASSIGN(DestructionObserver
);
270 WebContentsImpl::ColorChooserInfo::ColorChooserInfo(int render_process_id
,
272 ColorChooser
* chooser
,
274 : render_process_id(render_process_id
),
275 render_frame_id(render_frame_id
),
277 identifier(identifier
) {
280 WebContentsImpl::ColorChooserInfo::~ColorChooserInfo() {
283 // WebContentsImpl -------------------------------------------------------------
285 WebContentsImpl::WebContentsImpl(BrowserContext
* browser_context
,
286 WebContentsImpl
* opener
)
288 controller_(this, browser_context
),
289 render_view_host_delegate_view_(NULL
),
291 created_with_opener_(!!opener
),
293 accessible_parent_(NULL
),
295 frame_tree_(new NavigatorImpl(&controller_
, this),
301 is_load_to_different_document_(false),
302 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING
),
303 crashed_error_code_(0),
304 waiting_for_response_(false),
305 load_state_(net::LOAD_STATE_IDLE
, base::string16()),
306 loading_total_progress_(0.0),
307 loading_frames_in_progress_(0),
310 displayed_insecure_content_(false),
311 has_accessed_initial_document_(false),
313 should_normally_be_visible_(true),
314 is_being_destroyed_(false),
315 notify_disconnection_(false),
316 dialog_manager_(NULL
),
317 is_showing_before_unload_dialog_(false),
318 last_active_time_(base::TimeTicks::Now()),
319 closed_by_user_gesture_(false),
320 minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor
* 100)),
321 maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor
* 100)),
322 totalPinchGestureAmount_(0),
323 currentPinchZoomStepDelta_(0),
324 render_view_message_source_(NULL
),
325 fullscreen_widget_routing_id_(MSG_ROUTING_NONE
),
326 fullscreen_widget_had_focus_at_shutdown_(false),
328 force_disable_overscroll_content_(false),
329 last_dialog_suppressed_(false),
330 geolocation_service_context_(new GeolocationServiceContext()),
332 BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()),
333 audio_stream_monitor_(this),
334 virtual_keyboard_requested_(false),
335 loading_weak_factory_(this) {
336 for (size_t i
= 0; i
< g_created_callbacks
.Get().size(); i
++)
337 g_created_callbacks
.Get().at(i
).Run(this);
338 frame_tree_
.SetFrameRemoveListener(
339 base::Bind(&WebContentsImpl::OnFrameRemoved
,
340 base::Unretained(this)));
343 WebContentsImpl::~WebContentsImpl() {
344 is_being_destroyed_
= true;
346 // Delete all RFH pending shutdown, which will lead the corresponding RVH to
347 // shutdown and be deleted as well.
349 base::Bind(&RenderFrameHostManager::ClearRFHsPendingShutdown
));
351 ClearAllPowerSaveBlockers();
353 for (std::set
<RenderWidgetHostImpl
*>::iterator iter
=
354 created_widgets_
.begin(); iter
!= created_widgets_
.end(); ++iter
) {
355 (*iter
)->DetachDelegate();
357 created_widgets_
.clear();
359 // Clear out any JavaScript state.
361 dialog_manager_
->WebContentsDestroyed(this);
363 if (color_chooser_info_
.get())
364 color_chooser_info_
->chooser
->End();
366 NotifyDisconnected();
368 // Notify any observer that have a reference on this WebContents.
369 NotificationService::current()->Notify(
370 NOTIFICATION_WEB_CONTENTS_DESTROYED
,
371 Source
<WebContents
>(this),
372 NotificationService::NoDetails());
374 // Destroy all frame tree nodes except for the root; this notifies observers.
375 frame_tree_
.ResetForMainFrameSwap();
376 GetRenderManager()->ResetProxyHosts();
378 // Manually call the observer methods for the root frame tree node.
379 RenderFrameHostManager
* root
= GetRenderManager();
380 if (root
->pending_frame_host()) {
381 FOR_EACH_OBSERVER(WebContentsObserver
,
383 RenderFrameDeleted(root
->pending_frame_host()));
385 FOR_EACH_OBSERVER(WebContentsObserver
,
387 RenderFrameDeleted(root
->current_frame_host()));
389 if (root
->pending_render_view_host()) {
390 FOR_EACH_OBSERVER(WebContentsObserver
,
392 RenderViewDeleted(root
->pending_render_view_host()));
395 FOR_EACH_OBSERVER(WebContentsObserver
,
397 RenderViewDeleted(root
->current_host()));
399 FOR_EACH_OBSERVER(WebContentsObserver
,
401 WebContentsDestroyed());
403 FOR_EACH_OBSERVER(WebContentsObserver
,
409 STLDeleteContainerPairSecondPointers(destruction_observers_
.begin(),
410 destruction_observers_
.end());
413 WebContentsImpl
* WebContentsImpl::CreateWithOpener(
414 const WebContents::CreateParams
& params
,
415 WebContentsImpl
* opener
) {
416 TRACE_EVENT0("browser", "WebContentsImpl::CreateWithOpener");
417 WebContentsImpl
* new_contents
= new WebContentsImpl(
418 params
.browser_context
, params
.opener_suppressed
? NULL
: opener
);
420 if (params
.guest_delegate
) {
421 // This makes |new_contents| act as a guest.
422 // For more info, see comment above class BrowserPluginGuest.
423 BrowserPluginGuest::Create(new_contents
, params
.guest_delegate
);
424 // We are instantiating a WebContents for browser plugin. Set its subframe
426 new_contents
->is_subframe_
= true;
428 new_contents
->Init(params
);
433 std::vector
<WebContentsImpl
*> WebContentsImpl::GetAllWebContents() {
434 std::vector
<WebContentsImpl
*> result
;
435 scoped_ptr
<RenderWidgetHostIterator
> widgets(
436 RenderWidgetHostImpl::GetRenderWidgetHosts());
437 std::set
<WebContentsImpl
*> web_contents_set
;
438 while (RenderWidgetHost
* rwh
= widgets
->GetNextHost()) {
439 if (!rwh
->IsRenderView())
441 RenderViewHost
* rvh
= RenderViewHost::From(rwh
);
444 WebContents
* web_contents
= WebContents::FromRenderViewHost(rvh
);
447 WebContentsImpl
* wci
= static_cast<WebContentsImpl
*>(web_contents
);
448 if (web_contents_set
.find(wci
) == web_contents_set
.end()) {
449 web_contents_set
.insert(wci
);
450 result
.push_back(wci
);
456 RenderFrameHostManager
* WebContentsImpl::GetRenderManagerForTesting() {
457 return GetRenderManager();
460 bool WebContentsImpl::OnMessageReceived(RenderViewHost
* render_view_host
,
461 const IPC::Message
& message
) {
462 return OnMessageReceived(render_view_host
, NULL
, message
);
465 bool WebContentsImpl::OnMessageReceived(RenderViewHost
* render_view_host
,
466 RenderFrameHost
* render_frame_host
,
467 const IPC::Message
& message
) {
468 DCHECK(render_view_host
|| render_frame_host
);
470 static_cast<WebUIImpl
*>(GetWebUI())->OnMessageReceived(message
)) {
474 ObserverListBase
<WebContentsObserver
>::Iterator
it(observers_
);
475 WebContentsObserver
* observer
;
476 if (render_frame_host
) {
477 while ((observer
= it
.GetNext()) != NULL
)
478 if (observer
->OnMessageReceived(message
, render_frame_host
))
481 while ((observer
= it
.GetNext()) != NULL
)
482 if (observer
->OnMessageReceived(message
))
486 // Message handlers should be aware of which
487 // RenderViewHost/RenderFrameHost sent the message, which is temporarily
488 // stored in render_(view|frame)_message_source_.
489 if (render_frame_host
)
490 render_frame_message_source_
= render_frame_host
;
492 render_view_message_source_
= render_view_host
;
495 IPC_BEGIN_MESSAGE_MAP(WebContentsImpl
, message
)
496 IPC_MESSAGE_HANDLER(FrameHostMsg_DomOperationResponse
,
497 OnDomOperationResponse
)
498 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeThemeColor
,
500 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishDocumentLoad
,
501 OnDocumentLoadedInFrame
)
502 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishLoad
, OnDidFinishLoad
)
503 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartLoading
, OnDidStartLoading
)
504 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading
, OnDidStopLoading
)
505 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress
,
506 OnDidChangeLoadProgress
)
507 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenColorChooser
, OnOpenColorChooser
)
508 IPC_MESSAGE_HANDLER(FrameHostMsg_EndColorChooser
, OnEndColorChooser
)
509 IPC_MESSAGE_HANDLER(FrameHostMsg_SetSelectedColorInColorChooser
,
510 OnSetSelectedColorInColorChooser
)
511 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPlayingNotification
,
512 OnMediaPlayingNotification
)
513 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPausedNotification
,
514 OnMediaPausedNotification
)
515 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFirstVisuallyNonEmptyPaint
,
516 OnFirstVisuallyNonEmptyPaint
)
517 IPC_MESSAGE_HANDLER(ViewHostMsg_DidLoadResourceFromMemoryCache
,
518 OnDidLoadResourceFromMemoryCache
)
519 IPC_MESSAGE_HANDLER(ViewHostMsg_DidDisplayInsecureContent
,
520 OnDidDisplayInsecureContent
)
521 IPC_MESSAGE_HANDLER(ViewHostMsg_DidRunInsecureContent
,
522 OnDidRunInsecureContent
)
523 IPC_MESSAGE_HANDLER(ViewHostMsg_GoToEntryAtOffset
, OnGoToEntryAtOffset
)
524 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateZoomLimits
, OnUpdateZoomLimits
)
525 IPC_MESSAGE_HANDLER(ViewHostMsg_EnumerateDirectory
, OnEnumerateDirectory
)
526 IPC_MESSAGE_HANDLER(ViewHostMsg_RegisterProtocolHandler
,
527 OnRegisterProtocolHandler
)
528 IPC_MESSAGE_HANDLER(ViewHostMsg_UnregisterProtocolHandler
,
529 OnUnregisterProtocolHandler
)
530 IPC_MESSAGE_HANDLER(ViewHostMsg_Find_Reply
, OnFindReply
)
531 IPC_MESSAGE_HANDLER(ViewHostMsg_AppCacheAccessed
, OnAppCacheAccessed
)
532 IPC_MESSAGE_HANDLER(ViewHostMsg_WebUISend
, OnWebUISend
)
533 #if defined(ENABLE_PLUGINS)
534 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung
, OnPepperPluginHung
)
535 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed
, OnPluginCrashed
)
536 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission
,
537 OnRequestPpapiBrokerPermission
)
538 IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_Attach
,
539 OnBrowserPluginMessage(message
))
541 IPC_MESSAGE_HANDLER(ImageHostMsg_DidDownloadImage
, OnDidDownloadImage
)
542 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateFaviconURL
, OnUpdateFaviconURL
)
543 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowValidationMessage
,
544 OnShowValidationMessage
)
545 IPC_MESSAGE_HANDLER(ViewHostMsg_HideValidationMessage
,
546 OnHideValidationMessage
)
547 IPC_MESSAGE_HANDLER(ViewHostMsg_MoveValidationMessage
,
548 OnMoveValidationMessage
)
549 #if defined(OS_ANDROID)
550 IPC_MESSAGE_HANDLER(ViewHostMsg_FindMatchRects_Reply
,
551 OnFindMatchRectsReply
)
552 IPC_MESSAGE_HANDLER(ViewHostMsg_OpenDateTimeDialog
,
553 OnOpenDateTimeDialog
)
555 IPC_MESSAGE_UNHANDLED(handled
= false)
556 IPC_END_MESSAGE_MAP()
557 render_view_message_source_
= NULL
;
558 render_frame_message_source_
= NULL
;
563 void WebContentsImpl::RunFileChooser(
564 RenderViewHost
* render_view_host
,
565 const FileChooserParams
& params
) {
567 delegate_
->RunFileChooser(this, params
);
570 NavigationControllerImpl
& WebContentsImpl::GetController() {
574 const NavigationControllerImpl
& WebContentsImpl::GetController() const {
578 BrowserContext
* WebContentsImpl::GetBrowserContext() const {
579 return controller_
.GetBrowserContext();
582 const GURL
& WebContentsImpl::GetURL() const {
583 // We may not have a navigation entry yet.
584 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
585 return entry
? entry
->GetVirtualURL() : GURL::EmptyGURL();
588 const GURL
& WebContentsImpl::GetVisibleURL() const {
589 // We may not have a navigation entry yet.
590 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
591 return entry
? entry
->GetVirtualURL() : GURL::EmptyGURL();
594 const GURL
& WebContentsImpl::GetLastCommittedURL() const {
595 // We may not have a navigation entry yet.
596 NavigationEntry
* entry
= controller_
.GetLastCommittedEntry();
597 return entry
? entry
->GetVirtualURL() : GURL::EmptyGURL();
600 WebContentsDelegate
* WebContentsImpl::GetDelegate() {
604 void WebContentsImpl::SetDelegate(WebContentsDelegate
* delegate
) {
605 // TODO(cbentzel): remove this debugging code?
606 if (delegate
== delegate_
)
609 delegate_
->Detach(this);
610 delegate_
= delegate
;
612 delegate_
->Attach(this);
613 // Ensure the visible RVH reflects the new delegate's preferences.
615 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
619 RenderProcessHost
* WebContentsImpl::GetRenderProcessHost() const {
620 RenderViewHostImpl
* host
= GetRenderManager()->current_host();
621 return host
? host
->GetProcess() : NULL
;
624 RenderFrameHost
* WebContentsImpl::GetMainFrame() {
625 return frame_tree_
.root()->current_frame_host();
628 RenderFrameHost
* WebContentsImpl::GetFocusedFrame() {
629 if (!frame_tree_
.GetFocusedFrame())
631 return frame_tree_
.GetFocusedFrame()->current_frame_host();
634 void WebContentsImpl::ForEachFrame(
635 const base::Callback
<void(RenderFrameHost
*)>& on_frame
) {
636 frame_tree_
.ForEach(base::Bind(&ForEachFrameInternal
, on_frame
));
639 void WebContentsImpl::SendToAllFrames(IPC::Message
* message
) {
640 ForEachFrame(base::Bind(&SendToAllFramesInternal
, message
));
644 RenderViewHost
* WebContentsImpl::GetRenderViewHost() const {
645 return GetRenderManager()->current_host();
648 int WebContentsImpl::GetRoutingID() const {
649 if (!GetRenderViewHost())
650 return MSG_ROUTING_NONE
;
652 return GetRenderViewHost()->GetRoutingID();
655 int WebContentsImpl::GetFullscreenWidgetRoutingID() const {
656 return fullscreen_widget_routing_id_
;
659 RenderWidgetHostView
* WebContentsImpl::GetRenderWidgetHostView() const {
660 return GetRenderManager()->GetRenderWidgetHostView();
663 RenderWidgetHostView
* WebContentsImpl::GetFullscreenRenderWidgetHostView()
665 RenderWidgetHost
* const widget_host
=
666 RenderWidgetHostImpl::FromID(GetRenderProcessHost()->GetID(),
667 GetFullscreenWidgetRoutingID());
668 return widget_host
? widget_host
->GetView() : NULL
;
671 WebContentsView
* WebContentsImpl::GetView() const {
675 void WebContentsImpl::SetAccessibilityMode(AccessibilityMode mode
) {
676 if (mode
== accessibility_mode_
)
679 accessibility_mode_
= mode
;
681 base::Bind(&ForEachFrameInternal
,
682 base::Bind(&SetAccessibilityModeOnFrame
, mode
)));
684 base::Bind(&ForEachPendingFrameInternal
,
685 base::Bind(&SetAccessibilityModeOnFrame
, mode
)));
688 void WebContentsImpl::AddAccessibilityMode(AccessibilityMode mode
) {
689 SetAccessibilityMode(AddAccessibilityModeTo(accessibility_mode_
, mode
));
692 void WebContentsImpl::RemoveAccessibilityMode(AccessibilityMode mode
) {
693 SetAccessibilityMode(RemoveAccessibilityModeFrom(accessibility_mode_
, mode
));
696 void WebContentsImpl::ClearNavigationTransitionData() {
697 FrameTreeNode
* node
= frame_tree_
.root();
698 node
->render_manager()->ClearNavigationTransitionData();
701 WebUI
* WebContentsImpl::CreateWebUI(const GURL
& url
) {
702 WebUIImpl
* web_ui
= new WebUIImpl(this);
703 WebUIController
* controller
= WebUIControllerFactoryRegistry::GetInstance()->
704 CreateWebUIControllerForURL(web_ui
, url
);
706 web_ui
->AddMessageHandler(new GenericHandler());
707 web_ui
->SetController(controller
);
715 WebUI
* WebContentsImpl::GetWebUI() const {
716 return GetRenderManager()->web_ui() ? GetRenderManager()->web_ui()
717 : GetRenderManager()->pending_web_ui();
720 WebUI
* WebContentsImpl::GetCommittedWebUI() const {
721 return GetRenderManager()->web_ui();
724 void WebContentsImpl::SetUserAgentOverride(const std::string
& override
) {
725 if (GetUserAgentOverride() == override
)
728 renderer_preferences_
.user_agent_override
= override
;
730 // Send the new override string to the renderer.
731 RenderViewHost
* host
= GetRenderViewHost();
733 host
->SyncRendererPrefs();
735 // Reload the page if a load is currently in progress to avoid having
736 // different parts of the page loaded using different user agents.
737 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
738 if (is_loading_
&& entry
!= NULL
&& entry
->GetIsOverridingUserAgent())
739 controller_
.ReloadIgnoringCache(true);
741 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
742 UserAgentOverrideSet(override
));
745 const std::string
& WebContentsImpl::GetUserAgentOverride() const {
746 return renderer_preferences_
.user_agent_override
;
749 void WebContentsImpl::EnableTreeOnlyAccessibilityMode() {
750 AddAccessibilityMode(AccessibilityModeTreeOnly
);
753 bool WebContentsImpl::IsTreeOnlyAccessibilityModeForTesting() const {
754 return accessibility_mode_
== AccessibilityModeTreeOnly
;
757 bool WebContentsImpl::IsFullAccessibilityModeForTesting() const {
758 return accessibility_mode_
== AccessibilityModeComplete
;
762 void WebContentsImpl::SetParentNativeViewAccessible(
763 gfx::NativeViewAccessible accessible_parent
) {
764 accessible_parent_
= accessible_parent
;
765 RenderFrameHostImpl
* rfh
= static_cast<RenderFrameHostImpl
*>(GetMainFrame());
767 rfh
->SetParentNativeViewAccessible(accessible_parent
);
771 const base::string16
& WebContentsImpl::GetTitle() const {
772 // Transient entries take precedence. They are used for interstitial pages
773 // that are shown on top of existing pages.
774 NavigationEntry
* entry
= controller_
.GetTransientEntry();
775 std::string accept_languages
=
776 GetContentClient()->browser()->GetAcceptLangs(
777 GetBrowserContext());
779 return entry
->GetTitleForDisplay(accept_languages
);
781 WebUI
* our_web_ui
= GetRenderManager()->pending_web_ui() ?
782 GetRenderManager()->pending_web_ui() : GetRenderManager()->web_ui();
784 // Don't override the title in view source mode.
785 entry
= controller_
.GetVisibleEntry();
786 if (!(entry
&& entry
->IsViewSourceMode())) {
787 // Give the Web UI the chance to override our title.
788 const base::string16
& title
= our_web_ui
->GetOverriddenTitle();
794 // We use the title for the last committed entry rather than a pending
795 // navigation entry. For example, when the user types in a URL, we want to
796 // keep the old page's title until the new load has committed and we get a new
798 entry
= controller_
.GetLastCommittedEntry();
800 // We make an exception for initial navigations.
801 if (controller_
.IsInitialNavigation()) {
802 // We only want to use the title from the visible entry in one of two cases:
803 // 1. There's already a committed entry for an initial navigation, in which
804 // case we are doing a history navigation in a new tab (e.g., Ctrl+Back).
805 // 2. The pending entry has been explicitly assigned a title to display.
807 // If there's no last committed entry and no assigned title, we should fall
808 // back to |page_title_when_no_navigation_entry_| rather than showing the
811 (controller_
.GetVisibleEntry() &&
812 !controller_
.GetVisibleEntry()->GetTitle().empty())) {
813 entry
= controller_
.GetVisibleEntry();
818 return entry
->GetTitleForDisplay(accept_languages
);
821 // |page_title_when_no_navigation_entry_| is finally used
822 // if no title cannot be retrieved.
823 return page_title_when_no_navigation_entry_
;
826 int32
WebContentsImpl::GetMaxPageID() {
827 return GetMaxPageIDForSiteInstance(GetSiteInstance());
830 int32
WebContentsImpl::GetMaxPageIDForSiteInstance(
831 SiteInstance
* site_instance
) {
832 if (max_page_ids_
.find(site_instance
->GetId()) == max_page_ids_
.end())
833 max_page_ids_
[site_instance
->GetId()] = -1;
835 return max_page_ids_
[site_instance
->GetId()];
838 void WebContentsImpl::UpdateMaxPageID(int32 page_id
) {
839 UpdateMaxPageIDForSiteInstance(GetSiteInstance(), page_id
);
842 void WebContentsImpl::UpdateMaxPageIDForSiteInstance(
843 SiteInstance
* site_instance
, int32 page_id
) {
844 if (GetMaxPageIDForSiteInstance(site_instance
) < page_id
)
845 max_page_ids_
[site_instance
->GetId()] = page_id
;
848 void WebContentsImpl::CopyMaxPageIDsFrom(WebContents
* web_contents
) {
849 WebContentsImpl
* contents
= static_cast<WebContentsImpl
*>(web_contents
);
850 max_page_ids_
= contents
->max_page_ids_
;
853 SiteInstanceImpl
* WebContentsImpl::GetSiteInstance() const {
854 return GetRenderManager()->current_host()->GetSiteInstance();
857 SiteInstanceImpl
* WebContentsImpl::GetPendingSiteInstance() const {
858 RenderViewHostImpl
* dest_rvh
=
859 GetRenderManager()->pending_render_view_host() ?
860 GetRenderManager()->pending_render_view_host() :
861 GetRenderManager()->current_host();
862 return dest_rvh
->GetSiteInstance();
865 bool WebContentsImpl::IsLoading() const {
869 bool WebContentsImpl::IsLoadingToDifferentDocument() const {
870 return is_loading_
&& is_load_to_different_document_
;
873 bool WebContentsImpl::IsWaitingForResponse() const {
874 return waiting_for_response_
&& is_load_to_different_document_
;
877 const net::LoadStateWithParam
& WebContentsImpl::GetLoadState() const {
881 const base::string16
& WebContentsImpl::GetLoadStateHost() const {
882 return load_state_host_
;
885 uint64
WebContentsImpl::GetUploadSize() const {
889 uint64
WebContentsImpl::GetUploadPosition() const {
890 return upload_position_
;
893 std::set
<GURL
> WebContentsImpl::GetSitesInTab() const {
894 std::set
<GURL
> sites
;
895 frame_tree_
.ForEach(base::Bind(&CollectSites
,
896 base::Unretained(GetBrowserContext()),
897 base::Unretained(&sites
)));
901 const std::string
& WebContentsImpl::GetEncoding() const {
902 return canonical_encoding_
;
905 bool WebContentsImpl::DisplayedInsecureContent() const {
906 return displayed_insecure_content_
;
909 void WebContentsImpl::IncrementCapturerCount(const gfx::Size
& capture_size
) {
910 DCHECK(!is_being_destroyed_
);
912 DVLOG(1) << "There are now " << capturer_count_
913 << " capturing(s) of WebContentsImpl@" << this;
915 // Note: This provides a hint to upstream code to size the views optimally
916 // for quality (e.g., to avoid scaling).
917 if (!capture_size
.IsEmpty() && preferred_size_for_capture_
.IsEmpty()) {
918 preferred_size_for_capture_
= capture_size
;
919 OnPreferredSizeChanged(preferred_size_
);
923 void WebContentsImpl::DecrementCapturerCount() {
925 DVLOG(1) << "There are now " << capturer_count_
926 << " capturing(s) of WebContentsImpl@" << this;
927 DCHECK_LE(0, capturer_count_
);
929 if (is_being_destroyed_
)
932 if (capturer_count_
== 0) {
933 const gfx::Size old_size
= preferred_size_for_capture_
;
934 preferred_size_for_capture_
= gfx::Size();
935 OnPreferredSizeChanged(old_size
);
939 DVLOG(1) << "Executing delayed WasHidden().";
944 int WebContentsImpl::GetCapturerCount() const {
945 return capturer_count_
;
948 bool WebContentsImpl::IsAudioMuted() const {
949 return audio_muter_
.get() && audio_muter_
->is_muting();
952 void WebContentsImpl::SetAudioMuted(bool mute
) {
953 DVLOG(1) << "SetAudioMuted(mute=" << mute
<< "), was " << IsAudioMuted()
954 << " for WebContentsImpl@" << this;
956 if (mute
== IsAudioMuted())
961 audio_muter_
.reset(new WebContentsAudioMuter(this));
962 audio_muter_
->StartMuting();
964 DCHECK(audio_muter_
);
965 audio_muter_
->StopMuting();
968 // Notification for UI updates in response to the changed muting state.
969 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB
);
972 bool WebContentsImpl::IsCrashed() const {
973 return (crashed_status_
== base::TERMINATION_STATUS_PROCESS_CRASHED
||
974 crashed_status_
== base::TERMINATION_STATUS_ABNORMAL_TERMINATION
||
975 crashed_status_
== base::TERMINATION_STATUS_PROCESS_WAS_KILLED
);
978 void WebContentsImpl::SetIsCrashed(base::TerminationStatus status
,
980 if (status
== crashed_status_
)
983 crashed_status_
= status
;
984 crashed_error_code_
= error_code
;
985 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB
);
988 base::TerminationStatus
WebContentsImpl::GetCrashedStatus() const {
989 return crashed_status_
;
992 bool WebContentsImpl::IsBeingDestroyed() const {
993 return is_being_destroyed_
;
996 void WebContentsImpl::NotifyNavigationStateChanged(
997 InvalidateTypes changed_flags
) {
998 // Create and release the audio power save blocker depending on whether the
999 // tab is actively producing audio or not.
1000 if (changed_flags
== INVALIDATE_TYPE_TAB
&&
1001 AudioStreamMonitor::monitoring_available()) {
1002 if (WasRecentlyAudible()) {
1003 if (!audio_power_save_blocker_
)
1004 CreateAudioPowerSaveBlocker();
1006 audio_power_save_blocker_
.reset();
1011 delegate_
->NavigationStateChanged(this, changed_flags
);
1014 base::TimeTicks
WebContentsImpl::GetLastActiveTime() const {
1015 return last_active_time_
;
1018 void WebContentsImpl::WasShown() {
1019 controller_
.SetActive(true);
1021 std::set
<RenderWidgetHostView
*> widgets
= GetRenderWidgetHostViewsInTree();
1022 for (std::set
<RenderWidgetHostView
*>::iterator iter
= widgets
.begin();
1023 iter
!= widgets
.end();
1027 #if defined(OS_MACOSX)
1028 (*iter
)->SetActive(true);
1033 last_active_time_
= base::TimeTicks::Now();
1035 // The resize rect might have changed while this was inactive -- send the new
1036 // one to make sure it's up to date.
1037 RenderViewHostImpl
* rvh
=
1038 static_cast<RenderViewHostImpl
*>(GetRenderViewHost());
1040 rvh
->ResizeRectChanged(GetRootWindowResizerRect());
1043 // Restore power save blocker if there are active video players running.
1044 if (!active_video_players_
.empty() && !video_power_save_blocker_
)
1045 CreateVideoPowerSaveBlocker();
1047 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, WasShown());
1049 should_normally_be_visible_
= true;
1052 void WebContentsImpl::WasHidden() {
1053 // If there are entities capturing screenshots or video (e.g., mirroring),
1054 // don't activate the "disable rendering" optimization.
1055 if (capturer_count_
== 0) {
1056 // |GetRenderViewHost()| can be NULL if the user middle clicks a link to
1057 // open a tab in the background, then closes the tab before selecting it.
1058 // This is because closing the tab calls WebContentsImpl::Destroy(), which
1059 // removes the |GetRenderViewHost()|; then when we actually destroy the
1060 // window, OnWindowPosChanged() notices and calls WasHidden() (which
1062 std::set
<RenderWidgetHostView
*> widgets
= GetRenderWidgetHostViewsInTree();
1063 for (std::set
<RenderWidgetHostView
*>::iterator iter
= widgets
.begin();
1064 iter
!= widgets
.end();
1070 // Release any video power save blockers held as video is not visible.
1071 video_power_save_blocker_
.reset();
1074 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, WasHidden());
1076 should_normally_be_visible_
= false;
1079 bool WebContentsImpl::NeedToFireBeforeUnload() {
1080 // TODO(creis): Should we fire even for interstitial pages?
1081 return WillNotifyDisconnection() &&
1082 !ShowingInterstitialPage() &&
1083 !static_cast<RenderViewHostImpl
*>(
1084 GetRenderViewHost())->SuddenTerminationAllowed();
1087 void WebContentsImpl::DispatchBeforeUnload(bool for_cross_site_transition
) {
1088 static_cast<RenderFrameHostImpl
*>(GetMainFrame())->DispatchBeforeUnload(
1089 for_cross_site_transition
);
1092 void WebContentsImpl::Stop() {
1093 GetRenderManager()->Stop();
1094 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, NavigationStopped());
1097 WebContents
* WebContentsImpl::Clone() {
1098 // We use our current SiteInstance since the cloned entry will use it anyway.
1099 // We pass our own opener so that the cloned page can access it if it was
1101 CreateParams
create_params(GetBrowserContext(), GetSiteInstance());
1102 create_params
.initial_size
= GetContainerBounds().size();
1103 WebContentsImpl
* tc
= CreateWithOpener(create_params
, opener_
);
1104 tc
->GetController().CopyStateFrom(controller_
);
1105 FOR_EACH_OBSERVER(WebContentsObserver
,
1107 DidCloneToNewWebContents(this, tc
));
1111 void WebContentsImpl::Observe(int type
,
1112 const NotificationSource
& source
,
1113 const NotificationDetails
& details
) {
1115 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED
: {
1116 RenderWidgetHost
* host
= Source
<RenderWidgetHost
>(source
).ptr();
1117 RenderWidgetHostView
* view
= host
->GetView();
1118 if (view
== GetFullscreenRenderWidgetHostView()) {
1119 // We cannot just call view_->RestoreFocus() here. On some platforms,
1120 // attempting to focus the currently-invisible WebContentsView will be
1121 // flat-out ignored. Therefore, this boolean is used to track whether
1122 // we will request focus after the fullscreen widget has been
1124 fullscreen_widget_had_focus_at_shutdown_
= (view
&& view
->HasFocus());
1126 for (PendingWidgetViews::iterator i
= pending_widget_views_
.begin();
1127 i
!= pending_widget_views_
.end(); ++i
) {
1128 if (host
->GetView() == i
->second
) {
1129 pending_widget_views_
.erase(i
);
1141 WebContents
* WebContentsImpl::GetWebContents() {
1145 void WebContentsImpl::Init(const WebContents::CreateParams
& params
) {
1146 // This is set before initializing the render manager since
1147 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
1148 // it should be hidden.
1149 should_normally_be_visible_
= !params
.initially_hidden
;
1151 GetRenderManager()->Init(
1152 params
.browser_context
, params
.site_instance
, params
.routing_id
,
1153 params
.main_frame_routing_id
);
1155 WebContentsViewDelegate
* delegate
=
1156 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
1158 if (browser_plugin_guest_
) {
1159 scoped_ptr
<WebContentsView
> platform_view(CreateWebContentsView(
1160 this, delegate
, &render_view_host_delegate_view_
));
1162 WebContentsViewGuest
* rv
= new WebContentsViewGuest(
1163 this, browser_plugin_guest_
.get(), platform_view
.Pass(),
1164 render_view_host_delegate_view_
);
1165 render_view_host_delegate_view_
= rv
;
1168 // Regular WebContentsView.
1169 view_
.reset(CreateWebContentsView(
1170 this, delegate
, &render_view_host_delegate_view_
));
1172 CHECK(render_view_host_delegate_view_
);
1175 gfx::Size initial_size
= params
.initial_size
;
1176 view_
->CreateView(initial_size
, params
.context
);
1178 // Listen for whether our opener gets destroyed.
1180 AddDestructionObserver(opener_
);
1182 #if defined(ENABLE_PLUGINS)
1183 plugin_content_origin_whitelist_
.reset(
1184 new PluginContentOriginWhitelist(this));
1187 registrar_
.Add(this,
1188 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED
,
1189 NotificationService::AllBrowserContextsAndSources());
1191 screen_orientation_dispatcher_host_
.reset(
1192 new ScreenOrientationDispatcherHostImpl(this));
1194 manifest_manager_host_
.reset(new ManifestManagerHost(this));
1196 #if defined(OS_ANDROID)
1197 date_time_chooser_
.reset(new DateTimeChooserAndroid());
1200 // BrowserPluginGuest::Init needs to be called after this WebContents has
1201 // a RenderWidgetHostViewGuest. That is, |view_->CreateView| above.
1202 if (browser_plugin_guest_
)
1203 browser_plugin_guest_
->Init();
1206 void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl
* web_contents
) {
1207 RemoveDestructionObserver(web_contents
);
1209 // Clear the opener if it has been closed.
1210 if (web_contents
== opener_
) {
1214 // Clear a pending contents that has been closed before being shown.
1215 for (PendingContents::iterator iter
= pending_contents_
.begin();
1216 iter
!= pending_contents_
.end();
1218 if (iter
->second
!= web_contents
)
1220 pending_contents_
.erase(iter
);
1226 void WebContentsImpl::AddDestructionObserver(WebContentsImpl
* web_contents
) {
1227 if (!ContainsKey(destruction_observers_
, web_contents
)) {
1228 destruction_observers_
[web_contents
] =
1229 new DestructionObserver(this, web_contents
);
1233 void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl
* web_contents
) {
1234 DestructionObservers::iterator iter
=
1235 destruction_observers_
.find(web_contents
);
1236 if (iter
!= destruction_observers_
.end()) {
1237 delete destruction_observers_
[web_contents
];
1238 destruction_observers_
.erase(iter
);
1242 void WebContentsImpl::AddObserver(WebContentsObserver
* observer
) {
1243 observers_
.AddObserver(observer
);
1246 void WebContentsImpl::RemoveObserver(WebContentsObserver
* observer
) {
1247 observers_
.RemoveObserver(observer
);
1250 std::set
<RenderWidgetHostView
*>
1251 WebContentsImpl::GetRenderWidgetHostViewsInTree() {
1252 std::set
<RenderWidgetHostView
*> set
;
1253 if (ShowingInterstitialPage()) {
1254 set
.insert(GetRenderWidgetHostView());
1257 base::Bind(&AddRenderWidgetHostViewToSet
, base::Unretained(&set
)));
1262 void WebContentsImpl::Activate() {
1264 delegate_
->ActivateContents(this);
1267 void WebContentsImpl::Deactivate() {
1269 delegate_
->DeactivateContents(this);
1272 void WebContentsImpl::LostCapture() {
1274 delegate_
->LostCapture();
1277 void WebContentsImpl::RenderWidgetDeleted(
1278 RenderWidgetHostImpl
* render_widget_host
) {
1279 if (is_being_destroyed_
) {
1280 // |created_widgets_| might have been destroyed.
1284 std::set
<RenderWidgetHostImpl
*>::iterator iter
=
1285 created_widgets_
.find(render_widget_host
);
1286 if (iter
!= created_widgets_
.end())
1287 created_widgets_
.erase(iter
);
1289 if (render_widget_host
&&
1290 render_widget_host
->GetRoutingID() == fullscreen_widget_routing_id_
) {
1291 if (delegate_
&& delegate_
->EmbedsFullscreenWidget())
1292 delegate_
->ToggleFullscreenModeForTab(this, false);
1293 FOR_EACH_OBSERVER(WebContentsObserver
,
1295 DidDestroyFullscreenWidget(
1296 fullscreen_widget_routing_id_
));
1297 fullscreen_widget_routing_id_
= MSG_ROUTING_NONE
;
1298 if (fullscreen_widget_had_focus_at_shutdown_
)
1299 view_
->RestoreFocus();
1303 void WebContentsImpl::RenderWidgetGotFocus(
1304 RenderWidgetHostImpl
* render_widget_host
) {
1305 // Notify the delegate if an embedded fullscreen widget was focused.
1306 if (delegate_
&& render_widget_host
&&
1307 delegate_
->EmbedsFullscreenWidget() &&
1308 render_widget_host
->GetView() == GetFullscreenRenderWidgetHostView())
1309 delegate_
->WebContentsFocused(this);
1312 bool WebContentsImpl::PreHandleKeyboardEvent(
1313 const NativeWebKeyboardEvent
& event
,
1314 bool* is_keyboard_shortcut
) {
1316 delegate_
->PreHandleKeyboardEvent(this, event
, is_keyboard_shortcut
);
1319 void WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent
& event
) {
1320 if (browser_plugin_embedder_
&&
1321 browser_plugin_embedder_
->HandleKeyboardEvent(event
)) {
1325 delegate_
->HandleKeyboardEvent(this, event
);
1328 bool WebContentsImpl::HandleWheelEvent(
1329 const blink::WebMouseWheelEvent
& event
) {
1330 #if !defined(OS_MACOSX)
1331 // On platforms other than Mac, control+mousewheel changes zoom. On Mac, this
1332 // isn't done for two reasons:
1333 // -the OS already has a gesture to do this through pinch-zoom
1334 // -if a user starts an inertial scroll, let's go, and presses control
1335 // (i.e. control+tab) then the OS's buffered scroll events will come in
1336 // with control key set which isn't what the user wants
1338 event
.wheelTicksY
&&
1339 (event
.modifiers
& blink::WebInputEvent::ControlKey
) &&
1340 // Avoid adjusting the zoom in response to two-finger-scrolling touchpad
1341 // gestures, which are regrettably easy to trigger accidentally.
1342 !event
.hasPreciseScrollingDeltas
) {
1343 delegate_
->ContentsZoomChange(event
.wheelTicksY
> 0);
1350 bool WebContentsImpl::PreHandleGestureEvent(
1351 const blink::WebGestureEvent
& event
) {
1352 return delegate_
&& delegate_
->PreHandleGestureEvent(this, event
);
1355 bool WebContentsImpl::HandleGestureEvent(
1356 const blink::WebGestureEvent
& event
) {
1357 // Some platforms (eg. Mac) send GesturePinch events for trackpad pinch-zoom.
1358 // Use them to implement browser zoom, as for HandleWheelEvent above.
1359 if (event
.type
== blink::WebInputEvent::GesturePinchUpdate
&&
1360 event
.sourceDevice
== blink::WebGestureDeviceTouchpad
) {
1361 // The scale difference necessary to trigger a zoom action. Derived from
1362 // experimentation to find a value that feels reasonable.
1363 const float kZoomStepValue
= 0.6f
;
1365 // Find the (absolute) thresholds on either side of the current zoom factor,
1366 // then convert those to actual numbers to trigger a zoom in or out.
1367 // This logic deliberately makes the range around the starting zoom value
1368 // for the gesture twice as large as the other ranges (i.e., the notches are
1369 // at ..., -3*step, -2*step, -step, step, 2*step, 3*step, ... but not at 0)
1370 // so that it's easier to get back to your starting point than it is to
1372 float nextStep
= (abs(currentPinchZoomStepDelta_
) + 1) * kZoomStepValue
;
1373 float backStep
= abs(currentPinchZoomStepDelta_
) * kZoomStepValue
;
1374 float zoomInThreshold
= (currentPinchZoomStepDelta_
>= 0) ? nextStep
1376 float zoomOutThreshold
= (currentPinchZoomStepDelta_
<= 0) ? -nextStep
1379 totalPinchGestureAmount_
+= (event
.data
.pinchUpdate
.scale
- 1.0);
1380 if (totalPinchGestureAmount_
> zoomInThreshold
) {
1381 currentPinchZoomStepDelta_
++;
1383 delegate_
->ContentsZoomChange(true);
1384 } else if (totalPinchGestureAmount_
< zoomOutThreshold
) {
1385 currentPinchZoomStepDelta_
--;
1387 delegate_
->ContentsZoomChange(false);
1395 void WebContentsImpl::HandleMouseDown() {
1397 delegate_
->HandleMouseDown();
1400 void WebContentsImpl::HandleMouseUp() {
1402 delegate_
->HandleMouseUp();
1405 void WebContentsImpl::HandlePointerActivate() {
1407 delegate_
->HandlePointerActivate();
1410 void WebContentsImpl::HandleGestureBegin() {
1412 delegate_
->HandleGestureBegin();
1415 void WebContentsImpl::HandleGestureEnd() {
1417 delegate_
->HandleGestureEnd();
1420 void WebContentsImpl::ToggleFullscreenMode(bool enter_fullscreen
) {
1421 // This method is being called to enter or leave renderer-initiated fullscreen
1422 // mode. Either way, make sure any existing fullscreen widget is shut down
1424 RenderWidgetHostView
* const widget_view
= GetFullscreenRenderWidgetHostView();
1426 RenderWidgetHostImpl::From(widget_view
->GetRenderWidgetHost())->Shutdown();
1429 delegate_
->ToggleFullscreenModeForTab(this, enter_fullscreen
);
1431 FOR_EACH_OBSERVER(WebContentsObserver
,
1433 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1436 bool WebContentsImpl::IsFullscreenForCurrentTab() const {
1437 return delegate_
? delegate_
->IsFullscreenForTabOrPending(this) : false;
1440 void WebContentsImpl::RequestToLockMouse(bool user_gesture
,
1441 bool last_unlocked_by_target
) {
1443 delegate_
->RequestToLockMouse(this, user_gesture
, last_unlocked_by_target
);
1445 GotResponseToLockMouseRequest(false);
1449 void WebContentsImpl::LostMouseLock() {
1451 delegate_
->LostMouseLock();
1454 void WebContentsImpl::CreateNewWindow(
1455 int render_process_id
,
1457 int main_frame_route_id
,
1458 const ViewHostMsg_CreateWindow_Params
& params
,
1459 SessionStorageNamespace
* session_storage_namespace
) {
1460 // We usually create the new window in the same BrowsingInstance (group of
1461 // script-related windows), by passing in the current SiteInstance. However,
1462 // if the opener is being suppressed (in a non-guest), we create a new
1463 // SiteInstance in its own BrowsingInstance.
1464 bool is_guest
= BrowserPluginGuest::IsGuest(this);
1466 // If the opener is to be suppressed, the new window can be in any process.
1467 // Since routing ids are process specific, we must not have one passed in
1468 // as argument here.
1469 DCHECK(!params
.opener_suppressed
|| route_id
== MSG_ROUTING_NONE
);
1471 scoped_refptr
<SiteInstance
> site_instance
=
1472 params
.opener_suppressed
&& !is_guest
?
1473 SiteInstance::CreateForURL(GetBrowserContext(), params
.target_url
) :
1476 // A message to create a new window can only come from the active process for
1477 // this WebContentsImpl instance. If any other process sends the request,
1478 // it is invalid and the process must be terminated.
1479 if (GetRenderProcessHost()->GetID() != render_process_id
) {
1480 RenderProcessHost
* rph
= RenderProcessHost::FromID(render_process_id
);
1481 base::ProcessHandle process_handle
= rph
->GetHandle();
1482 if (process_handle
!= base::kNullProcessHandle
) {
1484 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWindow"));
1485 rph
->Shutdown(RESULT_CODE_KILLED
, false);
1490 // We must assign the SessionStorageNamespace before calling Init().
1492 // http://crbug.com/142685
1493 const std::string
& partition_id
=
1494 GetContentClient()->browser()->
1495 GetStoragePartitionIdForSite(GetBrowserContext(),
1496 site_instance
->GetSiteURL());
1497 StoragePartition
* partition
= BrowserContext::GetStoragePartition(
1498 GetBrowserContext(), site_instance
.get());
1499 DOMStorageContextWrapper
* dom_storage_context
=
1500 static_cast<DOMStorageContextWrapper
*>(partition
->GetDOMStorageContext());
1501 SessionStorageNamespaceImpl
* session_storage_namespace_impl
=
1502 static_cast<SessionStorageNamespaceImpl
*>(session_storage_namespace
);
1503 CHECK(session_storage_namespace_impl
->IsFromContext(dom_storage_context
));
1506 !delegate_
->ShouldCreateWebContents(this,
1508 params
.window_container_type
,
1512 session_storage_namespace
)) {
1513 if (route_id
!= MSG_ROUTING_NONE
&&
1514 !RenderViewHost::FromID(render_process_id
, route_id
)) {
1515 // If the embedder didn't create a WebContents for this route, we need to
1516 // delete the RenderView that had already been created.
1517 Send(new ViewMsg_Close(route_id
));
1519 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(route_id
);
1520 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(
1521 main_frame_route_id
);
1525 // Create the new web contents. This will automatically create the new
1526 // WebContentsView. In the future, we may want to create the view separately.
1527 CreateParams
create_params(GetBrowserContext(), site_instance
.get());
1528 create_params
.routing_id
= route_id
;
1529 create_params
.main_frame_routing_id
= main_frame_route_id
;
1530 create_params
.opener
= this;
1531 create_params
.opener_suppressed
= params
.opener_suppressed
;
1532 if (params
.disposition
== NEW_BACKGROUND_TAB
)
1533 create_params
.initially_hidden
= true;
1535 WebContentsImpl
* new_contents
= NULL
;
1537 create_params
.context
= view_
->GetNativeView();
1538 create_params
.initial_size
= GetContainerBounds().size();
1539 new_contents
= static_cast<WebContentsImpl
*>(
1540 WebContents::Create(create_params
));
1542 new_contents
= GetBrowserPluginGuest()->CreateNewGuestWindow(create_params
);
1544 new_contents
->GetController().SetSessionStorageNamespace(
1546 session_storage_namespace
);
1547 new_contents
->RenderViewCreated(new_contents
->GetRenderViewHost());
1549 // Save the window for later if we're not suppressing the opener (since it
1550 // will be shown immediately).
1551 if (!params
.opener_suppressed
) {
1553 WebContentsView
* new_view
= new_contents
->view_
.get();
1555 // TODO(brettw): It seems bogus that we have to call this function on the
1556 // newly created object and give it one of its own member variables.
1557 new_view
->CreateViewForWidget(new_contents
->GetRenderViewHost(), false);
1559 // Save the created window associated with the route so we can show it
1561 DCHECK_NE(MSG_ROUTING_NONE
, route_id
);
1562 pending_contents_
[route_id
] = new_contents
;
1563 AddDestructionObserver(new_contents
);
1567 delegate_
->WebContentsCreated(
1568 this, params
.opener_render_frame_id
, params
.frame_name
,
1569 params
.target_url
, new_contents
);
1572 if (params
.opener_suppressed
) {
1573 // When the opener is suppressed, the original renderer cannot access the
1574 // new window. As a result, we need to show and navigate the window here.
1575 bool was_blocked
= false;
1577 gfx::Rect initial_pos
;
1578 delegate_
->AddNewContents(
1579 this, new_contents
, params
.disposition
, initial_pos
,
1580 params
.user_gesture
, &was_blocked
);
1583 OpenURLParams
open_params(params
.target_url
,
1586 ui::PAGE_TRANSITION_LINK
,
1587 true /* is_renderer_initiated */);
1588 open_params
.user_gesture
= params
.user_gesture
;
1589 new_contents
->OpenURL(open_params
);
1594 void WebContentsImpl::CreateNewWidget(int render_process_id
,
1596 blink::WebPopupType popup_type
) {
1597 CreateNewWidget(render_process_id
, route_id
, false, popup_type
);
1600 void WebContentsImpl::CreateNewFullscreenWidget(int render_process_id
,
1602 CreateNewWidget(render_process_id
, route_id
, true, blink::WebPopupTypeNone
);
1605 void WebContentsImpl::CreateNewWidget(int render_process_id
,
1608 blink::WebPopupType popup_type
) {
1609 RenderProcessHost
* process
= GetRenderProcessHost();
1610 // A message to create a new widget can only come from the active process for
1611 // this WebContentsImpl instance. If any other process sends the request,
1612 // it is invalid and the process must be terminated.
1613 if (process
->GetID() != render_process_id
) {
1614 RenderProcessHost
* rph
= RenderProcessHost::FromID(render_process_id
);
1615 base::ProcessHandle process_handle
= rph
->GetHandle();
1616 if (process_handle
!= base::kNullProcessHandle
) {
1618 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWidget"));
1619 rph
->Shutdown(RESULT_CODE_KILLED
, false);
1624 RenderWidgetHostImpl
* widget_host
=
1625 new RenderWidgetHostImpl(this, process
, route_id
, IsHidden());
1626 created_widgets_
.insert(widget_host
);
1628 RenderWidgetHostViewBase
* widget_view
=
1629 static_cast<RenderWidgetHostViewBase
*>(
1630 view_
->CreateViewForPopupWidget(widget_host
));
1633 if (!is_fullscreen
) {
1634 // Popups should not get activated.
1635 widget_view
->SetPopupType(popup_type
);
1637 // Save the created widget associated with the route so we can show it later.
1638 pending_widget_views_
[route_id
] = widget_view
;
1640 #if defined(OS_MACOSX)
1641 // A RenderWidgetHostViewMac has lifetime scoped to the view. We'll retain it
1642 // to allow it to survive the trip without being hosted.
1643 base::mac::NSObjectRetain(widget_view
->GetNativeView());
1647 void WebContentsImpl::ShowCreatedWindow(int route_id
,
1648 WindowOpenDisposition disposition
,
1649 const gfx::Rect
& initial_pos
,
1650 bool user_gesture
) {
1651 WebContentsImpl
* contents
= GetCreatedWindow(route_id
);
1653 WebContentsDelegate
* delegate
= GetDelegate();
1655 delegate
->AddNewContents(
1656 this, contents
, disposition
, initial_pos
, user_gesture
, NULL
);
1661 void WebContentsImpl::ShowCreatedWidget(int route_id
,
1662 const gfx::Rect
& initial_pos
) {
1663 ShowCreatedWidget(route_id
, false, initial_pos
);
1666 void WebContentsImpl::ShowCreatedFullscreenWidget(int route_id
) {
1667 ShowCreatedWidget(route_id
, true, gfx::Rect());
1670 void WebContentsImpl::ShowCreatedWidget(int route_id
,
1672 const gfx::Rect
& initial_pos
) {
1673 RenderWidgetHostViewBase
* widget_host_view
=
1674 static_cast<RenderWidgetHostViewBase
*>(GetCreatedWidget(route_id
));
1675 if (!widget_host_view
)
1678 RenderWidgetHostView
* view
= NULL
;
1679 BrowserPluginGuest
* guest
= GetBrowserPluginGuest();
1680 if (guest
&& guest
->embedder_web_contents()) {
1681 view
= guest
->embedder_web_contents()->GetRenderWidgetHostView();
1683 view
= GetRenderWidgetHostView();
1686 if (is_fullscreen
) {
1687 DCHECK_EQ(MSG_ROUTING_NONE
, fullscreen_widget_routing_id_
);
1688 view_
->StoreFocus();
1689 fullscreen_widget_routing_id_
= route_id
;
1690 if (delegate_
&& delegate_
->EmbedsFullscreenWidget()) {
1691 widget_host_view
->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
1692 delegate_
->ToggleFullscreenModeForTab(this, true);
1694 widget_host_view
->InitAsFullscreen(view
);
1696 FOR_EACH_OBSERVER(WebContentsObserver
,
1698 DidShowFullscreenWidget(route_id
));
1699 if (!widget_host_view
->HasFocus())
1700 widget_host_view
->Focus();
1702 widget_host_view
->InitAsPopup(view
, initial_pos
);
1705 RenderWidgetHostImpl
* render_widget_host_impl
=
1706 RenderWidgetHostImpl::From(widget_host_view
->GetRenderWidgetHost());
1707 render_widget_host_impl
->Init();
1708 // Only allow privileged mouse lock for fullscreen render widget, which is
1709 // used to implement Pepper Flash fullscreen.
1710 render_widget_host_impl
->set_allow_privileged_mouse_lock(is_fullscreen
);
1712 #if defined(OS_MACOSX)
1713 // A RenderWidgetHostViewMac has lifetime scoped to the view. Now that it's
1714 // properly embedded (or purposefully ignored) we can release the retain we
1715 // took in CreateNewWidget().
1716 base::mac::NSObjectRelease(widget_host_view
->GetNativeView());
1720 WebContentsImpl
* WebContentsImpl::GetCreatedWindow(int route_id
) {
1721 PendingContents::iterator iter
= pending_contents_
.find(route_id
);
1723 // Certain systems can block the creation of new windows. If we didn't succeed
1724 // in creating one, just return NULL.
1725 if (iter
== pending_contents_
.end()) {
1729 WebContentsImpl
* new_contents
= iter
->second
;
1730 pending_contents_
.erase(route_id
);
1731 RemoveDestructionObserver(new_contents
);
1733 // Don't initialize the guest WebContents immediately.
1734 if (BrowserPluginGuest::IsGuest(new_contents
))
1735 return new_contents
;
1737 if (!new_contents
->GetRenderProcessHost()->HasConnection() ||
1738 !new_contents
->GetRenderViewHost()->GetView())
1741 // Resume blocked requests for both the RenderViewHost and RenderFrameHost.
1742 // TODO(brettw): It seems bogus to reach into here and initialize the host.
1743 static_cast<RenderViewHostImpl
*>(new_contents
->GetRenderViewHost())->Init();
1744 static_cast<RenderFrameHostImpl
*>(new_contents
->GetMainFrame())->Init();
1746 return new_contents
;
1749 RenderWidgetHostView
* WebContentsImpl::GetCreatedWidget(int route_id
) {
1750 PendingWidgetViews::iterator iter
= pending_widget_views_
.find(route_id
);
1751 if (iter
== pending_widget_views_
.end()) {
1756 RenderWidgetHostView
* widget_host_view
= iter
->second
;
1757 pending_widget_views_
.erase(route_id
);
1759 RenderWidgetHost
* widget_host
= widget_host_view
->GetRenderWidgetHost();
1760 if (!widget_host
->GetProcess()->HasConnection()) {
1761 // The view has gone away or the renderer crashed. Nothing to do.
1765 return widget_host_view
;
1768 void WebContentsImpl::RequestMediaAccessPermission(
1769 const MediaStreamRequest
& request
,
1770 const MediaResponseCallback
& callback
) {
1772 delegate_
->RequestMediaAccessPermission(this, request
, callback
);
1774 callback
.Run(MediaStreamDevices(),
1775 MEDIA_DEVICE_FAILED_DUE_TO_SHUTDOWN
,
1776 scoped_ptr
<MediaStreamUI
>());
1780 bool WebContentsImpl::CheckMediaAccessPermission(const GURL
& security_origin
,
1781 MediaStreamType type
) {
1782 DCHECK(type
== MEDIA_DEVICE_AUDIO_CAPTURE
||
1783 type
== MEDIA_DEVICE_VIDEO_CAPTURE
);
1785 delegate_
->CheckMediaAccessPermission(this, security_origin
, type
);
1788 SessionStorageNamespace
* WebContentsImpl::GetSessionStorageNamespace(
1789 SiteInstance
* instance
) {
1790 return controller_
.GetSessionStorageNamespace(instance
);
1793 SessionStorageNamespaceMap
WebContentsImpl::GetSessionStorageNamespaceMap() {
1794 return controller_
.GetSessionStorageNamespaceMap();
1797 FrameTree
* WebContentsImpl::GetFrameTree() {
1798 return &frame_tree_
;
1801 void WebContentsImpl::SetIsVirtualKeyboardRequested(bool requested
) {
1802 virtual_keyboard_requested_
= requested
;
1805 bool WebContentsImpl::IsVirtualKeyboardRequested() {
1806 return virtual_keyboard_requested_
;
1809 AccessibilityMode
WebContentsImpl::GetAccessibilityMode() const {
1810 return accessibility_mode_
;
1813 void WebContentsImpl::AccessibilityEventReceived(
1814 const std::vector
<AXEventNotificationDetails
>& details
) {
1816 WebContentsObserver
, observers_
, AccessibilityEventReceived(details
));
1819 RenderFrameHost
* WebContentsImpl::GetGuestByInstanceID(
1820 int browser_plugin_instance_id
) {
1821 BrowserPluginGuestManager
* guest_manager
=
1822 GetBrowserContext()->GetGuestManager();
1823 WebContents
* guest
= guest_manager
->GetGuestByInstanceID(
1824 this, browser_plugin_instance_id
);
1827 return guest
->GetMainFrame();
1830 GeolocationServiceContext
* WebContentsImpl::GetGeolocationServiceContext() {
1831 return geolocation_service_context_
.get();
1834 void WebContentsImpl::OnShowValidationMessage(
1835 const gfx::Rect
& anchor_in_root_view
,
1836 const base::string16
& main_text
,
1837 const base::string16
& sub_text
) {
1839 delegate_
->ShowValidationMessage(
1840 this, anchor_in_root_view
, main_text
, sub_text
);
1843 void WebContentsImpl::OnHideValidationMessage() {
1845 delegate_
->HideValidationMessage(this);
1848 void WebContentsImpl::OnMoveValidationMessage(
1849 const gfx::Rect
& anchor_in_root_view
) {
1851 delegate_
->MoveValidationMessage(this, anchor_in_root_view
);
1854 void WebContentsImpl::DidSendScreenRects(RenderWidgetHostImpl
* rwh
) {
1855 if (browser_plugin_embedder_
)
1856 browser_plugin_embedder_
->DidSendScreenRects();
1859 BrowserAccessibilityManager
*
1860 WebContentsImpl::GetRootBrowserAccessibilityManager() {
1861 RenderFrameHostImpl
* rfh
= static_cast<RenderFrameHostImpl
*>(GetMainFrame());
1862 return rfh
? rfh
->browser_accessibility_manager() : NULL
;
1865 BrowserAccessibilityManager
*
1866 WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
1867 RenderFrameHostImpl
* rfh
= static_cast<RenderFrameHostImpl
*>(GetMainFrame());
1868 return rfh
? rfh
->GetOrCreateBrowserAccessibilityManager() : NULL
;
1871 void WebContentsImpl::UpdatePreferredSize(const gfx::Size
& pref_size
) {
1872 const gfx::Size old_size
= GetPreferredSize();
1873 preferred_size_
= pref_size
;
1874 OnPreferredSizeChanged(old_size
);
1877 void WebContentsImpl::ResizeDueToAutoResize(const gfx::Size
& new_size
) {
1879 delegate_
->ResizeDueToAutoResize(this, new_size
);
1882 WebContents
* WebContentsImpl::OpenURL(const OpenURLParams
& params
) {
1886 WebContents
* new_contents
= delegate_
->OpenURLFromTab(this, params
);
1887 return new_contents
;
1890 bool WebContentsImpl::Send(IPC::Message
* message
) {
1891 if (!GetRenderViewHost()) {
1896 return GetRenderViewHost()->Send(message
);
1899 bool WebContentsImpl::NavigateToPendingEntry(
1900 NavigationController::ReloadType reload_type
) {
1901 FrameTreeNode
* node
= frame_tree_
.root();
1903 // Navigate in the FrameTreeNode specified in the pending entry, if any. This
1904 // is currently only used in --site-per-process and tests.
1905 NavigationEntryImpl
* pending_entry
=
1906 NavigationEntryImpl::FromNavigationEntry(controller_
.GetPendingEntry());
1907 if (pending_entry
->frame_tree_node_id() != -1) {
1908 FrameTreeNode
* subframe
=
1909 frame_tree_
.FindByID(pending_entry
->frame_tree_node_id());
1915 return node
->navigator()->NavigateToPendingEntry(
1916 node
->current_frame_host(), reload_type
);
1919 void WebContentsImpl::RenderFrameForInterstitialPageCreated(
1920 RenderFrameHost
* render_frame_host
) {
1921 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1922 RenderFrameForInterstitialPageCreated(render_frame_host
));
1925 void WebContentsImpl::AttachInterstitialPage(
1926 InterstitialPageImpl
* interstitial_page
) {
1927 DCHECK(interstitial_page
);
1928 GetRenderManager()->set_interstitial_page(interstitial_page
);
1930 // Cancel any visible dialogs so that they don't interfere with the
1932 if (dialog_manager_
)
1933 dialog_manager_
->CancelActiveAndPendingDialogs(this);
1935 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1936 DidAttachInterstitialPage());
1939 void WebContentsImpl::DetachInterstitialPage() {
1940 if (ShowingInterstitialPage())
1941 GetRenderManager()->remove_interstitial_page();
1942 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1943 DidDetachInterstitialPage());
1946 void WebContentsImpl::SetHistoryOffsetAndLength(int history_offset
,
1947 int history_length
) {
1948 SetHistoryOffsetAndLengthForView(
1949 GetRenderViewHost(), history_offset
, history_length
);
1952 void WebContentsImpl::SetHistoryOffsetAndLengthForView(
1953 RenderViewHost
* render_view_host
,
1955 int history_length
) {
1956 render_view_host
->Send(new ViewMsg_SetHistoryOffsetAndLength(
1957 render_view_host
->GetRoutingID(), history_offset
, history_length
));
1960 void WebContentsImpl::ReloadFocusedFrame(bool ignore_cache
) {
1961 RenderFrameHost
* focused_frame
= GetFocusedFrame();
1965 focused_frame
->Send(new FrameMsg_Reload(
1966 focused_frame
->GetRoutingID(), ignore_cache
));
1969 void WebContentsImpl::Undo() {
1970 RenderFrameHost
* focused_frame
= GetFocusedFrame();
1974 focused_frame
->Send(new InputMsg_Undo(focused_frame
->GetRoutingID()));
1975 RecordAction(base::UserMetricsAction("Undo"));
1978 void WebContentsImpl::Redo() {
1979 RenderFrameHost
* focused_frame
= GetFocusedFrame();
1982 focused_frame
->Send(new InputMsg_Redo(focused_frame
->GetRoutingID()));
1983 RecordAction(base::UserMetricsAction("Redo"));
1986 void WebContentsImpl::Cut() {
1987 RenderFrameHost
* focused_frame
= GetFocusedFrame();
1991 focused_frame
->Send(new InputMsg_Cut(focused_frame
->GetRoutingID()));
1992 RecordAction(base::UserMetricsAction("Cut"));
1995 void WebContentsImpl::Copy() {
1996 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2000 focused_frame
->Send(new InputMsg_Copy(focused_frame
->GetRoutingID()));
2001 RecordAction(base::UserMetricsAction("Copy"));
2004 void WebContentsImpl::CopyToFindPboard() {
2005 #if defined(OS_MACOSX)
2006 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2010 // Windows/Linux don't have the concept of a find pasteboard.
2011 focused_frame
->Send(
2012 new InputMsg_CopyToFindPboard(focused_frame
->GetRoutingID()));
2013 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
2017 void WebContentsImpl::Paste() {
2018 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2022 focused_frame
->Send(new InputMsg_Paste(focused_frame
->GetRoutingID()));
2023 RecordAction(base::UserMetricsAction("Paste"));
2026 void WebContentsImpl::PasteAndMatchStyle() {
2027 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2031 focused_frame
->Send(new InputMsg_PasteAndMatchStyle(
2032 focused_frame
->GetRoutingID()));
2033 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
2036 void WebContentsImpl::Delete() {
2037 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2041 focused_frame
->Send(new InputMsg_Delete(focused_frame
->GetRoutingID()));
2042 RecordAction(base::UserMetricsAction("DeleteSelection"));
2045 void WebContentsImpl::SelectAll() {
2046 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2050 focused_frame
->Send(new InputMsg_SelectAll(focused_frame
->GetRoutingID()));
2051 RecordAction(base::UserMetricsAction("SelectAll"));
2054 void WebContentsImpl::Unselect() {
2055 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2059 focused_frame
->Send(new InputMsg_Unselect(focused_frame
->GetRoutingID()));
2060 RecordAction(base::UserMetricsAction("Unselect"));
2063 void WebContentsImpl::Replace(const base::string16
& word
) {
2064 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2068 focused_frame
->Send(new InputMsg_Replace(
2069 focused_frame
->GetRoutingID(), word
));
2072 void WebContentsImpl::ReplaceMisspelling(const base::string16
& word
) {
2073 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2077 focused_frame
->Send(new InputMsg_ReplaceMisspelling(
2078 focused_frame
->GetRoutingID(), word
));
2081 void WebContentsImpl::NotifyContextMenuClosed(
2082 const CustomContextMenuContext
& context
) {
2083 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2087 focused_frame
->Send(new FrameMsg_ContextMenuClosed(
2088 focused_frame
->GetRoutingID(), context
));
2091 void WebContentsImpl::ExecuteCustomContextMenuCommand(
2092 int action
, const CustomContextMenuContext
& context
) {
2093 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2097 focused_frame
->Send(new FrameMsg_CustomContextMenuAction(
2098 focused_frame
->GetRoutingID(), context
, action
));
2101 gfx::NativeView
WebContentsImpl::GetNativeView() {
2102 return view_
->GetNativeView();
2105 gfx::NativeView
WebContentsImpl::GetContentNativeView() {
2106 return view_
->GetContentNativeView();
2109 gfx::NativeWindow
WebContentsImpl::GetTopLevelNativeWindow() {
2110 return view_
->GetTopLevelNativeWindow();
2113 gfx::Rect
WebContentsImpl::GetViewBounds() {
2114 return view_
->GetViewBounds();
2117 gfx::Rect
WebContentsImpl::GetContainerBounds() {
2119 view_
->GetContainerBounds(&rv
);
2123 DropData
* WebContentsImpl::GetDropData() {
2124 return view_
->GetDropData();
2127 void WebContentsImpl::Focus() {
2131 void WebContentsImpl::SetInitialFocus() {
2132 view_
->SetInitialFocus();
2135 void WebContentsImpl::StoreFocus() {
2136 view_
->StoreFocus();
2139 void WebContentsImpl::RestoreFocus() {
2140 view_
->RestoreFocus();
2143 void WebContentsImpl::FocusThroughTabTraversal(bool reverse
) {
2144 if (ShowingInterstitialPage()) {
2145 GetRenderManager()->interstitial_page()->FocusThroughTabTraversal(reverse
);
2148 RenderWidgetHostView
* const fullscreen_view
=
2149 GetFullscreenRenderWidgetHostView();
2150 if (fullscreen_view
) {
2151 fullscreen_view
->Focus();
2154 GetRenderViewHostImpl()->SetInitialFocus(reverse
);
2157 bool WebContentsImpl::ShowingInterstitialPage() const {
2158 return GetRenderManager()->interstitial_page() != NULL
;
2161 InterstitialPage
* WebContentsImpl::GetInterstitialPage() const {
2162 return GetRenderManager()->interstitial_page();
2165 bool WebContentsImpl::IsSavable() {
2166 // WebKit creates Document object when MIME type is application/xhtml+xml,
2167 // so we also support this MIME type.
2168 return contents_mime_type_
== "text/html" ||
2169 contents_mime_type_
== "text/xml" ||
2170 contents_mime_type_
== "application/xhtml+xml" ||
2171 contents_mime_type_
== "text/plain" ||
2172 contents_mime_type_
== "text/css" ||
2173 net::IsSupportedJavascriptMimeType(contents_mime_type_
.c_str());
2176 void WebContentsImpl::OnSavePage() {
2177 // If we can not save the page, try to download it.
2179 RecordDownloadSource(INITIATED_BY_SAVE_PACKAGE_ON_NON_HTML
);
2180 SaveFrame(GetURL(), Referrer());
2186 // Create the save package and possibly prompt the user for the name to save
2187 // the page as. The user prompt is an asynchronous operation that runs on
2189 save_package_
= new SavePackage(this);
2190 save_package_
->GetSaveInfo();
2193 // Used in automated testing to bypass prompting the user for file names.
2194 // Instead, the names and paths are hard coded rather than running them through
2195 // file name sanitation and extension / mime checking.
2196 bool WebContentsImpl::SavePage(const base::FilePath
& main_file
,
2197 const base::FilePath
& dir_path
,
2198 SavePageType save_type
) {
2199 // Stop the page from navigating.
2202 save_package_
= new SavePackage(this, save_type
, main_file
, dir_path
);
2203 return save_package_
->Init(SavePackageDownloadCreatedCallback());
2206 void WebContentsImpl::SaveFrame(const GURL
& url
,
2207 const Referrer
& referrer
) {
2208 if (!GetURL().is_valid())
2210 if (delegate_
&& delegate_
->SaveFrame(url
, referrer
))
2213 bool is_main_frame
= (url
== GetURL());
2215 DownloadManager
* dlm
=
2216 BrowserContext::GetDownloadManager(GetBrowserContext());
2220 if (is_main_frame
) {
2221 const NavigationEntry
* entry
= controller_
.GetLastCommittedEntry();
2223 post_id
= entry
->GetPostID();
2225 scoped_ptr
<DownloadUrlParameters
> params(
2226 DownloadUrlParameters::FromWebContents(this, url
));
2227 params
->set_referrer(referrer
);
2228 params
->set_post_id(post_id
);
2229 params
->set_prefer_cache(true);
2231 params
->set_method("POST");
2232 params
->set_prompt(true);
2233 dlm
->DownloadUrl(params
.Pass());
2236 void WebContentsImpl::GenerateMHTML(
2237 const base::FilePath
& file
,
2238 const base::Callback
<void(int64
)>& callback
) {
2239 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, file
, callback
);
2242 const std::string
& WebContentsImpl::GetContentsMimeType() const {
2243 return contents_mime_type_
;
2246 bool WebContentsImpl::WillNotifyDisconnection() const {
2247 return notify_disconnection_
;
2250 void WebContentsImpl::SetOverrideEncoding(const std::string
& encoding
) {
2251 SetEncoding(encoding
);
2252 Send(new ViewMsg_SetPageEncoding(GetRoutingID(), encoding
));
2255 void WebContentsImpl::ResetOverrideEncoding() {
2256 canonical_encoding_
.clear();
2257 Send(new ViewMsg_ResetPageEncodingToDefault(GetRoutingID()));
2260 RendererPreferences
* WebContentsImpl::GetMutableRendererPrefs() {
2261 return &renderer_preferences_
;
2264 void WebContentsImpl::Close() {
2265 Close(GetRenderViewHost());
2268 void WebContentsImpl::DragSourceEndedAt(int client_x
, int client_y
,
2269 int screen_x
, int screen_y
, blink::WebDragOperation operation
) {
2270 if (browser_plugin_embedder_
.get())
2271 browser_plugin_embedder_
->DragSourceEndedAt(client_x
, client_y
,
2272 screen_x
, screen_y
, operation
);
2273 if (GetRenderViewHost())
2274 GetRenderViewHostImpl()->DragSourceEndedAt(client_x
, client_y
,
2275 screen_x
, screen_y
, operation
);
2278 void WebContentsImpl::DidGetResourceResponseStart(
2279 const ResourceRequestDetails
& details
) {
2280 controller_
.ssl_manager()->DidStartResourceResponse(details
);
2282 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2283 DidGetResourceResponseStart(details
));
2285 // TODO(avi): Remove. http://crbug.com/170921
2286 NotificationService::current()->Notify(
2287 NOTIFICATION_RESOURCE_RESPONSE_STARTED
,
2288 Source
<WebContents
>(this),
2289 Details
<const ResourceRequestDetails
>(&details
));
2292 void WebContentsImpl::DidGetRedirectForResourceRequest(
2293 RenderFrameHost
* render_frame_host
,
2294 const ResourceRedirectDetails
& details
) {
2295 controller_
.ssl_manager()->DidReceiveResourceRedirect(details
);
2298 WebContentsObserver
,
2300 DidGetRedirectForResourceRequest(render_frame_host
, details
));
2302 // TODO(avi): Remove. http://crbug.com/170921
2303 NotificationService::current()->Notify(
2304 NOTIFICATION_RESOURCE_RECEIVED_REDIRECT
,
2305 Source
<WebContents
>(this),
2306 Details
<const ResourceRedirectDetails
>(&details
));
2309 void WebContentsImpl::SystemDragEnded() {
2310 if (GetRenderViewHost())
2311 GetRenderViewHostImpl()->DragSourceSystemDragEnded();
2313 delegate_
->DragEnded();
2314 if (browser_plugin_embedder_
.get())
2315 browser_plugin_embedder_
->SystemDragEnded();
2318 void WebContentsImpl::UserGestureDone() {
2322 void WebContentsImpl::SetClosedByUserGesture(bool value
) {
2323 closed_by_user_gesture_
= value
;
2326 bool WebContentsImpl::GetClosedByUserGesture() const {
2327 return closed_by_user_gesture_
;
2330 void WebContentsImpl::ViewSource() {
2334 NavigationEntry
* entry
= GetController().GetLastCommittedEntry();
2338 delegate_
->ViewSourceForTab(this, entry
->GetURL());
2341 void WebContentsImpl::ViewFrameSource(const GURL
& url
,
2342 const PageState
& page_state
) {
2346 delegate_
->ViewSourceForFrame(this, url
, page_state
);
2349 int WebContentsImpl::GetMinimumZoomPercent() const {
2350 return minimum_zoom_percent_
;
2353 int WebContentsImpl::GetMaximumZoomPercent() const {
2354 return maximum_zoom_percent_
;
2357 gfx::Size
WebContentsImpl::GetPreferredSize() const {
2358 return capturer_count_
== 0 ? preferred_size_
: preferred_size_for_capture_
;
2361 bool WebContentsImpl::GotResponseToLockMouseRequest(bool allowed
) {
2362 if (GetBrowserPluginGuest())
2363 return GetBrowserPluginGuest()->LockMouse(allowed
);
2365 return GetRenderViewHost() ?
2366 GetRenderViewHostImpl()->GotResponseToLockMouseRequest(allowed
) : false;
2369 bool WebContentsImpl::HasOpener() const {
2370 return opener_
!= NULL
;
2373 void WebContentsImpl::DidChooseColorInColorChooser(SkColor color
) {
2374 if (!color_chooser_info_
.get())
2376 RenderFrameHost
* rfh
= RenderFrameHost::FromID(
2377 color_chooser_info_
->render_process_id
,
2378 color_chooser_info_
->render_frame_id
);
2382 rfh
->Send(new FrameMsg_DidChooseColorResponse(
2383 rfh
->GetRoutingID(), color_chooser_info_
->identifier
, color
));
2386 void WebContentsImpl::DidEndColorChooser() {
2387 if (!color_chooser_info_
.get())
2389 RenderFrameHost
* rfh
= RenderFrameHost::FromID(
2390 color_chooser_info_
->render_process_id
,
2391 color_chooser_info_
->render_frame_id
);
2395 rfh
->Send(new FrameMsg_DidEndColorChooser(
2396 rfh
->GetRoutingID(), color_chooser_info_
->identifier
));
2397 color_chooser_info_
.reset();
2400 int WebContentsImpl::DownloadImage(const GURL
& url
,
2402 uint32_t max_bitmap_size
,
2403 const ImageDownloadCallback
& callback
) {
2404 int id
= StartDownload(GetMainFrame(), url
, is_favicon
, max_bitmap_size
);
2405 image_download_map_
[id
] = callback
;
2409 bool WebContentsImpl::IsSubframe() const {
2410 return is_subframe_
;
2413 void WebContentsImpl::Find(int request_id
,
2414 const base::string16
& search_text
,
2415 const blink::WebFindOptions
& options
) {
2416 // See if a top level browser plugin handles the find request first.
2417 if (browser_plugin_embedder_
&&
2418 browser_plugin_embedder_
->Find(request_id
, search_text
, options
)) {
2421 Send(new ViewMsg_Find(GetRoutingID(), request_id
, search_text
, options
));
2424 void WebContentsImpl::StopFinding(StopFindAction action
) {
2425 Send(new ViewMsg_StopFinding(GetRoutingID(), action
));
2428 void WebContentsImpl::InsertCSS(const std::string
& css
) {
2429 GetMainFrame()->Send(new FrameMsg_CSSInsertRequest(
2430 GetMainFrame()->GetRoutingID(), css
));
2433 bool WebContentsImpl::WasRecentlyAudible() {
2434 return audio_stream_monitor_
.WasRecentlyAudible();
2437 void WebContentsImpl::GetManifest(const GetManifestCallback
& callback
) {
2438 manifest_manager_host_
->GetManifest(GetMainFrame(), callback
);
2441 bool WebContentsImpl::FocusLocationBarByDefault() {
2442 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
2443 if (entry
&& entry
->GetURL() == GURL(url::kAboutBlankURL
))
2445 return delegate_
&& delegate_
->ShouldFocusLocationBarByDefault(this);
2448 void WebContentsImpl::SetFocusToLocationBar(bool select_all
) {
2450 delegate_
->SetFocusToLocationBar(select_all
);
2453 void WebContentsImpl::DidStartProvisionalLoad(
2454 RenderFrameHostImpl
* render_frame_host
,
2455 const GURL
& validated_url
,
2457 bool is_iframe_srcdoc
) {
2458 // Notify observers about the start of the provisional load.
2460 WebContentsObserver
,
2462 DidStartProvisionalLoadForFrame(
2463 render_frame_host
, validated_url
, is_error_page
, is_iframe_srcdoc
));
2466 void WebContentsImpl::DidStartNavigationTransition(
2467 RenderFrameHostImpl
* render_frame_host
) {
2468 #if defined(OS_ANDROID)
2469 int render_frame_id
= render_frame_host
->GetRoutingID();
2470 GetWebContentsAndroid()->DidStartNavigationTransitionForFrame(
2475 void WebContentsImpl::DidFailProvisionalLoadWithError(
2476 RenderFrameHostImpl
* render_frame_host
,
2477 const FrameHostMsg_DidFailProvisionalLoadWithError_Params
& params
) {
2478 GURL
validated_url(params
.url
);
2479 FOR_EACH_OBSERVER(WebContentsObserver
,
2481 DidFailProvisionalLoad(render_frame_host
,
2484 params
.error_description
));
2487 void WebContentsImpl::DidFailLoadWithError(
2488 RenderFrameHostImpl
* render_frame_host
,
2491 const base::string16
& error_description
) {
2493 WebContentsObserver
,
2495 DidFailLoad(render_frame_host
, url
, error_code
, error_description
));
2498 void WebContentsImpl::NotifyChangedNavigationState(
2499 InvalidateTypes changed_flags
) {
2500 NotifyNavigationStateChanged(changed_flags
);
2503 void WebContentsImpl::AboutToNavigateRenderFrame(
2504 RenderFrameHostImpl
* render_frame_host
) {
2505 // Notify observers that we will navigate in this RenderFrame.
2507 WebContentsObserver
,
2509 AboutToNavigateRenderFrame(render_frame_host
));
2512 void WebContentsImpl::DidStartNavigationToPendingEntry(
2513 RenderFrameHostImpl
* render_frame_host
,
2515 NavigationController::ReloadType reload_type
) {
2516 // Notify observers about navigation.
2518 WebContentsObserver
,
2520 DidStartNavigationToPendingEntry(url
, reload_type
));
2523 void WebContentsImpl::RequestOpenURL(RenderFrameHostImpl
* render_frame_host
,
2524 const OpenURLParams
& params
) {
2525 WebContents
* new_contents
= OpenURL(params
);
2528 // Notify observers.
2529 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2530 DidOpenRequestedURL(new_contents
,
2535 params
.transition
));
2539 bool WebContentsImpl::ShouldPreserveAbortedURLs() {
2542 return delegate_
->ShouldPreserveAbortedURLs(this);
2545 void WebContentsImpl::DidCommitProvisionalLoad(
2546 RenderFrameHostImpl
* render_frame_host
,
2548 ui::PageTransition transition_type
) {
2549 // Notify observers about the commit of the provisional load.
2550 FOR_EACH_OBSERVER(WebContentsObserver
,
2552 DidCommitProvisionalLoadForFrame(
2553 render_frame_host
, url
, transition_type
));
2556 void WebContentsImpl::DidNavigateMainFramePreCommit(
2557 bool navigation_is_within_page
) {
2558 // Ensure fullscreen mode is exited before committing the navigation to a
2559 // different page. The next page will not start out assuming it is in
2561 if (navigation_is_within_page
) {
2562 // No page change? Then, the renderer and browser can remain in fullscreen.
2565 if (IsFullscreenForCurrentTab())
2566 GetRenderViewHost()->ExitFullscreen();
2567 DCHECK(!IsFullscreenForCurrentTab());
2570 void WebContentsImpl::DidNavigateMainFramePostCommit(
2571 const LoadCommittedDetails
& details
,
2572 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) {
2573 if (details
.is_navigation_to_different_page()) {
2574 // Clear the status bubble. This is a workaround for a bug where WebKit
2575 // doesn't let us know that the cursor left an element during a
2576 // transition (this is also why the mouse cursor remains as a hand after
2577 // clicking on a link); see bugs 1184641 and 980803. We don't want to
2578 // clear the bubble when a user navigates to a named anchor in the same
2580 UpdateTargetURL(GURL());
2583 if (!details
.is_in_page
) {
2584 // Once the main frame is navigated, we're no longer considered to have
2585 // displayed insecure content.
2586 displayed_insecure_content_
= false;
2587 SSLManager::NotifySSLInternalStateChanged(
2588 GetController().GetBrowserContext());
2591 // Notify observers about navigation.
2592 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2593 DidNavigateMainFrame(details
, params
));
2596 delegate_
->DidNavigateMainFramePostCommit(this);
2597 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
2600 void WebContentsImpl::DidNavigateAnyFramePostCommit(
2601 RenderFrameHostImpl
* render_frame_host
,
2602 const LoadCommittedDetails
& details
,
2603 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) {
2604 // Now that something has committed, we don't need to track whether the
2605 // initial page has been accessed.
2606 has_accessed_initial_document_
= false;
2608 // If we navigate off the page, close all JavaScript dialogs.
2609 if (dialog_manager_
&& !details
.is_in_page
)
2610 dialog_manager_
->CancelActiveAndPendingDialogs(this);
2612 // Notify observers about navigation.
2613 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2614 DidNavigateAnyFrame(render_frame_host
, details
, params
));
2617 void WebContentsImpl::SetMainFrameMimeType(const std::string
& mime_type
) {
2618 contents_mime_type_
= mime_type
;
2621 bool WebContentsImpl::CanOverscrollContent() const {
2622 // Disable overscroll when touch emulation is on. See crbug.com/369938.
2623 if (force_disable_overscroll_content_
)
2627 return delegate_
->CanOverscrollContent();
2632 void WebContentsImpl::OnThemeColorChanged(SkColor theme_color
) {
2633 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2634 DidChangeThemeColor(theme_color
));
2637 void WebContentsImpl::OnDidLoadResourceFromMemoryCache(
2639 const std::string
& security_info
,
2640 const std::string
& http_method
,
2641 const std::string
& mime_type
,
2642 ResourceType resource_type
) {
2643 base::StatsCounter
cache("WebKit.CacheHit");
2646 // Send out a notification that we loaded a resource from our memory cache.
2648 net::CertStatus cert_status
= 0;
2649 int security_bits
= -1;
2650 int connection_status
= 0;
2651 SignedCertificateTimestampIDStatusList signed_certificate_timestamp_ids
;
2652 DeserializeSecurityInfo(security_info
, &cert_id
, &cert_status
,
2653 &security_bits
, &connection_status
,
2654 &signed_certificate_timestamp_ids
);
2655 // TODO(alcutter,eranm): Pass signed_certificate_timestamp_ids into details
2656 LoadFromMemoryCacheDetails
details(
2657 url
, GetRenderProcessHost()->GetID(), cert_id
, cert_status
, http_method
,
2658 mime_type
, resource_type
);
2660 controller_
.ssl_manager()->DidLoadFromMemoryCache(details
);
2662 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2663 DidLoadResourceFromMemoryCache(details
));
2665 if (url
.is_valid() && url
.SchemeIsHTTPOrHTTPS()) {
2666 scoped_refptr
<net::URLRequestContextGetter
> request_context(
2667 resource_type
== RESOURCE_TYPE_MEDIA
?
2668 GetBrowserContext()->GetMediaRequestContextForRenderProcess(
2669 GetRenderProcessHost()->GetID()) :
2670 GetBrowserContext()->GetRequestContextForRenderProcess(
2671 GetRenderProcessHost()->GetID()));
2672 BrowserThread::PostTask(
2675 base::Bind(&NotifyCacheOnIO
, request_context
, url
, http_method
));
2679 void WebContentsImpl::OnDidDisplayInsecureContent() {
2680 RecordAction(base::UserMetricsAction("SSL.DisplayedInsecureContent"));
2681 displayed_insecure_content_
= true;
2682 SSLManager::NotifySSLInternalStateChanged(
2683 GetController().GetBrowserContext());
2686 void WebContentsImpl::OnDidRunInsecureContent(
2687 const std::string
& security_origin
, const GURL
& target_url
) {
2688 LOG(WARNING
) << security_origin
<< " ran insecure content from "
2689 << target_url
.possibly_invalid_spec();
2690 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
2691 if (EndsWith(security_origin
, kDotGoogleDotCom
, false))
2692 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
2693 controller_
.ssl_manager()->DidRunInsecureContent(security_origin
);
2694 displayed_insecure_content_
= true;
2695 SSLManager::NotifySSLInternalStateChanged(
2696 GetController().GetBrowserContext());
2699 void WebContentsImpl::OnDocumentLoadedInFrame() {
2700 CHECK(render_frame_message_source_
);
2701 CHECK(!render_view_message_source_
);
2702 RenderFrameHostImpl
* rfh
=
2703 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2705 WebContentsObserver
, observers_
, DocumentLoadedInFrame(rfh
));
2708 void WebContentsImpl::OnDidFinishLoad(
2710 if (!render_frame_message_source_
) {
2711 RecordAction(base::UserMetricsAction("BadMessageTerminate_RVD2"));
2712 GetRenderProcessHost()->ReceivedBadMessage();
2716 GURL
validated_url(url
);
2717 RenderProcessHost
* render_process_host
=
2718 render_frame_message_source_
->GetProcess();
2719 render_process_host
->FilterURL(false, &validated_url
);
2721 RenderFrameHostImpl
* rfh
=
2722 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2724 WebContentsObserver
, observers_
, DidFinishLoad(rfh
, validated_url
));
2727 void WebContentsImpl::OnDidStartLoading(bool to_different_document
) {
2728 RenderFrameHostImpl
* rfh
=
2729 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2730 int64 render_frame_id
= rfh
->frame_tree_node()->frame_tree_node_id();
2732 // It is possible to get multiple calls to OnDidStartLoading that don't have
2733 // corresponding calls to OnDidStopLoading:
2734 // - With "swappedout://" URLs, this happens when a RenderView gets swapped
2735 // out for a cross-process navigation, and it turns into a placeholder for
2736 // one being rendered in a different process.
2737 // - Also, there might be more than one RenderFrameHost sharing the same
2738 // FrameTreeNode (and thus sharing its ID) each sending a start.
2739 // - But in the future, once clamy@ moves navigation network requests to the
2740 // browser process, there's a good chance that callbacks about starting and
2741 // stopping will all be handled by the browser. When that happens, there
2742 // should no longer be a start/stop call imbalance. TODO(avi): When this
2743 // future arrives, update this code to not allow this case.
2744 DCHECK_GE(loading_frames_in_progress_
, 0);
2745 if (loading_progresses_
.find(render_frame_id
) == loading_progresses_
.end()) {
2746 if (loading_frames_in_progress_
== 0)
2747 DidStartLoading(rfh
, to_different_document
);
2748 ++loading_frames_in_progress_
;
2751 loading_progresses_
[render_frame_id
] = kMinimumLoadingProgress
;
2752 SendLoadProgressChanged();
2755 void WebContentsImpl::OnDidStopLoading() {
2756 RenderFrameHostImpl
* rfh
=
2757 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2758 int64 render_frame_id
= rfh
->frame_tree_node()->frame_tree_node_id();
2760 if (loading_progresses_
.find(render_frame_id
) != loading_progresses_
.end()) {
2761 // Load stopped while we were still tracking load. Make sure we update
2762 // progress based on this frame's completion.
2763 loading_progresses_
[render_frame_id
] = 1.0;
2764 SendLoadProgressChanged();
2765 // Then we clean-up our states.
2766 if (loading_total_progress_
== 1.0)
2767 ResetLoadProgressState();
2770 // TODO(japhet): This should be a DCHECK, but the pdf plugin sometimes
2771 // calls DidStopLoading() without a matching DidStartLoading().
2772 if (loading_frames_in_progress_
== 0)
2774 --loading_frames_in_progress_
;
2775 if (loading_frames_in_progress_
== 0)
2776 DidStopLoading(rfh
);
2779 void WebContentsImpl::OnDidChangeLoadProgress(double load_progress
) {
2780 RenderFrameHostImpl
* rfh
=
2781 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2782 int64 render_frame_id
= rfh
->frame_tree_node()->frame_tree_node_id();
2784 loading_progresses_
[render_frame_id
] = load_progress
;
2786 // We notify progress change immediately for the first and last updates.
2787 // Also, since the message loop may be pretty busy when a page is loaded, it
2788 // might not execute a posted task in a timely manner so we make sure to
2789 // immediately send progress report if enough time has passed.
2790 base::TimeDelta min_delay
=
2791 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS
);
2792 if (load_progress
== 1.0 || loading_last_progress_update_
.is_null() ||
2793 base::TimeTicks::Now() - loading_last_progress_update_
> min_delay
) {
2794 // If there is a pending task to send progress, it is now obsolete.
2795 loading_weak_factory_
.InvalidateWeakPtrs();
2796 SendLoadProgressChanged();
2797 if (loading_total_progress_
== 1.0)
2798 ResetLoadProgressState();
2802 if (loading_weak_factory_
.HasWeakPtrs())
2805 base::MessageLoop::current()->PostDelayedTask(
2807 base::Bind(&WebContentsImpl::SendLoadProgressChanged
,
2808 loading_weak_factory_
.GetWeakPtr()),
2812 void WebContentsImpl::OnGoToEntryAtOffset(int offset
) {
2813 if (!delegate_
|| delegate_
->OnGoToEntryOffset(offset
))
2814 controller_
.GoToOffset(offset
);
2817 void WebContentsImpl::OnUpdateZoomLimits(int minimum_percent
,
2818 int maximum_percent
) {
2819 minimum_zoom_percent_
= minimum_percent
;
2820 maximum_zoom_percent_
= maximum_percent
;
2823 void WebContentsImpl::OnEnumerateDirectory(int request_id
,
2824 const base::FilePath
& path
) {
2828 ChildProcessSecurityPolicyImpl
* policy
=
2829 ChildProcessSecurityPolicyImpl::GetInstance();
2830 if (policy
->CanReadFile(GetRenderProcessHost()->GetID(), path
))
2831 delegate_
->EnumerateDirectory(this, request_id
, path
);
2834 void WebContentsImpl::OnRegisterProtocolHandler(const std::string
& protocol
,
2836 const base::string16
& title
,
2837 bool user_gesture
) {
2841 ChildProcessSecurityPolicyImpl
* policy
=
2842 ChildProcessSecurityPolicyImpl::GetInstance();
2843 if (policy
->IsPseudoScheme(protocol
))
2846 delegate_
->RegisterProtocolHandler(this, protocol
, url
, user_gesture
);
2849 void WebContentsImpl::OnUnregisterProtocolHandler(const std::string
& protocol
,
2851 bool user_gesture
) {
2855 ChildProcessSecurityPolicyImpl
* policy
=
2856 ChildProcessSecurityPolicyImpl::GetInstance();
2857 if (policy
->IsPseudoScheme(protocol
))
2860 delegate_
->UnregisterProtocolHandler(this, protocol
, url
, user_gesture
);
2863 void WebContentsImpl::OnFindReply(int request_id
,
2864 int number_of_matches
,
2865 const gfx::Rect
& selection_rect
,
2866 int active_match_ordinal
,
2867 bool final_update
) {
2869 delegate_
->FindReply(this, request_id
, number_of_matches
, selection_rect
,
2870 active_match_ordinal
, final_update
);
2874 #if defined(OS_ANDROID)
2875 void WebContentsImpl::OnFindMatchRectsReply(
2877 const std::vector
<gfx::RectF
>& rects
,
2878 const gfx::RectF
& active_rect
) {
2880 delegate_
->FindMatchRectsReply(this, version
, rects
, active_rect
);
2883 void WebContentsImpl::OnOpenDateTimeDialog(
2884 const ViewHostMsg_DateTimeDialogValue_Params
& value
) {
2885 date_time_chooser_
->ShowDialog(GetTopLevelNativeWindow(),
2886 GetRenderViewHost(),
2896 void WebContentsImpl::OnDomOperationResponse(const std::string
& json_string
,
2897 int automation_id
) {
2898 DomOperationNotificationDetails
details(json_string
, automation_id
);
2899 NotificationService::current()->Notify(
2900 NOTIFICATION_DOM_OPERATION_RESPONSE
,
2901 Source
<WebContents
>(this),
2902 Details
<DomOperationNotificationDetails
>(&details
));
2905 void WebContentsImpl::OnAppCacheAccessed(const GURL
& manifest_url
,
2906 bool blocked_by_policy
) {
2907 // Notify observers about navigation.
2908 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2909 AppCacheAccessed(manifest_url
, blocked_by_policy
));
2912 void WebContentsImpl::OnOpenColorChooser(
2913 int color_chooser_id
,
2915 const std::vector
<ColorSuggestion
>& suggestions
) {
2916 ColorChooser
* new_color_chooser
= delegate_
?
2917 delegate_
->OpenColorChooser(this, color
, suggestions
) :
2919 if (!new_color_chooser
)
2921 if (color_chooser_info_
.get())
2922 color_chooser_info_
->chooser
->End();
2924 color_chooser_info_
.reset(new ColorChooserInfo(
2925 render_frame_message_source_
->GetProcess()->GetID(),
2926 render_frame_message_source_
->GetRoutingID(),
2931 void WebContentsImpl::OnEndColorChooser(int color_chooser_id
) {
2932 if (color_chooser_info_
&&
2933 color_chooser_id
== color_chooser_info_
->identifier
)
2934 color_chooser_info_
->chooser
->End();
2937 void WebContentsImpl::OnSetSelectedColorInColorChooser(int color_chooser_id
,
2939 if (color_chooser_info_
&&
2940 color_chooser_id
== color_chooser_info_
->identifier
)
2941 color_chooser_info_
->chooser
->SetSelectedColor(color
);
2944 // This exists for render views that don't have a WebUI, but do have WebUI
2945 // bindings enabled.
2946 void WebContentsImpl::OnWebUISend(const GURL
& source_url
,
2947 const std::string
& name
,
2948 const base::ListValue
& args
) {
2950 delegate_
->WebUISend(this, source_url
, name
, args
);
2953 #if defined(ENABLE_PLUGINS)
2954 void WebContentsImpl::OnPepperPluginHung(int plugin_child_id
,
2955 const base::FilePath
& path
,
2957 UMA_HISTOGRAM_COUNTS("Pepper.PluginHung", 1);
2959 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2960 PluginHungStatusChanged(plugin_child_id
, path
, is_hung
));
2963 void WebContentsImpl::OnPluginCrashed(const base::FilePath
& plugin_path
,
2964 base::ProcessId plugin_pid
) {
2965 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2966 PluginCrashed(plugin_path
, plugin_pid
));
2969 void WebContentsImpl::OnRequestPpapiBrokerPermission(
2972 const base::FilePath
& plugin_path
) {
2974 OnPpapiBrokerPermissionResult(routing_id
, false);
2978 if (!delegate_
->RequestPpapiBrokerPermission(
2979 this, url
, plugin_path
,
2980 base::Bind(&WebContentsImpl::OnPpapiBrokerPermissionResult
,
2981 base::Unretained(this), routing_id
))) {
2983 OnPpapiBrokerPermissionResult(routing_id
, false);
2987 void WebContentsImpl::OnPpapiBrokerPermissionResult(int routing_id
,
2989 Send(new ViewMsg_PpapiBrokerPermissionResult(routing_id
, result
));
2992 void WebContentsImpl::OnBrowserPluginMessage(const IPC::Message
& message
) {
2993 // This creates a BrowserPluginEmbedder, which handles all the BrowserPlugin
2994 // specific messages for this WebContents. This means that any message from
2995 // a BrowserPlugin prior to this will be ignored.
2996 // For more info, see comment above classes BrowserPluginEmbedder and
2997 // BrowserPluginGuest.
2998 CHECK(!browser_plugin_embedder_
.get());
2999 browser_plugin_embedder_
.reset(BrowserPluginEmbedder::Create(this));
3000 browser_plugin_embedder_
->OnMessageReceived(message
);
3002 #endif // defined(ENABLE_PLUGINS)
3004 void WebContentsImpl::OnDidDownloadImage(
3006 int http_status_code
,
3007 const GURL
& image_url
,
3008 const std::vector
<SkBitmap
>& bitmaps
,
3009 const std::vector
<gfx::Size
>& original_bitmap_sizes
) {
3010 if (bitmaps
.size() != original_bitmap_sizes
.size())
3013 ImageDownloadMap::iterator iter
= image_download_map_
.find(id
);
3014 if (iter
== image_download_map_
.end()) {
3015 // Currently WebContents notifies us of ANY downloads so that it is
3016 // possible to get here.
3019 if (!iter
->second
.is_null()) {
3021 id
, http_status_code
, image_url
, bitmaps
, original_bitmap_sizes
);
3023 image_download_map_
.erase(id
);
3026 void WebContentsImpl::OnUpdateFaviconURL(
3027 const std::vector
<FaviconURL
>& candidates
) {
3028 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3029 DidUpdateFaviconURL(candidates
));
3032 void WebContentsImpl::CreateAudioPowerSaveBlocker() {
3033 // ChromeOS has its own way of handling power save blocks for media.
3034 #if !defined(OS_CHROMEOS)
3035 DCHECK(!audio_power_save_blocker_
);
3036 audio_power_save_blocker_
= PowerSaveBlocker::Create(
3037 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension
, "Playing Audio");
3041 void WebContentsImpl::CreateVideoPowerSaveBlocker() {
3042 // ChromeOS has its own way of handling power save blocks for media.
3043 #if !defined(OS_CHROMEOS)
3044 DCHECK(!video_power_save_blocker_
);
3045 DCHECK(!active_video_players_
.empty());
3046 video_power_save_blocker_
= PowerSaveBlocker::Create(
3047 PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep
, "Playing Video");
3048 #if defined(OS_ANDROID)
3049 static_cast<PowerSaveBlockerImpl
*>(video_power_save_blocker_
.get())
3050 ->InitDisplaySleepBlocker(GetView()->GetNativeView());
3055 void WebContentsImpl::MaybeReleasePowerSaveBlockers() {
3056 // If there are no more audio players and we don't have audio stream
3057 // monitoring, release the audio power save blocker here instead of during
3058 // NotifyNavigationStateChanged().
3059 if (active_audio_players_
.empty() &&
3060 !AudioStreamMonitor::monitoring_available()) {
3061 audio_power_save_blocker_
.reset();
3064 // If there are no more video players, clear the video power save blocker.
3065 if (active_video_players_
.empty())
3066 video_power_save_blocker_
.reset();
3069 void WebContentsImpl::OnMediaPlayingNotification(int64 player_cookie
,
3073 // Ignore the videos playing remotely and don't hold the wake lock for the
3075 if (is_remote
) return;
3078 AddMediaPlayerEntry(player_cookie
, &active_audio_players_
);
3080 // If we don't have audio stream monitoring, allocate the audio power save
3081 // blocker here instead of during NotifyNavigationStateChanged().
3082 if (!audio_power_save_blocker_
&&
3083 !AudioStreamMonitor::monitoring_available()) {
3084 CreateAudioPowerSaveBlocker();
3089 AddMediaPlayerEntry(player_cookie
, &active_video_players_
);
3091 // If we're not hidden and have just created a player, create a blocker.
3092 if (!video_power_save_blocker_
&& !IsHidden())
3093 CreateVideoPowerSaveBlocker();
3097 void WebContentsImpl::OnMediaPausedNotification(int64 player_cookie
) {
3098 RemoveMediaPlayerEntry(player_cookie
, &active_audio_players_
);
3099 RemoveMediaPlayerEntry(player_cookie
, &active_video_players_
);
3100 MaybeReleasePowerSaveBlockers();
3103 void WebContentsImpl::OnFirstVisuallyNonEmptyPaint() {
3104 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3105 DidFirstVisuallyNonEmptyPaint());
3108 void WebContentsImpl::DidChangeVisibleSSLState() {
3110 delegate_
->VisibleSSLStateChanged(this);
3113 void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
3114 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3115 BeforeFormRepostWarningShow());
3118 void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
3121 delegate_
->ShowRepostFormWarningDialog(this);
3124 bool WebContentsImpl::HasAccessedInitialDocument() {
3125 return has_accessed_initial_document_
;
3128 // Notifies the RenderWidgetHost instance about the fact that the page is
3129 // loading, or done loading.
3130 void WebContentsImpl::SetIsLoading(RenderViewHost
* render_view_host
,
3132 bool to_different_document
,
3133 LoadNotificationDetails
* details
) {
3134 if (is_loading
== is_loading_
)
3138 load_state_
= net::LoadStateWithParam(net::LOAD_STATE_IDLE
,
3140 load_state_host_
.clear();
3142 upload_position_
= 0;
3145 GetRenderManager()->SetIsLoading(is_loading
);
3147 is_loading_
= is_loading
;
3148 waiting_for_response_
= is_loading
;
3149 is_load_to_different_document_
= to_different_document
;
3152 delegate_
->LoadingStateChanged(this, to_different_document
);
3153 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD
);
3155 std::string url
= (details
? details
->url
.possibly_invalid_spec() : "NULL");
3157 TRACE_EVENT_ASYNC_BEGIN1("browser,navigation", "WebContentsImpl Loading",
3159 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3160 DidStartLoading(render_view_host
));
3162 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
3164 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3165 DidStopLoading(render_view_host
));
3168 // TODO(avi): Remove. http://crbug.com/170921
3169 int type
= is_loading
? NOTIFICATION_LOAD_START
: NOTIFICATION_LOAD_STOP
;
3170 NotificationDetails det
= NotificationService::NoDetails();
3172 det
= Details
<LoadNotificationDetails
>(details
);
3173 NotificationService::current()->Notify(
3174 type
, Source
<NavigationController
>(&controller_
), det
);
3177 void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point
& extent
) {
3178 RenderFrameHost
* focused_frame
= GetFocusedFrame();
3182 focused_frame
->Send(new InputMsg_MoveRangeSelectionExtent(
3183 focused_frame
->GetRoutingID(), extent
));
3186 void WebContentsImpl::SelectRange(const gfx::Point
& base
,
3187 const gfx::Point
& extent
) {
3188 RenderFrameHost
* focused_frame
= GetFocusedFrame();
3192 focused_frame
->Send(
3193 new InputMsg_SelectRange(focused_frame
->GetRoutingID(), base
, extent
));
3196 void WebContentsImpl::UpdateMaxPageIDIfNecessary(RenderViewHost
* rvh
) {
3197 // If we are creating a RVH for a restored controller, then we need to make
3198 // sure the RenderView starts with a next_page_id_ larger than the number
3199 // of restored entries. This must be called before the RenderView starts
3200 // navigating (to avoid a race between the browser updating max_page_id and
3201 // the renderer updating next_page_id_). Because of this, we only call this
3202 // from CreateRenderView and allow that to notify the RenderView for us.
3203 int max_restored_page_id
= controller_
.GetMaxRestoredPageID();
3204 if (max_restored_page_id
>
3205 GetMaxPageIDForSiteInstance(rvh
->GetSiteInstance()))
3206 UpdateMaxPageIDForSiteInstance(rvh
->GetSiteInstance(),
3207 max_restored_page_id
);
3210 bool WebContentsImpl::UpdateTitleForEntry(NavigationEntryImpl
* entry
,
3211 const base::string16
& title
) {
3212 // For file URLs without a title, use the pathname instead. In the case of a
3213 // synthesized title, we don't want the update to count toward the "one set
3214 // per page of the title to history."
3215 base::string16 final_title
;
3217 if (entry
&& entry
->GetURL().SchemeIsFile() && title
.empty()) {
3218 final_title
= base::UTF8ToUTF16(entry
->GetURL().ExtractFileName());
3219 explicit_set
= false; // Don't count synthetic titles toward the set limit.
3221 base::TrimWhitespace(title
, base::TRIM_ALL
, &final_title
);
3222 explicit_set
= true;
3225 // If a page is created via window.open and never navigated,
3226 // there will be no navigation entry. In this situation,
3227 // |page_title_when_no_navigation_entry_| will be used for page title.
3229 if (final_title
== entry
->GetTitle())
3230 return false; // Nothing changed, don't bother.
3232 entry
->SetTitle(final_title
);
3234 if (page_title_when_no_navigation_entry_
== final_title
)
3235 return false; // Nothing changed, don't bother.
3237 page_title_when_no_navigation_entry_
= final_title
;
3240 // Lastly, set the title for the view.
3241 view_
->SetPageTitle(final_title
);
3243 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3244 TitleWasSet(entry
, explicit_set
));
3246 // TODO(avi): Remove. http://crbug.com/170921
3247 std::pair
<NavigationEntry
*, bool> details
=
3248 std::make_pair(entry
, explicit_set
);
3249 NotificationService::current()->Notify(
3250 NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED
,
3251 Source
<WebContents
>(this),
3252 Details
<std::pair
<NavigationEntry
*, bool> >(&details
));
3257 void WebContentsImpl::SendLoadProgressChanged() {
3258 loading_last_progress_update_
= base::TimeTicks::Now();
3259 double progress
= 0.0;
3260 int frame_count
= 0;
3262 for (LoadingProgressMap::iterator it
= loading_progresses_
.begin();
3263 it
!= loading_progresses_
.end();
3265 progress
+= it
->second
;
3268 if (frame_count
== 0)
3270 progress
/= frame_count
;
3271 DCHECK(progress
<= 1.0);
3273 if (progress
<= loading_total_progress_
)
3275 loading_total_progress_
= progress
;
3278 delegate_
->LoadProgressChanged(this, progress
);
3281 void WebContentsImpl::ResetLoadProgressState() {
3282 loading_progresses_
.clear();
3283 loading_total_progress_
= 0.0;
3284 loading_weak_factory_
.InvalidateWeakPtrs();
3285 loading_last_progress_update_
= base::TimeTicks();
3288 void WebContentsImpl::NotifyViewSwapped(RenderViewHost
* old_host
,
3289 RenderViewHost
* new_host
) {
3290 // After sending out a swap notification, we need to send a disconnect
3291 // notification so that clients that pick up a pointer to |this| can NULL the
3292 // pointer. See Bug 1230284.
3293 notify_disconnection_
= true;
3294 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3295 RenderViewHostChanged(old_host
, new_host
));
3297 // TODO(avi): Remove. http://crbug.com/170921
3298 std::pair
<RenderViewHost
*, RenderViewHost
*> details
=
3299 std::make_pair(old_host
, new_host
);
3300 NotificationService::current()->Notify(
3301 NOTIFICATION_RENDER_VIEW_HOST_CHANGED
,
3302 Source
<WebContents
>(this),
3303 Details
<std::pair
<RenderViewHost
*, RenderViewHost
*> >(&details
));
3305 // Ensure that the associated embedder gets cleared after a RenderViewHost
3306 // gets swapped, so we don't reuse the same embedder next time a
3307 // RenderViewHost is attached to this WebContents.
3308 RemoveBrowserPluginEmbedder();
3311 void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost
* old_host
,
3312 RenderFrameHost
* new_host
) {
3313 FOR_EACH_OBSERVER(WebContentsObserver
,
3315 RenderFrameHostChanged(old_host
, new_host
));
3318 // TODO(avi): Remove this entire function because this notification is already
3319 // covered by two observer functions. http://crbug.com/170921
3320 void WebContentsImpl::NotifyDisconnected() {
3321 if (!notify_disconnection_
)
3324 notify_disconnection_
= false;
3325 NotificationService::current()->Notify(
3326 NOTIFICATION_WEB_CONTENTS_DISCONNECTED
,
3327 Source
<WebContents
>(this),
3328 NotificationService::NoDetails());
3331 void WebContentsImpl::NotifyNavigationEntryCommitted(
3332 const LoadCommittedDetails
& load_details
) {
3334 WebContentsObserver
, observers_
, NavigationEntryCommitted(load_details
));
3337 bool WebContentsImpl::OnMessageReceived(RenderFrameHost
* render_frame_host
,
3338 const IPC::Message
& message
) {
3339 return OnMessageReceived(NULL
, render_frame_host
, message
);
3342 const GURL
& WebContentsImpl::GetMainFrameLastCommittedURL() const {
3343 return GetLastCommittedURL();
3346 void WebContentsImpl::RenderFrameCreated(RenderFrameHost
* render_frame_host
) {
3347 // Note this is only for subframes, the notification for the main frame
3348 // happens in RenderViewCreated.
3349 FOR_EACH_OBSERVER(WebContentsObserver
,
3351 RenderFrameCreated(render_frame_host
));
3352 SetAccessibilityModeOnFrame(accessibility_mode_
, render_frame_host
);
3355 void WebContentsImpl::RenderFrameDeleted(RenderFrameHost
* render_frame_host
) {
3356 ClearPowerSaveBlockers(render_frame_host
);
3357 FOR_EACH_OBSERVER(WebContentsObserver
,
3359 RenderFrameDeleted(render_frame_host
));
3362 void WebContentsImpl::WorkerCrashed(RenderFrameHost
* render_frame_host
) {
3364 delegate_
->WorkerCrashed(this);
3367 void WebContentsImpl::ShowContextMenu(RenderFrameHost
* render_frame_host
,
3368 const ContextMenuParams
& params
) {
3369 ContextMenuParams
context_menu_params(params
);
3370 // Allow WebContentsDelegates to handle the context menu operation first.
3371 if (GetBrowserPluginGuest()) {
3372 WebContentsViewGuest
* view_guest
=
3373 static_cast<WebContentsViewGuest
*>(GetView());
3374 context_menu_params
= view_guest
->ConvertContextMenuParams(params
);
3376 if (delegate_
&& delegate_
->HandleContextMenu(context_menu_params
))
3379 render_view_host_delegate_view_
->ShowContextMenu(render_frame_host
,
3380 context_menu_params
);
3383 void WebContentsImpl::RunJavaScriptMessage(
3384 RenderFrameHost
* render_frame_host
,
3385 const base::string16
& message
,
3386 const base::string16
& default_prompt
,
3387 const GURL
& frame_url
,
3388 JavaScriptMessageType javascript_message_type
,
3389 IPC::Message
* reply_msg
) {
3390 // Suppress JavaScript dialogs when requested. Also suppress messages when
3391 // showing an interstitial as it's shown over the previous page and we don't
3392 // want the hidden page's dialogs to interfere with the interstitial.
3393 bool suppress_this_message
=
3394 static_cast<RenderFrameHostImpl
*>(render_frame_host
)->is_swapped_out() ||
3395 ShowingInterstitialPage() || !delegate_
||
3396 delegate_
->ShouldSuppressDialogs(this) ||
3397 !delegate_
->GetJavaScriptDialogManager(this);
3399 if (!suppress_this_message
) {
3400 std::string accept_lang
= GetContentClient()->browser()->
3401 GetAcceptLangs(GetBrowserContext());
3402 dialog_manager_
= delegate_
->GetJavaScriptDialogManager(this);
3403 dialog_manager_
->RunJavaScriptDialog(
3405 frame_url
.GetOrigin(),
3407 javascript_message_type
,
3410 base::Bind(&WebContentsImpl::OnDialogClosed
,
3411 base::Unretained(this),
3412 render_frame_host
->GetProcess()->GetID(),
3413 render_frame_host
->GetRoutingID(),
3416 &suppress_this_message
);
3419 if (suppress_this_message
) {
3420 // If we are suppressing messages, just reply as if the user immediately
3421 // pressed "Cancel", passing true to |dialog_was_suppressed|.
3422 OnDialogClosed(render_frame_host
->GetProcess()->GetID(),
3423 render_frame_host
->GetRoutingID(), reply_msg
,
3424 true, false, base::string16());
3427 // OnDialogClosed (two lines up) may have caused deletion of this object (see
3428 // http://crbug.com/288961 ). The only safe thing to do here is return.
3431 void WebContentsImpl::RunBeforeUnloadConfirm(
3432 RenderFrameHost
* render_frame_host
,
3433 const base::string16
& message
,
3435 IPC::Message
* reply_msg
) {
3436 RenderFrameHostImpl
* rfhi
=
3437 static_cast<RenderFrameHostImpl
*>(render_frame_host
);
3439 delegate_
->WillRunBeforeUnloadConfirm();
3441 bool suppress_this_message
=
3442 rfhi
->rfh_state() != RenderFrameHostImpl::STATE_DEFAULT
|| !delegate_
||
3443 delegate_
->ShouldSuppressDialogs(this) ||
3444 !delegate_
->GetJavaScriptDialogManager(this);
3445 if (suppress_this_message
) {
3446 rfhi
->JavaScriptDialogClosed(reply_msg
, true, base::string16(), true);
3450 is_showing_before_unload_dialog_
= true;
3451 dialog_manager_
= delegate_
->GetJavaScriptDialogManager(this);
3452 dialog_manager_
->RunBeforeUnloadDialog(
3453 this, message
, is_reload
,
3454 base::Bind(&WebContentsImpl::OnDialogClosed
, base::Unretained(this),
3455 render_frame_host
->GetProcess()->GetID(),
3456 render_frame_host
->GetRoutingID(), reply_msg
,
3460 WebContents
* WebContentsImpl::GetAsWebContents() {
3464 bool WebContentsImpl::IsNeverVisible() {
3467 return delegate_
->IsNeverVisible(this);
3471 gfx::NativeViewAccessible
WebContentsImpl::GetParentNativeViewAccessible() {
3472 return accessible_parent_
;
3476 RenderViewHostDelegateView
* WebContentsImpl::GetDelegateView() {
3477 return render_view_host_delegate_view_
;
3480 RendererPreferences
WebContentsImpl::GetRendererPrefs(
3481 BrowserContext
* browser_context
) const {
3482 return renderer_preferences_
;
3485 gfx::Rect
WebContentsImpl::GetRootWindowResizerRect() const {
3487 return delegate_
->GetRootWindowResizerRect();
3491 void WebContentsImpl::RemoveBrowserPluginEmbedder() {
3492 if (browser_plugin_embedder_
)
3493 browser_plugin_embedder_
.reset();
3496 void WebContentsImpl::RenderViewCreated(RenderViewHost
* render_view_host
) {
3497 // Don't send notifications if we are just creating a swapped-out RVH for
3498 // the opener chain. These won't be used for view-source or WebUI, so it's
3499 // ok to return early.
3500 if (!static_cast<RenderViewHostImpl
*>(render_view_host
)->is_active())
3504 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
3506 NotificationService::current()->Notify(
3507 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED
,
3508 Source
<WebContents
>(this),
3509 Details
<RenderViewHost
>(render_view_host
));
3511 // When we're creating views, we're still doing initial setup, so we always
3512 // use the pending Web UI rather than any possibly existing committed one.
3513 if (GetRenderManager()->pending_web_ui())
3514 GetRenderManager()->pending_web_ui()->RenderViewCreated(render_view_host
);
3516 NavigationEntry
* entry
= controller_
.GetPendingEntry();
3517 if (entry
&& entry
->IsViewSourceMode()) {
3518 // Put the renderer in view source mode.
3519 render_view_host
->Send(
3520 new ViewMsg_EnableViewSourceMode(render_view_host
->GetRoutingID()));
3523 view_
->RenderViewCreated(render_view_host
);
3526 WebContentsObserver
, observers_
, RenderViewCreated(render_view_host
));
3528 // We tell the observers now instead of when the main RenderFrameHostImpl is
3529 // constructed because otherwise it would be too early (i.e. IPCs sent to the
3530 // frame would be dropped because it's not created yet).
3531 RenderFrameHost
* main_frame
= render_view_host
->GetMainFrame();
3533 WebContentsObserver
, observers_
, RenderFrameCreated(main_frame
));
3534 SetAccessibilityModeOnFrame(accessibility_mode_
, main_frame
);
3536 DevToolsManager::GetInstance()->RenderViewCreated(this, render_view_host
);
3539 void WebContentsImpl::RenderViewReady(RenderViewHost
* rvh
) {
3540 if (rvh
!= GetRenderViewHost()) {
3541 // Don't notify the world, since this came from a renderer in the
3546 notify_disconnection_
= true;
3547 // TODO(avi): Remove. http://crbug.com/170921
3548 NotificationService::current()->Notify(
3549 NOTIFICATION_WEB_CONTENTS_CONNECTED
,
3550 Source
<WebContents
>(this),
3551 NotificationService::NoDetails());
3553 bool was_crashed
= IsCrashed();
3554 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING
, 0);
3556 // Restore the focus to the tab (otherwise the focus will be on the top
3558 if (was_crashed
&& !FocusLocationBarByDefault() &&
3559 (!delegate_
|| delegate_
->ShouldFocusPageAfterCrash())) {
3563 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, RenderViewReady());
3566 void WebContentsImpl::RenderViewTerminated(RenderViewHost
* rvh
,
3567 base::TerminationStatus status
,
3569 if (rvh
!= GetRenderViewHost()) {
3570 // The pending page's RenderViewHost is gone.
3574 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
3575 // renderer may not have made a clean exit.
3576 if (IsFullscreenForCurrentTab())
3577 ToggleFullscreenMode(false);
3579 // Cancel any visible dialogs so they are not left dangling over the sad tab.
3580 if (dialog_manager_
)
3581 dialog_manager_
->CancelActiveAndPendingDialogs(this);
3584 delegate_
->HideValidationMessage(this);
3586 SetIsLoading(rvh
, false, true, NULL
);
3587 NotifyDisconnected();
3588 SetIsCrashed(status
, error_code
);
3590 // Reset the loading progress. TODO(avi): What does it mean to have a
3591 // "renderer crash" when there is more than one renderer process serving a
3592 // webpage? Once this function is called at a more granular frame level, we
3593 // probably will need to more granularly reset the state here.
3594 ResetLoadProgressState();
3595 loading_frames_in_progress_
= 0;
3597 FOR_EACH_OBSERVER(WebContentsObserver
,
3599 RenderProcessGone(GetCrashedStatus()));
3602 void WebContentsImpl::RenderViewDeleted(RenderViewHost
* rvh
) {
3603 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, RenderViewDeleted(rvh
));
3606 void WebContentsImpl::UpdateState(RenderViewHost
* rvh
,
3608 const PageState
& page_state
) {
3609 // Ensure that this state update comes from a RenderViewHost that belongs to
3610 // this WebContents.
3611 // TODO(nasko): This should go through RenderFrameHost.
3612 // TODO(creis): We can't update state for cross-process subframes until we
3613 // have FrameNavigationEntries. Once we do, this should be a DCHECK.
3614 if (rvh
->GetDelegate()->GetAsWebContents() != this)
3617 // We must be prepared to handle state updates for any page, these occur
3618 // when the user is scrolling and entering form data, as well as when we're
3619 // leaving a page, in which case our state may have already been moved to
3620 // the next page. The navigation controller will look up the appropriate
3621 // NavigationEntry and update it when it is notified via the delegate.
3623 int entry_index
= controller_
.GetEntryIndexWithPageID(
3624 rvh
->GetSiteInstance(), page_id
);
3625 if (entry_index
< 0)
3627 NavigationEntry
* entry
= controller_
.GetEntryAtIndex(entry_index
);
3629 if (page_state
== entry
->GetPageState())
3630 return; // Nothing to update.
3631 entry
->SetPageState(page_state
);
3632 controller_
.NotifyEntryChanged(entry
, entry_index
);
3635 void WebContentsImpl::UpdateTargetURL(const GURL
& url
) {
3637 delegate_
->UpdateTargetURL(this, url
);
3640 void WebContentsImpl::Close(RenderViewHost
* rvh
) {
3641 #if defined(OS_MACOSX)
3642 // The UI may be in an event-tracking loop, such as between the
3643 // mouse-down and mouse-up in text selection or a button click.
3644 // Defer the close until after tracking is complete, so that we
3645 // don't free objects out from under the UI.
3646 // TODO(shess): This could get more fine-grained. For instance,
3647 // closing a tab in another window while selecting text in the
3648 // current window's Omnibox should be just fine.
3649 if (view_
->IsEventTracking()) {
3650 view_
->CloseTabAfterEventTracking();
3655 // Ignore this if it comes from a RenderViewHost that we aren't showing.
3656 if (delegate_
&& rvh
== GetRenderViewHost())
3657 delegate_
->CloseContents(this);
3660 void WebContentsImpl::SwappedOut(RenderFrameHost
* rfh
) {
3661 if (delegate_
&& rfh
->GetRenderViewHost() == GetRenderViewHost())
3662 delegate_
->SwappedOut(this);
3665 void WebContentsImpl::DidDeferAfterResponseStarted(
3666 const TransitionLayerData
& transition_data
) {
3667 #if defined(OS_ANDROID)
3668 GetWebContentsAndroid()->DidDeferAfterResponseStarted(transition_data
);
3672 bool WebContentsImpl::WillHandleDeferAfterResponseStarted() {
3673 #if defined(OS_ANDROID)
3674 return GetWebContentsAndroid()->WillHandleDeferAfterResponseStarted();
3680 void WebContentsImpl::RequestMove(const gfx::Rect
& new_bounds
) {
3681 if (delegate_
&& delegate_
->IsPopupOrPanel(this))
3682 delegate_
->MoveContents(this, new_bounds
);
3685 void WebContentsImpl::DidStartLoading(RenderFrameHost
* render_frame_host
,
3686 bool to_different_document
) {
3687 SetIsLoading(render_frame_host
->GetRenderViewHost(), true,
3688 to_different_document
, NULL
);
3691 void WebContentsImpl::DidStopLoading(RenderFrameHost
* render_frame_host
) {
3692 scoped_ptr
<LoadNotificationDetails
> details
;
3694 // Use the last committed entry rather than the active one, in case a
3695 // pending entry has been created.
3696 NavigationEntry
* entry
= controller_
.GetLastCommittedEntry();
3697 Navigator
* navigator
= frame_tree_
.root()->navigator();
3699 // An entry may not exist for a stop when loading an initial blank page or
3700 // if an iframe injected by script into a blank page finishes loading.
3702 base::TimeDelta elapsed
=
3703 base::TimeTicks::Now() - navigator
->GetCurrentLoadStart();
3705 details
.reset(new LoadNotificationDetails(
3706 entry
->GetVirtualURL(),
3707 entry
->GetTransitionType(),
3710 controller_
.GetCurrentEntryIndex()));
3713 SetIsLoading(render_frame_host
->GetRenderViewHost(), false, true,
3717 void WebContentsImpl::DidCancelLoading() {
3718 controller_
.DiscardNonCommittedEntries();
3720 // Update the URL display.
3721 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL
);
3724 void WebContentsImpl::DidAccessInitialDocument() {
3725 has_accessed_initial_document_
= true;
3727 // We may have left a failed browser-initiated navigation in the address bar
3728 // to let the user edit it and try again. Clear it now that content might
3729 // show up underneath it.
3730 if (!IsLoading() && controller_
.GetPendingEntry())
3731 controller_
.DiscardPendingEntry();
3733 // Update the URL display.
3734 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL
);
3737 void WebContentsImpl::DidDisownOpener(RenderFrameHost
* render_frame_host
) {
3738 // No action is necessary if the opener has already been cleared.
3742 // Clear our opener so that future cross-process navigations don't have an
3744 RemoveDestructionObserver(opener_
);
3747 // Notify all swapped out RenderViewHosts for this tab. This is important
3748 // in case we go back to them, or if another window in those processes tries
3749 // to access window.opener.
3750 GetRenderManager()->DidDisownOpener(render_frame_host
);
3753 void WebContentsImpl::DocumentOnLoadCompleted(
3754 RenderFrameHost
* render_frame_host
) {
3755 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3756 DocumentOnLoadCompletedInMainFrame());
3758 // TODO(avi): Remove. http://crbug.com/170921
3759 NotificationService::current()->Notify(
3760 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
,
3761 Source
<WebContents
>(this),
3762 NotificationService::NoDetails());
3765 void WebContentsImpl::UpdateTitle(RenderFrameHost
* render_frame_host
,
3767 const base::string16
& title
,
3768 base::i18n::TextDirection title_direction
) {
3769 RenderViewHost
* rvh
= render_frame_host
->GetRenderViewHost();
3771 // If we have a title, that's a pretty good indication that we've started
3772 // getting useful data.
3773 SetNotWaitingForResponse();
3775 // Try to find the navigation entry, which might not be the current one.
3776 // For example, it might be from a pending RVH for the pending entry.
3777 NavigationEntryImpl
* entry
= controller_
.GetEntryWithPageID(
3778 rvh
->GetSiteInstance(), page_id
);
3780 // We can handle title updates when we don't have an entry in
3781 // UpdateTitleForEntry, but only if the update is from the current RVH.
3782 // TODO(avi): Change to make decisions based on the RenderFrameHost.
3783 if (!entry
&& rvh
!= GetRenderViewHost())
3786 // TODO(evan): make use of title_direction.
3787 // http://code.google.com/p/chromium/issues/detail?id=27094
3788 if (!UpdateTitleForEntry(entry
, title
))
3791 // Broadcast notifications when the UI should be updated.
3792 if (entry
== controller_
.GetEntryAtOffset(0))
3793 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE
);
3796 void WebContentsImpl::UpdateEncoding(RenderFrameHost
* render_frame_host
,
3797 const std::string
& encoding
) {
3798 SetEncoding(encoding
);
3801 void WebContentsImpl::DocumentAvailableInMainFrame(
3802 RenderViewHost
* render_view_host
) {
3803 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3804 DocumentAvailableInMainFrame());
3806 void WebContentsImpl::RouteCloseEvent(RenderViewHost
* rvh
) {
3807 // Tell the active RenderViewHost to run unload handlers and close, as long
3808 // as the request came from a RenderViewHost in the same BrowsingInstance.
3809 // In most cases, we receive this from a swapped out RenderViewHost.
3810 // It is possible to receive it from one that has just been swapped in,
3811 // in which case we might as well deliver the message anyway.
3812 if (rvh
->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()))
3813 GetRenderViewHost()->ClosePage();
3816 void WebContentsImpl::RouteMessageEvent(
3817 RenderViewHost
* rvh
,
3818 const ViewMsg_PostMessage_Params
& params
) {
3819 // Only deliver the message to the active RenderViewHost if the request
3820 // came from a RenderViewHost in the same BrowsingInstance or if this
3821 // WebContents is dedicated to a browser plugin guest.
3822 // Note: This check means that an embedder could theoretically receive a
3823 // postMessage from anyone (not just its own guests). However, this is
3824 // probably not a risk for apps since other pages won't have references
3826 if (!rvh
->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()) &&
3827 !GetBrowserPluginGuest() && !GetBrowserPluginEmbedder())
3830 ViewMsg_PostMessage_Params
new_params(params
);
3832 if (!params
.message_port_ids
.empty()) {
3833 MessagePortMessageFilter
* message_port_message_filter
=
3834 static_cast<RenderProcessHostImpl
*>(GetRenderProcessHost())
3835 ->message_port_message_filter();
3836 message_port_message_filter
->UpdateMessagePortsWithNewRoutes(
3837 params
.message_port_ids
,
3838 &new_params
.new_routing_ids
);
3841 // If there is a source_routing_id, translate it to the routing ID for
3842 // the equivalent swapped out RVH in the target process. If we need
3843 // to create a swapped out RVH for the source tab, we create its opener
3844 // chain as well, since those will also be accessible to the target page.
3845 if (new_params
.source_routing_id
!= MSG_ROUTING_NONE
) {
3846 // Try to look up the WebContents for the source page.
3847 WebContentsImpl
* source_contents
= NULL
;
3848 RenderViewHostImpl
* source_rvh
= RenderViewHostImpl::FromID(
3849 rvh
->GetProcess()->GetID(), params
.source_routing_id
);
3851 source_contents
= static_cast<WebContentsImpl
*>(
3852 source_rvh
->GetDelegate()->GetAsWebContents());
3855 if (source_contents
) {
3856 if (GetBrowserPluginGuest()) {
3857 // We create a swapped out RenderView for the embedder in the guest's
3858 // render process but we intentionally do not expose the embedder's
3859 // opener chain to it.
3860 new_params
.source_routing_id
=
3861 source_contents
->CreateSwappedOutRenderView(GetSiteInstance());
3863 new_params
.source_routing_id
=
3864 source_contents
->CreateOpenerRenderViews(GetSiteInstance());
3867 // We couldn't find it, so don't pass a source frame.
3868 new_params
.source_routing_id
= MSG_ROUTING_NONE
;
3872 // In most cases, we receive this from a swapped out RenderViewHost.
3873 // It is possible to receive it from one that has just been swapped in,
3874 // in which case we might as well deliver the message anyway.
3875 Send(new ViewMsg_PostMessageEvent(GetRoutingID(), new_params
));
3878 bool WebContentsImpl::AddMessageToConsole(int32 level
,
3879 const base::string16
& message
,
3881 const base::string16
& source_id
) {
3884 return delegate_
->AddMessageToConsole(this, level
, message
, line_no
,
3888 WebPreferences
WebContentsImpl::ComputeWebkitPrefs() {
3889 // We want to base the page config off of the actual URL, rather than the
3891 // TODO(nasko): Investigate how to remove the GetActiveEntry usage here,
3892 // as it is deprecated and can be out of sync with GetRenderViewHost().
3893 GURL url
= controller_
.GetActiveEntry()
3894 ? controller_
.GetActiveEntry()->GetURL() : GURL::EmptyGURL();
3896 return GetRenderManager()->current_host()->ComputeWebkitPrefs(url
);
3899 int WebContentsImpl::CreateSwappedOutRenderView(
3900 SiteInstance
* instance
) {
3901 int render_view_routing_id
= MSG_ROUTING_NONE
;
3902 GetRenderManager()->CreateRenderFrame(
3903 instance
, nullptr, MSG_ROUTING_NONE
,
3904 CREATE_RF_SWAPPED_OUT
| CREATE_RF_FOR_MAIN_FRAME_NAVIGATION
|
3906 &render_view_routing_id
);
3907 return render_view_routing_id
;
3910 void WebContentsImpl::OnUserGesture() {
3911 // Notify observers.
3912 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, DidGetUserGesture());
3914 ResourceDispatcherHostImpl
* rdh
= ResourceDispatcherHostImpl::Get();
3915 if (rdh
) // NULL in unittests.
3916 rdh
->OnUserGesture(this);
3919 void WebContentsImpl::OnIgnoredUIEvent() {
3920 // Notify observers.
3921 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, DidGetIgnoredUIEvent());
3924 void WebContentsImpl::RendererUnresponsive(RenderViewHost
* render_view_host
) {
3925 // Don't show hung renderer dialog for a swapped out RVH.
3926 if (render_view_host
!= GetRenderViewHost())
3929 RenderViewHostImpl
* rvhi
= static_cast<RenderViewHostImpl
*>(render_view_host
);
3930 RenderFrameHostImpl
* rfhi
=
3931 static_cast<RenderFrameHostImpl
*>(rvhi
->GetMainFrame());
3933 // Ignore renderer unresponsive event if debugger is attached to the tab
3934 // since the event may be a result of the renderer sitting on a breakpoint.
3935 // See http://crbug.com/65458
3936 if (DevToolsAgentHost::IsDebuggerAttached(this))
3939 if (rfhi
->is_waiting_for_beforeunload_ack() ||
3940 rfhi
->IsWaitingForUnloadACK()) {
3941 // Hang occurred while firing the beforeunload/unload handler.
3942 // Pretend the handler fired so tab closing continues as if it had.
3943 rvhi
->set_sudden_termination_allowed(true);
3945 if (!GetRenderManager()->ShouldCloseTabOnUnresponsiveRenderer())
3948 // If the tab hangs in the beforeunload/unload handler there's really
3949 // nothing we can do to recover. If the hang is in the beforeunload handler,
3950 // pretend the beforeunload listeners have all fired and allow the delegate
3951 // to continue closing; the user will not have the option of cancelling the
3952 // close. Otherwise, pretend the unload listeners have all fired and close
3955 if (rfhi
->is_waiting_for_beforeunload_ack() && delegate_
) {
3956 delegate_
->BeforeUnloadFired(this, true, &close
);
3963 if (!GetRenderViewHostImpl() || !GetRenderViewHostImpl()->IsRenderViewLive())
3967 delegate_
->RendererUnresponsive(this);
3970 void WebContentsImpl::RendererResponsive(RenderViewHost
* render_view_host
) {
3972 delegate_
->RendererResponsive(this);
3975 void WebContentsImpl::LoadStateChanged(
3977 const net::LoadStateWithParam
& load_state
,
3978 uint64 upload_position
,
3979 uint64 upload_size
) {
3980 load_state_
= load_state
;
3981 upload_position_
= upload_position
;
3982 upload_size_
= upload_size
;
3983 load_state_host_
= net::IDNToUnicode(url
.host(),
3984 GetContentClient()->browser()->GetAcceptLangs(
3985 GetBrowserContext()));
3986 if (load_state_
.state
== net::LOAD_STATE_READING_RESPONSE
)
3987 SetNotWaitingForResponse();
3989 NotifyNavigationStateChanged(static_cast<InvalidateTypes
>(
3990 INVALIDATE_TYPE_LOAD
| INVALIDATE_TYPE_TAB
));
3994 void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
3995 bool proceed
, const base::TimeTicks
& proceed_time
,
3996 bool* proceed_to_fire_unload
) {
3997 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3998 BeforeUnloadFired(proceed_time
));
4000 delegate_
->BeforeUnloadFired(this, proceed
, proceed_to_fire_unload
);
4001 // Note: |this| might be deleted at this point.
4004 void WebContentsImpl::RenderProcessGoneFromRenderManager(
4005 RenderViewHost
* render_view_host
) {
4006 DCHECK(crashed_status_
!= base::TERMINATION_STATUS_STILL_RUNNING
);
4007 RenderViewTerminated(render_view_host
, crashed_status_
, crashed_error_code_
);
4010 void WebContentsImpl::UpdateRenderViewSizeForRenderManager() {
4011 // TODO(brettw) this is a hack. See WebContentsView::SizeContents.
4012 gfx::Size size
= GetSizeForNewRenderView();
4013 // 0x0 isn't a valid window size (minimal window size is 1x1) but it may be
4014 // here during container initialization and normal window size will be set
4015 // later. In case of tab duplication this resizing to 0x0 prevents setting
4016 // normal size later so just ignore it.
4017 if (!size
.IsEmpty())
4018 view_
->SizeContents(size
);
4021 void WebContentsImpl::CancelModalDialogsForRenderManager() {
4022 // We need to cancel modal dialogs when doing a process swap, since the load
4023 // deferrer would prevent us from swapping out.
4024 if (dialog_manager_
)
4025 dialog_manager_
->CancelActiveAndPendingDialogs(this);
4028 void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost
* old_host
,
4029 RenderFrameHost
* new_host
,
4030 bool is_main_frame
) {
4031 if (is_main_frame
) {
4032 NotifyViewSwapped(old_host
? old_host
->GetRenderViewHost() : NULL
,
4033 new_host
->GetRenderViewHost());
4035 // Make sure the visible RVH reflects the new delegate's preferences.
4037 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
4039 view_
->RenderViewSwappedIn(new_host
->GetRenderViewHost());
4042 NotifyFrameSwapped(old_host
, new_host
);
4045 int WebContentsImpl::CreateOpenerRenderViewsForRenderManager(
4046 SiteInstance
* instance
) {
4048 return MSG_ROUTING_NONE
;
4050 // Recursively create RenderViews for anything else in the opener chain.
4051 return opener_
->CreateOpenerRenderViews(instance
);
4054 int WebContentsImpl::CreateOpenerRenderViews(SiteInstance
* instance
) {
4055 int opener_route_id
= MSG_ROUTING_NONE
;
4057 // If this tab has an opener, ensure it has a RenderView in the given
4058 // SiteInstance as well.
4060 opener_route_id
= opener_
->CreateOpenerRenderViews(instance
);
4062 // If any of the renderers (current, pending, or swapped out) for this
4063 // WebContents has the same SiteInstance, use it.
4064 if (GetRenderManager()->current_host()->GetSiteInstance() == instance
)
4065 return GetRenderManager()->current_host()->GetRoutingID();
4067 if (GetRenderManager()->pending_render_view_host() &&
4068 GetRenderManager()->pending_render_view_host()->GetSiteInstance() ==
4070 return GetRenderManager()->pending_render_view_host()->GetRoutingID();
4072 RenderViewHostImpl
* rvh
= GetRenderManager()->GetSwappedOutRenderViewHost(
4075 return rvh
->GetRoutingID();
4077 // Create a swapped out RenderView in the given SiteInstance if none exists,
4078 // setting its opener to the given route_id. Return the new view's route_id.
4079 int render_view_routing_id
= MSG_ROUTING_NONE
;
4080 GetRenderManager()->CreateRenderFrame(instance
, nullptr, opener_route_id
,
4081 CREATE_RF_FOR_MAIN_FRAME_NAVIGATION
|
4082 CREATE_RF_SWAPPED_OUT
|
4084 &render_view_routing_id
);
4085 return render_view_routing_id
;
4088 NavigationControllerImpl
& WebContentsImpl::GetControllerForRenderManager() {
4089 return GetController();
4092 scoped_ptr
<WebUIImpl
> WebContentsImpl::CreateWebUIForRenderManager(
4094 return scoped_ptr
<WebUIImpl
>(static_cast<WebUIImpl
*>(CreateWebUI(url
)));
4098 WebContentsImpl::GetLastCommittedNavigationEntryForRenderManager() {
4099 return controller_
.GetLastCommittedEntry();
4102 bool WebContentsImpl::CreateRenderViewForRenderManager(
4103 RenderViewHost
* render_view_host
,
4104 int opener_route_id
,
4105 int proxy_routing_id
,
4106 bool for_main_frame_navigation
) {
4107 TRACE_EVENT0("browser,navigation",
4108 "WebContentsImpl::CreateRenderViewForRenderManager");
4109 // Can be NULL during tests.
4110 RenderWidgetHostViewBase
* rwh_view
;
4111 // TODO(kenrb): RenderWidgetHostViewChildFrame special casing is temporary
4112 // until RenderWidgetHost is attached to RenderFrameHost. We need to special
4113 // case this because RWH is still a base class of RenderViewHost, and child
4114 // frame RWHVs are unique in that they do not have their own WebContents.
4115 if (!for_main_frame_navigation
) {
4116 RenderWidgetHostViewChildFrame
* rwh_view_child
=
4117 new RenderWidgetHostViewChildFrame(render_view_host
);
4118 rwh_view
= rwh_view_child
;
4120 rwh_view
= view_
->CreateViewForWidget(render_view_host
, false);
4123 // Now that the RenderView has been created, we need to tell it its size.
4125 rwh_view
->SetSize(GetSizeForNewRenderView());
4127 // Make sure we use the correct starting page_id in the new RenderView.
4128 UpdateMaxPageIDIfNecessary(render_view_host
);
4130 GetMaxPageIDForSiteInstance(render_view_host
->GetSiteInstance());
4132 if (!static_cast<RenderViewHostImpl
*>(
4133 render_view_host
)->CreateRenderView(base::string16(),
4137 created_with_opener_
)) {
4141 SetHistoryOffsetAndLengthForView(render_view_host
,
4142 controller_
.GetLastCommittedEntryIndex(),
4143 controller_
.GetEntryCount());
4145 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
4146 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
4147 // linux. See crbug.com/83941.
4149 if (RenderWidgetHost
* render_widget_host
= rwh_view
->GetRenderWidgetHost())
4150 render_widget_host
->WasResized();
4157 bool WebContentsImpl::CreateRenderFrameForRenderManager(
4158 RenderFrameHost
* render_frame_host
,
4159 int parent_routing_id
,
4160 int proxy_routing_id
) {
4161 TRACE_EVENT0("browser,navigation",
4162 "WebContentsImpl::CreateRenderFrameForRenderManager");
4164 RenderFrameHostImpl
* rfh
=
4165 static_cast<RenderFrameHostImpl
*>(render_frame_host
);
4166 if (!rfh
->CreateRenderFrame(parent_routing_id
, proxy_routing_id
))
4169 // TODO(nasko): When RenderWidgetHost is owned by RenderFrameHost, the passed
4170 // RenderFrameHost will have to be associated with the appropriate
4171 // RenderWidgetHostView or a new one should be created here.
4176 #if defined(OS_ANDROID)
4178 base::android::ScopedJavaLocalRef
<jobject
>
4179 WebContentsImpl::GetJavaWebContents() {
4180 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
4181 return GetWebContentsAndroid()->GetJavaObject();
4184 WebContentsAndroid
* WebContentsImpl::GetWebContentsAndroid() {
4185 WebContentsAndroid
* web_contents_android
=
4186 static_cast<WebContentsAndroid
*>(GetUserData(kWebContentsAndroidKey
));
4187 if (!web_contents_android
) {
4188 web_contents_android
= new WebContentsAndroid(this);
4189 SetUserData(kWebContentsAndroidKey
, web_contents_android
);
4191 return web_contents_android
;
4194 bool WebContentsImpl::CreateRenderViewForInitialEmptyDocument() {
4195 return CreateRenderViewForRenderManager(GetRenderViewHost(),
4201 #elif defined(OS_MACOSX)
4203 void WebContentsImpl::SetAllowOtherViews(bool allow
) {
4204 view_
->SetAllowOtherViews(allow
);
4207 bool WebContentsImpl::GetAllowOtherViews() {
4208 return view_
->GetAllowOtherViews();
4213 void WebContentsImpl::OnDialogClosed(int render_process_id
,
4214 int render_frame_id
,
4215 IPC::Message
* reply_msg
,
4216 bool dialog_was_suppressed
,
4218 const base::string16
& user_input
) {
4219 RenderFrameHostImpl
* rfh
= RenderFrameHostImpl::FromID(render_process_id
,
4221 last_dialog_suppressed_
= dialog_was_suppressed
;
4223 if (is_showing_before_unload_dialog_
&& !success
) {
4224 // If a beforeunload dialog is canceled, we need to stop the throbber from
4225 // spinning, since we forced it to start spinning in Navigate.
4227 DidStopLoading(rfh
);
4228 controller_
.DiscardNonCommittedEntries();
4230 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
4231 BeforeUnloadDialogCancelled());
4234 is_showing_before_unload_dialog_
= false;
4236 rfh
->JavaScriptDialogClosed(reply_msg
, success
, user_input
,
4237 dialog_was_suppressed
);
4239 // Don't leak the sync IPC reply if the RFH or process is gone.
4244 void WebContentsImpl::SetEncoding(const std::string
& encoding
) {
4245 if (encoding
== last_reported_encoding_
)
4247 last_reported_encoding_
= encoding
;
4249 canonical_encoding_
= GetContentClient()->browser()->
4250 GetCanonicalEncodingNameByAliasName(encoding
);
4253 bool WebContentsImpl::IsHidden() {
4254 return capturer_count_
== 0 && !should_normally_be_visible_
;
4257 RenderFrameHostManager
* WebContentsImpl::GetRenderManager() const {
4258 return frame_tree_
.root()->render_manager();
4261 RenderViewHostImpl
* WebContentsImpl::GetRenderViewHostImpl() {
4262 return static_cast<RenderViewHostImpl
*>(GetRenderViewHost());
4265 BrowserPluginGuest
* WebContentsImpl::GetBrowserPluginGuest() const {
4266 return browser_plugin_guest_
.get();
4269 void WebContentsImpl::SetBrowserPluginGuest(BrowserPluginGuest
* guest
) {
4270 CHECK(!browser_plugin_guest_
);
4271 browser_plugin_guest_
.reset(guest
);
4274 BrowserPluginEmbedder
* WebContentsImpl::GetBrowserPluginEmbedder() const {
4275 return browser_plugin_embedder_
.get();
4278 void WebContentsImpl::ClearPowerSaveBlockers(
4279 RenderFrameHost
* render_frame_host
) {
4280 RemoveAllMediaPlayerEntries(render_frame_host
, &active_audio_players_
);
4281 RemoveAllMediaPlayerEntries(render_frame_host
, &active_video_players_
);
4282 MaybeReleasePowerSaveBlockers();
4285 void WebContentsImpl::ClearAllPowerSaveBlockers() {
4286 active_audio_players_
.clear();
4287 active_video_players_
.clear();
4288 audio_power_save_blocker_
.reset();
4289 video_power_save_blocker_
.reset();
4292 gfx::Size
WebContentsImpl::GetSizeForNewRenderView() {
4295 size
= delegate_
->GetSizeForNewRenderView(this);
4297 size
= GetContainerBounds().size();
4301 void WebContentsImpl::OnFrameRemoved(RenderFrameHost
* render_frame_host
) {
4303 WebContentsObserver
, observers_
, FrameDetached(render_frame_host
));
4306 void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size
& old_size
) {
4309 const gfx::Size new_size
= GetPreferredSize();
4310 if (new_size
!= old_size
)
4311 delegate_
->UpdatePreferredSize(this, new_size
);
4314 void WebContentsImpl::AddMediaPlayerEntry(int64 player_cookie
,
4315 ActiveMediaPlayerMap
* player_map
) {
4316 const uintptr_t key
=
4317 reinterpret_cast<uintptr_t>(render_frame_message_source_
);
4318 DCHECK(std::find((*player_map
)[key
].begin(),
4319 (*player_map
)[key
].end(),
4320 player_cookie
) == (*player_map
)[key
].end());
4321 (*player_map
)[key
].push_back(player_cookie
);
4324 void WebContentsImpl::RemoveMediaPlayerEntry(int64 player_cookie
,
4325 ActiveMediaPlayerMap
* player_map
) {
4326 const uintptr_t key
=
4327 reinterpret_cast<uintptr_t>(render_frame_message_source_
);
4328 ActiveMediaPlayerMap::iterator it
= player_map
->find(key
);
4329 if (it
== player_map
->end())
4332 // Remove the player.
4333 PlayerList::iterator player_it
=
4334 std::find(it
->second
.begin(), it
->second
.end(), player_cookie
);
4335 if (player_it
!= it
->second
.end())
4336 it
->second
.erase(player_it
);
4338 // If there are no players left, remove the map entry.
4339 if (it
->second
.empty())
4340 player_map
->erase(it
);
4343 void WebContentsImpl::RemoveAllMediaPlayerEntries(
4344 RenderFrameHost
* render_frame_host
,
4345 ActiveMediaPlayerMap
* player_map
) {
4346 ActiveMediaPlayerMap::iterator it
=
4347 player_map
->find(reinterpret_cast<uintptr_t>(render_frame_host
));
4348 if (it
== player_map
->end())
4350 player_map
->erase(it
);
4353 void WebContentsImpl::ResumeResponseDeferredAtStart() {
4354 FrameTreeNode
* node
= frame_tree_
.root();
4355 node
->render_manager()->ResumeResponseDeferredAtStart();
4358 void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable
) {
4359 force_disable_overscroll_content_
= force_disable
;
4361 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
4364 } // namespace content