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/render_view_devtools_agent_host.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_dispatcher_host.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/media/midi_dispatcher_host.h"
45 #include "content/browser/message_port_message_filter.h"
46 #include "content/browser/message_port_service.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/content_view_core_impl.h"
108 #include "content/browser/android/date_time_chooser_android.h"
109 #include "content/browser/media/android/browser_media_player_manager.h"
110 #include "content/browser/web_contents/web_contents_android.h"
111 #include "content/public/browser/android/content_view_core.h"
114 #if defined(OS_MACOSX)
115 #include "base/mac/foundation_util.h"
118 // Cross-Site Navigations
120 // If a WebContentsImpl is told to navigate to a different web site (as
121 // determined by SiteInstance), it will replace its current RenderViewHost with
122 // a new RenderViewHost dedicated to the new SiteInstance. This works as
125 // - RVHM::Navigate determines whether the destination is cross-site, and if so,
126 // it creates a pending_render_view_host_.
127 // - The pending RVH is "suspended," so that no navigation messages are sent to
128 // its renderer until the beforeunload JavaScript handler has a chance to
129 // run in the current RVH.
130 // - The pending RVH tells CrossSiteRequestManager (a thread-safe singleton)
131 // that it has a pending cross-site request. We will check this on the IO
132 // thread when deciding how to handle the response.
133 // - The current RVH runs its beforeunload handler. If it returns false, we
134 // cancel all the pending logic. Otherwise we allow the pending RVH to send
135 // the navigation request to its renderer.
136 // - ResourceDispatcherHost receives a ResourceRequest on the IO thread for the
137 // main resource load on the pending RVH. It creates a
138 // CrossSiteResourceHandler to check whether a process swap is needed when
139 // the request is ready to commit.
140 // - When RDH receives a response, the BufferedResourceHandler determines
141 // whether it is a download. If so, it sends a message to the new renderer
142 // causing it to cancel the request, and the download proceeds. For now, the
143 // pending RVH remains until the next DidNavigate event for this
144 // WebContentsImpl. This isn't ideal, but it doesn't affect any functionality.
145 // - After RDH receives a response and determines that it is safe and not a
146 // download, the CrossSiteResourceHandler checks whether a process swap is
147 // needed (either because CrossSiteRequestManager has state for it or because
148 // a transfer was needed for a redirect).
149 // - If so, CrossSiteResourceHandler pauses the response to first run the old
150 // page's unload handler. It does this by asynchronously calling the
151 // OnCrossSiteResponse method of RenderFrameHostManager on the UI thread,
152 // which sends a SwapOut message to the current RVH.
153 // - Once the unload handler is finished, RVHM::SwappedOut checks if a transfer
154 // to a new process is needed, based on the stored pending_nav_params_. (This
155 // is independent of whether we started out with a cross-process navigation.)
156 // - If not, it just tells the ResourceDispatcherHost to resume the response
157 // to its current RenderViewHost.
158 // - If so, it cancels the current pending RenderViewHost and sets up a new
159 // navigation using RequestTransferURL. When the transferred request
160 // arrives in the ResourceDispatcherHost, we transfer the response and
162 // - The pending renderer sends a FrameNavigate message that invokes the
163 // DidNavigate method. This replaces the current RVH with the
165 // - The previous renderer is kept swapped out in RenderFrameHostManager in case
166 // the user goes back. The process only stays live if another tab is using
167 // it, but if so, the existing frame relationships will be maintained.
172 const int kMinimumDelayBetweenLoadingUpdatesMS
= 100;
174 // This matches what Blink's ProgressTracker has traditionally used for a
175 // minimum progress value.
176 const double kMinimumLoadingProgress
= 0.1;
178 const char kDotGoogleDotCom
[] = ".google.com";
180 #if defined(OS_ANDROID)
181 const char kWebContentsAndroidKey
[] = "web_contents_android";
184 base::LazyInstance
<std::vector
<WebContentsImpl::CreatedCallback
> >
185 g_created_callbacks
= LAZY_INSTANCE_INITIALIZER
;
187 static int StartDownload(RenderFrameHost
* rfh
,
190 uint32_t max_bitmap_size
) {
191 static int g_next_image_download_id
= 0;
192 rfh
->Send(new ImageMsg_DownloadImage(rfh
->GetRoutingID(),
193 ++g_next_image_download_id
,
197 return g_next_image_download_id
;
200 void NotifyCacheOnIO(
201 scoped_refptr
<net::URLRequestContextGetter
> request_context
,
203 const std::string
& http_method
) {
204 request_context
->GetURLRequestContext()->http_transaction_factory()->
205 GetCache()->OnExternalCacheHit(url
, http_method
);
208 // Helper function for retrieving all the sites in a frame tree.
209 bool CollectSites(BrowserContext
* context
,
210 std::set
<GURL
>* sites
,
211 FrameTreeNode
* node
) {
212 sites
->insert(SiteInstance::GetSiteForURL(context
, node
->current_url()));
216 bool ForEachFrameInternal(
217 const base::Callback
<void(RenderFrameHost
*)>& on_frame
,
218 FrameTreeNode
* node
) {
219 on_frame
.Run(node
->current_frame_host());
223 bool ForEachPendingFrameInternal(
224 const base::Callback
<void(RenderFrameHost
*)>& on_frame
,
225 FrameTreeNode
* node
) {
226 RenderFrameHost
* pending_frame_host
=
227 node
->render_manager()->pending_frame_host();
228 if (pending_frame_host
)
229 on_frame
.Run(pending_frame_host
);
233 void SendToAllFramesInternal(IPC::Message
* message
, RenderFrameHost
* rfh
) {
234 IPC::Message
* message_copy
= new IPC::Message(*message
);
235 message_copy
->set_routing_id(rfh
->GetRoutingID());
236 rfh
->Send(message_copy
);
239 void AddRenderWidgetHostViewToSet(std::set
<RenderWidgetHostView
*>* set
,
240 RenderFrameHost
* rfh
) {
241 RenderWidgetHostView
* rwhv
= static_cast<RenderFrameHostImpl
*>(rfh
)
244 ->GetRenderWidgetHostView();
248 void SetAccessibilityModeOnFrame(AccessibilityMode mode
,
249 RenderFrameHost
* frame_host
) {
250 static_cast<RenderFrameHostImpl
*>(frame_host
)->SetAccessibilityMode(mode
);
255 WebContents
* WebContents::Create(const WebContents::CreateParams
& params
) {
256 return WebContentsImpl::CreateWithOpener(
257 params
, static_cast<WebContentsImpl
*>(params
.opener
));
260 WebContents
* WebContents::CreateWithSessionStorage(
261 const WebContents::CreateParams
& params
,
262 const SessionStorageNamespaceMap
& session_storage_namespace_map
) {
263 WebContentsImpl
* new_contents
= new WebContentsImpl(
264 params
.browser_context
, NULL
);
266 for (SessionStorageNamespaceMap::const_iterator it
=
267 session_storage_namespace_map
.begin();
268 it
!= session_storage_namespace_map
.end();
270 new_contents
->GetController()
271 .SetSessionStorageNamespace(it
->first
, it
->second
.get());
274 new_contents
->Init(params
);
278 void WebContentsImpl::AddCreatedCallback(const CreatedCallback
& callback
) {
279 g_created_callbacks
.Get().push_back(callback
);
282 void WebContentsImpl::RemoveCreatedCallback(const CreatedCallback
& callback
) {
283 for (size_t i
= 0; i
< g_created_callbacks
.Get().size(); ++i
) {
284 if (g_created_callbacks
.Get().at(i
).Equals(callback
)) {
285 g_created_callbacks
.Get().erase(g_created_callbacks
.Get().begin() + i
);
291 WebContents
* WebContents::FromRenderViewHost(const RenderViewHost
* rvh
) {
292 return rvh
->GetDelegate()->GetAsWebContents();
295 WebContents
* WebContents::FromRenderFrameHost(RenderFrameHost
* rfh
) {
296 RenderFrameHostImpl
* rfh_impl
= static_cast<RenderFrameHostImpl
*>(rfh
);
299 return rfh_impl
->delegate()->GetAsWebContents();
302 // WebContentsImpl::DestructionObserver ----------------------------------------
304 class WebContentsImpl::DestructionObserver
: public WebContentsObserver
{
306 DestructionObserver(WebContentsImpl
* owner
, WebContents
* watched_contents
)
307 : WebContentsObserver(watched_contents
),
311 // WebContentsObserver:
312 virtual void WebContentsDestroyed() OVERRIDE
{
313 owner_
->OnWebContentsDestroyed(
314 static_cast<WebContentsImpl
*>(web_contents()));
318 WebContentsImpl
* owner_
;
320 DISALLOW_COPY_AND_ASSIGN(DestructionObserver
);
323 WebContentsImpl::ColorChooserInfo::ColorChooserInfo(int render_process_id
,
325 ColorChooser
* chooser
,
327 : render_process_id(render_process_id
),
328 render_frame_id(render_frame_id
),
330 identifier(identifier
) {
333 WebContentsImpl::ColorChooserInfo::~ColorChooserInfo() {
336 // WebContentsImpl -------------------------------------------------------------
338 WebContentsImpl::WebContentsImpl(
339 BrowserContext
* browser_context
,
340 WebContentsImpl
* opener
)
342 controller_(this, browser_context
),
343 render_view_host_delegate_view_(NULL
),
345 created_with_opener_(!!opener
),
347 accessible_parent_(NULL
),
349 frame_tree_(new NavigatorImpl(&controller_
, this),
350 this, this, this, this),
352 is_load_to_different_document_(false),
353 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING
),
354 crashed_error_code_(0),
355 waiting_for_response_(false),
356 load_state_(net::LOAD_STATE_IDLE
, base::string16()),
357 loading_total_progress_(0.0),
358 loading_frames_in_progress_(0),
361 displayed_insecure_content_(false),
362 has_accessed_initial_document_(false),
364 should_normally_be_visible_(true),
365 is_being_destroyed_(false),
366 notify_disconnection_(false),
367 dialog_manager_(NULL
),
368 is_showing_before_unload_dialog_(false),
369 last_active_time_(base::TimeTicks::Now()),
370 closed_by_user_gesture_(false),
371 minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor
* 100)),
372 maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor
* 100)),
373 totalPinchGestureAmount_(0),
374 currentPinchZoomStepDelta_(0),
375 render_view_message_source_(NULL
),
376 fullscreen_widget_routing_id_(MSG_ROUTING_NONE
),
377 fullscreen_widget_had_focus_at_shutdown_(false),
379 force_disable_overscroll_content_(false),
380 last_dialog_suppressed_(false),
382 BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()),
383 audio_stream_monitor_(this),
384 loading_weak_factory_(this) {
385 for (size_t i
= 0; i
< g_created_callbacks
.Get().size(); i
++)
386 g_created_callbacks
.Get().at(i
).Run(this);
387 frame_tree_
.SetFrameRemoveListener(
388 base::Bind(&WebContentsImpl::OnFrameRemoved
,
389 base::Unretained(this)));
392 WebContentsImpl::~WebContentsImpl() {
393 is_being_destroyed_
= true;
395 // Delete all RFH pending shutdown, which will lead the corresponding RVH to
396 // shutdown and be deleted as well.
398 base::Bind(&RenderFrameHostManager::ClearRFHsPendingShutdown
));
400 ClearAllPowerSaveBlockers();
402 for (std::set
<RenderWidgetHostImpl
*>::iterator iter
=
403 created_widgets_
.begin(); iter
!= created_widgets_
.end(); ++iter
) {
404 (*iter
)->DetachDelegate();
406 created_widgets_
.clear();
408 // Clear out any JavaScript state.
410 dialog_manager_
->WebContentsDestroyed(this);
412 if (color_chooser_info_
.get())
413 color_chooser_info_
->chooser
->End();
415 NotifyDisconnected();
417 // Notify any observer that have a reference on this WebContents.
418 NotificationService::current()->Notify(
419 NOTIFICATION_WEB_CONTENTS_DESTROYED
,
420 Source
<WebContents
>(this),
421 NotificationService::NoDetails());
423 // Destroy all frame tree nodes except for the root; this notifies observers.
424 frame_tree_
.ResetForMainFrameSwap();
425 GetRenderManager()->ResetProxyHosts();
427 // Manually call the observer methods for the root frame tree node.
428 RenderFrameHostManager
* root
= GetRenderManager();
429 if (root
->pending_frame_host()) {
430 FOR_EACH_OBSERVER(WebContentsObserver
,
432 RenderFrameDeleted(root
->pending_frame_host()));
434 FOR_EACH_OBSERVER(WebContentsObserver
,
436 RenderFrameDeleted(root
->current_frame_host()));
438 if (root
->pending_render_view_host()) {
439 FOR_EACH_OBSERVER(WebContentsObserver
,
441 RenderViewDeleted(root
->pending_render_view_host()));
444 FOR_EACH_OBSERVER(WebContentsObserver
,
446 RenderViewDeleted(root
->current_host()));
448 FOR_EACH_OBSERVER(WebContentsObserver
,
450 WebContentsDestroyed());
452 FOR_EACH_OBSERVER(WebContentsObserver
,
458 STLDeleteContainerPairSecondPointers(destruction_observers_
.begin(),
459 destruction_observers_
.end());
462 WebContentsImpl
* WebContentsImpl::CreateWithOpener(
463 const WebContents::CreateParams
& params
,
464 WebContentsImpl
* opener
) {
465 TRACE_EVENT0("browser", "WebContentsImpl::CreateWithOpener");
466 WebContentsImpl
* new_contents
= new WebContentsImpl(
467 params
.browser_context
, params
.opener_suppressed
? NULL
: opener
);
469 if (params
.guest_delegate
) {
470 // This makes |new_contents| act as a guest.
471 // For more info, see comment above class BrowserPluginGuest.
472 BrowserPluginGuest::Create(new_contents
, params
.guest_delegate
);
473 // We are instantiating a WebContents for browser plugin. Set its subframe
475 new_contents
->is_subframe_
= true;
477 new_contents
->Init(params
);
482 std::vector
<WebContentsImpl
*> WebContentsImpl::GetAllWebContents() {
483 std::vector
<WebContentsImpl
*> result
;
484 scoped_ptr
<RenderWidgetHostIterator
> widgets(
485 RenderWidgetHostImpl::GetRenderWidgetHosts());
486 std::set
<WebContentsImpl
*> web_contents_set
;
487 while (RenderWidgetHost
* rwh
= widgets
->GetNextHost()) {
488 if (!rwh
->IsRenderView())
490 RenderViewHost
* rvh
= RenderViewHost::From(rwh
);
493 WebContents
* web_contents
= WebContents::FromRenderViewHost(rvh
);
496 WebContentsImpl
* wci
= static_cast<WebContentsImpl
*>(web_contents
);
497 if (web_contents_set
.find(wci
) == web_contents_set
.end()) {
498 web_contents_set
.insert(wci
);
499 result
.push_back(wci
);
505 RenderFrameHostManager
* WebContentsImpl::GetRenderManagerForTesting() {
506 return GetRenderManager();
509 bool WebContentsImpl::OnMessageReceived(RenderViewHost
* render_view_host
,
510 const IPC::Message
& message
) {
511 return OnMessageReceived(render_view_host
, NULL
, message
);
514 bool WebContentsImpl::OnMessageReceived(RenderViewHost
* render_view_host
,
515 RenderFrameHost
* render_frame_host
,
516 const IPC::Message
& message
) {
517 DCHECK(render_view_host
|| render_frame_host
);
519 static_cast<WebUIImpl
*>(GetWebUI())->OnMessageReceived(message
)) {
523 ObserverListBase
<WebContentsObserver
>::Iterator
it(observers_
);
524 WebContentsObserver
* observer
;
525 if (render_frame_host
) {
526 while ((observer
= it
.GetNext()) != NULL
)
527 if (observer
->OnMessageReceived(message
, render_frame_host
))
530 while ((observer
= it
.GetNext()) != NULL
)
531 if (observer
->OnMessageReceived(message
))
535 // Message handlers should be aware of which
536 // RenderViewHost/RenderFrameHost sent the message, which is temporarily
537 // stored in render_(view|frame)_message_source_.
538 if (render_frame_host
)
539 render_frame_message_source_
= render_frame_host
;
541 render_view_message_source_
= render_view_host
;
544 IPC_BEGIN_MESSAGE_MAP(WebContentsImpl
, message
)
545 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung
, OnPepperPluginHung
)
546 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed
, OnPluginCrashed
)
547 IPC_MESSAGE_HANDLER(FrameHostMsg_DomOperationResponse
,
548 OnDomOperationResponse
)
549 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeThemeColor
,
551 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishDocumentLoad
,
552 OnDocumentLoadedInFrame
)
553 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishLoad
, OnDidFinishLoad
)
554 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartLoading
, OnDidStartLoading
)
555 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading
, OnDidStopLoading
)
556 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress
,
557 OnDidChangeLoadProgress
)
558 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenColorChooser
, OnOpenColorChooser
)
559 IPC_MESSAGE_HANDLER(FrameHostMsg_EndColorChooser
, OnEndColorChooser
)
560 IPC_MESSAGE_HANDLER(FrameHostMsg_SetSelectedColorInColorChooser
,
561 OnSetSelectedColorInColorChooser
)
562 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPlayingNotification
,
563 OnMediaPlayingNotification
)
564 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPausedNotification
,
565 OnMediaPausedNotification
)
566 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFirstVisuallyNonEmptyPaint
,
567 OnFirstVisuallyNonEmptyPaint
)
568 IPC_MESSAGE_HANDLER(ViewHostMsg_DidLoadResourceFromMemoryCache
,
569 OnDidLoadResourceFromMemoryCache
)
570 IPC_MESSAGE_HANDLER(ViewHostMsg_DidDisplayInsecureContent
,
571 OnDidDisplayInsecureContent
)
572 IPC_MESSAGE_HANDLER(ViewHostMsg_DidRunInsecureContent
,
573 OnDidRunInsecureContent
)
574 IPC_MESSAGE_HANDLER(ViewHostMsg_GoToEntryAtOffset
, OnGoToEntryAtOffset
)
575 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateZoomLimits
, OnUpdateZoomLimits
)
576 IPC_MESSAGE_HANDLER(ViewHostMsg_EnumerateDirectory
, OnEnumerateDirectory
)
577 IPC_MESSAGE_HANDLER(ViewHostMsg_RegisterProtocolHandler
,
578 OnRegisterProtocolHandler
)
579 IPC_MESSAGE_HANDLER(ViewHostMsg_UnregisterProtocolHandler
,
580 OnUnregisterProtocolHandler
)
581 IPC_MESSAGE_HANDLER(ViewHostMsg_Find_Reply
, OnFindReply
)
582 IPC_MESSAGE_HANDLER(ViewHostMsg_AppCacheAccessed
, OnAppCacheAccessed
)
583 IPC_MESSAGE_HANDLER(ViewHostMsg_WebUISend
, OnWebUISend
)
584 #if defined(ENABLE_PLUGINS)
585 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission
,
586 OnRequestPpapiBrokerPermission
)
587 IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_Attach
,
588 OnBrowserPluginMessage(message
))
590 IPC_MESSAGE_HANDLER(ImageHostMsg_DidDownloadImage
, OnDidDownloadImage
)
591 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateFaviconURL
, OnUpdateFaviconURL
)
592 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowValidationMessage
,
593 OnShowValidationMessage
)
594 IPC_MESSAGE_HANDLER(ViewHostMsg_HideValidationMessage
,
595 OnHideValidationMessage
)
596 IPC_MESSAGE_HANDLER(ViewHostMsg_MoveValidationMessage
,
597 OnMoveValidationMessage
)
598 #if defined(OS_ANDROID)
599 IPC_MESSAGE_HANDLER(ViewHostMsg_FindMatchRects_Reply
,
600 OnFindMatchRectsReply
)
601 IPC_MESSAGE_HANDLER(ViewHostMsg_OpenDateTimeDialog
,
602 OnOpenDateTimeDialog
)
604 IPC_MESSAGE_UNHANDLED(handled
= false)
605 IPC_END_MESSAGE_MAP()
606 render_view_message_source_
= NULL
;
607 render_frame_message_source_
= NULL
;
612 void WebContentsImpl::RunFileChooser(
613 RenderViewHost
* render_view_host
,
614 const FileChooserParams
& params
) {
616 delegate_
->RunFileChooser(this, params
);
619 NavigationControllerImpl
& WebContentsImpl::GetController() {
623 const NavigationControllerImpl
& WebContentsImpl::GetController() const {
627 BrowserContext
* WebContentsImpl::GetBrowserContext() const {
628 return controller_
.GetBrowserContext();
631 const GURL
& WebContentsImpl::GetURL() const {
632 // We may not have a navigation entry yet.
633 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
634 return entry
? entry
->GetVirtualURL() : GURL::EmptyGURL();
637 const GURL
& WebContentsImpl::GetVisibleURL() const {
638 // We may not have a navigation entry yet.
639 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
640 return entry
? entry
->GetVirtualURL() : GURL::EmptyGURL();
643 const GURL
& WebContentsImpl::GetLastCommittedURL() const {
644 // We may not have a navigation entry yet.
645 NavigationEntry
* entry
= controller_
.GetLastCommittedEntry();
646 return entry
? entry
->GetVirtualURL() : GURL::EmptyGURL();
649 WebContentsDelegate
* WebContentsImpl::GetDelegate() {
653 void WebContentsImpl::SetDelegate(WebContentsDelegate
* delegate
) {
654 // TODO(cbentzel): remove this debugging code?
655 if (delegate
== delegate_
)
658 delegate_
->Detach(this);
659 delegate_
= delegate
;
661 delegate_
->Attach(this);
662 // Ensure the visible RVH reflects the new delegate's preferences.
664 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
668 RenderProcessHost
* WebContentsImpl::GetRenderProcessHost() const {
669 RenderViewHostImpl
* host
= GetRenderManager()->current_host();
670 return host
? host
->GetProcess() : NULL
;
673 RenderFrameHost
* WebContentsImpl::GetMainFrame() {
674 return frame_tree_
.root()->current_frame_host();
677 RenderFrameHost
* WebContentsImpl::GetFocusedFrame() {
678 if (!frame_tree_
.GetFocusedFrame())
680 return frame_tree_
.GetFocusedFrame()->current_frame_host();
683 void WebContentsImpl::ForEachFrame(
684 const base::Callback
<void(RenderFrameHost
*)>& on_frame
) {
685 frame_tree_
.ForEach(base::Bind(&ForEachFrameInternal
, on_frame
));
688 void WebContentsImpl::SendToAllFrames(IPC::Message
* message
) {
689 ForEachFrame(base::Bind(&SendToAllFramesInternal
, message
));
693 RenderViewHost
* WebContentsImpl::GetRenderViewHost() const {
694 return GetRenderManager()->current_host();
697 int WebContentsImpl::GetRoutingID() const {
698 if (!GetRenderViewHost())
699 return MSG_ROUTING_NONE
;
701 return GetRenderViewHost()->GetRoutingID();
704 int WebContentsImpl::GetFullscreenWidgetRoutingID() const {
705 return fullscreen_widget_routing_id_
;
708 RenderWidgetHostView
* WebContentsImpl::GetRenderWidgetHostView() const {
709 return GetRenderManager()->GetRenderWidgetHostView();
712 RenderWidgetHostView
* WebContentsImpl::GetFullscreenRenderWidgetHostView()
714 RenderWidgetHost
* const widget_host
=
715 RenderWidgetHostImpl::FromID(GetRenderProcessHost()->GetID(),
716 GetFullscreenWidgetRoutingID());
717 return widget_host
? widget_host
->GetView() : NULL
;
720 WebContentsView
* WebContentsImpl::GetView() const {
724 void WebContentsImpl::SetAccessibilityMode(AccessibilityMode mode
) {
725 if (mode
== accessibility_mode_
)
728 accessibility_mode_
= mode
;
730 base::Bind(&ForEachFrameInternal
,
731 base::Bind(&SetAccessibilityModeOnFrame
, mode
)));
733 base::Bind(&ForEachPendingFrameInternal
,
734 base::Bind(&SetAccessibilityModeOnFrame
, mode
)));
737 void WebContentsImpl::AddAccessibilityMode(AccessibilityMode mode
) {
738 SetAccessibilityMode(AddAccessibilityModeTo(accessibility_mode_
, mode
));
741 void WebContentsImpl::RemoveAccessibilityMode(AccessibilityMode mode
) {
742 SetAccessibilityMode(RemoveAccessibilityModeFrom(accessibility_mode_
, mode
));
745 WebUI
* WebContentsImpl::CreateWebUI(const GURL
& url
) {
746 WebUIImpl
* web_ui
= new WebUIImpl(this);
747 WebUIController
* controller
= WebUIControllerFactoryRegistry::GetInstance()->
748 CreateWebUIControllerForURL(web_ui
, url
);
750 web_ui
->AddMessageHandler(new GenericHandler());
751 web_ui
->SetController(controller
);
759 WebUI
* WebContentsImpl::GetWebUI() const {
760 return GetRenderManager()->web_ui() ? GetRenderManager()->web_ui()
761 : GetRenderManager()->pending_web_ui();
764 WebUI
* WebContentsImpl::GetCommittedWebUI() const {
765 return GetRenderManager()->web_ui();
768 void WebContentsImpl::SetUserAgentOverride(const std::string
& override
) {
769 if (GetUserAgentOverride() == override
)
772 renderer_preferences_
.user_agent_override
= override
;
774 // Send the new override string to the renderer.
775 RenderViewHost
* host
= GetRenderViewHost();
777 host
->SyncRendererPrefs();
779 // Reload the page if a load is currently in progress to avoid having
780 // different parts of the page loaded using different user agents.
781 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
782 if (is_loading_
&& entry
!= NULL
&& entry
->GetIsOverridingUserAgent())
783 controller_
.ReloadIgnoringCache(true);
785 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
786 UserAgentOverrideSet(override
));
789 const std::string
& WebContentsImpl::GetUserAgentOverride() const {
790 return renderer_preferences_
.user_agent_override
;
793 void WebContentsImpl::EnableTreeOnlyAccessibilityMode() {
794 AddAccessibilityMode(AccessibilityModeTreeOnly
);
797 bool WebContentsImpl::IsTreeOnlyAccessibilityModeForTesting() const {
798 return accessibility_mode_
== AccessibilityModeTreeOnly
;
801 bool WebContentsImpl::IsFullAccessibilityModeForTesting() const {
802 return accessibility_mode_
== AccessibilityModeComplete
;
806 void WebContentsImpl::SetParentNativeViewAccessible(
807 gfx::NativeViewAccessible accessible_parent
) {
808 accessible_parent_
= accessible_parent
;
809 RenderFrameHostImpl
* rfh
= static_cast<RenderFrameHostImpl
*>(GetMainFrame());
811 rfh
->SetParentNativeViewAccessible(accessible_parent
);
815 const base::string16
& WebContentsImpl::GetTitle() const {
816 // Transient entries take precedence. They are used for interstitial pages
817 // that are shown on top of existing pages.
818 NavigationEntry
* entry
= controller_
.GetTransientEntry();
819 std::string accept_languages
=
820 GetContentClient()->browser()->GetAcceptLangs(
821 GetBrowserContext());
823 return entry
->GetTitleForDisplay(accept_languages
);
825 WebUI
* our_web_ui
= GetRenderManager()->pending_web_ui() ?
826 GetRenderManager()->pending_web_ui() : GetRenderManager()->web_ui();
828 // Don't override the title in view source mode.
829 entry
= controller_
.GetVisibleEntry();
830 if (!(entry
&& entry
->IsViewSourceMode())) {
831 // Give the Web UI the chance to override our title.
832 const base::string16
& title
= our_web_ui
->GetOverriddenTitle();
838 // We use the title for the last committed entry rather than a pending
839 // navigation entry. For example, when the user types in a URL, we want to
840 // keep the old page's title until the new load has committed and we get a new
842 entry
= controller_
.GetLastCommittedEntry();
844 // We make an exception for initial navigations.
845 if (controller_
.IsInitialNavigation()) {
846 // We only want to use the title from the visible entry in one of two cases:
847 // 1. There's already a committed entry for an initial navigation, in which
848 // case we are doing a history navigation in a new tab (e.g., Ctrl+Back).
849 // 2. The pending entry has been explicitly assigned a title to display.
851 // If there's no last committed entry and no assigned title, we should fall
852 // back to |page_title_when_no_navigation_entry_| rather than showing the
855 (controller_
.GetVisibleEntry() &&
856 !controller_
.GetVisibleEntry()->GetTitle().empty())) {
857 entry
= controller_
.GetVisibleEntry();
862 return entry
->GetTitleForDisplay(accept_languages
);
865 // |page_title_when_no_navigation_entry_| is finally used
866 // if no title cannot be retrieved.
867 return page_title_when_no_navigation_entry_
;
870 int32
WebContentsImpl::GetMaxPageID() {
871 return GetMaxPageIDForSiteInstance(GetSiteInstance());
874 int32
WebContentsImpl::GetMaxPageIDForSiteInstance(
875 SiteInstance
* site_instance
) {
876 if (max_page_ids_
.find(site_instance
->GetId()) == max_page_ids_
.end())
877 max_page_ids_
[site_instance
->GetId()] = -1;
879 return max_page_ids_
[site_instance
->GetId()];
882 void WebContentsImpl::UpdateMaxPageID(int32 page_id
) {
883 UpdateMaxPageIDForSiteInstance(GetSiteInstance(), page_id
);
886 void WebContentsImpl::UpdateMaxPageIDForSiteInstance(
887 SiteInstance
* site_instance
, int32 page_id
) {
888 if (GetMaxPageIDForSiteInstance(site_instance
) < page_id
)
889 max_page_ids_
[site_instance
->GetId()] = page_id
;
892 void WebContentsImpl::CopyMaxPageIDsFrom(WebContents
* web_contents
) {
893 WebContentsImpl
* contents
= static_cast<WebContentsImpl
*>(web_contents
);
894 max_page_ids_
= contents
->max_page_ids_
;
897 SiteInstance
* WebContentsImpl::GetSiteInstance() const {
898 return GetRenderManager()->current_host()->GetSiteInstance();
901 SiteInstance
* WebContentsImpl::GetPendingSiteInstance() const {
902 RenderViewHost
* dest_rvh
= GetRenderManager()->pending_render_view_host() ?
903 GetRenderManager()->pending_render_view_host() :
904 GetRenderManager()->current_host();
905 return dest_rvh
->GetSiteInstance();
908 bool WebContentsImpl::IsLoading() const {
912 bool WebContentsImpl::IsLoadingToDifferentDocument() const {
913 return is_loading_
&& is_load_to_different_document_
;
916 bool WebContentsImpl::IsWaitingForResponse() const {
917 return waiting_for_response_
&& is_load_to_different_document_
;
920 const net::LoadStateWithParam
& WebContentsImpl::GetLoadState() const {
924 const base::string16
& WebContentsImpl::GetLoadStateHost() const {
925 return load_state_host_
;
928 uint64
WebContentsImpl::GetUploadSize() const {
932 uint64
WebContentsImpl::GetUploadPosition() const {
933 return upload_position_
;
936 std::set
<GURL
> WebContentsImpl::GetSitesInTab() const {
937 std::set
<GURL
> sites
;
938 frame_tree_
.ForEach(base::Bind(&CollectSites
,
939 base::Unretained(GetBrowserContext()),
940 base::Unretained(&sites
)));
944 const std::string
& WebContentsImpl::GetEncoding() const {
945 return canonical_encoding_
;
948 bool WebContentsImpl::DisplayedInsecureContent() const {
949 return displayed_insecure_content_
;
952 void WebContentsImpl::IncrementCapturerCount(const gfx::Size
& capture_size
) {
953 DCHECK(!is_being_destroyed_
);
955 DVLOG(1) << "There are now " << capturer_count_
956 << " capturing(s) of WebContentsImpl@" << this;
958 // Note: This provides a hint to upstream code to size the views optimally
959 // for quality (e.g., to avoid scaling).
960 if (!capture_size
.IsEmpty() && preferred_size_for_capture_
.IsEmpty()) {
961 preferred_size_for_capture_
= capture_size
;
962 OnPreferredSizeChanged(preferred_size_
);
966 void WebContentsImpl::DecrementCapturerCount() {
968 DVLOG(1) << "There are now " << capturer_count_
969 << " capturing(s) of WebContentsImpl@" << this;
970 DCHECK_LE(0, capturer_count_
);
972 if (is_being_destroyed_
)
975 if (capturer_count_
== 0) {
976 const gfx::Size old_size
= preferred_size_for_capture_
;
977 preferred_size_for_capture_
= gfx::Size();
978 OnPreferredSizeChanged(old_size
);
982 DVLOG(1) << "Executing delayed WasHidden().";
987 int WebContentsImpl::GetCapturerCount() const {
988 return capturer_count_
;
991 bool WebContentsImpl::IsAudioMuted() const {
992 return audio_muter_
.get() && audio_muter_
->is_muting();
995 void WebContentsImpl::SetAudioMuted(bool mute
) {
996 DVLOG(1) << "SetAudioMuted(mute=" << mute
<< "), was " << IsAudioMuted()
997 << " for WebContentsImpl@" << this;
999 if (mute
== IsAudioMuted())
1004 audio_muter_
.reset(new WebContentsAudioMuter(this));
1005 audio_muter_
->StartMuting();
1007 DCHECK(audio_muter_
);
1008 audio_muter_
->StopMuting();
1011 // Notification for UI updates in response to the changed muting state.
1012 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB
);
1015 bool WebContentsImpl::IsCrashed() const {
1016 return (crashed_status_
== base::TERMINATION_STATUS_PROCESS_CRASHED
||
1017 crashed_status_
== base::TERMINATION_STATUS_ABNORMAL_TERMINATION
||
1018 crashed_status_
== base::TERMINATION_STATUS_PROCESS_WAS_KILLED
);
1021 void WebContentsImpl::SetIsCrashed(base::TerminationStatus status
,
1023 if (status
== crashed_status_
)
1026 crashed_status_
= status
;
1027 crashed_error_code_
= error_code
;
1028 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB
);
1031 base::TerminationStatus
WebContentsImpl::GetCrashedStatus() const {
1032 return crashed_status_
;
1035 bool WebContentsImpl::IsBeingDestroyed() const {
1036 return is_being_destroyed_
;
1039 void WebContentsImpl::NotifyNavigationStateChanged(
1040 InvalidateTypes changed_flags
) {
1041 // Create and release the audio power save blocker depending on whether the
1042 // tab is actively producing audio or not.
1043 if (changed_flags
== INVALIDATE_TYPE_TAB
&&
1044 AudioStreamMonitor::monitoring_available()) {
1045 if (WasRecentlyAudible()) {
1046 if (!audio_power_save_blocker_
)
1047 CreateAudioPowerSaveBlocker();
1049 audio_power_save_blocker_
.reset();
1054 delegate_
->NavigationStateChanged(this, changed_flags
);
1057 base::TimeTicks
WebContentsImpl::GetLastActiveTime() const {
1058 return last_active_time_
;
1061 void WebContentsImpl::WasShown() {
1062 controller_
.SetActive(true);
1064 std::set
<RenderWidgetHostView
*> widgets
= GetRenderWidgetHostViewsInTree();
1065 for (std::set
<RenderWidgetHostView
*>::iterator iter
= widgets
.begin();
1066 iter
!= widgets
.end();
1070 #if defined(OS_MACOSX)
1071 (*iter
)->SetActive(true);
1076 last_active_time_
= base::TimeTicks::Now();
1078 // The resize rect might have changed while this was inactive -- send the new
1079 // one to make sure it's up to date.
1080 RenderViewHostImpl
* rvh
=
1081 static_cast<RenderViewHostImpl
*>(GetRenderViewHost());
1083 rvh
->ResizeRectChanged(GetRootWindowResizerRect());
1086 // Restore power save blocker if there are active video players running.
1087 if (!active_video_players_
.empty() && !video_power_save_blocker_
)
1088 CreateVideoPowerSaveBlocker();
1090 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, WasShown());
1092 should_normally_be_visible_
= true;
1095 void WebContentsImpl::WasHidden() {
1096 // If there are entities capturing screenshots or video (e.g., mirroring),
1097 // don't activate the "disable rendering" optimization.
1098 if (capturer_count_
== 0) {
1099 // |GetRenderViewHost()| can be NULL if the user middle clicks a link to
1100 // open a tab in the background, then closes the tab before selecting it.
1101 // This is because closing the tab calls WebContentsImpl::Destroy(), which
1102 // removes the |GetRenderViewHost()|; then when we actually destroy the
1103 // window, OnWindowPosChanged() notices and calls WasHidden() (which
1105 std::set
<RenderWidgetHostView
*> widgets
= GetRenderWidgetHostViewsInTree();
1106 for (std::set
<RenderWidgetHostView
*>::iterator iter
= widgets
.begin();
1107 iter
!= widgets
.end();
1113 // Release any video power save blockers held as video is not visible.
1114 video_power_save_blocker_
.reset();
1117 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, WasHidden());
1119 should_normally_be_visible_
= false;
1122 bool WebContentsImpl::NeedToFireBeforeUnload() {
1123 // TODO(creis): Should we fire even for interstitial pages?
1124 return WillNotifyDisconnection() &&
1125 !ShowingInterstitialPage() &&
1126 !static_cast<RenderViewHostImpl
*>(
1127 GetRenderViewHost())->SuddenTerminationAllowed();
1130 void WebContentsImpl::DispatchBeforeUnload(bool for_cross_site_transition
) {
1131 static_cast<RenderFrameHostImpl
*>(GetMainFrame())->DispatchBeforeUnload(
1132 for_cross_site_transition
);
1135 void WebContentsImpl::Stop() {
1136 GetRenderManager()->Stop();
1137 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, NavigationStopped());
1140 WebContents
* WebContentsImpl::Clone() {
1141 // We use our current SiteInstance since the cloned entry will use it anyway.
1142 // We pass our own opener so that the cloned page can access it if it was
1144 CreateParams
create_params(GetBrowserContext(), GetSiteInstance());
1145 create_params
.initial_size
= GetContainerBounds().size();
1146 WebContentsImpl
* tc
= CreateWithOpener(create_params
, opener_
);
1147 tc
->GetController().CopyStateFrom(controller_
);
1148 FOR_EACH_OBSERVER(WebContentsObserver
,
1150 DidCloneToNewWebContents(this, tc
));
1154 void WebContentsImpl::Observe(int type
,
1155 const NotificationSource
& source
,
1156 const NotificationDetails
& details
) {
1158 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED
: {
1159 RenderWidgetHost
* host
= Source
<RenderWidgetHost
>(source
).ptr();
1160 RenderWidgetHostView
* view
= host
->GetView();
1161 if (view
== GetFullscreenRenderWidgetHostView()) {
1162 // We cannot just call view_->RestoreFocus() here. On some platforms,
1163 // attempting to focus the currently-invisible WebContentsView will be
1164 // flat-out ignored. Therefore, this boolean is used to track whether
1165 // we will request focus after the fullscreen widget has been
1167 fullscreen_widget_had_focus_at_shutdown_
= (view
&& view
->HasFocus());
1169 for (PendingWidgetViews::iterator i
= pending_widget_views_
.begin();
1170 i
!= pending_widget_views_
.end(); ++i
) {
1171 if (host
->GetView() == i
->second
) {
1172 pending_widget_views_
.erase(i
);
1184 WebContents
* WebContentsImpl::GetWebContents() {
1188 void WebContentsImpl::Init(const WebContents::CreateParams
& params
) {
1189 // This is set before initializing the render manager since
1190 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
1191 // it should be hidden.
1192 should_normally_be_visible_
= !params
.initially_hidden
;
1194 GetRenderManager()->Init(
1195 params
.browser_context
, params
.site_instance
, params
.routing_id
,
1196 params
.main_frame_routing_id
);
1198 WebContentsViewDelegate
* delegate
=
1199 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
1201 if (browser_plugin_guest_
) {
1202 scoped_ptr
<WebContentsView
> platform_view(CreateWebContentsView(
1203 this, delegate
, &render_view_host_delegate_view_
));
1205 WebContentsViewGuest
* rv
= new WebContentsViewGuest(
1206 this, browser_plugin_guest_
.get(), platform_view
.Pass(),
1207 render_view_host_delegate_view_
);
1208 render_view_host_delegate_view_
= rv
;
1211 // Regular WebContentsView.
1212 view_
.reset(CreateWebContentsView(
1213 this, delegate
, &render_view_host_delegate_view_
));
1215 CHECK(render_view_host_delegate_view_
);
1218 gfx::Size initial_size
= params
.initial_size
;
1219 view_
->CreateView(initial_size
, params
.context
);
1221 // Listen for whether our opener gets destroyed.
1223 AddDestructionObserver(opener_
);
1225 registrar_
.Add(this,
1226 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED
,
1227 NotificationService::AllBrowserContextsAndSources());
1229 geolocation_dispatcher_host_
.reset(new GeolocationDispatcherHost(this));
1230 midi_dispatcher_host_
.reset(new MidiDispatcherHost(this));
1232 screen_orientation_dispatcher_host_
.reset(
1233 new ScreenOrientationDispatcherHostImpl(this));
1235 manifest_manager_host_
.reset(new ManifestManagerHost(this));
1237 #if defined(OS_ANDROID)
1238 date_time_chooser_
.reset(new DateTimeChooserAndroid());
1242 void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl
* web_contents
) {
1243 RemoveDestructionObserver(web_contents
);
1245 // Clear the opener if it has been closed.
1246 if (web_contents
== opener_
) {
1250 // Clear a pending contents that has been closed before being shown.
1251 for (PendingContents::iterator iter
= pending_contents_
.begin();
1252 iter
!= pending_contents_
.end();
1254 if (iter
->second
!= web_contents
)
1256 pending_contents_
.erase(iter
);
1262 void WebContentsImpl::AddDestructionObserver(WebContentsImpl
* web_contents
) {
1263 if (!ContainsKey(destruction_observers_
, web_contents
)) {
1264 destruction_observers_
[web_contents
] =
1265 new DestructionObserver(this, web_contents
);
1269 void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl
* web_contents
) {
1270 DestructionObservers::iterator iter
=
1271 destruction_observers_
.find(web_contents
);
1272 if (iter
!= destruction_observers_
.end()) {
1273 delete destruction_observers_
[web_contents
];
1274 destruction_observers_
.erase(iter
);
1278 void WebContentsImpl::AddObserver(WebContentsObserver
* observer
) {
1279 observers_
.AddObserver(observer
);
1282 void WebContentsImpl::RemoveObserver(WebContentsObserver
* observer
) {
1283 observers_
.RemoveObserver(observer
);
1286 std::set
<RenderWidgetHostView
*>
1287 WebContentsImpl::GetRenderWidgetHostViewsInTree() {
1288 std::set
<RenderWidgetHostView
*> set
;
1289 if (ShowingInterstitialPage()) {
1290 set
.insert(GetRenderWidgetHostView());
1293 base::Bind(&AddRenderWidgetHostViewToSet
, base::Unretained(&set
)));
1298 void WebContentsImpl::Activate() {
1300 delegate_
->ActivateContents(this);
1303 void WebContentsImpl::Deactivate() {
1305 delegate_
->DeactivateContents(this);
1308 void WebContentsImpl::LostCapture() {
1310 delegate_
->LostCapture();
1313 void WebContentsImpl::RenderWidgetDeleted(
1314 RenderWidgetHostImpl
* render_widget_host
) {
1315 if (is_being_destroyed_
) {
1316 // |created_widgets_| might have been destroyed.
1320 std::set
<RenderWidgetHostImpl
*>::iterator iter
=
1321 created_widgets_
.find(render_widget_host
);
1322 if (iter
!= created_widgets_
.end())
1323 created_widgets_
.erase(iter
);
1325 if (render_widget_host
&&
1326 render_widget_host
->GetRoutingID() == fullscreen_widget_routing_id_
) {
1327 if (delegate_
&& delegate_
->EmbedsFullscreenWidget())
1328 delegate_
->ToggleFullscreenModeForTab(this, false);
1329 FOR_EACH_OBSERVER(WebContentsObserver
,
1331 DidDestroyFullscreenWidget(
1332 fullscreen_widget_routing_id_
));
1333 fullscreen_widget_routing_id_
= MSG_ROUTING_NONE
;
1334 if (fullscreen_widget_had_focus_at_shutdown_
)
1335 view_
->RestoreFocus();
1339 bool WebContentsImpl::PreHandleKeyboardEvent(
1340 const NativeWebKeyboardEvent
& event
,
1341 bool* is_keyboard_shortcut
) {
1343 delegate_
->PreHandleKeyboardEvent(this, event
, is_keyboard_shortcut
);
1346 void WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent
& event
) {
1347 if (browser_plugin_embedder_
&&
1348 browser_plugin_embedder_
->HandleKeyboardEvent(event
)) {
1352 delegate_
->HandleKeyboardEvent(this, event
);
1355 bool WebContentsImpl::HandleWheelEvent(
1356 const blink::WebMouseWheelEvent
& event
) {
1357 #if !defined(OS_MACOSX)
1358 // On platforms other than Mac, control+mousewheel changes zoom. On Mac, this
1359 // isn't done for two reasons:
1360 // -the OS already has a gesture to do this through pinch-zoom
1361 // -if a user starts an inertial scroll, let's go, and presses control
1362 // (i.e. control+tab) then the OS's buffered scroll events will come in
1363 // with control key set which isn't what the user wants
1365 event
.wheelTicksY
&&
1366 (event
.modifiers
& blink::WebInputEvent::ControlKey
) &&
1367 // Avoid adjusting the zoom in response to two-finger-scrolling touchpad
1368 // gestures, which are regrettably easy to trigger accidentally.
1369 !event
.hasPreciseScrollingDeltas
) {
1370 delegate_
->ContentsZoomChange(event
.wheelTicksY
> 0);
1377 bool WebContentsImpl::PreHandleGestureEvent(
1378 const blink::WebGestureEvent
& event
) {
1379 return delegate_
&& delegate_
->PreHandleGestureEvent(this, event
);
1382 bool WebContentsImpl::HandleGestureEvent(
1383 const blink::WebGestureEvent
& event
) {
1384 // Some platforms (eg. Mac) send GesturePinch events for trackpad pinch-zoom.
1385 // Use them to implement browser zoom, as for HandleWheelEvent above.
1386 if (event
.type
== blink::WebInputEvent::GesturePinchUpdate
&&
1387 event
.sourceDevice
== blink::WebGestureDeviceTouchpad
) {
1388 // The scale difference necessary to trigger a zoom action. Derived from
1389 // experimentation to find a value that feels reasonable.
1390 const float kZoomStepValue
= 0.6f
;
1392 // Find the (absolute) thresholds on either side of the current zoom factor,
1393 // then convert those to actual numbers to trigger a zoom in or out.
1394 // This logic deliberately makes the range around the starting zoom value
1395 // for the gesture twice as large as the other ranges (i.e., the notches are
1396 // at ..., -3*step, -2*step, -step, step, 2*step, 3*step, ... but not at 0)
1397 // so that it's easier to get back to your starting point than it is to
1399 float nextStep
= (abs(currentPinchZoomStepDelta_
) + 1) * kZoomStepValue
;
1400 float backStep
= abs(currentPinchZoomStepDelta_
) * kZoomStepValue
;
1401 float zoomInThreshold
= (currentPinchZoomStepDelta_
>= 0) ? nextStep
1403 float zoomOutThreshold
= (currentPinchZoomStepDelta_
<= 0) ? -nextStep
1406 totalPinchGestureAmount_
+= (event
.data
.pinchUpdate
.scale
- 1.0);
1407 if (totalPinchGestureAmount_
> zoomInThreshold
) {
1408 currentPinchZoomStepDelta_
++;
1410 delegate_
->ContentsZoomChange(true);
1411 } else if (totalPinchGestureAmount_
< zoomOutThreshold
) {
1412 currentPinchZoomStepDelta_
--;
1414 delegate_
->ContentsZoomChange(false);
1422 void WebContentsImpl::HandleMouseDown() {
1424 delegate_
->HandleMouseDown();
1427 void WebContentsImpl::HandleMouseUp() {
1429 delegate_
->HandleMouseUp();
1432 void WebContentsImpl::HandlePointerActivate() {
1434 delegate_
->HandlePointerActivate();
1437 void WebContentsImpl::HandleGestureBegin() {
1439 delegate_
->HandleGestureBegin();
1442 void WebContentsImpl::HandleGestureEnd() {
1444 delegate_
->HandleGestureEnd();
1447 void WebContentsImpl::ToggleFullscreenMode(bool enter_fullscreen
) {
1448 // This method is being called to enter or leave renderer-initiated fullscreen
1449 // mode. Either way, make sure any existing fullscreen widget is shut down
1451 RenderWidgetHostView
* const widget_view
= GetFullscreenRenderWidgetHostView();
1453 RenderWidgetHostImpl::From(widget_view
->GetRenderWidgetHost())->Shutdown();
1456 delegate_
->ToggleFullscreenModeForTab(this, enter_fullscreen
);
1458 FOR_EACH_OBSERVER(WebContentsObserver
,
1460 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1463 bool WebContentsImpl::IsFullscreenForCurrentTab() const {
1464 return delegate_
? delegate_
->IsFullscreenForTabOrPending(this) : false;
1467 void WebContentsImpl::RequestToLockMouse(bool user_gesture
,
1468 bool last_unlocked_by_target
) {
1470 delegate_
->RequestToLockMouse(this, user_gesture
, last_unlocked_by_target
);
1472 GotResponseToLockMouseRequest(false);
1476 void WebContentsImpl::LostMouseLock() {
1478 delegate_
->LostMouseLock();
1481 void WebContentsImpl::CreateNewWindow(
1482 int render_process_id
,
1484 int main_frame_route_id
,
1485 const ViewHostMsg_CreateWindow_Params
& params
,
1486 SessionStorageNamespace
* session_storage_namespace
) {
1487 // We usually create the new window in the same BrowsingInstance (group of
1488 // script-related windows), by passing in the current SiteInstance. However,
1489 // if the opener is being suppressed (in a non-guest), we create a new
1490 // SiteInstance in its own BrowsingInstance.
1491 bool is_guest
= BrowserPluginGuest::IsGuest(this);
1493 // If the opener is to be suppressed, the new window can be in any process.
1494 // Since routing ids are process specific, we must not have one passed in
1495 // as argument here.
1496 DCHECK(!params
.opener_suppressed
|| route_id
== MSG_ROUTING_NONE
);
1498 scoped_refptr
<SiteInstance
> site_instance
=
1499 params
.opener_suppressed
&& !is_guest
?
1500 SiteInstance::CreateForURL(GetBrowserContext(), params
.target_url
) :
1503 // A message to create a new window can only come from the active process for
1504 // this WebContentsImpl instance. If any other process sends the request,
1505 // it is invalid and the process must be terminated.
1506 if (GetRenderProcessHost()->GetID() != render_process_id
) {
1507 base::ProcessHandle process_handle
=
1508 RenderProcessHost::FromID(render_process_id
)->GetHandle();
1509 if (process_handle
!= base::kNullProcessHandle
) {
1511 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWindow"));
1512 base::KillProcess(process_handle
, RESULT_CODE_KILLED
, false);
1517 // We must assign the SessionStorageNamespace before calling Init().
1519 // http://crbug.com/142685
1520 const std::string
& partition_id
=
1521 GetContentClient()->browser()->
1522 GetStoragePartitionIdForSite(GetBrowserContext(),
1523 site_instance
->GetSiteURL());
1524 StoragePartition
* partition
= BrowserContext::GetStoragePartition(
1525 GetBrowserContext(), site_instance
.get());
1526 DOMStorageContextWrapper
* dom_storage_context
=
1527 static_cast<DOMStorageContextWrapper
*>(partition
->GetDOMStorageContext());
1528 SessionStorageNamespaceImpl
* session_storage_namespace_impl
=
1529 static_cast<SessionStorageNamespaceImpl
*>(session_storage_namespace
);
1530 CHECK(session_storage_namespace_impl
->IsFromContext(dom_storage_context
));
1533 !delegate_
->ShouldCreateWebContents(this,
1535 params
.window_container_type
,
1539 session_storage_namespace
)) {
1540 if (route_id
!= MSG_ROUTING_NONE
&&
1541 !RenderViewHost::FromID(render_process_id
, route_id
)) {
1542 // If the embedder didn't create a WebContents for this route, we need to
1543 // delete the RenderView that had already been created.
1544 Send(new ViewMsg_Close(route_id
));
1546 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(route_id
);
1547 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(
1548 main_frame_route_id
);
1552 // Create the new web contents. This will automatically create the new
1553 // WebContentsView. In the future, we may want to create the view separately.
1554 CreateParams
create_params(GetBrowserContext(), site_instance
.get());
1555 create_params
.routing_id
= route_id
;
1556 create_params
.main_frame_routing_id
= main_frame_route_id
;
1557 create_params
.opener
= this;
1558 create_params
.opener_suppressed
= params
.opener_suppressed
;
1559 if (params
.disposition
== NEW_BACKGROUND_TAB
)
1560 create_params
.initially_hidden
= true;
1562 WebContentsImpl
* new_contents
= NULL
;
1564 create_params
.context
= view_
->GetNativeView();
1565 create_params
.initial_size
= GetContainerBounds().size();
1566 new_contents
= static_cast<WebContentsImpl
*>(
1567 WebContents::Create(create_params
));
1569 new_contents
= GetBrowserPluginGuest()->CreateNewGuestWindow(create_params
);
1571 new_contents
->GetController().SetSessionStorageNamespace(
1573 session_storage_namespace
);
1574 new_contents
->RenderViewCreated(new_contents
->GetRenderViewHost());
1576 // Save the window for later if we're not suppressing the opener (since it
1577 // will be shown immediately).
1578 if (!params
.opener_suppressed
) {
1580 WebContentsView
* new_view
= new_contents
->view_
.get();
1582 // TODO(brettw): It seems bogus that we have to call this function on the
1583 // newly created object and give it one of its own member variables.
1584 new_view
->CreateViewForWidget(new_contents
->GetRenderViewHost());
1586 // Save the created window associated with the route so we can show it
1588 DCHECK_NE(MSG_ROUTING_NONE
, route_id
);
1589 pending_contents_
[route_id
] = new_contents
;
1590 AddDestructionObserver(new_contents
);
1594 delegate_
->WebContentsCreated(
1595 this, params
.opener_render_frame_id
, params
.frame_name
,
1596 params
.target_url
, new_contents
);
1599 if (params
.opener_suppressed
) {
1600 // When the opener is suppressed, the original renderer cannot access the
1601 // new window. As a result, we need to show and navigate the window here.
1602 bool was_blocked
= false;
1604 gfx::Rect initial_pos
;
1605 delegate_
->AddNewContents(
1606 this, new_contents
, params
.disposition
, initial_pos
,
1607 params
.user_gesture
, &was_blocked
);
1610 OpenURLParams
open_params(params
.target_url
,
1613 ui::PAGE_TRANSITION_LINK
,
1614 true /* is_renderer_initiated */);
1615 open_params
.user_gesture
= params
.user_gesture
;
1616 new_contents
->OpenURL(open_params
);
1621 void WebContentsImpl::CreateNewWidget(int render_process_id
,
1623 blink::WebPopupType popup_type
) {
1624 CreateNewWidget(render_process_id
, route_id
, false, popup_type
);
1627 void WebContentsImpl::CreateNewFullscreenWidget(int render_process_id
,
1629 CreateNewWidget(render_process_id
, route_id
, true, blink::WebPopupTypeNone
);
1632 void WebContentsImpl::CreateNewWidget(int render_process_id
,
1635 blink::WebPopupType popup_type
) {
1636 RenderProcessHost
* process
= GetRenderProcessHost();
1637 // A message to create a new widget can only come from the active process for
1638 // this WebContentsImpl instance. If any other process sends the request,
1639 // it is invalid and the process must be terminated.
1640 if (process
->GetID() != render_process_id
) {
1641 base::ProcessHandle process_handle
=
1642 RenderProcessHost::FromID(render_process_id
)->GetHandle();
1643 if (process_handle
!= base::kNullProcessHandle
) {
1645 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWidget"));
1646 base::KillProcess(process_handle
, RESULT_CODE_KILLED
, false);
1651 RenderWidgetHostImpl
* widget_host
=
1652 new RenderWidgetHostImpl(this, process
, route_id
, IsHidden());
1653 created_widgets_
.insert(widget_host
);
1655 RenderWidgetHostViewBase
* widget_view
=
1656 static_cast<RenderWidgetHostViewBase
*>(
1657 view_
->CreateViewForPopupWidget(widget_host
));
1660 if (!is_fullscreen
) {
1661 // Popups should not get activated.
1662 widget_view
->SetPopupType(popup_type
);
1664 // Save the created widget associated with the route so we can show it later.
1665 pending_widget_views_
[route_id
] = widget_view
;
1667 #if defined(OS_MACOSX)
1668 // A RenderWidgetHostViewMac has lifetime scoped to the view. We'll retain it
1669 // to allow it to survive the trip without being hosted.
1670 base::mac::NSObjectRetain(widget_view
->GetNativeView());
1674 void WebContentsImpl::ShowCreatedWindow(int route_id
,
1675 WindowOpenDisposition disposition
,
1676 const gfx::Rect
& initial_pos
,
1677 bool user_gesture
) {
1678 WebContentsImpl
* contents
= GetCreatedWindow(route_id
);
1680 WebContentsDelegate
* delegate
= GetDelegate();
1682 delegate
->AddNewContents(
1683 this, contents
, disposition
, initial_pos
, user_gesture
, NULL
);
1688 void WebContentsImpl::ShowCreatedWidget(int route_id
,
1689 const gfx::Rect
& initial_pos
) {
1690 ShowCreatedWidget(route_id
, false, initial_pos
);
1693 void WebContentsImpl::ShowCreatedFullscreenWidget(int route_id
) {
1694 ShowCreatedWidget(route_id
, true, gfx::Rect());
1697 void WebContentsImpl::ShowCreatedWidget(int route_id
,
1699 const gfx::Rect
& initial_pos
) {
1700 RenderWidgetHostViewBase
* widget_host_view
=
1701 static_cast<RenderWidgetHostViewBase
*>(GetCreatedWidget(route_id
));
1702 if (!widget_host_view
)
1705 RenderWidgetHostView
* view
= NULL
;
1706 BrowserPluginGuest
* guest
= GetBrowserPluginGuest();
1707 if (guest
&& guest
->embedder_web_contents()) {
1708 view
= guest
->embedder_web_contents()->GetRenderWidgetHostView();
1710 view
= GetRenderWidgetHostView();
1713 if (is_fullscreen
) {
1714 DCHECK_EQ(MSG_ROUTING_NONE
, fullscreen_widget_routing_id_
);
1715 view_
->StoreFocus();
1716 fullscreen_widget_routing_id_
= route_id
;
1717 if (delegate_
&& delegate_
->EmbedsFullscreenWidget()) {
1718 widget_host_view
->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
1719 delegate_
->ToggleFullscreenModeForTab(this, true);
1721 widget_host_view
->InitAsFullscreen(view
);
1723 FOR_EACH_OBSERVER(WebContentsObserver
,
1725 DidShowFullscreenWidget(route_id
));
1726 if (!widget_host_view
->HasFocus())
1727 widget_host_view
->Focus();
1729 widget_host_view
->InitAsPopup(view
, initial_pos
);
1732 RenderWidgetHostImpl
* render_widget_host_impl
=
1733 RenderWidgetHostImpl::From(widget_host_view
->GetRenderWidgetHost());
1734 render_widget_host_impl
->Init();
1735 // Only allow privileged mouse lock for fullscreen render widget, which is
1736 // used to implement Pepper Flash fullscreen.
1737 render_widget_host_impl
->set_allow_privileged_mouse_lock(is_fullscreen
);
1739 #if defined(OS_MACOSX)
1740 // A RenderWidgetHostViewMac has lifetime scoped to the view. Now that it's
1741 // properly embedded (or purposefully ignored) we can release the retain we
1742 // took in CreateNewWidget().
1743 base::mac::NSObjectRelease(widget_host_view
->GetNativeView());
1747 WebContentsImpl
* WebContentsImpl::GetCreatedWindow(int route_id
) {
1748 PendingContents::iterator iter
= pending_contents_
.find(route_id
);
1750 // Certain systems can block the creation of new windows. If we didn't succeed
1751 // in creating one, just return NULL.
1752 if (iter
== pending_contents_
.end()) {
1756 WebContentsImpl
* new_contents
= iter
->second
;
1757 pending_contents_
.erase(route_id
);
1758 RemoveDestructionObserver(new_contents
);
1760 // Don't initialize the guest WebContents immediately.
1761 if (BrowserPluginGuest::IsGuest(new_contents
))
1762 return new_contents
;
1764 if (!new_contents
->GetRenderProcessHost()->HasConnection() ||
1765 !new_contents
->GetRenderViewHost()->GetView())
1768 // Resume blocked requests for both the RenderViewHost and RenderFrameHost.
1769 // TODO(brettw): It seems bogus to reach into here and initialize the host.
1770 static_cast<RenderViewHostImpl
*>(new_contents
->GetRenderViewHost())->Init();
1771 static_cast<RenderFrameHostImpl
*>(new_contents
->GetMainFrame())->Init();
1773 return new_contents
;
1776 RenderWidgetHostView
* WebContentsImpl::GetCreatedWidget(int route_id
) {
1777 PendingWidgetViews::iterator iter
= pending_widget_views_
.find(route_id
);
1778 if (iter
== pending_widget_views_
.end()) {
1783 RenderWidgetHostView
* widget_host_view
= iter
->second
;
1784 pending_widget_views_
.erase(route_id
);
1786 RenderWidgetHost
* widget_host
= widget_host_view
->GetRenderWidgetHost();
1787 if (!widget_host
->GetProcess()->HasConnection()) {
1788 // The view has gone away or the renderer crashed. Nothing to do.
1792 return widget_host_view
;
1795 void WebContentsImpl::RequestMediaAccessPermission(
1796 const MediaStreamRequest
& request
,
1797 const MediaResponseCallback
& callback
) {
1799 delegate_
->RequestMediaAccessPermission(this, request
, callback
);
1801 callback
.Run(MediaStreamDevices(),
1802 MEDIA_DEVICE_INVALID_STATE
,
1803 scoped_ptr
<MediaStreamUI
>());
1807 bool WebContentsImpl::CheckMediaAccessPermission(const GURL
& security_origin
,
1808 MediaStreamType type
) {
1809 DCHECK(type
== MEDIA_DEVICE_AUDIO_CAPTURE
||
1810 type
== MEDIA_DEVICE_VIDEO_CAPTURE
);
1812 delegate_
->CheckMediaAccessPermission(this, security_origin
, type
);
1815 SessionStorageNamespace
* WebContentsImpl::GetSessionStorageNamespace(
1816 SiteInstance
* instance
) {
1817 return controller_
.GetSessionStorageNamespace(instance
);
1820 SessionStorageNamespaceMap
WebContentsImpl::GetSessionStorageNamespaceMap() {
1821 return controller_
.GetSessionStorageNamespaceMap();
1824 FrameTree
* WebContentsImpl::GetFrameTree() {
1825 return &frame_tree_
;
1828 AccessibilityMode
WebContentsImpl::GetAccessibilityMode() const {
1829 return accessibility_mode_
;
1832 void WebContentsImpl::AccessibilityEventReceived(
1833 const std::vector
<AXEventNotificationDetails
>& details
) {
1835 WebContentsObserver
, observers_
, AccessibilityEventReceived(details
));
1838 RenderFrameHost
* WebContentsImpl::GetGuestByInstanceID(
1839 int browser_plugin_instance_id
) {
1840 BrowserPluginGuestManager
* guest_manager
=
1841 GetBrowserContext()->GetGuestManager();
1842 WebContents
* guest
= guest_manager
->GetGuestByInstanceID(
1843 this, browser_plugin_instance_id
);
1846 return guest
->GetMainFrame();
1849 void WebContentsImpl::OnShowValidationMessage(
1850 const gfx::Rect
& anchor_in_root_view
,
1851 const base::string16
& main_text
,
1852 const base::string16
& sub_text
) {
1854 delegate_
->ShowValidationMessage(
1855 this, anchor_in_root_view
, main_text
, sub_text
);
1858 void WebContentsImpl::OnHideValidationMessage() {
1860 delegate_
->HideValidationMessage(this);
1863 void WebContentsImpl::OnMoveValidationMessage(
1864 const gfx::Rect
& anchor_in_root_view
) {
1866 delegate_
->MoveValidationMessage(this, anchor_in_root_view
);
1869 void WebContentsImpl::DidSendScreenRects(RenderWidgetHostImpl
* rwh
) {
1870 if (browser_plugin_embedder_
)
1871 browser_plugin_embedder_
->DidSendScreenRects();
1874 BrowserAccessibilityManager
*
1875 WebContentsImpl::GetRootBrowserAccessibilityManager() {
1876 RenderFrameHostImpl
* rfh
= static_cast<RenderFrameHostImpl
*>(GetMainFrame());
1877 return rfh
? rfh
->browser_accessibility_manager() : NULL
;
1880 BrowserAccessibilityManager
*
1881 WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
1882 RenderFrameHostImpl
* rfh
= static_cast<RenderFrameHostImpl
*>(GetMainFrame());
1883 return rfh
? rfh
->GetOrCreateBrowserAccessibilityManager() : NULL
;
1886 void WebContentsImpl::UpdatePreferredSize(const gfx::Size
& pref_size
) {
1887 const gfx::Size old_size
= GetPreferredSize();
1888 preferred_size_
= pref_size
;
1889 OnPreferredSizeChanged(old_size
);
1892 void WebContentsImpl::ResizeDueToAutoResize(const gfx::Size
& new_size
) {
1894 delegate_
->ResizeDueToAutoResize(this, new_size
);
1897 WebContents
* WebContentsImpl::OpenURL(const OpenURLParams
& params
) {
1901 WebContents
* new_contents
= delegate_
->OpenURLFromTab(this, params
);
1902 return new_contents
;
1905 bool WebContentsImpl::Send(IPC::Message
* message
) {
1906 if (!GetRenderViewHost()) {
1911 return GetRenderViewHost()->Send(message
);
1914 bool WebContentsImpl::NavigateToPendingEntry(
1915 NavigationController::ReloadType reload_type
) {
1916 FrameTreeNode
* node
= frame_tree_
.root();
1918 // Navigate in the FrameTreeNode specified in the pending entry, if any. This
1919 // is currently only used in --site-per-process and tests.
1920 NavigationEntryImpl
* pending_entry
=
1921 NavigationEntryImpl::FromNavigationEntry(controller_
.GetPendingEntry());
1922 if (pending_entry
->frame_tree_node_id() != -1) {
1923 FrameTreeNode
* subframe
=
1924 frame_tree_
.FindByID(pending_entry
->frame_tree_node_id());
1930 return node
->navigator()->NavigateToPendingEntry(
1931 node
->current_frame_host(), reload_type
);
1934 void WebContentsImpl::RenderFrameForInterstitialPageCreated(
1935 RenderFrameHost
* render_frame_host
) {
1936 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1937 RenderFrameForInterstitialPageCreated(render_frame_host
));
1940 void WebContentsImpl::AttachInterstitialPage(
1941 InterstitialPageImpl
* interstitial_page
) {
1942 DCHECK(interstitial_page
);
1943 GetRenderManager()->set_interstitial_page(interstitial_page
);
1945 // Cancel any visible dialogs so that they don't interfere with the
1947 if (dialog_manager_
)
1948 dialog_manager_
->CancelActiveAndPendingDialogs(this);
1950 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1951 DidAttachInterstitialPage());
1954 void WebContentsImpl::DetachInterstitialPage() {
1955 if (ShowingInterstitialPage())
1956 GetRenderManager()->remove_interstitial_page();
1957 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1958 DidDetachInterstitialPage());
1961 void WebContentsImpl::SetHistoryLengthAndPrune(
1962 const SiteInstance
* site_instance
,
1964 int32 minimum_page_id
) {
1965 // SetHistoryLengthAndPrune doesn't work when there are pending cross-site
1966 // navigations. Callers should ensure that this is the case.
1967 if (GetRenderManager()->pending_render_view_host()) {
1971 RenderViewHostImpl
* rvh
= GetRenderViewHostImpl();
1976 if (site_instance
&& rvh
->GetSiteInstance() != site_instance
) {
1980 Send(new ViewMsg_SetHistoryLengthAndPrune(GetRoutingID(),
1985 void WebContentsImpl::ReloadFocusedFrame(bool ignore_cache
) {
1986 RenderFrameHost
* focused_frame
= GetFocusedFrame();
1990 focused_frame
->Send(new FrameMsg_Reload(
1991 focused_frame
->GetRoutingID(), ignore_cache
));
1994 void WebContentsImpl::Undo() {
1995 RenderFrameHost
* focused_frame
= GetFocusedFrame();
1999 focused_frame
->Send(new InputMsg_Undo(focused_frame
->GetRoutingID()));
2000 RecordAction(base::UserMetricsAction("Undo"));
2003 void WebContentsImpl::Redo() {
2004 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2007 focused_frame
->Send(new InputMsg_Redo(focused_frame
->GetRoutingID()));
2008 RecordAction(base::UserMetricsAction("Redo"));
2011 void WebContentsImpl::Cut() {
2012 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2016 focused_frame
->Send(new InputMsg_Cut(focused_frame
->GetRoutingID()));
2017 RecordAction(base::UserMetricsAction("Cut"));
2020 void WebContentsImpl::Copy() {
2021 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2025 focused_frame
->Send(new InputMsg_Copy(focused_frame
->GetRoutingID()));
2026 RecordAction(base::UserMetricsAction("Copy"));
2029 void WebContentsImpl::CopyToFindPboard() {
2030 #if defined(OS_MACOSX)
2031 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2035 // Windows/Linux don't have the concept of a find pasteboard.
2036 focused_frame
->Send(
2037 new InputMsg_CopyToFindPboard(focused_frame
->GetRoutingID()));
2038 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
2042 void WebContentsImpl::Paste() {
2043 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2047 focused_frame
->Send(new InputMsg_Paste(focused_frame
->GetRoutingID()));
2048 RecordAction(base::UserMetricsAction("Paste"));
2051 void WebContentsImpl::PasteAndMatchStyle() {
2052 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2056 focused_frame
->Send(new InputMsg_PasteAndMatchStyle(
2057 focused_frame
->GetRoutingID()));
2058 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
2061 void WebContentsImpl::Delete() {
2062 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2066 focused_frame
->Send(new InputMsg_Delete(focused_frame
->GetRoutingID()));
2067 RecordAction(base::UserMetricsAction("DeleteSelection"));
2070 void WebContentsImpl::SelectAll() {
2071 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2075 focused_frame
->Send(new InputMsg_SelectAll(focused_frame
->GetRoutingID()));
2076 RecordAction(base::UserMetricsAction("SelectAll"));
2079 void WebContentsImpl::Unselect() {
2080 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2084 focused_frame
->Send(new InputMsg_Unselect(focused_frame
->GetRoutingID()));
2085 RecordAction(base::UserMetricsAction("Unselect"));
2088 void WebContentsImpl::Replace(const base::string16
& word
) {
2089 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2093 focused_frame
->Send(new InputMsg_Replace(
2094 focused_frame
->GetRoutingID(), word
));
2097 void WebContentsImpl::ReplaceMisspelling(const base::string16
& word
) {
2098 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2102 focused_frame
->Send(new InputMsg_ReplaceMisspelling(
2103 focused_frame
->GetRoutingID(), word
));
2106 void WebContentsImpl::NotifyContextMenuClosed(
2107 const CustomContextMenuContext
& context
) {
2108 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2112 focused_frame
->Send(new FrameMsg_ContextMenuClosed(
2113 focused_frame
->GetRoutingID(), context
));
2116 void WebContentsImpl::ExecuteCustomContextMenuCommand(
2117 int action
, const CustomContextMenuContext
& context
) {
2118 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2122 focused_frame
->Send(new FrameMsg_CustomContextMenuAction(
2123 focused_frame
->GetRoutingID(), context
, action
));
2126 gfx::NativeView
WebContentsImpl::GetNativeView() {
2127 return view_
->GetNativeView();
2130 gfx::NativeView
WebContentsImpl::GetContentNativeView() {
2131 return view_
->GetContentNativeView();
2134 gfx::NativeWindow
WebContentsImpl::GetTopLevelNativeWindow() {
2135 return view_
->GetTopLevelNativeWindow();
2138 gfx::Rect
WebContentsImpl::GetViewBounds() {
2139 return view_
->GetViewBounds();
2142 gfx::Rect
WebContentsImpl::GetContainerBounds() {
2144 view_
->GetContainerBounds(&rv
);
2148 DropData
* WebContentsImpl::GetDropData() {
2149 return view_
->GetDropData();
2152 void WebContentsImpl::Focus() {
2153 RenderWidgetHostView
* const fullscreen_view
=
2154 GetFullscreenRenderWidgetHostView();
2155 if (fullscreen_view
)
2156 fullscreen_view
->Focus();
2161 void WebContentsImpl::SetInitialFocus() {
2162 RenderWidgetHostView
* const fullscreen_view
=
2163 GetFullscreenRenderWidgetHostView();
2164 if (fullscreen_view
)
2165 fullscreen_view
->Focus();
2167 view_
->SetInitialFocus();
2170 void WebContentsImpl::StoreFocus() {
2171 if (!GetFullscreenRenderWidgetHostView())
2172 view_
->StoreFocus();
2175 void WebContentsImpl::RestoreFocus() {
2176 RenderWidgetHostView
* const fullscreen_view
=
2177 GetFullscreenRenderWidgetHostView();
2178 if (fullscreen_view
)
2179 fullscreen_view
->Focus();
2181 view_
->RestoreFocus();
2184 void WebContentsImpl::FocusThroughTabTraversal(bool reverse
) {
2185 if (ShowingInterstitialPage()) {
2186 GetRenderManager()->interstitial_page()->FocusThroughTabTraversal(reverse
);
2189 RenderWidgetHostView
* const fullscreen_view
=
2190 GetFullscreenRenderWidgetHostView();
2191 if (fullscreen_view
) {
2192 fullscreen_view
->Focus();
2195 GetRenderViewHostImpl()->SetInitialFocus(reverse
);
2198 bool WebContentsImpl::ShowingInterstitialPage() const {
2199 return GetRenderManager()->interstitial_page() != NULL
;
2202 InterstitialPage
* WebContentsImpl::GetInterstitialPage() const {
2203 return GetRenderManager()->interstitial_page();
2206 bool WebContentsImpl::IsSavable() {
2207 // WebKit creates Document object when MIME type is application/xhtml+xml,
2208 // so we also support this MIME type.
2209 return contents_mime_type_
== "text/html" ||
2210 contents_mime_type_
== "text/xml" ||
2211 contents_mime_type_
== "application/xhtml+xml" ||
2212 contents_mime_type_
== "text/plain" ||
2213 contents_mime_type_
== "text/css" ||
2214 net::IsSupportedJavascriptMimeType(contents_mime_type_
.c_str());
2217 void WebContentsImpl::OnSavePage() {
2218 // If we can not save the page, try to download it.
2220 RecordDownloadSource(INITIATED_BY_SAVE_PACKAGE_ON_NON_HTML
);
2221 SaveFrame(GetURL(), Referrer());
2227 // Create the save package and possibly prompt the user for the name to save
2228 // the page as. The user prompt is an asynchronous operation that runs on
2230 save_package_
= new SavePackage(this);
2231 save_package_
->GetSaveInfo();
2234 // Used in automated testing to bypass prompting the user for file names.
2235 // Instead, the names and paths are hard coded rather than running them through
2236 // file name sanitation and extension / mime checking.
2237 bool WebContentsImpl::SavePage(const base::FilePath
& main_file
,
2238 const base::FilePath
& dir_path
,
2239 SavePageType save_type
) {
2240 // Stop the page from navigating.
2243 save_package_
= new SavePackage(this, save_type
, main_file
, dir_path
);
2244 return save_package_
->Init(SavePackageDownloadCreatedCallback());
2247 void WebContentsImpl::SaveFrame(const GURL
& url
,
2248 const Referrer
& referrer
) {
2249 if (!GetURL().is_valid())
2251 bool is_main_frame
= (url
== GetURL());
2253 DownloadManager
* dlm
=
2254 BrowserContext::GetDownloadManager(GetBrowserContext());
2258 if (is_main_frame
) {
2259 const NavigationEntry
* entry
= controller_
.GetLastCommittedEntry();
2261 post_id
= entry
->GetPostID();
2263 scoped_ptr
<DownloadUrlParameters
> params(
2264 DownloadUrlParameters::FromWebContents(this, url
));
2265 params
->set_referrer(referrer
);
2266 params
->set_post_id(post_id
);
2267 params
->set_prefer_cache(true);
2269 params
->set_method("POST");
2270 params
->set_prompt(true);
2271 dlm
->DownloadUrl(params
.Pass());
2274 void WebContentsImpl::GenerateMHTML(
2275 const base::FilePath
& file
,
2276 const base::Callback
<void(int64
)>& callback
) {
2277 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, file
, callback
);
2280 const std::string
& WebContentsImpl::GetContentsMimeType() const {
2281 return contents_mime_type_
;
2284 bool WebContentsImpl::WillNotifyDisconnection() const {
2285 return notify_disconnection_
;
2288 void WebContentsImpl::SetOverrideEncoding(const std::string
& encoding
) {
2289 SetEncoding(encoding
);
2290 Send(new ViewMsg_SetPageEncoding(GetRoutingID(), encoding
));
2293 void WebContentsImpl::ResetOverrideEncoding() {
2294 canonical_encoding_
.clear();
2295 Send(new ViewMsg_ResetPageEncodingToDefault(GetRoutingID()));
2298 RendererPreferences
* WebContentsImpl::GetMutableRendererPrefs() {
2299 return &renderer_preferences_
;
2302 void WebContentsImpl::Close() {
2303 Close(GetRenderViewHost());
2306 void WebContentsImpl::DragSourceEndedAt(int client_x
, int client_y
,
2307 int screen_x
, int screen_y
, blink::WebDragOperation operation
) {
2308 if (browser_plugin_embedder_
.get())
2309 browser_plugin_embedder_
->DragSourceEndedAt(client_x
, client_y
,
2310 screen_x
, screen_y
, operation
);
2311 if (GetRenderViewHost())
2312 GetRenderViewHostImpl()->DragSourceEndedAt(client_x
, client_y
,
2313 screen_x
, screen_y
, operation
);
2316 void WebContentsImpl::DidGetResourceResponseStart(
2317 const ResourceRequestDetails
& details
) {
2318 controller_
.ssl_manager()->DidStartResourceResponse(details
);
2320 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2321 DidGetResourceResponseStart(details
));
2323 // TODO(avi): Remove. http://crbug.com/170921
2324 NotificationService::current()->Notify(
2325 NOTIFICATION_RESOURCE_RESPONSE_STARTED
,
2326 Source
<WebContents
>(this),
2327 Details
<const ResourceRequestDetails
>(&details
));
2330 void WebContentsImpl::DidGetRedirectForResourceRequest(
2331 RenderViewHost
* render_view_host
,
2332 const ResourceRedirectDetails
& details
) {
2333 controller_
.ssl_manager()->DidReceiveResourceRedirect(details
);
2336 WebContentsObserver
,
2338 DidGetRedirectForResourceRequest(render_view_host
, details
));
2340 // TODO(avi): Remove. http://crbug.com/170921
2341 NotificationService::current()->Notify(
2342 NOTIFICATION_RESOURCE_RECEIVED_REDIRECT
,
2343 Source
<WebContents
>(this),
2344 Details
<const ResourceRedirectDetails
>(&details
));
2347 void WebContentsImpl::SystemDragEnded() {
2348 if (GetRenderViewHost())
2349 GetRenderViewHostImpl()->DragSourceSystemDragEnded();
2351 delegate_
->DragEnded();
2352 if (browser_plugin_embedder_
.get())
2353 browser_plugin_embedder_
->SystemDragEnded();
2356 void WebContentsImpl::UserGestureDone() {
2360 void WebContentsImpl::SetClosedByUserGesture(bool value
) {
2361 closed_by_user_gesture_
= value
;
2364 bool WebContentsImpl::GetClosedByUserGesture() const {
2365 return closed_by_user_gesture_
;
2368 void WebContentsImpl::ViewSource() {
2372 NavigationEntry
* entry
= GetController().GetLastCommittedEntry();
2376 delegate_
->ViewSourceForTab(this, entry
->GetURL());
2379 void WebContentsImpl::ViewFrameSource(const GURL
& url
,
2380 const PageState
& page_state
) {
2384 delegate_
->ViewSourceForFrame(this, url
, page_state
);
2387 int WebContentsImpl::GetMinimumZoomPercent() const {
2388 return minimum_zoom_percent_
;
2391 int WebContentsImpl::GetMaximumZoomPercent() const {
2392 return maximum_zoom_percent_
;
2395 gfx::Size
WebContentsImpl::GetPreferredSize() const {
2396 return capturer_count_
== 0 ? preferred_size_
: preferred_size_for_capture_
;
2399 bool WebContentsImpl::GotResponseToLockMouseRequest(bool allowed
) {
2400 if (GetBrowserPluginGuest())
2401 return GetBrowserPluginGuest()->LockMouse(allowed
);
2403 return GetRenderViewHost() ?
2404 GetRenderViewHostImpl()->GotResponseToLockMouseRequest(allowed
) : false;
2407 bool WebContentsImpl::HasOpener() const {
2408 return opener_
!= NULL
;
2411 void WebContentsImpl::DidChooseColorInColorChooser(SkColor color
) {
2412 if (!color_chooser_info_
.get())
2414 RenderFrameHost
* rfh
= RenderFrameHost::FromID(
2415 color_chooser_info_
->render_process_id
,
2416 color_chooser_info_
->render_frame_id
);
2420 rfh
->Send(new FrameMsg_DidChooseColorResponse(
2421 rfh
->GetRoutingID(), color_chooser_info_
->identifier
, color
));
2424 void WebContentsImpl::DidEndColorChooser() {
2425 if (!color_chooser_info_
.get())
2427 RenderFrameHost
* rfh
= RenderFrameHost::FromID(
2428 color_chooser_info_
->render_process_id
,
2429 color_chooser_info_
->render_frame_id
);
2433 rfh
->Send(new FrameMsg_DidEndColorChooser(
2434 rfh
->GetRoutingID(), color_chooser_info_
->identifier
));
2435 color_chooser_info_
.reset();
2438 int WebContentsImpl::DownloadImage(const GURL
& url
,
2440 uint32_t max_bitmap_size
,
2441 const ImageDownloadCallback
& callback
) {
2442 int id
= StartDownload(GetMainFrame(), url
, is_favicon
, max_bitmap_size
);
2443 image_download_map_
[id
] = callback
;
2447 bool WebContentsImpl::IsSubframe() const {
2448 return is_subframe_
;
2451 void WebContentsImpl::Find(int request_id
,
2452 const base::string16
& search_text
,
2453 const blink::WebFindOptions
& options
) {
2454 Send(new ViewMsg_Find(GetRoutingID(), request_id
, search_text
, options
));
2457 void WebContentsImpl::StopFinding(StopFindAction action
) {
2458 Send(new ViewMsg_StopFinding(GetRoutingID(), action
));
2461 void WebContentsImpl::InsertCSS(const std::string
& css
) {
2462 GetMainFrame()->Send(new FrameMsg_CSSInsertRequest(
2463 GetMainFrame()->GetRoutingID(), css
));
2466 bool WebContentsImpl::WasRecentlyAudible() {
2467 return audio_stream_monitor_
.WasRecentlyAudible();
2470 void WebContentsImpl::GetManifest(const GetManifestCallback
& callback
) {
2471 manifest_manager_host_
->GetManifest(GetMainFrame(), callback
);
2474 bool WebContentsImpl::FocusLocationBarByDefault() {
2475 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
2476 if (entry
&& entry
->GetURL() == GURL(url::kAboutBlankURL
))
2478 return delegate_
&& delegate_
->ShouldFocusLocationBarByDefault(this);
2481 void WebContentsImpl::SetFocusToLocationBar(bool select_all
) {
2483 delegate_
->SetFocusToLocationBar(select_all
);
2486 void WebContentsImpl::DidStartProvisionalLoad(
2487 RenderFrameHostImpl
* render_frame_host
,
2488 const GURL
& validated_url
,
2490 bool is_iframe_srcdoc
) {
2491 // Notify observers about the start of the provisional load.
2493 WebContentsObserver
,
2495 DidStartProvisionalLoadForFrame(
2496 render_frame_host
, validated_url
, is_error_page
, is_iframe_srcdoc
));
2498 if (!render_frame_host
->GetParent()) {
2500 WebContentsObserver
,
2502 ProvisionalChangeToMainFrameUrl(validated_url
,
2503 render_frame_host
));
2507 void WebContentsImpl::DidStartNavigationTransition(
2508 RenderFrameHostImpl
* render_frame_host
) {
2509 #if defined(OS_ANDROID)
2510 int render_frame_id
= render_frame_host
->GetRoutingID();
2511 GetWebContentsAndroid()->DidStartNavigationTransitionForFrame(
2516 void WebContentsImpl::DidFailProvisionalLoadWithError(
2517 RenderFrameHostImpl
* render_frame_host
,
2518 const FrameHostMsg_DidFailProvisionalLoadWithError_Params
& params
) {
2519 GURL
validated_url(params
.url
);
2520 FOR_EACH_OBSERVER(WebContentsObserver
,
2522 DidFailProvisionalLoad(render_frame_host
,
2525 params
.error_description
));
2528 void WebContentsImpl::DidFailLoadWithError(
2529 RenderFrameHostImpl
* render_frame_host
,
2532 const base::string16
& error_description
) {
2534 WebContentsObserver
,
2536 DidFailLoad(render_frame_host
, url
, error_code
, error_description
));
2539 void WebContentsImpl::NotifyChangedNavigationState(
2540 InvalidateTypes changed_flags
) {
2541 NotifyNavigationStateChanged(changed_flags
);
2544 void WebContentsImpl::AboutToNavigateRenderFrame(
2545 RenderFrameHostImpl
* render_frame_host
) {
2546 // Notify observers that we will navigate in this RenderView.
2547 RenderViewHost
* render_view_host
= render_frame_host
->render_view_host();
2549 WebContentsObserver
,
2551 AboutToNavigateRenderView(render_view_host
));
2554 void WebContentsImpl::DidStartNavigationToPendingEntry(
2555 RenderFrameHostImpl
* render_frame_host
,
2557 NavigationController::ReloadType reload_type
) {
2558 // Notify observers about navigation.
2560 WebContentsObserver
,
2562 DidStartNavigationToPendingEntry(url
, reload_type
));
2565 void WebContentsImpl::RequestOpenURL(RenderFrameHostImpl
* render_frame_host
,
2566 const OpenURLParams
& params
) {
2567 int source_render_frame_id
= render_frame_host
->GetRoutingID();
2568 WebContents
* new_contents
= OpenURL(params
);
2571 // Notify observers.
2572 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2573 DidOpenRequestedURL(new_contents
,
2578 source_render_frame_id
));
2582 bool WebContentsImpl::ShouldPreserveAbortedURLs() {
2585 return delegate_
->ShouldPreserveAbortedURLs(this);
2588 void WebContentsImpl::DidRedirectProvisionalLoad(
2589 RenderFrameHostImpl
* render_frame_host
,
2590 const GURL
& validated_target_url
) {
2591 // Notify observers about the provisional change in the main frame URL.
2593 WebContentsObserver
,
2595 ProvisionalChangeToMainFrameUrl(validated_target_url
,
2596 render_frame_host
));
2599 void WebContentsImpl::DidCommitProvisionalLoad(
2600 RenderFrameHostImpl
* render_frame_host
,
2602 ui::PageTransition transition_type
) {
2603 // Notify observers about the commit of the provisional load.
2604 FOR_EACH_OBSERVER(WebContentsObserver
,
2606 DidCommitProvisionalLoadForFrame(
2607 render_frame_host
, url
, transition_type
));
2610 void WebContentsImpl::DidNavigateMainFramePreCommit(
2611 bool navigation_is_within_page
) {
2612 // Ensure fullscreen mode is exited before committing the navigation to a
2613 // different page. The next page will not start out assuming it is in
2615 if (navigation_is_within_page
) {
2616 // No page change? Then, the renderer and browser can remain in fullscreen.
2619 if (IsFullscreenForCurrentTab())
2620 GetRenderViewHost()->ExitFullscreen();
2621 DCHECK(!IsFullscreenForCurrentTab());
2624 void WebContentsImpl::DidNavigateMainFramePostCommit(
2625 const LoadCommittedDetails
& details
,
2626 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) {
2627 if (details
.is_navigation_to_different_page()) {
2628 // Clear the status bubble. This is a workaround for a bug where WebKit
2629 // doesn't let us know that the cursor left an element during a
2630 // transition (this is also why the mouse cursor remains as a hand after
2631 // clicking on a link); see bugs 1184641 and 980803. We don't want to
2632 // clear the bubble when a user navigates to a named anchor in the same
2634 UpdateTargetURL(details
.entry
->GetPageID(), GURL());
2637 if (!details
.is_in_page
) {
2638 // Once the main frame is navigated, we're no longer considered to have
2639 // displayed insecure content.
2640 displayed_insecure_content_
= false;
2641 SSLManager::NotifySSLInternalStateChanged(
2642 GetController().GetBrowserContext());
2645 // Notify observers about navigation.
2646 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2647 DidNavigateMainFrame(details
, params
));
2650 delegate_
->DidNavigateMainFramePostCommit(this);
2651 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
2654 void WebContentsImpl::DidNavigateAnyFramePostCommit(
2655 RenderFrameHostImpl
* render_frame_host
,
2656 const LoadCommittedDetails
& details
,
2657 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) {
2658 // Now that something has committed, we don't need to track whether the
2659 // initial page has been accessed.
2660 has_accessed_initial_document_
= false;
2662 // If we navigate off the page, close all JavaScript dialogs.
2663 if (dialog_manager_
&& !details
.is_in_page
)
2664 dialog_manager_
->CancelActiveAndPendingDialogs(this);
2666 // Notify observers about navigation.
2667 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2668 DidNavigateAnyFrame(details
, params
));
2671 void WebContentsImpl::SetMainFrameMimeType(const std::string
& mime_type
) {
2672 contents_mime_type_
= mime_type
;
2675 bool WebContentsImpl::CanOverscrollContent() const {
2676 // Disable overscroll when touch emulation is on. See crbug.com/369938.
2677 if (force_disable_overscroll_content_
)
2681 return delegate_
->CanOverscrollContent();
2686 void WebContentsImpl::OnThemeColorChanged(SkColor theme_color
) {
2687 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2688 DidChangeThemeColor(theme_color
));
2691 void WebContentsImpl::OnDidLoadResourceFromMemoryCache(
2693 const std::string
& security_info
,
2694 const std::string
& http_method
,
2695 const std::string
& mime_type
,
2696 ResourceType resource_type
) {
2697 base::StatsCounter
cache("WebKit.CacheHit");
2700 // Send out a notification that we loaded a resource from our memory cache.
2702 net::CertStatus cert_status
= 0;
2703 int security_bits
= -1;
2704 int connection_status
= 0;
2705 SignedCertificateTimestampIDStatusList signed_certificate_timestamp_ids
;
2706 DeserializeSecurityInfo(security_info
, &cert_id
, &cert_status
,
2707 &security_bits
, &connection_status
,
2708 &signed_certificate_timestamp_ids
);
2709 // TODO(alcutter,eranm): Pass signed_certificate_timestamp_ids into details
2710 LoadFromMemoryCacheDetails
details(
2711 url
, GetRenderProcessHost()->GetID(), cert_id
, cert_status
, http_method
,
2712 mime_type
, resource_type
);
2714 controller_
.ssl_manager()->DidLoadFromMemoryCache(details
);
2716 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2717 DidLoadResourceFromMemoryCache(details
));
2719 if (url
.is_valid() && url
.SchemeIsHTTPOrHTTPS()) {
2720 scoped_refptr
<net::URLRequestContextGetter
> request_context(
2721 resource_type
== RESOURCE_TYPE_MEDIA
?
2722 GetBrowserContext()->GetMediaRequestContextForRenderProcess(
2723 GetRenderProcessHost()->GetID()) :
2724 GetBrowserContext()->GetRequestContextForRenderProcess(
2725 GetRenderProcessHost()->GetID()));
2726 BrowserThread::PostTask(
2729 base::Bind(&NotifyCacheOnIO
, request_context
, url
, http_method
));
2733 void WebContentsImpl::OnDidDisplayInsecureContent() {
2734 RecordAction(base::UserMetricsAction("SSL.DisplayedInsecureContent"));
2735 displayed_insecure_content_
= true;
2736 SSLManager::NotifySSLInternalStateChanged(
2737 GetController().GetBrowserContext());
2740 void WebContentsImpl::OnDidRunInsecureContent(
2741 const std::string
& security_origin
, const GURL
& target_url
) {
2742 LOG(WARNING
) << security_origin
<< " ran insecure content from "
2743 << target_url
.possibly_invalid_spec();
2744 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
2745 if (EndsWith(security_origin
, kDotGoogleDotCom
, false))
2746 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
2747 controller_
.ssl_manager()->DidRunInsecureContent(security_origin
);
2748 displayed_insecure_content_
= true;
2749 SSLManager::NotifySSLInternalStateChanged(
2750 GetController().GetBrowserContext());
2753 void WebContentsImpl::OnDocumentLoadedInFrame() {
2754 CHECK(render_frame_message_source_
);
2755 CHECK(!render_view_message_source_
);
2756 RenderFrameHostImpl
* rfh
=
2757 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2759 WebContentsObserver
, observers_
, DocumentLoadedInFrame(rfh
));
2762 void WebContentsImpl::OnDidFinishLoad(
2764 if (!render_frame_message_source_
) {
2765 RecordAction(base::UserMetricsAction("BadMessageTerminate_RVD2"));
2766 GetRenderProcessHost()->ReceivedBadMessage();
2770 GURL
validated_url(url
);
2771 RenderProcessHost
* render_process_host
=
2772 render_frame_message_source_
->GetProcess();
2773 render_process_host
->FilterURL(false, &validated_url
);
2775 RenderFrameHostImpl
* rfh
=
2776 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2778 WebContentsObserver
, observers_
, DidFinishLoad(rfh
, validated_url
));
2781 void WebContentsImpl::OnDidStartLoading(bool to_different_document
) {
2782 RenderFrameHostImpl
* rfh
=
2783 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2784 int64 render_frame_id
= rfh
->frame_tree_node()->frame_tree_node_id();
2786 // It is possible to get multiple calls to OnDidStartLoading that don't have
2787 // corresponding calls to OnDidStopLoading:
2788 // - With "swappedout://" URLs, this happens when a RenderView gets swapped
2789 // out for a cross-process navigation, and it turns into a placeholder for
2790 // one being rendered in a different process.
2791 // - Also, there might be more than one RenderFrameHost sharing the same
2792 // FrameTreeNode (and thus sharing its ID) each sending a start.
2793 // - But in the future, once clamy@ moves navigation network requests to the
2794 // browser process, there's a good chance that callbacks about starting and
2795 // stopping will all be handled by the browser. When that happens, there
2796 // should no longer be a start/stop call imbalance. TODO(avi): When this
2797 // future arrives, update this code to not allow this case.
2798 DCHECK_GE(loading_frames_in_progress_
, 0);
2799 if (loading_progresses_
.find(render_frame_id
) == loading_progresses_
.end()) {
2800 if (loading_frames_in_progress_
== 0)
2801 DidStartLoading(rfh
, to_different_document
);
2802 ++loading_frames_in_progress_
;
2805 loading_progresses_
[render_frame_id
] = kMinimumLoadingProgress
;
2806 SendLoadProgressChanged();
2809 void WebContentsImpl::OnDidStopLoading() {
2810 RenderFrameHostImpl
* rfh
=
2811 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2812 int64 render_frame_id
= rfh
->frame_tree_node()->frame_tree_node_id();
2814 if (loading_progresses_
.find(render_frame_id
) != loading_progresses_
.end()) {
2815 // Load stopped while we were still tracking load. Make sure we update
2816 // progress based on this frame's completion.
2817 loading_progresses_
[render_frame_id
] = 1.0;
2818 SendLoadProgressChanged();
2819 // Then we clean-up our states.
2820 if (loading_total_progress_
== 1.0)
2821 ResetLoadProgressState();
2824 // TODO(japhet): This should be a DCHECK, but the pdf plugin sometimes
2825 // calls DidStopLoading() without a matching DidStartLoading().
2826 if (loading_frames_in_progress_
== 0)
2828 --loading_frames_in_progress_
;
2829 if (loading_frames_in_progress_
== 0)
2830 DidStopLoading(rfh
);
2833 void WebContentsImpl::OnDidChangeLoadProgress(double load_progress
) {
2834 RenderFrameHostImpl
* rfh
=
2835 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2836 int64 render_frame_id
= rfh
->frame_tree_node()->frame_tree_node_id();
2838 loading_progresses_
[render_frame_id
] = load_progress
;
2840 // We notify progress change immediately for the first and last updates.
2841 // Also, since the message loop may be pretty busy when a page is loaded, it
2842 // might not execute a posted task in a timely manner so we make sure to
2843 // immediately send progress report if enough time has passed.
2844 base::TimeDelta min_delay
=
2845 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS
);
2846 if (load_progress
== 1.0 || loading_last_progress_update_
.is_null() ||
2847 base::TimeTicks::Now() - loading_last_progress_update_
> min_delay
) {
2848 // If there is a pending task to send progress, it is now obsolete.
2849 loading_weak_factory_
.InvalidateWeakPtrs();
2850 SendLoadProgressChanged();
2851 if (loading_total_progress_
== 1.0)
2852 ResetLoadProgressState();
2856 if (loading_weak_factory_
.HasWeakPtrs())
2859 base::MessageLoop::current()->PostDelayedTask(
2861 base::Bind(&WebContentsImpl::SendLoadProgressChanged
,
2862 loading_weak_factory_
.GetWeakPtr()),
2866 void WebContentsImpl::OnGoToEntryAtOffset(int offset
) {
2867 if (!delegate_
|| delegate_
->OnGoToEntryOffset(offset
))
2868 controller_
.GoToOffset(offset
);
2871 void WebContentsImpl::OnUpdateZoomLimits(int minimum_percent
,
2872 int maximum_percent
) {
2873 minimum_zoom_percent_
= minimum_percent
;
2874 maximum_zoom_percent_
= maximum_percent
;
2877 void WebContentsImpl::OnEnumerateDirectory(int request_id
,
2878 const base::FilePath
& path
) {
2882 ChildProcessSecurityPolicyImpl
* policy
=
2883 ChildProcessSecurityPolicyImpl::GetInstance();
2884 if (policy
->CanReadFile(GetRenderProcessHost()->GetID(), path
))
2885 delegate_
->EnumerateDirectory(this, request_id
, path
);
2888 void WebContentsImpl::OnRegisterProtocolHandler(const std::string
& protocol
,
2890 const base::string16
& title
,
2891 bool user_gesture
) {
2895 ChildProcessSecurityPolicyImpl
* policy
=
2896 ChildProcessSecurityPolicyImpl::GetInstance();
2897 if (policy
->IsPseudoScheme(protocol
))
2900 delegate_
->RegisterProtocolHandler(this, protocol
, url
, user_gesture
);
2903 void WebContentsImpl::OnUnregisterProtocolHandler(const std::string
& protocol
,
2905 bool user_gesture
) {
2909 ChildProcessSecurityPolicyImpl
* policy
=
2910 ChildProcessSecurityPolicyImpl::GetInstance();
2911 if (policy
->IsPseudoScheme(protocol
))
2914 delegate_
->UnregisterProtocolHandler(this, protocol
, url
, user_gesture
);
2917 void WebContentsImpl::OnFindReply(int request_id
,
2918 int number_of_matches
,
2919 const gfx::Rect
& selection_rect
,
2920 int active_match_ordinal
,
2921 bool final_update
) {
2923 delegate_
->FindReply(this, request_id
, number_of_matches
, selection_rect
,
2924 active_match_ordinal
, final_update
);
2928 #if defined(OS_ANDROID)
2929 void WebContentsImpl::OnFindMatchRectsReply(
2931 const std::vector
<gfx::RectF
>& rects
,
2932 const gfx::RectF
& active_rect
) {
2934 delegate_
->FindMatchRectsReply(this, version
, rects
, active_rect
);
2937 void WebContentsImpl::OnOpenDateTimeDialog(
2938 const ViewHostMsg_DateTimeDialogValue_Params
& value
) {
2939 date_time_chooser_
->ShowDialog(ContentViewCore::FromWebContents(this),
2940 GetRenderViewHost(),
2951 void WebContentsImpl::OnPepperPluginHung(int plugin_child_id
,
2952 const base::FilePath
& path
,
2954 UMA_HISTOGRAM_COUNTS("Pepper.PluginHung", 1);
2956 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2957 PluginHungStatusChanged(plugin_child_id
, path
, is_hung
));
2960 void WebContentsImpl::OnPluginCrashed(const base::FilePath
& plugin_path
,
2961 base::ProcessId plugin_pid
) {
2962 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2963 PluginCrashed(plugin_path
, plugin_pid
));
2966 void WebContentsImpl::OnDomOperationResponse(const std::string
& json_string
,
2967 int automation_id
) {
2968 DomOperationNotificationDetails
details(json_string
, automation_id
);
2969 NotificationService::current()->Notify(
2970 NOTIFICATION_DOM_OPERATION_RESPONSE
,
2971 Source
<WebContents
>(this),
2972 Details
<DomOperationNotificationDetails
>(&details
));
2975 void WebContentsImpl::OnAppCacheAccessed(const GURL
& manifest_url
,
2976 bool blocked_by_policy
) {
2977 // Notify observers about navigation.
2978 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2979 AppCacheAccessed(manifest_url
, blocked_by_policy
));
2982 void WebContentsImpl::OnOpenColorChooser(
2983 int color_chooser_id
,
2985 const std::vector
<ColorSuggestion
>& suggestions
) {
2986 ColorChooser
* new_color_chooser
= delegate_
?
2987 delegate_
->OpenColorChooser(this, color
, suggestions
) :
2989 if (!new_color_chooser
)
2991 if (color_chooser_info_
.get())
2992 color_chooser_info_
->chooser
->End();
2994 color_chooser_info_
.reset(new ColorChooserInfo(
2995 render_frame_message_source_
->GetProcess()->GetID(),
2996 render_frame_message_source_
->GetRoutingID(),
3001 void WebContentsImpl::OnEndColorChooser(int color_chooser_id
) {
3002 if (color_chooser_info_
&&
3003 color_chooser_id
== color_chooser_info_
->identifier
)
3004 color_chooser_info_
->chooser
->End();
3007 void WebContentsImpl::OnSetSelectedColorInColorChooser(int color_chooser_id
,
3009 if (color_chooser_info_
&&
3010 color_chooser_id
== color_chooser_info_
->identifier
)
3011 color_chooser_info_
->chooser
->SetSelectedColor(color
);
3014 // This exists for render views that don't have a WebUI, but do have WebUI
3015 // bindings enabled.
3016 void WebContentsImpl::OnWebUISend(const GURL
& source_url
,
3017 const std::string
& name
,
3018 const base::ListValue
& args
) {
3020 delegate_
->WebUISend(this, source_url
, name
, args
);
3023 #if defined(ENABLE_PLUGINS)
3024 void WebContentsImpl::OnRequestPpapiBrokerPermission(
3027 const base::FilePath
& plugin_path
) {
3029 OnPpapiBrokerPermissionResult(routing_id
, false);
3033 if (!delegate_
->RequestPpapiBrokerPermission(
3034 this, url
, plugin_path
,
3035 base::Bind(&WebContentsImpl::OnPpapiBrokerPermissionResult
,
3036 base::Unretained(this), routing_id
))) {
3038 OnPpapiBrokerPermissionResult(routing_id
, false);
3042 void WebContentsImpl::OnPpapiBrokerPermissionResult(int routing_id
,
3044 Send(new ViewMsg_PpapiBrokerPermissionResult(routing_id
, result
));
3047 void WebContentsImpl::OnBrowserPluginMessage(const IPC::Message
& message
) {
3048 // This creates a BrowserPluginEmbedder, which handles all the BrowserPlugin
3049 // specific messages for this WebContents. This means that any message from
3050 // a BrowserPlugin prior to this will be ignored.
3051 // For more info, see comment above classes BrowserPluginEmbedder and
3052 // BrowserPluginGuest.
3053 CHECK(!browser_plugin_embedder_
.get());
3054 browser_plugin_embedder_
.reset(BrowserPluginEmbedder::Create(this));
3055 browser_plugin_embedder_
->OnMessageReceived(message
);
3059 void WebContentsImpl::OnDidDownloadImage(
3061 int http_status_code
,
3062 const GURL
& image_url
,
3063 const std::vector
<SkBitmap
>& bitmaps
,
3064 const std::vector
<gfx::Size
>& original_bitmap_sizes
) {
3065 if (bitmaps
.size() != original_bitmap_sizes
.size())
3068 ImageDownloadMap::iterator iter
= image_download_map_
.find(id
);
3069 if (iter
== image_download_map_
.end()) {
3070 // Currently WebContents notifies us of ANY downloads so that it is
3071 // possible to get here.
3074 if (!iter
->second
.is_null()) {
3076 id
, http_status_code
, image_url
, bitmaps
, original_bitmap_sizes
);
3078 image_download_map_
.erase(id
);
3081 void WebContentsImpl::OnUpdateFaviconURL(
3082 const std::vector
<FaviconURL
>& candidates
) {
3083 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3084 DidUpdateFaviconURL(candidates
));
3087 void WebContentsImpl::CreateAudioPowerSaveBlocker() {
3088 // ChromeOS has its own way of handling power save blocks for media.
3089 #if !defined(OS_CHROMEOS)
3090 DCHECK(!audio_power_save_blocker_
);
3091 audio_power_save_blocker_
= PowerSaveBlocker::Create(
3092 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension
, "Playing Audio");
3096 void WebContentsImpl::CreateVideoPowerSaveBlocker() {
3097 // ChromeOS has its own way of handling power save blocks for media.
3098 #if !defined(OS_CHROMEOS)
3099 DCHECK(!video_power_save_blocker_
);
3100 DCHECK(!active_video_players_
.empty());
3101 video_power_save_blocker_
= PowerSaveBlocker::Create(
3102 PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep
, "Playing Video");
3103 #if defined(OS_ANDROID)
3104 static_cast<PowerSaveBlockerImpl
*>(video_power_save_blocker_
.get())
3105 ->InitDisplaySleepBlocker(GetView()->GetNativeView());
3110 void WebContentsImpl::MaybeReleasePowerSaveBlockers() {
3111 // If there are no more audio players and we don't have audio stream
3112 // monitoring, release the audio power save blocker here instead of during
3113 // NotifyNavigationStateChanged().
3114 if (active_audio_players_
.empty() &&
3115 !AudioStreamMonitor::monitoring_available()) {
3116 audio_power_save_blocker_
.reset();
3119 // If there are no more video players, clear the video power save blocker.
3120 if (active_video_players_
.empty())
3121 video_power_save_blocker_
.reset();
3124 void WebContentsImpl::OnMediaPlayingNotification(int64 player_cookie
,
3128 AddMediaPlayerEntry(player_cookie
, &active_audio_players_
);
3130 // If we don't have audio stream monitoring, allocate the audio power save
3131 // blocker here instead of during NotifyNavigationStateChanged().
3132 if (!audio_power_save_blocker_
&&
3133 !AudioStreamMonitor::monitoring_available()) {
3134 CreateAudioPowerSaveBlocker();
3139 AddMediaPlayerEntry(player_cookie
, &active_video_players_
);
3141 // If we're not hidden and have just created a player, create a blocker.
3142 if (!video_power_save_blocker_
&& !IsHidden())
3143 CreateVideoPowerSaveBlocker();
3147 void WebContentsImpl::OnMediaPausedNotification(int64 player_cookie
) {
3148 RemoveMediaPlayerEntry(player_cookie
, &active_audio_players_
);
3149 RemoveMediaPlayerEntry(player_cookie
, &active_video_players_
);
3150 MaybeReleasePowerSaveBlockers();
3153 void WebContentsImpl::OnFirstVisuallyNonEmptyPaint() {
3154 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3155 DidFirstVisuallyNonEmptyPaint());
3158 void WebContentsImpl::DidChangeVisibleSSLState() {
3160 delegate_
->VisibleSSLStateChanged(this);
3163 void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
3164 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3165 BeforeFormRepostWarningShow());
3168 void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
3171 delegate_
->ShowRepostFormWarningDialog(this);
3174 bool WebContentsImpl::HasAccessedInitialDocument() {
3175 return has_accessed_initial_document_
;
3178 // Notifies the RenderWidgetHost instance about the fact that the page is
3179 // loading, or done loading.
3180 void WebContentsImpl::SetIsLoading(RenderViewHost
* render_view_host
,
3182 bool to_different_document
,
3183 LoadNotificationDetails
* details
) {
3184 if (is_loading
== is_loading_
)
3188 load_state_
= net::LoadStateWithParam(net::LOAD_STATE_IDLE
,
3190 load_state_host_
.clear();
3192 upload_position_
= 0;
3195 GetRenderManager()->SetIsLoading(is_loading
);
3197 is_loading_
= is_loading
;
3198 waiting_for_response_
= is_loading
;
3199 is_load_to_different_document_
= to_different_document
;
3202 delegate_
->LoadingStateChanged(this, to_different_document
);
3203 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD
);
3205 std::string url
= (details
? details
->url
.possibly_invalid_spec() : "NULL");
3207 TRACE_EVENT_ASYNC_BEGIN1("browser,navigation", "WebContentsImpl Loading",
3209 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3210 DidStartLoading(render_view_host
));
3212 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
3214 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3215 DidStopLoading(render_view_host
));
3218 // TODO(avi): Remove. http://crbug.com/170921
3219 int type
= is_loading
? NOTIFICATION_LOAD_START
: NOTIFICATION_LOAD_STOP
;
3220 NotificationDetails det
= NotificationService::NoDetails();
3222 det
= Details
<LoadNotificationDetails
>(details
);
3223 NotificationService::current()->Notify(
3224 type
, Source
<NavigationController
>(&controller_
), det
);
3227 void WebContentsImpl::SelectRange(const gfx::Point
& start
,
3228 const gfx::Point
& end
) {
3229 RenderFrameHost
* focused_frame
= GetFocusedFrame();
3233 focused_frame
->Send(
3234 new InputMsg_SelectRange(focused_frame
->GetRoutingID(), start
, end
));
3237 void WebContentsImpl::UpdateMaxPageIDIfNecessary(RenderViewHost
* rvh
) {
3238 // If we are creating a RVH for a restored controller, then we need to make
3239 // sure the RenderView starts with a next_page_id_ larger than the number
3240 // of restored entries. This must be called before the RenderView starts
3241 // navigating (to avoid a race between the browser updating max_page_id and
3242 // the renderer updating next_page_id_). Because of this, we only call this
3243 // from CreateRenderView and allow that to notify the RenderView for us.
3244 int max_restored_page_id
= controller_
.GetMaxRestoredPageID();
3245 if (max_restored_page_id
>
3246 GetMaxPageIDForSiteInstance(rvh
->GetSiteInstance()))
3247 UpdateMaxPageIDForSiteInstance(rvh
->GetSiteInstance(),
3248 max_restored_page_id
);
3251 bool WebContentsImpl::UpdateTitleForEntry(NavigationEntryImpl
* entry
,
3252 const base::string16
& title
) {
3253 // For file URLs without a title, use the pathname instead. In the case of a
3254 // synthesized title, we don't want the update to count toward the "one set
3255 // per page of the title to history."
3256 base::string16 final_title
;
3258 if (entry
&& entry
->GetURL().SchemeIsFile() && title
.empty()) {
3259 final_title
= base::UTF8ToUTF16(entry
->GetURL().ExtractFileName());
3260 explicit_set
= false; // Don't count synthetic titles toward the set limit.
3262 base::TrimWhitespace(title
, base::TRIM_ALL
, &final_title
);
3263 explicit_set
= true;
3266 // If a page is created via window.open and never navigated,
3267 // there will be no navigation entry. In this situation,
3268 // |page_title_when_no_navigation_entry_| will be used for page title.
3270 if (final_title
== entry
->GetTitle())
3271 return false; // Nothing changed, don't bother.
3273 entry
->SetTitle(final_title
);
3275 if (page_title_when_no_navigation_entry_
== final_title
)
3276 return false; // Nothing changed, don't bother.
3278 page_title_when_no_navigation_entry_
= final_title
;
3281 // Lastly, set the title for the view.
3282 view_
->SetPageTitle(final_title
);
3284 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3285 TitleWasSet(entry
, explicit_set
));
3287 // TODO(avi): Remove. http://crbug.com/170921
3288 std::pair
<NavigationEntry
*, bool> details
=
3289 std::make_pair(entry
, explicit_set
);
3290 NotificationService::current()->Notify(
3291 NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED
,
3292 Source
<WebContents
>(this),
3293 Details
<std::pair
<NavigationEntry
*, bool> >(&details
));
3298 void WebContentsImpl::SendLoadProgressChanged() {
3299 loading_last_progress_update_
= base::TimeTicks::Now();
3300 double progress
= 0.0;
3301 int frame_count
= 0;
3303 for (LoadingProgressMap::iterator it
= loading_progresses_
.begin();
3304 it
!= loading_progresses_
.end();
3306 progress
+= it
->second
;
3309 if (frame_count
== 0)
3311 progress
/= frame_count
;
3312 DCHECK(progress
<= 1.0);
3314 if (progress
<= loading_total_progress_
)
3316 loading_total_progress_
= progress
;
3319 delegate_
->LoadProgressChanged(this, progress
);
3322 void WebContentsImpl::ResetLoadProgressState() {
3323 loading_progresses_
.clear();
3324 loading_total_progress_
= 0.0;
3325 loading_weak_factory_
.InvalidateWeakPtrs();
3326 loading_last_progress_update_
= base::TimeTicks();
3329 void WebContentsImpl::NotifyViewSwapped(RenderViewHost
* old_host
,
3330 RenderViewHost
* new_host
) {
3331 // After sending out a swap notification, we need to send a disconnect
3332 // notification so that clients that pick up a pointer to |this| can NULL the
3333 // pointer. See Bug 1230284.
3334 notify_disconnection_
= true;
3335 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3336 RenderViewHostChanged(old_host
, new_host
));
3338 // TODO(avi): Remove. http://crbug.com/170921
3339 std::pair
<RenderViewHost
*, RenderViewHost
*> details
=
3340 std::make_pair(old_host
, new_host
);
3341 NotificationService::current()->Notify(
3342 NOTIFICATION_RENDER_VIEW_HOST_CHANGED
,
3343 Source
<WebContents
>(this),
3344 Details
<std::pair
<RenderViewHost
*, RenderViewHost
*> >(&details
));
3346 // Ensure that the associated embedder gets cleared after a RenderViewHost
3347 // gets swapped, so we don't reuse the same embedder next time a
3348 // RenderViewHost is attached to this WebContents.
3349 RemoveBrowserPluginEmbedder();
3352 void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost
* old_host
,
3353 RenderFrameHost
* new_host
) {
3354 FOR_EACH_OBSERVER(WebContentsObserver
,
3356 RenderFrameHostChanged(old_host
, new_host
));
3359 // TODO(avi): Remove this entire function because this notification is already
3360 // covered by two observer functions. http://crbug.com/170921
3361 void WebContentsImpl::NotifyDisconnected() {
3362 if (!notify_disconnection_
)
3365 notify_disconnection_
= false;
3366 NotificationService::current()->Notify(
3367 NOTIFICATION_WEB_CONTENTS_DISCONNECTED
,
3368 Source
<WebContents
>(this),
3369 NotificationService::NoDetails());
3372 void WebContentsImpl::NotifyNavigationEntryCommitted(
3373 const LoadCommittedDetails
& load_details
) {
3375 WebContentsObserver
, observers_
, NavigationEntryCommitted(load_details
));
3378 bool WebContentsImpl::OnMessageReceived(RenderFrameHost
* render_frame_host
,
3379 const IPC::Message
& message
) {
3380 return OnMessageReceived(NULL
, render_frame_host
, message
);
3383 const GURL
& WebContentsImpl::GetMainFrameLastCommittedURL() const {
3384 return GetLastCommittedURL();
3387 void WebContentsImpl::RenderFrameCreated(RenderFrameHost
* render_frame_host
) {
3388 // Note this is only for subframes, the notification for the main frame
3389 // happens in RenderViewCreated.
3390 FOR_EACH_OBSERVER(WebContentsObserver
,
3392 RenderFrameCreated(render_frame_host
));
3393 SetAccessibilityModeOnFrame(accessibility_mode_
, render_frame_host
);
3396 void WebContentsImpl::RenderFrameDeleted(RenderFrameHost
* render_frame_host
) {
3397 ClearPowerSaveBlockers(render_frame_host
);
3398 FOR_EACH_OBSERVER(WebContentsObserver
,
3400 RenderFrameDeleted(render_frame_host
));
3403 void WebContentsImpl::WorkerCrashed(RenderFrameHost
* render_frame_host
) {
3405 delegate_
->WorkerCrashed(this);
3408 void WebContentsImpl::ShowContextMenu(RenderFrameHost
* render_frame_host
,
3409 const ContextMenuParams
& params
) {
3410 ContextMenuParams
context_menu_params(params
);
3411 // Allow WebContentsDelegates to handle the context menu operation first.
3412 if (GetBrowserPluginGuest()) {
3413 WebContentsViewGuest
* view_guest
=
3414 static_cast<WebContentsViewGuest
*>(GetView());
3415 context_menu_params
= view_guest
->ConvertContextMenuParams(params
);
3417 if (delegate_
&& delegate_
->HandleContextMenu(context_menu_params
))
3420 render_view_host_delegate_view_
->ShowContextMenu(render_frame_host
,
3421 context_menu_params
);
3424 void WebContentsImpl::RunJavaScriptMessage(
3425 RenderFrameHost
* render_frame_host
,
3426 const base::string16
& message
,
3427 const base::string16
& default_prompt
,
3428 const GURL
& frame_url
,
3429 JavaScriptMessageType javascript_message_type
,
3430 IPC::Message
* reply_msg
) {
3431 // Suppress JavaScript dialogs when requested. Also suppress messages when
3432 // showing an interstitial as it's shown over the previous page and we don't
3433 // want the hidden page's dialogs to interfere with the interstitial.
3434 bool suppress_this_message
=
3435 static_cast<RenderViewHostImpl
*>(render_frame_host
->GetRenderViewHost())->
3437 ShowingInterstitialPage() ||
3439 delegate_
->ShouldSuppressDialogs() ||
3440 !delegate_
->GetJavaScriptDialogManager();
3442 if (!suppress_this_message
) {
3443 std::string accept_lang
= GetContentClient()->browser()->
3444 GetAcceptLangs(GetBrowserContext());
3445 dialog_manager_
= delegate_
->GetJavaScriptDialogManager();
3446 dialog_manager_
->RunJavaScriptDialog(
3448 frame_url
.GetOrigin(),
3450 javascript_message_type
,
3453 base::Bind(&WebContentsImpl::OnDialogClosed
,
3454 base::Unretained(this),
3455 render_frame_host
->GetProcess()->GetID(),
3456 render_frame_host
->GetRoutingID(),
3459 &suppress_this_message
);
3462 if (suppress_this_message
) {
3463 // If we are suppressing messages, just reply as if the user immediately
3464 // pressed "Cancel", passing true to |dialog_was_suppressed|.
3465 OnDialogClosed(render_frame_host
->GetProcess()->GetID(),
3466 render_frame_host
->GetRoutingID(), reply_msg
,
3467 true, false, base::string16());
3470 // OnDialogClosed (two lines up) may have caused deletion of this object (see
3471 // http://crbug.com/288961 ). The only safe thing to do here is return.
3474 void WebContentsImpl::RunBeforeUnloadConfirm(
3475 RenderFrameHost
* render_frame_host
,
3476 const base::string16
& message
,
3478 IPC::Message
* reply_msg
) {
3479 RenderFrameHostImpl
* rfhi
=
3480 static_cast<RenderFrameHostImpl
*>(render_frame_host
);
3481 RenderViewHostImpl
* rvhi
=
3482 static_cast<RenderViewHostImpl
*>(render_frame_host
->GetRenderViewHost());
3484 delegate_
->WillRunBeforeUnloadConfirm();
3486 bool suppress_this_message
=
3487 rvhi
->rvh_state() != RenderViewHostImpl::STATE_DEFAULT
||
3489 delegate_
->ShouldSuppressDialogs() ||
3490 !delegate_
->GetJavaScriptDialogManager();
3491 if (suppress_this_message
) {
3492 rfhi
->JavaScriptDialogClosed(reply_msg
, true, base::string16(), true);
3496 is_showing_before_unload_dialog_
= true;
3497 dialog_manager_
= delegate_
->GetJavaScriptDialogManager();
3498 dialog_manager_
->RunBeforeUnloadDialog(
3499 this, message
, is_reload
,
3500 base::Bind(&WebContentsImpl::OnDialogClosed
, base::Unretained(this),
3501 render_frame_host
->GetProcess()->GetID(),
3502 render_frame_host
->GetRoutingID(), reply_msg
,
3506 WebContents
* WebContentsImpl::GetAsWebContents() {
3510 bool WebContentsImpl::IsNeverVisible() {
3513 return delegate_
->IsNeverVisible(this);
3517 gfx::NativeViewAccessible
WebContentsImpl::GetParentNativeViewAccessible() {
3518 return accessible_parent_
;
3522 RenderViewHostDelegateView
* WebContentsImpl::GetDelegateView() {
3523 return render_view_host_delegate_view_
;
3526 RendererPreferences
WebContentsImpl::GetRendererPrefs(
3527 BrowserContext
* browser_context
) const {
3528 return renderer_preferences_
;
3531 gfx::Rect
WebContentsImpl::GetRootWindowResizerRect() const {
3533 return delegate_
->GetRootWindowResizerRect();
3537 void WebContentsImpl::RemoveBrowserPluginEmbedder() {
3538 if (browser_plugin_embedder_
)
3539 browser_plugin_embedder_
.reset();
3542 void WebContentsImpl::RenderViewCreated(RenderViewHost
* render_view_host
) {
3543 // Don't send notifications if we are just creating a swapped-out RVH for
3544 // the opener chain. These won't be used for view-source or WebUI, so it's
3545 // ok to return early.
3546 if (static_cast<RenderViewHostImpl
*>(render_view_host
)->IsSwappedOut())
3550 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
3552 NotificationService::current()->Notify(
3553 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED
,
3554 Source
<WebContents
>(this),
3555 Details
<RenderViewHost
>(render_view_host
));
3557 // When we're creating views, we're still doing initial setup, so we always
3558 // use the pending Web UI rather than any possibly existing committed one.
3559 if (GetRenderManager()->pending_web_ui())
3560 GetRenderManager()->pending_web_ui()->RenderViewCreated(render_view_host
);
3562 NavigationEntry
* entry
= controller_
.GetPendingEntry();
3563 if (entry
&& entry
->IsViewSourceMode()) {
3564 // Put the renderer in view source mode.
3565 render_view_host
->Send(
3566 new ViewMsg_EnableViewSourceMode(render_view_host
->GetRoutingID()));
3569 view_
->RenderViewCreated(render_view_host
);
3572 WebContentsObserver
, observers_
, RenderViewCreated(render_view_host
));
3574 // We tell the observers now instead of when the main RenderFrameHostImpl is
3575 // constructed because otherwise it would be too early (i.e. IPCs sent to the
3576 // frame would be dropped because it's not created yet).
3577 RenderFrameHost
* main_frame
= render_view_host
->GetMainFrame();
3579 WebContentsObserver
, observers_
, RenderFrameCreated(main_frame
));
3580 SetAccessibilityModeOnFrame(accessibility_mode_
, main_frame
);
3583 void WebContentsImpl::RenderViewReady(RenderViewHost
* rvh
) {
3584 if (rvh
!= GetRenderViewHost()) {
3585 // Don't notify the world, since this came from a renderer in the
3590 notify_disconnection_
= true;
3591 // TODO(avi): Remove. http://crbug.com/170921
3592 NotificationService::current()->Notify(
3593 NOTIFICATION_WEB_CONTENTS_CONNECTED
,
3594 Source
<WebContents
>(this),
3595 NotificationService::NoDetails());
3597 bool was_crashed
= IsCrashed();
3598 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING
, 0);
3600 // Restore the focus to the tab (otherwise the focus will be on the top
3602 if (was_crashed
&& !FocusLocationBarByDefault() &&
3603 (!delegate_
|| delegate_
->ShouldFocusPageAfterCrash())) {
3607 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, RenderViewReady());
3610 void WebContentsImpl::RenderViewTerminated(RenderViewHost
* rvh
,
3611 base::TerminationStatus status
,
3613 if (rvh
!= GetRenderViewHost()) {
3614 // The pending page's RenderViewHost is gone.
3618 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
3619 // renderer may not have made a clean exit.
3620 if (IsFullscreenForCurrentTab())
3621 ToggleFullscreenMode(false);
3623 // Cancel any visible dialogs so they are not left dangling over the sad tab.
3624 if (dialog_manager_
)
3625 dialog_manager_
->CancelActiveAndPendingDialogs(this);
3628 delegate_
->HideValidationMessage(this);
3630 SetIsLoading(rvh
, false, true, NULL
);
3631 NotifyDisconnected();
3632 SetIsCrashed(status
, error_code
);
3634 // Reset the loading progress. TODO(avi): What does it mean to have a
3635 // "renderer crash" when there is more than one renderer process serving a
3636 // webpage? Once this function is called at a more granular frame level, we
3637 // probably will need to more granularly reset the state here.
3638 ResetLoadProgressState();
3639 loading_frames_in_progress_
= 0;
3641 FOR_EACH_OBSERVER(WebContentsObserver
,
3643 RenderProcessGone(GetCrashedStatus()));
3646 void WebContentsImpl::RenderViewDeleted(RenderViewHost
* rvh
) {
3647 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, RenderViewDeleted(rvh
));
3650 void WebContentsImpl::UpdateState(RenderViewHost
* rvh
,
3652 const PageState
& page_state
) {
3653 // Ensure that this state update comes from either the active RVH or one of
3654 // the swapped out RVHs. We don't expect to hear from any other RVHs.
3655 // TODO(nasko): This should go through RenderFrameHost.
3656 // TODO(creis): We can't update state for cross-process subframes until we
3657 // have FrameNavigationEntries. Once we do, this should be a DCHECK.
3658 if (rvh
!= GetRenderViewHost() &&
3659 !GetRenderManager()->IsRVHOnSwappedOutList(
3660 static_cast<RenderViewHostImpl
*>(rvh
)))
3663 // We must be prepared to handle state updates for any page, these occur
3664 // when the user is scrolling and entering form data, as well as when we're
3665 // leaving a page, in which case our state may have already been moved to
3666 // the next page. The navigation controller will look up the appropriate
3667 // NavigationEntry and update it when it is notified via the delegate.
3669 int entry_index
= controller_
.GetEntryIndexWithPageID(
3670 rvh
->GetSiteInstance(), page_id
);
3671 if (entry_index
< 0)
3673 NavigationEntry
* entry
= controller_
.GetEntryAtIndex(entry_index
);
3675 if (page_state
== entry
->GetPageState())
3676 return; // Nothing to update.
3677 entry
->SetPageState(page_state
);
3678 controller_
.NotifyEntryChanged(entry
, entry_index
);
3681 void WebContentsImpl::UpdateTargetURL(int32 page_id
, const GURL
& url
) {
3683 delegate_
->UpdateTargetURL(this, page_id
, url
);
3686 void WebContentsImpl::Close(RenderViewHost
* rvh
) {
3687 #if defined(OS_MACOSX)
3688 // The UI may be in an event-tracking loop, such as between the
3689 // mouse-down and mouse-up in text selection or a button click.
3690 // Defer the close until after tracking is complete, so that we
3691 // don't free objects out from under the UI.
3692 // TODO(shess): This could get more fine-grained. For instance,
3693 // closing a tab in another window while selecting text in the
3694 // current window's Omnibox should be just fine.
3695 if (view_
->IsEventTracking()) {
3696 view_
->CloseTabAfterEventTracking();
3701 // Ignore this if it comes from a RenderViewHost that we aren't showing.
3702 if (delegate_
&& rvh
== GetRenderViewHost())
3703 delegate_
->CloseContents(this);
3706 void WebContentsImpl::SwappedOut(RenderFrameHost
* rfh
) {
3707 if (delegate_
&& rfh
->GetRenderViewHost() == GetRenderViewHost())
3708 delegate_
->SwappedOut(this);
3711 void WebContentsImpl::DidDeferAfterResponseStarted(
3712 const TransitionLayerData
& transition_data
) {
3713 #if defined(OS_ANDROID)
3714 GetWebContentsAndroid()->DidDeferAfterResponseStarted(transition_data
);
3718 bool WebContentsImpl::WillHandleDeferAfterResponseStarted() {
3719 #if defined(OS_ANDROID)
3720 return GetWebContentsAndroid()->WillHandleDeferAfterResponseStarted();
3726 void WebContentsImpl::RequestMove(const gfx::Rect
& new_bounds
) {
3727 if (delegate_
&& delegate_
->IsPopupOrPanel(this))
3728 delegate_
->MoveContents(this, new_bounds
);
3731 void WebContentsImpl::DidStartLoading(RenderFrameHost
* render_frame_host
,
3732 bool to_different_document
) {
3733 SetIsLoading(render_frame_host
->GetRenderViewHost(), true,
3734 to_different_document
, NULL
);
3737 void WebContentsImpl::DidStopLoading(RenderFrameHost
* render_frame_host
) {
3738 scoped_ptr
<LoadNotificationDetails
> details
;
3740 // Use the last committed entry rather than the active one, in case a
3741 // pending entry has been created.
3742 NavigationEntry
* entry
= controller_
.GetLastCommittedEntry();
3743 Navigator
* navigator
= frame_tree_
.root()->navigator();
3745 // An entry may not exist for a stop when loading an initial blank page or
3746 // if an iframe injected by script into a blank page finishes loading.
3748 base::TimeDelta elapsed
=
3749 base::TimeTicks::Now() - navigator
->GetCurrentLoadStart();
3751 details
.reset(new LoadNotificationDetails(
3752 entry
->GetVirtualURL(),
3753 entry
->GetTransitionType(),
3756 controller_
.GetCurrentEntryIndex()));
3759 SetIsLoading(render_frame_host
->GetRenderViewHost(), false, true,
3763 void WebContentsImpl::DidCancelLoading() {
3764 controller_
.DiscardNonCommittedEntries();
3766 // Update the URL display.
3767 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL
);
3770 void WebContentsImpl::DidAccessInitialDocument() {
3771 has_accessed_initial_document_
= true;
3773 // We may have left a failed browser-initiated navigation in the address bar
3774 // to let the user edit it and try again. Clear it now that content might
3775 // show up underneath it.
3776 if (!IsLoading() && controller_
.GetPendingEntry())
3777 controller_
.DiscardPendingEntry();
3779 // Update the URL display.
3780 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL
);
3783 void WebContentsImpl::DidDisownOpener(RenderFrameHost
* render_frame_host
) {
3784 // No action is necessary if the opener has already been cleared.
3788 // Clear our opener so that future cross-process navigations don't have an
3790 RemoveDestructionObserver(opener_
);
3793 // Notify all swapped out RenderViewHosts for this tab. This is important
3794 // in case we go back to them, or if another window in those processes tries
3795 // to access window.opener.
3796 GetRenderManager()->DidDisownOpener(render_frame_host
);
3799 void WebContentsImpl::DocumentOnLoadCompleted(
3800 RenderFrameHost
* render_frame_host
) {
3801 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3802 DocumentOnLoadCompletedInMainFrame());
3804 // TODO(avi): Remove. http://crbug.com/170921
3805 NotificationService::current()->Notify(
3806 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
,
3807 Source
<WebContents
>(this),
3808 NotificationService::NoDetails());
3811 void WebContentsImpl::UpdateTitle(RenderFrameHost
* render_frame_host
,
3813 const base::string16
& title
,
3814 base::i18n::TextDirection title_direction
) {
3815 RenderViewHost
* rvh
= render_frame_host
->GetRenderViewHost();
3817 // If we have a title, that's a pretty good indication that we've started
3818 // getting useful data.
3819 SetNotWaitingForResponse();
3821 // Try to find the navigation entry, which might not be the current one.
3822 // For example, it might be from a pending RVH for the pending entry.
3823 NavigationEntryImpl
* entry
= controller_
.GetEntryWithPageID(
3824 rvh
->GetSiteInstance(), page_id
);
3826 // We can handle title updates when we don't have an entry in
3827 // UpdateTitleForEntry, but only if the update is from the current RVH.
3828 // TODO(avi): Change to make decisions based on the RenderFrameHost.
3829 if (!entry
&& rvh
!= GetRenderViewHost())
3832 // TODO(evan): make use of title_direction.
3833 // http://code.google.com/p/chromium/issues/detail?id=27094
3834 if (!UpdateTitleForEntry(entry
, title
))
3837 // Broadcast notifications when the UI should be updated.
3838 if (entry
== controller_
.GetEntryAtOffset(0))
3839 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE
);
3842 void WebContentsImpl::UpdateEncoding(RenderFrameHost
* render_frame_host
,
3843 const std::string
& encoding
) {
3844 SetEncoding(encoding
);
3847 void WebContentsImpl::DocumentAvailableInMainFrame(
3848 RenderViewHost
* render_view_host
) {
3849 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3850 DocumentAvailableInMainFrame());
3852 void WebContentsImpl::RouteCloseEvent(RenderViewHost
* rvh
) {
3853 // Tell the active RenderViewHost to run unload handlers and close, as long
3854 // as the request came from a RenderViewHost in the same BrowsingInstance.
3855 // In most cases, we receive this from a swapped out RenderViewHost.
3856 // It is possible to receive it from one that has just been swapped in,
3857 // in which case we might as well deliver the message anyway.
3858 if (rvh
->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()))
3859 GetRenderViewHost()->ClosePage();
3862 void WebContentsImpl::RouteMessageEvent(
3863 RenderViewHost
* rvh
,
3864 const ViewMsg_PostMessage_Params
& params
) {
3865 // Only deliver the message to the active RenderViewHost if the request
3866 // came from a RenderViewHost in the same BrowsingInstance or if this
3867 // WebContents is dedicated to a browser plugin guest.
3868 // Note: This check means that an embedder could theoretically receive a
3869 // postMessage from anyone (not just its own guests). However, this is
3870 // probably not a risk for apps since other pages won't have references
3872 if (!rvh
->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()) &&
3873 !GetBrowserPluginGuest() && !GetBrowserPluginEmbedder())
3876 ViewMsg_PostMessage_Params
new_params(params
);
3878 if (!params
.message_port_ids
.empty()) {
3879 MessagePortMessageFilter
* message_port_message_filter
=
3880 static_cast<RenderProcessHostImpl
*>(GetRenderProcessHost())
3881 ->message_port_message_filter();
3882 message_port_message_filter
->UpdateMessagePortsWithNewRoutes(
3883 params
.message_port_ids
,
3884 &new_params
.new_routing_ids
);
3887 // If there is a source_routing_id, translate it to the routing ID for
3888 // the equivalent swapped out RVH in the target process. If we need
3889 // to create a swapped out RVH for the source tab, we create its opener
3890 // chain as well, since those will also be accessible to the target page.
3891 if (new_params
.source_routing_id
!= MSG_ROUTING_NONE
) {
3892 // Try to look up the WebContents for the source page.
3893 WebContentsImpl
* source_contents
= NULL
;
3894 RenderViewHostImpl
* source_rvh
= RenderViewHostImpl::FromID(
3895 rvh
->GetProcess()->GetID(), params
.source_routing_id
);
3897 source_contents
= static_cast<WebContentsImpl
*>(
3898 source_rvh
->GetDelegate()->GetAsWebContents());
3901 if (source_contents
) {
3902 if (GetBrowserPluginGuest()) {
3903 // We create a swapped out RenderView for the embedder in the guest's
3904 // render process but we intentionally do not expose the embedder's
3905 // opener chain to it.
3906 new_params
.source_routing_id
=
3907 source_contents
->CreateSwappedOutRenderView(GetSiteInstance());
3909 new_params
.source_routing_id
=
3910 source_contents
->CreateOpenerRenderViews(GetSiteInstance());
3913 // We couldn't find it, so don't pass a source frame.
3914 new_params
.source_routing_id
= MSG_ROUTING_NONE
;
3918 // In most cases, we receive this from a swapped out RenderViewHost.
3919 // It is possible to receive it from one that has just been swapped in,
3920 // in which case we might as well deliver the message anyway.
3921 Send(new ViewMsg_PostMessageEvent(GetRoutingID(), new_params
));
3924 bool WebContentsImpl::AddMessageToConsole(int32 level
,
3925 const base::string16
& message
,
3927 const base::string16
& source_id
) {
3930 return delegate_
->AddMessageToConsole(this, level
, message
, line_no
,
3934 WebPreferences
WebContentsImpl::ComputeWebkitPrefs() {
3935 // We want to base the page config off of the actual URL, rather than the
3937 // TODO(nasko): Investigate how to remove the GetActiveEntry usage here,
3938 // as it is deprecated and can be out of sync with GetRenderViewHost().
3939 GURL url
= controller_
.GetActiveEntry()
3940 ? controller_
.GetActiveEntry()->GetURL() : GURL::EmptyGURL();
3942 return GetRenderManager()->current_host()->ComputeWebkitPrefs(url
);
3945 int WebContentsImpl::CreateSwappedOutRenderView(
3946 SiteInstance
* instance
) {
3947 return GetRenderManager()->CreateRenderFrame(
3948 instance
, MSG_ROUTING_NONE
, true, true, true);
3951 void WebContentsImpl::OnUserGesture() {
3952 // Notify observers.
3953 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, DidGetUserGesture());
3955 ResourceDispatcherHostImpl
* rdh
= ResourceDispatcherHostImpl::Get();
3956 if (rdh
) // NULL in unittests.
3957 rdh
->OnUserGesture(this);
3960 void WebContentsImpl::OnIgnoredUIEvent() {
3961 // Notify observers.
3962 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, DidGetIgnoredUIEvent());
3965 void WebContentsImpl::RendererUnresponsive(RenderViewHost
* rvh
,
3966 bool is_during_beforeunload
,
3967 bool is_during_unload
) {
3968 // Don't show hung renderer dialog for a swapped out RVH.
3969 if (rvh
!= GetRenderViewHost())
3972 RenderViewHostImpl
* rvhi
= static_cast<RenderViewHostImpl
*>(rvh
);
3974 // Ignore renderer unresponsive event if debugger is attached to the tab
3975 // since the event may be a result of the renderer sitting on a breakpoint.
3976 // See http://crbug.com/65458
3977 if (DevToolsAgentHost::IsDebuggerAttached(this))
3980 if (is_during_beforeunload
|| is_during_unload
) {
3981 // Hang occurred while firing the beforeunload/unload handler.
3982 // Pretend the handler fired so tab closing continues as if it had.
3983 rvhi
->set_sudden_termination_allowed(true);
3985 if (!GetRenderManager()->ShouldCloseTabOnUnresponsiveRenderer())
3988 // If the tab hangs in the beforeunload/unload handler there's really
3989 // nothing we can do to recover. If the hang is in the beforeunload handler,
3990 // pretend the beforeunload listeners have all fired and allow the delegate
3991 // to continue closing; the user will not have the option of cancelling the
3992 // close. Otherwise, pretend the unload listeners have all fired and close
3995 if (is_during_beforeunload
&& delegate_
) {
3996 delegate_
->BeforeUnloadFired(this, true, &close
);
4003 if (!GetRenderViewHostImpl() || !GetRenderViewHostImpl()->IsRenderViewLive())
4007 delegate_
->RendererUnresponsive(this);
4010 void WebContentsImpl::RendererResponsive(RenderViewHost
* render_view_host
) {
4012 delegate_
->RendererResponsive(this);
4015 void WebContentsImpl::LoadStateChanged(
4017 const net::LoadStateWithParam
& load_state
,
4018 uint64 upload_position
,
4019 uint64 upload_size
) {
4020 load_state_
= load_state
;
4021 upload_position_
= upload_position
;
4022 upload_size_
= upload_size
;
4023 load_state_host_
= net::IDNToUnicode(url
.host(),
4024 GetContentClient()->browser()->GetAcceptLangs(
4025 GetBrowserContext()));
4026 if (load_state_
.state
== net::LOAD_STATE_READING_RESPONSE
)
4027 SetNotWaitingForResponse();
4029 NotifyNavigationStateChanged(static_cast<InvalidateTypes
>(
4030 INVALIDATE_TYPE_LOAD
| INVALIDATE_TYPE_TAB
));
4034 void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
4035 bool proceed
, const base::TimeTicks
& proceed_time
,
4036 bool* proceed_to_fire_unload
) {
4037 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
4038 BeforeUnloadFired(proceed_time
));
4040 delegate_
->BeforeUnloadFired(this, proceed
, proceed_to_fire_unload
);
4041 // Note: |this| might be deleted at this point.
4044 void WebContentsImpl::RenderProcessGoneFromRenderManager(
4045 RenderViewHost
* render_view_host
) {
4046 DCHECK(crashed_status_
!= base::TERMINATION_STATUS_STILL_RUNNING
);
4047 RenderViewTerminated(render_view_host
, crashed_status_
, crashed_error_code_
);
4050 void WebContentsImpl::UpdateRenderViewSizeForRenderManager() {
4051 // TODO(brettw) this is a hack. See WebContentsView::SizeContents.
4052 gfx::Size size
= GetSizeForNewRenderView();
4053 // 0x0 isn't a valid window size (minimal window size is 1x1) but it may be
4054 // here during container initialization and normal window size will be set
4055 // later. In case of tab duplication this resizing to 0x0 prevents setting
4056 // normal size later so just ignore it.
4057 if (!size
.IsEmpty())
4058 view_
->SizeContents(size
);
4061 void WebContentsImpl::CancelModalDialogsForRenderManager() {
4062 // We need to cancel modal dialogs when doing a process swap, since the load
4063 // deferrer would prevent us from swapping out.
4064 if (dialog_manager_
)
4065 dialog_manager_
->CancelActiveAndPendingDialogs(this);
4068 void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost
* old_host
,
4069 RenderFrameHost
* new_host
,
4070 bool is_main_frame
) {
4071 if (is_main_frame
) {
4072 NotifyViewSwapped(old_host
? old_host
->GetRenderViewHost() : NULL
,
4073 new_host
->GetRenderViewHost());
4075 // Make sure the visible RVH reflects the new delegate's preferences.
4077 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
4079 view_
->RenderViewSwappedIn(new_host
->GetRenderViewHost());
4082 NotifyFrameSwapped(old_host
, new_host
);
4085 int WebContentsImpl::CreateOpenerRenderViewsForRenderManager(
4086 SiteInstance
* instance
) {
4088 return MSG_ROUTING_NONE
;
4090 // Recursively create RenderViews for anything else in the opener chain.
4091 return opener_
->CreateOpenerRenderViews(instance
);
4094 int WebContentsImpl::CreateOpenerRenderViews(SiteInstance
* instance
) {
4095 int opener_route_id
= MSG_ROUTING_NONE
;
4097 // If this tab has an opener, ensure it has a RenderView in the given
4098 // SiteInstance as well.
4100 opener_route_id
= opener_
->CreateOpenerRenderViews(instance
);
4102 // If any of the renderers (current, pending, or swapped out) for this
4103 // WebContents has the same SiteInstance, use it.
4104 if (GetRenderManager()->current_host()->GetSiteInstance() == instance
)
4105 return GetRenderManager()->current_host()->GetRoutingID();
4107 if (GetRenderManager()->pending_render_view_host() &&
4108 GetRenderManager()->pending_render_view_host()->GetSiteInstance() ==
4110 return GetRenderManager()->pending_render_view_host()->GetRoutingID();
4112 RenderViewHostImpl
* rvh
= GetRenderManager()->GetSwappedOutRenderViewHost(
4115 return rvh
->GetRoutingID();
4117 // Create a swapped out RenderView in the given SiteInstance if none exists,
4118 // setting its opener to the given route_id. Return the new view's route_id.
4119 return GetRenderManager()->CreateRenderFrame(
4120 instance
, opener_route_id
, true, true, true);
4123 NavigationControllerImpl
& WebContentsImpl::GetControllerForRenderManager() {
4124 return GetController();
4127 WebUIImpl
* WebContentsImpl::CreateWebUIForRenderManager(const GURL
& url
) {
4128 return static_cast<WebUIImpl
*>(CreateWebUI(url
));
4132 WebContentsImpl::GetLastCommittedNavigationEntryForRenderManager() {
4133 return controller_
.GetLastCommittedEntry();
4136 bool WebContentsImpl::CreateRenderViewForRenderManager(
4137 RenderViewHost
* render_view_host
,
4138 int opener_route_id
,
4139 int proxy_routing_id
,
4140 bool for_main_frame_navigation
) {
4141 TRACE_EVENT0("browser,navigation",
4142 "WebContentsImpl::CreateRenderViewForRenderManager");
4143 // Can be NULL during tests.
4144 RenderWidgetHostViewBase
* rwh_view
;
4145 // TODO(kenrb): RenderWidgetHostViewChildFrame special casing is temporary
4146 // until RenderWidgetHost is attached to RenderFrameHost. We need to special
4147 // case this because RWH is still a base class of RenderViewHost, and child
4148 // frame RWHVs are unique in that they do not have their own WebContents.
4149 if (!for_main_frame_navigation
) {
4150 RenderWidgetHostViewChildFrame
* rwh_view_child
=
4151 new RenderWidgetHostViewChildFrame(render_view_host
);
4152 rwh_view
= rwh_view_child
;
4154 rwh_view
= view_
->CreateViewForWidget(render_view_host
);
4157 // Now that the RenderView has been created, we need to tell it its size.
4159 rwh_view
->SetSize(GetSizeForNewRenderView());
4161 // Make sure we use the correct starting page_id in the new RenderView.
4162 UpdateMaxPageIDIfNecessary(render_view_host
);
4164 GetMaxPageIDForSiteInstance(render_view_host
->GetSiteInstance());
4166 if (!static_cast<RenderViewHostImpl
*>(
4167 render_view_host
)->CreateRenderView(base::string16(),
4171 created_with_opener_
)) {
4175 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
4176 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
4177 // linux. See crbug.com/83941.
4179 if (RenderWidgetHost
* render_widget_host
= rwh_view
->GetRenderWidgetHost())
4180 render_widget_host
->WasResized();
4187 bool WebContentsImpl::CreateRenderFrameForRenderManager(
4188 RenderFrameHost
* render_frame_host
,
4189 int parent_routing_id
) {
4190 TRACE_EVENT0("browser,navigation",
4191 "WebContentsImpl::CreateRenderFrameForRenderManager");
4193 RenderFrameHostImpl
* rfh
=
4194 static_cast<RenderFrameHostImpl
*>(render_frame_host
);
4195 if (!rfh
->CreateRenderFrame(parent_routing_id
))
4198 // TODO(nasko): When RenderWidgetHost is owned by RenderFrameHost, the passed
4199 // RenderFrameHost will have to be associated with the appropriate
4200 // RenderWidgetHostView or a new one should be created here.
4205 #if defined(OS_ANDROID)
4207 base::android::ScopedJavaLocalRef
<jobject
>
4208 WebContentsImpl::GetJavaWebContents() {
4209 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
4210 return GetWebContentsAndroid()->GetJavaObject();
4213 WebContentsAndroid
* WebContentsImpl::GetWebContentsAndroid() {
4214 WebContentsAndroid
* web_contents_android
=
4215 static_cast<WebContentsAndroid
*>(GetUserData(kWebContentsAndroidKey
));
4216 if (!web_contents_android
) {
4217 web_contents_android
= new WebContentsAndroid(this);
4218 SetUserData(kWebContentsAndroidKey
, web_contents_android
);
4220 return web_contents_android
;
4223 bool WebContentsImpl::CreateRenderViewForInitialEmptyDocument() {
4224 return CreateRenderViewForRenderManager(GetRenderViewHost(),
4230 #elif defined(OS_MACOSX)
4232 void WebContentsImpl::SetAllowOtherViews(bool allow
) {
4233 view_
->SetAllowOtherViews(allow
);
4236 bool WebContentsImpl::GetAllowOtherViews() {
4237 return view_
->GetAllowOtherViews();
4242 void WebContentsImpl::OnDialogClosed(int render_process_id
,
4243 int render_frame_id
,
4244 IPC::Message
* reply_msg
,
4245 bool dialog_was_suppressed
,
4247 const base::string16
& user_input
) {
4248 RenderFrameHostImpl
* rfh
= RenderFrameHostImpl::FromID(render_process_id
,
4250 last_dialog_suppressed_
= dialog_was_suppressed
;
4252 if (is_showing_before_unload_dialog_
&& !success
) {
4253 // If a beforeunload dialog is canceled, we need to stop the throbber from
4254 // spinning, since we forced it to start spinning in Navigate.
4256 DidStopLoading(rfh
);
4257 controller_
.DiscardNonCommittedEntries();
4259 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
4260 BeforeUnloadDialogCancelled());
4263 is_showing_before_unload_dialog_
= false;
4265 rfh
->JavaScriptDialogClosed(reply_msg
, success
, user_input
,
4266 dialog_was_suppressed
);
4268 // Don't leak the sync IPC reply if the RFH or process is gone.
4273 void WebContentsImpl::SetEncoding(const std::string
& encoding
) {
4274 if (encoding
== last_reported_encoding_
)
4276 last_reported_encoding_
= encoding
;
4278 canonical_encoding_
= GetContentClient()->browser()->
4279 GetCanonicalEncodingNameByAliasName(encoding
);
4282 void WebContentsImpl::CreateViewAndSetSizeForRVH(RenderViewHost
* rvh
) {
4283 RenderWidgetHostViewBase
* rwh_view
= view_
->CreateViewForWidget(rvh
);
4284 // Can be NULL during tests.
4286 rwh_view
->SetSize(GetContainerBounds().size());
4289 bool WebContentsImpl::IsHidden() {
4290 return capturer_count_
== 0 && !should_normally_be_visible_
;
4293 RenderFrameHostManager
* WebContentsImpl::GetRenderManager() const {
4294 return frame_tree_
.root()->render_manager();
4297 RenderViewHostImpl
* WebContentsImpl::GetRenderViewHostImpl() {
4298 return static_cast<RenderViewHostImpl
*>(GetRenderViewHost());
4301 BrowserPluginGuest
* WebContentsImpl::GetBrowserPluginGuest() const {
4302 return browser_plugin_guest_
.get();
4305 void WebContentsImpl::SetBrowserPluginGuest(BrowserPluginGuest
* guest
) {
4306 CHECK(!browser_plugin_guest_
);
4307 browser_plugin_guest_
.reset(guest
);
4310 BrowserPluginEmbedder
* WebContentsImpl::GetBrowserPluginEmbedder() const {
4311 return browser_plugin_embedder_
.get();
4314 void WebContentsImpl::ClearPowerSaveBlockers(
4315 RenderFrameHost
* render_frame_host
) {
4316 RemoveAllMediaPlayerEntries(render_frame_host
, &active_audio_players_
);
4317 RemoveAllMediaPlayerEntries(render_frame_host
, &active_video_players_
);
4318 MaybeReleasePowerSaveBlockers();
4321 void WebContentsImpl::ClearAllPowerSaveBlockers() {
4322 active_audio_players_
.clear();
4323 active_video_players_
.clear();
4324 audio_power_save_blocker_
.reset();
4325 video_power_save_blocker_
.reset();
4328 gfx::Size
WebContentsImpl::GetSizeForNewRenderView() {
4331 size
= delegate_
->GetSizeForNewRenderView(this);
4333 size
= GetContainerBounds().size();
4337 void WebContentsImpl::OnFrameRemoved(RenderFrameHost
* render_frame_host
) {
4339 WebContentsObserver
, observers_
, FrameDetached(render_frame_host
));
4342 void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size
& old_size
) {
4345 const gfx::Size new_size
= GetPreferredSize();
4346 if (new_size
!= old_size
)
4347 delegate_
->UpdatePreferredSize(this, new_size
);
4350 void WebContentsImpl::AddMediaPlayerEntry(int64 player_cookie
,
4351 ActiveMediaPlayerMap
* player_map
) {
4352 const uintptr_t key
=
4353 reinterpret_cast<uintptr_t>(render_frame_message_source_
);
4354 DCHECK(std::find((*player_map
)[key
].begin(),
4355 (*player_map
)[key
].end(),
4356 player_cookie
) == (*player_map
)[key
].end());
4357 (*player_map
)[key
].push_back(player_cookie
);
4360 void WebContentsImpl::RemoveMediaPlayerEntry(int64 player_cookie
,
4361 ActiveMediaPlayerMap
* player_map
) {
4362 const uintptr_t key
=
4363 reinterpret_cast<uintptr_t>(render_frame_message_source_
);
4364 ActiveMediaPlayerMap::iterator it
= player_map
->find(key
);
4365 if (it
== player_map
->end())
4368 // Remove the player.
4369 PlayerList::iterator player_it
=
4370 std::find(it
->second
.begin(), it
->second
.end(), player_cookie
);
4371 if (player_it
!= it
->second
.end())
4372 it
->second
.erase(player_it
);
4374 // If there are no players left, remove the map entry.
4375 if (it
->second
.empty())
4376 player_map
->erase(it
);
4379 void WebContentsImpl::RemoveAllMediaPlayerEntries(
4380 RenderFrameHost
* render_frame_host
,
4381 ActiveMediaPlayerMap
* player_map
) {
4382 ActiveMediaPlayerMap::iterator it
=
4383 player_map
->find(reinterpret_cast<uintptr_t>(render_frame_host
));
4384 if (it
== player_map
->end())
4386 player_map
->erase(it
);
4389 void WebContentsImpl::ResumeResponseDeferredAtStart() {
4390 FrameTreeNode
* node
= frame_tree_
.root();
4391 node
->render_manager()->ResumeResponseDeferredAtStart();
4394 void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable
) {
4395 force_disable_overscroll_content_
= force_disable
;
4397 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
4400 } // namespace content