Use native radiobutton for Default Search Engine picker dialog.
[chromium-blink-merge.git] / content / browser / web_contents / web_contents_impl.cc
blobed930379a66a3b8f3935c878d1d0a81355faf0d5
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"
7 #include <utility>
9 #include "base/command_line.h"
10 #include "base/lazy_instance.h"
11 #include "base/logging.h"
12 #include "base/metrics/histogram.h"
13 #include "base/process/process.h"
14 #include "base/profiler/scoped_tracker.h"
15 #include "base/strings/string16.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/string_util.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/time/time.h"
20 #include "base/trace_event/trace_event.h"
21 #include "components/mime_util/mime_util.h"
22 #include "content/browser/accessibility/accessibility_mode_helper.h"
23 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
24 #include "content/browser/bad_message.h"
25 #include "content/browser/browser_plugin/browser_plugin_embedder.h"
26 #include "content/browser/browser_plugin/browser_plugin_guest.h"
27 #include "content/browser/child_process_security_policy_impl.h"
28 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
29 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
30 #include "content/browser/download/download_stats.h"
31 #include "content/browser/download/mhtml_generation_manager.h"
32 #include "content/browser/download/save_package.h"
33 #include "content/browser/frame_host/cross_process_frame_connector.h"
34 #include "content/browser/frame_host/interstitial_page_impl.h"
35 #include "content/browser/frame_host/navigation_entry_impl.h"
36 #include "content/browser/frame_host/navigator_impl.h"
37 #include "content/browser/frame_host/render_frame_host_impl.h"
38 #include "content/browser/frame_host/render_widget_host_view_child_frame.h"
39 #include "content/browser/geolocation/geolocation_service_context.h"
40 #include "content/browser/host_zoom_map_impl.h"
41 #include "content/browser/loader/resource_dispatcher_host_impl.h"
42 #include "content/browser/manifest/manifest_manager_host.h"
43 #include "content/browser/media/audio_stream_monitor.h"
44 #include "content/browser/media/capture/web_contents_audio_muter.h"
45 #include "content/browser/message_port_message_filter.h"
46 #include "content/browser/plugin_content_origin_whitelist.h"
47 #include "content/browser/power_save_blocker_impl.h"
48 #include "content/browser/renderer_host/render_process_host_impl.h"
49 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
50 #include "content/browser/renderer_host/render_view_host_impl.h"
51 #include "content/browser/renderer_host/render_widget_host_impl.h"
52 #include "content/browser/renderer_host/render_widget_host_view_base.h"
53 #include "content/browser/screen_orientation/screen_orientation_dispatcher_host_impl.h"
54 #include "content/browser/site_instance_impl.h"
55 #include "content/browser/web_contents/web_contents_view_guest.h"
56 #include "content/browser/webui/generic_handler.h"
57 #include "content/browser/webui/web_ui_controller_factory_registry.h"
58 #include "content/browser/webui/web_ui_impl.h"
59 #include "content/common/browser_plugin/browser_plugin_constants.h"
60 #include "content/common/browser_plugin/browser_plugin_messages.h"
61 #include "content/common/frame_messages.h"
62 #include "content/common/image_messages.h"
63 #include "content/common/input_messages.h"
64 #include "content/common/ssl_status_serialization.h"
65 #include "content/common/view_messages.h"
66 #include "content/public/browser/ax_event_notification_details.h"
67 #include "content/public/browser/browser_context.h"
68 #include "content/public/browser/browser_plugin_guest_manager.h"
69 #include "content/public/browser/content_browser_client.h"
70 #include "content/public/browser/devtools_agent_host.h"
71 #include "content/public/browser/download_manager.h"
72 #include "content/public/browser/download_url_parameters.h"
73 #include "content/public/browser/invalidate_type.h"
74 #include "content/public/browser/javascript_dialog_manager.h"
75 #include "content/public/browser/load_from_memory_cache_details.h"
76 #include "content/public/browser/load_notification_details.h"
77 #include "content/public/browser/navigation_details.h"
78 #include "content/public/browser/notification_details.h"
79 #include "content/public/browser/notification_service.h"
80 #include "content/public/browser/render_widget_host_iterator.h"
81 #include "content/public/browser/resource_request_details.h"
82 #include "content/public/browser/screen_orientation_dispatcher_host.h"
83 #include "content/public/browser/storage_partition.h"
84 #include "content/public/browser/user_metrics.h"
85 #include "content/public/browser/web_contents_delegate.h"
86 #include "content/public/browser/web_contents_observer.h"
87 #include "content/public/common/bindings_policy.h"
88 #include "content/public/common/content_constants.h"
89 #include "content/public/common/content_switches.h"
90 #include "content/public/common/page_zoom.h"
91 #include "content/public/common/result_codes.h"
92 #include "content/public/common/url_constants.h"
93 #include "content/public/common/url_utils.h"
94 #include "content/public/common/web_preferences.h"
95 #include "net/base/net_util.h"
96 #include "net/http/http_cache.h"
97 #include "net/http/http_transaction_factory.h"
98 #include "net/url_request/url_request_context.h"
99 #include "net/url_request/url_request_context_getter.h"
100 #include "ui/base/layout.h"
101 #include "ui/gfx/display.h"
102 #include "ui/gfx/screen.h"
103 #include "ui/gl/gl_switches.h"
105 #if defined(ENABLE_BROWSER_CDMS)
106 #include "content/browser/media/media_web_contents_observer.h"
107 #endif
109 #if defined(OS_ANDROID)
110 #include "content/browser/android/content_video_view.h"
111 #include "content/browser/android/date_time_chooser_android.h"
112 #include "content/browser/android/media_players_observer.h"
113 #include "content/browser/media/android/browser_media_player_manager.h"
114 #include "content/browser/web_contents/web_contents_android.h"
115 #endif
117 #if defined(OS_MACOSX)
118 #include "base/mac/foundation_util.h"
119 #endif
121 namespace content {
122 namespace {
124 const int kMinimumDelayBetweenLoadingUpdatesMS = 100;
125 const char kDotGoogleDotCom[] = ".google.com";
127 #if defined(OS_ANDROID)
128 const char kWebContentsAndroidKey[] = "web_contents_android";
129 #endif // OS_ANDROID
131 base::LazyInstance<std::vector<WebContentsImpl::CreatedCallback> >
132 g_created_callbacks = LAZY_INSTANCE_INITIALIZER;
134 static int StartDownload(RenderFrameHost* rfh,
135 const GURL& url,
136 bool is_favicon,
137 uint32_t max_bitmap_size,
138 bool bypass_cache) {
139 static int g_next_image_download_id = 0;
140 rfh->Send(new ImageMsg_DownloadImage(rfh->GetRoutingID(),
141 ++g_next_image_download_id,
142 url,
143 is_favicon,
144 max_bitmap_size,
145 bypass_cache));
146 return g_next_image_download_id;
149 void NotifyCacheOnIO(
150 scoped_refptr<net::URLRequestContextGetter> request_context,
151 const GURL& url,
152 const std::string& http_method) {
153 net::HttpCache* cache = request_context->GetURLRequestContext()->
154 http_transaction_factory()->GetCache();
155 if (cache)
156 cache->OnExternalCacheHit(url, http_method);
159 // Helper function for retrieving all the sites in a frame tree.
160 bool CollectSites(BrowserContext* context,
161 std::set<GURL>* sites,
162 FrameTreeNode* node) {
163 sites->insert(SiteInstance::GetSiteForURL(context, node->current_url()));
164 return true;
167 bool ForEachFrameInternal(
168 const base::Callback<void(RenderFrameHost*)>& on_frame,
169 FrameTreeNode* node) {
170 on_frame.Run(node->current_frame_host());
171 return true;
174 bool ForEachPendingFrameInternal(
175 const base::Callback<void(RenderFrameHost*)>& on_frame,
176 FrameTreeNode* node) {
177 RenderFrameHost* pending_frame_host =
178 node->render_manager()->pending_frame_host();
179 if (pending_frame_host)
180 on_frame.Run(pending_frame_host);
181 return true;
184 void SendToAllFramesInternal(IPC::Message* message, RenderFrameHost* rfh) {
185 IPC::Message* message_copy = new IPC::Message(*message);
186 message_copy->set_routing_id(rfh->GetRoutingID());
187 rfh->Send(message_copy);
190 void AddRenderWidgetHostViewToSet(std::set<RenderWidgetHostView*>* set,
191 RenderFrameHost* rfh) {
192 RenderWidgetHostView* rwhv = static_cast<RenderFrameHostImpl*>(rfh)
193 ->frame_tree_node()
194 ->render_manager()
195 ->GetRenderWidgetHostView();
196 set->insert(rwhv);
199 void SetAccessibilityModeOnFrame(AccessibilityMode mode,
200 RenderFrameHost* frame_host) {
201 static_cast<RenderFrameHostImpl*>(frame_host)->SetAccessibilityMode(mode);
204 } // namespace
206 WebContents* WebContents::Create(const WebContents::CreateParams& params) {
207 return WebContentsImpl::CreateWithOpener(
208 params, static_cast<WebContentsImpl*>(params.opener));
211 WebContents* WebContents::CreateWithSessionStorage(
212 const WebContents::CreateParams& params,
213 const SessionStorageNamespaceMap& session_storage_namespace_map) {
214 WebContentsImpl* new_contents = new WebContentsImpl(
215 params.browser_context, NULL);
217 for (SessionStorageNamespaceMap::const_iterator it =
218 session_storage_namespace_map.begin();
219 it != session_storage_namespace_map.end();
220 ++it) {
221 new_contents->GetController()
222 .SetSessionStorageNamespace(it->first, it->second.get());
225 new_contents->Init(params);
226 return new_contents;
229 void WebContentsImpl::FriendZone::AddCreatedCallbackForTesting(
230 const CreatedCallback& callback) {
231 g_created_callbacks.Get().push_back(callback);
234 void WebContentsImpl::FriendZone::RemoveCreatedCallbackForTesting(
235 const CreatedCallback& callback) {
236 for (size_t i = 0; i < g_created_callbacks.Get().size(); ++i) {
237 if (g_created_callbacks.Get().at(i).Equals(callback)) {
238 g_created_callbacks.Get().erase(g_created_callbacks.Get().begin() + i);
239 return;
244 WebContents* WebContents::FromRenderViewHost(const RenderViewHost* rvh) {
245 return rvh->GetDelegate()->GetAsWebContents();
248 WebContents* WebContents::FromRenderFrameHost(RenderFrameHost* rfh) {
249 RenderFrameHostImpl* rfh_impl = static_cast<RenderFrameHostImpl*>(rfh);
250 if (!rfh_impl)
251 return NULL;
252 return rfh_impl->delegate()->GetAsWebContents();
255 // WebContentsImpl::DestructionObserver ----------------------------------------
257 class WebContentsImpl::DestructionObserver : public WebContentsObserver {
258 public:
259 DestructionObserver(WebContentsImpl* owner, WebContents* watched_contents)
260 : WebContentsObserver(watched_contents),
261 owner_(owner) {
264 // WebContentsObserver:
265 void WebContentsDestroyed() override {
266 owner_->OnWebContentsDestroyed(
267 static_cast<WebContentsImpl*>(web_contents()));
270 private:
271 WebContentsImpl* owner_;
273 DISALLOW_COPY_AND_ASSIGN(DestructionObserver);
276 WebContentsImpl::ColorChooserInfo::ColorChooserInfo(int render_process_id,
277 int render_frame_id,
278 ColorChooser* chooser,
279 int identifier)
280 : render_process_id(render_process_id),
281 render_frame_id(render_frame_id),
282 chooser(chooser),
283 identifier(identifier) {
286 WebContentsImpl::ColorChooserInfo::~ColorChooserInfo() {
289 // WebContentsImpl -------------------------------------------------------------
291 WebContentsImpl::WebContentsImpl(BrowserContext* browser_context,
292 WebContentsImpl* opener)
293 : delegate_(NULL),
294 controller_(this, browser_context),
295 render_view_host_delegate_view_(NULL),
296 opener_(opener),
297 created_with_opener_(!!opener),
298 #if defined(OS_WIN)
299 accessible_parent_(NULL),
300 #endif
301 frame_tree_(new NavigatorImpl(&controller_, this),
302 this,
303 this,
304 this,
305 this),
306 is_loading_(false),
307 is_load_to_different_document_(false),
308 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING),
309 crashed_error_code_(0),
310 waiting_for_response_(false),
311 load_state_(net::LOAD_STATE_IDLE, base::string16()),
312 upload_size_(0),
313 upload_position_(0),
314 displayed_insecure_content_(false),
315 has_accessed_initial_document_(false),
316 theme_color_(SK_ColorTRANSPARENT),
317 last_sent_theme_color_(SK_ColorTRANSPARENT),
318 capturer_count_(0),
319 should_normally_be_visible_(true),
320 is_being_destroyed_(false),
321 notify_disconnection_(false),
322 dialog_manager_(NULL),
323 is_showing_before_unload_dialog_(false),
324 last_active_time_(base::TimeTicks::Now()),
325 closed_by_user_gesture_(false),
326 minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)),
327 maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)),
328 render_view_message_source_(NULL),
329 render_frame_message_source_(NULL),
330 fullscreen_widget_routing_id_(MSG_ROUTING_NONE),
331 fullscreen_widget_had_focus_at_shutdown_(false),
332 is_subframe_(false),
333 force_disable_overscroll_content_(false),
334 last_dialog_suppressed_(false),
335 geolocation_service_context_(new GeolocationServiceContext()),
336 accessibility_mode_(
337 BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()),
338 virtual_keyboard_requested_(false),
339 loading_weak_factory_(this) {
340 frame_tree_.SetFrameRemoveListener(
341 base::Bind(&WebContentsImpl::OnFrameRemoved,
342 base::Unretained(this)));
343 #if defined(ENABLE_BROWSER_CDMS)
344 media_web_contents_observer_.reset(new MediaWebContentsObserver(this));
345 #endif
347 #if defined(OS_ANDROID)
348 audio_state_provider_.reset(new MediaPlayersObserver(this));
349 #else
350 audio_state_provider_.reset(new AudioStreamMonitor(this));
351 #endif
354 WebContentsImpl::~WebContentsImpl() {
355 is_being_destroyed_ = true;
357 // Delete all RFH pending shutdown, which will lead the corresponding RVH to
358 // shutdown and be deleted as well.
359 frame_tree_.ForEach(
360 base::Bind(&RenderFrameHostManager::ClearRFHsPendingShutdown));
362 ClearAllPowerSaveBlockers();
364 for (std::set<RenderWidgetHostImpl*>::iterator iter =
365 created_widgets_.begin(); iter != created_widgets_.end(); ++iter) {
366 (*iter)->DetachDelegate();
368 created_widgets_.clear();
370 // Clear out any JavaScript state.
371 if (dialog_manager_)
372 dialog_manager_->ResetDialogState(this);
374 if (color_chooser_info_.get())
375 color_chooser_info_->chooser->End();
377 NotifyDisconnected();
379 // Notify any observer that have a reference on this WebContents.
380 NotificationService::current()->Notify(
381 NOTIFICATION_WEB_CONTENTS_DESTROYED,
382 Source<WebContents>(this),
383 NotificationService::NoDetails());
385 // Destroy all frame tree nodes except for the root; this notifies observers.
386 frame_tree_.root()->ResetForNewProcess();
387 GetRenderManager()->ResetProxyHosts();
389 // Manually call the observer methods for the root frame tree node.
390 RenderFrameHostManager* root = GetRenderManager();
392 if (root->pending_frame_host())
393 root->pending_frame_host()->SetRenderFrameCreated(false);
394 root->current_frame_host()->SetRenderFrameCreated(false);
396 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
397 FrameDeleted(root->current_frame_host()));
399 if (root->pending_render_view_host()) {
400 FOR_EACH_OBSERVER(WebContentsObserver,
401 observers_,
402 RenderViewDeleted(root->pending_render_view_host()));
405 FOR_EACH_OBSERVER(WebContentsObserver,
406 observers_,
407 RenderViewDeleted(root->current_host()));
409 FOR_EACH_OBSERVER(WebContentsObserver,
410 observers_,
411 WebContentsDestroyed());
413 FOR_EACH_OBSERVER(WebContentsObserver,
414 observers_,
415 ResetWebContents());
417 SetDelegate(NULL);
419 STLDeleteContainerPairSecondPointers(destruction_observers_.begin(),
420 destruction_observers_.end());
423 WebContentsImpl* WebContentsImpl::CreateWithOpener(
424 const WebContents::CreateParams& params,
425 WebContentsImpl* opener) {
426 TRACE_EVENT0("browser", "WebContentsImpl::CreateWithOpener");
427 WebContentsImpl* new_contents = new WebContentsImpl(
428 params.browser_context, params.opener_suppressed ? NULL : opener);
430 if (params.guest_delegate) {
431 // This makes |new_contents| act as a guest.
432 // For more info, see comment above class BrowserPluginGuest.
433 BrowserPluginGuest::Create(new_contents, params.guest_delegate);
434 // We are instantiating a WebContents for browser plugin. Set its subframe
435 // bit to true.
436 new_contents->is_subframe_ = true;
438 new_contents->Init(params);
439 return new_contents;
442 // static
443 std::vector<WebContentsImpl*> WebContentsImpl::GetAllWebContents() {
444 std::vector<WebContentsImpl*> result;
445 scoped_ptr<RenderWidgetHostIterator> widgets(
446 RenderWidgetHostImpl::GetRenderWidgetHosts());
447 std::set<WebContentsImpl*> web_contents_set;
448 while (RenderWidgetHost* rwh = widgets->GetNextHost()) {
449 if (!rwh->IsRenderView())
450 continue;
451 RenderViewHost* rvh = RenderViewHost::From(rwh);
452 if (!rvh)
453 continue;
454 WebContents* web_contents = WebContents::FromRenderViewHost(rvh);
455 if (!web_contents)
456 continue;
457 WebContentsImpl* wci = static_cast<WebContentsImpl*>(web_contents);
458 if (web_contents_set.find(wci) == web_contents_set.end()) {
459 web_contents_set.insert(wci);
460 result.push_back(wci);
463 return result;
466 RenderFrameHostManager* WebContentsImpl::GetRenderManagerForTesting() {
467 return GetRenderManager();
470 bool WebContentsImpl::OnMessageReceived(RenderViewHost* render_view_host,
471 const IPC::Message& message) {
472 return OnMessageReceived(render_view_host, NULL, message);
475 bool WebContentsImpl::OnMessageReceived(RenderViewHost* render_view_host,
476 RenderFrameHost* render_frame_host,
477 const IPC::Message& message) {
478 DCHECK(render_view_host || render_frame_host);
479 if (GetWebUI() &&
480 static_cast<WebUIImpl*>(GetWebUI())->OnMessageReceived(message)) {
481 return true;
484 ObserverListBase<WebContentsObserver>::Iterator it(&observers_);
485 WebContentsObserver* observer;
486 if (render_frame_host) {
487 while ((observer = it.GetNext()) != NULL)
488 if (observer->OnMessageReceived(message, render_frame_host))
489 return true;
490 } else {
491 while ((observer = it.GetNext()) != NULL)
492 if (observer->OnMessageReceived(message))
493 return true;
496 // Message handlers should be aware of which
497 // RenderViewHost/RenderFrameHost sent the message, which is temporarily
498 // stored in render_(view|frame)_message_source_.
499 if (render_frame_host)
500 render_frame_message_source_ = render_frame_host;
501 else
502 render_view_message_source_ = render_view_host;
504 bool handled = true;
505 IPC_BEGIN_MESSAGE_MAP(WebContentsImpl, message)
506 IPC_MESSAGE_HANDLER(FrameHostMsg_DomOperationResponse,
507 OnDomOperationResponse)
508 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeThemeColor,
509 OnThemeColorChanged)
510 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishDocumentLoad,
511 OnDocumentLoadedInFrame)
512 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishLoad, OnDidFinishLoad)
513 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenColorChooser, OnOpenColorChooser)
514 IPC_MESSAGE_HANDLER(FrameHostMsg_EndColorChooser, OnEndColorChooser)
515 IPC_MESSAGE_HANDLER(FrameHostMsg_SetSelectedColorInColorChooser,
516 OnSetSelectedColorInColorChooser)
517 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPlayingNotification,
518 OnMediaPlayingNotification)
519 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPausedNotification,
520 OnMediaPausedNotification)
521 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFirstVisuallyNonEmptyPaint,
522 OnFirstVisuallyNonEmptyPaint)
523 IPC_MESSAGE_HANDLER(ViewHostMsg_DidLoadResourceFromMemoryCache,
524 OnDidLoadResourceFromMemoryCache)
525 IPC_MESSAGE_HANDLER(ViewHostMsg_DidDisplayInsecureContent,
526 OnDidDisplayInsecureContent)
527 IPC_MESSAGE_HANDLER(ViewHostMsg_DidRunInsecureContent,
528 OnDidRunInsecureContent)
529 IPC_MESSAGE_HANDLER(ViewHostMsg_GoToEntryAtOffset, OnGoToEntryAtOffset)
530 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateZoomLimits, OnUpdateZoomLimits)
531 IPC_MESSAGE_HANDLER(ViewHostMsg_EnumerateDirectory, OnEnumerateDirectory)
532 IPC_MESSAGE_HANDLER(ViewHostMsg_RegisterProtocolHandler,
533 OnRegisterProtocolHandler)
534 IPC_MESSAGE_HANDLER(ViewHostMsg_UnregisterProtocolHandler,
535 OnUnregisterProtocolHandler)
536 IPC_MESSAGE_HANDLER(ViewHostMsg_Find_Reply, OnFindReply)
537 IPC_MESSAGE_HANDLER(ViewHostMsg_AppCacheAccessed, OnAppCacheAccessed)
538 IPC_MESSAGE_HANDLER(ViewHostMsg_WebUISend, OnWebUISend)
539 #if defined(ENABLE_PLUGINS)
540 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung, OnPepperPluginHung)
541 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed, OnPluginCrashed)
542 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission,
543 OnRequestPpapiBrokerPermission)
544 IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_Attach,
545 OnBrowserPluginMessage(render_frame_host,
546 message))
547 #endif
548 IPC_MESSAGE_HANDLER(ImageHostMsg_DidDownloadImage, OnDidDownloadImage)
549 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateFaviconURL, OnUpdateFaviconURL)
550 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowValidationMessage,
551 OnShowValidationMessage)
552 IPC_MESSAGE_HANDLER(ViewHostMsg_HideValidationMessage,
553 OnHideValidationMessage)
554 IPC_MESSAGE_HANDLER(ViewHostMsg_MoveValidationMessage,
555 OnMoveValidationMessage)
556 #if defined(OS_ANDROID)
557 IPC_MESSAGE_HANDLER(ViewHostMsg_FindMatchRects_Reply,
558 OnFindMatchRectsReply)
559 IPC_MESSAGE_HANDLER(ViewHostMsg_OpenDateTimeDialog,
560 OnOpenDateTimeDialog)
561 #endif
562 IPC_MESSAGE_UNHANDLED(handled = false)
563 IPC_END_MESSAGE_MAP()
564 render_view_message_source_ = NULL;
565 render_frame_message_source_ = NULL;
567 return handled;
570 bool WebContentsImpl::HasValidFrameSource() {
571 if (!render_frame_message_source_) {
572 DCHECK(render_view_message_source_);
573 bad_message::ReceivedBadMessage(GetRenderProcessHost(),
574 bad_message::WC_INVALID_FRAME_SOURCE);
575 return false;
578 return true;
581 void WebContentsImpl::RunFileChooser(
582 RenderViewHost* render_view_host,
583 const FileChooserParams& params) {
584 if (delegate_)
585 delegate_->RunFileChooser(this, params);
588 NavigationControllerImpl& WebContentsImpl::GetController() {
589 return controller_;
592 const NavigationControllerImpl& WebContentsImpl::GetController() const {
593 return controller_;
596 BrowserContext* WebContentsImpl::GetBrowserContext() const {
597 return controller_.GetBrowserContext();
600 const GURL& WebContentsImpl::GetURL() const {
601 // We may not have a navigation entry yet.
602 NavigationEntry* entry = controller_.GetVisibleEntry();
603 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
606 const GURL& WebContentsImpl::GetVisibleURL() const {
607 // We may not have a navigation entry yet.
608 NavigationEntry* entry = controller_.GetVisibleEntry();
609 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
612 const GURL& WebContentsImpl::GetLastCommittedURL() const {
613 // We may not have a navigation entry yet.
614 NavigationEntry* entry = controller_.GetLastCommittedEntry();
615 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
618 WebContentsDelegate* WebContentsImpl::GetDelegate() {
619 return delegate_;
622 void WebContentsImpl::SetDelegate(WebContentsDelegate* delegate) {
623 // TODO(cbentzel): remove this debugging code?
624 if (delegate == delegate_)
625 return;
626 if (delegate_)
627 delegate_->Detach(this);
628 delegate_ = delegate;
629 if (delegate_) {
630 delegate_->Attach(this);
631 // Ensure the visible RVH reflects the new delegate's preferences.
632 if (view_)
633 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
637 RenderProcessHost* WebContentsImpl::GetRenderProcessHost() const {
638 RenderViewHostImpl* host = GetRenderManager()->current_host();
639 return host ? host->GetProcess() : NULL;
642 RenderFrameHostImpl* WebContentsImpl::GetMainFrame() {
643 return frame_tree_.root()->current_frame_host();
646 RenderFrameHostImpl* WebContentsImpl::GetFocusedFrame() {
647 FrameTreeNode* focused_node = frame_tree_.GetFocusedFrame();
648 if (!focused_node)
649 return nullptr;
650 return focused_node->current_frame_host();
653 void WebContentsImpl::ForEachFrame(
654 const base::Callback<void(RenderFrameHost*)>& on_frame) {
655 frame_tree_.ForEach(base::Bind(&ForEachFrameInternal, on_frame));
658 void WebContentsImpl::SendToAllFrames(IPC::Message* message) {
659 ForEachFrame(base::Bind(&SendToAllFramesInternal, message));
660 delete message;
663 RenderViewHostImpl* WebContentsImpl::GetRenderViewHost() const {
664 return GetRenderManager()->current_host();
667 int WebContentsImpl::GetRoutingID() const {
668 if (!GetRenderViewHost())
669 return MSG_ROUTING_NONE;
671 return GetRenderViewHost()->GetRoutingID();
674 int WebContentsImpl::GetFullscreenWidgetRoutingID() const {
675 return fullscreen_widget_routing_id_;
678 void WebContentsImpl::ClosePage() {
679 GetRenderViewHost()->ClosePage();
682 RenderWidgetHostView* WebContentsImpl::GetRenderWidgetHostView() const {
683 return GetRenderManager()->GetRenderWidgetHostView();
686 RenderWidgetHostView* WebContentsImpl::GetFullscreenRenderWidgetHostView()
687 const {
688 RenderWidgetHost* const widget_host =
689 RenderWidgetHostImpl::FromID(GetRenderProcessHost()->GetID(),
690 GetFullscreenWidgetRoutingID());
691 return widget_host ? widget_host->GetView() : NULL;
694 WebContentsView* WebContentsImpl::GetView() const {
695 return view_.get();
698 SkColor WebContentsImpl::GetThemeColor() const {
699 return theme_color_;
702 void WebContentsImpl::SetAccessibilityMode(AccessibilityMode mode) {
703 if (mode == accessibility_mode_)
704 return;
706 accessibility_mode_ = mode;
707 frame_tree_.ForEach(
708 base::Bind(&ForEachFrameInternal,
709 base::Bind(&SetAccessibilityModeOnFrame, mode)));
710 frame_tree_.ForEach(
711 base::Bind(&ForEachPendingFrameInternal,
712 base::Bind(&SetAccessibilityModeOnFrame, mode)));
715 void WebContentsImpl::AddAccessibilityMode(AccessibilityMode mode) {
716 SetAccessibilityMode(AddAccessibilityModeTo(accessibility_mode_, mode));
719 void WebContentsImpl::RemoveAccessibilityMode(AccessibilityMode mode) {
720 SetAccessibilityMode(RemoveAccessibilityModeFrom(accessibility_mode_, mode));
723 void WebContentsImpl::RequestAXTreeSnapshot(AXTreeSnapshotCallback callback) {
724 // TODO(dmazzoni): http://crbug.com/475608 This only returns the
725 // accessibility tree from the main frame and everything in the
726 // same site instance.
727 GetMainFrame()->RequestAXTreeSnapshot(callback);
730 void WebContentsImpl::ClearNavigationTransitionData() {
731 FrameTreeNode* node = frame_tree_.root();
732 node->render_manager()->ClearNavigationTransitionData();
735 WebUI* WebContentsImpl::CreateWebUI(const GURL& url) {
736 WebUIImpl* web_ui = new WebUIImpl(this);
737 WebUIController* controller = WebUIControllerFactoryRegistry::GetInstance()->
738 CreateWebUIControllerForURL(web_ui, url);
739 if (controller) {
740 web_ui->AddMessageHandler(new GenericHandler());
741 web_ui->SetController(controller);
742 return web_ui;
745 delete web_ui;
746 return NULL;
749 WebUI* WebContentsImpl::GetWebUI() const {
750 return GetRenderManager()->web_ui() ? GetRenderManager()->web_ui()
751 : GetRenderManager()->pending_web_ui();
754 WebUI* WebContentsImpl::GetCommittedWebUI() const {
755 return GetRenderManager()->web_ui();
758 void WebContentsImpl::SetUserAgentOverride(const std::string& override) {
759 if (GetUserAgentOverride() == override)
760 return;
762 renderer_preferences_.user_agent_override = override;
764 // Send the new override string to the renderer.
765 RenderViewHost* host = GetRenderViewHost();
766 if (host)
767 host->SyncRendererPrefs();
769 // Reload the page if a load is currently in progress to avoid having
770 // different parts of the page loaded using different user agents.
771 NavigationEntry* entry = controller_.GetVisibleEntry();
772 if (is_loading_ && entry != NULL && entry->GetIsOverridingUserAgent())
773 controller_.ReloadIgnoringCache(true);
775 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
776 UserAgentOverrideSet(override));
779 const std::string& WebContentsImpl::GetUserAgentOverride() const {
780 return renderer_preferences_.user_agent_override;
783 void WebContentsImpl::EnableTreeOnlyAccessibilityMode() {
784 AddAccessibilityMode(AccessibilityModeTreeOnly);
787 bool WebContentsImpl::IsTreeOnlyAccessibilityModeForTesting() const {
788 return accessibility_mode_ == AccessibilityModeTreeOnly;
791 bool WebContentsImpl::IsFullAccessibilityModeForTesting() const {
792 return accessibility_mode_ == AccessibilityModeComplete;
795 #if defined(OS_WIN)
796 void WebContentsImpl::SetParentNativeViewAccessible(
797 gfx::NativeViewAccessible accessible_parent) {
798 accessible_parent_ = accessible_parent;
799 RenderFrameHostImpl* rfh = GetMainFrame();
800 if (rfh)
801 rfh->SetParentNativeViewAccessible(accessible_parent);
803 #endif
805 const base::string16& WebContentsImpl::GetTitle() const {
806 // Transient entries take precedence. They are used for interstitial pages
807 // that are shown on top of existing pages.
808 NavigationEntry* entry = controller_.GetTransientEntry();
809 std::string accept_languages =
810 GetContentClient()->browser()->GetAcceptLangs(
811 GetBrowserContext());
812 if (entry) {
813 return entry->GetTitleForDisplay(accept_languages);
815 WebUI* our_web_ui = GetRenderManager()->pending_web_ui() ?
816 GetRenderManager()->pending_web_ui() : GetRenderManager()->web_ui();
817 if (our_web_ui) {
818 // Don't override the title in view source mode.
819 entry = controller_.GetVisibleEntry();
820 if (!(entry && entry->IsViewSourceMode())) {
821 // Give the Web UI the chance to override our title.
822 const base::string16& title = our_web_ui->GetOverriddenTitle();
823 if (!title.empty())
824 return title;
828 // We use the title for the last committed entry rather than a pending
829 // navigation entry. For example, when the user types in a URL, we want to
830 // keep the old page's title until the new load has committed and we get a new
831 // title.
832 entry = controller_.GetLastCommittedEntry();
834 // We make an exception for initial navigations.
835 if (controller_.IsInitialNavigation()) {
836 // We only want to use the title from the visible entry in one of two cases:
837 // 1. There's already a committed entry for an initial navigation, in which
838 // case we are doing a history navigation in a new tab (e.g., Ctrl+Back).
839 // 2. The pending entry has been explicitly assigned a title to display.
841 // If there's no last committed entry and no assigned title, we should fall
842 // back to |page_title_when_no_navigation_entry_| rather than showing the
843 // URL.
844 if (entry ||
845 (controller_.GetVisibleEntry() &&
846 !controller_.GetVisibleEntry()->GetTitle().empty())) {
847 entry = controller_.GetVisibleEntry();
851 if (entry) {
852 return entry->GetTitleForDisplay(accept_languages);
855 // |page_title_when_no_navigation_entry_| is finally used
856 // if no title cannot be retrieved.
857 return page_title_when_no_navigation_entry_;
860 int32 WebContentsImpl::GetMaxPageID() {
861 return GetMaxPageIDForSiteInstance(GetSiteInstance());
864 int32 WebContentsImpl::GetMaxPageIDForSiteInstance(
865 SiteInstance* site_instance) {
866 if (max_page_ids_.find(site_instance->GetId()) == max_page_ids_.end())
867 max_page_ids_[site_instance->GetId()] = -1;
869 return max_page_ids_[site_instance->GetId()];
872 void WebContentsImpl::UpdateMaxPageID(int32 page_id) {
873 UpdateMaxPageIDForSiteInstance(GetSiteInstance(), page_id);
876 void WebContentsImpl::UpdateMaxPageIDForSiteInstance(
877 SiteInstance* site_instance, int32 page_id) {
878 if (GetMaxPageIDForSiteInstance(site_instance) < page_id)
879 max_page_ids_[site_instance->GetId()] = page_id;
882 void WebContentsImpl::CopyMaxPageIDsFrom(WebContents* web_contents) {
883 WebContentsImpl* contents = static_cast<WebContentsImpl*>(web_contents);
884 max_page_ids_ = contents->max_page_ids_;
887 SiteInstanceImpl* WebContentsImpl::GetSiteInstance() const {
888 return GetRenderManager()->current_host()->GetSiteInstance();
891 SiteInstanceImpl* WebContentsImpl::GetPendingSiteInstance() const {
892 RenderViewHostImpl* dest_rvh =
893 GetRenderManager()->pending_render_view_host() ?
894 GetRenderManager()->pending_render_view_host() :
895 GetRenderManager()->current_host();
896 return dest_rvh->GetSiteInstance();
899 bool WebContentsImpl::IsLoading() const {
900 return is_loading_;
903 bool WebContentsImpl::IsLoadingToDifferentDocument() const {
904 return is_loading_ && is_load_to_different_document_;
907 bool WebContentsImpl::IsWaitingForResponse() const {
908 return waiting_for_response_ && is_load_to_different_document_;
911 const net::LoadStateWithParam& WebContentsImpl::GetLoadState() const {
912 return load_state_;
915 const base::string16& WebContentsImpl::GetLoadStateHost() const {
916 return load_state_host_;
919 uint64 WebContentsImpl::GetUploadSize() const {
920 return upload_size_;
923 uint64 WebContentsImpl::GetUploadPosition() const {
924 return upload_position_;
927 std::set<GURL> WebContentsImpl::GetSitesInTab() const {
928 std::set<GURL> sites;
929 frame_tree_.ForEach(base::Bind(&CollectSites,
930 base::Unretained(GetBrowserContext()),
931 base::Unretained(&sites)));
932 return sites;
935 const std::string& WebContentsImpl::GetEncoding() const {
936 return canonical_encoding_;
939 bool WebContentsImpl::DisplayedInsecureContent() const {
940 return displayed_insecure_content_;
943 void WebContentsImpl::IncrementCapturerCount(const gfx::Size& capture_size) {
944 DCHECK(!is_being_destroyed_);
945 ++capturer_count_;
946 DVLOG(1) << "There are now " << capturer_count_
947 << " capturing(s) of WebContentsImpl@" << this;
949 // Note: This provides a hint to upstream code to size the views optimally
950 // for quality (e.g., to avoid scaling).
951 if (!capture_size.IsEmpty() && preferred_size_for_capture_.IsEmpty()) {
952 preferred_size_for_capture_ = capture_size;
953 OnPreferredSizeChanged(preferred_size_);
956 // Ensure that all views are un-occluded before capture begins.
957 WasUnOccluded();
960 void WebContentsImpl::DecrementCapturerCount() {
961 --capturer_count_;
962 DVLOG(1) << "There are now " << capturer_count_
963 << " capturing(s) of WebContentsImpl@" << this;
964 DCHECK_LE(0, capturer_count_);
966 if (is_being_destroyed_)
967 return;
969 if (capturer_count_ == 0) {
970 const gfx::Size old_size = preferred_size_for_capture_;
971 preferred_size_for_capture_ = gfx::Size();
972 OnPreferredSizeChanged(old_size);
975 if (IsHidden()) {
976 DVLOG(1) << "Executing delayed WasHidden().";
977 WasHidden();
981 int WebContentsImpl::GetCapturerCount() const {
982 return capturer_count_;
985 bool WebContentsImpl::IsAudioMuted() const {
986 return audio_muter_.get() && audio_muter_->is_muting();
989 void WebContentsImpl::SetAudioMuted(bool mute) {
990 DVLOG(1) << "SetAudioMuted(mute=" << mute << "), was " << IsAudioMuted()
991 << " for WebContentsImpl@" << this;
993 if (mute == IsAudioMuted())
994 return;
996 if (mute) {
997 if (!audio_muter_)
998 audio_muter_.reset(new WebContentsAudioMuter(this));
999 audio_muter_->StartMuting();
1000 } else {
1001 DCHECK(audio_muter_);
1002 audio_muter_->StopMuting();
1005 // Notification for UI updates in response to the changed muting state.
1006 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
1009 bool WebContentsImpl::IsCrashed() const {
1010 return (crashed_status_ == base::TERMINATION_STATUS_PROCESS_CRASHED ||
1011 crashed_status_ == base::TERMINATION_STATUS_ABNORMAL_TERMINATION ||
1012 crashed_status_ == base::TERMINATION_STATUS_PROCESS_WAS_KILLED);
1015 void WebContentsImpl::SetIsCrashed(base::TerminationStatus status,
1016 int error_code) {
1017 if (status == crashed_status_)
1018 return;
1020 crashed_status_ = status;
1021 crashed_error_code_ = error_code;
1022 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
1025 base::TerminationStatus WebContentsImpl::GetCrashedStatus() const {
1026 return crashed_status_;
1029 bool WebContentsImpl::IsBeingDestroyed() const {
1030 return is_being_destroyed_;
1033 void WebContentsImpl::NotifyNavigationStateChanged(
1034 InvalidateTypes changed_flags) {
1035 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1036 // is fixed.
1037 tracked_objects::ScopedTracker tracking_profile(
1038 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1039 "466285 WebContentsImpl::NotifyNavigationStateChanged"));
1040 // Create and release the audio power save blocker depending on whether the
1041 // tab is actively producing audio or not.
1042 if ((changed_flags & INVALIDATE_TYPE_TAB) &&
1043 audio_state_provider_->IsAudioStateAvailable()) {
1044 if (WasRecentlyAudible()) {
1045 if (!audio_power_save_blocker_)
1046 CreateAudioPowerSaveBlocker();
1047 } else {
1048 audio_power_save_blocker_.reset();
1052 if (delegate_)
1053 delegate_->NavigationStateChanged(this, changed_flags);
1056 base::TimeTicks WebContentsImpl::GetLastActiveTime() const {
1057 return last_active_time_;
1060 void WebContentsImpl::WasShown() {
1061 controller_.SetActive(true);
1063 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1064 if (view) {
1065 view->Show();
1066 #if defined(OS_MACOSX)
1067 view->SetActive(true);
1068 #endif
1072 last_active_time_ = base::TimeTicks::Now();
1074 // The resize rect might have changed while this was inactive -- send the new
1075 // one to make sure it's up to date.
1076 RenderViewHostImpl* rvh = GetRenderViewHost();
1077 if (rvh)
1078 rvh->ResizeRectChanged(GetRootWindowResizerRect());
1080 // Restore power save blocker if there are active video players running.
1081 if (!active_video_players_.empty() && !video_power_save_blocker_)
1082 CreateVideoPowerSaveBlocker();
1084 FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasShown());
1086 should_normally_be_visible_ = true;
1089 void WebContentsImpl::WasHidden() {
1090 // If there are entities capturing screenshots or video (e.g., mirroring),
1091 // don't activate the "disable rendering" optimization.
1092 if (capturer_count_ == 0) {
1093 // |GetRenderViewHost()| can be NULL if the user middle clicks a link to
1094 // open a tab in the background, then closes the tab before selecting it.
1095 // This is because closing the tab calls WebContentsImpl::Destroy(), which
1096 // removes the |GetRenderViewHost()|; then when we actually destroy the
1097 // window, OnWindowPosChanged() notices and calls WasHidden() (which
1098 // calls us).
1099 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1100 if (view)
1101 view->Hide();
1104 // Release any video power save blockers held as video is not visible.
1105 video_power_save_blocker_.reset();
1108 FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasHidden());
1110 should_normally_be_visible_ = false;
1113 void WebContentsImpl::WasOccluded() {
1114 if (capturer_count_ > 0)
1115 return;
1117 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1118 if (view)
1119 view->WasOccluded();
1123 void WebContentsImpl::WasUnOccluded() {
1124 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1125 if (view)
1126 view->WasUnOccluded();
1130 bool WebContentsImpl::NeedToFireBeforeUnload() {
1131 // TODO(creis): Should we fire even for interstitial pages?
1132 return WillNotifyDisconnection() && !ShowingInterstitialPage() &&
1133 !GetRenderViewHost()->SuddenTerminationAllowed();
1136 void WebContentsImpl::DispatchBeforeUnload(bool for_cross_site_transition) {
1137 GetMainFrame()->DispatchBeforeUnload(for_cross_site_transition);
1140 void WebContentsImpl::Stop() {
1141 GetRenderManager()->Stop();
1142 FOR_EACH_OBSERVER(WebContentsObserver, observers_, NavigationStopped());
1145 WebContents* WebContentsImpl::Clone() {
1146 // We use our current SiteInstance since the cloned entry will use it anyway.
1147 // We pass our own opener so that the cloned page can access it if it was
1148 // before.
1149 CreateParams create_params(GetBrowserContext(), GetSiteInstance());
1150 create_params.initial_size = GetContainerBounds().size();
1151 WebContentsImpl* tc = CreateWithOpener(create_params, opener_);
1152 tc->GetController().CopyStateFrom(controller_);
1153 FOR_EACH_OBSERVER(WebContentsObserver,
1154 observers_,
1155 DidCloneToNewWebContents(this, tc));
1156 return tc;
1159 void WebContentsImpl::Observe(int type,
1160 const NotificationSource& source,
1161 const NotificationDetails& details) {
1162 switch (type) {
1163 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: {
1164 RenderWidgetHost* host = Source<RenderWidgetHost>(source).ptr();
1165 RenderWidgetHostView* view = host->GetView();
1166 if (view == GetFullscreenRenderWidgetHostView()) {
1167 // We cannot just call view_->RestoreFocus() here. On some platforms,
1168 // attempting to focus the currently-invisible WebContentsView will be
1169 // flat-out ignored. Therefore, this boolean is used to track whether
1170 // we will request focus after the fullscreen widget has been
1171 // destroyed.
1172 fullscreen_widget_had_focus_at_shutdown_ = (view && view->HasFocus());
1173 } else {
1174 for (PendingWidgetViews::iterator i = pending_widget_views_.begin();
1175 i != pending_widget_views_.end(); ++i) {
1176 if (host->GetView() == i->second) {
1177 pending_widget_views_.erase(i);
1178 break;
1182 break;
1184 default:
1185 NOTREACHED();
1189 WebContents* WebContentsImpl::GetWebContents() {
1190 return this;
1193 void WebContentsImpl::Init(const WebContents::CreateParams& params) {
1194 // This is set before initializing the render manager since
1195 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
1196 // it should be hidden.
1197 should_normally_be_visible_ = !params.initially_hidden;
1199 // Either both routing ids can be given, or neither can be.
1200 DCHECK((params.routing_id == MSG_ROUTING_NONE &&
1201 params.main_frame_routing_id == MSG_ROUTING_NONE) ||
1202 (params.routing_id != MSG_ROUTING_NONE &&
1203 params.main_frame_routing_id != MSG_ROUTING_NONE));
1204 GetRenderManager()->Init(
1205 params.browser_context, params.site_instance, params.routing_id,
1206 params.main_frame_routing_id);
1207 frame_tree_.root()->SetFrameName(params.main_frame_name);
1209 WebContentsViewDelegate* delegate =
1210 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
1212 if (browser_plugin_guest_) {
1213 scoped_ptr<WebContentsView> platform_view(CreateWebContentsView(
1214 this, delegate, &render_view_host_delegate_view_));
1216 WebContentsViewGuest* rv = new WebContentsViewGuest(
1217 this, browser_plugin_guest_.get(), platform_view.Pass(),
1218 render_view_host_delegate_view_);
1219 render_view_host_delegate_view_ = rv;
1220 view_.reset(rv);
1221 } else {
1222 // Regular WebContentsView.
1223 view_.reset(CreateWebContentsView(
1224 this, delegate, &render_view_host_delegate_view_));
1226 CHECK(render_view_host_delegate_view_);
1227 CHECK(view_.get());
1229 gfx::Size initial_size = params.initial_size;
1230 view_->CreateView(initial_size, params.context);
1232 // Listen for whether our opener gets destroyed.
1233 if (opener_)
1234 AddDestructionObserver(opener_);
1236 #if defined(ENABLE_PLUGINS)
1237 plugin_content_origin_whitelist_.reset(
1238 new PluginContentOriginWhitelist(this));
1239 #endif
1241 registrar_.Add(this,
1242 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1243 NotificationService::AllBrowserContextsAndSources());
1245 screen_orientation_dispatcher_host_.reset(
1246 new ScreenOrientationDispatcherHostImpl(this));
1248 manifest_manager_host_.reset(new ManifestManagerHost(this));
1250 #if defined(OS_ANDROID)
1251 date_time_chooser_.reset(new DateTimeChooserAndroid());
1252 #endif
1254 // BrowserPluginGuest::Init needs to be called after this WebContents has
1255 // a RenderWidgetHostViewGuest. That is, |view_->CreateView| above.
1256 if (browser_plugin_guest_)
1257 browser_plugin_guest_->Init();
1259 for (size_t i = 0; i < g_created_callbacks.Get().size(); i++)
1260 g_created_callbacks.Get().at(i).Run(this);
1262 // If the WebContents creation was renderer-initiated, it means that the
1263 // corresponding RenderView and main RenderFrame have already been created.
1264 // Ensure observers are notified about this.
1265 if (params.renderer_initiated_creation) {
1266 RenderViewCreated(GetRenderViewHost());
1267 GetRenderManager()->current_frame_host()->SetRenderFrameCreated(true);
1270 // Ensure that observers are notified of the creation of this WebContents's
1271 // main RenderFrameHost. It must be done here for main frames, since the
1272 // NotifySwappedFromRenderManager expects view_ to already be created and that
1273 // happens after RenderFrameHostManager::Init.
1274 NotifySwappedFromRenderManager(
1275 nullptr, GetRenderManager()->current_frame_host(), true);
1278 void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl* web_contents) {
1279 RemoveDestructionObserver(web_contents);
1281 // Clear the opener if it has been closed.
1282 if (web_contents == opener_) {
1283 opener_ = NULL;
1284 return;
1286 // Clear a pending contents that has been closed before being shown.
1287 for (PendingContents::iterator iter = pending_contents_.begin();
1288 iter != pending_contents_.end();
1289 ++iter) {
1290 if (iter->second != web_contents)
1291 continue;
1292 pending_contents_.erase(iter);
1293 return;
1295 NOTREACHED();
1298 void WebContentsImpl::AddDestructionObserver(WebContentsImpl* web_contents) {
1299 if (!ContainsKey(destruction_observers_, web_contents)) {
1300 destruction_observers_[web_contents] =
1301 new DestructionObserver(this, web_contents);
1305 void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl* web_contents) {
1306 DestructionObservers::iterator iter =
1307 destruction_observers_.find(web_contents);
1308 if (iter != destruction_observers_.end()) {
1309 delete destruction_observers_[web_contents];
1310 destruction_observers_.erase(iter);
1314 void WebContentsImpl::AddObserver(WebContentsObserver* observer) {
1315 observers_.AddObserver(observer);
1318 void WebContentsImpl::RemoveObserver(WebContentsObserver* observer) {
1319 observers_.RemoveObserver(observer);
1322 std::set<RenderWidgetHostView*>
1323 WebContentsImpl::GetRenderWidgetHostViewsInTree() {
1324 std::set<RenderWidgetHostView*> set;
1325 if (ShowingInterstitialPage()) {
1326 set.insert(GetRenderWidgetHostView());
1327 } else {
1328 ForEachFrame(
1329 base::Bind(&AddRenderWidgetHostViewToSet, base::Unretained(&set)));
1331 return set;
1334 void WebContentsImpl::Activate() {
1335 if (delegate_)
1336 delegate_->ActivateContents(this);
1339 void WebContentsImpl::Deactivate() {
1340 if (delegate_)
1341 delegate_->DeactivateContents(this);
1344 void WebContentsImpl::LostCapture() {
1345 if (delegate_)
1346 delegate_->LostCapture();
1349 void WebContentsImpl::RenderWidgetDeleted(
1350 RenderWidgetHostImpl* render_widget_host) {
1351 if (is_being_destroyed_) {
1352 // |created_widgets_| might have been destroyed.
1353 return;
1356 std::set<RenderWidgetHostImpl*>::iterator iter =
1357 created_widgets_.find(render_widget_host);
1358 if (iter != created_widgets_.end())
1359 created_widgets_.erase(iter);
1361 if (render_widget_host &&
1362 render_widget_host->GetRoutingID() == fullscreen_widget_routing_id_) {
1363 if (delegate_ && delegate_->EmbedsFullscreenWidget())
1364 delegate_->ExitFullscreenModeForTab(this);
1365 FOR_EACH_OBSERVER(WebContentsObserver,
1366 observers_,
1367 DidDestroyFullscreenWidget(
1368 fullscreen_widget_routing_id_));
1369 fullscreen_widget_routing_id_ = MSG_ROUTING_NONE;
1370 if (fullscreen_widget_had_focus_at_shutdown_)
1371 view_->RestoreFocus();
1375 void WebContentsImpl::RenderWidgetGotFocus(
1376 RenderWidgetHostImpl* render_widget_host) {
1377 // Notify the observers if an embedded fullscreen widget was focused.
1378 if (delegate_ && render_widget_host && delegate_->EmbedsFullscreenWidget() &&
1379 render_widget_host->GetView() == GetFullscreenRenderWidgetHostView()) {
1380 NotifyWebContentsFocused();
1384 void WebContentsImpl::RenderWidgetWasResized(
1385 RenderWidgetHostImpl* render_widget_host,
1386 bool width_changed) {
1387 RenderFrameHostImpl* rfh = GetMainFrame();
1388 if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
1389 return;
1391 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1392 MainFrameWasResized(width_changed));
1395 void WebContentsImpl::ScreenInfoChanged() {
1396 if (browser_plugin_embedder_)
1397 browser_plugin_embedder_->ScreenInfoChanged();
1400 bool WebContentsImpl::PreHandleKeyboardEvent(
1401 const NativeWebKeyboardEvent& event,
1402 bool* is_keyboard_shortcut) {
1403 return delegate_ &&
1404 delegate_->PreHandleKeyboardEvent(this, event, is_keyboard_shortcut);
1407 void WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
1408 if (browser_plugin_embedder_ &&
1409 browser_plugin_embedder_->HandleKeyboardEvent(event)) {
1410 return;
1412 if (delegate_)
1413 delegate_->HandleKeyboardEvent(this, event);
1416 bool WebContentsImpl::HandleWheelEvent(
1417 const blink::WebMouseWheelEvent& event) {
1418 #if !defined(OS_MACOSX)
1419 // On platforms other than Mac, control+mousewheel may change zoom. On Mac,
1420 // this isn't done for two reasons:
1421 // -the OS already has a gesture to do this through pinch-zoom
1422 // -if a user starts an inertial scroll, let's go, and presses control
1423 // (i.e. control+tab) then the OS's buffered scroll events will come in
1424 // with control key set which isn't what the user wants
1425 if (delegate_ && event.wheelTicksY &&
1426 (event.modifiers & blink::WebInputEvent::ControlKey) &&
1427 !event.canScroll) {
1428 delegate_->ContentsZoomChange(event.wheelTicksY > 0);
1429 return true;
1431 #endif
1432 return false;
1435 bool WebContentsImpl::PreHandleGestureEvent(
1436 const blink::WebGestureEvent& event) {
1437 return delegate_ && delegate_->PreHandleGestureEvent(this, event);
1440 void WebContentsImpl::EnterFullscreenMode(const GURL& origin) {
1441 // This method is being called to enter renderer-initiated fullscreen mode.
1442 // Make sure any existing fullscreen widget is shut down first.
1443 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
1444 if (widget_view)
1445 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())->Shutdown();
1447 if (delegate_)
1448 delegate_->EnterFullscreenModeForTab(this, origin);
1450 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1451 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1454 void WebContentsImpl::ExitFullscreenMode() {
1455 // This method is being called to leave renderer-initiated fullscreen mode.
1456 // Make sure any existing fullscreen widget is shut down first.
1457 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
1458 if (widget_view)
1459 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())->Shutdown();
1461 #if defined(OS_ANDROID)
1462 ContentVideoView* video_view = ContentVideoView::GetInstance();
1463 if (video_view != NULL)
1464 video_view->OnExitFullscreen();
1465 #endif
1467 if (delegate_)
1468 delegate_->ExitFullscreenModeForTab(this);
1470 // Ensure web contents exit fullscreen state by sending a resize message,
1471 // which includes the fullscreen state. This is required for the situation
1472 // of the browser moving the view into a fullscreen state "browser fullscreen"
1473 // and then the contents entering "tab fullscreen". Exiting the contents
1474 // "tab fullscreen" then won't have the side effect of the view resizing,
1475 // hence the explicit call here is required.
1476 if (RenderWidgetHostView* rwh_view = GetRenderWidgetHostView()) {
1477 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
1478 render_widget_host->WasResized();
1481 FOR_EACH_OBSERVER(WebContentsObserver,
1482 observers_,
1483 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1486 bool WebContentsImpl::IsFullscreenForCurrentTab() const {
1487 return delegate_ ? delegate_->IsFullscreenForTabOrPending(this) : false;
1490 blink::WebDisplayMode WebContentsImpl::GetDisplayMode() const {
1491 return delegate_ ? delegate_->GetDisplayMode(this)
1492 : blink::WebDisplayModeBrowser;
1495 void WebContentsImpl::RequestToLockMouse(bool user_gesture,
1496 bool last_unlocked_by_target) {
1497 if (delegate_) {
1498 delegate_->RequestToLockMouse(this, user_gesture, last_unlocked_by_target);
1499 } else {
1500 GotResponseToLockMouseRequest(false);
1504 void WebContentsImpl::LostMouseLock() {
1505 if (delegate_)
1506 delegate_->LostMouseLock();
1509 void WebContentsImpl::CreateNewWindow(
1510 int render_process_id,
1511 int route_id,
1512 int main_frame_route_id,
1513 const ViewHostMsg_CreateWindow_Params& params,
1514 SessionStorageNamespace* session_storage_namespace) {
1515 // We usually create the new window in the same BrowsingInstance (group of
1516 // script-related windows), by passing in the current SiteInstance. However,
1517 // if the opener is being suppressed (in a non-guest), we create a new
1518 // SiteInstance in its own BrowsingInstance.
1519 bool is_guest = BrowserPluginGuest::IsGuest(this);
1521 // If the opener is to be suppressed, the new window can be in any process.
1522 // Since routing ids are process specific, we must not have one passed in
1523 // as argument here.
1524 DCHECK(!params.opener_suppressed || route_id == MSG_ROUTING_NONE);
1526 scoped_refptr<SiteInstance> site_instance =
1527 params.opener_suppressed && !is_guest ?
1528 SiteInstance::CreateForURL(GetBrowserContext(), params.target_url) :
1529 GetSiteInstance();
1531 // A message to create a new window can only come from the active process for
1532 // this WebContentsImpl instance. If any other process sends the request,
1533 // it is invalid and the process must be terminated.
1534 if (GetRenderProcessHost()->GetID() != render_process_id) {
1535 RenderProcessHost* rph = RenderProcessHost::FromID(render_process_id);
1536 base::ProcessHandle process_handle = rph->GetHandle();
1537 if (process_handle != base::kNullProcessHandle) {
1538 RecordAction(
1539 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWindow"));
1540 rph->Shutdown(RESULT_CODE_KILLED, false);
1542 return;
1545 // We must assign the SessionStorageNamespace before calling Init().
1547 // http://crbug.com/142685
1548 const std::string& partition_id =
1549 GetContentClient()->browser()->
1550 GetStoragePartitionIdForSite(GetBrowserContext(),
1551 site_instance->GetSiteURL());
1552 StoragePartition* partition = BrowserContext::GetStoragePartition(
1553 GetBrowserContext(), site_instance.get());
1554 DOMStorageContextWrapper* dom_storage_context =
1555 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
1556 SessionStorageNamespaceImpl* session_storage_namespace_impl =
1557 static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
1558 CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
1560 if (delegate_ &&
1561 !delegate_->ShouldCreateWebContents(this,
1562 route_id,
1563 main_frame_route_id,
1564 params.window_container_type,
1565 params.frame_name,
1566 params.target_url,
1567 partition_id,
1568 session_storage_namespace)) {
1569 if (route_id != MSG_ROUTING_NONE &&
1570 !RenderViewHost::FromID(render_process_id, route_id)) {
1571 // If the embedder didn't create a WebContents for this route, we need to
1572 // delete the RenderView that had already been created.
1573 Send(new ViewMsg_Close(route_id));
1575 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(route_id);
1576 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(
1577 main_frame_route_id);
1578 return;
1581 // Create the new web contents. This will automatically create the new
1582 // WebContentsView. In the future, we may want to create the view separately.
1583 CreateParams create_params(GetBrowserContext(), site_instance.get());
1584 create_params.routing_id = route_id;
1585 create_params.main_frame_routing_id = main_frame_route_id;
1586 create_params.main_frame_name = base::UTF16ToUTF8(params.frame_name);
1587 create_params.opener = this;
1588 create_params.opener_suppressed = params.opener_suppressed;
1589 if (params.disposition == NEW_BACKGROUND_TAB)
1590 create_params.initially_hidden = true;
1591 create_params.renderer_initiated_creation = true;
1593 WebContentsImpl* new_contents = NULL;
1594 if (!is_guest) {
1595 create_params.context = view_->GetNativeView();
1596 create_params.initial_size = GetContainerBounds().size();
1597 new_contents = static_cast<WebContentsImpl*>(
1598 WebContents::Create(create_params));
1599 } else {
1600 new_contents = GetBrowserPluginGuest()->CreateNewGuestWindow(create_params);
1602 new_contents->GetController().SetSessionStorageNamespace(
1603 partition_id,
1604 session_storage_namespace);
1606 // Save the window for later if we're not suppressing the opener (since it
1607 // will be shown immediately).
1608 if (!params.opener_suppressed) {
1609 if (!is_guest) {
1610 WebContentsView* new_view = new_contents->view_.get();
1612 // TODO(brettw): It seems bogus that we have to call this function on the
1613 // newly created object and give it one of its own member variables.
1614 new_view->CreateViewForWidget(new_contents->GetRenderViewHost(), false);
1616 // Save the created window associated with the route so we can show it
1617 // later.
1618 DCHECK_NE(MSG_ROUTING_NONE, route_id);
1619 pending_contents_[route_id] = new_contents;
1620 AddDestructionObserver(new_contents);
1623 if (delegate_) {
1624 delegate_->WebContentsCreated(
1625 this, params.opener_render_frame_id, params.frame_name,
1626 params.target_url, new_contents);
1629 if (params.opener_suppressed) {
1630 // When the opener is suppressed, the original renderer cannot access the
1631 // new window. As a result, we need to show and navigate the window here.
1632 bool was_blocked = false;
1633 if (delegate_) {
1634 gfx::Rect initial_rect;
1635 delegate_->AddNewContents(
1636 this, new_contents, params.disposition, initial_rect,
1637 params.user_gesture, &was_blocked);
1639 if (!was_blocked) {
1640 OpenURLParams open_params(params.target_url,
1641 Referrer(),
1642 CURRENT_TAB,
1643 ui::PAGE_TRANSITION_LINK,
1644 true /* is_renderer_initiated */);
1645 open_params.user_gesture = params.user_gesture;
1646 new_contents->OpenURL(open_params);
1651 void WebContentsImpl::CreateNewWidget(int render_process_id,
1652 int route_id,
1653 blink::WebPopupType popup_type) {
1654 CreateNewWidget(render_process_id, route_id, false, popup_type);
1657 void WebContentsImpl::CreateNewFullscreenWidget(int render_process_id,
1658 int route_id) {
1659 CreateNewWidget(render_process_id, route_id, true, blink::WebPopupTypeNone);
1662 void WebContentsImpl::CreateNewWidget(int render_process_id,
1663 int route_id,
1664 bool is_fullscreen,
1665 blink::WebPopupType popup_type) {
1666 RenderProcessHost* process = GetRenderProcessHost();
1667 // A message to create a new widget can only come from the active process for
1668 // this WebContentsImpl instance. If any other process sends the request,
1669 // it is invalid and the process must be terminated.
1670 if (process->GetID() != render_process_id) {
1671 RenderProcessHost* rph = RenderProcessHost::FromID(render_process_id);
1672 base::ProcessHandle process_handle = rph->GetHandle();
1673 if (process_handle != base::kNullProcessHandle) {
1674 RecordAction(
1675 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWidget"));
1676 rph->Shutdown(RESULT_CODE_KILLED, false);
1678 return;
1681 RenderWidgetHostImpl* widget_host =
1682 new RenderWidgetHostImpl(this, process, route_id, IsHidden());
1683 created_widgets_.insert(widget_host);
1685 RenderWidgetHostViewBase* widget_view =
1686 static_cast<RenderWidgetHostViewBase*>(
1687 view_->CreateViewForPopupWidget(widget_host));
1688 if (!widget_view)
1689 return;
1690 if (!is_fullscreen) {
1691 // Popups should not get activated.
1692 widget_view->SetPopupType(popup_type);
1694 // Save the created widget associated with the route so we can show it later.
1695 pending_widget_views_[route_id] = widget_view;
1697 #if defined(OS_MACOSX)
1698 // A RenderWidgetHostViewMac has lifetime scoped to the view. We'll retain it
1699 // to allow it to survive the trip without being hosted.
1700 base::mac::NSObjectRetain(widget_view->GetNativeView());
1701 #endif
1704 void WebContentsImpl::ShowCreatedWindow(int route_id,
1705 WindowOpenDisposition disposition,
1706 const gfx::Rect& initial_rect,
1707 bool user_gesture) {
1708 WebContentsImpl* contents = GetCreatedWindow(route_id);
1709 if (contents) {
1710 WebContentsDelegate* delegate = GetDelegate();
1711 if (!delegate || delegate->ShouldResumeRequestsForCreatedWindow())
1712 contents->ResumeLoadingCreatedWebContents();
1714 if (delegate) {
1715 delegate->AddNewContents(
1716 this, contents, disposition, initial_rect, user_gesture, NULL);
1721 void WebContentsImpl::ShowCreatedWidget(int route_id,
1722 const gfx::Rect& initial_rect) {
1723 ShowCreatedWidget(route_id, false, initial_rect);
1726 void WebContentsImpl::ShowCreatedFullscreenWidget(int route_id) {
1727 ShowCreatedWidget(route_id, true, gfx::Rect());
1730 void WebContentsImpl::ShowCreatedWidget(int route_id,
1731 bool is_fullscreen,
1732 const gfx::Rect& initial_rect) {
1733 RenderWidgetHostViewBase* widget_host_view =
1734 static_cast<RenderWidgetHostViewBase*>(GetCreatedWidget(route_id));
1735 if (!widget_host_view)
1736 return;
1738 RenderWidgetHostView* view = NULL;
1739 BrowserPluginGuest* guest = GetBrowserPluginGuest();
1740 if (guest && guest->embedder_web_contents()) {
1741 view = guest->embedder_web_contents()->GetRenderWidgetHostView();
1742 } else {
1743 view = GetRenderWidgetHostView();
1746 if (is_fullscreen) {
1747 DCHECK_EQ(MSG_ROUTING_NONE, fullscreen_widget_routing_id_);
1748 view_->StoreFocus();
1749 fullscreen_widget_routing_id_ = route_id;
1750 if (delegate_ && delegate_->EmbedsFullscreenWidget()) {
1751 widget_host_view->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
1752 delegate_->EnterFullscreenModeForTab(this, GURL());
1753 } else {
1754 widget_host_view->InitAsFullscreen(view);
1756 FOR_EACH_OBSERVER(WebContentsObserver,
1757 observers_,
1758 DidShowFullscreenWidget(route_id));
1759 if (!widget_host_view->HasFocus())
1760 widget_host_view->Focus();
1761 } else {
1762 widget_host_view->InitAsPopup(view, initial_rect);
1765 RenderWidgetHostImpl* render_widget_host_impl =
1766 RenderWidgetHostImpl::From(widget_host_view->GetRenderWidgetHost());
1767 render_widget_host_impl->Init();
1768 // Only allow privileged mouse lock for fullscreen render widget, which is
1769 // used to implement Pepper Flash fullscreen.
1770 render_widget_host_impl->set_allow_privileged_mouse_lock(is_fullscreen);
1772 #if defined(OS_MACOSX)
1773 // A RenderWidgetHostViewMac has lifetime scoped to the view. Now that it's
1774 // properly embedded (or purposefully ignored) we can release the retain we
1775 // took in CreateNewWidget().
1776 base::mac::NSObjectRelease(widget_host_view->GetNativeView());
1777 #endif
1780 WebContentsImpl* WebContentsImpl::GetCreatedWindow(int route_id) {
1781 PendingContents::iterator iter = pending_contents_.find(route_id);
1783 // Certain systems can block the creation of new windows. If we didn't succeed
1784 // in creating one, just return NULL.
1785 if (iter == pending_contents_.end()) {
1786 return NULL;
1789 WebContentsImpl* new_contents = iter->second;
1790 pending_contents_.erase(route_id);
1791 RemoveDestructionObserver(new_contents);
1793 // Don't initialize the guest WebContents immediately.
1794 if (BrowserPluginGuest::IsGuest(new_contents))
1795 return new_contents;
1797 if (!new_contents->GetRenderProcessHost()->HasConnection() ||
1798 !new_contents->GetRenderViewHost()->GetView())
1799 return NULL;
1801 return new_contents;
1804 RenderWidgetHostView* WebContentsImpl::GetCreatedWidget(int route_id) {
1805 PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id);
1806 if (iter == pending_widget_views_.end()) {
1807 DCHECK(false);
1808 return NULL;
1811 RenderWidgetHostView* widget_host_view = iter->second;
1812 pending_widget_views_.erase(route_id);
1814 RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
1815 if (!widget_host->GetProcess()->HasConnection()) {
1816 // The view has gone away or the renderer crashed. Nothing to do.
1817 return NULL;
1820 return widget_host_view;
1823 void WebContentsImpl::RequestMediaAccessPermission(
1824 const MediaStreamRequest& request,
1825 const MediaResponseCallback& callback) {
1826 if (delegate_) {
1827 delegate_->RequestMediaAccessPermission(this, request, callback);
1828 } else {
1829 callback.Run(MediaStreamDevices(),
1830 MEDIA_DEVICE_FAILED_DUE_TO_SHUTDOWN,
1831 scoped_ptr<MediaStreamUI>());
1835 bool WebContentsImpl::CheckMediaAccessPermission(const GURL& security_origin,
1836 MediaStreamType type) {
1837 DCHECK(type == MEDIA_DEVICE_AUDIO_CAPTURE ||
1838 type == MEDIA_DEVICE_VIDEO_CAPTURE);
1839 return delegate_ &&
1840 delegate_->CheckMediaAccessPermission(this, security_origin, type);
1843 SessionStorageNamespace* WebContentsImpl::GetSessionStorageNamespace(
1844 SiteInstance* instance) {
1845 return controller_.GetSessionStorageNamespace(instance);
1848 SessionStorageNamespaceMap WebContentsImpl::GetSessionStorageNamespaceMap() {
1849 return controller_.GetSessionStorageNamespaceMap();
1852 FrameTree* WebContentsImpl::GetFrameTree() {
1853 return &frame_tree_;
1856 void WebContentsImpl::SetIsVirtualKeyboardRequested(bool requested) {
1857 virtual_keyboard_requested_ = requested;
1860 bool WebContentsImpl::IsVirtualKeyboardRequested() {
1861 return virtual_keyboard_requested_;
1864 AccessibilityMode WebContentsImpl::GetAccessibilityMode() const {
1865 return accessibility_mode_;
1868 void WebContentsImpl::AccessibilityEventReceived(
1869 const std::vector<AXEventNotificationDetails>& details) {
1870 FOR_EACH_OBSERVER(
1871 WebContentsObserver, observers_, AccessibilityEventReceived(details));
1874 RenderFrameHost* WebContentsImpl::GetGuestByInstanceID(
1875 RenderFrameHost* render_frame_host,
1876 int browser_plugin_instance_id) {
1877 BrowserPluginGuestManager* guest_manager =
1878 GetBrowserContext()->GetGuestManager();
1879 if (!guest_manager)
1880 return nullptr;
1882 WebContents* guest = guest_manager->GetGuestByInstanceID(
1883 render_frame_host->GetProcess()->GetID(), browser_plugin_instance_id);
1884 if (!guest)
1885 return nullptr;
1887 return guest->GetMainFrame();
1890 GeolocationServiceContext* WebContentsImpl::GetGeolocationServiceContext() {
1891 return geolocation_service_context_.get();
1894 void WebContentsImpl::OnShowValidationMessage(
1895 const gfx::Rect& anchor_in_root_view,
1896 const base::string16& main_text,
1897 const base::string16& sub_text) {
1898 if (delegate_)
1899 delegate_->ShowValidationMessage(
1900 this, anchor_in_root_view, main_text, sub_text);
1903 void WebContentsImpl::OnHideValidationMessage() {
1904 if (delegate_)
1905 delegate_->HideValidationMessage(this);
1908 void WebContentsImpl::OnMoveValidationMessage(
1909 const gfx::Rect& anchor_in_root_view) {
1910 if (delegate_)
1911 delegate_->MoveValidationMessage(this, anchor_in_root_view);
1914 void WebContentsImpl::DidSendScreenRects(RenderWidgetHostImpl* rwh) {
1915 if (browser_plugin_embedder_)
1916 browser_plugin_embedder_->DidSendScreenRects();
1919 BrowserAccessibilityManager*
1920 WebContentsImpl::GetRootBrowserAccessibilityManager() {
1921 RenderFrameHostImpl* rfh = GetMainFrame();
1922 return rfh ? rfh->browser_accessibility_manager() : nullptr;
1925 BrowserAccessibilityManager*
1926 WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
1927 RenderFrameHostImpl* rfh = GetMainFrame();
1928 return rfh ? rfh->GetOrCreateBrowserAccessibilityManager() : nullptr;
1931 void WebContentsImpl::UpdatePreferredSize(const gfx::Size& pref_size) {
1932 const gfx::Size old_size = GetPreferredSize();
1933 preferred_size_ = pref_size;
1934 OnPreferredSizeChanged(old_size);
1937 void WebContentsImpl::ResizeDueToAutoResize(const gfx::Size& new_size) {
1938 if (delegate_)
1939 delegate_->ResizeDueToAutoResize(this, new_size);
1942 WebContents* WebContentsImpl::OpenURL(const OpenURLParams& params) {
1943 if (!delegate_)
1944 return NULL;
1946 WebContents* new_contents = delegate_->OpenURLFromTab(this, params);
1947 return new_contents;
1950 bool WebContentsImpl::Send(IPC::Message* message) {
1951 if (!GetRenderViewHost()) {
1952 delete message;
1953 return false;
1956 return GetRenderViewHost()->Send(message);
1959 bool WebContentsImpl::NavigateToPendingEntry(
1960 NavigationController::ReloadType reload_type) {
1961 FrameTreeNode* node = frame_tree_.root();
1963 // Navigate in the FrameTreeNode specified in the pending entry, if any. This
1964 // is currently only used in --site-per-process and tests.
1965 // TODO(creis): Remove this method and NavigationEntryImpl::frame_tree_node_id
1966 // by using FrameNavigationEntries instead. See https://crbug.com/236848.
1967 NavigationEntryImpl* pending_entry = controller_.GetPendingEntry();
1968 if (pending_entry->frame_tree_node_id() != -1) {
1969 FrameTreeNode* subframe =
1970 frame_tree_.FindByID(pending_entry->frame_tree_node_id());
1971 DCHECK(subframe);
1972 if (subframe)
1973 node = subframe;
1976 return node->navigator()->NavigateToPendingEntry(node, reload_type);
1979 void WebContentsImpl::RenderFrameForInterstitialPageCreated(
1980 RenderFrameHost* render_frame_host) {
1981 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1982 RenderFrameForInterstitialPageCreated(render_frame_host));
1985 void WebContentsImpl::AttachInterstitialPage(
1986 InterstitialPageImpl* interstitial_page) {
1987 DCHECK(interstitial_page);
1988 GetRenderManager()->set_interstitial_page(interstitial_page);
1990 // Cancel any visible dialogs so that they don't interfere with the
1991 // interstitial.
1992 if (dialog_manager_)
1993 dialog_manager_->CancelActiveAndPendingDialogs(this);
1995 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1996 DidAttachInterstitialPage());
1999 void WebContentsImpl::DetachInterstitialPage() {
2000 if (ShowingInterstitialPage())
2001 GetRenderManager()->remove_interstitial_page();
2002 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2003 DidDetachInterstitialPage());
2006 void WebContentsImpl::SetHistoryOffsetAndLength(int history_offset,
2007 int history_length) {
2008 SetHistoryOffsetAndLengthForView(
2009 GetRenderViewHost(), history_offset, history_length);
2012 void WebContentsImpl::SetHistoryOffsetAndLengthForView(
2013 RenderViewHost* render_view_host,
2014 int history_offset,
2015 int history_length) {
2016 render_view_host->Send(new ViewMsg_SetHistoryOffsetAndLength(
2017 render_view_host->GetRoutingID(), history_offset, history_length));
2020 void WebContentsImpl::ReloadFocusedFrame(bool ignore_cache) {
2021 RenderFrameHost* focused_frame = GetFocusedFrame();
2022 if (!focused_frame)
2023 return;
2025 focused_frame->Send(new FrameMsg_Reload(
2026 focused_frame->GetRoutingID(), ignore_cache));
2029 void WebContentsImpl::Undo() {
2030 RenderFrameHost* focused_frame = GetFocusedFrame();
2031 if (!focused_frame)
2032 return;
2034 focused_frame->Send(new InputMsg_Undo(focused_frame->GetRoutingID()));
2035 RecordAction(base::UserMetricsAction("Undo"));
2038 void WebContentsImpl::Redo() {
2039 RenderFrameHost* focused_frame = GetFocusedFrame();
2040 if (!focused_frame)
2041 return;
2042 focused_frame->Send(new InputMsg_Redo(focused_frame->GetRoutingID()));
2043 RecordAction(base::UserMetricsAction("Redo"));
2046 void WebContentsImpl::Cut() {
2047 RenderFrameHost* focused_frame = GetFocusedFrame();
2048 if (!focused_frame)
2049 return;
2051 focused_frame->Send(new InputMsg_Cut(focused_frame->GetRoutingID()));
2052 RecordAction(base::UserMetricsAction("Cut"));
2055 void WebContentsImpl::Copy() {
2056 RenderFrameHost* focused_frame = GetFocusedFrame();
2057 if (!focused_frame)
2058 return;
2060 focused_frame->Send(new InputMsg_Copy(focused_frame->GetRoutingID()));
2061 RecordAction(base::UserMetricsAction("Copy"));
2064 void WebContentsImpl::CopyToFindPboard() {
2065 #if defined(OS_MACOSX)
2066 RenderFrameHost* focused_frame = GetFocusedFrame();
2067 if (!focused_frame)
2068 return;
2070 // Windows/Linux don't have the concept of a find pasteboard.
2071 focused_frame->Send(
2072 new InputMsg_CopyToFindPboard(focused_frame->GetRoutingID()));
2073 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
2074 #endif
2077 void WebContentsImpl::Paste() {
2078 RenderFrameHost* focused_frame = GetFocusedFrame();
2079 if (!focused_frame)
2080 return;
2082 focused_frame->Send(new InputMsg_Paste(focused_frame->GetRoutingID()));
2083 RecordAction(base::UserMetricsAction("Paste"));
2086 void WebContentsImpl::PasteAndMatchStyle() {
2087 RenderFrameHost* focused_frame = GetFocusedFrame();
2088 if (!focused_frame)
2089 return;
2091 focused_frame->Send(new InputMsg_PasteAndMatchStyle(
2092 focused_frame->GetRoutingID()));
2093 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
2096 void WebContentsImpl::Delete() {
2097 RenderFrameHost* focused_frame = GetFocusedFrame();
2098 if (!focused_frame)
2099 return;
2101 focused_frame->Send(new InputMsg_Delete(focused_frame->GetRoutingID()));
2102 RecordAction(base::UserMetricsAction("DeleteSelection"));
2105 void WebContentsImpl::SelectAll() {
2106 RenderFrameHost* focused_frame = GetFocusedFrame();
2107 if (!focused_frame)
2108 return;
2110 focused_frame->Send(new InputMsg_SelectAll(focused_frame->GetRoutingID()));
2111 RecordAction(base::UserMetricsAction("SelectAll"));
2114 void WebContentsImpl::Unselect() {
2115 RenderFrameHost* focused_frame = GetFocusedFrame();
2116 if (!focused_frame)
2117 return;
2119 focused_frame->Send(new InputMsg_Unselect(focused_frame->GetRoutingID()));
2120 RecordAction(base::UserMetricsAction("Unselect"));
2123 void WebContentsImpl::Replace(const base::string16& word) {
2124 RenderFrameHost* focused_frame = GetFocusedFrame();
2125 if (!focused_frame)
2126 return;
2128 focused_frame->Send(new InputMsg_Replace(
2129 focused_frame->GetRoutingID(), word));
2132 void WebContentsImpl::ReplaceMisspelling(const base::string16& word) {
2133 RenderFrameHost* focused_frame = GetFocusedFrame();
2134 if (!focused_frame)
2135 return;
2137 focused_frame->Send(new InputMsg_ReplaceMisspelling(
2138 focused_frame->GetRoutingID(), word));
2141 void WebContentsImpl::NotifyContextMenuClosed(
2142 const CustomContextMenuContext& context) {
2143 RenderFrameHost* focused_frame = GetFocusedFrame();
2144 if (!focused_frame)
2145 return;
2147 focused_frame->Send(new FrameMsg_ContextMenuClosed(
2148 focused_frame->GetRoutingID(), context));
2151 void WebContentsImpl::ExecuteCustomContextMenuCommand(
2152 int action, const CustomContextMenuContext& context) {
2153 RenderFrameHost* focused_frame = GetFocusedFrame();
2154 if (!focused_frame)
2155 return;
2157 focused_frame->Send(new FrameMsg_CustomContextMenuAction(
2158 focused_frame->GetRoutingID(), context, action));
2161 gfx::NativeView WebContentsImpl::GetNativeView() {
2162 return view_->GetNativeView();
2165 gfx::NativeView WebContentsImpl::GetContentNativeView() {
2166 return view_->GetContentNativeView();
2169 gfx::NativeWindow WebContentsImpl::GetTopLevelNativeWindow() {
2170 return view_->GetTopLevelNativeWindow();
2173 gfx::Rect WebContentsImpl::GetViewBounds() {
2174 return view_->GetViewBounds();
2177 gfx::Rect WebContentsImpl::GetContainerBounds() {
2178 gfx::Rect rv;
2179 view_->GetContainerBounds(&rv);
2180 return rv;
2183 DropData* WebContentsImpl::GetDropData() {
2184 return view_->GetDropData();
2187 void WebContentsImpl::Focus() {
2188 view_->Focus();
2191 void WebContentsImpl::SetInitialFocus() {
2192 view_->SetInitialFocus();
2195 void WebContentsImpl::StoreFocus() {
2196 view_->StoreFocus();
2199 void WebContentsImpl::RestoreFocus() {
2200 view_->RestoreFocus();
2203 void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
2204 if (ShowingInterstitialPage()) {
2205 GetRenderManager()->interstitial_page()->FocusThroughTabTraversal(reverse);
2206 return;
2208 RenderWidgetHostView* const fullscreen_view =
2209 GetFullscreenRenderWidgetHostView();
2210 if (fullscreen_view) {
2211 fullscreen_view->Focus();
2212 return;
2214 GetRenderViewHost()->SetInitialFocus(reverse);
2217 bool WebContentsImpl::ShowingInterstitialPage() const {
2218 return GetRenderManager()->interstitial_page() != NULL;
2221 InterstitialPage* WebContentsImpl::GetInterstitialPage() const {
2222 return GetRenderManager()->interstitial_page();
2225 bool WebContentsImpl::IsSavable() {
2226 // WebKit creates Document object when MIME type is application/xhtml+xml,
2227 // so we also support this MIME type.
2228 return contents_mime_type_ == "text/html" ||
2229 contents_mime_type_ == "text/xml" ||
2230 contents_mime_type_ == "application/xhtml+xml" ||
2231 contents_mime_type_ == "text/plain" ||
2232 contents_mime_type_ == "text/css" ||
2233 mime_util::IsSupportedJavascriptMimeType(contents_mime_type_);
2236 void WebContentsImpl::OnSavePage() {
2237 // If we can not save the page, try to download it.
2238 if (!IsSavable()) {
2239 RecordDownloadSource(INITIATED_BY_SAVE_PACKAGE_ON_NON_HTML);
2240 SaveFrame(GetLastCommittedURL(), Referrer());
2241 return;
2244 Stop();
2246 // Create the save package and possibly prompt the user for the name to save
2247 // the page as. The user prompt is an asynchronous operation that runs on
2248 // another thread.
2249 save_package_ = new SavePackage(this);
2250 save_package_->GetSaveInfo();
2253 // Used in automated testing to bypass prompting the user for file names.
2254 // Instead, the names and paths are hard coded rather than running them through
2255 // file name sanitation and extension / mime checking.
2256 bool WebContentsImpl::SavePage(const base::FilePath& main_file,
2257 const base::FilePath& dir_path,
2258 SavePageType save_type) {
2259 // Stop the page from navigating.
2260 Stop();
2262 save_package_ = new SavePackage(this, save_type, main_file, dir_path);
2263 return save_package_->Init(SavePackageDownloadCreatedCallback());
2266 void WebContentsImpl::SaveFrame(const GURL& url,
2267 const Referrer& referrer) {
2268 SaveFrameWithHeaders(url, referrer, std::string());
2271 void WebContentsImpl::SaveFrameWithHeaders(const GURL& url,
2272 const Referrer& referrer,
2273 const std::string& headers) {
2274 if (!GetLastCommittedURL().is_valid())
2275 return;
2276 if (delegate_ && delegate_->SaveFrame(url, referrer))
2277 return;
2279 // TODO(nasko): This check for main frame is incorrect and should be fixed
2280 // by explicitly passing in which frame this method should target.
2281 bool is_main_frame = (url == GetLastCommittedURL());
2283 DownloadManager* dlm =
2284 BrowserContext::GetDownloadManager(GetBrowserContext());
2285 if (!dlm)
2286 return;
2287 int64 post_id = -1;
2288 if (is_main_frame) {
2289 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2290 if (entry)
2291 post_id = entry->GetPostID();
2293 scoped_ptr<DownloadUrlParameters> params(
2294 DownloadUrlParameters::FromWebContents(this, url));
2295 params->set_referrer(referrer);
2296 params->set_post_id(post_id);
2297 if (post_id >= 0)
2298 params->set_method("POST");
2299 params->set_prompt(true);
2301 if (headers.empty()) {
2302 params->set_prefer_cache(true);
2303 } else {
2304 std::vector<std::string> key_value_list;
2305 base::SplitString(headers, '\n', &key_value_list);
2306 for (const auto& key_value : key_value_list) {
2307 std::vector<std::string> pair;
2308 base::SplitString(key_value, ':', &pair);
2309 DCHECK_EQ(2ul, pair.size());
2310 params->add_request_header(pair[0], pair[1]);
2313 dlm->DownloadUrl(params.Pass());
2316 void WebContentsImpl::GenerateMHTML(
2317 const base::FilePath& file,
2318 const base::Callback<void(int64)>& callback) {
2319 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, file, callback);
2322 const std::string& WebContentsImpl::GetContentsMimeType() const {
2323 return contents_mime_type_;
2326 bool WebContentsImpl::WillNotifyDisconnection() const {
2327 return notify_disconnection_;
2330 void WebContentsImpl::SetOverrideEncoding(const std::string& encoding) {
2331 SetEncoding(encoding);
2332 Send(new ViewMsg_SetPageEncoding(GetRoutingID(), encoding));
2335 void WebContentsImpl::ResetOverrideEncoding() {
2336 canonical_encoding_.clear();
2337 Send(new ViewMsg_ResetPageEncodingToDefault(GetRoutingID()));
2340 RendererPreferences* WebContentsImpl::GetMutableRendererPrefs() {
2341 return &renderer_preferences_;
2344 void WebContentsImpl::Close() {
2345 Close(GetRenderViewHost());
2348 void WebContentsImpl::DragSourceEndedAt(int client_x, int client_y,
2349 int screen_x, int screen_y, blink::WebDragOperation operation) {
2350 if (browser_plugin_embedder_.get())
2351 browser_plugin_embedder_->DragSourceEndedAt(client_x, client_y,
2352 screen_x, screen_y, operation);
2353 if (GetRenderViewHost())
2354 GetRenderViewHost()->DragSourceEndedAt(client_x, client_y, screen_x,
2355 screen_y, operation);
2358 void WebContentsImpl::DidGetResourceResponseStart(
2359 const ResourceRequestDetails& details) {
2360 controller_.ssl_manager()->DidStartResourceResponse(details);
2362 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2363 DidGetResourceResponseStart(details));
2365 // TODO(avi): Remove. http://crbug.com/170921
2366 NotificationService::current()->Notify(
2367 NOTIFICATION_RESOURCE_RESPONSE_STARTED,
2368 Source<WebContents>(this),
2369 Details<const ResourceRequestDetails>(&details));
2372 void WebContentsImpl::DidGetRedirectForResourceRequest(
2373 RenderFrameHost* render_frame_host,
2374 const ResourceRedirectDetails& details) {
2375 controller_.ssl_manager()->DidReceiveResourceRedirect(details);
2377 FOR_EACH_OBSERVER(
2378 WebContentsObserver,
2379 observers_,
2380 DidGetRedirectForResourceRequest(render_frame_host, details));
2382 // TODO(avi): Remove. http://crbug.com/170921
2383 NotificationService::current()->Notify(
2384 NOTIFICATION_RESOURCE_RECEIVED_REDIRECT,
2385 Source<WebContents>(this),
2386 Details<const ResourceRedirectDetails>(&details));
2389 void WebContentsImpl::NotifyWebContentsFocused() {
2390 FOR_EACH_OBSERVER(WebContentsObserver, observers_, OnWebContentsFocused());
2393 void WebContentsImpl::SystemDragEnded() {
2394 if (GetRenderViewHost())
2395 GetRenderViewHost()->DragSourceSystemDragEnded();
2396 if (browser_plugin_embedder_.get())
2397 browser_plugin_embedder_->SystemDragEnded();
2400 void WebContentsImpl::UserGestureDone() {
2401 OnUserGesture();
2404 void WebContentsImpl::SetClosedByUserGesture(bool value) {
2405 closed_by_user_gesture_ = value;
2408 bool WebContentsImpl::GetClosedByUserGesture() const {
2409 return closed_by_user_gesture_;
2412 void WebContentsImpl::ViewSource() {
2413 if (!delegate_)
2414 return;
2416 NavigationEntry* entry = GetController().GetLastCommittedEntry();
2417 if (!entry)
2418 return;
2420 delegate_->ViewSourceForTab(this, entry->GetURL());
2423 void WebContentsImpl::ViewFrameSource(const GURL& url,
2424 const PageState& page_state) {
2425 if (!delegate_)
2426 return;
2428 delegate_->ViewSourceForFrame(this, url, page_state);
2431 int WebContentsImpl::GetMinimumZoomPercent() const {
2432 return minimum_zoom_percent_;
2435 int WebContentsImpl::GetMaximumZoomPercent() const {
2436 return maximum_zoom_percent_;
2439 void WebContentsImpl::ResetPageScale() {
2440 Send(new ViewMsg_ResetPageScale(GetRoutingID()));
2443 gfx::Size WebContentsImpl::GetPreferredSize() const {
2444 return capturer_count_ == 0 ? preferred_size_ : preferred_size_for_capture_;
2447 bool WebContentsImpl::GotResponseToLockMouseRequest(bool allowed) {
2448 if (GetBrowserPluginGuest())
2449 return GetBrowserPluginGuest()->LockMouse(allowed);
2451 return GetRenderViewHost()
2452 ? GetRenderViewHost()->GotResponseToLockMouseRequest(allowed)
2453 : false;
2456 bool WebContentsImpl::HasOpener() const {
2457 return opener_ != NULL;
2460 WebContents* WebContentsImpl::GetOpener() const {
2461 return static_cast<WebContents*>(opener_);
2464 void WebContentsImpl::DidChooseColorInColorChooser(SkColor color) {
2465 if (!color_chooser_info_.get())
2466 return;
2467 RenderFrameHost* rfh = RenderFrameHost::FromID(
2468 color_chooser_info_->render_process_id,
2469 color_chooser_info_->render_frame_id);
2470 if (!rfh)
2471 return;
2473 rfh->Send(new FrameMsg_DidChooseColorResponse(
2474 rfh->GetRoutingID(), color_chooser_info_->identifier, color));
2477 void WebContentsImpl::DidEndColorChooser() {
2478 if (!color_chooser_info_.get())
2479 return;
2480 RenderFrameHost* rfh = RenderFrameHost::FromID(
2481 color_chooser_info_->render_process_id,
2482 color_chooser_info_->render_frame_id);
2483 if (!rfh)
2484 return;
2486 rfh->Send(new FrameMsg_DidEndColorChooser(
2487 rfh->GetRoutingID(), color_chooser_info_->identifier));
2488 color_chooser_info_.reset();
2491 int WebContentsImpl::DownloadImage(const GURL& url,
2492 bool is_favicon,
2493 uint32_t max_bitmap_size,
2494 bool bypass_cache,
2495 const ImageDownloadCallback& callback) {
2496 int id = StartDownload(GetMainFrame(), url, is_favicon, max_bitmap_size,
2497 bypass_cache);
2498 image_download_map_[id] = callback;
2499 return id;
2502 bool WebContentsImpl::IsSubframe() const {
2503 return is_subframe_;
2506 void WebContentsImpl::Find(int request_id,
2507 const base::string16& search_text,
2508 const blink::WebFindOptions& options) {
2509 // See if a top level browser plugin handles the find request first.
2510 if (browser_plugin_embedder_) {
2511 BrowserPluginGuest* guest = browser_plugin_embedder_->GetFullPageGuest();
2512 if (guest && guest->Find(request_id, search_text, options))
2513 return;
2515 Send(new ViewMsg_Find(GetRoutingID(), request_id, search_text, options));
2518 void WebContentsImpl::StopFinding(StopFindAction action) {
2519 // See if a top level browser plugin handles the stop finding request first.
2520 if (browser_plugin_embedder_) {
2521 BrowserPluginGuest* guest = browser_plugin_embedder_->GetFullPageGuest();
2522 if (guest && guest->StopFinding(action))
2523 return;
2525 Send(new ViewMsg_StopFinding(GetRoutingID(), action));
2528 void WebContentsImpl::InsertCSS(const std::string& css) {
2529 GetMainFrame()->Send(new FrameMsg_CSSInsertRequest(
2530 GetMainFrame()->GetRoutingID(), css));
2533 bool WebContentsImpl::WasRecentlyAudible() {
2534 return audio_state_provider_->WasRecentlyAudible();
2537 void WebContentsImpl::GetManifest(const GetManifestCallback& callback) {
2538 manifest_manager_host_->GetManifest(GetMainFrame(), callback);
2541 void WebContentsImpl::ExitFullscreen() {
2542 // Clean up related state and initiate the fullscreen exit.
2543 GetRenderViewHost()->RejectMouseLockOrUnlockIfNecessary();
2544 ExitFullscreenMode();
2547 void WebContentsImpl::ResumeLoadingCreatedWebContents() {
2548 // Resume blocked requests for both the RenderViewHost and RenderFrameHost.
2549 // TODO(brettw): It seems bogus to reach into here and initialize the host.
2550 GetRenderViewHost()->Init();
2551 GetMainFrame()->Init();
2554 bool WebContentsImpl::FocusLocationBarByDefault() {
2555 NavigationEntry* entry = controller_.GetVisibleEntry();
2556 if (entry && entry->GetURL() == GURL(url::kAboutBlankURL))
2557 return true;
2558 return delegate_ && delegate_->ShouldFocusLocationBarByDefault(this);
2561 void WebContentsImpl::SetFocusToLocationBar(bool select_all) {
2562 if (delegate_)
2563 delegate_->SetFocusToLocationBar(select_all);
2566 void WebContentsImpl::DidStartProvisionalLoad(
2567 RenderFrameHostImpl* render_frame_host,
2568 const GURL& validated_url,
2569 bool is_error_page,
2570 bool is_iframe_srcdoc) {
2571 // Notify observers about the start of the provisional load.
2572 FOR_EACH_OBSERVER(
2573 WebContentsObserver,
2574 observers_,
2575 DidStartProvisionalLoadForFrame(
2576 render_frame_host, validated_url, is_error_page, is_iframe_srcdoc));
2578 // Notify accessibility if this is a reload.
2579 NavigationEntry* entry = controller_.GetVisibleEntry();
2580 if (entry && ui::PageTransitionCoreTypeIs(
2581 entry->GetTransitionType(), ui::PAGE_TRANSITION_RELOAD)) {
2582 FrameTreeNode* ftn = render_frame_host->frame_tree_node();
2583 BrowserAccessibilityManager* manager =
2584 ftn->current_frame_host()->browser_accessibility_manager();
2585 if (manager)
2586 manager->UserIsReloading();
2590 void WebContentsImpl::DidStartNavigationTransition(
2591 RenderFrameHostImpl* render_frame_host) {
2592 #if defined(OS_ANDROID)
2593 int render_frame_id = render_frame_host->GetRoutingID();
2594 GetWebContentsAndroid()->DidStartNavigationTransitionForFrame(
2595 render_frame_id);
2596 #endif
2599 void WebContentsImpl::DidFailProvisionalLoadWithError(
2600 RenderFrameHostImpl* render_frame_host,
2601 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
2602 GURL validated_url(params.url);
2603 FOR_EACH_OBSERVER(WebContentsObserver,
2604 observers_,
2605 DidFailProvisionalLoad(render_frame_host,
2606 validated_url,
2607 params.error_code,
2608 params.error_description));
2610 FrameTreeNode* ftn = render_frame_host->frame_tree_node();
2611 BrowserAccessibilityManager* manager =
2612 ftn->current_frame_host()->browser_accessibility_manager();
2613 if (manager)
2614 manager->NavigationFailed();
2617 void WebContentsImpl::DidFailLoadWithError(
2618 RenderFrameHostImpl* render_frame_host,
2619 const GURL& url,
2620 int error_code,
2621 const base::string16& error_description) {
2622 FOR_EACH_OBSERVER(
2623 WebContentsObserver,
2624 observers_,
2625 DidFailLoad(render_frame_host, url, error_code, error_description));
2628 void WebContentsImpl::NotifyChangedNavigationState(
2629 InvalidateTypes changed_flags) {
2630 NotifyNavigationStateChanged(changed_flags);
2633 void WebContentsImpl::AboutToNavigateRenderFrame(
2634 RenderFrameHostImpl* old_host,
2635 RenderFrameHostImpl* new_host) {
2636 // Notify observers that we will navigate in this RenderFrame.
2637 FOR_EACH_OBSERVER(
2638 WebContentsObserver,
2639 observers_,
2640 AboutToNavigateRenderFrame(old_host, new_host));
2643 void WebContentsImpl::DidStartNavigationToPendingEntry(
2644 const GURL& url,
2645 NavigationController::ReloadType reload_type) {
2646 // Notify observers about navigation.
2647 FOR_EACH_OBSERVER(
2648 WebContentsObserver,
2649 observers_,
2650 DidStartNavigationToPendingEntry(url, reload_type));
2653 void WebContentsImpl::RequestOpenURL(RenderFrameHostImpl* render_frame_host,
2654 const OpenURLParams& params) {
2655 // OpenURL can blow away the source RFH. Use the process/frame routing ID as a
2656 // weak pointer of sorts.
2657 const int32_t process_id = render_frame_host->GetProcess()->GetID();
2658 const int32_t frame_id = render_frame_host->GetRoutingID();
2660 WebContents* new_contents = OpenURL(params);
2662 if (new_contents && RenderFrameHost::FromID(process_id, frame_id)) {
2663 // Notify observers.
2664 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2665 DidOpenRequestedURL(new_contents,
2666 render_frame_host,
2667 params.url,
2668 params.referrer,
2669 params.disposition,
2670 params.transition));
2674 bool WebContentsImpl::ShouldPreserveAbortedURLs() {
2675 if (!delegate_)
2676 return false;
2677 return delegate_->ShouldPreserveAbortedURLs(this);
2680 void WebContentsImpl::DidCommitProvisionalLoad(
2681 RenderFrameHostImpl* render_frame_host,
2682 const GURL& url,
2683 ui::PageTransition transition_type) {
2684 // Notify observers about the commit of the provisional load.
2685 FOR_EACH_OBSERVER(WebContentsObserver,
2686 observers_,
2687 DidCommitProvisionalLoadForFrame(
2688 render_frame_host, url, transition_type));
2690 BrowserAccessibilityManager* manager =
2691 render_frame_host->browser_accessibility_manager();
2692 if (manager)
2693 manager->NavigationSucceeded();
2696 void WebContentsImpl::DidNavigateMainFramePreCommit(
2697 bool navigation_is_within_page) {
2698 // Ensure fullscreen mode is exited before committing the navigation to a
2699 // different page. The next page will not start out assuming it is in
2700 // fullscreen mode.
2701 if (navigation_is_within_page) {
2702 // No page change? Then, the renderer and browser can remain in fullscreen.
2703 return;
2705 if (IsFullscreenForCurrentTab())
2706 ExitFullscreen();
2707 DCHECK(!IsFullscreenForCurrentTab());
2710 void WebContentsImpl::DidNavigateMainFramePostCommit(
2711 RenderFrameHostImpl* render_frame_host,
2712 const LoadCommittedDetails& details,
2713 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
2714 if (details.is_navigation_to_different_page()) {
2715 // Clear the status bubble. This is a workaround for a bug where WebKit
2716 // doesn't let us know that the cursor left an element during a
2717 // transition (this is also why the mouse cursor remains as a hand after
2718 // clicking on a link); see bugs 1184641 and 980803. We don't want to
2719 // clear the bubble when a user navigates to a named anchor in the same
2720 // page.
2721 UpdateTargetURL(render_frame_host->GetRenderViewHost(), GURL());
2723 RenderWidgetHostViewBase* rwhvb =
2724 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
2725 if (rwhvb)
2726 rwhvb->OnDidNavigateMainFrameToNewPage();
2728 // Reset theme color on navigation to new page.
2729 theme_color_ = SK_ColorTRANSPARENT;
2732 if (!details.is_in_page) {
2733 // Once the main frame is navigated, we're no longer considered to have
2734 // displayed insecure content.
2735 displayed_insecure_content_ = false;
2736 SSLManager::NotifySSLInternalStateChanged(
2737 GetController().GetBrowserContext());
2740 // Notify observers about navigation.
2741 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2742 DidNavigateMainFrame(details, params));
2744 if (delegate_)
2745 delegate_->DidNavigateMainFramePostCommit(this);
2746 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
2749 void WebContentsImpl::DidNavigateAnyFramePostCommit(
2750 RenderFrameHostImpl* render_frame_host,
2751 const LoadCommittedDetails& details,
2752 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
2753 // Now that something has committed, we don't need to track whether the
2754 // initial page has been accessed.
2755 has_accessed_initial_document_ = false;
2757 // If we navigate off the page, close all JavaScript dialogs.
2758 if (dialog_manager_ && !details.is_in_page)
2759 dialog_manager_->CancelActiveAndPendingDialogs(this);
2761 // Notify observers about navigation.
2762 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2763 DidNavigateAnyFrame(render_frame_host, details, params));
2766 void WebContentsImpl::SetMainFrameMimeType(const std::string& mime_type) {
2767 contents_mime_type_ = mime_type;
2770 bool WebContentsImpl::CanOverscrollContent() const {
2771 // Disable overscroll when touch emulation is on. See crbug.com/369938.
2772 if (force_disable_overscroll_content_)
2773 return false;
2775 if (delegate_)
2776 return delegate_->CanOverscrollContent();
2778 return false;
2781 void WebContentsImpl::OnThemeColorChanged(SkColor theme_color) {
2782 // Update the theme color. This is to be published to observers on visually
2783 // non empty paint.
2784 theme_color_ = theme_color;
2787 void WebContentsImpl::OnDidLoadResourceFromMemoryCache(
2788 const GURL& url,
2789 const std::string& security_info,
2790 const std::string& http_method,
2791 const std::string& mime_type,
2792 ResourceType resource_type) {
2794 // Send out a notification that we loaded a resource from our memory cache.
2795 int cert_id = 0;
2796 net::CertStatus cert_status = 0;
2797 int security_bits = -1;
2798 int connection_status = 0;
2799 SignedCertificateTimestampIDStatusList signed_certificate_timestamp_ids;
2800 DeserializeSecurityInfo(security_info, &cert_id, &cert_status,
2801 &security_bits, &connection_status,
2802 &signed_certificate_timestamp_ids);
2803 // TODO(alcutter,eranm): Pass signed_certificate_timestamp_ids into details
2804 LoadFromMemoryCacheDetails details(
2805 url, GetRenderProcessHost()->GetID(), cert_id, cert_status, http_method,
2806 mime_type, resource_type);
2808 controller_.ssl_manager()->DidLoadFromMemoryCache(details);
2810 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2811 DidLoadResourceFromMemoryCache(details));
2813 if (url.is_valid() && url.SchemeIsHTTPOrHTTPS()) {
2814 scoped_refptr<net::URLRequestContextGetter> request_context(
2815 resource_type == RESOURCE_TYPE_MEDIA ?
2816 GetBrowserContext()->GetMediaRequestContextForRenderProcess(
2817 GetRenderProcessHost()->GetID()) :
2818 GetBrowserContext()->GetRequestContextForRenderProcess(
2819 GetRenderProcessHost()->GetID()));
2820 BrowserThread::PostTask(
2821 BrowserThread::IO,
2822 FROM_HERE,
2823 base::Bind(&NotifyCacheOnIO, request_context, url, http_method));
2827 void WebContentsImpl::OnDidDisplayInsecureContent() {
2828 RecordAction(base::UserMetricsAction("SSL.DisplayedInsecureContent"));
2829 displayed_insecure_content_ = true;
2830 SSLManager::NotifySSLInternalStateChanged(
2831 GetController().GetBrowserContext());
2834 void WebContentsImpl::OnDidRunInsecureContent(
2835 const std::string& security_origin, const GURL& target_url) {
2836 LOG(WARNING) << security_origin << " ran insecure content from "
2837 << target_url.possibly_invalid_spec();
2838 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
2839 if (EndsWith(security_origin, kDotGoogleDotCom, false))
2840 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
2841 controller_.ssl_manager()->DidRunInsecureContent(security_origin);
2842 displayed_insecure_content_ = true;
2843 SSLManager::NotifySSLInternalStateChanged(
2844 GetController().GetBrowserContext());
2847 void WebContentsImpl::OnDocumentLoadedInFrame() {
2848 if (!HasValidFrameSource())
2849 return;
2851 RenderFrameHostImpl* rfh =
2852 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2853 FOR_EACH_OBSERVER(
2854 WebContentsObserver, observers_, DocumentLoadedInFrame(rfh));
2857 void WebContentsImpl::OnDidFinishLoad(const GURL& url) {
2858 if (!HasValidFrameSource())
2859 return;
2861 GURL validated_url(url);
2862 RenderProcessHost* render_process_host =
2863 render_frame_message_source_->GetProcess();
2864 render_process_host->FilterURL(false, &validated_url);
2866 RenderFrameHostImpl* rfh =
2867 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2868 FOR_EACH_OBSERVER(
2869 WebContentsObserver, observers_, DidFinishLoad(rfh, validated_url));
2872 void WebContentsImpl::OnGoToEntryAtOffset(int offset) {
2873 if (!delegate_ || delegate_->OnGoToEntryOffset(offset))
2874 controller_.GoToOffset(offset);
2877 void WebContentsImpl::OnUpdateZoomLimits(int minimum_percent,
2878 int maximum_percent) {
2879 minimum_zoom_percent_ = minimum_percent;
2880 maximum_zoom_percent_ = maximum_percent;
2883 void WebContentsImpl::OnEnumerateDirectory(int request_id,
2884 const base::FilePath& path) {
2885 if (!delegate_)
2886 return;
2888 ChildProcessSecurityPolicyImpl* policy =
2889 ChildProcessSecurityPolicyImpl::GetInstance();
2890 if (policy->CanReadFile(GetRenderProcessHost()->GetID(), path))
2891 delegate_->EnumerateDirectory(this, request_id, path);
2894 void WebContentsImpl::OnRegisterProtocolHandler(const std::string& protocol,
2895 const GURL& url,
2896 const base::string16& title,
2897 bool user_gesture) {
2898 if (!delegate_)
2899 return;
2901 ChildProcessSecurityPolicyImpl* policy =
2902 ChildProcessSecurityPolicyImpl::GetInstance();
2903 if (policy->IsPseudoScheme(protocol))
2904 return;
2906 delegate_->RegisterProtocolHandler(this, protocol, url, user_gesture);
2909 void WebContentsImpl::OnUnregisterProtocolHandler(const std::string& protocol,
2910 const GURL& url,
2911 bool user_gesture) {
2912 if (!delegate_)
2913 return;
2915 ChildProcessSecurityPolicyImpl* policy =
2916 ChildProcessSecurityPolicyImpl::GetInstance();
2917 if (policy->IsPseudoScheme(protocol))
2918 return;
2920 delegate_->UnregisterProtocolHandler(this, protocol, url, user_gesture);
2923 void WebContentsImpl::OnFindReply(int request_id,
2924 int number_of_matches,
2925 const gfx::Rect& selection_rect,
2926 int active_match_ordinal,
2927 bool final_update) {
2928 if (delegate_) {
2929 delegate_->FindReply(this, request_id, number_of_matches, selection_rect,
2930 active_match_ordinal, final_update);
2934 #if defined(OS_ANDROID)
2935 void WebContentsImpl::OnFindMatchRectsReply(
2936 int version,
2937 const std::vector<gfx::RectF>& rects,
2938 const gfx::RectF& active_rect) {
2939 if (delegate_)
2940 delegate_->FindMatchRectsReply(this, version, rects, active_rect);
2943 void WebContentsImpl::OnOpenDateTimeDialog(
2944 const ViewHostMsg_DateTimeDialogValue_Params& value) {
2945 date_time_chooser_->ShowDialog(GetTopLevelNativeWindow(),
2946 GetRenderViewHost(),
2947 value.dialog_type,
2948 value.dialog_value,
2949 value.minimum,
2950 value.maximum,
2951 value.step,
2952 value.suggestions);
2954 #endif
2956 void WebContentsImpl::OnDomOperationResponse(const std::string& json_string,
2957 int automation_id) {
2958 DomOperationNotificationDetails details(json_string, automation_id);
2959 NotificationService::current()->Notify(
2960 NOTIFICATION_DOM_OPERATION_RESPONSE,
2961 Source<WebContents>(this),
2962 Details<DomOperationNotificationDetails>(&details));
2965 void WebContentsImpl::OnAppCacheAccessed(const GURL& manifest_url,
2966 bool blocked_by_policy) {
2967 // Notify observers about navigation.
2968 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2969 AppCacheAccessed(manifest_url, blocked_by_policy));
2972 void WebContentsImpl::OnOpenColorChooser(
2973 int color_chooser_id,
2974 SkColor color,
2975 const std::vector<ColorSuggestion>& suggestions) {
2976 if (!HasValidFrameSource())
2977 return;
2979 ColorChooser* new_color_chooser = delegate_ ?
2980 delegate_->OpenColorChooser(this, color, suggestions) :
2981 NULL;
2982 if (!new_color_chooser)
2983 return;
2984 if (color_chooser_info_.get())
2985 color_chooser_info_->chooser->End();
2987 color_chooser_info_.reset(new ColorChooserInfo(
2988 render_frame_message_source_->GetProcess()->GetID(),
2989 render_frame_message_source_->GetRoutingID(),
2990 new_color_chooser,
2991 color_chooser_id));
2994 void WebContentsImpl::OnEndColorChooser(int color_chooser_id) {
2995 if (color_chooser_info_ &&
2996 color_chooser_id == color_chooser_info_->identifier)
2997 color_chooser_info_->chooser->End();
3000 void WebContentsImpl::OnSetSelectedColorInColorChooser(int color_chooser_id,
3001 SkColor color) {
3002 if (color_chooser_info_ &&
3003 color_chooser_id == color_chooser_info_->identifier)
3004 color_chooser_info_->chooser->SetSelectedColor(color);
3007 // This exists for render views that don't have a WebUI, but do have WebUI
3008 // bindings enabled.
3009 void WebContentsImpl::OnWebUISend(const GURL& source_url,
3010 const std::string& name,
3011 const base::ListValue& args) {
3012 if (delegate_)
3013 delegate_->WebUISend(this, source_url, name, args);
3016 #if defined(ENABLE_PLUGINS)
3017 void WebContentsImpl::OnPepperPluginHung(int plugin_child_id,
3018 const base::FilePath& path,
3019 bool is_hung) {
3020 UMA_HISTOGRAM_COUNTS("Pepper.PluginHung", 1);
3022 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3023 PluginHungStatusChanged(plugin_child_id, path, is_hung));
3026 void WebContentsImpl::OnPluginCrashed(const base::FilePath& plugin_path,
3027 base::ProcessId plugin_pid) {
3028 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3029 PluginCrashed(plugin_path, plugin_pid));
3032 void WebContentsImpl::OnRequestPpapiBrokerPermission(
3033 int routing_id,
3034 const GURL& url,
3035 const base::FilePath& plugin_path) {
3036 if (!delegate_) {
3037 OnPpapiBrokerPermissionResult(routing_id, false);
3038 return;
3041 if (!delegate_->RequestPpapiBrokerPermission(
3042 this, url, plugin_path,
3043 base::Bind(&WebContentsImpl::OnPpapiBrokerPermissionResult,
3044 base::Unretained(this), routing_id))) {
3045 NOTIMPLEMENTED();
3046 OnPpapiBrokerPermissionResult(routing_id, false);
3050 void WebContentsImpl::OnPpapiBrokerPermissionResult(int routing_id,
3051 bool result) {
3052 Send(new ViewMsg_PpapiBrokerPermissionResult(routing_id, result));
3055 void WebContentsImpl::OnBrowserPluginMessage(RenderFrameHost* render_frame_host,
3056 const IPC::Message& message) {
3057 CHECK(!browser_plugin_embedder_.get());
3058 CreateBrowserPluginEmbedderIfNecessary();
3059 browser_plugin_embedder_->OnMessageReceived(message, render_frame_host);
3061 #endif // defined(ENABLE_PLUGINS)
3063 void WebContentsImpl::OnDidDownloadImage(
3064 int id,
3065 int http_status_code,
3066 const GURL& image_url,
3067 const std::vector<SkBitmap>& bitmaps,
3068 const std::vector<gfx::Size>& original_bitmap_sizes) {
3069 if (bitmaps.size() != original_bitmap_sizes.size())
3070 return;
3072 ImageDownloadMap::iterator iter = image_download_map_.find(id);
3073 if (iter == image_download_map_.end()) {
3074 // Currently WebContents notifies us of ANY downloads so that it is
3075 // possible to get here.
3076 return;
3078 if (!iter->second.is_null()) {
3079 iter->second.Run(
3080 id, http_status_code, image_url, bitmaps, original_bitmap_sizes);
3082 image_download_map_.erase(id);
3085 void WebContentsImpl::OnUpdateFaviconURL(
3086 const std::vector<FaviconURL>& candidates) {
3087 // We get updated favicon URLs after the page stops loading. If a cross-site
3088 // navigation occurs while a page is still loading, the initial page
3089 // may stop loading and send us updated favicon URLs after the navigation
3090 // for the new page has committed.
3091 RenderViewHostImpl* rvhi =
3092 static_cast<RenderViewHostImpl*>(render_view_message_source_);
3093 if (!rvhi->is_active())
3094 return;
3096 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3097 DidUpdateFaviconURL(candidates));
3100 void WebContentsImpl::CreateAudioPowerSaveBlocker() {
3101 DCHECK(!audio_power_save_blocker_);
3102 audio_power_save_blocker_ = PowerSaveBlocker::Create(
3103 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension,
3104 PowerSaveBlocker::kReasonAudioPlayback, "Playing audio");
3107 void WebContentsImpl::CreateVideoPowerSaveBlocker() {
3108 DCHECK(!video_power_save_blocker_);
3109 DCHECK(!active_video_players_.empty());
3110 video_power_save_blocker_ = PowerSaveBlocker::Create(
3111 PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep,
3112 PowerSaveBlocker::kReasonVideoPlayback, "Playing video");
3113 #if defined(OS_ANDROID)
3114 static_cast<PowerSaveBlockerImpl*>(video_power_save_blocker_.get())
3115 ->InitDisplaySleepBlocker(this);
3116 #endif
3119 void WebContentsImpl::MaybeReleasePowerSaveBlockers() {
3120 // If there are no more audio players and we don't have audio stream
3121 // monitoring, release the audio power save blocker here instead of during
3122 // NotifyNavigationStateChanged().
3123 if (active_audio_players_.empty() &&
3124 !audio_state_provider_->IsAudioStateAvailable()) {
3125 audio_power_save_blocker_.reset();
3128 // If there are no more video players, clear the video power save blocker.
3129 if (active_video_players_.empty())
3130 video_power_save_blocker_.reset();
3133 void WebContentsImpl::OnMediaPlayingNotification(int64 player_cookie,
3134 bool has_video,
3135 bool has_audio,
3136 bool is_remote) {
3137 // Ignore the videos playing remotely and don't hold the wake lock for the
3138 // screen.
3139 if (is_remote) return;
3141 if (has_audio) {
3142 AddMediaPlayerEntry(player_cookie, &active_audio_players_);
3144 // If we don't have audio stream monitoring, allocate the audio power save
3145 // blocker here instead of during NotifyNavigationStateChanged().
3146 if (!audio_power_save_blocker_ &&
3147 !audio_state_provider_->IsAudioStateAvailable()) {
3148 CreateAudioPowerSaveBlocker();
3152 if (has_video) {
3153 AddMediaPlayerEntry(player_cookie, &active_video_players_);
3155 // If we're not hidden and have just created a player, create a blocker.
3156 if (!video_power_save_blocker_ && !IsHidden())
3157 CreateVideoPowerSaveBlocker();
3160 FOR_EACH_OBSERVER(WebContentsObserver, observers_, MediaStartedPlaying());
3163 void WebContentsImpl::OnMediaPausedNotification(int64 player_cookie) {
3164 RemoveMediaPlayerEntry(player_cookie, &active_audio_players_);
3165 RemoveMediaPlayerEntry(player_cookie, &active_video_players_);
3166 MaybeReleasePowerSaveBlockers();
3168 FOR_EACH_OBSERVER(WebContentsObserver, observers_, MediaPaused());
3171 void WebContentsImpl::OnFirstVisuallyNonEmptyPaint() {
3172 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3173 DidFirstVisuallyNonEmptyPaint());
3175 if (theme_color_ != last_sent_theme_color_) {
3176 // Theme color should have updated by now if there was one.
3177 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3178 DidChangeThemeColor(theme_color_));
3179 last_sent_theme_color_ = theme_color_;
3183 void WebContentsImpl::DidChangeVisibleSSLState() {
3184 if (delegate_)
3185 delegate_->VisibleSSLStateChanged(this);
3188 void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
3189 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3190 BeforeFormRepostWarningShow());
3193 void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
3194 Activate();
3195 if (delegate_)
3196 delegate_->ShowRepostFormWarningDialog(this);
3199 bool WebContentsImpl::HasAccessedInitialDocument() {
3200 return has_accessed_initial_document_;
3203 // Notifies the RenderWidgetHost instance about the fact that the page is
3204 // loading, or done loading.
3205 void WebContentsImpl::SetIsLoading(bool is_loading,
3206 bool to_different_document,
3207 LoadNotificationDetails* details) {
3208 if (is_loading == is_loading_)
3209 return;
3211 if (!is_loading) {
3212 load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
3213 base::string16());
3214 load_state_host_.clear();
3215 upload_size_ = 0;
3216 upload_position_ = 0;
3219 GetRenderManager()->SetIsLoading(is_loading);
3221 is_loading_ = is_loading;
3222 waiting_for_response_ = is_loading;
3223 is_load_to_different_document_ = to_different_document;
3225 if (delegate_)
3226 delegate_->LoadingStateChanged(this, to_different_document);
3227 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
3229 std::string url = (details ? details->url.possibly_invalid_spec() : "NULL");
3230 if (is_loading) {
3231 TRACE_EVENT_ASYNC_BEGIN1("browser,navigation", "WebContentsImpl Loading",
3232 this, "URL", url);
3233 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidStartLoading());
3234 } else {
3235 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
3236 this, "URL", url);
3237 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidStopLoading());
3240 // TODO(avi): Remove. http://crbug.com/170921
3241 int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
3242 NotificationDetails det = NotificationService::NoDetails();
3243 if (details)
3244 det = Details<LoadNotificationDetails>(details);
3245 NotificationService::current()->Notify(
3246 type, Source<NavigationController>(&controller_), det);
3249 void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point& extent) {
3250 RenderFrameHost* focused_frame = GetFocusedFrame();
3251 if (!focused_frame)
3252 return;
3254 focused_frame->Send(new InputMsg_MoveRangeSelectionExtent(
3255 focused_frame->GetRoutingID(), extent));
3258 void WebContentsImpl::SelectRange(const gfx::Point& base,
3259 const gfx::Point& extent) {
3260 RenderFrameHost* focused_frame = GetFocusedFrame();
3261 if (!focused_frame)
3262 return;
3264 focused_frame->Send(
3265 new InputMsg_SelectRange(focused_frame->GetRoutingID(), base, extent));
3268 void WebContentsImpl::UpdateMaxPageIDIfNecessary(RenderViewHost* rvh) {
3269 // If we are creating a RVH for a restored controller, then we need to make
3270 // sure the RenderView starts with a next_page_id_ larger than the number
3271 // of restored entries. This must be called before the RenderView starts
3272 // navigating (to avoid a race between the browser updating max_page_id and
3273 // the renderer updating next_page_id_). Because of this, we only call this
3274 // from CreateRenderView and allow that to notify the RenderView for us.
3275 int max_restored_page_id = controller_.GetMaxRestoredPageID();
3276 if (max_restored_page_id >
3277 GetMaxPageIDForSiteInstance(rvh->GetSiteInstance()))
3278 UpdateMaxPageIDForSiteInstance(rvh->GetSiteInstance(),
3279 max_restored_page_id);
3282 bool WebContentsImpl::UpdateTitleForEntry(NavigationEntryImpl* entry,
3283 const base::string16& title) {
3284 // For file URLs without a title, use the pathname instead. In the case of a
3285 // synthesized title, we don't want the update to count toward the "one set
3286 // per page of the title to history."
3287 base::string16 final_title;
3288 bool explicit_set;
3289 if (entry && entry->GetURL().SchemeIsFile() && title.empty()) {
3290 final_title = base::UTF8ToUTF16(entry->GetURL().ExtractFileName());
3291 explicit_set = false; // Don't count synthetic titles toward the set limit.
3292 } else {
3293 base::TrimWhitespace(title, base::TRIM_ALL, &final_title);
3294 explicit_set = true;
3297 // If a page is created via window.open and never navigated,
3298 // there will be no navigation entry. In this situation,
3299 // |page_title_when_no_navigation_entry_| will be used for page title.
3300 if (entry) {
3301 if (final_title == entry->GetTitle())
3302 return false; // Nothing changed, don't bother.
3304 entry->SetTitle(final_title);
3305 } else {
3306 if (page_title_when_no_navigation_entry_ == final_title)
3307 return false; // Nothing changed, don't bother.
3309 page_title_when_no_navigation_entry_ = final_title;
3312 // Lastly, set the title for the view.
3313 view_->SetPageTitle(final_title);
3315 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3316 TitleWasSet(entry, explicit_set));
3318 // TODO(avi): Remove. http://crbug.com/170921
3319 std::pair<NavigationEntry*, bool> details =
3320 std::make_pair(entry, explicit_set);
3321 NotificationService::current()->Notify(
3322 NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED,
3323 Source<WebContents>(this),
3324 Details<std::pair<NavigationEntry*, bool> >(&details));
3326 return true;
3329 void WebContentsImpl::SendChangeLoadProgress() {
3330 loading_last_progress_update_ = base::TimeTicks::Now();
3331 if (delegate_)
3332 delegate_->LoadProgressChanged(this, frame_tree_.load_progress());
3335 void WebContentsImpl::ResetLoadProgressState() {
3336 frame_tree_.ResetLoadProgress();
3337 loading_weak_factory_.InvalidateWeakPtrs();
3338 loading_last_progress_update_ = base::TimeTicks();
3341 void WebContentsImpl::NotifyViewSwapped(RenderViewHost* old_host,
3342 RenderViewHost* new_host) {
3343 // After sending out a swap notification, we need to send a disconnect
3344 // notification so that clients that pick up a pointer to |this| can NULL the
3345 // pointer. See Bug 1230284.
3346 notify_disconnection_ = true;
3347 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3348 RenderViewHostChanged(old_host, new_host));
3350 // TODO(avi): Remove. http://crbug.com/170921
3351 std::pair<RenderViewHost*, RenderViewHost*> details =
3352 std::make_pair(old_host, new_host);
3353 NotificationService::current()->Notify(
3354 NOTIFICATION_RENDER_VIEW_HOST_CHANGED,
3355 Source<WebContents>(this),
3356 Details<std::pair<RenderViewHost*, RenderViewHost*> >(&details));
3358 // Ensure that the associated embedder gets cleared after a RenderViewHost
3359 // gets swapped, so we don't reuse the same embedder next time a
3360 // RenderViewHost is attached to this WebContents.
3361 RemoveBrowserPluginEmbedder();
3364 void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost* old_host,
3365 RenderFrameHost* new_host) {
3366 FOR_EACH_OBSERVER(WebContentsObserver,
3367 observers_,
3368 RenderFrameHostChanged(old_host, new_host));
3371 // TODO(avi): Remove this entire function because this notification is already
3372 // covered by two observer functions. http://crbug.com/170921
3373 void WebContentsImpl::NotifyDisconnected() {
3374 if (!notify_disconnection_)
3375 return;
3377 notify_disconnection_ = false;
3378 NotificationService::current()->Notify(
3379 NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
3380 Source<WebContents>(this),
3381 NotificationService::NoDetails());
3384 void WebContentsImpl::NotifyNavigationEntryCommitted(
3385 const LoadCommittedDetails& load_details) {
3386 FOR_EACH_OBSERVER(
3387 WebContentsObserver, observers_, NavigationEntryCommitted(load_details));
3390 bool WebContentsImpl::OnMessageReceived(RenderFrameHost* render_frame_host,
3391 const IPC::Message& message) {
3392 return OnMessageReceived(NULL, render_frame_host, message);
3395 const GURL& WebContentsImpl::GetMainFrameLastCommittedURL() const {
3396 return GetLastCommittedURL();
3399 void WebContentsImpl::RenderFrameCreated(RenderFrameHost* render_frame_host) {
3400 // Note this is only for subframes, the notification for the main frame
3401 // happens in RenderViewCreated.
3402 FOR_EACH_OBSERVER(WebContentsObserver,
3403 observers_,
3404 RenderFrameCreated(render_frame_host));
3405 SetAccessibilityModeOnFrame(accessibility_mode_, render_frame_host);
3408 void WebContentsImpl::RenderFrameDeleted(RenderFrameHost* render_frame_host) {
3409 ClearPowerSaveBlockers(render_frame_host);
3410 FOR_EACH_OBSERVER(WebContentsObserver,
3411 observers_,
3412 RenderFrameDeleted(render_frame_host));
3415 void WebContentsImpl::WorkerCrashed(RenderFrameHost* render_frame_host) {
3416 if (delegate_)
3417 delegate_->WorkerCrashed(this);
3420 void WebContentsImpl::ShowContextMenu(RenderFrameHost* render_frame_host,
3421 const ContextMenuParams& params) {
3422 ContextMenuParams context_menu_params(params);
3423 // Allow WebContentsDelegates to handle the context menu operation first.
3424 if (delegate_ && delegate_->HandleContextMenu(context_menu_params))
3425 return;
3427 render_view_host_delegate_view_->ShowContextMenu(render_frame_host,
3428 context_menu_params);
3431 void WebContentsImpl::RunJavaScriptMessage(
3432 RenderFrameHost* render_frame_host,
3433 const base::string16& message,
3434 const base::string16& default_prompt,
3435 const GURL& frame_url,
3436 JavaScriptMessageType javascript_message_type,
3437 IPC::Message* reply_msg) {
3438 // Suppress JavaScript dialogs when requested. Also suppress messages when
3439 // showing an interstitial as it's shown over the previous page and we don't
3440 // want the hidden page's dialogs to interfere with the interstitial.
3441 bool suppress_this_message =
3442 static_cast<RenderFrameHostImpl*>(render_frame_host)->is_swapped_out() ||
3443 ShowingInterstitialPage() || !delegate_ ||
3444 delegate_->ShouldSuppressDialogs(this) ||
3445 !delegate_->GetJavaScriptDialogManager(this);
3447 if (!suppress_this_message) {
3448 std::string accept_lang = GetContentClient()->browser()->
3449 GetAcceptLangs(GetBrowserContext());
3450 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
3451 dialog_manager_->RunJavaScriptDialog(
3452 this,
3453 frame_url.GetOrigin(),
3454 accept_lang,
3455 javascript_message_type,
3456 message,
3457 default_prompt,
3458 base::Bind(&WebContentsImpl::OnDialogClosed,
3459 base::Unretained(this),
3460 render_frame_host->GetProcess()->GetID(),
3461 render_frame_host->GetRoutingID(),
3462 reply_msg,
3463 false),
3464 &suppress_this_message);
3467 if (suppress_this_message) {
3468 // If we are suppressing messages, just reply as if the user immediately
3469 // pressed "Cancel", passing true to |dialog_was_suppressed|.
3470 OnDialogClosed(render_frame_host->GetProcess()->GetID(),
3471 render_frame_host->GetRoutingID(), reply_msg,
3472 true, false, base::string16());
3475 // OnDialogClosed (two lines up) may have caused deletion of this object (see
3476 // http://crbug.com/288961 ). The only safe thing to do here is return.
3479 void WebContentsImpl::RunBeforeUnloadConfirm(
3480 RenderFrameHost* render_frame_host,
3481 const base::string16& message,
3482 bool is_reload,
3483 IPC::Message* reply_msg) {
3484 RenderFrameHostImpl* rfhi =
3485 static_cast<RenderFrameHostImpl*>(render_frame_host);
3486 if (delegate_)
3487 delegate_->WillRunBeforeUnloadConfirm();
3489 bool suppress_this_message =
3490 rfhi->rfh_state() != RenderFrameHostImpl::STATE_DEFAULT || !delegate_ ||
3491 delegate_->ShouldSuppressDialogs(this) ||
3492 !delegate_->GetJavaScriptDialogManager(this);
3493 if (suppress_this_message) {
3494 rfhi->JavaScriptDialogClosed(reply_msg, true, base::string16(), true);
3495 return;
3498 is_showing_before_unload_dialog_ = true;
3499 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
3500 dialog_manager_->RunBeforeUnloadDialog(
3501 this, message, is_reload,
3502 base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
3503 render_frame_host->GetProcess()->GetID(),
3504 render_frame_host->GetRoutingID(), reply_msg,
3505 false));
3508 WebContents* WebContentsImpl::GetAsWebContents() {
3509 return this;
3512 bool WebContentsImpl::IsNeverVisible() {
3513 if (!delegate_)
3514 return false;
3515 return delegate_->IsNeverVisible(this);
3518 #if defined(OS_WIN)
3519 gfx::NativeViewAccessible WebContentsImpl::GetParentNativeViewAccessible() {
3520 return accessible_parent_;
3522 #endif
3524 RenderViewHostDelegateView* WebContentsImpl::GetDelegateView() {
3525 return render_view_host_delegate_view_;
3528 RendererPreferences WebContentsImpl::GetRendererPrefs(
3529 BrowserContext* browser_context) const {
3530 return renderer_preferences_;
3533 gfx::Rect WebContentsImpl::GetRootWindowResizerRect() const {
3534 if (delegate_)
3535 return delegate_->GetRootWindowResizerRect();
3536 return gfx::Rect();
3539 void WebContentsImpl::RemoveBrowserPluginEmbedder() {
3540 if (browser_plugin_embedder_)
3541 browser_plugin_embedder_.reset();
3544 void WebContentsImpl::RenderViewCreated(RenderViewHost* render_view_host) {
3545 // Don't send notifications if we are just creating a swapped-out RVH for
3546 // the opener chain. These won't be used for view-source or WebUI, so it's
3547 // ok to return early.
3548 if (!static_cast<RenderViewHostImpl*>(render_view_host)->is_active())
3549 return;
3551 if (delegate_)
3552 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
3554 NotificationService::current()->Notify(
3555 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
3556 Source<WebContents>(this),
3557 Details<RenderViewHost>(render_view_host));
3559 // When we're creating views, we're still doing initial setup, so we always
3560 // use the pending Web UI rather than any possibly existing committed one.
3561 if (GetRenderManager()->pending_web_ui())
3562 GetRenderManager()->pending_web_ui()->RenderViewCreated(render_view_host);
3564 NavigationEntry* entry = controller_.GetPendingEntry();
3565 if (entry && entry->IsViewSourceMode()) {
3566 // Put the renderer in view source mode.
3567 render_view_host->Send(
3568 new ViewMsg_EnableViewSourceMode(render_view_host->GetRoutingID()));
3571 view_->RenderViewCreated(render_view_host);
3573 FOR_EACH_OBSERVER(
3574 WebContentsObserver, observers_, RenderViewCreated(render_view_host));
3577 void WebContentsImpl::RenderViewReady(RenderViewHost* rvh) {
3578 if (rvh != GetRenderViewHost()) {
3579 // Don't notify the world, since this came from a renderer in the
3580 // background.
3581 return;
3584 notify_disconnection_ = true;
3585 // TODO(avi): Remove. http://crbug.com/170921
3586 NotificationService::current()->Notify(
3587 NOTIFICATION_WEB_CONTENTS_CONNECTED,
3588 Source<WebContents>(this),
3589 NotificationService::NoDetails());
3591 bool was_crashed = IsCrashed();
3592 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
3594 // Restore the focus to the tab (otherwise the focus will be on the top
3595 // window).
3596 if (was_crashed && !FocusLocationBarByDefault() &&
3597 (!delegate_ || delegate_->ShouldFocusPageAfterCrash())) {
3598 view_->Focus();
3601 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewReady());
3604 void WebContentsImpl::RenderViewTerminated(RenderViewHost* rvh,
3605 base::TerminationStatus status,
3606 int error_code) {
3607 if (rvh != GetRenderViewHost()) {
3608 // The pending page's RenderViewHost is gone.
3609 return;
3612 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
3613 // renderer may not have made a clean exit.
3614 if (IsFullscreenForCurrentTab())
3615 ExitFullscreenMode();
3617 // Cancel any visible dialogs so they are not left dangling over the sad tab.
3618 if (dialog_manager_)
3619 dialog_manager_->CancelActiveAndPendingDialogs(this);
3621 if (delegate_)
3622 delegate_->HideValidationMessage(this);
3624 SetIsLoading(false, true, nullptr);
3625 NotifyDisconnected();
3626 SetIsCrashed(status, error_code);
3628 // Reset the loading progress. TODO(avi): What does it mean to have a
3629 // "renderer crash" when there is more than one renderer process serving a
3630 // webpage? Once this function is called at a more granular frame level, we
3631 // probably will need to more granularly reset the state here.
3632 ResetLoadProgressState();
3634 FOR_EACH_OBSERVER(WebContentsObserver,
3635 observers_,
3636 RenderProcessGone(GetCrashedStatus()));
3639 void WebContentsImpl::RenderViewDeleted(RenderViewHost* rvh) {
3640 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewDeleted(rvh));
3643 void WebContentsImpl::UpdateState(RenderViewHost* rvh,
3644 int32 page_id,
3645 const PageState& page_state) {
3646 // Ensure that this state update comes from a RenderViewHost that belongs to
3647 // this WebContents.
3648 // TODO(nasko): This should go through RenderFrameHost.
3649 // TODO(creis): We can't update state for cross-process subframes until we
3650 // have FrameNavigationEntries. Once we do, this should be a DCHECK.
3651 if (rvh->GetDelegate()->GetAsWebContents() != this)
3652 return;
3654 // We must be prepared to handle state updates for any page, these occur
3655 // when the user is scrolling and entering form data, as well as when we're
3656 // leaving a page, in which case our state may have already been moved to
3657 // the next page. The navigation controller will look up the appropriate
3658 // NavigationEntry and update it when it is notified via the delegate.
3660 int entry_index = controller_.GetEntryIndexWithPageID(
3661 rvh->GetSiteInstance(), page_id);
3662 if (entry_index < 0)
3663 return;
3664 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
3666 if (page_state == entry->GetPageState())
3667 return; // Nothing to update.
3668 entry->SetPageState(page_state);
3669 controller_.NotifyEntryChanged(entry, entry_index);
3672 void WebContentsImpl::UpdateTargetURL(RenderViewHost* render_view_host,
3673 const GURL& url) {
3674 if (fullscreen_widget_routing_id_ != MSG_ROUTING_NONE) {
3675 // If we're fullscreen only update the url if it's from the fullscreen
3676 // renderer.
3677 RenderWidgetHostView* fs = GetFullscreenRenderWidgetHostView();
3678 if (fs && fs->GetRenderWidgetHost() != render_view_host)
3679 return;
3681 if (delegate_)
3682 delegate_->UpdateTargetURL(this, url);
3685 void WebContentsImpl::Close(RenderViewHost* rvh) {
3686 #if defined(OS_MACOSX)
3687 // The UI may be in an event-tracking loop, such as between the
3688 // mouse-down and mouse-up in text selection or a button click.
3689 // Defer the close until after tracking is complete, so that we
3690 // don't free objects out from under the UI.
3691 // TODO(shess): This could get more fine-grained. For instance,
3692 // closing a tab in another window while selecting text in the
3693 // current window's Omnibox should be just fine.
3694 if (view_->IsEventTracking()) {
3695 view_->CloseTabAfterEventTracking();
3696 return;
3698 #endif
3700 // Ignore this if it comes from a RenderViewHost that we aren't showing.
3701 if (delegate_ && rvh == GetRenderViewHost())
3702 delegate_->CloseContents(this);
3705 void WebContentsImpl::SwappedOut(RenderFrameHost* rfh) {
3706 if (delegate_ && rfh->GetRenderViewHost() == GetRenderViewHost())
3707 delegate_->SwappedOut(this);
3710 void WebContentsImpl::DidDeferAfterResponseStarted(
3711 const TransitionLayerData& transition_data) {
3712 #if defined(OS_ANDROID)
3713 GetWebContentsAndroid()->DidDeferAfterResponseStarted(transition_data);
3714 #endif
3717 bool WebContentsImpl::WillHandleDeferAfterResponseStarted() {
3718 #if defined(OS_ANDROID)
3719 return GetWebContentsAndroid()->WillHandleDeferAfterResponseStarted();
3720 #else
3721 return false;
3722 #endif
3725 void WebContentsImpl::RequestMove(const gfx::Rect& new_bounds) {
3726 if (delegate_ && delegate_->IsPopupOrPanel(this))
3727 delegate_->MoveContents(this, new_bounds);
3730 void WebContentsImpl::DidStartLoading(FrameTreeNode* frame_tree_node,
3731 bool to_different_document) {
3732 SetIsLoading(true, to_different_document, nullptr);
3734 // Notify accessibility that the user is navigating away from the
3735 // current document.
3737 // TODO(dmazzoni): do this using a WebContentsObserver.
3738 BrowserAccessibilityManager* manager =
3739 frame_tree_node->current_frame_host()->browser_accessibility_manager();
3740 if (manager)
3741 manager->UserIsNavigatingAway();
3744 void WebContentsImpl::DidStopLoading() {
3745 scoped_ptr<LoadNotificationDetails> details;
3747 // Use the last committed entry rather than the active one, in case a
3748 // pending entry has been created.
3749 NavigationEntry* entry = controller_.GetLastCommittedEntry();
3750 Navigator* navigator = frame_tree_.root()->navigator();
3752 // An entry may not exist for a stop when loading an initial blank page or
3753 // if an iframe injected by script into a blank page finishes loading.
3754 if (entry) {
3755 base::TimeDelta elapsed =
3756 base::TimeTicks::Now() - navigator->GetCurrentLoadStart();
3758 details.reset(new LoadNotificationDetails(
3759 entry->GetVirtualURL(),
3760 entry->GetTransitionType(),
3761 elapsed,
3762 &controller_,
3763 controller_.GetCurrentEntryIndex()));
3766 SetIsLoading(false, true, details.get());
3769 void WebContentsImpl::DidChangeLoadProgress() {
3770 double load_progress = frame_tree_.load_progress();
3772 // The delegate is notified immediately for the first and last updates. Also,
3773 // since the message loop may be pretty busy when a page is loaded, it might
3774 // not execute a posted task in a timely manner so the progress report is sent
3775 // immediately if enough time has passed.
3776 base::TimeDelta min_delay =
3777 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS);
3778 bool delay_elapsed = loading_last_progress_update_.is_null() ||
3779 base::TimeTicks::Now() - loading_last_progress_update_ > min_delay;
3781 if (load_progress == 0.0 || load_progress == 1.0 || delay_elapsed) {
3782 // If there is a pending task to send progress, it is now obsolete.
3783 loading_weak_factory_.InvalidateWeakPtrs();
3785 // Notify the load progress change.
3786 SendChangeLoadProgress();
3788 // Clean-up the states if needed.
3789 if (load_progress == 1.0)
3790 ResetLoadProgressState();
3791 return;
3794 if (loading_weak_factory_.HasWeakPtrs())
3795 return;
3797 base::MessageLoop::current()->PostDelayedTask(
3798 FROM_HERE,
3799 base::Bind(&WebContentsImpl::SendChangeLoadProgress,
3800 loading_weak_factory_.GetWeakPtr()),
3801 min_delay);
3804 void WebContentsImpl::DidCancelLoading() {
3805 controller_.DiscardNonCommittedEntries();
3807 // Update the URL display.
3808 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
3811 void WebContentsImpl::DidAccessInitialDocument() {
3812 has_accessed_initial_document_ = true;
3814 // We may have left a failed browser-initiated navigation in the address bar
3815 // to let the user edit it and try again. Clear it now that content might
3816 // show up underneath it.
3817 if (!IsLoading() && controller_.GetPendingEntry())
3818 controller_.DiscardPendingEntry(false);
3820 // Update the URL display.
3821 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
3824 void WebContentsImpl::DidChangeName(RenderFrameHost* render_frame_host,
3825 const std::string& name) {
3826 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3827 FrameNameChanged(render_frame_host, name));
3830 void WebContentsImpl::DidDisownOpener(RenderFrameHost* render_frame_host) {
3831 // No action is necessary if the opener has already been cleared.
3832 if (!opener_)
3833 return;
3835 // Clear our opener so that future cross-process navigations don't have an
3836 // opener assigned.
3837 RemoveDestructionObserver(opener_);
3838 opener_ = NULL;
3840 // Notify all swapped out RenderViewHosts for this tab. This is important
3841 // in case we go back to them, or if another window in those processes tries
3842 // to access window.opener.
3843 GetRenderManager()->DidDisownOpener(render_frame_host);
3846 void WebContentsImpl::DocumentOnLoadCompleted(
3847 RenderFrameHost* render_frame_host) {
3848 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3849 DocumentOnLoadCompletedInMainFrame());
3851 // TODO(avi): Remove. http://crbug.com/170921
3852 NotificationService::current()->Notify(
3853 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
3854 Source<WebContents>(this),
3855 NotificationService::NoDetails());
3858 void WebContentsImpl::UpdateTitle(RenderFrameHost* render_frame_host,
3859 int32 page_id,
3860 const base::string16& title,
3861 base::i18n::TextDirection title_direction) {
3862 RenderViewHost* rvh = render_frame_host->GetRenderViewHost();
3864 // If we have a title, that's a pretty good indication that we've started
3865 // getting useful data.
3866 SetNotWaitingForResponse();
3868 // Try to find the navigation entry, which might not be the current one.
3869 // For example, it might be from a pending RVH for the pending entry.
3870 NavigationEntryImpl* entry = controller_.GetEntryWithPageID(
3871 rvh->GetSiteInstance(), page_id);
3873 // Re http://crbug.com/369661, page id is going away. This function should
3874 // only ever be called for the last committed entry. When this is verified,
3875 // this function can be greatly simplified.
3876 CHECK_EQ(entry, controller_.GetLastCommittedEntry());
3878 // We can handle title updates when we don't have an entry in
3879 // UpdateTitleForEntry, but only if the update is from the current RVH.
3880 // TODO(avi): Change to make decisions based on the RenderFrameHost.
3881 if (!entry && rvh != GetRenderViewHost())
3882 return;
3884 // TODO(evan): make use of title_direction.
3885 // http://code.google.com/p/chromium/issues/detail?id=27094
3886 if (!UpdateTitleForEntry(entry, title))
3887 return;
3889 // Broadcast notifications when the UI should be updated.
3890 if (entry == controller_.GetEntryAtOffset(0))
3891 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
3894 void WebContentsImpl::UpdateEncoding(RenderFrameHost* render_frame_host,
3895 const std::string& encoding) {
3896 SetEncoding(encoding);
3899 void WebContentsImpl::DocumentAvailableInMainFrame(
3900 RenderViewHost* render_view_host) {
3901 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3902 DocumentAvailableInMainFrame());
3905 void WebContentsImpl::RouteCloseEvent(RenderViewHost* rvh) {
3906 // Tell the active RenderViewHost to run unload handlers and close, as long
3907 // as the request came from a RenderViewHost in the same BrowsingInstance.
3908 // In most cases, we receive this from a swapped out RenderViewHost.
3909 // It is possible to receive it from one that has just been swapped in,
3910 // in which case we might as well deliver the message anyway.
3911 if (rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()))
3912 ClosePage();
3915 bool WebContentsImpl::ShouldRouteMessageEvent(
3916 RenderFrameHost* target_rfh,
3917 SiteInstance* source_site_instance) const {
3918 // Allow the message if this WebContents is dedicated to a browser plugin
3919 // guest.
3920 // Note: This check means that an embedder could theoretically receive a
3921 // postMessage from anyone (not just its own guests). However, this is
3922 // probably not a risk for apps since other pages won't have references
3923 // to App windows.
3924 return GetBrowserPluginGuest() || GetBrowserPluginEmbedder();
3927 int WebContentsImpl::EnsureOpenerRenderViewsExist(
3928 RenderFrameHost* source_rfh) {
3929 WebContentsImpl* source_web_contents = static_cast<WebContentsImpl*>(
3930 WebContents::FromRenderFrameHost(source_rfh));
3932 if (source_web_contents) {
3933 if (GetBrowserPluginGuest()) {
3934 // We create a swapped out RenderView for the embedder in the guest's
3935 // render process but we intentionally do not expose the embedder's
3936 // opener chain to it.
3937 return
3938 source_web_contents->CreateSwappedOutRenderView(GetSiteInstance());
3939 } else {
3940 return source_web_contents->CreateOpenerRenderViews(GetSiteInstance());
3944 return MSG_ROUTING_NONE;
3947 bool WebContentsImpl::AddMessageToConsole(int32 level,
3948 const base::string16& message,
3949 int32 line_no,
3950 const base::string16& source_id) {
3951 if (!delegate_)
3952 return false;
3953 return delegate_->AddMessageToConsole(this, level, message, line_no,
3954 source_id);
3957 int WebContentsImpl::CreateSwappedOutRenderView(
3958 SiteInstance* instance) {
3959 int render_view_routing_id = MSG_ROUTING_NONE;
3960 GetRenderManager()->CreateRenderFrame(
3961 instance, nullptr, MSG_ROUTING_NONE,
3962 CREATE_RF_SWAPPED_OUT | CREATE_RF_FOR_MAIN_FRAME_NAVIGATION |
3963 CREATE_RF_HIDDEN,
3964 &render_view_routing_id);
3965 return render_view_routing_id;
3968 void WebContentsImpl::OnUserGesture() {
3969 // Notify observers.
3970 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetUserGesture());
3972 ResourceDispatcherHostImpl* rdh = ResourceDispatcherHostImpl::Get();
3973 if (rdh) // NULL in unittests.
3974 rdh->OnUserGesture(this);
3977 void WebContentsImpl::OnIgnoredUIEvent() {
3978 // Notify observers.
3979 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetIgnoredUIEvent());
3982 void WebContentsImpl::RendererUnresponsive(RenderViewHost* render_view_host) {
3983 // Don't show hung renderer dialog for a swapped out RVH.
3984 if (render_view_host != GetRenderViewHost())
3985 return;
3987 RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(render_view_host);
3988 RenderFrameHostImpl* rfhi =
3989 static_cast<RenderFrameHostImpl*>(rvhi->GetMainFrame());
3991 // Ignore renderer unresponsive event if debugger is attached to the tab
3992 // since the event may be a result of the renderer sitting on a breakpoint.
3993 // See http://crbug.com/65458
3994 if (DevToolsAgentHost::IsDebuggerAttached(this))
3995 return;
3997 if (rfhi->IsWaitingForBeforeUnloadACK() ||
3998 rfhi->IsWaitingForUnloadACK()) {
3999 // Hang occurred while firing the beforeunload/unload handler.
4000 // Pretend the handler fired so tab closing continues as if it had.
4001 rvhi->set_sudden_termination_allowed(true);
4003 if (!GetRenderManager()->ShouldCloseTabOnUnresponsiveRenderer())
4004 return;
4006 // If the tab hangs in the beforeunload/unload handler there's really
4007 // nothing we can do to recover. If the hang is in the beforeunload handler,
4008 // pretend the beforeunload listeners have all fired and allow the delegate
4009 // to continue closing; the user will not have the option of cancelling the
4010 // close. Otherwise, pretend the unload listeners have all fired and close
4011 // the tab.
4012 bool close = true;
4013 if (rfhi->IsWaitingForBeforeUnloadACK() && delegate_) {
4014 delegate_->BeforeUnloadFired(this, true, &close);
4016 if (close)
4017 Close(rvhi);
4018 return;
4021 if (!GetRenderViewHost() || !GetRenderViewHost()->IsRenderViewLive())
4022 return;
4024 if (delegate_)
4025 delegate_->RendererUnresponsive(this);
4028 void WebContentsImpl::RendererResponsive(RenderViewHost* render_view_host) {
4029 if (delegate_)
4030 delegate_->RendererResponsive(this);
4033 void WebContentsImpl::LoadStateChanged(
4034 const GURL& url,
4035 const net::LoadStateWithParam& load_state,
4036 uint64 upload_position,
4037 uint64 upload_size) {
4038 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
4039 // is fixed.
4040 tracked_objects::ScopedTracker tracking_profile1(
4041 FROM_HERE_WITH_EXPLICIT_FUNCTION(
4042 "466285 WebContentsImpl::LoadStateChanged::Start"));
4043 load_state_ = load_state;
4044 upload_position_ = upload_position;
4045 upload_size_ = upload_size;
4046 load_state_host_ = net::IDNToUnicode(url.host(),
4047 GetContentClient()->browser()->GetAcceptLangs(
4048 GetBrowserContext()));
4049 if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
4050 SetNotWaitingForResponse();
4051 if (IsLoading()) {
4052 NotifyNavigationStateChanged(static_cast<InvalidateTypes>(
4053 INVALIDATE_TYPE_LOAD | INVALIDATE_TYPE_TAB));
4057 void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
4058 bool proceed, const base::TimeTicks& proceed_time,
4059 bool* proceed_to_fire_unload) {
4060 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4061 BeforeUnloadFired(proceed_time));
4062 if (delegate_)
4063 delegate_->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
4064 // Note: |this| might be deleted at this point.
4067 void WebContentsImpl::RenderProcessGoneFromRenderManager(
4068 RenderViewHost* render_view_host) {
4069 DCHECK(crashed_status_ != base::TERMINATION_STATUS_STILL_RUNNING);
4070 RenderViewTerminated(render_view_host, crashed_status_, crashed_error_code_);
4073 void WebContentsImpl::UpdateRenderViewSizeForRenderManager() {
4074 // TODO(brettw) this is a hack. See WebContentsView::SizeContents.
4075 gfx::Size size = GetSizeForNewRenderView();
4076 // 0x0 isn't a valid window size (minimal window size is 1x1) but it may be
4077 // here during container initialization and normal window size will be set
4078 // later. In case of tab duplication this resizing to 0x0 prevents setting
4079 // normal size later so just ignore it.
4080 if (!size.IsEmpty())
4081 view_->SizeContents(size);
4084 void WebContentsImpl::CancelModalDialogsForRenderManager() {
4085 // We need to cancel modal dialogs when doing a process swap, since the load
4086 // deferrer would prevent us from swapping out. We also clear the state
4087 // because this is a cross-process navigation, which means that it's a new
4088 // site that should not have to pay for the sins of its predecessor.
4089 if (dialog_manager_)
4090 dialog_manager_->ResetDialogState(this);
4093 void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost* old_host,
4094 RenderFrameHost* new_host,
4095 bool is_main_frame) {
4096 if (is_main_frame) {
4097 NotifyViewSwapped(old_host ? old_host->GetRenderViewHost() : nullptr,
4098 new_host->GetRenderViewHost());
4100 // Make sure the visible RVH reflects the new delegate's preferences.
4101 if (delegate_)
4102 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
4104 view_->RenderViewSwappedIn(new_host->GetRenderViewHost());
4107 NotifyFrameSwapped(old_host, new_host);
4110 void WebContentsImpl::NotifyMainFrameSwappedFromRenderManager(
4111 RenderViewHost* old_host,
4112 RenderViewHost* new_host) {
4113 NotifyViewSwapped(old_host, new_host);
4116 int WebContentsImpl::CreateOpenerRenderViewsForRenderManager(
4117 SiteInstance* instance) {
4118 if (!opener_)
4119 return MSG_ROUTING_NONE;
4121 // Recursively create RenderViews for anything else in the opener chain.
4122 return opener_->CreateOpenerRenderViews(instance);
4125 int WebContentsImpl::CreateOpenerRenderViews(SiteInstance* instance) {
4126 int opener_route_id = MSG_ROUTING_NONE;
4128 // If this tab has an opener, ensure it has a RenderView in the given
4129 // SiteInstance as well.
4130 if (opener_)
4131 opener_route_id = opener_->CreateOpenerRenderViews(instance);
4133 // If any of the renderers (current, pending, or swapped out) for this
4134 // WebContents has the same SiteInstance, use it.
4135 if (GetRenderManager()->current_host()->GetSiteInstance() == instance)
4136 return GetRenderManager()->current_host()->GetRoutingID();
4138 if (GetRenderManager()->pending_render_view_host() &&
4139 GetRenderManager()->pending_render_view_host()->GetSiteInstance() ==
4140 instance)
4141 return GetRenderManager()->pending_render_view_host()->GetRoutingID();
4143 RenderViewHostImpl* rvh = GetRenderManager()->GetSwappedOutRenderViewHost(
4144 instance);
4145 if (rvh)
4146 return rvh->GetRoutingID();
4148 // Create a swapped out RenderView in the given SiteInstance if none exists,
4149 // setting its opener to the given route_id. Return the new view's route_id.
4150 int render_view_routing_id = MSG_ROUTING_NONE;
4151 GetRenderManager()->CreateRenderFrame(instance, nullptr, opener_route_id,
4152 CREATE_RF_FOR_MAIN_FRAME_NAVIGATION |
4153 CREATE_RF_SWAPPED_OUT |
4154 CREATE_RF_HIDDEN,
4155 &render_view_routing_id);
4156 return render_view_routing_id;
4159 NavigationControllerImpl& WebContentsImpl::GetControllerForRenderManager() {
4160 return GetController();
4163 scoped_ptr<WebUIImpl> WebContentsImpl::CreateWebUIForRenderManager(
4164 const GURL& url) {
4165 return scoped_ptr<WebUIImpl>(static_cast<WebUIImpl*>(CreateWebUI(url)));
4168 NavigationEntry*
4169 WebContentsImpl::GetLastCommittedNavigationEntryForRenderManager() {
4170 return controller_.GetLastCommittedEntry();
4173 bool WebContentsImpl::CreateRenderViewForRenderManager(
4174 RenderViewHost* render_view_host,
4175 int opener_route_id,
4176 int proxy_routing_id,
4177 bool for_main_frame_navigation) {
4178 TRACE_EVENT0("browser,navigation",
4179 "WebContentsImpl::CreateRenderViewForRenderManager");
4180 // Can be NULL during tests.
4181 RenderWidgetHostViewBase* rwh_view;
4182 // TODO(kenrb): RenderWidgetHostViewChildFrame special casing is temporary
4183 // until RenderWidgetHost is attached to RenderFrameHost. We need to special
4184 // case this because RWH is still a base class of RenderViewHost, and child
4185 // frame RWHVs are unique in that they do not have their own WebContents.
4186 if (!for_main_frame_navigation) {
4187 RenderWidgetHostViewChildFrame* rwh_view_child =
4188 new RenderWidgetHostViewChildFrame(render_view_host);
4189 rwh_view = rwh_view_child;
4190 } else {
4191 rwh_view = view_->CreateViewForWidget(render_view_host, false);
4194 // Now that the RenderView has been created, we need to tell it its size.
4195 if (rwh_view)
4196 rwh_view->SetSize(GetSizeForNewRenderView());
4198 // Make sure we use the correct starting page_id in the new RenderView.
4199 UpdateMaxPageIDIfNecessary(render_view_host);
4200 int32 max_page_id =
4201 GetMaxPageIDForSiteInstance(render_view_host->GetSiteInstance());
4203 if (!static_cast<RenderViewHostImpl*>(
4204 render_view_host)->CreateRenderView(base::string16(),
4205 opener_route_id,
4206 proxy_routing_id,
4207 max_page_id,
4208 created_with_opener_)) {
4209 return false;
4212 SetHistoryOffsetAndLengthForView(render_view_host,
4213 controller_.GetLastCommittedEntryIndex(),
4214 controller_.GetEntryCount());
4216 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
4217 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
4218 // linux. See crbug.com/83941.
4219 if (rwh_view) {
4220 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
4221 render_widget_host->WasResized();
4223 #endif
4225 return true;
4228 bool WebContentsImpl::CreateRenderFrameForRenderManager(
4229 RenderFrameHost* render_frame_host,
4230 int parent_routing_id,
4231 int previous_sibling_routing_id,
4232 int proxy_routing_id) {
4233 TRACE_EVENT0("browser,navigation",
4234 "WebContentsImpl::CreateRenderFrameForRenderManager");
4236 RenderFrameHostImpl* rfh =
4237 static_cast<RenderFrameHostImpl*>(render_frame_host);
4238 if (!rfh->CreateRenderFrame(parent_routing_id, previous_sibling_routing_id,
4239 proxy_routing_id))
4240 return false;
4242 // TODO(nasko): When RenderWidgetHost is owned by RenderFrameHost, the passed
4243 // RenderFrameHost will have to be associated with the appropriate
4244 // RenderWidgetHostView or a new one should be created here.
4246 return true;
4249 #if defined(OS_ANDROID)
4251 base::android::ScopedJavaLocalRef<jobject>
4252 WebContentsImpl::GetJavaWebContents() {
4253 DCHECK_CURRENTLY_ON(BrowserThread::UI);
4254 return GetWebContentsAndroid()->GetJavaObject();
4257 WebContentsAndroid* WebContentsImpl::GetWebContentsAndroid() {
4258 WebContentsAndroid* web_contents_android =
4259 static_cast<WebContentsAndroid*>(GetUserData(kWebContentsAndroidKey));
4260 if (!web_contents_android) {
4261 web_contents_android = new WebContentsAndroid(this);
4262 SetUserData(kWebContentsAndroidKey, web_contents_android);
4264 return web_contents_android;
4267 bool WebContentsImpl::CreateRenderViewForInitialEmptyDocument() {
4268 return CreateRenderViewForRenderManager(GetRenderViewHost(),
4269 MSG_ROUTING_NONE,
4270 MSG_ROUTING_NONE,
4271 true);
4274 #elif defined(OS_MACOSX)
4276 void WebContentsImpl::SetAllowOtherViews(bool allow) {
4277 view_->SetAllowOtherViews(allow);
4280 bool WebContentsImpl::GetAllowOtherViews() {
4281 return view_->GetAllowOtherViews();
4284 #endif
4286 void WebContentsImpl::OnDialogClosed(int render_process_id,
4287 int render_frame_id,
4288 IPC::Message* reply_msg,
4289 bool dialog_was_suppressed,
4290 bool success,
4291 const base::string16& user_input) {
4292 RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(render_process_id,
4293 render_frame_id);
4294 last_dialog_suppressed_ = dialog_was_suppressed;
4296 if (is_showing_before_unload_dialog_ && !success) {
4297 // If a beforeunload dialog is canceled, we need to stop the throbber from
4298 // spinning, since we forced it to start spinning in Navigate.
4299 if (rfh)
4300 DidStopLoading();
4301 controller_.DiscardNonCommittedEntries();
4303 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4304 BeforeUnloadDialogCancelled());
4307 is_showing_before_unload_dialog_ = false;
4308 if (rfh) {
4309 rfh->JavaScriptDialogClosed(reply_msg, success, user_input,
4310 dialog_was_suppressed);
4311 } else {
4312 // Don't leak the sync IPC reply if the RFH or process is gone.
4313 delete reply_msg;
4317 void WebContentsImpl::SetEncoding(const std::string& encoding) {
4318 if (encoding == last_reported_encoding_)
4319 return;
4320 last_reported_encoding_ = encoding;
4322 canonical_encoding_ = GetContentClient()->browser()->
4323 GetCanonicalEncodingNameByAliasName(encoding);
4326 bool WebContentsImpl::IsHidden() {
4327 return capturer_count_ == 0 && !should_normally_be_visible_;
4330 RenderFrameHostManager* WebContentsImpl::GetRenderManager() const {
4331 return frame_tree_.root()->render_manager();
4334 BrowserPluginGuest* WebContentsImpl::GetBrowserPluginGuest() const {
4335 return browser_plugin_guest_.get();
4338 void WebContentsImpl::SetBrowserPluginGuest(BrowserPluginGuest* guest) {
4339 CHECK(!browser_plugin_guest_);
4340 browser_plugin_guest_.reset(guest);
4343 BrowserPluginEmbedder* WebContentsImpl::GetBrowserPluginEmbedder() const {
4344 return browser_plugin_embedder_.get();
4347 void WebContentsImpl::CreateBrowserPluginEmbedderIfNecessary() {
4348 if (browser_plugin_embedder_)
4349 return;
4350 browser_plugin_embedder_.reset(BrowserPluginEmbedder::Create(this));
4353 void WebContentsImpl::ClearPowerSaveBlockers(
4354 RenderFrameHost* render_frame_host) {
4355 RemoveAllMediaPlayerEntries(render_frame_host, &active_audio_players_);
4356 RemoveAllMediaPlayerEntries(render_frame_host, &active_video_players_);
4357 MaybeReleasePowerSaveBlockers();
4360 void WebContentsImpl::ClearAllPowerSaveBlockers() {
4361 active_audio_players_.clear();
4362 active_video_players_.clear();
4363 audio_power_save_blocker_.reset();
4364 video_power_save_blocker_.reset();
4367 gfx::Size WebContentsImpl::GetSizeForNewRenderView() {
4368 gfx::Size size;
4369 if (delegate_)
4370 size = delegate_->GetSizeForNewRenderView(this);
4371 if (size.IsEmpty())
4372 size = GetContainerBounds().size();
4373 return size;
4376 void WebContentsImpl::OnFrameRemoved(RenderFrameHost* render_frame_host) {
4377 FOR_EACH_OBSERVER(
4378 WebContentsObserver, observers_, FrameDeleted(render_frame_host));
4381 void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size& old_size) {
4382 if (!delegate_)
4383 return;
4384 const gfx::Size new_size = GetPreferredSize();
4385 if (new_size != old_size)
4386 delegate_->UpdatePreferredSize(this, new_size);
4389 void WebContentsImpl::AddMediaPlayerEntry(int64 player_cookie,
4390 ActiveMediaPlayerMap* player_map) {
4391 if (!HasValidFrameSource())
4392 return;
4394 const uintptr_t key =
4395 reinterpret_cast<uintptr_t>(render_frame_message_source_);
4396 DCHECK(std::find((*player_map)[key].begin(),
4397 (*player_map)[key].end(),
4398 player_cookie) == (*player_map)[key].end());
4399 (*player_map)[key].push_back(player_cookie);
4402 void WebContentsImpl::RemoveMediaPlayerEntry(int64 player_cookie,
4403 ActiveMediaPlayerMap* player_map) {
4404 if (!HasValidFrameSource())
4405 return;
4407 const uintptr_t key =
4408 reinterpret_cast<uintptr_t>(render_frame_message_source_);
4409 ActiveMediaPlayerMap::iterator it = player_map->find(key);
4410 if (it == player_map->end())
4411 return;
4413 // Remove the player.
4414 PlayerList::iterator player_it =
4415 std::find(it->second.begin(), it->second.end(), player_cookie);
4416 if (player_it != it->second.end())
4417 it->second.erase(player_it);
4419 // If there are no players left, remove the map entry.
4420 if (it->second.empty())
4421 player_map->erase(it);
4424 void WebContentsImpl::RemoveAllMediaPlayerEntries(
4425 RenderFrameHost* render_frame_host,
4426 ActiveMediaPlayerMap* player_map) {
4427 ActiveMediaPlayerMap::iterator it =
4428 player_map->find(reinterpret_cast<uintptr_t>(render_frame_host));
4429 if (it == player_map->end())
4430 return;
4431 player_map->erase(it);
4434 void WebContentsImpl::ResumeResponseDeferredAtStart() {
4435 FrameTreeNode* node = frame_tree_.root();
4436 node->render_manager()->ResumeResponseDeferredAtStart();
4439 void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable) {
4440 force_disable_overscroll_content_ = force_disable;
4441 if (view_)
4442 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
4445 } // namespace content