Fix: Don't access MessagePortService in the UI thread.
[chromium-blink-merge.git] / content / browser / web_contents / web_contents_impl.cc
blob3b300b6e4f774eeb75b2580c72714c9d6a11a20d
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/strings/string16.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/time/time.h"
19 #include "base/trace_event/trace_event.h"
20 #include "content/browser/accessibility/accessibility_mode_helper.h"
21 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
22 #include "content/browser/browser_plugin/browser_plugin_embedder.h"
23 #include "content/browser/browser_plugin/browser_plugin_guest.h"
24 #include "content/browser/child_process_security_policy_impl.h"
25 #include "content/browser/devtools/devtools_manager.h"
26 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
27 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
28 #include "content/browser/download/download_stats.h"
29 #include "content/browser/download/mhtml_generation_manager.h"
30 #include "content/browser/download/save_package.h"
31 #include "content/browser/frame_host/cross_process_frame_connector.h"
32 #include "content/browser/frame_host/interstitial_page_impl.h"
33 #include "content/browser/frame_host/navigation_entry_impl.h"
34 #include "content/browser/frame_host/navigator_impl.h"
35 #include "content/browser/frame_host/render_frame_host_impl.h"
36 #include "content/browser/frame_host/render_widget_host_view_child_frame.h"
37 #include "content/browser/geolocation/geolocation_service_context.h"
38 #include "content/browser/host_zoom_map_impl.h"
39 #include "content/browser/loader/resource_dispatcher_host_impl.h"
40 #include "content/browser/manifest/manifest_manager_host.h"
41 #include "content/browser/media/audio_stream_monitor.h"
42 #include "content/browser/media/capture/web_contents_audio_muter.h"
43 #include "content/browser/message_port_message_filter.h"
44 #include "content/browser/plugin_content_origin_whitelist.h"
45 #include "content/browser/power_save_blocker_impl.h"
46 #include "content/browser/renderer_host/render_process_host_impl.h"
47 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
48 #include "content/browser/renderer_host/render_view_host_impl.h"
49 #include "content/browser/renderer_host/render_widget_host_impl.h"
50 #include "content/browser/renderer_host/render_widget_host_view_base.h"
51 #include "content/browser/screen_orientation/screen_orientation_dispatcher_host_impl.h"
52 #include "content/browser/site_instance_impl.h"
53 #include "content/browser/web_contents/web_contents_view_guest.h"
54 #include "content/browser/webui/generic_handler.h"
55 #include "content/browser/webui/web_ui_controller_factory_registry.h"
56 #include "content/browser/webui/web_ui_impl.h"
57 #include "content/common/browser_plugin/browser_plugin_constants.h"
58 #include "content/common/browser_plugin/browser_plugin_messages.h"
59 #include "content/common/frame_messages.h"
60 #include "content/common/image_messages.h"
61 #include "content/common/input_messages.h"
62 #include "content/common/ssl_status_serialization.h"
63 #include "content/common/view_messages.h"
64 #include "content/public/browser/ax_event_notification_details.h"
65 #include "content/public/browser/browser_context.h"
66 #include "content/public/browser/browser_plugin_guest_manager.h"
67 #include "content/public/browser/content_browser_client.h"
68 #include "content/public/browser/devtools_agent_host.h"
69 #include "content/public/browser/download_manager.h"
70 #include "content/public/browser/download_url_parameters.h"
71 #include "content/public/browser/invalidate_type.h"
72 #include "content/public/browser/javascript_dialog_manager.h"
73 #include "content/public/browser/load_from_memory_cache_details.h"
74 #include "content/public/browser/load_notification_details.h"
75 #include "content/public/browser/navigation_details.h"
76 #include "content/public/browser/notification_details.h"
77 #include "content/public/browser/notification_service.h"
78 #include "content/public/browser/render_widget_host_iterator.h"
79 #include "content/public/browser/resource_request_details.h"
80 #include "content/public/browser/screen_orientation_dispatcher_host.h"
81 #include "content/public/browser/storage_partition.h"
82 #include "content/public/browser/user_metrics.h"
83 #include "content/public/browser/web_contents_delegate.h"
84 #include "content/public/browser/web_contents_observer.h"
85 #include "content/public/common/bindings_policy.h"
86 #include "content/public/common/content_constants.h"
87 #include "content/public/common/content_switches.h"
88 #include "content/public/common/page_zoom.h"
89 #include "content/public/common/result_codes.h"
90 #include "content/public/common/url_constants.h"
91 #include "content/public/common/url_utils.h"
92 #include "content/public/common/web_preferences.h"
93 #include "net/base/mime_util.h"
94 #include "net/base/net_util.h"
95 #include "net/http/http_cache.h"
96 #include "net/http/http_transaction_factory.h"
97 #include "net/url_request/url_request_context.h"
98 #include "net/url_request/url_request_context_getter.h"
99 #include "ui/base/layout.h"
100 #include "ui/gfx/display.h"
101 #include "ui/gfx/screen.h"
102 #include "ui/gl/gl_switches.h"
104 #if defined(ENABLE_BROWSER_CDMS)
105 #include "content/browser/media/media_web_contents_observer.h"
106 #endif
108 #if defined(OS_ANDROID)
109 #include "content/browser/android/content_video_view.h"
110 #include "content/browser/android/date_time_chooser_android.h"
111 #include "content/browser/media/android/browser_media_player_manager.h"
112 #include "content/browser/web_contents/web_contents_android.h"
113 #endif
115 #if defined(OS_MACOSX)
116 #include "base/mac/foundation_util.h"
117 #endif
119 namespace content {
120 namespace {
122 const int kMinimumDelayBetweenLoadingUpdatesMS = 100;
124 // This matches what Blink's ProgressTracker has traditionally used for a
125 // minimum progress value.
126 const double kMinimumLoadingProgress = 0.1;
128 const char kDotGoogleDotCom[] = ".google.com";
130 #if defined(OS_ANDROID)
131 const char kWebContentsAndroidKey[] = "web_contents_android";
132 #endif // OS_ANDROID
134 base::LazyInstance<std::vector<WebContentsImpl::CreatedCallback> >
135 g_created_callbacks = LAZY_INSTANCE_INITIALIZER;
137 static int StartDownload(RenderFrameHost* rfh,
138 const GURL& url,
139 bool is_favicon,
140 uint32_t max_bitmap_size) {
141 static int g_next_image_download_id = 0;
142 rfh->Send(new ImageMsg_DownloadImage(rfh->GetRoutingID(),
143 ++g_next_image_download_id,
144 url,
145 is_favicon,
146 max_bitmap_size));
147 return g_next_image_download_id;
150 void NotifyCacheOnIO(
151 scoped_refptr<net::URLRequestContextGetter> request_context,
152 const GURL& url,
153 const std::string& http_method) {
154 request_context->GetURLRequestContext()->http_transaction_factory()->
155 GetCache()->OnExternalCacheHit(url, http_method);
158 // Helper function for retrieving all the sites in a frame tree.
159 bool CollectSites(BrowserContext* context,
160 std::set<GURL>* sites,
161 FrameTreeNode* node) {
162 sites->insert(SiteInstance::GetSiteForURL(context, node->current_url()));
163 return true;
166 bool ForEachFrameInternal(
167 const base::Callback<void(RenderFrameHost*)>& on_frame,
168 FrameTreeNode* node) {
169 on_frame.Run(node->current_frame_host());
170 return true;
173 bool ForEachPendingFrameInternal(
174 const base::Callback<void(RenderFrameHost*)>& on_frame,
175 FrameTreeNode* node) {
176 RenderFrameHost* pending_frame_host =
177 node->render_manager()->pending_frame_host();
178 if (pending_frame_host)
179 on_frame.Run(pending_frame_host);
180 return true;
183 void SendToAllFramesInternal(IPC::Message* message, RenderFrameHost* rfh) {
184 IPC::Message* message_copy = new IPC::Message(*message);
185 message_copy->set_routing_id(rfh->GetRoutingID());
186 rfh->Send(message_copy);
189 void AddRenderWidgetHostViewToSet(std::set<RenderWidgetHostView*>* set,
190 RenderFrameHost* rfh) {
191 RenderWidgetHostView* rwhv = static_cast<RenderFrameHostImpl*>(rfh)
192 ->frame_tree_node()
193 ->render_manager()
194 ->GetRenderWidgetHostView();
195 set->insert(rwhv);
198 void SetAccessibilityModeOnFrame(AccessibilityMode mode,
199 RenderFrameHost* frame_host) {
200 static_cast<RenderFrameHostImpl*>(frame_host)->SetAccessibilityMode(mode);
203 // Enable sudden termination for the current RenderFrameHost of
204 // |frame_tree_node| if the ID of its SiteInstance is |site_instance_id|. Used
205 // with FrameTree::ForEach.
206 bool EnableSuddenTermination(int32 site_instance_id,
207 FrameTreeNode* frame_tree_node) {
208 if (frame_tree_node->current_frame_host()->GetSiteInstance()->GetId()
209 == site_instance_id) {
210 frame_tree_node->current_frame_host()
211 ->set_override_sudden_termination_status(true);
213 return true;
216 // Returns false and sets |sudden_termination_allowed| to false if sudden
217 // termination is not allowed for the current RenderFrameHost of
218 // |frame_tree_node|. Used with FrameTree::ForEach.
219 bool SuddenTerminationAllowed(bool* sudden_termination_allowed,
220 FrameTreeNode* frame_tree_node) {
221 if (frame_tree_node->current_frame_host()->SuddenTerminationAllowed())
222 return true;
223 *sudden_termination_allowed = false;
224 return false;
227 } // namespace
229 WebContents* WebContents::Create(const WebContents::CreateParams& params) {
230 return WebContentsImpl::CreateWithOpener(
231 params, static_cast<WebContentsImpl*>(params.opener));
234 WebContents* WebContents::CreateWithSessionStorage(
235 const WebContents::CreateParams& params,
236 const SessionStorageNamespaceMap& session_storage_namespace_map) {
237 WebContentsImpl* new_contents = new WebContentsImpl(
238 params.browser_context, NULL);
240 for (SessionStorageNamespaceMap::const_iterator it =
241 session_storage_namespace_map.begin();
242 it != session_storage_namespace_map.end();
243 ++it) {
244 new_contents->GetController()
245 .SetSessionStorageNamespace(it->first, it->second.get());
248 new_contents->Init(params);
249 return new_contents;
252 void WebContentsImpl::FriendZone::AddCreatedCallbackForTesting(
253 const CreatedCallback& callback) {
254 g_created_callbacks.Get().push_back(callback);
257 void WebContentsImpl::FriendZone::RemoveCreatedCallbackForTesting(
258 const CreatedCallback& callback) {
259 for (size_t i = 0; i < g_created_callbacks.Get().size(); ++i) {
260 if (g_created_callbacks.Get().at(i).Equals(callback)) {
261 g_created_callbacks.Get().erase(g_created_callbacks.Get().begin() + i);
262 return;
267 WebContents* WebContents::FromRenderViewHost(const RenderViewHost* rvh) {
268 return rvh->GetDelegate()->GetAsWebContents();
271 WebContents* WebContents::FromRenderFrameHost(RenderFrameHost* rfh) {
272 RenderFrameHostImpl* rfh_impl = static_cast<RenderFrameHostImpl*>(rfh);
273 if (!rfh_impl)
274 return NULL;
275 return rfh_impl->delegate()->GetAsWebContents();
278 // WebContentsImpl::DestructionObserver ----------------------------------------
280 class WebContentsImpl::DestructionObserver : public WebContentsObserver {
281 public:
282 DestructionObserver(WebContentsImpl* owner, WebContents* watched_contents)
283 : WebContentsObserver(watched_contents),
284 owner_(owner) {
287 // WebContentsObserver:
288 void WebContentsDestroyed() override {
289 owner_->OnWebContentsDestroyed(
290 static_cast<WebContentsImpl*>(web_contents()));
293 private:
294 WebContentsImpl* owner_;
296 DISALLOW_COPY_AND_ASSIGN(DestructionObserver);
299 WebContentsImpl::ColorChooserInfo::ColorChooserInfo(int render_process_id,
300 int render_frame_id,
301 ColorChooser* chooser,
302 int identifier)
303 : render_process_id(render_process_id),
304 render_frame_id(render_frame_id),
305 chooser(chooser),
306 identifier(identifier) {
309 WebContentsImpl::ColorChooserInfo::~ColorChooserInfo() {
312 // WebContentsImpl -------------------------------------------------------------
314 WebContentsImpl::WebContentsImpl(BrowserContext* browser_context,
315 WebContentsImpl* opener)
316 : delegate_(NULL),
317 controller_(this, browser_context),
318 render_view_host_delegate_view_(NULL),
319 opener_(opener),
320 created_with_opener_(!!opener),
321 #if defined(OS_WIN)
322 accessible_parent_(NULL),
323 #endif
324 frame_tree_(new NavigatorImpl(&controller_, this),
325 this,
326 this,
327 this,
328 this),
329 is_loading_(false),
330 is_load_to_different_document_(false),
331 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING),
332 crashed_error_code_(0),
333 waiting_for_response_(false),
334 load_state_(net::LOAD_STATE_IDLE, base::string16()),
335 loading_total_progress_(0.0),
336 loading_frames_in_progress_(0),
337 upload_size_(0),
338 upload_position_(0),
339 displayed_insecure_content_(false),
340 has_accessed_initial_document_(false),
341 capturer_count_(0),
342 should_normally_be_visible_(true),
343 is_being_destroyed_(false),
344 notify_disconnection_(false),
345 dialog_manager_(NULL),
346 is_showing_before_unload_dialog_(false),
347 last_active_time_(base::TimeTicks::Now()),
348 closed_by_user_gesture_(false),
349 minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)),
350 maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)),
351 render_view_message_source_(NULL),
352 render_frame_message_source_(NULL),
353 fullscreen_widget_routing_id_(MSG_ROUTING_NONE),
354 fullscreen_widget_had_focus_at_shutdown_(false),
355 is_subframe_(false),
356 force_disable_overscroll_content_(false),
357 last_dialog_suppressed_(false),
358 geolocation_service_context_(new GeolocationServiceContext()),
359 accessibility_mode_(
360 BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()),
361 audio_stream_monitor_(this),
362 virtual_keyboard_requested_(false),
363 loading_weak_factory_(this) {
364 frame_tree_.SetFrameRemoveListener(
365 base::Bind(&WebContentsImpl::OnFrameRemoved,
366 base::Unretained(this)));
367 #if defined(ENABLE_BROWSER_CDMS)
368 media_web_contents_observer_.reset(new MediaWebContentsObserver(this));
369 #endif
372 WebContentsImpl::~WebContentsImpl() {
373 is_being_destroyed_ = true;
375 // Delete all RFH pending shutdown, which will lead the corresponding RVH to
376 // shutdown and be deleted as well.
377 frame_tree_.ForEach(
378 base::Bind(&RenderFrameHostManager::ClearRFHsPendingShutdown));
380 ClearAllPowerSaveBlockers();
382 for (std::set<RenderWidgetHostImpl*>::iterator iter =
383 created_widgets_.begin(); iter != created_widgets_.end(); ++iter) {
384 (*iter)->DetachDelegate();
386 created_widgets_.clear();
388 // Clear out any JavaScript state.
389 if (dialog_manager_)
390 dialog_manager_->WebContentsDestroyed(this);
392 if (color_chooser_info_.get())
393 color_chooser_info_->chooser->End();
395 NotifyDisconnected();
397 // Notify any observer that have a reference on this WebContents.
398 NotificationService::current()->Notify(
399 NOTIFICATION_WEB_CONTENTS_DESTROYED,
400 Source<WebContents>(this),
401 NotificationService::NoDetails());
403 // Destroy all frame tree nodes except for the root; this notifies observers.
404 frame_tree_.ResetForMainFrameSwap();
405 GetRenderManager()->ResetProxyHosts();
407 // Manually call the observer methods for the root frame tree node.
408 RenderFrameHostManager* root = GetRenderManager();
409 if (root->pending_frame_host()) {
410 FOR_EACH_OBSERVER(WebContentsObserver,
411 observers_,
412 RenderFrameDeleted(root->pending_frame_host()));
414 FOR_EACH_OBSERVER(WebContentsObserver,
415 observers_,
416 RenderFrameDeleted(root->current_frame_host()));
418 if (root->pending_render_view_host()) {
419 FOR_EACH_OBSERVER(WebContentsObserver,
420 observers_,
421 RenderViewDeleted(root->pending_render_view_host()));
424 FOR_EACH_OBSERVER(WebContentsObserver,
425 observers_,
426 RenderViewDeleted(root->current_host()));
428 FOR_EACH_OBSERVER(WebContentsObserver,
429 observers_,
430 WebContentsDestroyed());
432 FOR_EACH_OBSERVER(WebContentsObserver,
433 observers_,
434 ResetWebContents());
436 SetDelegate(NULL);
438 STLDeleteContainerPairSecondPointers(destruction_observers_.begin(),
439 destruction_observers_.end());
442 WebContentsImpl* WebContentsImpl::CreateWithOpener(
443 const WebContents::CreateParams& params,
444 WebContentsImpl* opener) {
445 TRACE_EVENT0("browser", "WebContentsImpl::CreateWithOpener");
446 WebContentsImpl* new_contents = new WebContentsImpl(
447 params.browser_context, params.opener_suppressed ? NULL : opener);
449 if (params.guest_delegate) {
450 // This makes |new_contents| act as a guest.
451 // For more info, see comment above class BrowserPluginGuest.
452 BrowserPluginGuest::Create(new_contents, params.guest_delegate);
453 // We are instantiating a WebContents for browser plugin. Set its subframe
454 // bit to true.
455 new_contents->is_subframe_ = true;
457 new_contents->Init(params);
458 return new_contents;
461 // static
462 std::vector<WebContentsImpl*> WebContentsImpl::GetAllWebContents() {
463 std::vector<WebContentsImpl*> result;
464 scoped_ptr<RenderWidgetHostIterator> widgets(
465 RenderWidgetHostImpl::GetRenderWidgetHosts());
466 std::set<WebContentsImpl*> web_contents_set;
467 while (RenderWidgetHost* rwh = widgets->GetNextHost()) {
468 if (!rwh->IsRenderView())
469 continue;
470 RenderViewHost* rvh = RenderViewHost::From(rwh);
471 if (!rvh)
472 continue;
473 WebContents* web_contents = WebContents::FromRenderViewHost(rvh);
474 if (!web_contents)
475 continue;
476 WebContentsImpl* wci = static_cast<WebContentsImpl*>(web_contents);
477 if (web_contents_set.find(wci) == web_contents_set.end()) {
478 web_contents_set.insert(wci);
479 result.push_back(wci);
482 return result;
485 RenderFrameHostManager* WebContentsImpl::GetRenderManagerForTesting() {
486 return GetRenderManager();
489 bool WebContentsImpl::OnMessageReceived(RenderViewHost* render_view_host,
490 const IPC::Message& message) {
491 return OnMessageReceived(render_view_host, NULL, message);
494 bool WebContentsImpl::OnMessageReceived(RenderViewHost* render_view_host,
495 RenderFrameHost* render_frame_host,
496 const IPC::Message& message) {
497 DCHECK(render_view_host || render_frame_host);
498 if (GetWebUI() &&
499 static_cast<WebUIImpl*>(GetWebUI())->OnMessageReceived(message)) {
500 return true;
503 ObserverListBase<WebContentsObserver>::Iterator it(observers_);
504 WebContentsObserver* observer;
505 if (render_frame_host) {
506 while ((observer = it.GetNext()) != NULL)
507 if (observer->OnMessageReceived(message, render_frame_host))
508 return true;
509 } else {
510 while ((observer = it.GetNext()) != NULL)
511 if (observer->OnMessageReceived(message))
512 return true;
515 // Message handlers should be aware of which
516 // RenderViewHost/RenderFrameHost sent the message, which is temporarily
517 // stored in render_(view|frame)_message_source_.
518 if (render_frame_host)
519 render_frame_message_source_ = render_frame_host;
520 else
521 render_view_message_source_ = render_view_host;
523 bool handled = true;
524 IPC_BEGIN_MESSAGE_MAP(WebContentsImpl, message)
525 IPC_MESSAGE_HANDLER(FrameHostMsg_DomOperationResponse,
526 OnDomOperationResponse)
527 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeThemeColor,
528 OnThemeColorChanged)
529 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishDocumentLoad,
530 OnDocumentLoadedInFrame)
531 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishLoad, OnDidFinishLoad)
532 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartLoading, OnDidStartLoading)
533 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading)
534 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress,
535 OnDidChangeLoadProgress)
536 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenColorChooser, OnOpenColorChooser)
537 IPC_MESSAGE_HANDLER(FrameHostMsg_EndColorChooser, OnEndColorChooser)
538 IPC_MESSAGE_HANDLER(FrameHostMsg_SetSelectedColorInColorChooser,
539 OnSetSelectedColorInColorChooser)
540 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPlayingNotification,
541 OnMediaPlayingNotification)
542 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPausedNotification,
543 OnMediaPausedNotification)
544 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFirstVisuallyNonEmptyPaint,
545 OnFirstVisuallyNonEmptyPaint)
546 IPC_MESSAGE_HANDLER(ViewHostMsg_DidLoadResourceFromMemoryCache,
547 OnDidLoadResourceFromMemoryCache)
548 IPC_MESSAGE_HANDLER(ViewHostMsg_DidDisplayInsecureContent,
549 OnDidDisplayInsecureContent)
550 IPC_MESSAGE_HANDLER(ViewHostMsg_DidRunInsecureContent,
551 OnDidRunInsecureContent)
552 IPC_MESSAGE_HANDLER(ViewHostMsg_GoToEntryAtOffset, OnGoToEntryAtOffset)
553 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateZoomLimits, OnUpdateZoomLimits)
554 IPC_MESSAGE_HANDLER(ViewHostMsg_EnumerateDirectory, OnEnumerateDirectory)
555 IPC_MESSAGE_HANDLER(ViewHostMsg_RegisterProtocolHandler,
556 OnRegisterProtocolHandler)
557 IPC_MESSAGE_HANDLER(ViewHostMsg_UnregisterProtocolHandler,
558 OnUnregisterProtocolHandler)
559 IPC_MESSAGE_HANDLER(ViewHostMsg_Find_Reply, OnFindReply)
560 IPC_MESSAGE_HANDLER(ViewHostMsg_AppCacheAccessed, OnAppCacheAccessed)
561 IPC_MESSAGE_HANDLER(ViewHostMsg_WebUISend, OnWebUISend)
562 #if defined(ENABLE_PLUGINS)
563 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung, OnPepperPluginHung)
564 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed, OnPluginCrashed)
565 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission,
566 OnRequestPpapiBrokerPermission)
567 IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_Attach,
568 OnBrowserPluginMessage(render_frame_host,
569 message))
570 #endif
571 IPC_MESSAGE_HANDLER(ImageHostMsg_DidDownloadImage, OnDidDownloadImage)
572 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateFaviconURL, OnUpdateFaviconURL)
573 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowValidationMessage,
574 OnShowValidationMessage)
575 IPC_MESSAGE_HANDLER(ViewHostMsg_HideValidationMessage,
576 OnHideValidationMessage)
577 IPC_MESSAGE_HANDLER(ViewHostMsg_MoveValidationMessage,
578 OnMoveValidationMessage)
579 #if defined(OS_ANDROID)
580 IPC_MESSAGE_HANDLER(ViewHostMsg_FindMatchRects_Reply,
581 OnFindMatchRectsReply)
582 IPC_MESSAGE_HANDLER(ViewHostMsg_OpenDateTimeDialog,
583 OnOpenDateTimeDialog)
584 #endif
585 IPC_MESSAGE_UNHANDLED(handled = false)
586 IPC_END_MESSAGE_MAP()
587 render_view_message_source_ = NULL;
588 render_frame_message_source_ = NULL;
590 return handled;
593 bool WebContentsImpl::HasValidFrameSource() {
594 if (!render_frame_message_source_) {
595 DCHECK(render_view_message_source_);
596 RecordAction(base::UserMetricsAction("BadMessageTerminate_WC"));
597 GetRenderProcessHost()->ReceivedBadMessage();
598 return false;
601 return true;
604 void WebContentsImpl::RunFileChooser(
605 RenderViewHost* render_view_host,
606 const FileChooserParams& params) {
607 if (delegate_)
608 delegate_->RunFileChooser(this, params);
611 NavigationControllerImpl& WebContentsImpl::GetController() {
612 return controller_;
615 const NavigationControllerImpl& WebContentsImpl::GetController() const {
616 return controller_;
619 BrowserContext* WebContentsImpl::GetBrowserContext() const {
620 return controller_.GetBrowserContext();
623 const GURL& WebContentsImpl::GetURL() const {
624 // We may not have a navigation entry yet.
625 NavigationEntry* entry = controller_.GetVisibleEntry();
626 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
629 const GURL& WebContentsImpl::GetVisibleURL() const {
630 // We may not have a navigation entry yet.
631 NavigationEntry* entry = controller_.GetVisibleEntry();
632 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
635 const GURL& WebContentsImpl::GetLastCommittedURL() const {
636 // We may not have a navigation entry yet.
637 NavigationEntry* entry = controller_.GetLastCommittedEntry();
638 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
641 WebContentsDelegate* WebContentsImpl::GetDelegate() {
642 return delegate_;
645 void WebContentsImpl::SetDelegate(WebContentsDelegate* delegate) {
646 // TODO(cbentzel): remove this debugging code?
647 if (delegate == delegate_)
648 return;
649 if (delegate_)
650 delegate_->Detach(this);
651 delegate_ = delegate;
652 if (delegate_) {
653 delegate_->Attach(this);
654 // Ensure the visible RVH reflects the new delegate's preferences.
655 if (view_)
656 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
660 RenderProcessHost* WebContentsImpl::GetRenderProcessHost() const {
661 RenderViewHostImpl* host = GetRenderManager()->current_host();
662 return host ? host->GetProcess() : NULL;
665 RenderFrameHostImpl* WebContentsImpl::GetMainFrame() {
666 return frame_tree_.root()->current_frame_host();
669 RenderFrameHost* WebContentsImpl::GetFocusedFrame() {
670 if (!frame_tree_.GetFocusedFrame())
671 return NULL;
672 return frame_tree_.GetFocusedFrame()->current_frame_host();
675 void WebContentsImpl::ForEachFrame(
676 const base::Callback<void(RenderFrameHost*)>& on_frame) {
677 frame_tree_.ForEach(base::Bind(&ForEachFrameInternal, on_frame));
680 void WebContentsImpl::SendToAllFrames(IPC::Message* message) {
681 ForEachFrame(base::Bind(&SendToAllFramesInternal, message));
682 delete message;
685 RenderViewHost* WebContentsImpl::GetRenderViewHost() const {
686 return GetRenderManager()->current_host();
689 int WebContentsImpl::GetRoutingID() const {
690 if (!GetRenderViewHost())
691 return MSG_ROUTING_NONE;
693 return GetRenderViewHost()->GetRoutingID();
696 int WebContentsImpl::GetFullscreenWidgetRoutingID() const {
697 return fullscreen_widget_routing_id_;
700 RenderWidgetHostView* WebContentsImpl::GetRenderWidgetHostView() const {
701 return GetRenderManager()->GetRenderWidgetHostView();
704 RenderWidgetHostView* WebContentsImpl::GetFullscreenRenderWidgetHostView()
705 const {
706 RenderWidgetHost* const widget_host =
707 RenderWidgetHostImpl::FromID(GetRenderProcessHost()->GetID(),
708 GetFullscreenWidgetRoutingID());
709 return widget_host ? widget_host->GetView() : NULL;
712 WebContentsView* WebContentsImpl::GetView() const {
713 return view_.get();
716 void WebContentsImpl::SetAccessibilityMode(AccessibilityMode mode) {
717 if (mode == accessibility_mode_)
718 return;
720 accessibility_mode_ = mode;
721 frame_tree_.ForEach(
722 base::Bind(&ForEachFrameInternal,
723 base::Bind(&SetAccessibilityModeOnFrame, mode)));
724 frame_tree_.ForEach(
725 base::Bind(&ForEachPendingFrameInternal,
726 base::Bind(&SetAccessibilityModeOnFrame, mode)));
729 void WebContentsImpl::AddAccessibilityMode(AccessibilityMode mode) {
730 SetAccessibilityMode(AddAccessibilityModeTo(accessibility_mode_, mode));
733 void WebContentsImpl::RemoveAccessibilityMode(AccessibilityMode mode) {
734 SetAccessibilityMode(RemoveAccessibilityModeFrom(accessibility_mode_, mode));
737 void WebContentsImpl::ClearNavigationTransitionData() {
738 FrameTreeNode* node = frame_tree_.root();
739 node->render_manager()->ClearNavigationTransitionData();
742 WebUI* WebContentsImpl::CreateWebUI(const GURL& url) {
743 WebUIImpl* web_ui = new WebUIImpl(this);
744 WebUIController* controller = WebUIControllerFactoryRegistry::GetInstance()->
745 CreateWebUIControllerForURL(web_ui, url);
746 if (controller) {
747 web_ui->AddMessageHandler(new GenericHandler());
748 web_ui->SetController(controller);
749 return web_ui;
752 delete web_ui;
753 return NULL;
756 WebUI* WebContentsImpl::GetWebUI() const {
757 return GetRenderManager()->web_ui() ? GetRenderManager()->web_ui()
758 : GetRenderManager()->pending_web_ui();
761 WebUI* WebContentsImpl::GetCommittedWebUI() const {
762 return GetRenderManager()->web_ui();
765 void WebContentsImpl::SetUserAgentOverride(const std::string& override) {
766 if (GetUserAgentOverride() == override)
767 return;
769 renderer_preferences_.user_agent_override = override;
771 // Send the new override string to the renderer.
772 RenderViewHost* host = GetRenderViewHost();
773 if (host)
774 host->SyncRendererPrefs();
776 // Reload the page if a load is currently in progress to avoid having
777 // different parts of the page loaded using different user agents.
778 NavigationEntry* entry = controller_.GetVisibleEntry();
779 if (is_loading_ && entry != NULL && entry->GetIsOverridingUserAgent())
780 controller_.ReloadIgnoringCache(true);
782 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
783 UserAgentOverrideSet(override));
786 const std::string& WebContentsImpl::GetUserAgentOverride() const {
787 return renderer_preferences_.user_agent_override;
790 void WebContentsImpl::EnableTreeOnlyAccessibilityMode() {
791 AddAccessibilityMode(AccessibilityModeTreeOnly);
794 bool WebContentsImpl::IsTreeOnlyAccessibilityModeForTesting() const {
795 return accessibility_mode_ == AccessibilityModeTreeOnly;
798 bool WebContentsImpl::IsFullAccessibilityModeForTesting() const {
799 return accessibility_mode_ == AccessibilityModeComplete;
802 #if defined(OS_WIN)
803 void WebContentsImpl::SetParentNativeViewAccessible(
804 gfx::NativeViewAccessible accessible_parent) {
805 accessible_parent_ = accessible_parent;
806 RenderFrameHostImpl* rfh = GetMainFrame();
807 if (rfh)
808 rfh->SetParentNativeViewAccessible(accessible_parent);
810 #endif
812 const base::string16& WebContentsImpl::GetTitle() const {
813 // Transient entries take precedence. They are used for interstitial pages
814 // that are shown on top of existing pages.
815 NavigationEntry* entry = controller_.GetTransientEntry();
816 std::string accept_languages =
817 GetContentClient()->browser()->GetAcceptLangs(
818 GetBrowserContext());
819 if (entry) {
820 return entry->GetTitleForDisplay(accept_languages);
822 WebUI* our_web_ui = GetRenderManager()->pending_web_ui() ?
823 GetRenderManager()->pending_web_ui() : GetRenderManager()->web_ui();
824 if (our_web_ui) {
825 // Don't override the title in view source mode.
826 entry = controller_.GetVisibleEntry();
827 if (!(entry && entry->IsViewSourceMode())) {
828 // Give the Web UI the chance to override our title.
829 const base::string16& title = our_web_ui->GetOverriddenTitle();
830 if (!title.empty())
831 return title;
835 // We use the title for the last committed entry rather than a pending
836 // navigation entry. For example, when the user types in a URL, we want to
837 // keep the old page's title until the new load has committed and we get a new
838 // title.
839 entry = controller_.GetLastCommittedEntry();
841 // We make an exception for initial navigations.
842 if (controller_.IsInitialNavigation()) {
843 // We only want to use the title from the visible entry in one of two cases:
844 // 1. There's already a committed entry for an initial navigation, in which
845 // case we are doing a history navigation in a new tab (e.g., Ctrl+Back).
846 // 2. The pending entry has been explicitly assigned a title to display.
848 // If there's no last committed entry and no assigned title, we should fall
849 // back to |page_title_when_no_navigation_entry_| rather than showing the
850 // URL.
851 if (entry ||
852 (controller_.GetVisibleEntry() &&
853 !controller_.GetVisibleEntry()->GetTitle().empty())) {
854 entry = controller_.GetVisibleEntry();
858 if (entry) {
859 return entry->GetTitleForDisplay(accept_languages);
862 // |page_title_when_no_navigation_entry_| is finally used
863 // if no title cannot be retrieved.
864 return page_title_when_no_navigation_entry_;
867 int32 WebContentsImpl::GetMaxPageID() {
868 return GetMaxPageIDForSiteInstance(GetSiteInstance());
871 int32 WebContentsImpl::GetMaxPageIDForSiteInstance(
872 SiteInstance* site_instance) {
873 if (max_page_ids_.find(site_instance->GetId()) == max_page_ids_.end())
874 max_page_ids_[site_instance->GetId()] = -1;
876 return max_page_ids_[site_instance->GetId()];
879 void WebContentsImpl::UpdateMaxPageID(int32 page_id) {
880 UpdateMaxPageIDForSiteInstance(GetSiteInstance(), page_id);
883 void WebContentsImpl::UpdateMaxPageIDForSiteInstance(
884 SiteInstance* site_instance, int32 page_id) {
885 if (GetMaxPageIDForSiteInstance(site_instance) < page_id)
886 max_page_ids_[site_instance->GetId()] = page_id;
889 void WebContentsImpl::CopyMaxPageIDsFrom(WebContents* web_contents) {
890 WebContentsImpl* contents = static_cast<WebContentsImpl*>(web_contents);
891 max_page_ids_ = contents->max_page_ids_;
894 SiteInstanceImpl* WebContentsImpl::GetSiteInstance() const {
895 return GetRenderManager()->current_host()->GetSiteInstance();
898 SiteInstanceImpl* WebContentsImpl::GetPendingSiteInstance() const {
899 RenderViewHostImpl* dest_rvh =
900 GetRenderManager()->pending_render_view_host() ?
901 GetRenderManager()->pending_render_view_host() :
902 GetRenderManager()->current_host();
903 return dest_rvh->GetSiteInstance();
906 bool WebContentsImpl::IsLoading() const {
907 return is_loading_;
910 bool WebContentsImpl::IsLoadingToDifferentDocument() const {
911 return is_loading_ && is_load_to_different_document_;
914 bool WebContentsImpl::IsWaitingForResponse() const {
915 return waiting_for_response_ && is_load_to_different_document_;
918 const net::LoadStateWithParam& WebContentsImpl::GetLoadState() const {
919 return load_state_;
922 const base::string16& WebContentsImpl::GetLoadStateHost() const {
923 return load_state_host_;
926 uint64 WebContentsImpl::GetUploadSize() const {
927 return upload_size_;
930 uint64 WebContentsImpl::GetUploadPosition() const {
931 return upload_position_;
934 std::set<GURL> WebContentsImpl::GetSitesInTab() const {
935 std::set<GURL> sites;
936 frame_tree_.ForEach(base::Bind(&CollectSites,
937 base::Unretained(GetBrowserContext()),
938 base::Unretained(&sites)));
939 return sites;
942 const std::string& WebContentsImpl::GetEncoding() const {
943 return canonical_encoding_;
946 bool WebContentsImpl::DisplayedInsecureContent() const {
947 return displayed_insecure_content_;
950 void WebContentsImpl::IncrementCapturerCount(const gfx::Size& capture_size) {
951 DCHECK(!is_being_destroyed_);
952 ++capturer_count_;
953 DVLOG(1) << "There are now " << capturer_count_
954 << " capturing(s) of WebContentsImpl@" << this;
956 // Note: This provides a hint to upstream code to size the views optimally
957 // for quality (e.g., to avoid scaling).
958 if (!capture_size.IsEmpty() && preferred_size_for_capture_.IsEmpty()) {
959 preferred_size_for_capture_ = capture_size;
960 OnPreferredSizeChanged(preferred_size_);
963 // Ensure that all views are un-occluded before capture begins.
964 WasUnOccluded();
967 void WebContentsImpl::DecrementCapturerCount() {
968 --capturer_count_;
969 DVLOG(1) << "There are now " << capturer_count_
970 << " capturing(s) of WebContentsImpl@" << this;
971 DCHECK_LE(0, capturer_count_);
973 if (is_being_destroyed_)
974 return;
976 if (capturer_count_ == 0) {
977 const gfx::Size old_size = preferred_size_for_capture_;
978 preferred_size_for_capture_ = gfx::Size();
979 OnPreferredSizeChanged(old_size);
982 if (IsHidden()) {
983 DVLOG(1) << "Executing delayed WasHidden().";
984 WasHidden();
988 int WebContentsImpl::GetCapturerCount() const {
989 return capturer_count_;
992 bool WebContentsImpl::IsAudioMuted() const {
993 return audio_muter_.get() && audio_muter_->is_muting();
996 void WebContentsImpl::SetAudioMuted(bool mute) {
997 DVLOG(1) << "SetAudioMuted(mute=" << mute << "), was " << IsAudioMuted()
998 << " for WebContentsImpl@" << this;
1000 if (mute == IsAudioMuted())
1001 return;
1003 if (mute) {
1004 if (!audio_muter_)
1005 audio_muter_.reset(new WebContentsAudioMuter(this));
1006 audio_muter_->StartMuting();
1007 } else {
1008 DCHECK(audio_muter_);
1009 audio_muter_->StopMuting();
1012 // Notification for UI updates in response to the changed muting state.
1013 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
1016 bool WebContentsImpl::IsCrashed() const {
1017 return (crashed_status_ == base::TERMINATION_STATUS_PROCESS_CRASHED ||
1018 crashed_status_ == base::TERMINATION_STATUS_ABNORMAL_TERMINATION ||
1019 crashed_status_ == base::TERMINATION_STATUS_PROCESS_WAS_KILLED);
1022 void WebContentsImpl::SetIsCrashed(base::TerminationStatus status,
1023 int error_code) {
1024 if (status == crashed_status_)
1025 return;
1027 crashed_status_ = status;
1028 crashed_error_code_ = error_code;
1029 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
1032 base::TerminationStatus WebContentsImpl::GetCrashedStatus() const {
1033 return crashed_status_;
1036 bool WebContentsImpl::IsBeingDestroyed() const {
1037 return is_being_destroyed_;
1040 void WebContentsImpl::NotifyNavigationStateChanged(
1041 InvalidateTypes changed_flags) {
1042 // Create and release the audio power save blocker depending on whether the
1043 // tab is actively producing audio or not.
1044 if ((changed_flags & INVALIDATE_TYPE_TAB) &&
1045 AudioStreamMonitor::monitoring_available()) {
1046 if (WasRecentlyAudible()) {
1047 if (!audio_power_save_blocker_)
1048 CreateAudioPowerSaveBlocker();
1049 } else {
1050 audio_power_save_blocker_.reset();
1054 if (delegate_)
1055 delegate_->NavigationStateChanged(this, changed_flags);
1058 base::TimeTicks WebContentsImpl::GetLastActiveTime() const {
1059 return last_active_time_;
1062 void WebContentsImpl::WasShown() {
1063 controller_.SetActive(true);
1065 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1066 if (view) {
1067 view->Show();
1068 #if defined(OS_MACOSX)
1069 view->SetActive(true);
1070 #endif
1074 last_active_time_ = base::TimeTicks::Now();
1076 // The resize rect might have changed while this was inactive -- send the new
1077 // one to make sure it's up to date.
1078 RenderViewHostImpl* rvh =
1079 static_cast<RenderViewHostImpl*>(GetRenderViewHost());
1080 if (rvh) {
1081 rvh->ResizeRectChanged(GetRootWindowResizerRect());
1084 // Restore power save blocker if there are active video players running.
1085 if (!active_video_players_.empty() && !video_power_save_blocker_)
1086 CreateVideoPowerSaveBlocker();
1088 FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasShown());
1090 should_normally_be_visible_ = true;
1093 void WebContentsImpl::WasHidden() {
1094 // If there are entities capturing screenshots or video (e.g., mirroring),
1095 // don't activate the "disable rendering" optimization.
1096 if (capturer_count_ == 0) {
1097 // |GetRenderViewHost()| can be NULL if the user middle clicks a link to
1098 // open a tab in the background, then closes the tab before selecting it.
1099 // This is because closing the tab calls WebContentsImpl::Destroy(), which
1100 // removes the |GetRenderViewHost()|; then when we actually destroy the
1101 // window, OnWindowPosChanged() notices and calls WasHidden() (which
1102 // calls us).
1103 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1104 if (view)
1105 view->Hide();
1108 // Release any video power save blockers held as video is not visible.
1109 video_power_save_blocker_.reset();
1112 FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasHidden());
1114 should_normally_be_visible_ = false;
1117 void WebContentsImpl::WasOccluded() {
1118 if (capturer_count_ > 0)
1119 return;
1121 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1122 if (view)
1123 view->WasOccluded();
1127 void WebContentsImpl::WasUnOccluded() {
1128 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1129 if (view)
1130 view->WasUnOccluded();
1134 bool WebContentsImpl::NeedToFireBeforeUnload() {
1135 bool sudden_termination_allowed = true;
1136 frame_tree_.ForEach(base::Bind(
1137 &SuddenTerminationAllowed, &sudden_termination_allowed));
1138 // TODO(creis): Should we fire even for interstitial pages?
1139 return WillNotifyDisconnection() &&
1140 !ShowingInterstitialPage() &&
1141 !sudden_termination_allowed;
1144 void WebContentsImpl::DispatchBeforeUnload(bool for_cross_site_transition) {
1145 GetMainFrame()->DispatchBeforeUnload(for_cross_site_transition);
1148 void WebContentsImpl::Stop() {
1149 GetRenderManager()->Stop();
1150 FOR_EACH_OBSERVER(WebContentsObserver, observers_, NavigationStopped());
1153 WebContents* WebContentsImpl::Clone() {
1154 // We use our current SiteInstance since the cloned entry will use it anyway.
1155 // We pass our own opener so that the cloned page can access it if it was
1156 // before.
1157 CreateParams create_params(GetBrowserContext(), GetSiteInstance());
1158 create_params.initial_size = GetContainerBounds().size();
1159 WebContentsImpl* tc = CreateWithOpener(create_params, opener_);
1160 tc->GetController().CopyStateFrom(controller_);
1161 FOR_EACH_OBSERVER(WebContentsObserver,
1162 observers_,
1163 DidCloneToNewWebContents(this, tc));
1164 return tc;
1167 void WebContentsImpl::Observe(int type,
1168 const NotificationSource& source,
1169 const NotificationDetails& details) {
1170 switch (type) {
1171 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: {
1172 RenderWidgetHost* host = Source<RenderWidgetHost>(source).ptr();
1173 RenderWidgetHostView* view = host->GetView();
1174 if (view == GetFullscreenRenderWidgetHostView()) {
1175 // We cannot just call view_->RestoreFocus() here. On some platforms,
1176 // attempting to focus the currently-invisible WebContentsView will be
1177 // flat-out ignored. Therefore, this boolean is used to track whether
1178 // we will request focus after the fullscreen widget has been
1179 // destroyed.
1180 fullscreen_widget_had_focus_at_shutdown_ = (view && view->HasFocus());
1181 } else {
1182 for (PendingWidgetViews::iterator i = pending_widget_views_.begin();
1183 i != pending_widget_views_.end(); ++i) {
1184 if (host->GetView() == i->second) {
1185 pending_widget_views_.erase(i);
1186 break;
1190 break;
1192 default:
1193 NOTREACHED();
1197 WebContents* WebContentsImpl::GetWebContents() {
1198 return this;
1201 void WebContentsImpl::Init(const WebContents::CreateParams& params) {
1202 // This is set before initializing the render manager since
1203 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
1204 // it should be hidden.
1205 should_normally_be_visible_ = !params.initially_hidden;
1207 // Either both routing ids can be given, or neither can be.
1208 DCHECK((params.routing_id == MSG_ROUTING_NONE &&
1209 params.main_frame_routing_id == MSG_ROUTING_NONE) ||
1210 (params.routing_id != MSG_ROUTING_NONE &&
1211 params.main_frame_routing_id != MSG_ROUTING_NONE));
1212 GetRenderManager()->Init(
1213 params.browser_context, params.site_instance, params.routing_id,
1214 params.main_frame_routing_id);
1216 WebContentsViewDelegate* delegate =
1217 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
1219 if (browser_plugin_guest_) {
1220 scoped_ptr<WebContentsView> platform_view(CreateWebContentsView(
1221 this, delegate, &render_view_host_delegate_view_));
1223 WebContentsViewGuest* rv = new WebContentsViewGuest(
1224 this, browser_plugin_guest_.get(), platform_view.Pass(),
1225 render_view_host_delegate_view_);
1226 render_view_host_delegate_view_ = rv;
1227 view_.reset(rv);
1228 } else {
1229 // Regular WebContentsView.
1230 view_.reset(CreateWebContentsView(
1231 this, delegate, &render_view_host_delegate_view_));
1233 CHECK(render_view_host_delegate_view_);
1234 CHECK(view_.get());
1236 gfx::Size initial_size = params.initial_size;
1237 view_->CreateView(initial_size, params.context);
1239 // Listen for whether our opener gets destroyed.
1240 if (opener_)
1241 AddDestructionObserver(opener_);
1243 #if defined(ENABLE_PLUGINS)
1244 plugin_content_origin_whitelist_.reset(
1245 new PluginContentOriginWhitelist(this));
1246 #endif
1248 registrar_.Add(this,
1249 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1250 NotificationService::AllBrowserContextsAndSources());
1252 screen_orientation_dispatcher_host_.reset(
1253 new ScreenOrientationDispatcherHostImpl(this));
1255 manifest_manager_host_.reset(new ManifestManagerHost(this));
1257 #if defined(OS_ANDROID)
1258 date_time_chooser_.reset(new DateTimeChooserAndroid());
1259 #endif
1261 // BrowserPluginGuest::Init needs to be called after this WebContents has
1262 // a RenderWidgetHostViewGuest. That is, |view_->CreateView| above.
1263 if (browser_plugin_guest_)
1264 browser_plugin_guest_->Init();
1266 for (size_t i = 0; i < g_created_callbacks.Get().size(); i++)
1267 g_created_callbacks.Get().at(i).Run(this);
1270 void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl* web_contents) {
1271 RemoveDestructionObserver(web_contents);
1273 // Clear the opener if it has been closed.
1274 if (web_contents == opener_) {
1275 opener_ = NULL;
1276 return;
1278 // Clear a pending contents that has been closed before being shown.
1279 for (PendingContents::iterator iter = pending_contents_.begin();
1280 iter != pending_contents_.end();
1281 ++iter) {
1282 if (iter->second != web_contents)
1283 continue;
1284 pending_contents_.erase(iter);
1285 return;
1287 NOTREACHED();
1290 void WebContentsImpl::AddDestructionObserver(WebContentsImpl* web_contents) {
1291 if (!ContainsKey(destruction_observers_, web_contents)) {
1292 destruction_observers_[web_contents] =
1293 new DestructionObserver(this, web_contents);
1297 void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl* web_contents) {
1298 DestructionObservers::iterator iter =
1299 destruction_observers_.find(web_contents);
1300 if (iter != destruction_observers_.end()) {
1301 delete destruction_observers_[web_contents];
1302 destruction_observers_.erase(iter);
1306 void WebContentsImpl::AddObserver(WebContentsObserver* observer) {
1307 observers_.AddObserver(observer);
1310 void WebContentsImpl::RemoveObserver(WebContentsObserver* observer) {
1311 observers_.RemoveObserver(observer);
1314 std::set<RenderWidgetHostView*>
1315 WebContentsImpl::GetRenderWidgetHostViewsInTree() {
1316 std::set<RenderWidgetHostView*> set;
1317 if (ShowingInterstitialPage()) {
1318 set.insert(GetRenderWidgetHostView());
1319 } else {
1320 ForEachFrame(
1321 base::Bind(&AddRenderWidgetHostViewToSet, base::Unretained(&set)));
1323 return set;
1326 void WebContentsImpl::Activate() {
1327 if (delegate_)
1328 delegate_->ActivateContents(this);
1331 void WebContentsImpl::Deactivate() {
1332 if (delegate_)
1333 delegate_->DeactivateContents(this);
1336 void WebContentsImpl::LostCapture() {
1337 if (delegate_)
1338 delegate_->LostCapture();
1341 void WebContentsImpl::RenderWidgetDeleted(
1342 RenderWidgetHostImpl* render_widget_host) {
1343 if (is_being_destroyed_) {
1344 // |created_widgets_| might have been destroyed.
1345 return;
1348 std::set<RenderWidgetHostImpl*>::iterator iter =
1349 created_widgets_.find(render_widget_host);
1350 if (iter != created_widgets_.end())
1351 created_widgets_.erase(iter);
1353 if (render_widget_host &&
1354 render_widget_host->GetRoutingID() == fullscreen_widget_routing_id_) {
1355 if (delegate_ && delegate_->EmbedsFullscreenWidget())
1356 delegate_->ExitFullscreenModeForTab(this);
1357 FOR_EACH_OBSERVER(WebContentsObserver,
1358 observers_,
1359 DidDestroyFullscreenWidget(
1360 fullscreen_widget_routing_id_));
1361 fullscreen_widget_routing_id_ = MSG_ROUTING_NONE;
1362 if (fullscreen_widget_had_focus_at_shutdown_)
1363 view_->RestoreFocus();
1367 void WebContentsImpl::RenderWidgetGotFocus(
1368 RenderWidgetHostImpl* render_widget_host) {
1369 // Notify the delegate if an embedded fullscreen widget was focused.
1370 if (delegate_ && render_widget_host &&
1371 delegate_->EmbedsFullscreenWidget() &&
1372 render_widget_host->GetView() == GetFullscreenRenderWidgetHostView())
1373 delegate_->WebContentsFocused(this);
1376 void WebContentsImpl::RenderWidgetWasResized(
1377 RenderWidgetHostImpl* render_widget_host,
1378 bool width_changed) {
1379 RenderFrameHostImpl* rfh = GetMainFrame();
1380 if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
1381 return;
1383 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1384 MainFrameWasResized(width_changed));
1387 bool WebContentsImpl::PreHandleKeyboardEvent(
1388 const NativeWebKeyboardEvent& event,
1389 bool* is_keyboard_shortcut) {
1390 return delegate_ &&
1391 delegate_->PreHandleKeyboardEvent(this, event, is_keyboard_shortcut);
1394 void WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
1395 if (browser_plugin_embedder_ &&
1396 browser_plugin_embedder_->HandleKeyboardEvent(event)) {
1397 return;
1399 if (delegate_)
1400 delegate_->HandleKeyboardEvent(this, event);
1403 bool WebContentsImpl::HandleWheelEvent(
1404 const blink::WebMouseWheelEvent& event) {
1405 #if !defined(OS_MACOSX)
1406 // On platforms other than Mac, control+mousewheel may change zoom. On Mac,
1407 // this isn't done for two reasons:
1408 // -the OS already has a gesture to do this through pinch-zoom
1409 // -if a user starts an inertial scroll, let's go, and presses control
1410 // (i.e. control+tab) then the OS's buffered scroll events will come in
1411 // with control key set which isn't what the user wants
1412 if (delegate_ && event.wheelTicksY &&
1413 (event.modifiers & blink::WebInputEvent::ControlKey) &&
1414 !event.canScroll) {
1415 delegate_->ContentsZoomChange(event.wheelTicksY > 0);
1416 return true;
1418 #endif
1419 return false;
1422 bool WebContentsImpl::PreHandleGestureEvent(
1423 const blink::WebGestureEvent& event) {
1424 return delegate_ && delegate_->PreHandleGestureEvent(this, event);
1427 void WebContentsImpl::HandleMouseDown() {
1428 if (delegate_)
1429 delegate_->HandleMouseDown();
1432 void WebContentsImpl::HandleMouseUp() {
1433 if (delegate_)
1434 delegate_->HandleMouseUp();
1437 void WebContentsImpl::HandlePointerActivate() {
1438 if (delegate_)
1439 delegate_->HandlePointerActivate();
1442 void WebContentsImpl::HandleGestureBegin() {
1443 if (delegate_)
1444 delegate_->HandleGestureBegin();
1447 void WebContentsImpl::HandleGestureEnd() {
1448 if (delegate_)
1449 delegate_->HandleGestureEnd();
1452 void WebContentsImpl::EnterFullscreenMode(const GURL& origin) {
1453 // This method is being called to enter renderer-initiated fullscreen mode.
1454 // Make sure any existing fullscreen widget is shut down first.
1455 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
1456 if (widget_view)
1457 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())->Shutdown();
1459 if (delegate_)
1460 delegate_->EnterFullscreenModeForTab(this, origin);
1462 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1463 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1466 void WebContentsImpl::ExitFullscreenMode() {
1467 // This method is being called to leave renderer-initiated fullscreen mode.
1468 // Make sure any existing fullscreen widget is shut down first.
1469 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
1470 if (widget_view)
1471 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())->Shutdown();
1473 #if defined(OS_ANDROID)
1474 ContentVideoView* video_view = ContentVideoView::GetInstance();
1475 if (video_view != NULL)
1476 video_view->OnExitFullscreen();
1477 #endif
1479 if (delegate_)
1480 delegate_->ExitFullscreenModeForTab(this);
1482 FOR_EACH_OBSERVER(WebContentsObserver,
1483 observers_,
1484 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1487 bool WebContentsImpl::IsFullscreenForCurrentTab() const {
1488 return delegate_ ? delegate_->IsFullscreenForTabOrPending(this) : false;
1491 void WebContentsImpl::RequestToLockMouse(bool user_gesture,
1492 bool last_unlocked_by_target) {
1493 if (delegate_) {
1494 delegate_->RequestToLockMouse(this, user_gesture, last_unlocked_by_target);
1495 } else {
1496 GotResponseToLockMouseRequest(false);
1500 void WebContentsImpl::LostMouseLock() {
1501 if (delegate_)
1502 delegate_->LostMouseLock();
1505 void WebContentsImpl::CreateNewWindow(
1506 int render_process_id,
1507 int route_id,
1508 int main_frame_route_id,
1509 const ViewHostMsg_CreateWindow_Params& params,
1510 SessionStorageNamespace* session_storage_namespace) {
1511 // We usually create the new window in the same BrowsingInstance (group of
1512 // script-related windows), by passing in the current SiteInstance. However,
1513 // if the opener is being suppressed (in a non-guest), we create a new
1514 // SiteInstance in its own BrowsingInstance.
1515 bool is_guest = BrowserPluginGuest::IsGuest(this);
1517 // If the opener is to be suppressed, the new window can be in any process.
1518 // Since routing ids are process specific, we must not have one passed in
1519 // as argument here.
1520 DCHECK(!params.opener_suppressed || route_id == MSG_ROUTING_NONE);
1522 scoped_refptr<SiteInstance> site_instance =
1523 params.opener_suppressed && !is_guest ?
1524 SiteInstance::CreateForURL(GetBrowserContext(), params.target_url) :
1525 GetSiteInstance();
1527 // A message to create a new window can only come from the active process for
1528 // this WebContentsImpl instance. If any other process sends the request,
1529 // it is invalid and the process must be terminated.
1530 if (GetRenderProcessHost()->GetID() != render_process_id) {
1531 RenderProcessHost* rph = RenderProcessHost::FromID(render_process_id);
1532 base::ProcessHandle process_handle = rph->GetHandle();
1533 if (process_handle != base::kNullProcessHandle) {
1534 RecordAction(
1535 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWindow"));
1536 rph->Shutdown(RESULT_CODE_KILLED, false);
1538 return;
1541 // We must assign the SessionStorageNamespace before calling Init().
1543 // http://crbug.com/142685
1544 const std::string& partition_id =
1545 GetContentClient()->browser()->
1546 GetStoragePartitionIdForSite(GetBrowserContext(),
1547 site_instance->GetSiteURL());
1548 StoragePartition* partition = BrowserContext::GetStoragePartition(
1549 GetBrowserContext(), site_instance.get());
1550 DOMStorageContextWrapper* dom_storage_context =
1551 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
1552 SessionStorageNamespaceImpl* session_storage_namespace_impl =
1553 static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
1554 CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
1556 if (delegate_ &&
1557 !delegate_->ShouldCreateWebContents(this,
1558 route_id,
1559 main_frame_route_id,
1560 params.window_container_type,
1561 params.frame_name,
1562 params.target_url,
1563 partition_id,
1564 session_storage_namespace)) {
1565 if (route_id != MSG_ROUTING_NONE &&
1566 !RenderViewHost::FromID(render_process_id, route_id)) {
1567 // If the embedder didn't create a WebContents for this route, we need to
1568 // delete the RenderView that had already been created.
1569 Send(new ViewMsg_Close(route_id));
1571 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(route_id);
1572 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(
1573 main_frame_route_id);
1574 return;
1577 // Create the new web contents. This will automatically create the new
1578 // WebContentsView. In the future, we may want to create the view separately.
1579 CreateParams create_params(GetBrowserContext(), site_instance.get());
1580 create_params.routing_id = route_id;
1581 create_params.main_frame_routing_id = main_frame_route_id;
1582 create_params.opener = this;
1583 create_params.opener_suppressed = params.opener_suppressed;
1584 if (params.disposition == NEW_BACKGROUND_TAB)
1585 create_params.initially_hidden = true;
1587 WebContentsImpl* new_contents = NULL;
1588 if (!is_guest) {
1589 create_params.context = view_->GetNativeView();
1590 create_params.initial_size = GetContainerBounds().size();
1591 new_contents = static_cast<WebContentsImpl*>(
1592 WebContents::Create(create_params));
1593 } else {
1594 new_contents = GetBrowserPluginGuest()->CreateNewGuestWindow(create_params);
1596 new_contents->GetController().SetSessionStorageNamespace(
1597 partition_id,
1598 session_storage_namespace);
1599 new_contents->RenderViewCreated(new_contents->GetRenderViewHost());
1601 // Save the window for later if we're not suppressing the opener (since it
1602 // will be shown immediately).
1603 if (!params.opener_suppressed) {
1604 if (!is_guest) {
1605 WebContentsView* new_view = new_contents->view_.get();
1607 // TODO(brettw): It seems bogus that we have to call this function on the
1608 // newly created object and give it one of its own member variables.
1609 new_view->CreateViewForWidget(new_contents->GetRenderViewHost(), false);
1611 // Save the created window associated with the route so we can show it
1612 // later.
1613 DCHECK_NE(MSG_ROUTING_NONE, route_id);
1614 pending_contents_[route_id] = new_contents;
1615 AddDestructionObserver(new_contents);
1618 if (delegate_) {
1619 delegate_->WebContentsCreated(
1620 this, params.opener_render_frame_id, params.frame_name,
1621 params.target_url, new_contents);
1624 if (params.opener_suppressed) {
1625 // When the opener is suppressed, the original renderer cannot access the
1626 // new window. As a result, we need to show and navigate the window here.
1627 bool was_blocked = false;
1628 if (delegate_) {
1629 gfx::Rect initial_rect;
1630 delegate_->AddNewContents(
1631 this, new_contents, params.disposition, initial_rect,
1632 params.user_gesture, &was_blocked);
1634 if (!was_blocked) {
1635 OpenURLParams open_params(params.target_url,
1636 Referrer(),
1637 CURRENT_TAB,
1638 ui::PAGE_TRANSITION_LINK,
1639 true /* is_renderer_initiated */);
1640 open_params.user_gesture = params.user_gesture;
1641 new_contents->OpenURL(open_params);
1646 void WebContentsImpl::CreateNewWidget(int render_process_id,
1647 int route_id,
1648 blink::WebPopupType popup_type) {
1649 CreateNewWidget(render_process_id, route_id, false, popup_type);
1652 void WebContentsImpl::CreateNewFullscreenWidget(int render_process_id,
1653 int route_id) {
1654 CreateNewWidget(render_process_id, route_id, true, blink::WebPopupTypeNone);
1657 void WebContentsImpl::CreateNewWidget(int render_process_id,
1658 int route_id,
1659 bool is_fullscreen,
1660 blink::WebPopupType popup_type) {
1661 RenderProcessHost* process = GetRenderProcessHost();
1662 // A message to create a new widget can only come from the active process for
1663 // this WebContentsImpl instance. If any other process sends the request,
1664 // it is invalid and the process must be terminated.
1665 if (process->GetID() != render_process_id) {
1666 RenderProcessHost* rph = RenderProcessHost::FromID(render_process_id);
1667 base::ProcessHandle process_handle = rph->GetHandle();
1668 if (process_handle != base::kNullProcessHandle) {
1669 RecordAction(
1670 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWidget"));
1671 rph->Shutdown(RESULT_CODE_KILLED, false);
1673 return;
1676 RenderWidgetHostImpl* widget_host =
1677 new RenderWidgetHostImpl(this, process, route_id, IsHidden());
1678 created_widgets_.insert(widget_host);
1680 RenderWidgetHostViewBase* widget_view =
1681 static_cast<RenderWidgetHostViewBase*>(
1682 view_->CreateViewForPopupWidget(widget_host));
1683 if (!widget_view)
1684 return;
1685 if (!is_fullscreen) {
1686 // Popups should not get activated.
1687 widget_view->SetPopupType(popup_type);
1689 // Save the created widget associated with the route so we can show it later.
1690 pending_widget_views_[route_id] = widget_view;
1692 #if defined(OS_MACOSX)
1693 // A RenderWidgetHostViewMac has lifetime scoped to the view. We'll retain it
1694 // to allow it to survive the trip without being hosted.
1695 base::mac::NSObjectRetain(widget_view->GetNativeView());
1696 #endif
1699 void WebContentsImpl::ShowCreatedWindow(int route_id,
1700 WindowOpenDisposition disposition,
1701 const gfx::Rect& initial_rect,
1702 bool user_gesture) {
1703 WebContentsImpl* contents = GetCreatedWindow(route_id);
1704 if (contents) {
1705 WebContentsDelegate* delegate = GetDelegate();
1706 if (delegate) {
1707 delegate->AddNewContents(
1708 this, contents, disposition, initial_rect, user_gesture, NULL);
1713 void WebContentsImpl::ShowCreatedWidget(int route_id,
1714 const gfx::Rect& initial_rect) {
1715 ShowCreatedWidget(route_id, false, initial_rect);
1718 void WebContentsImpl::ShowCreatedFullscreenWidget(int route_id) {
1719 ShowCreatedWidget(route_id, true, gfx::Rect());
1722 void WebContentsImpl::ShowCreatedWidget(int route_id,
1723 bool is_fullscreen,
1724 const gfx::Rect& initial_rect) {
1725 RenderWidgetHostViewBase* widget_host_view =
1726 static_cast<RenderWidgetHostViewBase*>(GetCreatedWidget(route_id));
1727 if (!widget_host_view)
1728 return;
1730 RenderWidgetHostView* view = NULL;
1731 BrowserPluginGuest* guest = GetBrowserPluginGuest();
1732 if (guest && guest->embedder_web_contents()) {
1733 view = guest->embedder_web_contents()->GetRenderWidgetHostView();
1734 } else {
1735 view = GetRenderWidgetHostView();
1738 if (is_fullscreen) {
1739 DCHECK_EQ(MSG_ROUTING_NONE, fullscreen_widget_routing_id_);
1740 view_->StoreFocus();
1741 fullscreen_widget_routing_id_ = route_id;
1742 if (delegate_ && delegate_->EmbedsFullscreenWidget()) {
1743 widget_host_view->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
1744 delegate_->EnterFullscreenModeForTab(this, GURL());
1745 } else {
1746 widget_host_view->InitAsFullscreen(view);
1748 FOR_EACH_OBSERVER(WebContentsObserver,
1749 observers_,
1750 DidShowFullscreenWidget(route_id));
1751 if (!widget_host_view->HasFocus())
1752 widget_host_view->Focus();
1753 } else {
1754 widget_host_view->InitAsPopup(view, initial_rect);
1757 RenderWidgetHostImpl* render_widget_host_impl =
1758 RenderWidgetHostImpl::From(widget_host_view->GetRenderWidgetHost());
1759 render_widget_host_impl->Init();
1760 // Only allow privileged mouse lock for fullscreen render widget, which is
1761 // used to implement Pepper Flash fullscreen.
1762 render_widget_host_impl->set_allow_privileged_mouse_lock(is_fullscreen);
1764 #if defined(OS_MACOSX)
1765 // A RenderWidgetHostViewMac has lifetime scoped to the view. Now that it's
1766 // properly embedded (or purposefully ignored) we can release the retain we
1767 // took in CreateNewWidget().
1768 base::mac::NSObjectRelease(widget_host_view->GetNativeView());
1769 #endif
1772 WebContentsImpl* WebContentsImpl::GetCreatedWindow(int route_id) {
1773 PendingContents::iterator iter = pending_contents_.find(route_id);
1775 // Certain systems can block the creation of new windows. If we didn't succeed
1776 // in creating one, just return NULL.
1777 if (iter == pending_contents_.end()) {
1778 return NULL;
1781 WebContentsImpl* new_contents = iter->second;
1782 pending_contents_.erase(route_id);
1783 RemoveDestructionObserver(new_contents);
1785 // Don't initialize the guest WebContents immediately.
1786 if (BrowserPluginGuest::IsGuest(new_contents))
1787 return new_contents;
1789 if (!new_contents->GetRenderProcessHost()->HasConnection() ||
1790 !new_contents->GetRenderViewHost()->GetView())
1791 return NULL;
1793 // Resume blocked requests for both the RenderViewHost and RenderFrameHost.
1794 // TODO(brettw): It seems bogus to reach into here and initialize the host.
1795 static_cast<RenderViewHostImpl*>(new_contents->GetRenderViewHost())->Init();
1796 new_contents->GetMainFrame()->Init();
1798 return new_contents;
1801 RenderWidgetHostView* WebContentsImpl::GetCreatedWidget(int route_id) {
1802 PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id);
1803 if (iter == pending_widget_views_.end()) {
1804 DCHECK(false);
1805 return NULL;
1808 RenderWidgetHostView* widget_host_view = iter->second;
1809 pending_widget_views_.erase(route_id);
1811 RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
1812 if (!widget_host->GetProcess()->HasConnection()) {
1813 // The view has gone away or the renderer crashed. Nothing to do.
1814 return NULL;
1817 return widget_host_view;
1820 void WebContentsImpl::RequestMediaAccessPermission(
1821 const MediaStreamRequest& request,
1822 const MediaResponseCallback& callback) {
1823 if (delegate_) {
1824 delegate_->RequestMediaAccessPermission(this, request, callback);
1825 } else {
1826 callback.Run(MediaStreamDevices(),
1827 MEDIA_DEVICE_FAILED_DUE_TO_SHUTDOWN,
1828 scoped_ptr<MediaStreamUI>());
1832 bool WebContentsImpl::CheckMediaAccessPermission(const GURL& security_origin,
1833 MediaStreamType type) {
1834 DCHECK(type == MEDIA_DEVICE_AUDIO_CAPTURE ||
1835 type == MEDIA_DEVICE_VIDEO_CAPTURE);
1836 return delegate_ &&
1837 delegate_->CheckMediaAccessPermission(this, security_origin, type);
1840 SessionStorageNamespace* WebContentsImpl::GetSessionStorageNamespace(
1841 SiteInstance* instance) {
1842 return controller_.GetSessionStorageNamespace(instance);
1845 SessionStorageNamespaceMap WebContentsImpl::GetSessionStorageNamespaceMap() {
1846 return controller_.GetSessionStorageNamespaceMap();
1849 FrameTree* WebContentsImpl::GetFrameTree() {
1850 return &frame_tree_;
1853 void WebContentsImpl::SetIsVirtualKeyboardRequested(bool requested) {
1854 virtual_keyboard_requested_ = requested;
1857 bool WebContentsImpl::IsVirtualKeyboardRequested() {
1858 return virtual_keyboard_requested_;
1861 AccessibilityMode WebContentsImpl::GetAccessibilityMode() const {
1862 return accessibility_mode_;
1865 void WebContentsImpl::AccessibilityEventReceived(
1866 const std::vector<AXEventNotificationDetails>& details) {
1867 FOR_EACH_OBSERVER(
1868 WebContentsObserver, observers_, AccessibilityEventReceived(details));
1871 RenderFrameHost* WebContentsImpl::GetGuestByInstanceID(
1872 RenderFrameHost* render_frame_host,
1873 int browser_plugin_instance_id) {
1874 BrowserPluginGuestManager* guest_manager =
1875 GetBrowserContext()->GetGuestManager();
1876 // TODO(fsamuel): Change message routing to use the process ID of the
1877 // |render_frame_host| once BrowserPlugin IPCs get routed using the RFH
1878 // routing ID. See http://crbug.com/436339.
1879 WebContents* guest = guest_manager->GetGuestByInstanceID(
1880 GetRenderProcessHost()->GetID(), browser_plugin_instance_id);
1881 if (!guest)
1882 return NULL;
1883 return guest->GetMainFrame();
1886 GeolocationServiceContext* WebContentsImpl::GetGeolocationServiceContext() {
1887 return geolocation_service_context_.get();
1890 void WebContentsImpl::OnShowValidationMessage(
1891 const gfx::Rect& anchor_in_root_view,
1892 const base::string16& main_text,
1893 const base::string16& sub_text) {
1894 if (delegate_)
1895 delegate_->ShowValidationMessage(
1896 this, anchor_in_root_view, main_text, sub_text);
1899 void WebContentsImpl::OnHideValidationMessage() {
1900 if (delegate_)
1901 delegate_->HideValidationMessage(this);
1904 void WebContentsImpl::OnMoveValidationMessage(
1905 const gfx::Rect& anchor_in_root_view) {
1906 if (delegate_)
1907 delegate_->MoveValidationMessage(this, anchor_in_root_view);
1910 void WebContentsImpl::DidSendScreenRects(RenderWidgetHostImpl* rwh) {
1911 if (browser_plugin_embedder_)
1912 browser_plugin_embedder_->DidSendScreenRects();
1915 BrowserAccessibilityManager*
1916 WebContentsImpl::GetRootBrowserAccessibilityManager() {
1917 RenderFrameHostImpl* rfh = GetMainFrame();
1918 return rfh ? rfh->browser_accessibility_manager() : NULL;
1921 BrowserAccessibilityManager*
1922 WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
1923 RenderFrameHostImpl* rfh = GetMainFrame();
1924 return rfh ? rfh->GetOrCreateBrowserAccessibilityManager() : NULL;
1927 void WebContentsImpl::UpdatePreferredSize(const gfx::Size& pref_size) {
1928 const gfx::Size old_size = GetPreferredSize();
1929 preferred_size_ = pref_size;
1930 OnPreferredSizeChanged(old_size);
1933 void WebContentsImpl::ResizeDueToAutoResize(const gfx::Size& new_size) {
1934 if (delegate_)
1935 delegate_->ResizeDueToAutoResize(this, new_size);
1938 WebContents* WebContentsImpl::OpenURL(const OpenURLParams& params) {
1939 if (!delegate_)
1940 return NULL;
1942 WebContents* new_contents = delegate_->OpenURLFromTab(this, params);
1943 return new_contents;
1946 bool WebContentsImpl::Send(IPC::Message* message) {
1947 if (!GetRenderViewHost()) {
1948 delete message;
1949 return false;
1952 return GetRenderViewHost()->Send(message);
1955 bool WebContentsImpl::NavigateToPendingEntry(
1956 NavigationController::ReloadType reload_type) {
1957 FrameTreeNode* node = frame_tree_.root();
1959 // Navigate in the FrameTreeNode specified in the pending entry, if any. This
1960 // is currently only used in --site-per-process and tests.
1961 NavigationEntryImpl* pending_entry =
1962 NavigationEntryImpl::FromNavigationEntry(controller_.GetPendingEntry());
1963 if (pending_entry->frame_tree_node_id() != -1) {
1964 FrameTreeNode* subframe =
1965 frame_tree_.FindByID(pending_entry->frame_tree_node_id());
1966 DCHECK(subframe);
1967 if (subframe)
1968 node = subframe;
1971 return node->navigator()->NavigateToPendingEntry(
1972 node->current_frame_host(), reload_type);
1975 void WebContentsImpl::RenderFrameForInterstitialPageCreated(
1976 RenderFrameHost* render_frame_host) {
1977 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1978 RenderFrameForInterstitialPageCreated(render_frame_host));
1981 void WebContentsImpl::AttachInterstitialPage(
1982 InterstitialPageImpl* interstitial_page) {
1983 DCHECK(interstitial_page);
1984 GetRenderManager()->set_interstitial_page(interstitial_page);
1986 // Cancel any visible dialogs so that they don't interfere with the
1987 // interstitial.
1988 if (dialog_manager_)
1989 dialog_manager_->CancelActiveAndPendingDialogs(this);
1991 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1992 DidAttachInterstitialPage());
1995 void WebContentsImpl::DetachInterstitialPage() {
1996 if (ShowingInterstitialPage())
1997 GetRenderManager()->remove_interstitial_page();
1998 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1999 DidDetachInterstitialPage());
2002 void WebContentsImpl::SetHistoryOffsetAndLength(int history_offset,
2003 int history_length) {
2004 SetHistoryOffsetAndLengthForView(
2005 GetRenderViewHost(), history_offset, history_length);
2008 void WebContentsImpl::SetHistoryOffsetAndLengthForView(
2009 RenderViewHost* render_view_host,
2010 int history_offset,
2011 int history_length) {
2012 render_view_host->Send(new ViewMsg_SetHistoryOffsetAndLength(
2013 render_view_host->GetRoutingID(), history_offset, history_length));
2016 void WebContentsImpl::ReloadFocusedFrame(bool ignore_cache) {
2017 RenderFrameHost* focused_frame = GetFocusedFrame();
2018 if (!focused_frame)
2019 return;
2021 focused_frame->Send(new FrameMsg_Reload(
2022 focused_frame->GetRoutingID(), ignore_cache));
2025 void WebContentsImpl::Undo() {
2026 RenderFrameHost* focused_frame = GetFocusedFrame();
2027 if (!focused_frame)
2028 return;
2030 focused_frame->Send(new InputMsg_Undo(focused_frame->GetRoutingID()));
2031 RecordAction(base::UserMetricsAction("Undo"));
2034 void WebContentsImpl::Redo() {
2035 RenderFrameHost* focused_frame = GetFocusedFrame();
2036 if (!focused_frame)
2037 return;
2038 focused_frame->Send(new InputMsg_Redo(focused_frame->GetRoutingID()));
2039 RecordAction(base::UserMetricsAction("Redo"));
2042 void WebContentsImpl::Cut() {
2043 RenderFrameHost* focused_frame = GetFocusedFrame();
2044 if (!focused_frame)
2045 return;
2047 focused_frame->Send(new InputMsg_Cut(focused_frame->GetRoutingID()));
2048 RecordAction(base::UserMetricsAction("Cut"));
2051 void WebContentsImpl::Copy() {
2052 RenderFrameHost* focused_frame = GetFocusedFrame();
2053 if (!focused_frame)
2054 return;
2056 focused_frame->Send(new InputMsg_Copy(focused_frame->GetRoutingID()));
2057 RecordAction(base::UserMetricsAction("Copy"));
2060 void WebContentsImpl::CopyToFindPboard() {
2061 #if defined(OS_MACOSX)
2062 RenderFrameHost* focused_frame = GetFocusedFrame();
2063 if (!focused_frame)
2064 return;
2066 // Windows/Linux don't have the concept of a find pasteboard.
2067 focused_frame->Send(
2068 new InputMsg_CopyToFindPboard(focused_frame->GetRoutingID()));
2069 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
2070 #endif
2073 void WebContentsImpl::Paste() {
2074 RenderFrameHost* focused_frame = GetFocusedFrame();
2075 if (!focused_frame)
2076 return;
2078 focused_frame->Send(new InputMsg_Paste(focused_frame->GetRoutingID()));
2079 RecordAction(base::UserMetricsAction("Paste"));
2082 void WebContentsImpl::PasteAndMatchStyle() {
2083 RenderFrameHost* focused_frame = GetFocusedFrame();
2084 if (!focused_frame)
2085 return;
2087 focused_frame->Send(new InputMsg_PasteAndMatchStyle(
2088 focused_frame->GetRoutingID()));
2089 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
2092 void WebContentsImpl::Delete() {
2093 RenderFrameHost* focused_frame = GetFocusedFrame();
2094 if (!focused_frame)
2095 return;
2097 focused_frame->Send(new InputMsg_Delete(focused_frame->GetRoutingID()));
2098 RecordAction(base::UserMetricsAction("DeleteSelection"));
2101 void WebContentsImpl::SelectAll() {
2102 RenderFrameHost* focused_frame = GetFocusedFrame();
2103 if (!focused_frame)
2104 return;
2106 focused_frame->Send(new InputMsg_SelectAll(focused_frame->GetRoutingID()));
2107 RecordAction(base::UserMetricsAction("SelectAll"));
2110 void WebContentsImpl::Unselect() {
2111 RenderFrameHost* focused_frame = GetFocusedFrame();
2112 if (!focused_frame)
2113 return;
2115 focused_frame->Send(new InputMsg_Unselect(focused_frame->GetRoutingID()));
2116 RecordAction(base::UserMetricsAction("Unselect"));
2119 void WebContentsImpl::Replace(const base::string16& word) {
2120 RenderFrameHost* focused_frame = GetFocusedFrame();
2121 if (!focused_frame)
2122 return;
2124 focused_frame->Send(new InputMsg_Replace(
2125 focused_frame->GetRoutingID(), word));
2128 void WebContentsImpl::ReplaceMisspelling(const base::string16& word) {
2129 RenderFrameHost* focused_frame = GetFocusedFrame();
2130 if (!focused_frame)
2131 return;
2133 focused_frame->Send(new InputMsg_ReplaceMisspelling(
2134 focused_frame->GetRoutingID(), word));
2137 void WebContentsImpl::NotifyContextMenuClosed(
2138 const CustomContextMenuContext& context) {
2139 RenderFrameHost* focused_frame = GetFocusedFrame();
2140 if (!focused_frame)
2141 return;
2143 focused_frame->Send(new FrameMsg_ContextMenuClosed(
2144 focused_frame->GetRoutingID(), context));
2147 void WebContentsImpl::ExecuteCustomContextMenuCommand(
2148 int action, const CustomContextMenuContext& context) {
2149 RenderFrameHost* focused_frame = GetFocusedFrame();
2150 if (!focused_frame)
2151 return;
2153 focused_frame->Send(new FrameMsg_CustomContextMenuAction(
2154 focused_frame->GetRoutingID(), context, action));
2157 gfx::NativeView WebContentsImpl::GetNativeView() {
2158 return view_->GetNativeView();
2161 gfx::NativeView WebContentsImpl::GetContentNativeView() {
2162 return view_->GetContentNativeView();
2165 gfx::NativeWindow WebContentsImpl::GetTopLevelNativeWindow() {
2166 return view_->GetTopLevelNativeWindow();
2169 gfx::Rect WebContentsImpl::GetViewBounds() {
2170 return view_->GetViewBounds();
2173 gfx::Rect WebContentsImpl::GetContainerBounds() {
2174 gfx::Rect rv;
2175 view_->GetContainerBounds(&rv);
2176 return rv;
2179 DropData* WebContentsImpl::GetDropData() {
2180 return view_->GetDropData();
2183 void WebContentsImpl::Focus() {
2184 view_->Focus();
2187 void WebContentsImpl::SetInitialFocus() {
2188 view_->SetInitialFocus();
2191 void WebContentsImpl::StoreFocus() {
2192 view_->StoreFocus();
2195 void WebContentsImpl::RestoreFocus() {
2196 view_->RestoreFocus();
2199 void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
2200 if (ShowingInterstitialPage()) {
2201 GetRenderManager()->interstitial_page()->FocusThroughTabTraversal(reverse);
2202 return;
2204 RenderWidgetHostView* const fullscreen_view =
2205 GetFullscreenRenderWidgetHostView();
2206 if (fullscreen_view) {
2207 fullscreen_view->Focus();
2208 return;
2210 GetRenderViewHostImpl()->SetInitialFocus(reverse);
2213 bool WebContentsImpl::ShowingInterstitialPage() const {
2214 return GetRenderManager()->interstitial_page() != NULL;
2217 InterstitialPage* WebContentsImpl::GetInterstitialPage() const {
2218 return GetRenderManager()->interstitial_page();
2221 bool WebContentsImpl::IsSavable() {
2222 // WebKit creates Document object when MIME type is application/xhtml+xml,
2223 // so we also support this MIME type.
2224 return contents_mime_type_ == "text/html" ||
2225 contents_mime_type_ == "text/xml" ||
2226 contents_mime_type_ == "application/xhtml+xml" ||
2227 contents_mime_type_ == "text/plain" ||
2228 contents_mime_type_ == "text/css" ||
2229 net::IsSupportedJavascriptMimeType(contents_mime_type_.c_str());
2232 void WebContentsImpl::OnSavePage() {
2233 // If we can not save the page, try to download it.
2234 if (!IsSavable()) {
2235 RecordDownloadSource(INITIATED_BY_SAVE_PACKAGE_ON_NON_HTML);
2236 SaveFrame(GetURL(), Referrer());
2237 return;
2240 Stop();
2242 // Create the save package and possibly prompt the user for the name to save
2243 // the page as. The user prompt is an asynchronous operation that runs on
2244 // another thread.
2245 save_package_ = new SavePackage(this);
2246 save_package_->GetSaveInfo();
2249 // Used in automated testing to bypass prompting the user for file names.
2250 // Instead, the names and paths are hard coded rather than running them through
2251 // file name sanitation and extension / mime checking.
2252 bool WebContentsImpl::SavePage(const base::FilePath& main_file,
2253 const base::FilePath& dir_path,
2254 SavePageType save_type) {
2255 // Stop the page from navigating.
2256 Stop();
2258 save_package_ = new SavePackage(this, save_type, main_file, dir_path);
2259 return save_package_->Init(SavePackageDownloadCreatedCallback());
2262 void WebContentsImpl::SaveFrame(const GURL& url,
2263 const Referrer& referrer) {
2264 if (!GetURL().is_valid())
2265 return;
2266 if (delegate_ && delegate_->SaveFrame(url, referrer))
2267 return;
2269 bool is_main_frame = (url == GetURL());
2271 DownloadManager* dlm =
2272 BrowserContext::GetDownloadManager(GetBrowserContext());
2273 if (!dlm)
2274 return;
2275 int64 post_id = -1;
2276 if (is_main_frame) {
2277 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2278 if (entry)
2279 post_id = entry->GetPostID();
2281 scoped_ptr<DownloadUrlParameters> params(
2282 DownloadUrlParameters::FromWebContents(this, url));
2283 params->set_referrer(referrer);
2284 params->set_post_id(post_id);
2285 params->set_prefer_cache(true);
2286 if (post_id >= 0)
2287 params->set_method("POST");
2288 params->set_prompt(true);
2289 dlm->DownloadUrl(params.Pass());
2292 void WebContentsImpl::GenerateMHTML(
2293 const base::FilePath& file,
2294 const base::Callback<void(int64)>& callback) {
2295 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, file, callback);
2298 const std::string& WebContentsImpl::GetContentsMimeType() const {
2299 return contents_mime_type_;
2302 bool WebContentsImpl::WillNotifyDisconnection() const {
2303 return notify_disconnection_;
2306 void WebContentsImpl::SetOverrideEncoding(const std::string& encoding) {
2307 SetEncoding(encoding);
2308 Send(new ViewMsg_SetPageEncoding(GetRoutingID(), encoding));
2311 void WebContentsImpl::ResetOverrideEncoding() {
2312 canonical_encoding_.clear();
2313 Send(new ViewMsg_ResetPageEncodingToDefault(GetRoutingID()));
2316 RendererPreferences* WebContentsImpl::GetMutableRendererPrefs() {
2317 return &renderer_preferences_;
2320 void WebContentsImpl::Close() {
2321 Close(GetRenderViewHost());
2324 void WebContentsImpl::DragSourceEndedAt(int client_x, int client_y,
2325 int screen_x, int screen_y, blink::WebDragOperation operation) {
2326 if (browser_plugin_embedder_.get())
2327 browser_plugin_embedder_->DragSourceEndedAt(client_x, client_y,
2328 screen_x, screen_y, operation);
2329 if (GetRenderViewHost())
2330 GetRenderViewHostImpl()->DragSourceEndedAt(client_x, client_y,
2331 screen_x, screen_y, operation);
2334 void WebContentsImpl::DidGetResourceResponseStart(
2335 const ResourceRequestDetails& details) {
2336 controller_.ssl_manager()->DidStartResourceResponse(details);
2338 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2339 DidGetResourceResponseStart(details));
2341 // TODO(avi): Remove. http://crbug.com/170921
2342 NotificationService::current()->Notify(
2343 NOTIFICATION_RESOURCE_RESPONSE_STARTED,
2344 Source<WebContents>(this),
2345 Details<const ResourceRequestDetails>(&details));
2348 void WebContentsImpl::DidGetRedirectForResourceRequest(
2349 RenderFrameHost* render_frame_host,
2350 const ResourceRedirectDetails& details) {
2351 controller_.ssl_manager()->DidReceiveResourceRedirect(details);
2353 FOR_EACH_OBSERVER(
2354 WebContentsObserver,
2355 observers_,
2356 DidGetRedirectForResourceRequest(render_frame_host, details));
2358 // TODO(avi): Remove. http://crbug.com/170921
2359 NotificationService::current()->Notify(
2360 NOTIFICATION_RESOURCE_RECEIVED_REDIRECT,
2361 Source<WebContents>(this),
2362 Details<const ResourceRedirectDetails>(&details));
2365 void WebContentsImpl::SystemDragEnded() {
2366 if (GetRenderViewHost())
2367 GetRenderViewHostImpl()->DragSourceSystemDragEnded();
2368 if (delegate_)
2369 delegate_->DragEnded();
2370 if (browser_plugin_embedder_.get())
2371 browser_plugin_embedder_->SystemDragEnded();
2374 void WebContentsImpl::UserGestureDone() {
2375 OnUserGesture();
2378 void WebContentsImpl::SetClosedByUserGesture(bool value) {
2379 closed_by_user_gesture_ = value;
2382 bool WebContentsImpl::GetClosedByUserGesture() const {
2383 return closed_by_user_gesture_;
2386 void WebContentsImpl::ViewSource() {
2387 if (!delegate_)
2388 return;
2390 NavigationEntry* entry = GetController().GetLastCommittedEntry();
2391 if (!entry)
2392 return;
2394 delegate_->ViewSourceForTab(this, entry->GetURL());
2397 void WebContentsImpl::ViewFrameSource(const GURL& url,
2398 const PageState& page_state) {
2399 if (!delegate_)
2400 return;
2402 delegate_->ViewSourceForFrame(this, url, page_state);
2405 int WebContentsImpl::GetMinimumZoomPercent() const {
2406 return minimum_zoom_percent_;
2409 int WebContentsImpl::GetMaximumZoomPercent() const {
2410 return maximum_zoom_percent_;
2413 gfx::Size WebContentsImpl::GetPreferredSize() const {
2414 return capturer_count_ == 0 ? preferred_size_ : preferred_size_for_capture_;
2417 bool WebContentsImpl::GotResponseToLockMouseRequest(bool allowed) {
2418 if (GetBrowserPluginGuest())
2419 return GetBrowserPluginGuest()->LockMouse(allowed);
2421 return GetRenderViewHost() ?
2422 GetRenderViewHostImpl()->GotResponseToLockMouseRequest(allowed) : false;
2425 bool WebContentsImpl::HasOpener() const {
2426 return opener_ != NULL;
2429 WebContents* WebContentsImpl::GetOpener() const {
2430 return static_cast<WebContents*>(opener_);
2433 void WebContentsImpl::DidChooseColorInColorChooser(SkColor color) {
2434 if (!color_chooser_info_.get())
2435 return;
2436 RenderFrameHost* rfh = RenderFrameHost::FromID(
2437 color_chooser_info_->render_process_id,
2438 color_chooser_info_->render_frame_id);
2439 if (!rfh)
2440 return;
2442 rfh->Send(new FrameMsg_DidChooseColorResponse(
2443 rfh->GetRoutingID(), color_chooser_info_->identifier, color));
2446 void WebContentsImpl::DidEndColorChooser() {
2447 if (!color_chooser_info_.get())
2448 return;
2449 RenderFrameHost* rfh = RenderFrameHost::FromID(
2450 color_chooser_info_->render_process_id,
2451 color_chooser_info_->render_frame_id);
2452 if (!rfh)
2453 return;
2455 rfh->Send(new FrameMsg_DidEndColorChooser(
2456 rfh->GetRoutingID(), color_chooser_info_->identifier));
2457 color_chooser_info_.reset();
2460 int WebContentsImpl::DownloadImage(const GURL& url,
2461 bool is_favicon,
2462 uint32_t max_bitmap_size,
2463 const ImageDownloadCallback& callback) {
2464 int id = StartDownload(GetMainFrame(), url, is_favicon, max_bitmap_size);
2465 image_download_map_[id] = callback;
2466 return id;
2469 bool WebContentsImpl::IsSubframe() const {
2470 return is_subframe_;
2473 void WebContentsImpl::Find(int request_id,
2474 const base::string16& search_text,
2475 const blink::WebFindOptions& options) {
2476 // See if a top level browser plugin handles the find request first.
2477 if (browser_plugin_embedder_ &&
2478 browser_plugin_embedder_->Find(request_id, search_text, options)) {
2479 return;
2481 Send(new ViewMsg_Find(GetRoutingID(), request_id, search_text, options));
2484 void WebContentsImpl::StopFinding(StopFindAction action) {
2485 // See if a top level browser plugin handles the stop finding request first.
2486 if (browser_plugin_embedder_ &&
2487 browser_plugin_embedder_->StopFinding(action)) {
2488 return;
2490 Send(new ViewMsg_StopFinding(GetRoutingID(), action));
2493 void WebContentsImpl::InsertCSS(const std::string& css) {
2494 GetMainFrame()->Send(new FrameMsg_CSSInsertRequest(
2495 GetMainFrame()->GetRoutingID(), css));
2498 bool WebContentsImpl::WasRecentlyAudible() {
2499 return audio_stream_monitor_.WasRecentlyAudible();
2502 void WebContentsImpl::GetManifest(const GetManifestCallback& callback) {
2503 manifest_manager_host_->GetManifest(GetMainFrame(), callback);
2506 void WebContentsImpl::ExitFullscreen() {
2507 // Clean up related state and initiate the fullscreen exit.
2508 GetRenderViewHostImpl()->RejectMouseLockOrUnlockIfNecessary();
2509 ExitFullscreenMode();
2512 bool WebContentsImpl::FocusLocationBarByDefault() {
2513 NavigationEntry* entry = controller_.GetVisibleEntry();
2514 if (entry && entry->GetURL() == GURL(url::kAboutBlankURL))
2515 return true;
2516 return delegate_ && delegate_->ShouldFocusLocationBarByDefault(this);
2519 void WebContentsImpl::SetFocusToLocationBar(bool select_all) {
2520 if (delegate_)
2521 delegate_->SetFocusToLocationBar(select_all);
2524 void WebContentsImpl::DidStartProvisionalLoad(
2525 RenderFrameHostImpl* render_frame_host,
2526 const GURL& validated_url,
2527 bool is_error_page,
2528 bool is_iframe_srcdoc) {
2529 // Notify observers about the start of the provisional load.
2530 FOR_EACH_OBSERVER(
2531 WebContentsObserver,
2532 observers_,
2533 DidStartProvisionalLoadForFrame(
2534 render_frame_host, validated_url, is_error_page, is_iframe_srcdoc));
2536 // Notify accessibility if this is a reload.
2537 NavigationEntry* entry = controller_.GetVisibleEntry();
2538 if (entry && ui::PageTransitionCoreTypeIs(
2539 entry->GetTransitionType(), ui::PAGE_TRANSITION_RELOAD)) {
2540 FrameTreeNode* ftn = render_frame_host->frame_tree_node();
2541 BrowserAccessibilityManager* manager =
2542 ftn->current_frame_host()->browser_accessibility_manager();
2543 if (manager)
2544 manager->UserIsReloading();
2548 void WebContentsImpl::DidStartNavigationTransition(
2549 RenderFrameHostImpl* render_frame_host) {
2550 #if defined(OS_ANDROID)
2551 int render_frame_id = render_frame_host->GetRoutingID();
2552 GetWebContentsAndroid()->DidStartNavigationTransitionForFrame(
2553 render_frame_id);
2554 #endif
2557 void WebContentsImpl::DidFailProvisionalLoadWithError(
2558 RenderFrameHostImpl* render_frame_host,
2559 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
2560 GURL validated_url(params.url);
2561 FOR_EACH_OBSERVER(WebContentsObserver,
2562 observers_,
2563 DidFailProvisionalLoad(render_frame_host,
2564 validated_url,
2565 params.error_code,
2566 params.error_description));
2568 FrameTreeNode* ftn = render_frame_host->frame_tree_node();
2569 BrowserAccessibilityManager* manager =
2570 ftn->current_frame_host()->browser_accessibility_manager();
2571 if (manager)
2572 manager->NavigationFailed();
2575 void WebContentsImpl::DidFailLoadWithError(
2576 RenderFrameHostImpl* render_frame_host,
2577 const GURL& url,
2578 int error_code,
2579 const base::string16& error_description) {
2580 FOR_EACH_OBSERVER(
2581 WebContentsObserver,
2582 observers_,
2583 DidFailLoad(render_frame_host, url, error_code, error_description));
2586 void WebContentsImpl::NotifyChangedNavigationState(
2587 InvalidateTypes changed_flags) {
2588 NotifyNavigationStateChanged(changed_flags);
2591 void WebContentsImpl::AboutToNavigateRenderFrame(
2592 RenderFrameHostImpl* old_host,
2593 RenderFrameHostImpl* new_host) {
2594 // Notify observers that we will navigate in this RenderFrame.
2595 FOR_EACH_OBSERVER(
2596 WebContentsObserver,
2597 observers_,
2598 AboutToNavigateRenderFrame(old_host, new_host));
2601 void WebContentsImpl::DidStartNavigationToPendingEntry(
2602 RenderFrameHostImpl* render_frame_host,
2603 const GURL& url,
2604 NavigationController::ReloadType reload_type) {
2605 // Notify observers about navigation.
2606 FOR_EACH_OBSERVER(
2607 WebContentsObserver,
2608 observers_,
2609 DidStartNavigationToPendingEntry(url, reload_type));
2612 void WebContentsImpl::RequestOpenURL(RenderFrameHostImpl* render_frame_host,
2613 const OpenURLParams& params) {
2614 // OpenURL can blow away the source RFH. Use the process/frame routing ID as a
2615 // weak pointer of sorts.
2616 const int32_t process_id = render_frame_host->GetProcess()->GetID();
2617 const int32_t frame_id = render_frame_host->GetRoutingID();
2619 WebContents* new_contents = OpenURL(params);
2621 if (new_contents && RenderFrameHost::FromID(process_id, frame_id)) {
2622 // Notify observers.
2623 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2624 DidOpenRequestedURL(new_contents,
2625 render_frame_host,
2626 params.url,
2627 params.referrer,
2628 params.disposition,
2629 params.transition));
2633 bool WebContentsImpl::ShouldPreserveAbortedURLs() {
2634 if (!delegate_)
2635 return false;
2636 return delegate_->ShouldPreserveAbortedURLs(this);
2639 void WebContentsImpl::DidCommitProvisionalLoad(
2640 RenderFrameHostImpl* render_frame_host,
2641 const GURL& url,
2642 ui::PageTransition transition_type) {
2643 // Notify observers about the commit of the provisional load.
2644 FOR_EACH_OBSERVER(WebContentsObserver,
2645 observers_,
2646 DidCommitProvisionalLoadForFrame(
2647 render_frame_host, url, transition_type));
2649 BrowserAccessibilityManager* manager =
2650 render_frame_host->browser_accessibility_manager();
2651 if (manager)
2652 manager->NavigationSucceeded();
2655 void WebContentsImpl::DidNavigateMainFramePreCommit(
2656 bool navigation_is_within_page) {
2657 // Ensure fullscreen mode is exited before committing the navigation to a
2658 // different page. The next page will not start out assuming it is in
2659 // fullscreen mode.
2660 if (navigation_is_within_page) {
2661 // No page change? Then, the renderer and browser can remain in fullscreen.
2662 return;
2664 if (IsFullscreenForCurrentTab())
2665 ExitFullscreen();
2666 DCHECK(!IsFullscreenForCurrentTab());
2669 void WebContentsImpl::DidNavigateMainFramePostCommit(
2670 RenderFrameHostImpl* render_frame_host,
2671 const LoadCommittedDetails& details,
2672 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
2673 if (details.is_navigation_to_different_page()) {
2674 // Clear the status bubble. This is a workaround for a bug where WebKit
2675 // doesn't let us know that the cursor left an element during a
2676 // transition (this is also why the mouse cursor remains as a hand after
2677 // clicking on a link); see bugs 1184641 and 980803. We don't want to
2678 // clear the bubble when a user navigates to a named anchor in the same
2679 // page.
2680 UpdateTargetURL(render_frame_host->GetRenderViewHost(), GURL());
2682 RenderWidgetHostViewBase* rwhvb =
2683 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
2684 if (rwhvb)
2685 rwhvb->OnDidNavigateMainFrameToNewPage();
2688 if (!details.is_in_page) {
2689 // Once the main frame is navigated, we're no longer considered to have
2690 // displayed insecure content.
2691 displayed_insecure_content_ = false;
2692 SSLManager::NotifySSLInternalStateChanged(
2693 GetController().GetBrowserContext());
2696 // Notify observers about navigation.
2697 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2698 DidNavigateMainFrame(details, params));
2700 if (delegate_)
2701 delegate_->DidNavigateMainFramePostCommit(this);
2702 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
2705 void WebContentsImpl::DidNavigateAnyFramePostCommit(
2706 RenderFrameHostImpl* render_frame_host,
2707 const LoadCommittedDetails& details,
2708 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
2709 // Now that something has committed, we don't need to track whether the
2710 // initial page has been accessed.
2711 has_accessed_initial_document_ = false;
2713 // If we navigate off the page, close all JavaScript dialogs.
2714 if (dialog_manager_ && !details.is_in_page)
2715 dialog_manager_->CancelActiveAndPendingDialogs(this);
2717 // Notify observers about navigation.
2718 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2719 DidNavigateAnyFrame(render_frame_host, details, params));
2722 void WebContentsImpl::SetMainFrameMimeType(const std::string& mime_type) {
2723 contents_mime_type_ = mime_type;
2726 bool WebContentsImpl::CanOverscrollContent() const {
2727 // Disable overscroll when touch emulation is on. See crbug.com/369938.
2728 if (force_disable_overscroll_content_)
2729 return false;
2731 if (delegate_)
2732 return delegate_->CanOverscrollContent();
2734 return false;
2737 void WebContentsImpl::OnThemeColorChanged(SkColor theme_color) {
2738 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2739 DidChangeThemeColor(theme_color));
2742 void WebContentsImpl::OnDidLoadResourceFromMemoryCache(
2743 const GURL& url,
2744 const std::string& security_info,
2745 const std::string& http_method,
2746 const std::string& mime_type,
2747 ResourceType resource_type) {
2749 // Send out a notification that we loaded a resource from our memory cache.
2750 int cert_id = 0;
2751 net::CertStatus cert_status = 0;
2752 int security_bits = -1;
2753 int connection_status = 0;
2754 SignedCertificateTimestampIDStatusList signed_certificate_timestamp_ids;
2755 DeserializeSecurityInfo(security_info, &cert_id, &cert_status,
2756 &security_bits, &connection_status,
2757 &signed_certificate_timestamp_ids);
2758 // TODO(alcutter,eranm): Pass signed_certificate_timestamp_ids into details
2759 LoadFromMemoryCacheDetails details(
2760 url, GetRenderProcessHost()->GetID(), cert_id, cert_status, http_method,
2761 mime_type, resource_type);
2763 controller_.ssl_manager()->DidLoadFromMemoryCache(details);
2765 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2766 DidLoadResourceFromMemoryCache(details));
2768 if (url.is_valid() && url.SchemeIsHTTPOrHTTPS()) {
2769 scoped_refptr<net::URLRequestContextGetter> request_context(
2770 resource_type == RESOURCE_TYPE_MEDIA ?
2771 GetBrowserContext()->GetMediaRequestContextForRenderProcess(
2772 GetRenderProcessHost()->GetID()) :
2773 GetBrowserContext()->GetRequestContextForRenderProcess(
2774 GetRenderProcessHost()->GetID()));
2775 BrowserThread::PostTask(
2776 BrowserThread::IO,
2777 FROM_HERE,
2778 base::Bind(&NotifyCacheOnIO, request_context, url, http_method));
2782 void WebContentsImpl::OnDidDisplayInsecureContent() {
2783 RecordAction(base::UserMetricsAction("SSL.DisplayedInsecureContent"));
2784 displayed_insecure_content_ = true;
2785 SSLManager::NotifySSLInternalStateChanged(
2786 GetController().GetBrowserContext());
2789 void WebContentsImpl::OnDidRunInsecureContent(
2790 const std::string& security_origin, const GURL& target_url) {
2791 LOG(WARNING) << security_origin << " ran insecure content from "
2792 << target_url.possibly_invalid_spec();
2793 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
2794 if (EndsWith(security_origin, kDotGoogleDotCom, false))
2795 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
2796 controller_.ssl_manager()->DidRunInsecureContent(security_origin);
2797 displayed_insecure_content_ = true;
2798 SSLManager::NotifySSLInternalStateChanged(
2799 GetController().GetBrowserContext());
2802 void WebContentsImpl::OnDocumentLoadedInFrame() {
2803 if (!HasValidFrameSource())
2804 return;
2806 RenderFrameHostImpl* rfh =
2807 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2808 FOR_EACH_OBSERVER(
2809 WebContentsObserver, observers_, DocumentLoadedInFrame(rfh));
2812 void WebContentsImpl::OnDidFinishLoad(const GURL& url) {
2813 if (!HasValidFrameSource())
2814 return;
2816 GURL validated_url(url);
2817 RenderProcessHost* render_process_host =
2818 render_frame_message_source_->GetProcess();
2819 render_process_host->FilterURL(false, &validated_url);
2821 RenderFrameHostImpl* rfh =
2822 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2823 FOR_EACH_OBSERVER(
2824 WebContentsObserver, observers_, DidFinishLoad(rfh, validated_url));
2827 void WebContentsImpl::OnDidStartLoading(bool to_different_document) {
2828 if (!HasValidFrameSource())
2829 return;
2831 RenderFrameHostImpl* rfh =
2832 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2833 int64 render_frame_id = rfh->frame_tree_node()->frame_tree_node_id();
2835 // Any main frame load to a new document should reset the load progress, since
2836 // it will replace the current page and any frames.
2837 if (to_different_document && !rfh->GetParent()) {
2838 ResetLoadProgressState();
2839 loading_frames_in_progress_ = 0;
2840 rfh->frame_tree_node()->set_is_loading(false);
2843 // It is possible to get multiple calls to OnDidStartLoading that don't have
2844 // corresponding calls to OnDidStopLoading:
2845 // - With "swappedout://" URLs, this happens when a RenderView gets swapped
2846 // out for a cross-process navigation, and it turns into a placeholder for
2847 // one being rendered in a different process.
2848 // - Also, there might be more than one RenderFrameHost sharing the same
2849 // FrameTreeNode (and thus sharing its ID) each sending a start.
2850 // - But in the future, once clamy@ moves navigation network requests to the
2851 // browser process, there's a good chance that callbacks about starting and
2852 // stopping will all be handled by the browser. When that happens, there
2853 // should no longer be a start/stop call imbalance. TODO(avi): When this
2854 // future arrives, update this code to not allow this case.
2855 if (rfh->frame_tree_node()->is_loading())
2856 return;
2858 DCHECK_GE(loading_frames_in_progress_, 0);
2859 if (loading_frames_in_progress_ == 0)
2860 DidStartLoading(rfh, to_different_document);
2862 ++loading_frames_in_progress_;
2863 rfh->frame_tree_node()->set_is_loading(true);
2865 // Notify the RenderFrameHostManager of the event.
2866 rfh->frame_tree_node()->render_manager()->OnDidStartLoading();
2868 loading_progresses_[render_frame_id] = kMinimumLoadingProgress;
2869 SendLoadProgressChanged();
2872 void WebContentsImpl::OnDidStopLoading() {
2873 if (!HasValidFrameSource())
2874 return;
2876 RenderFrameHostImpl* rfh =
2877 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2878 int64 render_frame_id = rfh->frame_tree_node()->frame_tree_node_id();
2879 rfh->frame_tree_node()->set_is_loading(false);
2881 if (loading_progresses_.find(render_frame_id) != loading_progresses_.end()) {
2882 // Load stopped while we were still tracking load. Make sure we update
2883 // progress based on this frame's completion.
2884 loading_progresses_[render_frame_id] = 1.0;
2885 SendLoadProgressChanged();
2886 // Then we clean-up our states.
2887 if (loading_total_progress_ == 1.0)
2888 ResetLoadProgressState();
2891 // Notify the RenderFrameHostManager of the event.
2892 rfh->frame_tree_node()->render_manager()->OnDidStopLoading();
2894 // TODO(japhet): This should be a DCHECK, but the pdf plugin sometimes
2895 // calls DidStopLoading() without a matching DidStartLoading().
2896 if (loading_frames_in_progress_ == 0)
2897 return;
2898 --loading_frames_in_progress_;
2899 if (loading_frames_in_progress_ == 0)
2900 DidStopLoading(rfh);
2903 void WebContentsImpl::OnDidChangeLoadProgress(double load_progress) {
2904 if (!HasValidFrameSource())
2905 return;
2907 RenderFrameHostImpl* rfh =
2908 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2909 int64 render_frame_id = rfh->frame_tree_node()->frame_tree_node_id();
2911 loading_progresses_[render_frame_id] = load_progress;
2913 // We notify progress change immediately for the first and last updates.
2914 // Also, since the message loop may be pretty busy when a page is loaded, it
2915 // might not execute a posted task in a timely manner so we make sure to
2916 // immediately send progress report if enough time has passed.
2917 base::TimeDelta min_delay =
2918 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS);
2919 if (load_progress == 1.0 || loading_last_progress_update_.is_null() ||
2920 base::TimeTicks::Now() - loading_last_progress_update_ > min_delay) {
2921 // If there is a pending task to send progress, it is now obsolete.
2922 loading_weak_factory_.InvalidateWeakPtrs();
2923 SendLoadProgressChanged();
2924 if (loading_total_progress_ == 1.0)
2925 ResetLoadProgressState();
2926 return;
2929 if (loading_weak_factory_.HasWeakPtrs())
2930 return;
2932 base::MessageLoop::current()->PostDelayedTask(
2933 FROM_HERE,
2934 base::Bind(&WebContentsImpl::SendLoadProgressChanged,
2935 loading_weak_factory_.GetWeakPtr()),
2936 min_delay);
2939 void WebContentsImpl::OnGoToEntryAtOffset(int offset) {
2940 if (!delegate_ || delegate_->OnGoToEntryOffset(offset))
2941 controller_.GoToOffset(offset);
2944 void WebContentsImpl::OnUpdateZoomLimits(int minimum_percent,
2945 int maximum_percent) {
2946 minimum_zoom_percent_ = minimum_percent;
2947 maximum_zoom_percent_ = maximum_percent;
2950 void WebContentsImpl::OnEnumerateDirectory(int request_id,
2951 const base::FilePath& path) {
2952 if (!delegate_)
2953 return;
2955 ChildProcessSecurityPolicyImpl* policy =
2956 ChildProcessSecurityPolicyImpl::GetInstance();
2957 if (policy->CanReadFile(GetRenderProcessHost()->GetID(), path))
2958 delegate_->EnumerateDirectory(this, request_id, path);
2961 void WebContentsImpl::OnRegisterProtocolHandler(const std::string& protocol,
2962 const GURL& url,
2963 const base::string16& title,
2964 bool user_gesture) {
2965 if (!delegate_)
2966 return;
2968 ChildProcessSecurityPolicyImpl* policy =
2969 ChildProcessSecurityPolicyImpl::GetInstance();
2970 if (policy->IsPseudoScheme(protocol))
2971 return;
2973 delegate_->RegisterProtocolHandler(this, protocol, url, user_gesture);
2976 void WebContentsImpl::OnUnregisterProtocolHandler(const std::string& protocol,
2977 const GURL& url,
2978 bool user_gesture) {
2979 if (!delegate_)
2980 return;
2982 ChildProcessSecurityPolicyImpl* policy =
2983 ChildProcessSecurityPolicyImpl::GetInstance();
2984 if (policy->IsPseudoScheme(protocol))
2985 return;
2987 delegate_->UnregisterProtocolHandler(this, protocol, url, user_gesture);
2990 void WebContentsImpl::OnFindReply(int request_id,
2991 int number_of_matches,
2992 const gfx::Rect& selection_rect,
2993 int active_match_ordinal,
2994 bool final_update) {
2995 if (delegate_) {
2996 delegate_->FindReply(this, request_id, number_of_matches, selection_rect,
2997 active_match_ordinal, final_update);
3001 #if defined(OS_ANDROID)
3002 void WebContentsImpl::OnFindMatchRectsReply(
3003 int version,
3004 const std::vector<gfx::RectF>& rects,
3005 const gfx::RectF& active_rect) {
3006 if (delegate_)
3007 delegate_->FindMatchRectsReply(this, version, rects, active_rect);
3010 void WebContentsImpl::OnOpenDateTimeDialog(
3011 const ViewHostMsg_DateTimeDialogValue_Params& value) {
3012 date_time_chooser_->ShowDialog(GetTopLevelNativeWindow(),
3013 GetRenderViewHost(),
3014 value.dialog_type,
3015 value.dialog_value,
3016 value.minimum,
3017 value.maximum,
3018 value.step,
3019 value.suggestions);
3021 #endif
3023 void WebContentsImpl::OnDomOperationResponse(const std::string& json_string,
3024 int automation_id) {
3025 DomOperationNotificationDetails details(json_string, automation_id);
3026 NotificationService::current()->Notify(
3027 NOTIFICATION_DOM_OPERATION_RESPONSE,
3028 Source<WebContents>(this),
3029 Details<DomOperationNotificationDetails>(&details));
3032 void WebContentsImpl::OnAppCacheAccessed(const GURL& manifest_url,
3033 bool blocked_by_policy) {
3034 // Notify observers about navigation.
3035 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3036 AppCacheAccessed(manifest_url, blocked_by_policy));
3039 void WebContentsImpl::OnOpenColorChooser(
3040 int color_chooser_id,
3041 SkColor color,
3042 const std::vector<ColorSuggestion>& suggestions) {
3043 if (!HasValidFrameSource())
3044 return;
3046 ColorChooser* new_color_chooser = delegate_ ?
3047 delegate_->OpenColorChooser(this, color, suggestions) :
3048 NULL;
3049 if (!new_color_chooser)
3050 return;
3051 if (color_chooser_info_.get())
3052 color_chooser_info_->chooser->End();
3054 color_chooser_info_.reset(new ColorChooserInfo(
3055 render_frame_message_source_->GetProcess()->GetID(),
3056 render_frame_message_source_->GetRoutingID(),
3057 new_color_chooser,
3058 color_chooser_id));
3061 void WebContentsImpl::OnEndColorChooser(int color_chooser_id) {
3062 if (color_chooser_info_ &&
3063 color_chooser_id == color_chooser_info_->identifier)
3064 color_chooser_info_->chooser->End();
3067 void WebContentsImpl::OnSetSelectedColorInColorChooser(int color_chooser_id,
3068 SkColor color) {
3069 if (color_chooser_info_ &&
3070 color_chooser_id == color_chooser_info_->identifier)
3071 color_chooser_info_->chooser->SetSelectedColor(color);
3074 // This exists for render views that don't have a WebUI, but do have WebUI
3075 // bindings enabled.
3076 void WebContentsImpl::OnWebUISend(const GURL& source_url,
3077 const std::string& name,
3078 const base::ListValue& args) {
3079 if (delegate_)
3080 delegate_->WebUISend(this, source_url, name, args);
3083 #if defined(ENABLE_PLUGINS)
3084 void WebContentsImpl::OnPepperPluginHung(int plugin_child_id,
3085 const base::FilePath& path,
3086 bool is_hung) {
3087 UMA_HISTOGRAM_COUNTS("Pepper.PluginHung", 1);
3089 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3090 PluginHungStatusChanged(plugin_child_id, path, is_hung));
3093 void WebContentsImpl::OnPluginCrashed(const base::FilePath& plugin_path,
3094 base::ProcessId plugin_pid) {
3095 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3096 PluginCrashed(plugin_path, plugin_pid));
3099 void WebContentsImpl::OnRequestPpapiBrokerPermission(
3100 int routing_id,
3101 const GURL& url,
3102 const base::FilePath& plugin_path) {
3103 if (!delegate_) {
3104 OnPpapiBrokerPermissionResult(routing_id, false);
3105 return;
3108 if (!delegate_->RequestPpapiBrokerPermission(
3109 this, url, plugin_path,
3110 base::Bind(&WebContentsImpl::OnPpapiBrokerPermissionResult,
3111 base::Unretained(this), routing_id))) {
3112 NOTIMPLEMENTED();
3113 OnPpapiBrokerPermissionResult(routing_id, false);
3117 void WebContentsImpl::OnPpapiBrokerPermissionResult(int routing_id,
3118 bool result) {
3119 Send(new ViewMsg_PpapiBrokerPermissionResult(routing_id, result));
3122 void WebContentsImpl::OnBrowserPluginMessage(RenderFrameHost* render_frame_host,
3123 const IPC::Message& message) {
3124 // This creates a BrowserPluginEmbedder, which handles all the BrowserPlugin
3125 // specific messages for this WebContents. This means that any message from
3126 // a BrowserPlugin prior to this will be ignored.
3127 // For more info, see comment above classes BrowserPluginEmbedder and
3128 // BrowserPluginGuest.
3129 CHECK(!browser_plugin_embedder_.get());
3130 browser_plugin_embedder_.reset(BrowserPluginEmbedder::Create(this));
3131 browser_plugin_embedder_->OnMessageReceived(message, render_frame_host);
3133 #endif // defined(ENABLE_PLUGINS)
3135 void WebContentsImpl::OnDidDownloadImage(
3136 int id,
3137 int http_status_code,
3138 const GURL& image_url,
3139 const std::vector<SkBitmap>& bitmaps,
3140 const std::vector<gfx::Size>& original_bitmap_sizes) {
3141 if (bitmaps.size() != original_bitmap_sizes.size())
3142 return;
3144 ImageDownloadMap::iterator iter = image_download_map_.find(id);
3145 if (iter == image_download_map_.end()) {
3146 // Currently WebContents notifies us of ANY downloads so that it is
3147 // possible to get here.
3148 return;
3150 if (!iter->second.is_null()) {
3151 iter->second.Run(
3152 id, http_status_code, image_url, bitmaps, original_bitmap_sizes);
3154 image_download_map_.erase(id);
3157 void WebContentsImpl::OnUpdateFaviconURL(
3158 const std::vector<FaviconURL>& candidates) {
3159 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3160 DidUpdateFaviconURL(candidates));
3163 void WebContentsImpl::CreateAudioPowerSaveBlocker() {
3164 // ChromeOS has its own way of handling power save blocks for media.
3165 #if !defined(OS_CHROMEOS)
3166 DCHECK(!audio_power_save_blocker_);
3167 audio_power_save_blocker_ = PowerSaveBlocker::Create(
3168 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension, "Playing Audio");
3169 #endif
3172 void WebContentsImpl::CreateVideoPowerSaveBlocker() {
3173 // ChromeOS has its own way of handling power save blocks for media.
3174 #if !defined(OS_CHROMEOS)
3175 DCHECK(!video_power_save_blocker_);
3176 DCHECK(!active_video_players_.empty());
3177 video_power_save_blocker_ = PowerSaveBlocker::Create(
3178 PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep, "Playing Video");
3179 #if defined(OS_ANDROID)
3180 static_cast<PowerSaveBlockerImpl*>(video_power_save_blocker_.get())
3181 ->InitDisplaySleepBlocker(GetView()->GetNativeView());
3182 #endif
3183 #endif
3186 void WebContentsImpl::MaybeReleasePowerSaveBlockers() {
3187 // If there are no more audio players and we don't have audio stream
3188 // monitoring, release the audio power save blocker here instead of during
3189 // NotifyNavigationStateChanged().
3190 if (active_audio_players_.empty() &&
3191 !AudioStreamMonitor::monitoring_available()) {
3192 audio_power_save_blocker_.reset();
3195 // If there are no more video players, clear the video power save blocker.
3196 if (active_video_players_.empty())
3197 video_power_save_blocker_.reset();
3200 void WebContentsImpl::OnMediaPlayingNotification(int64 player_cookie,
3201 bool has_video,
3202 bool has_audio,
3203 bool is_remote) {
3204 // Ignore the videos playing remotely and don't hold the wake lock for the
3205 // screen.
3206 if (is_remote) return;
3208 if (has_audio) {
3209 AddMediaPlayerEntry(player_cookie, &active_audio_players_);
3211 // If we don't have audio stream monitoring, allocate the audio power save
3212 // blocker here instead of during NotifyNavigationStateChanged().
3213 if (!audio_power_save_blocker_ &&
3214 !AudioStreamMonitor::monitoring_available()) {
3215 CreateAudioPowerSaveBlocker();
3219 if (has_video) {
3220 AddMediaPlayerEntry(player_cookie, &active_video_players_);
3222 // If we're not hidden and have just created a player, create a blocker.
3223 if (!video_power_save_blocker_ && !IsHidden())
3224 CreateVideoPowerSaveBlocker();
3228 void WebContentsImpl::OnMediaPausedNotification(int64 player_cookie) {
3229 RemoveMediaPlayerEntry(player_cookie, &active_audio_players_);
3230 RemoveMediaPlayerEntry(player_cookie, &active_video_players_);
3231 MaybeReleasePowerSaveBlockers();
3234 void WebContentsImpl::OnFirstVisuallyNonEmptyPaint() {
3235 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3236 DidFirstVisuallyNonEmptyPaint());
3239 void WebContentsImpl::DidChangeVisibleSSLState() {
3240 if (delegate_)
3241 delegate_->VisibleSSLStateChanged(this);
3244 void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
3245 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3246 BeforeFormRepostWarningShow());
3249 void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
3250 Activate();
3251 if (delegate_)
3252 delegate_->ShowRepostFormWarningDialog(this);
3255 bool WebContentsImpl::HasAccessedInitialDocument() {
3256 return has_accessed_initial_document_;
3259 // Notifies the RenderWidgetHost instance about the fact that the page is
3260 // loading, or done loading.
3261 void WebContentsImpl::SetIsLoading(RenderViewHost* render_view_host,
3262 bool is_loading,
3263 bool to_different_document,
3264 LoadNotificationDetails* details) {
3265 if (is_loading == is_loading_)
3266 return;
3268 if (!is_loading) {
3269 load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
3270 base::string16());
3271 load_state_host_.clear();
3272 upload_size_ = 0;
3273 upload_position_ = 0;
3276 GetRenderManager()->SetIsLoading(is_loading);
3278 is_loading_ = is_loading;
3279 waiting_for_response_ = is_loading;
3280 is_load_to_different_document_ = to_different_document;
3282 if (delegate_)
3283 delegate_->LoadingStateChanged(this, to_different_document);
3284 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
3286 std::string url = (details ? details->url.possibly_invalid_spec() : "NULL");
3287 if (is_loading) {
3288 TRACE_EVENT_ASYNC_BEGIN1("browser,navigation", "WebContentsImpl Loading",
3289 this, "URL", url);
3290 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3291 DidStartLoading(render_view_host));
3292 } else {
3293 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
3294 this, "URL", url);
3295 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3296 DidStopLoading(render_view_host));
3299 // TODO(avi): Remove. http://crbug.com/170921
3300 int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
3301 NotificationDetails det = NotificationService::NoDetails();
3302 if (details)
3303 det = Details<LoadNotificationDetails>(details);
3304 NotificationService::current()->Notify(
3305 type, Source<NavigationController>(&controller_), det);
3308 void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point& extent) {
3309 RenderFrameHost* focused_frame = GetFocusedFrame();
3310 if (!focused_frame)
3311 return;
3313 focused_frame->Send(new InputMsg_MoveRangeSelectionExtent(
3314 focused_frame->GetRoutingID(), extent));
3317 void WebContentsImpl::SelectRange(const gfx::Point& base,
3318 const gfx::Point& extent) {
3319 RenderFrameHost* focused_frame = GetFocusedFrame();
3320 if (!focused_frame)
3321 return;
3323 focused_frame->Send(
3324 new InputMsg_SelectRange(focused_frame->GetRoutingID(), base, extent));
3327 void WebContentsImpl::UpdateMaxPageIDIfNecessary(RenderViewHost* rvh) {
3328 // If we are creating a RVH for a restored controller, then we need to make
3329 // sure the RenderView starts with a next_page_id_ larger than the number
3330 // of restored entries. This must be called before the RenderView starts
3331 // navigating (to avoid a race between the browser updating max_page_id and
3332 // the renderer updating next_page_id_). Because of this, we only call this
3333 // from CreateRenderView and allow that to notify the RenderView for us.
3334 int max_restored_page_id = controller_.GetMaxRestoredPageID();
3335 if (max_restored_page_id >
3336 GetMaxPageIDForSiteInstance(rvh->GetSiteInstance()))
3337 UpdateMaxPageIDForSiteInstance(rvh->GetSiteInstance(),
3338 max_restored_page_id);
3341 bool WebContentsImpl::UpdateTitleForEntry(NavigationEntryImpl* entry,
3342 const base::string16& title) {
3343 // For file URLs without a title, use the pathname instead. In the case of a
3344 // synthesized title, we don't want the update to count toward the "one set
3345 // per page of the title to history."
3346 base::string16 final_title;
3347 bool explicit_set;
3348 if (entry && entry->GetURL().SchemeIsFile() && title.empty()) {
3349 final_title = base::UTF8ToUTF16(entry->GetURL().ExtractFileName());
3350 explicit_set = false; // Don't count synthetic titles toward the set limit.
3351 } else {
3352 base::TrimWhitespace(title, base::TRIM_ALL, &final_title);
3353 explicit_set = true;
3356 // If a page is created via window.open and never navigated,
3357 // there will be no navigation entry. In this situation,
3358 // |page_title_when_no_navigation_entry_| will be used for page title.
3359 if (entry) {
3360 if (final_title == entry->GetTitle())
3361 return false; // Nothing changed, don't bother.
3363 entry->SetTitle(final_title);
3364 } else {
3365 if (page_title_when_no_navigation_entry_ == final_title)
3366 return false; // Nothing changed, don't bother.
3368 page_title_when_no_navigation_entry_ = final_title;
3371 // Lastly, set the title for the view.
3372 view_->SetPageTitle(final_title);
3374 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3375 TitleWasSet(entry, explicit_set));
3377 // TODO(avi): Remove. http://crbug.com/170921
3378 std::pair<NavigationEntry*, bool> details =
3379 std::make_pair(entry, explicit_set);
3380 NotificationService::current()->Notify(
3381 NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED,
3382 Source<WebContents>(this),
3383 Details<std::pair<NavigationEntry*, bool> >(&details));
3385 return true;
3388 void WebContentsImpl::SendLoadProgressChanged() {
3389 loading_last_progress_update_ = base::TimeTicks::Now();
3390 double progress = 0.0;
3391 int frame_count = 0;
3393 for (LoadingProgressMap::iterator it = loading_progresses_.begin();
3394 it != loading_progresses_.end();
3395 ++it) {
3396 progress += it->second;
3397 ++frame_count;
3399 if (frame_count == 0)
3400 return;
3401 progress /= frame_count;
3402 DCHECK(progress <= 1.0);
3404 if (progress <= loading_total_progress_)
3405 return;
3406 loading_total_progress_ = progress;
3408 if (delegate_)
3409 delegate_->LoadProgressChanged(this, progress);
3412 void WebContentsImpl::ResetLoadProgressState() {
3413 loading_progresses_.clear();
3414 loading_total_progress_ = 0.0;
3415 loading_weak_factory_.InvalidateWeakPtrs();
3416 loading_last_progress_update_ = base::TimeTicks();
3419 void WebContentsImpl::NotifyViewSwapped(RenderViewHost* old_host,
3420 RenderViewHost* new_host) {
3421 // After sending out a swap notification, we need to send a disconnect
3422 // notification so that clients that pick up a pointer to |this| can NULL the
3423 // pointer. See Bug 1230284.
3424 notify_disconnection_ = true;
3425 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3426 RenderViewHostChanged(old_host, new_host));
3428 // TODO(avi): Remove. http://crbug.com/170921
3429 std::pair<RenderViewHost*, RenderViewHost*> details =
3430 std::make_pair(old_host, new_host);
3431 NotificationService::current()->Notify(
3432 NOTIFICATION_RENDER_VIEW_HOST_CHANGED,
3433 Source<WebContents>(this),
3434 Details<std::pair<RenderViewHost*, RenderViewHost*> >(&details));
3436 // Ensure that the associated embedder gets cleared after a RenderViewHost
3437 // gets swapped, so we don't reuse the same embedder next time a
3438 // RenderViewHost is attached to this WebContents.
3439 RemoveBrowserPluginEmbedder();
3442 void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost* old_host,
3443 RenderFrameHost* new_host) {
3444 FOR_EACH_OBSERVER(WebContentsObserver,
3445 observers_,
3446 RenderFrameHostChanged(old_host, new_host));
3449 // TODO(avi): Remove this entire function because this notification is already
3450 // covered by two observer functions. http://crbug.com/170921
3451 void WebContentsImpl::NotifyDisconnected() {
3452 if (!notify_disconnection_)
3453 return;
3455 notify_disconnection_ = false;
3456 NotificationService::current()->Notify(
3457 NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
3458 Source<WebContents>(this),
3459 NotificationService::NoDetails());
3462 void WebContentsImpl::NotifyNavigationEntryCommitted(
3463 const LoadCommittedDetails& load_details) {
3464 FOR_EACH_OBSERVER(
3465 WebContentsObserver, observers_, NavigationEntryCommitted(load_details));
3468 bool WebContentsImpl::OnMessageReceived(RenderFrameHost* render_frame_host,
3469 const IPC::Message& message) {
3470 return OnMessageReceived(NULL, render_frame_host, message);
3473 const GURL& WebContentsImpl::GetMainFrameLastCommittedURL() const {
3474 return GetLastCommittedURL();
3477 void WebContentsImpl::RenderFrameCreated(RenderFrameHost* render_frame_host) {
3478 // Note this is only for subframes, the notification for the main frame
3479 // happens in RenderViewCreated.
3480 FOR_EACH_OBSERVER(WebContentsObserver,
3481 observers_,
3482 RenderFrameCreated(render_frame_host));
3483 SetAccessibilityModeOnFrame(accessibility_mode_, render_frame_host);
3486 void WebContentsImpl::RenderFrameDeleted(RenderFrameHost* render_frame_host) {
3487 ClearPowerSaveBlockers(render_frame_host);
3488 FOR_EACH_OBSERVER(WebContentsObserver,
3489 observers_,
3490 RenderFrameDeleted(render_frame_host));
3493 void WebContentsImpl::WorkerCrashed(RenderFrameHost* render_frame_host) {
3494 if (delegate_)
3495 delegate_->WorkerCrashed(this);
3498 void WebContentsImpl::ShowContextMenu(RenderFrameHost* render_frame_host,
3499 const ContextMenuParams& params) {
3500 ContextMenuParams context_menu_params(params);
3501 // Allow WebContentsDelegates to handle the context menu operation first.
3502 if (GetBrowserPluginGuest()) {
3503 WebContentsViewGuest* view_guest =
3504 static_cast<WebContentsViewGuest*>(GetView());
3505 context_menu_params = view_guest->ConvertContextMenuParams(params);
3507 if (delegate_ && delegate_->HandleContextMenu(context_menu_params))
3508 return;
3510 render_view_host_delegate_view_->ShowContextMenu(render_frame_host,
3511 context_menu_params);
3514 void WebContentsImpl::RunJavaScriptMessage(
3515 RenderFrameHost* render_frame_host,
3516 const base::string16& message,
3517 const base::string16& default_prompt,
3518 const GURL& frame_url,
3519 JavaScriptMessageType javascript_message_type,
3520 IPC::Message* reply_msg) {
3521 // Suppress JavaScript dialogs when requested. Also suppress messages when
3522 // showing an interstitial as it's shown over the previous page and we don't
3523 // want the hidden page's dialogs to interfere with the interstitial.
3524 bool suppress_this_message =
3525 static_cast<RenderFrameHostImpl*>(render_frame_host)->is_swapped_out() ||
3526 ShowingInterstitialPage() || !delegate_ ||
3527 delegate_->ShouldSuppressDialogs(this) ||
3528 !delegate_->GetJavaScriptDialogManager(this);
3530 if (!suppress_this_message) {
3531 std::string accept_lang = GetContentClient()->browser()->
3532 GetAcceptLangs(GetBrowserContext());
3533 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
3534 dialog_manager_->RunJavaScriptDialog(
3535 this,
3536 frame_url.GetOrigin(),
3537 accept_lang,
3538 javascript_message_type,
3539 message,
3540 default_prompt,
3541 base::Bind(&WebContentsImpl::OnDialogClosed,
3542 base::Unretained(this),
3543 render_frame_host->GetProcess()->GetID(),
3544 render_frame_host->GetRoutingID(),
3545 reply_msg,
3546 false),
3547 &suppress_this_message);
3550 if (suppress_this_message) {
3551 // If we are suppressing messages, just reply as if the user immediately
3552 // pressed "Cancel", passing true to |dialog_was_suppressed|.
3553 OnDialogClosed(render_frame_host->GetProcess()->GetID(),
3554 render_frame_host->GetRoutingID(), reply_msg,
3555 true, false, base::string16());
3558 // OnDialogClosed (two lines up) may have caused deletion of this object (see
3559 // http://crbug.com/288961 ). The only safe thing to do here is return.
3562 void WebContentsImpl::RunBeforeUnloadConfirm(
3563 RenderFrameHost* render_frame_host,
3564 const base::string16& message,
3565 bool is_reload,
3566 IPC::Message* reply_msg) {
3567 RenderFrameHostImpl* rfhi =
3568 static_cast<RenderFrameHostImpl*>(render_frame_host);
3569 if (delegate_)
3570 delegate_->WillRunBeforeUnloadConfirm();
3572 bool suppress_this_message =
3573 rfhi->rfh_state() != RenderFrameHostImpl::STATE_DEFAULT || !delegate_ ||
3574 delegate_->ShouldSuppressDialogs(this) ||
3575 !delegate_->GetJavaScriptDialogManager(this);
3576 if (suppress_this_message) {
3577 rfhi->JavaScriptDialogClosed(reply_msg, true, base::string16(), true);
3578 return;
3581 is_showing_before_unload_dialog_ = true;
3582 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
3583 dialog_manager_->RunBeforeUnloadDialog(
3584 this, message, is_reload,
3585 base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
3586 render_frame_host->GetProcess()->GetID(),
3587 render_frame_host->GetRoutingID(), reply_msg,
3588 false));
3591 WebContents* WebContentsImpl::GetAsWebContents() {
3592 return this;
3595 bool WebContentsImpl::IsNeverVisible() {
3596 if (!delegate_)
3597 return false;
3598 return delegate_->IsNeverVisible(this);
3601 #if defined(OS_WIN)
3602 gfx::NativeViewAccessible WebContentsImpl::GetParentNativeViewAccessible() {
3603 return accessible_parent_;
3605 #endif
3607 RenderViewHostDelegateView* WebContentsImpl::GetDelegateView() {
3608 return render_view_host_delegate_view_;
3611 RendererPreferences WebContentsImpl::GetRendererPrefs(
3612 BrowserContext* browser_context) const {
3613 return renderer_preferences_;
3616 gfx::Rect WebContentsImpl::GetRootWindowResizerRect() const {
3617 if (delegate_)
3618 return delegate_->GetRootWindowResizerRect();
3619 return gfx::Rect();
3622 void WebContentsImpl::RemoveBrowserPluginEmbedder() {
3623 if (browser_plugin_embedder_)
3624 browser_plugin_embedder_.reset();
3627 void WebContentsImpl::RenderViewCreated(RenderViewHost* render_view_host) {
3628 // Don't send notifications if we are just creating a swapped-out RVH for
3629 // the opener chain. These won't be used for view-source or WebUI, so it's
3630 // ok to return early.
3631 if (!static_cast<RenderViewHostImpl*>(render_view_host)->is_active())
3632 return;
3634 if (delegate_)
3635 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
3637 NotificationService::current()->Notify(
3638 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
3639 Source<WebContents>(this),
3640 Details<RenderViewHost>(render_view_host));
3642 // When we're creating views, we're still doing initial setup, so we always
3643 // use the pending Web UI rather than any possibly existing committed one.
3644 if (GetRenderManager()->pending_web_ui())
3645 GetRenderManager()->pending_web_ui()->RenderViewCreated(render_view_host);
3647 NavigationEntry* entry = controller_.GetPendingEntry();
3648 if (entry && entry->IsViewSourceMode()) {
3649 // Put the renderer in view source mode.
3650 render_view_host->Send(
3651 new ViewMsg_EnableViewSourceMode(render_view_host->GetRoutingID()));
3654 view_->RenderViewCreated(render_view_host);
3656 FOR_EACH_OBSERVER(
3657 WebContentsObserver, observers_, RenderViewCreated(render_view_host));
3659 // We tell the observers now instead of when the main RenderFrameHostImpl is
3660 // constructed because otherwise it would be too early (i.e. IPCs sent to the
3661 // frame would be dropped because it's not created yet).
3662 RenderFrameHost* main_frame = render_view_host->GetMainFrame();
3663 FOR_EACH_OBSERVER(
3664 WebContentsObserver, observers_, RenderFrameCreated(main_frame));
3665 SetAccessibilityModeOnFrame(accessibility_mode_, main_frame);
3667 DevToolsManager::GetInstance()->RenderViewCreated(this, render_view_host);
3670 void WebContentsImpl::RenderViewReady(RenderViewHost* rvh) {
3671 if (rvh != GetRenderViewHost()) {
3672 // Don't notify the world, since this came from a renderer in the
3673 // background.
3674 return;
3677 notify_disconnection_ = true;
3678 // TODO(avi): Remove. http://crbug.com/170921
3679 NotificationService::current()->Notify(
3680 NOTIFICATION_WEB_CONTENTS_CONNECTED,
3681 Source<WebContents>(this),
3682 NotificationService::NoDetails());
3684 bool was_crashed = IsCrashed();
3685 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
3687 // Restore the focus to the tab (otherwise the focus will be on the top
3688 // window).
3689 if (was_crashed && !FocusLocationBarByDefault() &&
3690 (!delegate_ || delegate_->ShouldFocusPageAfterCrash())) {
3691 view_->Focus();
3694 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewReady());
3697 void WebContentsImpl::RenderViewTerminated(RenderViewHost* rvh,
3698 base::TerminationStatus status,
3699 int error_code) {
3700 // TODO(nasko): This isn't ideal; the termination process should be handled by
3701 // RenderFrameDeleted(). See http://crbug.com/455943.
3702 ClearPowerSaveBlockers(rvh->GetMainFrame());
3704 if (rvh != GetRenderViewHost()) {
3705 // The pending page's RenderViewHost is gone.
3706 return;
3709 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
3710 // renderer may not have made a clean exit.
3711 if (IsFullscreenForCurrentTab())
3712 ExitFullscreenMode();
3714 // Cancel any visible dialogs so they are not left dangling over the sad tab.
3715 if (dialog_manager_)
3716 dialog_manager_->CancelActiveAndPendingDialogs(this);
3718 if (delegate_)
3719 delegate_->HideValidationMessage(this);
3721 SetIsLoading(rvh, false, true, NULL);
3722 NotifyDisconnected();
3723 SetIsCrashed(status, error_code);
3725 // Reset the loading progress. TODO(avi): What does it mean to have a
3726 // "renderer crash" when there is more than one renderer process serving a
3727 // webpage? Once this function is called at a more granular frame level, we
3728 // probably will need to more granularly reset the state here.
3729 ResetLoadProgressState();
3730 loading_frames_in_progress_ = 0;
3732 FOR_EACH_OBSERVER(WebContentsObserver,
3733 observers_,
3734 RenderProcessGone(GetCrashedStatus()));
3737 void WebContentsImpl::RenderViewDeleted(RenderViewHost* rvh) {
3738 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewDeleted(rvh));
3741 void WebContentsImpl::UpdateState(RenderViewHost* rvh,
3742 int32 page_id,
3743 const PageState& page_state) {
3744 // Ensure that this state update comes from a RenderViewHost that belongs to
3745 // this WebContents.
3746 // TODO(nasko): This should go through RenderFrameHost.
3747 // TODO(creis): We can't update state for cross-process subframes until we
3748 // have FrameNavigationEntries. Once we do, this should be a DCHECK.
3749 if (rvh->GetDelegate()->GetAsWebContents() != this)
3750 return;
3752 // We must be prepared to handle state updates for any page, these occur
3753 // when the user is scrolling and entering form data, as well as when we're
3754 // leaving a page, in which case our state may have already been moved to
3755 // the next page. The navigation controller will look up the appropriate
3756 // NavigationEntry and update it when it is notified via the delegate.
3758 int entry_index = controller_.GetEntryIndexWithPageID(
3759 rvh->GetSiteInstance(), page_id);
3760 if (entry_index < 0)
3761 return;
3762 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
3764 if (page_state == entry->GetPageState())
3765 return; // Nothing to update.
3766 entry->SetPageState(page_state);
3767 controller_.NotifyEntryChanged(entry, entry_index);
3770 void WebContentsImpl::UpdateTargetURL(RenderViewHost* render_view_host,
3771 const GURL& url) {
3772 if (fullscreen_widget_routing_id_ != MSG_ROUTING_NONE) {
3773 // If we're fullscreen only update the url if it's from the fullscreen
3774 // renderer.
3775 RenderWidgetHostView* fs = GetFullscreenRenderWidgetHostView();
3776 if (fs && fs->GetRenderWidgetHost() != render_view_host)
3777 return;
3779 if (delegate_)
3780 delegate_->UpdateTargetURL(this, url);
3783 void WebContentsImpl::Close(RenderViewHost* rvh) {
3784 #if defined(OS_MACOSX)
3785 // The UI may be in an event-tracking loop, such as between the
3786 // mouse-down and mouse-up in text selection or a button click.
3787 // Defer the close until after tracking is complete, so that we
3788 // don't free objects out from under the UI.
3789 // TODO(shess): This could get more fine-grained. For instance,
3790 // closing a tab in another window while selecting text in the
3791 // current window's Omnibox should be just fine.
3792 if (view_->IsEventTracking()) {
3793 view_->CloseTabAfterEventTracking();
3794 return;
3796 #endif
3798 // Ignore this if it comes from a RenderViewHost that we aren't showing.
3799 if (delegate_ && rvh == GetRenderViewHost())
3800 delegate_->CloseContents(this);
3803 void WebContentsImpl::SwappedOut(RenderFrameHost* rfh) {
3804 if (delegate_ && rfh->GetRenderViewHost() == GetRenderViewHost())
3805 delegate_->SwappedOut(this);
3808 void WebContentsImpl::DidDeferAfterResponseStarted(
3809 const TransitionLayerData& transition_data) {
3810 #if defined(OS_ANDROID)
3811 GetWebContentsAndroid()->DidDeferAfterResponseStarted(transition_data);
3812 #endif
3815 bool WebContentsImpl::WillHandleDeferAfterResponseStarted() {
3816 #if defined(OS_ANDROID)
3817 return GetWebContentsAndroid()->WillHandleDeferAfterResponseStarted();
3818 #else
3819 return false;
3820 #endif
3823 void WebContentsImpl::RequestMove(const gfx::Rect& new_bounds) {
3824 if (delegate_ && delegate_->IsPopupOrPanel(this))
3825 delegate_->MoveContents(this, new_bounds);
3828 void WebContentsImpl::DidStartLoading(RenderFrameHost* render_frame_host,
3829 bool to_different_document) {
3830 SetIsLoading(render_frame_host->GetRenderViewHost(), true,
3831 to_different_document, NULL);
3833 // Notify accessibility that the user is navigating away from the
3834 // current document.
3836 // TODO(dmazzoni): do this using a WebContentsObserver.
3837 FrameTreeNode* ftn = static_cast<RenderFrameHostImpl*>(render_frame_host)->
3838 frame_tree_node();
3839 BrowserAccessibilityManager* manager =
3840 ftn->current_frame_host()->browser_accessibility_manager();
3841 if (manager)
3842 manager->UserIsNavigatingAway();
3845 void WebContentsImpl::DidStopLoading(RenderFrameHost* render_frame_host) {
3846 scoped_ptr<LoadNotificationDetails> details;
3848 // Use the last committed entry rather than the active one, in case a
3849 // pending entry has been created.
3850 NavigationEntry* entry = controller_.GetLastCommittedEntry();
3851 Navigator* navigator = frame_tree_.root()->navigator();
3853 // An entry may not exist for a stop when loading an initial blank page or
3854 // if an iframe injected by script into a blank page finishes loading.
3855 if (entry) {
3856 base::TimeDelta elapsed =
3857 base::TimeTicks::Now() - navigator->GetCurrentLoadStart();
3859 details.reset(new LoadNotificationDetails(
3860 entry->GetVirtualURL(),
3861 entry->GetTransitionType(),
3862 elapsed,
3863 &controller_,
3864 controller_.GetCurrentEntryIndex()));
3867 SetIsLoading(render_frame_host->GetRenderViewHost(), false, true,
3868 details.get());
3871 void WebContentsImpl::DidCancelLoading() {
3872 controller_.DiscardNonCommittedEntries();
3874 // Update the URL display.
3875 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
3878 void WebContentsImpl::DidAccessInitialDocument() {
3879 has_accessed_initial_document_ = true;
3881 // We may have left a failed browser-initiated navigation in the address bar
3882 // to let the user edit it and try again. Clear it now that content might
3883 // show up underneath it.
3884 if (!IsLoading() && controller_.GetPendingEntry())
3885 controller_.DiscardPendingEntry();
3887 // Update the URL display.
3888 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
3891 void WebContentsImpl::DidDisownOpener(RenderFrameHost* render_frame_host) {
3892 // No action is necessary if the opener has already been cleared.
3893 if (!opener_)
3894 return;
3896 // Clear our opener so that future cross-process navigations don't have an
3897 // opener assigned.
3898 RemoveDestructionObserver(opener_);
3899 opener_ = NULL;
3901 // Notify all swapped out RenderViewHosts for this tab. This is important
3902 // in case we go back to them, or if another window in those processes tries
3903 // to access window.opener.
3904 GetRenderManager()->DidDisownOpener(render_frame_host);
3907 void WebContentsImpl::DocumentOnLoadCompleted(
3908 RenderFrameHost* render_frame_host) {
3909 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3910 DocumentOnLoadCompletedInMainFrame());
3912 // TODO(avi): Remove. http://crbug.com/170921
3913 NotificationService::current()->Notify(
3914 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
3915 Source<WebContents>(this),
3916 NotificationService::NoDetails());
3919 void WebContentsImpl::UpdateTitle(RenderFrameHost* render_frame_host,
3920 int32 page_id,
3921 const base::string16& title,
3922 base::i18n::TextDirection title_direction) {
3923 RenderViewHost* rvh = render_frame_host->GetRenderViewHost();
3925 // If we have a title, that's a pretty good indication that we've started
3926 // getting useful data.
3927 SetNotWaitingForResponse();
3929 // Try to find the navigation entry, which might not be the current one.
3930 // For example, it might be from a pending RVH for the pending entry.
3931 NavigationEntryImpl* entry = controller_.GetEntryWithPageID(
3932 rvh->GetSiteInstance(), page_id);
3934 // We can handle title updates when we don't have an entry in
3935 // UpdateTitleForEntry, but only if the update is from the current RVH.
3936 // TODO(avi): Change to make decisions based on the RenderFrameHost.
3937 if (!entry && rvh != GetRenderViewHost())
3938 return;
3940 // TODO(evan): make use of title_direction.
3941 // http://code.google.com/p/chromium/issues/detail?id=27094
3942 if (!UpdateTitleForEntry(entry, title))
3943 return;
3945 // Broadcast notifications when the UI should be updated.
3946 if (entry == controller_.GetEntryAtOffset(0))
3947 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
3950 void WebContentsImpl::UpdateEncoding(RenderFrameHost* render_frame_host,
3951 const std::string& encoding) {
3952 SetEncoding(encoding);
3955 void WebContentsImpl::DocumentAvailableInMainFrame(
3956 RenderViewHost* render_view_host) {
3957 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3958 DocumentAvailableInMainFrame());
3960 void WebContentsImpl::RouteCloseEvent(RenderViewHost* rvh) {
3961 // Tell the active RenderViewHost to run unload handlers and close, as long
3962 // as the request came from a RenderViewHost in the same BrowsingInstance.
3963 // In most cases, we receive this from a swapped out RenderViewHost.
3964 // It is possible to receive it from one that has just been swapped in,
3965 // in which case we might as well deliver the message anyway.
3966 if (rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()))
3967 GetRenderViewHost()->ClosePage();
3970 void WebContentsImpl::RouteMessageEvent(
3971 RenderViewHost* rvh,
3972 const ViewMsg_PostMessage_Params& params) {
3973 // Only deliver the message to the active RenderViewHost if the request
3974 // came from a RenderViewHost in the same BrowsingInstance or if this
3975 // WebContents is dedicated to a browser plugin guest.
3976 // Note: This check means that an embedder could theoretically receive a
3977 // postMessage from anyone (not just its own guests). However, this is
3978 // probably not a risk for apps since other pages won't have references
3979 // to App windows.
3980 if (!rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()) &&
3981 !GetBrowserPluginGuest() && !GetBrowserPluginEmbedder())
3982 return;
3984 ViewMsg_PostMessage_Params new_params(params);
3986 // If there is a source_routing_id, translate it to the routing ID for
3987 // the equivalent swapped out RVH in the target process. If we need
3988 // to create a swapped out RVH for the source tab, we create its opener
3989 // chain as well, since those will also be accessible to the target page.
3990 if (new_params.source_routing_id != MSG_ROUTING_NONE) {
3991 // Try to look up the WebContents for the source page.
3992 WebContentsImpl* source_contents = NULL;
3993 RenderViewHostImpl* source_rvh = RenderViewHostImpl::FromID(
3994 rvh->GetProcess()->GetID(), params.source_routing_id);
3995 if (source_rvh) {
3996 source_contents = static_cast<WebContentsImpl*>(
3997 source_rvh->GetDelegate()->GetAsWebContents());
4000 if (source_contents) {
4001 if (GetBrowserPluginGuest()) {
4002 // We create a swapped out RenderView for the embedder in the guest's
4003 // render process but we intentionally do not expose the embedder's
4004 // opener chain to it.
4005 new_params.source_routing_id =
4006 source_contents->CreateSwappedOutRenderView(GetSiteInstance());
4007 } else {
4008 new_params.source_routing_id =
4009 source_contents->CreateOpenerRenderViews(GetSiteInstance());
4011 } else {
4012 // We couldn't find it, so don't pass a source frame.
4013 new_params.source_routing_id = MSG_ROUTING_NONE;
4017 // In most cases, we receive this from a swapped out RenderViewHost.
4018 // It is possible to receive it from one that has just been swapped in,
4019 // in which case we might as well deliver the message anyway.
4020 if (!params.message_port_ids.empty()) {
4021 // Updating the message port information has to be done in the IO thread;
4022 // MessagePortMessageFilter::RouteMessageEventWithMessagePorts will send
4023 // ViewMsg_PostMessageEvent after it's done. Note that a trivial solution
4024 // would've been to post a task on the IO thread to do the IO-thread-bound
4025 // work, and make that post a task back to WebContentsImpl in the UI
4026 // thread. But we cannot do that, since there's nothing to guarantee that
4027 // WebContentsImpl stays alive during the round trip.
4028 scoped_refptr<MessagePortMessageFilter> message_port_message_filter(
4029 static_cast<RenderProcessHostImpl*>(GetRenderProcessHost())
4030 ->message_port_message_filter());
4031 BrowserThread::PostTask(
4032 BrowserThread::IO, FROM_HERE,
4033 base::Bind(&MessagePortMessageFilter::RouteMessageEventWithMessagePorts,
4034 message_port_message_filter, GetRoutingID(), new_params));
4035 } else {
4036 Send(new ViewMsg_PostMessageEvent(GetRoutingID(), new_params));
4040 bool WebContentsImpl::AddMessageToConsole(int32 level,
4041 const base::string16& message,
4042 int32 line_no,
4043 const base::string16& source_id) {
4044 if (!delegate_)
4045 return false;
4046 return delegate_->AddMessageToConsole(this, level, message, line_no,
4047 source_id);
4050 int WebContentsImpl::CreateSwappedOutRenderView(
4051 SiteInstance* instance) {
4052 int render_view_routing_id = MSG_ROUTING_NONE;
4053 GetRenderManager()->CreateRenderFrame(
4054 instance, nullptr, MSG_ROUTING_NONE,
4055 CREATE_RF_SWAPPED_OUT | CREATE_RF_FOR_MAIN_FRAME_NAVIGATION |
4056 CREATE_RF_HIDDEN,
4057 &render_view_routing_id);
4058 return render_view_routing_id;
4061 void WebContentsImpl::OnUserGesture() {
4062 // Notify observers.
4063 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetUserGesture());
4065 ResourceDispatcherHostImpl* rdh = ResourceDispatcherHostImpl::Get();
4066 if (rdh) // NULL in unittests.
4067 rdh->OnUserGesture(this);
4070 void WebContentsImpl::OnIgnoredUIEvent() {
4071 // Notify observers.
4072 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetIgnoredUIEvent());
4075 void WebContentsImpl::RendererUnresponsive(RenderViewHost* render_view_host) {
4076 // Don't show hung renderer dialog for a swapped out RVH.
4077 if (render_view_host != GetRenderViewHost())
4078 return;
4080 RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(render_view_host);
4081 RenderFrameHostImpl* rfhi =
4082 static_cast<RenderFrameHostImpl*>(rvhi->GetMainFrame());
4084 // Ignore renderer unresponsive event if debugger is attached to the tab
4085 // since the event may be a result of the renderer sitting on a breakpoint.
4086 // See http://crbug.com/65458
4087 if (DevToolsAgentHost::IsDebuggerAttached(this))
4088 return;
4090 if (rfhi->IsWaitingForBeforeUnloadACK() ||
4091 rfhi->IsWaitingForUnloadACK()) {
4092 // Hang occurred while firing the beforeunload/unload handler.
4093 // Pretend the handler fired so tab closing continues as if it had.
4094 frame_tree_.ForEach(base::Bind(
4095 &EnableSuddenTermination, rvhi->GetSiteInstance()->GetId()));
4097 if (!GetRenderManager()->ShouldCloseTabOnUnresponsiveRenderer())
4098 return;
4100 // If the tab hangs in the beforeunload/unload handler there's really
4101 // nothing we can do to recover. If the hang is in the beforeunload handler,
4102 // pretend the beforeunload listeners have all fired and allow the delegate
4103 // to continue closing; the user will not have the option of cancelling the
4104 // close. Otherwise, pretend the unload listeners have all fired and close
4105 // the tab.
4106 bool close = true;
4107 if (rfhi->IsWaitingForBeforeUnloadACK() && delegate_) {
4108 delegate_->BeforeUnloadFired(this, true, &close);
4110 if (close)
4111 Close(rvhi);
4112 return;
4115 if (!GetRenderViewHostImpl() || !GetRenderViewHostImpl()->IsRenderViewLive())
4116 return;
4118 if (delegate_)
4119 delegate_->RendererUnresponsive(this);
4122 void WebContentsImpl::RendererResponsive(RenderViewHost* render_view_host) {
4123 if (delegate_)
4124 delegate_->RendererResponsive(this);
4127 void WebContentsImpl::LoadStateChanged(
4128 const GURL& url,
4129 const net::LoadStateWithParam& load_state,
4130 uint64 upload_position,
4131 uint64 upload_size) {
4132 load_state_ = load_state;
4133 upload_position_ = upload_position;
4134 upload_size_ = upload_size;
4135 load_state_host_ = net::IDNToUnicode(url.host(),
4136 GetContentClient()->browser()->GetAcceptLangs(
4137 GetBrowserContext()));
4138 if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
4139 SetNotWaitingForResponse();
4140 if (IsLoading()) {
4141 NotifyNavigationStateChanged(static_cast<InvalidateTypes>(
4142 INVALIDATE_TYPE_LOAD | INVALIDATE_TYPE_TAB));
4146 void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
4147 bool proceed, const base::TimeTicks& proceed_time,
4148 bool* proceed_to_fire_unload) {
4149 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4150 BeforeUnloadFired(proceed_time));
4151 if (delegate_)
4152 delegate_->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
4153 // Note: |this| might be deleted at this point.
4156 void WebContentsImpl::RenderProcessGoneFromRenderManager(
4157 RenderViewHost* render_view_host) {
4158 DCHECK(crashed_status_ != base::TERMINATION_STATUS_STILL_RUNNING);
4159 RenderViewTerminated(render_view_host, crashed_status_, crashed_error_code_);
4162 void WebContentsImpl::UpdateRenderViewSizeForRenderManager() {
4163 // TODO(brettw) this is a hack. See WebContentsView::SizeContents.
4164 gfx::Size size = GetSizeForNewRenderView();
4165 // 0x0 isn't a valid window size (minimal window size is 1x1) but it may be
4166 // here during container initialization and normal window size will be set
4167 // later. In case of tab duplication this resizing to 0x0 prevents setting
4168 // normal size later so just ignore it.
4169 if (!size.IsEmpty())
4170 view_->SizeContents(size);
4173 void WebContentsImpl::CancelModalDialogsForRenderManager() {
4174 // We need to cancel modal dialogs when doing a process swap, since the load
4175 // deferrer would prevent us from swapping out.
4176 if (dialog_manager_)
4177 dialog_manager_->CancelActiveAndPendingDialogs(this);
4180 void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost* old_host,
4181 RenderFrameHost* new_host,
4182 bool is_main_frame) {
4183 if (is_main_frame) {
4184 NotifyViewSwapped(old_host ? old_host->GetRenderViewHost() : NULL,
4185 new_host->GetRenderViewHost());
4187 // Make sure the visible RVH reflects the new delegate's preferences.
4188 if (delegate_)
4189 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
4191 view_->RenderViewSwappedIn(new_host->GetRenderViewHost());
4194 NotifyFrameSwapped(old_host, new_host);
4197 int WebContentsImpl::CreateOpenerRenderViewsForRenderManager(
4198 SiteInstance* instance) {
4199 if (!opener_)
4200 return MSG_ROUTING_NONE;
4202 // Recursively create RenderViews for anything else in the opener chain.
4203 return opener_->CreateOpenerRenderViews(instance);
4206 int WebContentsImpl::CreateOpenerRenderViews(SiteInstance* instance) {
4207 int opener_route_id = MSG_ROUTING_NONE;
4209 // If this tab has an opener, ensure it has a RenderView in the given
4210 // SiteInstance as well.
4211 if (opener_)
4212 opener_route_id = opener_->CreateOpenerRenderViews(instance);
4214 // If any of the renderers (current, pending, or swapped out) for this
4215 // WebContents has the same SiteInstance, use it.
4216 if (GetRenderManager()->current_host()->GetSiteInstance() == instance)
4217 return GetRenderManager()->current_host()->GetRoutingID();
4219 if (GetRenderManager()->pending_render_view_host() &&
4220 GetRenderManager()->pending_render_view_host()->GetSiteInstance() ==
4221 instance)
4222 return GetRenderManager()->pending_render_view_host()->GetRoutingID();
4224 RenderViewHostImpl* rvh = GetRenderManager()->GetSwappedOutRenderViewHost(
4225 instance);
4226 if (rvh)
4227 return rvh->GetRoutingID();
4229 // Create a swapped out RenderView in the given SiteInstance if none exists,
4230 // setting its opener to the given route_id. Return the new view's route_id.
4231 int render_view_routing_id = MSG_ROUTING_NONE;
4232 GetRenderManager()->CreateRenderFrame(instance, nullptr, opener_route_id,
4233 CREATE_RF_FOR_MAIN_FRAME_NAVIGATION |
4234 CREATE_RF_SWAPPED_OUT |
4235 CREATE_RF_HIDDEN,
4236 &render_view_routing_id);
4237 return render_view_routing_id;
4240 NavigationControllerImpl& WebContentsImpl::GetControllerForRenderManager() {
4241 return GetController();
4244 scoped_ptr<WebUIImpl> WebContentsImpl::CreateWebUIForRenderManager(
4245 const GURL& url) {
4246 return scoped_ptr<WebUIImpl>(static_cast<WebUIImpl*>(CreateWebUI(url)));
4249 NavigationEntry*
4250 WebContentsImpl::GetLastCommittedNavigationEntryForRenderManager() {
4251 return controller_.GetLastCommittedEntry();
4254 bool WebContentsImpl::CreateRenderViewForRenderManager(
4255 RenderViewHost* render_view_host,
4256 int opener_route_id,
4257 int proxy_routing_id,
4258 bool for_main_frame_navigation) {
4259 TRACE_EVENT0("browser,navigation",
4260 "WebContentsImpl::CreateRenderViewForRenderManager");
4261 // Can be NULL during tests.
4262 RenderWidgetHostViewBase* rwh_view;
4263 // TODO(kenrb): RenderWidgetHostViewChildFrame special casing is temporary
4264 // until RenderWidgetHost is attached to RenderFrameHost. We need to special
4265 // case this because RWH is still a base class of RenderViewHost, and child
4266 // frame RWHVs are unique in that they do not have their own WebContents.
4267 if (!for_main_frame_navigation) {
4268 RenderWidgetHostViewChildFrame* rwh_view_child =
4269 new RenderWidgetHostViewChildFrame(render_view_host);
4270 rwh_view = rwh_view_child;
4271 } else {
4272 rwh_view = view_->CreateViewForWidget(render_view_host, false);
4275 // Now that the RenderView has been created, we need to tell it its size.
4276 if (rwh_view)
4277 rwh_view->SetSize(GetSizeForNewRenderView());
4279 // Make sure we use the correct starting page_id in the new RenderView.
4280 UpdateMaxPageIDIfNecessary(render_view_host);
4281 int32 max_page_id =
4282 GetMaxPageIDForSiteInstance(render_view_host->GetSiteInstance());
4284 if (!static_cast<RenderViewHostImpl*>(
4285 render_view_host)->CreateRenderView(base::string16(),
4286 opener_route_id,
4287 proxy_routing_id,
4288 max_page_id,
4289 created_with_opener_)) {
4290 return false;
4293 SetHistoryOffsetAndLengthForView(render_view_host,
4294 controller_.GetLastCommittedEntryIndex(),
4295 controller_.GetEntryCount());
4297 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
4298 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
4299 // linux. See crbug.com/83941.
4300 if (rwh_view) {
4301 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
4302 render_widget_host->WasResized();
4304 #endif
4306 return true;
4309 bool WebContentsImpl::CreateRenderFrameForRenderManager(
4310 RenderFrameHost* render_frame_host,
4311 int parent_routing_id,
4312 int proxy_routing_id) {
4313 TRACE_EVENT0("browser,navigation",
4314 "WebContentsImpl::CreateRenderFrameForRenderManager");
4316 RenderFrameHostImpl* rfh =
4317 static_cast<RenderFrameHostImpl*>(render_frame_host);
4318 if (!rfh->CreateRenderFrame(parent_routing_id, proxy_routing_id))
4319 return false;
4321 // TODO(nasko): When RenderWidgetHost is owned by RenderFrameHost, the passed
4322 // RenderFrameHost will have to be associated with the appropriate
4323 // RenderWidgetHostView or a new one should be created here.
4325 return true;
4328 #if defined(OS_ANDROID)
4330 base::android::ScopedJavaLocalRef<jobject>
4331 WebContentsImpl::GetJavaWebContents() {
4332 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
4333 return GetWebContentsAndroid()->GetJavaObject();
4336 WebContentsAndroid* WebContentsImpl::GetWebContentsAndroid() {
4337 WebContentsAndroid* web_contents_android =
4338 static_cast<WebContentsAndroid*>(GetUserData(kWebContentsAndroidKey));
4339 if (!web_contents_android) {
4340 web_contents_android = new WebContentsAndroid(this);
4341 SetUserData(kWebContentsAndroidKey, web_contents_android);
4343 return web_contents_android;
4346 bool WebContentsImpl::CreateRenderViewForInitialEmptyDocument() {
4347 return CreateRenderViewForRenderManager(GetRenderViewHost(),
4348 MSG_ROUTING_NONE,
4349 MSG_ROUTING_NONE,
4350 true);
4353 #elif defined(OS_MACOSX)
4355 void WebContentsImpl::SetAllowOtherViews(bool allow) {
4356 view_->SetAllowOtherViews(allow);
4359 bool WebContentsImpl::GetAllowOtherViews() {
4360 return view_->GetAllowOtherViews();
4363 #endif
4365 void WebContentsImpl::OnDialogClosed(int render_process_id,
4366 int render_frame_id,
4367 IPC::Message* reply_msg,
4368 bool dialog_was_suppressed,
4369 bool success,
4370 const base::string16& user_input) {
4371 RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(render_process_id,
4372 render_frame_id);
4373 last_dialog_suppressed_ = dialog_was_suppressed;
4375 if (is_showing_before_unload_dialog_ && !success) {
4376 // If a beforeunload dialog is canceled, we need to stop the throbber from
4377 // spinning, since we forced it to start spinning in Navigate.
4378 if (rfh)
4379 DidStopLoading(rfh);
4380 controller_.DiscardNonCommittedEntries();
4382 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4383 BeforeUnloadDialogCancelled());
4386 is_showing_before_unload_dialog_ = false;
4387 if (rfh) {
4388 rfh->JavaScriptDialogClosed(reply_msg, success, user_input,
4389 dialog_was_suppressed);
4390 } else {
4391 // Don't leak the sync IPC reply if the RFH or process is gone.
4392 delete reply_msg;
4396 void WebContentsImpl::SetEncoding(const std::string& encoding) {
4397 if (encoding == last_reported_encoding_)
4398 return;
4399 last_reported_encoding_ = encoding;
4401 canonical_encoding_ = GetContentClient()->browser()->
4402 GetCanonicalEncodingNameByAliasName(encoding);
4405 bool WebContentsImpl::IsHidden() {
4406 return capturer_count_ == 0 && !should_normally_be_visible_;
4409 RenderFrameHostManager* WebContentsImpl::GetRenderManager() const {
4410 return frame_tree_.root()->render_manager();
4413 RenderViewHostImpl* WebContentsImpl::GetRenderViewHostImpl() {
4414 return static_cast<RenderViewHostImpl*>(GetRenderViewHost());
4417 BrowserPluginGuest* WebContentsImpl::GetBrowserPluginGuest() const {
4418 return browser_plugin_guest_.get();
4421 void WebContentsImpl::SetBrowserPluginGuest(BrowserPluginGuest* guest) {
4422 CHECK(!browser_plugin_guest_);
4423 browser_plugin_guest_.reset(guest);
4426 BrowserPluginEmbedder* WebContentsImpl::GetBrowserPluginEmbedder() const {
4427 return browser_plugin_embedder_.get();
4430 void WebContentsImpl::ClearPowerSaveBlockers(
4431 RenderFrameHost* render_frame_host) {
4432 RemoveAllMediaPlayerEntries(render_frame_host, &active_audio_players_);
4433 RemoveAllMediaPlayerEntries(render_frame_host, &active_video_players_);
4434 MaybeReleasePowerSaveBlockers();
4437 void WebContentsImpl::ClearAllPowerSaveBlockers() {
4438 active_audio_players_.clear();
4439 active_video_players_.clear();
4440 audio_power_save_blocker_.reset();
4441 video_power_save_blocker_.reset();
4444 gfx::Size WebContentsImpl::GetSizeForNewRenderView() {
4445 gfx::Size size;
4446 if (delegate_)
4447 size = delegate_->GetSizeForNewRenderView(this);
4448 if (size.IsEmpty())
4449 size = GetContainerBounds().size();
4450 return size;
4453 void WebContentsImpl::OnFrameRemoved(RenderFrameHost* render_frame_host) {
4454 FOR_EACH_OBSERVER(
4455 WebContentsObserver, observers_, FrameDeleted(render_frame_host));
4458 void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size& old_size) {
4459 if (!delegate_)
4460 return;
4461 const gfx::Size new_size = GetPreferredSize();
4462 if (new_size != old_size)
4463 delegate_->UpdatePreferredSize(this, new_size);
4466 void WebContentsImpl::AddMediaPlayerEntry(int64 player_cookie,
4467 ActiveMediaPlayerMap* player_map) {
4468 if (!HasValidFrameSource())
4469 return;
4471 const uintptr_t key =
4472 reinterpret_cast<uintptr_t>(render_frame_message_source_);
4473 DCHECK(std::find((*player_map)[key].begin(),
4474 (*player_map)[key].end(),
4475 player_cookie) == (*player_map)[key].end());
4476 (*player_map)[key].push_back(player_cookie);
4479 void WebContentsImpl::RemoveMediaPlayerEntry(int64 player_cookie,
4480 ActiveMediaPlayerMap* player_map) {
4481 if (!HasValidFrameSource())
4482 return;
4484 const uintptr_t key =
4485 reinterpret_cast<uintptr_t>(render_frame_message_source_);
4486 ActiveMediaPlayerMap::iterator it = player_map->find(key);
4487 if (it == player_map->end())
4488 return;
4490 // Remove the player.
4491 PlayerList::iterator player_it =
4492 std::find(it->second.begin(), it->second.end(), player_cookie);
4493 if (player_it != it->second.end())
4494 it->second.erase(player_it);
4496 // If there are no players left, remove the map entry.
4497 if (it->second.empty())
4498 player_map->erase(it);
4501 void WebContentsImpl::RemoveAllMediaPlayerEntries(
4502 RenderFrameHost* render_frame_host,
4503 ActiveMediaPlayerMap* player_map) {
4504 ActiveMediaPlayerMap::iterator it =
4505 player_map->find(reinterpret_cast<uintptr_t>(render_frame_host));
4506 if (it == player_map->end())
4507 return;
4508 player_map->erase(it);
4511 void WebContentsImpl::ResumeResponseDeferredAtStart() {
4512 FrameTreeNode* node = frame_tree_.root();
4513 node->render_manager()->ResumeResponseDeferredAtStart();
4516 void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable) {
4517 force_disable_overscroll_content_ = force_disable;
4518 if (view_)
4519 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
4522 } // namespace content