Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / content / browser / web_contents / web_contents_impl.cc
blob951652aec614ea3cea69b3af2041af3aea9cc8ae
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/location.h"
12 #include "base/logging.h"
13 #include "base/metrics/histogram.h"
14 #include "base/process/process.h"
15 #include "base/profiler/scoped_tracker.h"
16 #include "base/single_thread_task_runner.h"
17 #include "base/strings/string16.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/thread_task_runner_handle.h"
22 #include "base/time/time.h"
23 #include "base/trace_event/trace_event.h"
24 #include "components/mime_util/mime_util.h"
25 #include "content/browser/accessibility/accessibility_mode_helper.h"
26 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
27 #include "content/browser/bad_message.h"
28 #include "content/browser/browser_plugin/browser_plugin_embedder.h"
29 #include "content/browser/browser_plugin/browser_plugin_guest.h"
30 #include "content/browser/child_process_security_policy_impl.h"
31 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
32 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
33 #include "content/browser/download/download_stats.h"
34 #include "content/browser/download/mhtml_generation_manager.h"
35 #include "content/browser/download/save_package.h"
36 #include "content/browser/frame_host/cross_process_frame_connector.h"
37 #include "content/browser/frame_host/interstitial_page_impl.h"
38 #include "content/browser/frame_host/navigation_entry_impl.h"
39 #include "content/browser/frame_host/navigator_impl.h"
40 #include "content/browser/frame_host/render_frame_host_impl.h"
41 #include "content/browser/frame_host/render_widget_host_view_child_frame.h"
42 #include "content/browser/geolocation/geolocation_service_context.h"
43 #include "content/browser/host_zoom_map_impl.h"
44 #include "content/browser/loader/resource_dispatcher_host_impl.h"
45 #include "content/browser/manifest/manifest_manager_host.h"
46 #include "content/browser/media/audio_stream_monitor.h"
47 #include "content/browser/media/capture/web_contents_audio_muter.h"
48 #include "content/browser/message_port_message_filter.h"
49 #include "content/browser/plugin_content_origin_whitelist.h"
50 #include "content/browser/power_save_blocker_impl.h"
51 #include "content/browser/renderer_host/render_process_host_impl.h"
52 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
53 #include "content/browser/renderer_host/render_view_host_impl.h"
54 #include "content/browser/renderer_host/render_widget_host_impl.h"
55 #include "content/browser/renderer_host/render_widget_host_view_base.h"
56 #include "content/browser/screen_orientation/screen_orientation_dispatcher_host_impl.h"
57 #include "content/browser/site_instance_impl.h"
58 #include "content/browser/web_contents/web_contents_view_guest.h"
59 #include "content/browser/webui/generic_handler.h"
60 #include "content/browser/webui/web_ui_controller_factory_registry.h"
61 #include "content/browser/webui/web_ui_impl.h"
62 #include "content/common/browser_plugin/browser_plugin_constants.h"
63 #include "content/common/browser_plugin/browser_plugin_messages.h"
64 #include "content/common/frame_messages.h"
65 #include "content/common/input_messages.h"
66 #include "content/common/ssl_status_serialization.h"
67 #include "content/common/view_messages.h"
68 #include "content/public/browser/ax_event_notification_details.h"
69 #include "content/public/browser/browser_context.h"
70 #include "content/public/browser/browser_plugin_guest_manager.h"
71 #include "content/public/browser/content_browser_client.h"
72 #include "content/public/browser/devtools_agent_host.h"
73 #include "content/public/browser/download_manager.h"
74 #include "content/public/browser/download_url_parameters.h"
75 #include "content/public/browser/invalidate_type.h"
76 #include "content/public/browser/javascript_dialog_manager.h"
77 #include "content/public/browser/load_from_memory_cache_details.h"
78 #include "content/public/browser/load_notification_details.h"
79 #include "content/public/browser/navigation_details.h"
80 #include "content/public/browser/notification_details.h"
81 #include "content/public/browser/notification_service.h"
82 #include "content/public/browser/render_widget_host_iterator.h"
83 #include "content/public/browser/resource_request_details.h"
84 #include "content/public/browser/screen_orientation_dispatcher_host.h"
85 #include "content/public/browser/security_style_explanations.h"
86 #include "content/public/browser/storage_partition.h"
87 #include "content/public/browser/user_metrics.h"
88 #include "content/public/browser/web_contents_delegate.h"
89 #include "content/public/browser/web_contents_observer.h"
90 #include "content/public/common/bindings_policy.h"
91 #include "content/public/common/content_constants.h"
92 #include "content/public/common/content_switches.h"
93 #include "content/public/common/page_zoom.h"
94 #include "content/public/common/result_codes.h"
95 #include "content/public/common/security_style.h"
96 #include "content/public/common/url_constants.h"
97 #include "content/public/common/url_utils.h"
98 #include "content/public/common/web_preferences.h"
99 #include "mojo/common/url_type_converters.h"
100 #include "mojo/converters/geometry/geometry_type_converters.h"
101 #include "net/base/net_util.h"
102 #include "net/http/http_cache.h"
103 #include "net/http/http_transaction_factory.h"
104 #include "net/url_request/url_request_context.h"
105 #include "net/url_request/url_request_context_getter.h"
106 #include "skia/public/type_converters.h"
107 #include "third_party/skia/include/core/SkBitmap.h"
108 #include "ui/base/layout.h"
109 #include "ui/gfx/display.h"
110 #include "ui/gfx/screen.h"
111 #include "ui/gl/gl_switches.h"
113 #if defined(ENABLE_BROWSER_CDMS)
114 #include "content/browser/media/media_web_contents_observer.h"
115 #endif
117 #if defined(OS_ANDROID)
118 #include "content/browser/android/content_video_view.h"
119 #include "content/browser/android/date_time_chooser_android.h"
120 #include "content/browser/android/media_players_observer.h"
121 #include "content/browser/media/android/media_session.h"
122 #include "content/browser/web_contents/web_contents_android.h"
123 #endif
125 #if defined(OS_MACOSX)
126 #include "base/mac/foundation_util.h"
127 #endif
129 namespace content {
130 namespace {
132 const int kMinimumDelayBetweenLoadingUpdatesMS = 100;
133 const char kDotGoogleDotCom[] = ".google.com";
135 #if defined(OS_ANDROID)
136 const char kWebContentsAndroidKey[] = "web_contents_android";
137 #endif // OS_ANDROID
139 base::LazyInstance<std::vector<WebContentsImpl::CreatedCallback> >
140 g_created_callbacks = LAZY_INSTANCE_INITIALIZER;
142 static void DidDownloadImage(const WebContents::ImageDownloadCallback& callback,
143 int id,
144 const GURL& image_url,
145 image_downloader::DownloadResultPtr result) {
146 DCHECK(result);
148 const std::vector<SkBitmap> images =
149 result->images.To<std::vector<SkBitmap>>();
150 const std::vector<gfx::Size> original_image_sizes =
151 result->original_image_sizes.To<std::vector<gfx::Size>>();
153 callback.Run(id, result->http_status_code, image_url, images,
154 original_image_sizes);
157 void NotifyCacheOnIO(
158 scoped_refptr<net::URLRequestContextGetter> request_context,
159 const GURL& url,
160 const std::string& http_method) {
161 net::HttpCache* cache = request_context->GetURLRequestContext()->
162 http_transaction_factory()->GetCache();
163 if (cache)
164 cache->OnExternalCacheHit(url, http_method);
167 // Helper function for retrieving all the sites in a frame tree.
168 bool CollectSites(BrowserContext* context,
169 std::set<GURL>* sites,
170 FrameTreeNode* node) {
171 sites->insert(SiteInstance::GetSiteForURL(context, node->current_url()));
172 return true;
175 bool FindMatchingProcess(int render_process_id,
176 bool* did_match_process,
177 FrameTreeNode* node) {
178 if (node->current_frame_host()->GetProcess()->GetID() == render_process_id) {
179 *did_match_process = true;
180 return false;
182 return true;
185 bool ForEachFrameInternal(
186 const base::Callback<void(RenderFrameHost*)>& on_frame,
187 FrameTreeNode* node) {
188 on_frame.Run(node->current_frame_host());
189 return true;
192 bool ForEachPendingFrameInternal(
193 const base::Callback<void(RenderFrameHost*)>& on_frame,
194 FrameTreeNode* node) {
195 RenderFrameHost* pending_frame_host =
196 node->render_manager()->pending_frame_host();
197 if (pending_frame_host)
198 on_frame.Run(pending_frame_host);
199 return true;
202 void SendToAllFramesInternal(IPC::Message* message, RenderFrameHost* rfh) {
203 IPC::Message* message_copy = new IPC::Message(*message);
204 message_copy->set_routing_id(rfh->GetRoutingID());
205 rfh->Send(message_copy);
208 void AddRenderWidgetHostViewToSet(std::set<RenderWidgetHostView*>* set,
209 RenderFrameHost* rfh) {
210 RenderWidgetHostView* rwhv = static_cast<RenderFrameHostImpl*>(rfh)
211 ->frame_tree_node()
212 ->render_manager()
213 ->GetRenderWidgetHostView();
214 set->insert(rwhv);
217 void SetAccessibilityModeOnFrame(AccessibilityMode mode,
218 RenderFrameHost* frame_host) {
219 static_cast<RenderFrameHostImpl*>(frame_host)->SetAccessibilityMode(mode);
222 void ResetAccessibility(RenderFrameHost* rfh) {
223 static_cast<RenderFrameHostImpl*>(rfh)->AccessibilityReset();
226 } // namespace
228 WebContents* WebContents::Create(const WebContents::CreateParams& params) {
229 FrameTreeNode* opener_node = nullptr;
230 if (params.opener_render_frame_id != MSG_ROUTING_NONE) {
231 RenderFrameHostImpl* opener_rfh = RenderFrameHostImpl::FromID(
232 params.opener_render_process_id, params.opener_render_frame_id);
233 if (opener_rfh)
234 opener_node = opener_rfh->frame_tree_node();
236 return WebContentsImpl::CreateWithOpener(params, opener_node);
239 WebContents* WebContents::CreateWithSessionStorage(
240 const WebContents::CreateParams& params,
241 const SessionStorageNamespaceMap& session_storage_namespace_map) {
242 WebContentsImpl* new_contents = new WebContentsImpl(params.browser_context);
244 for (SessionStorageNamespaceMap::const_iterator it =
245 session_storage_namespace_map.begin();
246 it != session_storage_namespace_map.end();
247 ++it) {
248 new_contents->GetController()
249 .SetSessionStorageNamespace(it->first, it->second.get());
252 new_contents->Init(params);
253 return new_contents;
256 void WebContentsImpl::FriendZone::AddCreatedCallbackForTesting(
257 const CreatedCallback& callback) {
258 g_created_callbacks.Get().push_back(callback);
261 void WebContentsImpl::FriendZone::RemoveCreatedCallbackForTesting(
262 const CreatedCallback& callback) {
263 for (size_t i = 0; i < g_created_callbacks.Get().size(); ++i) {
264 if (g_created_callbacks.Get().at(i).Equals(callback)) {
265 g_created_callbacks.Get().erase(g_created_callbacks.Get().begin() + i);
266 return;
271 WebContents* WebContents::FromRenderViewHost(const RenderViewHost* rvh) {
272 return rvh->GetDelegate()->GetAsWebContents();
275 WebContents* WebContents::FromRenderFrameHost(RenderFrameHost* rfh) {
276 RenderFrameHostImpl* rfh_impl = static_cast<RenderFrameHostImpl*>(rfh);
277 if (!rfh_impl)
278 return NULL;
279 return rfh_impl->delegate()->GetAsWebContents();
282 // WebContentsImpl::DestructionObserver ----------------------------------------
284 class WebContentsImpl::DestructionObserver : public WebContentsObserver {
285 public:
286 DestructionObserver(WebContentsImpl* owner, WebContents* watched_contents)
287 : WebContentsObserver(watched_contents),
288 owner_(owner) {
291 // WebContentsObserver:
292 void WebContentsDestroyed() override {
293 owner_->OnWebContentsDestroyed(
294 static_cast<WebContentsImpl*>(web_contents()));
297 private:
298 WebContentsImpl* owner_;
300 DISALLOW_COPY_AND_ASSIGN(DestructionObserver);
303 WebContentsImpl::ColorChooserInfo::ColorChooserInfo(int render_process_id,
304 int render_frame_id,
305 ColorChooser* chooser,
306 int identifier)
307 : render_process_id(render_process_id),
308 render_frame_id(render_frame_id),
309 chooser(chooser),
310 identifier(identifier) {
313 WebContentsImpl::ColorChooserInfo::~ColorChooserInfo() {
316 // WebContentsImpl::WebContentsTreeNode ----------------------------------------
317 WebContentsImpl::WebContentsTreeNode::WebContentsTreeNode()
318 : outer_web_contents_(nullptr),
319 outer_contents_frame_tree_node_id_(
320 FrameTreeNode::kFrameTreeNodeInvalidID) {
323 WebContentsImpl::WebContentsTreeNode::~WebContentsTreeNode() {
324 // Remove child pointer from our parent.
325 if (outer_web_contents_) {
326 ChildrenSet& child_ptrs_in_parent =
327 outer_web_contents_->node_->inner_web_contents_tree_nodes_;
328 ChildrenSet::iterator iter = child_ptrs_in_parent.find(this);
329 DCHECK(iter != child_ptrs_in_parent.end());
330 child_ptrs_in_parent.erase(this);
333 // Remove parent pointers from our children.
334 // TODO(lazyboy): We should destroy the children WebContentses too. If the
335 // children do not manage their own lifetime, then we would leak their
336 // WebContentses.
337 for (WebContentsTreeNode* child : inner_web_contents_tree_nodes_)
338 child->outer_web_contents_ = nullptr;
341 void WebContentsImpl::WebContentsTreeNode::ConnectToOuterWebContents(
342 WebContentsImpl* outer_web_contents,
343 RenderFrameHostImpl* outer_contents_frame) {
344 outer_web_contents_ = outer_web_contents;
345 outer_contents_frame_tree_node_id_ =
346 outer_contents_frame->frame_tree_node()->frame_tree_node_id();
348 if (!outer_web_contents_->node_)
349 outer_web_contents_->node_.reset(new WebContentsTreeNode());
351 outer_web_contents_->node_->inner_web_contents_tree_nodes_.insert(this);
354 // WebContentsImpl -------------------------------------------------------------
356 WebContentsImpl::WebContentsImpl(BrowserContext* browser_context)
357 : delegate_(NULL),
358 controller_(this, browser_context),
359 render_view_host_delegate_view_(NULL),
360 created_with_opener_(false),
361 #if defined(OS_WIN)
362 accessible_parent_(NULL),
363 #endif
364 frame_tree_(new NavigatorImpl(&controller_, this),
365 this,
366 this,
367 this,
368 this),
369 is_loading_(false),
370 is_load_to_different_document_(false),
371 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING),
372 crashed_error_code_(0),
373 waiting_for_response_(false),
374 load_state_(net::LOAD_STATE_IDLE, base::string16()),
375 upload_size_(0),
376 upload_position_(0),
377 is_resume_pending_(false),
378 displayed_insecure_content_(false),
379 has_accessed_initial_document_(false),
380 theme_color_(SK_ColorTRANSPARENT),
381 last_sent_theme_color_(SK_ColorTRANSPARENT),
382 did_first_visually_non_empty_paint_(false),
383 capturer_count_(0),
384 should_normally_be_visible_(true),
385 is_being_destroyed_(false),
386 notify_disconnection_(false),
387 dialog_manager_(NULL),
388 is_showing_before_unload_dialog_(false),
389 last_active_time_(base::TimeTicks::Now()),
390 closed_by_user_gesture_(false),
391 minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)),
392 maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)),
393 render_view_message_source_(NULL),
394 render_frame_message_source_(NULL),
395 fullscreen_widget_routing_id_(MSG_ROUTING_NONE),
396 fullscreen_widget_had_focus_at_shutdown_(false),
397 is_subframe_(false),
398 force_disable_overscroll_content_(false),
399 last_dialog_suppressed_(false),
400 geolocation_service_context_(new GeolocationServiceContext()),
401 accessibility_mode_(
402 BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()),
403 virtual_keyboard_requested_(false),
404 loading_weak_factory_(this) {
405 frame_tree_.SetFrameRemoveListener(
406 base::Bind(&WebContentsImpl::OnFrameRemoved,
407 base::Unretained(this)));
408 #if defined(ENABLE_BROWSER_CDMS)
409 media_web_contents_observer_.reset(new MediaWebContentsObserver(this));
410 #endif
412 #if defined(OS_ANDROID)
413 audio_state_provider_.reset(new MediaPlayersObserver(this));
414 #else
415 audio_state_provider_.reset(new AudioStreamMonitor(this));
416 #endif
419 WebContentsImpl::~WebContentsImpl() {
420 is_being_destroyed_ = true;
422 // Delete all RFH pending shutdown, which will lead the corresponding RVH to
423 // shutdown and be deleted as well.
424 frame_tree_.ForEach(
425 base::Bind(&RenderFrameHostManager::ClearRFHsPendingShutdown));
427 ClearAllPowerSaveBlockers();
429 for (std::set<RenderWidgetHostImpl*>::iterator iter =
430 created_widgets_.begin(); iter != created_widgets_.end(); ++iter) {
431 (*iter)->DetachDelegate();
433 created_widgets_.clear();
435 // Clear out any JavaScript state.
436 if (dialog_manager_)
437 dialog_manager_->ResetDialogState(this);
439 if (color_chooser_info_.get())
440 color_chooser_info_->chooser->End();
442 NotifyDisconnected();
444 // Notify any observer that have a reference on this WebContents.
445 NotificationService::current()->Notify(
446 NOTIFICATION_WEB_CONTENTS_DESTROYED,
447 Source<WebContents>(this),
448 NotificationService::NoDetails());
450 // Destroy all frame tree nodes except for the root; this notifies observers.
451 frame_tree_.root()->ResetForNewProcess();
452 GetRenderManager()->ResetProxyHosts();
454 // Manually call the observer methods for the root frame tree node.
455 RenderFrameHostManager* root = GetRenderManager();
457 if (root->pending_frame_host())
458 root->pending_frame_host()->SetRenderFrameCreated(false);
459 root->current_frame_host()->SetRenderFrameCreated(false);
461 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
462 FrameDeleted(root->current_frame_host()));
464 if (root->pending_render_view_host()) {
465 FOR_EACH_OBSERVER(WebContentsObserver,
466 observers_,
467 RenderViewDeleted(root->pending_render_view_host()));
470 FOR_EACH_OBSERVER(WebContentsObserver,
471 observers_,
472 RenderViewDeleted(root->current_host()));
474 FOR_EACH_OBSERVER(WebContentsObserver,
475 observers_,
476 WebContentsDestroyed());
478 FOR_EACH_OBSERVER(WebContentsObserver,
479 observers_,
480 ResetWebContents());
482 SetDelegate(NULL);
484 STLDeleteContainerPairSecondPointers(destruction_observers_.begin(),
485 destruction_observers_.end());
488 WebContentsImpl* WebContentsImpl::CreateWithOpener(
489 const WebContents::CreateParams& params,
490 FrameTreeNode* opener) {
491 TRACE_EVENT0("browser", "WebContentsImpl::CreateWithOpener");
492 WebContentsImpl* new_contents = new WebContentsImpl(params.browser_context);
494 if (!params.opener_suppressed && opener) {
495 new_contents->GetFrameTree()->root()->SetOpener(opener);
496 new_contents->created_with_opener_ = true;
499 // This may be true even when opener is null, such as when opening blocked
500 // popups.
501 if (params.created_with_opener)
502 new_contents->created_with_opener_ = true;
504 if (params.guest_delegate) {
505 // This makes |new_contents| act as a guest.
506 // For more info, see comment above class BrowserPluginGuest.
507 BrowserPluginGuest::Create(new_contents, params.guest_delegate);
508 // We are instantiating a WebContents for browser plugin. Set its subframe
509 // bit to true.
510 new_contents->is_subframe_ = true;
512 new_contents->Init(params);
513 return new_contents;
516 // static
517 std::vector<WebContentsImpl*> WebContentsImpl::GetAllWebContents() {
518 std::vector<WebContentsImpl*> result;
519 scoped_ptr<RenderWidgetHostIterator> widgets(
520 RenderWidgetHostImpl::GetRenderWidgetHosts());
521 std::set<WebContentsImpl*> web_contents_set;
522 while (RenderWidgetHost* rwh = widgets->GetNextHost()) {
523 if (!rwh->IsRenderView())
524 continue;
525 RenderViewHost* rvh = RenderViewHost::From(rwh);
526 if (!rvh)
527 continue;
528 WebContents* web_contents = WebContents::FromRenderViewHost(rvh);
529 if (!web_contents)
530 continue;
531 WebContentsImpl* wci = static_cast<WebContentsImpl*>(web_contents);
532 if (web_contents_set.find(wci) == web_contents_set.end()) {
533 web_contents_set.insert(wci);
534 result.push_back(wci);
537 return result;
540 // static
541 WebContentsImpl* WebContentsImpl::FromFrameTreeNode(
542 FrameTreeNode* frame_tree_node) {
543 return static_cast<WebContentsImpl*>(
544 WebContents::FromRenderFrameHost(frame_tree_node->current_frame_host()));
547 RenderFrameHostManager* WebContentsImpl::GetRenderManagerForTesting() {
548 return GetRenderManager();
551 bool WebContentsImpl::OnMessageReceived(RenderViewHost* render_view_host,
552 const IPC::Message& message) {
553 return OnMessageReceived(render_view_host, NULL, message);
556 bool WebContentsImpl::OnMessageReceived(RenderViewHost* render_view_host,
557 RenderFrameHost* render_frame_host,
558 const IPC::Message& message) {
559 DCHECK(render_view_host || render_frame_host);
560 if (GetWebUI() &&
561 static_cast<WebUIImpl*>(GetWebUI())->OnMessageReceived(message)) {
562 return true;
565 base::ObserverListBase<WebContentsObserver>::Iterator it(&observers_);
566 WebContentsObserver* observer;
567 if (render_frame_host) {
568 while ((observer = it.GetNext()) != NULL)
569 if (observer->OnMessageReceived(message, render_frame_host))
570 return true;
571 } else {
572 while ((observer = it.GetNext()) != NULL)
573 if (observer->OnMessageReceived(message))
574 return true;
577 // Message handlers should be aware of which
578 // RenderViewHost/RenderFrameHost sent the message, which is temporarily
579 // stored in render_(view|frame)_message_source_.
580 if (render_frame_host)
581 render_frame_message_source_ = render_frame_host;
582 else
583 render_view_message_source_ = render_view_host;
585 bool handled = true;
586 IPC_BEGIN_MESSAGE_MAP(WebContentsImpl, message)
587 IPC_MESSAGE_HANDLER(FrameHostMsg_DomOperationResponse,
588 OnDomOperationResponse)
589 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeThemeColor,
590 OnThemeColorChanged)
591 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishDocumentLoad,
592 OnDocumentLoadedInFrame)
593 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishLoad, OnDidFinishLoad)
594 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenColorChooser, OnOpenColorChooser)
595 IPC_MESSAGE_HANDLER(FrameHostMsg_EndColorChooser, OnEndColorChooser)
596 IPC_MESSAGE_HANDLER(FrameHostMsg_SetSelectedColorInColorChooser,
597 OnSetSelectedColorInColorChooser)
598 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPlayingNotification,
599 OnMediaPlayingNotification)
600 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPausedNotification,
601 OnMediaPausedNotification)
602 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFirstVisuallyNonEmptyPaint,
603 OnFirstVisuallyNonEmptyPaint)
604 IPC_MESSAGE_HANDLER(ViewHostMsg_DidLoadResourceFromMemoryCache,
605 OnDidLoadResourceFromMemoryCache)
606 IPC_MESSAGE_HANDLER(ViewHostMsg_DidDisplayInsecureContent,
607 OnDidDisplayInsecureContent)
608 IPC_MESSAGE_HANDLER(ViewHostMsg_DidRunInsecureContent,
609 OnDidRunInsecureContent)
610 IPC_MESSAGE_HANDLER(ViewHostMsg_GoToEntryAtOffset, OnGoToEntryAtOffset)
611 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateZoomLimits, OnUpdateZoomLimits)
612 IPC_MESSAGE_HANDLER(ViewHostMsg_EnumerateDirectory, OnEnumerateDirectory)
613 IPC_MESSAGE_HANDLER(FrameHostMsg_RegisterProtocolHandler,
614 OnRegisterProtocolHandler)
615 IPC_MESSAGE_HANDLER(FrameHostMsg_UnregisterProtocolHandler,
616 OnUnregisterProtocolHandler)
617 IPC_MESSAGE_HANDLER(ViewHostMsg_Find_Reply, OnFindReply)
618 IPC_MESSAGE_HANDLER(ViewHostMsg_AppCacheAccessed, OnAppCacheAccessed)
619 IPC_MESSAGE_HANDLER(ViewHostMsg_WebUISend, OnWebUISend)
620 #if defined(ENABLE_PLUGINS)
621 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceCreated,
622 OnPepperInstanceCreated)
623 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceDeleted,
624 OnPepperInstanceDeleted)
625 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung, OnPepperPluginHung)
626 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed, OnPluginCrashed)
627 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission,
628 OnRequestPpapiBrokerPermission)
629 IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_Attach,
630 OnBrowserPluginMessage(render_frame_host,
631 message))
632 #endif
633 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateFaviconURL, OnUpdateFaviconURL)
634 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowValidationMessage,
635 OnShowValidationMessage)
636 IPC_MESSAGE_HANDLER(ViewHostMsg_HideValidationMessage,
637 OnHideValidationMessage)
638 IPC_MESSAGE_HANDLER(ViewHostMsg_MoveValidationMessage,
639 OnMoveValidationMessage)
640 #if defined(OS_ANDROID)
641 IPC_MESSAGE_HANDLER(ViewHostMsg_FindMatchRects_Reply,
642 OnFindMatchRectsReply)
643 IPC_MESSAGE_HANDLER(ViewHostMsg_OpenDateTimeDialog,
644 OnOpenDateTimeDialog)
645 #endif
646 IPC_MESSAGE_UNHANDLED(handled = false)
647 IPC_END_MESSAGE_MAP()
648 render_view_message_source_ = NULL;
649 render_frame_message_source_ = NULL;
651 return handled;
654 bool WebContentsImpl::HasValidFrameSource() {
655 if (!render_frame_message_source_) {
656 DCHECK(render_view_message_source_);
657 bad_message::ReceivedBadMessage(GetRenderProcessHost(),
658 bad_message::WC_INVALID_FRAME_SOURCE);
659 return false;
662 return true;
665 void WebContentsImpl::RunFileChooser(
666 RenderViewHost* render_view_host,
667 const FileChooserParams& params) {
668 if (delegate_)
669 delegate_->RunFileChooser(this, params);
672 NavigationControllerImpl& WebContentsImpl::GetController() {
673 return controller_;
676 const NavigationControllerImpl& WebContentsImpl::GetController() const {
677 return controller_;
680 BrowserContext* WebContentsImpl::GetBrowserContext() const {
681 return controller_.GetBrowserContext();
684 const GURL& WebContentsImpl::GetURL() const {
685 // We may not have a navigation entry yet.
686 NavigationEntry* entry = controller_.GetVisibleEntry();
687 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
690 const GURL& WebContentsImpl::GetVisibleURL() const {
691 // We may not have a navigation entry yet.
692 NavigationEntry* entry = controller_.GetVisibleEntry();
693 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
696 const GURL& WebContentsImpl::GetLastCommittedURL() const {
697 // We may not have a navigation entry yet.
698 NavigationEntry* entry = controller_.GetLastCommittedEntry();
699 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
702 WebContentsDelegate* WebContentsImpl::GetDelegate() {
703 return delegate_;
706 void WebContentsImpl::SetDelegate(WebContentsDelegate* delegate) {
707 // TODO(cbentzel): remove this debugging code?
708 if (delegate == delegate_)
709 return;
710 if (delegate_)
711 delegate_->Detach(this);
712 delegate_ = delegate;
713 if (delegate_) {
714 delegate_->Attach(this);
715 // Ensure the visible RVH reflects the new delegate's preferences.
716 if (view_)
717 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
721 RenderProcessHost* WebContentsImpl::GetRenderProcessHost() const {
722 RenderViewHostImpl* host = GetRenderManager()->current_host();
723 return host ? host->GetProcess() : NULL;
726 RenderFrameHostImpl* WebContentsImpl::GetMainFrame() {
727 return frame_tree_.root()->current_frame_host();
730 RenderFrameHostImpl* WebContentsImpl::GetFocusedFrame() {
731 FrameTreeNode* focused_node = frame_tree_.GetFocusedFrame();
732 if (!focused_node)
733 return nullptr;
734 return focused_node->current_frame_host();
737 void WebContentsImpl::ForEachFrame(
738 const base::Callback<void(RenderFrameHost*)>& on_frame) {
739 frame_tree_.ForEach(base::Bind(&ForEachFrameInternal, on_frame));
742 void WebContentsImpl::SendToAllFrames(IPC::Message* message) {
743 ForEachFrame(base::Bind(&SendToAllFramesInternal, message));
744 delete message;
747 RenderViewHostImpl* WebContentsImpl::GetRenderViewHost() const {
748 return GetRenderManager()->current_host();
751 int WebContentsImpl::GetRoutingID() const {
752 if (!GetRenderViewHost())
753 return MSG_ROUTING_NONE;
755 return GetRenderViewHost()->GetRoutingID();
758 void WebContentsImpl::CancelActiveAndPendingDialogs() {
759 if (dialog_manager_)
760 dialog_manager_->CancelActiveAndPendingDialogs(this);
761 if (browser_plugin_embedder_)
762 browser_plugin_embedder_->CancelGuestDialogs();
765 int WebContentsImpl::GetFullscreenWidgetRoutingID() const {
766 return fullscreen_widget_routing_id_;
769 void WebContentsImpl::ClosePage() {
770 GetRenderViewHost()->ClosePage();
773 RenderWidgetHostView* WebContentsImpl::GetRenderWidgetHostView() const {
774 return GetRenderManager()->GetRenderWidgetHostView();
777 RenderWidgetHostView* WebContentsImpl::GetFullscreenRenderWidgetHostView()
778 const {
779 RenderWidgetHost* const widget_host =
780 RenderWidgetHostImpl::FromID(GetRenderProcessHost()->GetID(),
781 GetFullscreenWidgetRoutingID());
782 return widget_host ? widget_host->GetView() : NULL;
785 WebContentsView* WebContentsImpl::GetView() const {
786 return view_.get();
789 SkColor WebContentsImpl::GetThemeColor() const {
790 return theme_color_;
793 void WebContentsImpl::SetAccessibilityMode(AccessibilityMode mode) {
794 if (mode == accessibility_mode_)
795 return;
797 accessibility_mode_ = mode;
798 frame_tree_.ForEach(
799 base::Bind(&ForEachFrameInternal,
800 base::Bind(&SetAccessibilityModeOnFrame, mode)));
801 frame_tree_.ForEach(
802 base::Bind(&ForEachPendingFrameInternal,
803 base::Bind(&SetAccessibilityModeOnFrame, mode)));
806 void WebContentsImpl::AddAccessibilityMode(AccessibilityMode mode) {
807 SetAccessibilityMode(AddAccessibilityModeTo(accessibility_mode_, mode));
810 void WebContentsImpl::RemoveAccessibilityMode(AccessibilityMode mode) {
811 SetAccessibilityMode(RemoveAccessibilityModeFrom(accessibility_mode_, mode));
814 void WebContentsImpl::RequestAXTreeSnapshot(AXTreeSnapshotCallback callback) {
815 // TODO(dmazzoni): http://crbug.com/475608 This only returns the
816 // accessibility tree from the main frame and everything in the
817 // same site instance.
818 GetMainFrame()->RequestAXTreeSnapshot(callback);
821 WebUI* WebContentsImpl::CreateWebUI(const GURL& url) {
822 WebUIImpl* web_ui = new WebUIImpl(this);
823 WebUIController* controller = WebUIControllerFactoryRegistry::GetInstance()->
824 CreateWebUIControllerForURL(web_ui, url);
825 if (controller) {
826 web_ui->AddMessageHandler(new GenericHandler());
827 web_ui->SetController(controller);
828 return web_ui;
831 delete web_ui;
832 return NULL;
835 WebUI* WebContentsImpl::GetWebUI() const {
836 return GetRenderManager()->web_ui() ? GetRenderManager()->web_ui()
837 : GetRenderManager()->pending_web_ui();
840 WebUI* WebContentsImpl::GetCommittedWebUI() const {
841 return GetRenderManager()->web_ui();
844 void WebContentsImpl::SetUserAgentOverride(const std::string& override) {
845 if (GetUserAgentOverride() == override)
846 return;
848 renderer_preferences_.user_agent_override = override;
850 // Send the new override string to the renderer.
851 RenderViewHost* host = GetRenderViewHost();
852 if (host)
853 host->SyncRendererPrefs();
855 // Reload the page if a load is currently in progress to avoid having
856 // different parts of the page loaded using different user agents.
857 NavigationEntry* entry = controller_.GetVisibleEntry();
858 if (is_loading_ && entry != NULL && entry->GetIsOverridingUserAgent())
859 controller_.ReloadIgnoringCache(true);
861 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
862 UserAgentOverrideSet(override));
865 const std::string& WebContentsImpl::GetUserAgentOverride() const {
866 return renderer_preferences_.user_agent_override;
869 void WebContentsImpl::EnableTreeOnlyAccessibilityMode() {
870 if (GetAccessibilityMode() == AccessibilityModeTreeOnly)
871 ForEachFrame(base::Bind(&ResetAccessibility));
872 else
873 AddAccessibilityMode(AccessibilityModeTreeOnly);
876 bool WebContentsImpl::IsTreeOnlyAccessibilityModeForTesting() const {
877 return accessibility_mode_ == AccessibilityModeTreeOnly;
880 bool WebContentsImpl::IsFullAccessibilityModeForTesting() const {
881 return accessibility_mode_ == AccessibilityModeComplete;
884 #if defined(OS_WIN)
885 void WebContentsImpl::SetParentNativeViewAccessible(
886 gfx::NativeViewAccessible accessible_parent) {
887 accessible_parent_ = accessible_parent;
888 RenderFrameHostImpl* rfh = GetMainFrame();
889 if (rfh)
890 rfh->SetParentNativeViewAccessible(accessible_parent);
892 #endif
894 const base::string16& WebContentsImpl::GetTitle() const {
895 // Transient entries take precedence. They are used for interstitial pages
896 // that are shown on top of existing pages.
897 NavigationEntry* entry = controller_.GetTransientEntry();
898 std::string accept_languages =
899 GetContentClient()->browser()->GetAcceptLangs(
900 GetBrowserContext());
901 if (entry) {
902 return entry->GetTitleForDisplay(accept_languages);
904 WebUI* our_web_ui = GetRenderManager()->pending_web_ui() ?
905 GetRenderManager()->pending_web_ui() : GetRenderManager()->web_ui();
906 if (our_web_ui) {
907 // Don't override the title in view source mode.
908 entry = controller_.GetVisibleEntry();
909 if (!(entry && entry->IsViewSourceMode())) {
910 // Give the Web UI the chance to override our title.
911 const base::string16& title = our_web_ui->GetOverriddenTitle();
912 if (!title.empty())
913 return title;
917 // We use the title for the last committed entry rather than a pending
918 // navigation entry. For example, when the user types in a URL, we want to
919 // keep the old page's title until the new load has committed and we get a new
920 // title.
921 entry = controller_.GetLastCommittedEntry();
923 // We make an exception for initial navigations.
924 if (controller_.IsInitialNavigation()) {
925 // We only want to use the title from the visible entry in one of two cases:
926 // 1. There's already a committed entry for an initial navigation, in which
927 // case we are doing a history navigation in a new tab (e.g., Ctrl+Back).
928 // 2. The pending entry has been explicitly assigned a title to display.
930 // If there's no last committed entry and no assigned title, we should fall
931 // back to |page_title_when_no_navigation_entry_| rather than showing the
932 // URL.
933 if (entry ||
934 (controller_.GetVisibleEntry() &&
935 !controller_.GetVisibleEntry()->GetTitle().empty())) {
936 entry = controller_.GetVisibleEntry();
940 if (entry) {
941 return entry->GetTitleForDisplay(accept_languages);
944 // |page_title_when_no_navigation_entry_| is finally used
945 // if no title cannot be retrieved.
946 return page_title_when_no_navigation_entry_;
949 int32 WebContentsImpl::GetMaxPageID() {
950 return GetMaxPageIDForSiteInstance(GetSiteInstance());
953 int32 WebContentsImpl::GetMaxPageIDForSiteInstance(
954 SiteInstance* site_instance) {
955 if (max_page_ids_.find(site_instance->GetId()) == max_page_ids_.end())
956 max_page_ids_[site_instance->GetId()] = -1;
958 return max_page_ids_[site_instance->GetId()];
961 void WebContentsImpl::UpdateMaxPageID(int32 page_id) {
962 UpdateMaxPageIDForSiteInstance(GetSiteInstance(), page_id);
965 void WebContentsImpl::UpdateMaxPageIDForSiteInstance(
966 SiteInstance* site_instance, int32 page_id) {
967 if (GetMaxPageIDForSiteInstance(site_instance) < page_id)
968 max_page_ids_[site_instance->GetId()] = page_id;
971 void WebContentsImpl::CopyMaxPageIDsFrom(WebContents* web_contents) {
972 WebContentsImpl* contents = static_cast<WebContentsImpl*>(web_contents);
973 max_page_ids_ = contents->max_page_ids_;
976 SiteInstanceImpl* WebContentsImpl::GetSiteInstance() const {
977 return GetRenderManager()->current_host()->GetSiteInstance();
980 SiteInstanceImpl* WebContentsImpl::GetPendingSiteInstance() const {
981 RenderViewHostImpl* dest_rvh =
982 GetRenderManager()->pending_render_view_host() ?
983 GetRenderManager()->pending_render_view_host() :
984 GetRenderManager()->current_host();
985 return dest_rvh->GetSiteInstance();
988 bool WebContentsImpl::IsLoading() const {
989 return is_loading_;
992 bool WebContentsImpl::IsLoadingToDifferentDocument() const {
993 return is_loading_ && is_load_to_different_document_;
996 bool WebContentsImpl::IsWaitingForResponse() const {
997 return waiting_for_response_ && is_load_to_different_document_;
1000 const net::LoadStateWithParam& WebContentsImpl::GetLoadState() const {
1001 return load_state_;
1004 const base::string16& WebContentsImpl::GetLoadStateHost() const {
1005 return load_state_host_;
1008 uint64 WebContentsImpl::GetUploadSize() const {
1009 return upload_size_;
1012 uint64 WebContentsImpl::GetUploadPosition() const {
1013 return upload_position_;
1016 std::set<GURL> WebContentsImpl::GetSitesInTab() const {
1017 std::set<GURL> sites;
1018 frame_tree_.ForEach(base::Bind(&CollectSites,
1019 base::Unretained(GetBrowserContext()),
1020 base::Unretained(&sites)));
1021 return sites;
1024 const std::string& WebContentsImpl::GetEncoding() const {
1025 return canonical_encoding_;
1028 bool WebContentsImpl::DisplayedInsecureContent() const {
1029 return displayed_insecure_content_;
1032 void WebContentsImpl::IncrementCapturerCount(const gfx::Size& capture_size) {
1033 DCHECK(!is_being_destroyed_);
1034 ++capturer_count_;
1035 DVLOG(1) << "There are now " << capturer_count_
1036 << " capturing(s) of WebContentsImpl@" << this;
1038 // Note: This provides a hint to upstream code to size the views optimally
1039 // for quality (e.g., to avoid scaling).
1040 if (!capture_size.IsEmpty() && preferred_size_for_capture_.IsEmpty()) {
1041 preferred_size_for_capture_ = capture_size;
1042 OnPreferredSizeChanged(preferred_size_);
1045 // Ensure that all views are un-occluded before capture begins.
1046 WasUnOccluded();
1049 void WebContentsImpl::DecrementCapturerCount() {
1050 --capturer_count_;
1051 DVLOG(1) << "There are now " << capturer_count_
1052 << " capturing(s) of WebContentsImpl@" << this;
1053 DCHECK_LE(0, capturer_count_);
1055 if (is_being_destroyed_)
1056 return;
1058 if (capturer_count_ == 0) {
1059 const gfx::Size old_size = preferred_size_for_capture_;
1060 preferred_size_for_capture_ = gfx::Size();
1061 OnPreferredSizeChanged(old_size);
1064 if (IsHidden()) {
1065 DVLOG(1) << "Executing delayed WasHidden().";
1066 WasHidden();
1070 int WebContentsImpl::GetCapturerCount() const {
1071 return capturer_count_;
1074 bool WebContentsImpl::IsAudioMuted() const {
1075 return audio_muter_.get() && audio_muter_->is_muting();
1078 void WebContentsImpl::SetAudioMuted(bool mute) {
1079 DVLOG(1) << "SetAudioMuted(mute=" << mute << "), was " << IsAudioMuted()
1080 << " for WebContentsImpl@" << this;
1082 if (mute == IsAudioMuted())
1083 return;
1085 if (mute) {
1086 if (!audio_muter_)
1087 audio_muter_.reset(new WebContentsAudioMuter(this));
1088 audio_muter_->StartMuting();
1089 } else {
1090 DCHECK(audio_muter_);
1091 audio_muter_->StopMuting();
1094 // Notification for UI updates in response to the changed muting state.
1095 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
1098 bool WebContentsImpl::IsCrashed() const {
1099 return (crashed_status_ == base::TERMINATION_STATUS_PROCESS_CRASHED ||
1100 crashed_status_ == base::TERMINATION_STATUS_ABNORMAL_TERMINATION ||
1101 crashed_status_ == base::TERMINATION_STATUS_PROCESS_WAS_KILLED
1102 #if defined(OS_CHROMEOS)
1104 crashed_status_ == base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM
1105 #endif
1109 void WebContentsImpl::SetIsCrashed(base::TerminationStatus status,
1110 int error_code) {
1111 if (status == crashed_status_)
1112 return;
1114 crashed_status_ = status;
1115 crashed_error_code_ = error_code;
1116 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
1119 base::TerminationStatus WebContentsImpl::GetCrashedStatus() const {
1120 return crashed_status_;
1123 bool WebContentsImpl::IsBeingDestroyed() const {
1124 return is_being_destroyed_;
1127 void WebContentsImpl::NotifyNavigationStateChanged(
1128 InvalidateTypes changed_flags) {
1129 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1130 // is fixed.
1131 tracked_objects::ScopedTracker tracking_profile(
1132 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1133 "466285 WebContentsImpl::NotifyNavigationStateChanged"));
1134 // Create and release the audio power save blocker depending on whether the
1135 // tab is actively producing audio or not.
1136 if ((changed_flags & INVALIDATE_TYPE_TAB) &&
1137 audio_state_provider_->IsAudioStateAvailable()) {
1138 if (WasRecentlyAudible()) {
1139 if (!audio_power_save_blocker_)
1140 CreateAudioPowerSaveBlocker();
1141 } else {
1142 audio_power_save_blocker_.reset();
1146 if (delegate_)
1147 delegate_->NavigationStateChanged(this, changed_flags);
1150 base::TimeTicks WebContentsImpl::GetLastActiveTime() const {
1151 return last_active_time_;
1154 void WebContentsImpl::SetLastActiveTime(base::TimeTicks last_active_time) {
1155 last_active_time_ = last_active_time;
1158 void WebContentsImpl::WasShown() {
1159 controller_.SetActive(true);
1161 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1162 if (view) {
1163 view->Show();
1164 #if defined(OS_MACOSX)
1165 view->SetActive(true);
1166 #endif
1170 last_active_time_ = base::TimeTicks::Now();
1172 // The resize rect might have changed while this was inactive -- send the new
1173 // one to make sure it's up to date.
1174 RenderViewHostImpl* rvh = GetRenderViewHost();
1175 if (rvh)
1176 rvh->ResizeRectChanged(GetRootWindowResizerRect());
1178 // Restore power save blocker if there are active video players running.
1179 if (!active_video_players_.empty() && !video_power_save_blocker_)
1180 CreateVideoPowerSaveBlocker();
1182 FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasShown());
1184 should_normally_be_visible_ = true;
1187 void WebContentsImpl::WasHidden() {
1188 // If there are entities capturing screenshots or video (e.g., mirroring),
1189 // don't activate the "disable rendering" optimization.
1190 if (capturer_count_ == 0) {
1191 // |GetRenderViewHost()| can be NULL if the user middle clicks a link to
1192 // open a tab in the background, then closes the tab before selecting it.
1193 // This is because closing the tab calls WebContentsImpl::Destroy(), which
1194 // removes the |GetRenderViewHost()|; then when we actually destroy the
1195 // window, OnWindowPosChanged() notices and calls WasHidden() (which
1196 // calls us).
1197 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1198 if (view)
1199 view->Hide();
1202 // Release any video power save blockers held as video is not visible.
1203 video_power_save_blocker_.reset();
1206 FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasHidden());
1208 should_normally_be_visible_ = false;
1211 void WebContentsImpl::WasOccluded() {
1212 if (capturer_count_ > 0)
1213 return;
1215 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1216 if (view)
1217 view->WasOccluded();
1221 void WebContentsImpl::WasUnOccluded() {
1222 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1223 if (view)
1224 view->WasUnOccluded();
1228 bool WebContentsImpl::NeedToFireBeforeUnload() {
1229 // TODO(creis): Should we fire even for interstitial pages?
1230 return WillNotifyDisconnection() && !ShowingInterstitialPage() &&
1231 !GetRenderViewHost()->SuddenTerminationAllowed();
1234 void WebContentsImpl::DispatchBeforeUnload(bool for_cross_site_transition) {
1235 GetMainFrame()->DispatchBeforeUnload(for_cross_site_transition);
1238 void WebContentsImpl::AttachToOuterWebContentsFrame(
1239 WebContents* outer_web_contents,
1240 RenderFrameHost* outer_contents_frame) {
1241 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1242 switches::kSitePerProcess));
1243 // Create a link to our outer WebContents.
1244 node_.reset(new WebContentsTreeNode());
1245 node_->ConnectToOuterWebContents(
1246 static_cast<WebContentsImpl*>(outer_web_contents),
1247 static_cast<RenderFrameHostImpl*>(outer_contents_frame));
1249 DCHECK(outer_contents_frame);
1251 // Create a proxy in top-level RenderFrameHostManager, pointing to the
1252 // SiteInstance of the outer WebContents. The proxy will be used to send
1253 // postMessage to the inner WebContents.
1254 GetRenderManager()->CreateOuterDelegateProxy(
1255 outer_contents_frame->GetSiteInstance(),
1256 static_cast<RenderFrameHostImpl*>(outer_contents_frame));
1258 GetRenderManager()->SetRWHViewForInnerContents(
1259 GetRenderManager()->GetRenderWidgetHostView());
1262 void WebContentsImpl::Stop() {
1263 frame_tree_.ForEach(base::Bind(&FrameTreeNode::StopLoading));
1264 FOR_EACH_OBSERVER(WebContentsObserver, observers_, NavigationStopped());
1267 WebContents* WebContentsImpl::Clone() {
1268 // We use our current SiteInstance since the cloned entry will use it anyway.
1269 // We pass our own opener so that the cloned page can access it if it was set
1270 // before.
1271 CreateParams create_params(GetBrowserContext(), GetSiteInstance());
1272 create_params.initial_size = GetContainerBounds().size();
1273 WebContentsImpl* tc =
1274 CreateWithOpener(create_params, frame_tree_.root()->opener());
1275 tc->GetController().CopyStateFrom(controller_);
1276 FOR_EACH_OBSERVER(WebContentsObserver,
1277 observers_,
1278 DidCloneToNewWebContents(this, tc));
1279 return tc;
1282 void WebContentsImpl::Observe(int type,
1283 const NotificationSource& source,
1284 const NotificationDetails& details) {
1285 switch (type) {
1286 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: {
1287 RenderWidgetHost* host = Source<RenderWidgetHost>(source).ptr();
1288 RenderWidgetHostView* view = host->GetView();
1289 if (view == GetFullscreenRenderWidgetHostView()) {
1290 // We cannot just call view_->RestoreFocus() here. On some platforms,
1291 // attempting to focus the currently-invisible WebContentsView will be
1292 // flat-out ignored. Therefore, this boolean is used to track whether
1293 // we will request focus after the fullscreen widget has been
1294 // destroyed.
1295 fullscreen_widget_had_focus_at_shutdown_ = (view && view->HasFocus());
1296 } else {
1297 for (PendingWidgetViews::iterator i = pending_widget_views_.begin();
1298 i != pending_widget_views_.end(); ++i) {
1299 if (host->GetView() == i->second) {
1300 pending_widget_views_.erase(i);
1301 break;
1305 break;
1307 default:
1308 NOTREACHED();
1312 WebContents* WebContentsImpl::GetWebContents() {
1313 return this;
1316 void WebContentsImpl::Init(const WebContents::CreateParams& params) {
1317 // This is set before initializing the render manager since
1318 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
1319 // it should be hidden.
1320 should_normally_be_visible_ = !params.initially_hidden;
1322 // Either both routing ids can be given, or neither can be.
1323 DCHECK((params.routing_id == MSG_ROUTING_NONE &&
1324 params.main_frame_routing_id == MSG_ROUTING_NONE) ||
1325 (params.routing_id != MSG_ROUTING_NONE &&
1326 params.main_frame_routing_id != MSG_ROUTING_NONE));
1327 GetRenderManager()->Init(
1328 params.browser_context, params.site_instance, params.routing_id,
1329 params.main_frame_routing_id);
1330 frame_tree_.root()->SetFrameName(params.main_frame_name);
1332 WebContentsViewDelegate* delegate =
1333 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
1335 if (browser_plugin_guest_ &&
1336 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1337 switches::kSitePerProcess)) {
1338 scoped_ptr<WebContentsView> platform_view(CreateWebContentsView(
1339 this, delegate, &render_view_host_delegate_view_));
1341 WebContentsViewGuest* rv = new WebContentsViewGuest(
1342 this, browser_plugin_guest_.get(), platform_view.Pass(),
1343 render_view_host_delegate_view_);
1344 render_view_host_delegate_view_ = rv;
1345 view_.reset(rv);
1346 } else {
1347 // Regular WebContentsView.
1348 view_.reset(CreateWebContentsView(
1349 this, delegate, &render_view_host_delegate_view_));
1351 CHECK(render_view_host_delegate_view_);
1352 CHECK(view_.get());
1354 gfx::Size initial_size = params.initial_size;
1355 view_->CreateView(initial_size, params.context);
1357 #if defined(ENABLE_PLUGINS)
1358 plugin_content_origin_whitelist_.reset(
1359 new PluginContentOriginWhitelist(this));
1360 #endif
1362 registrar_.Add(this,
1363 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1364 NotificationService::AllBrowserContextsAndSources());
1366 screen_orientation_dispatcher_host_.reset(
1367 new ScreenOrientationDispatcherHostImpl(this));
1369 manifest_manager_host_.reset(new ManifestManagerHost(this));
1371 #if defined(OS_ANDROID)
1372 date_time_chooser_.reset(new DateTimeChooserAndroid());
1373 #endif
1375 // BrowserPluginGuest::Init needs to be called after this WebContents has
1376 // a RenderWidgetHostViewGuest. That is, |view_->CreateView| above.
1377 if (browser_plugin_guest_)
1378 browser_plugin_guest_->Init();
1380 for (size_t i = 0; i < g_created_callbacks.Get().size(); i++)
1381 g_created_callbacks.Get().at(i).Run(this);
1383 // If the WebContents creation was renderer-initiated, it means that the
1384 // corresponding RenderView and main RenderFrame have already been created.
1385 // Ensure observers are notified about this.
1386 if (params.renderer_initiated_creation) {
1387 GetRenderViewHost()->set_renderer_initialized(true);
1388 RenderViewCreated(GetRenderViewHost());
1389 GetRenderManager()->current_frame_host()->SetRenderFrameCreated(true);
1392 // Ensure that observers are notified of the creation of this WebContents's
1393 // main RenderFrameHost. It must be done here for main frames, since the
1394 // NotifySwappedFromRenderManager expects view_ to already be created and that
1395 // happens after RenderFrameHostManager::Init.
1396 NotifySwappedFromRenderManager(
1397 nullptr, GetRenderManager()->current_frame_host(), true);
1400 void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl* web_contents) {
1401 RemoveDestructionObserver(web_contents);
1403 // Clear a pending contents that has been closed before being shown.
1404 for (PendingContents::iterator iter = pending_contents_.begin();
1405 iter != pending_contents_.end();
1406 ++iter) {
1407 if (iter->second != web_contents)
1408 continue;
1409 pending_contents_.erase(iter);
1410 return;
1412 NOTREACHED();
1415 void WebContentsImpl::AddDestructionObserver(WebContentsImpl* web_contents) {
1416 if (!ContainsKey(destruction_observers_, web_contents)) {
1417 destruction_observers_[web_contents] =
1418 new DestructionObserver(this, web_contents);
1422 void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl* web_contents) {
1423 DestructionObservers::iterator iter =
1424 destruction_observers_.find(web_contents);
1425 if (iter != destruction_observers_.end()) {
1426 delete destruction_observers_[web_contents];
1427 destruction_observers_.erase(iter);
1431 void WebContentsImpl::AddObserver(WebContentsObserver* observer) {
1432 observers_.AddObserver(observer);
1435 void WebContentsImpl::RemoveObserver(WebContentsObserver* observer) {
1436 observers_.RemoveObserver(observer);
1439 std::set<RenderWidgetHostView*>
1440 WebContentsImpl::GetRenderWidgetHostViewsInTree() {
1441 std::set<RenderWidgetHostView*> set;
1442 if (ShowingInterstitialPage()) {
1443 set.insert(GetRenderWidgetHostView());
1444 } else {
1445 ForEachFrame(
1446 base::Bind(&AddRenderWidgetHostViewToSet, base::Unretained(&set)));
1448 return set;
1451 void WebContentsImpl::Activate() {
1452 if (delegate_)
1453 delegate_->ActivateContents(this);
1456 void WebContentsImpl::Deactivate() {
1457 if (delegate_)
1458 delegate_->DeactivateContents(this);
1461 void WebContentsImpl::LostCapture() {
1462 if (delegate_)
1463 delegate_->LostCapture();
1466 void WebContentsImpl::RenderWidgetDeleted(
1467 RenderWidgetHostImpl* render_widget_host) {
1468 if (is_being_destroyed_) {
1469 // |created_widgets_| might have been destroyed.
1470 return;
1473 std::set<RenderWidgetHostImpl*>::iterator iter =
1474 created_widgets_.find(render_widget_host);
1475 if (iter != created_widgets_.end())
1476 created_widgets_.erase(iter);
1478 if (render_widget_host &&
1479 render_widget_host->GetRoutingID() == fullscreen_widget_routing_id_) {
1480 if (delegate_ && delegate_->EmbedsFullscreenWidget())
1481 delegate_->ExitFullscreenModeForTab(this);
1482 FOR_EACH_OBSERVER(WebContentsObserver,
1483 observers_,
1484 DidDestroyFullscreenWidget(
1485 fullscreen_widget_routing_id_));
1486 fullscreen_widget_routing_id_ = MSG_ROUTING_NONE;
1487 if (fullscreen_widget_had_focus_at_shutdown_)
1488 view_->RestoreFocus();
1492 void WebContentsImpl::RenderWidgetGotFocus(
1493 RenderWidgetHostImpl* render_widget_host) {
1494 // Notify the observers if an embedded fullscreen widget was focused.
1495 if (delegate_ && render_widget_host && delegate_->EmbedsFullscreenWidget() &&
1496 render_widget_host->GetView() == GetFullscreenRenderWidgetHostView()) {
1497 NotifyWebContentsFocused();
1501 void WebContentsImpl::RenderWidgetWasResized(
1502 RenderWidgetHostImpl* render_widget_host,
1503 bool width_changed) {
1504 RenderFrameHostImpl* rfh = GetMainFrame();
1505 if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
1506 return;
1508 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1509 MainFrameWasResized(width_changed));
1512 void WebContentsImpl::ScreenInfoChanged() {
1513 if (browser_plugin_embedder_)
1514 browser_plugin_embedder_->ScreenInfoChanged();
1517 bool WebContentsImpl::PreHandleKeyboardEvent(
1518 const NativeWebKeyboardEvent& event,
1519 bool* is_keyboard_shortcut) {
1520 return delegate_ &&
1521 delegate_->PreHandleKeyboardEvent(this, event, is_keyboard_shortcut);
1524 void WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
1525 if (browser_plugin_embedder_ &&
1526 browser_plugin_embedder_->HandleKeyboardEvent(event)) {
1527 return;
1529 if (delegate_)
1530 delegate_->HandleKeyboardEvent(this, event);
1533 bool WebContentsImpl::HandleWheelEvent(
1534 const blink::WebMouseWheelEvent& event) {
1535 #if !defined(OS_MACOSX)
1536 // On platforms other than Mac, control+mousewheel may change zoom. On Mac,
1537 // this isn't done for two reasons:
1538 // -the OS already has a gesture to do this through pinch-zoom
1539 // -if a user starts an inertial scroll, let's go, and presses control
1540 // (i.e. control+tab) then the OS's buffered scroll events will come in
1541 // with control key set which isn't what the user wants
1542 if (delegate_ && event.wheelTicksY &&
1543 (event.modifiers & blink::WebInputEvent::ControlKey) &&
1544 !event.canScroll) {
1545 delegate_->ContentsZoomChange(event.wheelTicksY > 0);
1546 return true;
1548 #endif
1549 return false;
1552 bool WebContentsImpl::PreHandleGestureEvent(
1553 const blink::WebGestureEvent& event) {
1554 return delegate_ && delegate_->PreHandleGestureEvent(this, event);
1557 void WebContentsImpl::EnterFullscreenMode(const GURL& origin) {
1558 // This method is being called to enter renderer-initiated fullscreen mode.
1559 // Make sure any existing fullscreen widget is shut down first.
1560 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
1561 if (widget_view)
1562 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())->Shutdown();
1564 if (delegate_)
1565 delegate_->EnterFullscreenModeForTab(this, origin);
1567 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1568 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1571 void WebContentsImpl::ExitFullscreenMode() {
1572 // This method is being called to leave renderer-initiated fullscreen mode.
1573 // Make sure any existing fullscreen widget is shut down first.
1574 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
1575 if (widget_view)
1576 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())->Shutdown();
1578 #if defined(OS_ANDROID)
1579 ContentVideoView* video_view = ContentVideoView::GetInstance();
1580 if (video_view != NULL)
1581 video_view->OnExitFullscreen();
1582 #endif
1584 if (delegate_)
1585 delegate_->ExitFullscreenModeForTab(this);
1587 // Ensure web contents exit fullscreen state by sending a resize message,
1588 // which includes the fullscreen state. This is required for the situation
1589 // of the browser moving the view into a fullscreen state "browser fullscreen"
1590 // and then the contents entering "tab fullscreen". Exiting the contents
1591 // "tab fullscreen" then won't have the side effect of the view resizing,
1592 // hence the explicit call here is required.
1593 if (RenderWidgetHostView* rwh_view = GetRenderWidgetHostView()) {
1594 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
1595 render_widget_host->WasResized();
1598 FOR_EACH_OBSERVER(WebContentsObserver,
1599 observers_,
1600 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1603 bool WebContentsImpl::IsFullscreenForCurrentTab() const {
1604 return delegate_ ? delegate_->IsFullscreenForTabOrPending(this) : false;
1607 blink::WebDisplayMode WebContentsImpl::GetDisplayMode() const {
1608 return delegate_ ? delegate_->GetDisplayMode(this)
1609 : blink::WebDisplayModeBrowser;
1612 void WebContentsImpl::RequestToLockMouse(bool user_gesture,
1613 bool last_unlocked_by_target) {
1614 if (delegate_) {
1615 delegate_->RequestToLockMouse(this, user_gesture, last_unlocked_by_target);
1616 } else {
1617 GotResponseToLockMouseRequest(false);
1621 void WebContentsImpl::LostMouseLock() {
1622 if (delegate_)
1623 delegate_->LostMouseLock();
1626 void WebContentsImpl::CreateNewWindow(
1627 SiteInstance* source_site_instance,
1628 int route_id,
1629 int main_frame_route_id,
1630 const ViewHostMsg_CreateWindow_Params& params,
1631 SessionStorageNamespace* session_storage_namespace) {
1632 // We usually create the new window in the same BrowsingInstance (group of
1633 // script-related windows), by passing in the current SiteInstance. However,
1634 // if the opener is being suppressed (in a non-guest), we create a new
1635 // SiteInstance in its own BrowsingInstance.
1636 bool is_guest = BrowserPluginGuest::IsGuest(this);
1638 if (is_guest &&
1639 base::CommandLine::ForCurrentProcess()->HasSwitch(
1640 switches::kSitePerProcess)) {
1641 // TODO(lazyboy): CreateNewWindow doesn't work for OOPIF-based <webview>
1642 // yet.
1643 NOTREACHED();
1646 // If the opener is to be suppressed, the new window can be in any process.
1647 // Since routing ids are process specific, we must not have one passed in
1648 // as argument here.
1649 DCHECK(!params.opener_suppressed || route_id == MSG_ROUTING_NONE);
1651 scoped_refptr<SiteInstance> site_instance =
1652 params.opener_suppressed && !is_guest
1653 ? SiteInstance::CreateForURL(GetBrowserContext(), params.target_url)
1654 : source_site_instance;
1656 // A message to create a new window can only come from a process for a frame
1657 // in this WebContents' FrameTree. If any other process sends the request, it
1658 // is invalid and the process must be terminated.
1659 int render_process_id = source_site_instance->GetProcess()->GetID();
1660 bool did_match_process = false;
1661 frame_tree_.ForEach(
1662 base::Bind(&FindMatchingProcess, render_process_id, &did_match_process));
1663 if (!did_match_process) {
1664 RenderProcessHost* rph = source_site_instance->GetProcess();
1665 base::ProcessHandle process_handle = rph->GetHandle();
1666 if (process_handle != base::kNullProcessHandle) {
1667 RecordAction(
1668 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWindow"));
1669 rph->Shutdown(RESULT_CODE_KILLED, false);
1671 return;
1674 // We must assign the SessionStorageNamespace before calling Init().
1676 // http://crbug.com/142685
1677 const std::string& partition_id =
1678 GetContentClient()->browser()->
1679 GetStoragePartitionIdForSite(GetBrowserContext(),
1680 site_instance->GetSiteURL());
1681 StoragePartition* partition = BrowserContext::GetStoragePartition(
1682 GetBrowserContext(), site_instance.get());
1683 DOMStorageContextWrapper* dom_storage_context =
1684 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
1685 SessionStorageNamespaceImpl* session_storage_namespace_impl =
1686 static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
1687 CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
1689 if (delegate_ &&
1690 !delegate_->ShouldCreateWebContents(this,
1691 route_id,
1692 main_frame_route_id,
1693 params.window_container_type,
1694 params.frame_name,
1695 params.target_url,
1696 partition_id,
1697 session_storage_namespace)) {
1698 if (route_id != MSG_ROUTING_NONE &&
1699 !RenderViewHost::FromID(render_process_id, route_id)) {
1700 // If the embedder didn't create a WebContents for this route, we need to
1701 // delete the RenderView that had already been created.
1702 Send(new ViewMsg_Close(route_id));
1704 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(route_id);
1705 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(
1706 main_frame_route_id);
1707 return;
1710 // Create the new web contents. This will automatically create the new
1711 // WebContentsView. In the future, we may want to create the view separately.
1712 CreateParams create_params(GetBrowserContext(), site_instance.get());
1713 create_params.routing_id = route_id;
1714 create_params.main_frame_routing_id = main_frame_route_id;
1715 create_params.main_frame_name = params.frame_name;
1716 create_params.opener_render_process_id = render_process_id;
1717 create_params.opener_render_frame_id = params.opener_render_frame_id;
1718 create_params.opener_suppressed = params.opener_suppressed;
1719 if (params.disposition == NEW_BACKGROUND_TAB)
1720 create_params.initially_hidden = true;
1721 create_params.renderer_initiated_creation =
1722 main_frame_route_id != MSG_ROUTING_NONE;
1724 WebContentsImpl* new_contents = NULL;
1725 if (!is_guest) {
1726 create_params.context = view_->GetNativeView();
1727 create_params.initial_size = GetContainerBounds().size();
1728 new_contents = static_cast<WebContentsImpl*>(
1729 WebContents::Create(create_params));
1730 } else {
1731 new_contents = GetBrowserPluginGuest()->CreateNewGuestWindow(create_params);
1733 new_contents->GetController().SetSessionStorageNamespace(
1734 partition_id,
1735 session_storage_namespace);
1737 // If the new frame has a name, make sure any SiteInstances that can find
1738 // this named frame have proxies for it. Must be called after
1739 // SetSessionStorageNamespace, since this calls CreateRenderView, which uses
1740 // GetSessionStorageNamespace.
1741 if (!params.frame_name.empty())
1742 new_contents->GetRenderManager()->CreateProxiesForNewNamedFrame();
1744 // Save the window for later if we're not suppressing the opener (since it
1745 // will be shown immediately).
1746 if (!params.opener_suppressed) {
1747 if (!is_guest) {
1748 WebContentsView* new_view = new_contents->view_.get();
1750 // TODO(brettw): It seems bogus that we have to call this function on the
1751 // newly created object and give it one of its own member variables.
1752 new_view->CreateViewForWidget(new_contents->GetRenderViewHost(), false);
1754 // Save the created window associated with the route so we can show it
1755 // later.
1756 DCHECK_NE(MSG_ROUTING_NONE, route_id);
1757 pending_contents_[route_id] = new_contents;
1758 AddDestructionObserver(new_contents);
1761 if (delegate_) {
1762 delegate_->WebContentsCreated(
1763 this, params.opener_render_frame_id, params.frame_name,
1764 params.target_url, new_contents);
1767 if (params.opener_suppressed) {
1768 // When the opener is suppressed, the original renderer cannot access the
1769 // new window. As a result, we need to show and navigate the window here.
1770 bool was_blocked = false;
1771 if (delegate_) {
1772 gfx::Rect initial_rect;
1773 delegate_->AddNewContents(
1774 this, new_contents, params.disposition, initial_rect,
1775 params.user_gesture, &was_blocked);
1777 if (!was_blocked) {
1778 OpenURLParams open_params(params.target_url,
1779 Referrer(),
1780 CURRENT_TAB,
1781 ui::PAGE_TRANSITION_LINK,
1782 true /* is_renderer_initiated */);
1783 open_params.user_gesture = params.user_gesture;
1785 if (delegate_ && !is_guest &&
1786 !delegate_->ShouldResumeRequestsForCreatedWindow()) {
1787 // We are in asynchronous add new contents path, delay opening url
1788 new_contents->delayed_open_url_params_.reset(
1789 new OpenURLParams(open_params));
1790 } else {
1791 new_contents->OpenURL(open_params);
1797 void WebContentsImpl::CreateNewWidget(int render_process_id,
1798 int route_id,
1799 blink::WebPopupType popup_type) {
1800 CreateNewWidget(render_process_id, route_id, false, popup_type);
1803 void WebContentsImpl::CreateNewFullscreenWidget(int render_process_id,
1804 int route_id) {
1805 CreateNewWidget(render_process_id, route_id, true, blink::WebPopupTypeNone);
1808 void WebContentsImpl::CreateNewWidget(int render_process_id,
1809 int route_id,
1810 bool is_fullscreen,
1811 blink::WebPopupType popup_type) {
1812 RenderProcessHost* process = GetRenderProcessHost();
1813 // A message to create a new widget can only come from the active process for
1814 // this WebContentsImpl instance. If any other process sends the request,
1815 // it is invalid and the process must be terminated.
1816 if (process->GetID() != render_process_id) {
1817 RenderProcessHost* rph = RenderProcessHost::FromID(render_process_id);
1818 base::ProcessHandle process_handle = rph->GetHandle();
1819 if (process_handle != base::kNullProcessHandle) {
1820 RecordAction(
1821 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWidget"));
1822 rph->Shutdown(RESULT_CODE_KILLED, false);
1824 return;
1827 RenderWidgetHostImpl* widget_host =
1828 new RenderWidgetHostImpl(this, process, route_id, IsHidden());
1829 created_widgets_.insert(widget_host);
1831 RenderWidgetHostViewBase* widget_view =
1832 static_cast<RenderWidgetHostViewBase*>(
1833 view_->CreateViewForPopupWidget(widget_host));
1834 if (!widget_view)
1835 return;
1836 if (!is_fullscreen) {
1837 // Popups should not get activated.
1838 widget_view->SetPopupType(popup_type);
1840 // Save the created widget associated with the route so we can show it later.
1841 pending_widget_views_[route_id] = widget_view;
1843 #if defined(OS_MACOSX)
1844 // A RenderWidgetHostViewMac has lifetime scoped to the view. We'll retain it
1845 // to allow it to survive the trip without being hosted.
1846 base::mac::NSObjectRetain(widget_view->GetNativeView());
1847 #endif
1850 void WebContentsImpl::ShowCreatedWindow(int route_id,
1851 WindowOpenDisposition disposition,
1852 const gfx::Rect& initial_rect,
1853 bool user_gesture) {
1854 WebContentsImpl* contents = GetCreatedWindow(route_id);
1855 if (contents) {
1856 WebContentsDelegate* delegate = GetDelegate();
1857 contents->is_resume_pending_ = true;
1858 if (!delegate || delegate->ShouldResumeRequestsForCreatedWindow())
1859 contents->ResumeLoadingCreatedWebContents();
1861 if (delegate) {
1862 delegate->AddNewContents(
1863 this, contents, disposition, initial_rect, user_gesture, NULL);
1868 void WebContentsImpl::ShowCreatedWidget(int route_id,
1869 const gfx::Rect& initial_rect) {
1870 ShowCreatedWidget(route_id, false, initial_rect);
1873 void WebContentsImpl::ShowCreatedFullscreenWidget(int route_id) {
1874 ShowCreatedWidget(route_id, true, gfx::Rect());
1877 void WebContentsImpl::ShowCreatedWidget(int route_id,
1878 bool is_fullscreen,
1879 const gfx::Rect& initial_rect) {
1880 RenderWidgetHostViewBase* widget_host_view =
1881 static_cast<RenderWidgetHostViewBase*>(GetCreatedWidget(route_id));
1882 if (!widget_host_view)
1883 return;
1885 RenderWidgetHostView* view = NULL;
1886 BrowserPluginGuest* guest = GetBrowserPluginGuest();
1887 if (guest && guest->embedder_web_contents()) {
1888 view = guest->embedder_web_contents()->GetRenderWidgetHostView();
1889 } else {
1890 view = GetRenderWidgetHostView();
1893 if (is_fullscreen) {
1894 DCHECK_EQ(MSG_ROUTING_NONE, fullscreen_widget_routing_id_);
1895 view_->StoreFocus();
1896 fullscreen_widget_routing_id_ = route_id;
1897 if (delegate_ && delegate_->EmbedsFullscreenWidget()) {
1898 widget_host_view->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
1899 delegate_->EnterFullscreenModeForTab(this, GURL());
1900 } else {
1901 widget_host_view->InitAsFullscreen(view);
1903 FOR_EACH_OBSERVER(WebContentsObserver,
1904 observers_,
1905 DidShowFullscreenWidget(route_id));
1906 if (!widget_host_view->HasFocus())
1907 widget_host_view->Focus();
1908 } else {
1909 widget_host_view->InitAsPopup(view, initial_rect);
1912 RenderWidgetHostImpl* render_widget_host_impl =
1913 RenderWidgetHostImpl::From(widget_host_view->GetRenderWidgetHost());
1914 render_widget_host_impl->Init();
1915 // Only allow privileged mouse lock for fullscreen render widget, which is
1916 // used to implement Pepper Flash fullscreen.
1917 render_widget_host_impl->set_allow_privileged_mouse_lock(is_fullscreen);
1919 #if defined(OS_MACOSX)
1920 // A RenderWidgetHostViewMac has lifetime scoped to the view. Now that it's
1921 // properly embedded (or purposefully ignored) we can release the retain we
1922 // took in CreateNewWidget().
1923 base::mac::NSObjectRelease(widget_host_view->GetNativeView());
1924 #endif
1927 WebContentsImpl* WebContentsImpl::GetCreatedWindow(int route_id) {
1928 PendingContents::iterator iter = pending_contents_.find(route_id);
1930 // Certain systems can block the creation of new windows. If we didn't succeed
1931 // in creating one, just return NULL.
1932 if (iter == pending_contents_.end()) {
1933 return NULL;
1936 WebContentsImpl* new_contents = iter->second;
1937 pending_contents_.erase(route_id);
1938 RemoveDestructionObserver(new_contents);
1940 // Don't initialize the guest WebContents immediately.
1941 if (BrowserPluginGuest::IsGuest(new_contents))
1942 return new_contents;
1944 if (!new_contents->GetRenderProcessHost()->HasConnection() ||
1945 !new_contents->GetRenderViewHost()->GetView())
1946 return NULL;
1948 return new_contents;
1951 RenderWidgetHostView* WebContentsImpl::GetCreatedWidget(int route_id) {
1952 PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id);
1953 if (iter == pending_widget_views_.end()) {
1954 DCHECK(false);
1955 return NULL;
1958 RenderWidgetHostView* widget_host_view = iter->second;
1959 pending_widget_views_.erase(route_id);
1961 RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
1962 if (!widget_host->GetProcess()->HasConnection()) {
1963 // The view has gone away or the renderer crashed. Nothing to do.
1964 return NULL;
1967 return widget_host_view;
1970 void WebContentsImpl::RequestMediaAccessPermission(
1971 const MediaStreamRequest& request,
1972 const MediaResponseCallback& callback) {
1973 if (delegate_) {
1974 delegate_->RequestMediaAccessPermission(this, request, callback);
1975 } else {
1976 callback.Run(MediaStreamDevices(),
1977 MEDIA_DEVICE_FAILED_DUE_TO_SHUTDOWN,
1978 scoped_ptr<MediaStreamUI>());
1982 bool WebContentsImpl::CheckMediaAccessPermission(const GURL& security_origin,
1983 MediaStreamType type) {
1984 DCHECK(type == MEDIA_DEVICE_AUDIO_CAPTURE ||
1985 type == MEDIA_DEVICE_VIDEO_CAPTURE);
1986 return delegate_ &&
1987 delegate_->CheckMediaAccessPermission(this, security_origin, type);
1990 SessionStorageNamespace* WebContentsImpl::GetSessionStorageNamespace(
1991 SiteInstance* instance) {
1992 return controller_.GetSessionStorageNamespace(instance);
1995 SessionStorageNamespaceMap WebContentsImpl::GetSessionStorageNamespaceMap() {
1996 return controller_.GetSessionStorageNamespaceMap();
1999 FrameTree* WebContentsImpl::GetFrameTree() {
2000 return &frame_tree_;
2003 void WebContentsImpl::SetIsVirtualKeyboardRequested(bool requested) {
2004 virtual_keyboard_requested_ = requested;
2007 bool WebContentsImpl::IsVirtualKeyboardRequested() {
2008 return virtual_keyboard_requested_;
2011 AccessibilityMode WebContentsImpl::GetAccessibilityMode() const {
2012 return accessibility_mode_;
2015 void WebContentsImpl::AccessibilityEventReceived(
2016 const std::vector<AXEventNotificationDetails>& details) {
2017 FOR_EACH_OBSERVER(
2018 WebContentsObserver, observers_, AccessibilityEventReceived(details));
2021 RenderFrameHost* WebContentsImpl::GetGuestByInstanceID(
2022 RenderFrameHost* render_frame_host,
2023 int browser_plugin_instance_id) {
2024 BrowserPluginGuestManager* guest_manager =
2025 GetBrowserContext()->GetGuestManager();
2026 if (!guest_manager)
2027 return nullptr;
2029 WebContents* guest = guest_manager->GetGuestByInstanceID(
2030 render_frame_host->GetProcess()->GetID(), browser_plugin_instance_id);
2031 if (!guest)
2032 return nullptr;
2034 return guest->GetMainFrame();
2037 GeolocationServiceContext* WebContentsImpl::GetGeolocationServiceContext() {
2038 return geolocation_service_context_.get();
2041 void WebContentsImpl::OnShowValidationMessage(
2042 const gfx::Rect& anchor_in_root_view,
2043 const base::string16& main_text,
2044 const base::string16& sub_text) {
2045 if (delegate_)
2046 delegate_->ShowValidationMessage(
2047 this, anchor_in_root_view, main_text, sub_text);
2050 void WebContentsImpl::OnHideValidationMessage() {
2051 if (delegate_)
2052 delegate_->HideValidationMessage(this);
2055 void WebContentsImpl::OnMoveValidationMessage(
2056 const gfx::Rect& anchor_in_root_view) {
2057 if (delegate_)
2058 delegate_->MoveValidationMessage(this, anchor_in_root_view);
2061 void WebContentsImpl::DidSendScreenRects(RenderWidgetHostImpl* rwh) {
2062 if (browser_plugin_embedder_)
2063 browser_plugin_embedder_->DidSendScreenRects();
2066 BrowserAccessibilityManager*
2067 WebContentsImpl::GetRootBrowserAccessibilityManager() {
2068 RenderFrameHostImpl* rfh = GetMainFrame();
2069 return rfh ? rfh->browser_accessibility_manager() : nullptr;
2072 BrowserAccessibilityManager*
2073 WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
2074 RenderFrameHostImpl* rfh = GetMainFrame();
2075 return rfh ? rfh->GetOrCreateBrowserAccessibilityManager() : nullptr;
2078 void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point& extent) {
2079 RenderFrameHost* focused_frame = GetFocusedFrame();
2080 if (!focused_frame)
2081 return;
2083 focused_frame->Send(new InputMsg_MoveRangeSelectionExtent(
2084 focused_frame->GetRoutingID(), extent));
2087 void WebContentsImpl::SelectRange(const gfx::Point& base,
2088 const gfx::Point& extent) {
2089 RenderFrameHost* focused_frame = GetFocusedFrame();
2090 if (!focused_frame)
2091 return;
2093 focused_frame->Send(
2094 new InputMsg_SelectRange(focused_frame->GetRoutingID(), base, extent));
2097 void WebContentsImpl::AdjustSelectionByCharacterOffset(int start_adjust,
2098 int end_adjust) {
2099 RenderFrameHost* focused_frame = GetFocusedFrame();
2100 if (!focused_frame)
2101 return;
2103 focused_frame->Send(new InputMsg_AdjustSelectionByCharacterOffset(
2104 focused_frame->GetRoutingID(), start_adjust, end_adjust));
2107 void WebContentsImpl::UpdatePreferredSize(const gfx::Size& pref_size) {
2108 const gfx::Size old_size = GetPreferredSize();
2109 preferred_size_ = pref_size;
2110 OnPreferredSizeChanged(old_size);
2113 void WebContentsImpl::ResizeDueToAutoResize(const gfx::Size& new_size) {
2114 if (delegate_)
2115 delegate_->ResizeDueToAutoResize(this, new_size);
2118 WebContents* WebContentsImpl::OpenURL(const OpenURLParams& params) {
2119 if (!delegate_)
2120 return NULL;
2122 WebContents* new_contents = delegate_->OpenURLFromTab(this, params);
2123 return new_contents;
2126 bool WebContentsImpl::Send(IPC::Message* message) {
2127 if (!GetRenderViewHost()) {
2128 delete message;
2129 return false;
2132 return GetRenderViewHost()->Send(message);
2135 void WebContentsImpl::RenderFrameForInterstitialPageCreated(
2136 RenderFrameHost* render_frame_host) {
2137 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2138 RenderFrameForInterstitialPageCreated(render_frame_host));
2141 void WebContentsImpl::AttachInterstitialPage(
2142 InterstitialPageImpl* interstitial_page) {
2143 DCHECK(interstitial_page);
2144 GetRenderManager()->set_interstitial_page(interstitial_page);
2146 // Cancel any visible dialogs so that they don't interfere with the
2147 // interstitial.
2148 CancelActiveAndPendingDialogs();
2150 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2151 DidAttachInterstitialPage());
2154 void WebContentsImpl::DetachInterstitialPage() {
2155 if (ShowingInterstitialPage())
2156 GetRenderManager()->remove_interstitial_page();
2157 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2158 DidDetachInterstitialPage());
2161 void WebContentsImpl::SetHistoryOffsetAndLength(int history_offset,
2162 int history_length) {
2163 SetHistoryOffsetAndLengthForView(
2164 GetRenderViewHost(), history_offset, history_length);
2167 void WebContentsImpl::SetHistoryOffsetAndLengthForView(
2168 RenderViewHost* render_view_host,
2169 int history_offset,
2170 int history_length) {
2171 render_view_host->Send(new ViewMsg_SetHistoryOffsetAndLength(
2172 render_view_host->GetRoutingID(), history_offset, history_length));
2175 void WebContentsImpl::ReloadFocusedFrame(bool ignore_cache) {
2176 RenderFrameHost* focused_frame = GetFocusedFrame();
2177 if (!focused_frame)
2178 return;
2180 focused_frame->Send(new FrameMsg_Reload(
2181 focused_frame->GetRoutingID(), ignore_cache));
2184 void WebContentsImpl::Undo() {
2185 RenderFrameHost* focused_frame = GetFocusedFrame();
2186 if (!focused_frame)
2187 return;
2189 focused_frame->Send(new InputMsg_Undo(focused_frame->GetRoutingID()));
2190 RecordAction(base::UserMetricsAction("Undo"));
2193 void WebContentsImpl::Redo() {
2194 RenderFrameHost* focused_frame = GetFocusedFrame();
2195 if (!focused_frame)
2196 return;
2197 focused_frame->Send(new InputMsg_Redo(focused_frame->GetRoutingID()));
2198 RecordAction(base::UserMetricsAction("Redo"));
2201 void WebContentsImpl::Cut() {
2202 RenderFrameHost* focused_frame = GetFocusedFrame();
2203 if (!focused_frame)
2204 return;
2206 focused_frame->Send(new InputMsg_Cut(focused_frame->GetRoutingID()));
2207 RecordAction(base::UserMetricsAction("Cut"));
2210 void WebContentsImpl::Copy() {
2211 RenderFrameHost* focused_frame = GetFocusedFrame();
2212 if (!focused_frame)
2213 return;
2215 focused_frame->Send(new InputMsg_Copy(focused_frame->GetRoutingID()));
2216 RecordAction(base::UserMetricsAction("Copy"));
2219 void WebContentsImpl::CopyToFindPboard() {
2220 #if defined(OS_MACOSX)
2221 RenderFrameHost* focused_frame = GetFocusedFrame();
2222 if (!focused_frame)
2223 return;
2225 // Windows/Linux don't have the concept of a find pasteboard.
2226 focused_frame->Send(
2227 new InputMsg_CopyToFindPboard(focused_frame->GetRoutingID()));
2228 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
2229 #endif
2232 void WebContentsImpl::Paste() {
2233 RenderFrameHost* focused_frame = GetFocusedFrame();
2234 if (!focused_frame)
2235 return;
2237 focused_frame->Send(new InputMsg_Paste(focused_frame->GetRoutingID()));
2238 RecordAction(base::UserMetricsAction("Paste"));
2241 void WebContentsImpl::PasteAndMatchStyle() {
2242 RenderFrameHost* focused_frame = GetFocusedFrame();
2243 if (!focused_frame)
2244 return;
2246 focused_frame->Send(new InputMsg_PasteAndMatchStyle(
2247 focused_frame->GetRoutingID()));
2248 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
2251 void WebContentsImpl::Delete() {
2252 RenderFrameHost* focused_frame = GetFocusedFrame();
2253 if (!focused_frame)
2254 return;
2256 focused_frame->Send(new InputMsg_Delete(focused_frame->GetRoutingID()));
2257 RecordAction(base::UserMetricsAction("DeleteSelection"));
2260 void WebContentsImpl::SelectAll() {
2261 RenderFrameHost* focused_frame = GetFocusedFrame();
2262 if (!focused_frame)
2263 return;
2265 focused_frame->Send(new InputMsg_SelectAll(focused_frame->GetRoutingID()));
2266 RecordAction(base::UserMetricsAction("SelectAll"));
2269 void WebContentsImpl::Unselect() {
2270 RenderFrameHost* focused_frame = GetFocusedFrame();
2271 if (!focused_frame)
2272 return;
2274 focused_frame->Send(new InputMsg_Unselect(focused_frame->GetRoutingID()));
2275 RecordAction(base::UserMetricsAction("Unselect"));
2278 void WebContentsImpl::Replace(const base::string16& word) {
2279 RenderFrameHost* focused_frame = GetFocusedFrame();
2280 if (!focused_frame)
2281 return;
2283 focused_frame->Send(new InputMsg_Replace(
2284 focused_frame->GetRoutingID(), word));
2287 void WebContentsImpl::ReplaceMisspelling(const base::string16& word) {
2288 RenderFrameHost* focused_frame = GetFocusedFrame();
2289 if (!focused_frame)
2290 return;
2292 focused_frame->Send(new InputMsg_ReplaceMisspelling(
2293 focused_frame->GetRoutingID(), word));
2296 void WebContentsImpl::NotifyContextMenuClosed(
2297 const CustomContextMenuContext& context) {
2298 RenderFrameHost* focused_frame = GetFocusedFrame();
2299 if (!focused_frame)
2300 return;
2302 focused_frame->Send(new FrameMsg_ContextMenuClosed(
2303 focused_frame->GetRoutingID(), context));
2306 void WebContentsImpl::ExecuteCustomContextMenuCommand(
2307 int action, const CustomContextMenuContext& context) {
2308 RenderFrameHost* focused_frame = GetFocusedFrame();
2309 if (!focused_frame)
2310 return;
2312 focused_frame->Send(new FrameMsg_CustomContextMenuAction(
2313 focused_frame->GetRoutingID(), context, action));
2316 gfx::NativeView WebContentsImpl::GetNativeView() {
2317 return view_->GetNativeView();
2320 gfx::NativeView WebContentsImpl::GetContentNativeView() {
2321 return view_->GetContentNativeView();
2324 gfx::NativeWindow WebContentsImpl::GetTopLevelNativeWindow() {
2325 return view_->GetTopLevelNativeWindow();
2328 gfx::Rect WebContentsImpl::GetViewBounds() {
2329 return view_->GetViewBounds();
2332 gfx::Rect WebContentsImpl::GetContainerBounds() {
2333 gfx::Rect rv;
2334 view_->GetContainerBounds(&rv);
2335 return rv;
2338 DropData* WebContentsImpl::GetDropData() {
2339 return view_->GetDropData();
2342 void WebContentsImpl::Focus() {
2343 view_->Focus();
2346 void WebContentsImpl::SetInitialFocus() {
2347 view_->SetInitialFocus();
2350 void WebContentsImpl::StoreFocus() {
2351 view_->StoreFocus();
2354 void WebContentsImpl::RestoreFocus() {
2355 view_->RestoreFocus();
2358 void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
2359 if (ShowingInterstitialPage()) {
2360 GetRenderManager()->interstitial_page()->FocusThroughTabTraversal(reverse);
2361 return;
2363 RenderWidgetHostView* const fullscreen_view =
2364 GetFullscreenRenderWidgetHostView();
2365 if (fullscreen_view) {
2366 fullscreen_view->Focus();
2367 return;
2369 GetRenderViewHost()->SetInitialFocus(reverse);
2372 bool WebContentsImpl::ShowingInterstitialPage() const {
2373 return GetRenderManager()->interstitial_page() != NULL;
2376 InterstitialPage* WebContentsImpl::GetInterstitialPage() const {
2377 return GetRenderManager()->interstitial_page();
2380 bool WebContentsImpl::IsSavable() {
2381 // WebKit creates Document object when MIME type is application/xhtml+xml,
2382 // so we also support this MIME type.
2383 return contents_mime_type_ == "text/html" ||
2384 contents_mime_type_ == "text/xml" ||
2385 contents_mime_type_ == "application/xhtml+xml" ||
2386 contents_mime_type_ == "text/plain" ||
2387 contents_mime_type_ == "text/css" ||
2388 mime_util::IsSupportedJavascriptMimeType(contents_mime_type_);
2391 void WebContentsImpl::OnSavePage() {
2392 // If we can not save the page, try to download it.
2393 if (!IsSavable()) {
2394 RecordDownloadSource(INITIATED_BY_SAVE_PACKAGE_ON_NON_HTML);
2395 SaveFrame(GetLastCommittedURL(), Referrer());
2396 return;
2399 Stop();
2401 // Create the save package and possibly prompt the user for the name to save
2402 // the page as. The user prompt is an asynchronous operation that runs on
2403 // another thread.
2404 save_package_ = new SavePackage(this);
2405 save_package_->GetSaveInfo();
2408 // Used in automated testing to bypass prompting the user for file names.
2409 // Instead, the names and paths are hard coded rather than running them through
2410 // file name sanitation and extension / mime checking.
2411 bool WebContentsImpl::SavePage(const base::FilePath& main_file,
2412 const base::FilePath& dir_path,
2413 SavePageType save_type) {
2414 // Stop the page from navigating.
2415 Stop();
2417 save_package_ = new SavePackage(this, save_type, main_file, dir_path);
2418 return save_package_->Init(SavePackageDownloadCreatedCallback());
2421 void WebContentsImpl::SaveFrame(const GURL& url,
2422 const Referrer& referrer) {
2423 SaveFrameWithHeaders(url, referrer, std::string());
2426 void WebContentsImpl::SaveFrameWithHeaders(const GURL& url,
2427 const Referrer& referrer,
2428 const std::string& headers) {
2429 if (!GetLastCommittedURL().is_valid())
2430 return;
2431 if (delegate_ && delegate_->SaveFrame(url, referrer))
2432 return;
2434 // TODO(nasko): This check for main frame is incorrect and should be fixed
2435 // by explicitly passing in which frame this method should target.
2436 bool is_main_frame = (url == GetLastCommittedURL());
2438 DownloadManager* dlm =
2439 BrowserContext::GetDownloadManager(GetBrowserContext());
2440 if (!dlm)
2441 return;
2442 int64 post_id = -1;
2443 if (is_main_frame) {
2444 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2445 if (entry)
2446 post_id = entry->GetPostID();
2448 scoped_ptr<DownloadUrlParameters> params(
2449 DownloadUrlParameters::FromWebContents(this, url));
2450 params->set_referrer(referrer);
2451 params->set_post_id(post_id);
2452 if (post_id >= 0)
2453 params->set_method("POST");
2454 params->set_prompt(true);
2456 if (headers.empty()) {
2457 params->set_prefer_cache(true);
2458 } else {
2459 std::vector<std::string> key_value_list;
2460 base::SplitString(headers, '\n', &key_value_list);
2461 for (const auto& key_value : key_value_list) {
2462 std::vector<std::string> pair;
2463 base::SplitString(key_value, ':', &pair);
2464 DCHECK_EQ(2ul, pair.size());
2465 params->add_request_header(pair[0], pair[1]);
2468 dlm->DownloadUrl(params.Pass());
2471 void WebContentsImpl::GenerateMHTML(
2472 const base::FilePath& file,
2473 const base::Callback<void(int64)>& callback) {
2474 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, file, callback);
2477 const std::string& WebContentsImpl::GetContentsMimeType() const {
2478 return contents_mime_type_;
2481 bool WebContentsImpl::WillNotifyDisconnection() const {
2482 return notify_disconnection_;
2485 void WebContentsImpl::SetOverrideEncoding(const std::string& encoding) {
2486 SetEncoding(encoding);
2487 Send(new ViewMsg_SetPageEncoding(GetRoutingID(), encoding));
2490 void WebContentsImpl::ResetOverrideEncoding() {
2491 canonical_encoding_.clear();
2492 Send(new ViewMsg_ResetPageEncodingToDefault(GetRoutingID()));
2495 RendererPreferences* WebContentsImpl::GetMutableRendererPrefs() {
2496 return &renderer_preferences_;
2499 void WebContentsImpl::Close() {
2500 Close(GetRenderViewHost());
2503 void WebContentsImpl::DragSourceEndedAt(int client_x, int client_y,
2504 int screen_x, int screen_y, blink::WebDragOperation operation) {
2505 if (browser_plugin_embedder_.get())
2506 browser_plugin_embedder_->DragSourceEndedAt(client_x, client_y,
2507 screen_x, screen_y, operation);
2508 if (GetRenderViewHost())
2509 GetRenderViewHost()->DragSourceEndedAt(client_x, client_y, screen_x,
2510 screen_y, operation);
2513 void WebContentsImpl::DidGetResourceResponseStart(
2514 const ResourceRequestDetails& details) {
2515 controller_.ssl_manager()->DidStartResourceResponse(details);
2517 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2518 DidGetResourceResponseStart(details));
2521 void WebContentsImpl::DidGetRedirectForResourceRequest(
2522 RenderFrameHost* render_frame_host,
2523 const ResourceRedirectDetails& details) {
2524 controller_.ssl_manager()->DidReceiveResourceRedirect(details);
2526 FOR_EACH_OBSERVER(
2527 WebContentsObserver,
2528 observers_,
2529 DidGetRedirectForResourceRequest(render_frame_host, details));
2531 // TODO(avi): Remove. http://crbug.com/170921
2532 NotificationService::current()->Notify(
2533 NOTIFICATION_RESOURCE_RECEIVED_REDIRECT,
2534 Source<WebContents>(this),
2535 Details<const ResourceRedirectDetails>(&details));
2538 void WebContentsImpl::NotifyWebContentsFocused() {
2539 FOR_EACH_OBSERVER(WebContentsObserver, observers_, OnWebContentsFocused());
2542 void WebContentsImpl::SystemDragEnded() {
2543 if (GetRenderViewHost())
2544 GetRenderViewHost()->DragSourceSystemDragEnded();
2545 if (browser_plugin_embedder_.get())
2546 browser_plugin_embedder_->SystemDragEnded();
2549 void WebContentsImpl::UserGestureDone() {
2550 OnUserGesture();
2553 void WebContentsImpl::SetClosedByUserGesture(bool value) {
2554 closed_by_user_gesture_ = value;
2557 bool WebContentsImpl::GetClosedByUserGesture() const {
2558 return closed_by_user_gesture_;
2561 void WebContentsImpl::ViewSource() {
2562 if (!delegate_)
2563 return;
2565 NavigationEntry* entry = GetController().GetLastCommittedEntry();
2566 if (!entry)
2567 return;
2569 delegate_->ViewSourceForTab(this, entry->GetURL());
2572 void WebContentsImpl::ViewFrameSource(const GURL& url,
2573 const PageState& page_state) {
2574 if (!delegate_)
2575 return;
2577 delegate_->ViewSourceForFrame(this, url, page_state);
2580 int WebContentsImpl::GetMinimumZoomPercent() const {
2581 return minimum_zoom_percent_;
2584 int WebContentsImpl::GetMaximumZoomPercent() const {
2585 return maximum_zoom_percent_;
2588 void WebContentsImpl::ResetPageScale() {
2589 Send(new ViewMsg_ResetPageScale(GetRoutingID()));
2592 gfx::Size WebContentsImpl::GetPreferredSize() const {
2593 return capturer_count_ == 0 ? preferred_size_ : preferred_size_for_capture_;
2596 bool WebContentsImpl::GotResponseToLockMouseRequest(bool allowed) {
2597 if (GetBrowserPluginGuest())
2598 return GetBrowserPluginGuest()->LockMouse(allowed);
2600 return GetRenderViewHost()
2601 ? GetRenderViewHost()->GotResponseToLockMouseRequest(allowed)
2602 : false;
2605 bool WebContentsImpl::HasOpener() const {
2606 return GetOpener() != NULL;
2609 WebContentsImpl* WebContentsImpl::GetOpener() const {
2610 FrameTreeNode* opener_ftn = frame_tree_.root()->opener();
2611 return opener_ftn ? FromFrameTreeNode(opener_ftn) : nullptr;
2614 void WebContentsImpl::DidChooseColorInColorChooser(SkColor color) {
2615 if (!color_chooser_info_.get())
2616 return;
2617 RenderFrameHost* rfh = RenderFrameHost::FromID(
2618 color_chooser_info_->render_process_id,
2619 color_chooser_info_->render_frame_id);
2620 if (!rfh)
2621 return;
2623 rfh->Send(new FrameMsg_DidChooseColorResponse(
2624 rfh->GetRoutingID(), color_chooser_info_->identifier, color));
2627 void WebContentsImpl::DidEndColorChooser() {
2628 if (!color_chooser_info_.get())
2629 return;
2630 RenderFrameHost* rfh = RenderFrameHost::FromID(
2631 color_chooser_info_->render_process_id,
2632 color_chooser_info_->render_frame_id);
2633 if (!rfh)
2634 return;
2636 rfh->Send(new FrameMsg_DidEndColorChooser(
2637 rfh->GetRoutingID(), color_chooser_info_->identifier));
2638 color_chooser_info_.reset();
2641 int WebContentsImpl::DownloadImage(
2642 const GURL& url,
2643 bool is_favicon,
2644 uint32_t max_bitmap_size,
2645 bool bypass_cache,
2646 const WebContents::ImageDownloadCallback& callback) {
2647 static int next_image_download_id = 0;
2648 const image_downloader::ImageDownloaderPtr& mojo_image_downloader =
2649 GetMainFrame()->GetMojoImageDownloader();
2650 image_downloader::DownloadRequestPtr req =
2651 image_downloader::DownloadRequest::New();
2653 req->url = mojo::String::From(url);
2654 req->is_favicon = is_favicon;
2655 req->max_bitmap_size = max_bitmap_size;
2656 req->bypass_cache = bypass_cache;
2658 mojo_image_downloader->DownloadImage(
2659 req.Pass(),
2660 base::Bind(&DidDownloadImage, callback, ++next_image_download_id, url));
2661 return next_image_download_id;
2664 bool WebContentsImpl::IsSubframe() const {
2665 return is_subframe_;
2668 void WebContentsImpl::Find(int request_id,
2669 const base::string16& search_text,
2670 const blink::WebFindOptions& options) {
2671 // See if a top level browser plugin handles the find request first.
2672 if (browser_plugin_embedder_) {
2673 BrowserPluginGuest* guest = browser_plugin_embedder_->GetFullPageGuest();
2674 if (guest && guest->Find(request_id, search_text, options))
2675 return;
2677 Send(new ViewMsg_Find(GetRoutingID(), request_id, search_text, options));
2680 void WebContentsImpl::StopFinding(StopFindAction action) {
2681 // See if a top level browser plugin handles the stop finding request first.
2682 if (browser_plugin_embedder_) {
2683 BrowserPluginGuest* guest = browser_plugin_embedder_->GetFullPageGuest();
2684 if (guest && guest->StopFinding(action))
2685 return;
2687 Send(new ViewMsg_StopFinding(GetRoutingID(), action));
2690 void WebContentsImpl::InsertCSS(const std::string& css) {
2691 GetMainFrame()->Send(new FrameMsg_CSSInsertRequest(
2692 GetMainFrame()->GetRoutingID(), css));
2695 bool WebContentsImpl::WasRecentlyAudible() {
2696 return audio_state_provider_->WasRecentlyAudible();
2699 void WebContentsImpl::GetManifest(const GetManifestCallback& callback) {
2700 manifest_manager_host_->GetManifest(GetMainFrame(), callback);
2703 void WebContentsImpl::ExitFullscreen() {
2704 // Clean up related state and initiate the fullscreen exit.
2705 GetRenderViewHost()->RejectMouseLockOrUnlockIfNecessary();
2706 ExitFullscreenMode();
2709 void WebContentsImpl::ResumeLoadingCreatedWebContents() {
2710 if (delayed_open_url_params_.get()) {
2711 OpenURL(*delayed_open_url_params_.get());
2712 delayed_open_url_params_.reset(nullptr);
2713 return;
2716 // Resume blocked requests for both the RenderViewHost and RenderFrameHost.
2717 // TODO(brettw): It seems bogus to reach into here and initialize the host.
2718 if (is_resume_pending_) {
2719 is_resume_pending_ = false;
2720 GetRenderViewHost()->Init();
2721 GetMainFrame()->Init();
2725 bool WebContentsImpl::FocusLocationBarByDefault() {
2726 NavigationEntry* entry = controller_.GetVisibleEntry();
2727 if (entry && entry->GetURL() == GURL(url::kAboutBlankURL))
2728 return true;
2729 return delegate_ && delegate_->ShouldFocusLocationBarByDefault(this);
2732 void WebContentsImpl::SetFocusToLocationBar(bool select_all) {
2733 if (delegate_)
2734 delegate_->SetFocusToLocationBar(select_all);
2737 void WebContentsImpl::DidStartProvisionalLoad(
2738 RenderFrameHostImpl* render_frame_host,
2739 const GURL& validated_url,
2740 bool is_error_page,
2741 bool is_iframe_srcdoc) {
2742 // Notify observers about the start of the provisional load.
2743 FOR_EACH_OBSERVER(
2744 WebContentsObserver,
2745 observers_,
2746 DidStartProvisionalLoadForFrame(
2747 render_frame_host, validated_url, is_error_page, is_iframe_srcdoc));
2749 // Notify accessibility if this is a reload.
2750 NavigationEntry* entry = controller_.GetVisibleEntry();
2751 if (entry && ui::PageTransitionCoreTypeIs(
2752 entry->GetTransitionType(), ui::PAGE_TRANSITION_RELOAD)) {
2753 FrameTreeNode* ftn = render_frame_host->frame_tree_node();
2754 BrowserAccessibilityManager* manager =
2755 ftn->current_frame_host()->browser_accessibility_manager();
2756 if (manager)
2757 manager->UserIsReloading();
2761 void WebContentsImpl::DidFailProvisionalLoadWithError(
2762 RenderFrameHostImpl* render_frame_host,
2763 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
2764 GURL validated_url(params.url);
2765 FOR_EACH_OBSERVER(WebContentsObserver,
2766 observers_,
2767 DidFailProvisionalLoad(render_frame_host,
2768 validated_url,
2769 params.error_code,
2770 params.error_description,
2771 params.was_ignored_by_handler));
2773 FrameTreeNode* ftn = render_frame_host->frame_tree_node();
2774 BrowserAccessibilityManager* manager =
2775 ftn->current_frame_host()->browser_accessibility_manager();
2776 if (manager)
2777 manager->NavigationFailed();
2780 void WebContentsImpl::DidFailLoadWithError(
2781 RenderFrameHostImpl* render_frame_host,
2782 const GURL& url,
2783 int error_code,
2784 const base::string16& error_description,
2785 bool was_ignored_by_handler) {
2786 FOR_EACH_OBSERVER(
2787 WebContentsObserver,
2788 observers_,
2789 DidFailLoad(render_frame_host, url, error_code, error_description,
2790 was_ignored_by_handler));
2793 void WebContentsImpl::NotifyChangedNavigationState(
2794 InvalidateTypes changed_flags) {
2795 NotifyNavigationStateChanged(changed_flags);
2798 void WebContentsImpl::AboutToNavigateRenderFrame(
2799 RenderFrameHostImpl* old_host,
2800 RenderFrameHostImpl* new_host) {
2801 // Notify observers that we will navigate in this RenderFrame.
2802 FOR_EACH_OBSERVER(
2803 WebContentsObserver,
2804 observers_,
2805 AboutToNavigateRenderFrame(old_host, new_host));
2808 void WebContentsImpl::DidStartNavigationToPendingEntry(
2809 const GURL& url,
2810 NavigationController::ReloadType reload_type) {
2811 // Notify observers about navigation.
2812 FOR_EACH_OBSERVER(
2813 WebContentsObserver,
2814 observers_,
2815 DidStartNavigationToPendingEntry(url, reload_type));
2818 void WebContentsImpl::RequestOpenURL(RenderFrameHostImpl* render_frame_host,
2819 const OpenURLParams& params) {
2820 // OpenURL can blow away the source RFH. Use the process/frame routing ID as a
2821 // weak pointer of sorts.
2822 const int32_t process_id = render_frame_host->GetProcess()->GetID();
2823 const int32_t frame_id = render_frame_host->GetRoutingID();
2825 WebContents* new_contents = OpenURL(params);
2827 if (new_contents && RenderFrameHost::FromID(process_id, frame_id)) {
2828 // Notify observers.
2829 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2830 DidOpenRequestedURL(new_contents,
2831 render_frame_host,
2832 params.url,
2833 params.referrer,
2834 params.disposition,
2835 params.transition));
2839 bool WebContentsImpl::ShouldPreserveAbortedURLs() {
2840 if (!delegate_)
2841 return false;
2842 return delegate_->ShouldPreserveAbortedURLs(this);
2845 void WebContentsImpl::DidCommitProvisionalLoad(
2846 RenderFrameHostImpl* render_frame_host,
2847 const GURL& url,
2848 ui::PageTransition transition_type) {
2849 // Notify observers about the commit of the provisional load.
2850 FOR_EACH_OBSERVER(WebContentsObserver,
2851 observers_,
2852 DidCommitProvisionalLoadForFrame(
2853 render_frame_host, url, transition_type));
2855 BrowserAccessibilityManager* manager =
2856 render_frame_host->browser_accessibility_manager();
2857 if (manager)
2858 manager->NavigationSucceeded();
2861 void WebContentsImpl::DidNavigateMainFramePreCommit(
2862 bool navigation_is_within_page) {
2863 // Ensure fullscreen mode is exited before committing the navigation to a
2864 // different page. The next page will not start out assuming it is in
2865 // fullscreen mode.
2866 if (navigation_is_within_page) {
2867 // No page change? Then, the renderer and browser can remain in fullscreen.
2868 return;
2870 if (IsFullscreenForCurrentTab())
2871 ExitFullscreen();
2872 DCHECK(!IsFullscreenForCurrentTab());
2875 void WebContentsImpl::DidNavigateMainFramePostCommit(
2876 RenderFrameHostImpl* render_frame_host,
2877 const LoadCommittedDetails& details,
2878 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
2879 if (details.is_navigation_to_different_page()) {
2880 // Clear the status bubble. This is a workaround for a bug where WebKit
2881 // doesn't let us know that the cursor left an element during a
2882 // transition (this is also why the mouse cursor remains as a hand after
2883 // clicking on a link); see bugs 1184641 and 980803. We don't want to
2884 // clear the bubble when a user navigates to a named anchor in the same
2885 // page.
2886 UpdateTargetURL(render_frame_host->GetRenderViewHost(), GURL());
2888 RenderWidgetHostViewBase* rwhvb =
2889 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
2890 if (rwhvb)
2891 rwhvb->OnDidNavigateMainFrameToNewPage();
2893 did_first_visually_non_empty_paint_ = false;
2895 // Reset theme color on navigation to new page.
2896 theme_color_ = SK_ColorTRANSPARENT;
2899 if (!details.is_in_page) {
2900 // Once the main frame is navigated, we're no longer considered to have
2901 // displayed insecure content.
2902 displayed_insecure_content_ = false;
2903 SSLManager::NotifySSLInternalStateChanged(
2904 GetController().GetBrowserContext());
2907 // Notify observers about navigation.
2908 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2909 DidNavigateMainFrame(details, params));
2911 if (delegate_)
2912 delegate_->DidNavigateMainFramePostCommit(this);
2913 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
2916 void WebContentsImpl::DidNavigateAnyFramePostCommit(
2917 RenderFrameHostImpl* render_frame_host,
2918 const LoadCommittedDetails& details,
2919 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
2920 // Now that something has committed, we don't need to track whether the
2921 // initial page has been accessed.
2922 has_accessed_initial_document_ = false;
2924 // If we navigate off the page, close all JavaScript dialogs.
2925 if (!details.is_in_page)
2926 CancelActiveAndPendingDialogs();
2928 // Notify observers about navigation.
2929 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2930 DidNavigateAnyFrame(render_frame_host, details, params));
2933 void WebContentsImpl::SetMainFrameMimeType(const std::string& mime_type) {
2934 contents_mime_type_ = mime_type;
2937 bool WebContentsImpl::CanOverscrollContent() const {
2938 // Disable overscroll when touch emulation is on. See crbug.com/369938.
2939 if (force_disable_overscroll_content_)
2940 return false;
2942 if (delegate_)
2943 return delegate_->CanOverscrollContent();
2945 return false;
2948 void WebContentsImpl::OnThemeColorChanged(SkColor theme_color) {
2949 // Update the theme color. This is to be published to observers after the
2950 // first visually non-empty paint.
2951 theme_color_ = theme_color;
2953 if (did_first_visually_non_empty_paint_ &&
2954 last_sent_theme_color_ != theme_color_) {
2955 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2956 DidChangeThemeColor(theme_color_));
2957 last_sent_theme_color_ = theme_color_;
2961 void WebContentsImpl::OnDidLoadResourceFromMemoryCache(
2962 const GURL& url,
2963 const std::string& security_info,
2964 const std::string& http_method,
2965 const std::string& mime_type,
2966 ResourceType resource_type) {
2967 SSLStatus status;
2968 if (!DeserializeSecurityInfo(security_info, &status)) {
2969 bad_message::ReceivedBadMessage(
2970 GetRenderProcessHost(),
2971 bad_message::WC_MEMORY_CACHE_RESOURCE_BAD_SECURITY_INFO);
2972 return;
2975 // Send out a notification that we loaded a resource from our memory cache.
2976 // TODO(alcutter,eranm): Pass signed_certificate_timestamp_ids into details.
2977 LoadFromMemoryCacheDetails details(
2978 url, GetRenderProcessHost()->GetID(), status.cert_id, status.cert_status,
2979 http_method, mime_type, resource_type);
2981 controller_.ssl_manager()->DidLoadFromMemoryCache(details);
2983 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2984 DidLoadResourceFromMemoryCache(details));
2986 if (url.is_valid() && url.SchemeIsHTTPOrHTTPS()) {
2987 scoped_refptr<net::URLRequestContextGetter> request_context(
2988 resource_type == RESOURCE_TYPE_MEDIA ?
2989 GetBrowserContext()->GetMediaRequestContextForRenderProcess(
2990 GetRenderProcessHost()->GetID()) :
2991 GetBrowserContext()->GetRequestContextForRenderProcess(
2992 GetRenderProcessHost()->GetID()));
2993 BrowserThread::PostTask(
2994 BrowserThread::IO,
2995 FROM_HERE,
2996 base::Bind(&NotifyCacheOnIO, request_context, url, http_method));
3000 void WebContentsImpl::OnDidDisplayInsecureContent() {
3001 RecordAction(base::UserMetricsAction("SSL.DisplayedInsecureContent"));
3002 displayed_insecure_content_ = true;
3003 SSLManager::NotifySSLInternalStateChanged(
3004 GetController().GetBrowserContext());
3007 void WebContentsImpl::OnDidRunInsecureContent(
3008 const std::string& security_origin, const GURL& target_url) {
3009 LOG(WARNING) << security_origin << " ran insecure content from "
3010 << target_url.possibly_invalid_spec();
3011 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
3012 if (base::EndsWith(security_origin, kDotGoogleDotCom,
3013 base::CompareCase::INSENSITIVE_ASCII))
3014 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
3015 controller_.ssl_manager()->DidRunInsecureContent(security_origin);
3016 displayed_insecure_content_ = true;
3017 SSLManager::NotifySSLInternalStateChanged(
3018 GetController().GetBrowserContext());
3021 void WebContentsImpl::OnDocumentLoadedInFrame() {
3022 if (!HasValidFrameSource())
3023 return;
3025 RenderFrameHostImpl* rfh =
3026 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
3027 FOR_EACH_OBSERVER(
3028 WebContentsObserver, observers_, DocumentLoadedInFrame(rfh));
3031 void WebContentsImpl::OnDidFinishLoad(const GURL& url) {
3032 if (!HasValidFrameSource())
3033 return;
3035 GURL validated_url(url);
3036 RenderProcessHost* render_process_host =
3037 render_frame_message_source_->GetProcess();
3038 render_process_host->FilterURL(false, &validated_url);
3040 RenderFrameHostImpl* rfh =
3041 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
3042 FOR_EACH_OBSERVER(
3043 WebContentsObserver, observers_, DidFinishLoad(rfh, validated_url));
3046 void WebContentsImpl::OnGoToEntryAtOffset(int offset) {
3047 if (!delegate_ || delegate_->OnGoToEntryOffset(offset))
3048 controller_.GoToOffset(offset);
3051 void WebContentsImpl::OnUpdateZoomLimits(int minimum_percent,
3052 int maximum_percent) {
3053 minimum_zoom_percent_ = minimum_percent;
3054 maximum_zoom_percent_ = maximum_percent;
3057 void WebContentsImpl::OnEnumerateDirectory(int request_id,
3058 const base::FilePath& path) {
3059 if (!delegate_)
3060 return;
3062 ChildProcessSecurityPolicyImpl* policy =
3063 ChildProcessSecurityPolicyImpl::GetInstance();
3064 if (policy->CanReadFile(GetRenderProcessHost()->GetID(), path))
3065 delegate_->EnumerateDirectory(this, request_id, path);
3068 void WebContentsImpl::OnRegisterProtocolHandler(const std::string& protocol,
3069 const GURL& url,
3070 const base::string16& title,
3071 bool user_gesture) {
3072 if (!delegate_)
3073 return;
3075 ChildProcessSecurityPolicyImpl* policy =
3076 ChildProcessSecurityPolicyImpl::GetInstance();
3077 if (policy->IsPseudoScheme(protocol))
3078 return;
3080 delegate_->RegisterProtocolHandler(this, protocol, url, user_gesture);
3083 void WebContentsImpl::OnUnregisterProtocolHandler(const std::string& protocol,
3084 const GURL& url,
3085 bool user_gesture) {
3086 if (!delegate_)
3087 return;
3089 ChildProcessSecurityPolicyImpl* policy =
3090 ChildProcessSecurityPolicyImpl::GetInstance();
3091 if (policy->IsPseudoScheme(protocol))
3092 return;
3094 delegate_->UnregisterProtocolHandler(this, protocol, url, user_gesture);
3097 void WebContentsImpl::OnFindReply(int request_id,
3098 int number_of_matches,
3099 const gfx::Rect& selection_rect,
3100 int active_match_ordinal,
3101 bool final_update) {
3102 if (delegate_) {
3103 delegate_->FindReply(this, request_id, number_of_matches, selection_rect,
3104 active_match_ordinal, final_update);
3108 #if defined(OS_ANDROID)
3109 void WebContentsImpl::OnFindMatchRectsReply(
3110 int version,
3111 const std::vector<gfx::RectF>& rects,
3112 const gfx::RectF& active_rect) {
3113 if (delegate_)
3114 delegate_->FindMatchRectsReply(this, version, rects, active_rect);
3117 void WebContentsImpl::OnOpenDateTimeDialog(
3118 const ViewHostMsg_DateTimeDialogValue_Params& value) {
3119 date_time_chooser_->ShowDialog(GetTopLevelNativeWindow(),
3120 GetRenderViewHost(),
3121 value.dialog_type,
3122 value.dialog_value,
3123 value.minimum,
3124 value.maximum,
3125 value.step,
3126 value.suggestions);
3128 #endif
3130 void WebContentsImpl::OnDomOperationResponse(const std::string& json_string,
3131 int automation_id) {
3132 DomOperationNotificationDetails details(json_string, automation_id);
3133 NotificationService::current()->Notify(
3134 NOTIFICATION_DOM_OPERATION_RESPONSE,
3135 Source<WebContents>(this),
3136 Details<DomOperationNotificationDetails>(&details));
3139 void WebContentsImpl::OnAppCacheAccessed(const GURL& manifest_url,
3140 bool blocked_by_policy) {
3141 // Notify observers about navigation.
3142 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3143 AppCacheAccessed(manifest_url, blocked_by_policy));
3146 void WebContentsImpl::OnOpenColorChooser(
3147 int color_chooser_id,
3148 SkColor color,
3149 const std::vector<ColorSuggestion>& suggestions) {
3150 if (!HasValidFrameSource())
3151 return;
3153 ColorChooser* new_color_chooser = delegate_ ?
3154 delegate_->OpenColorChooser(this, color, suggestions) :
3155 NULL;
3156 if (!new_color_chooser)
3157 return;
3158 if (color_chooser_info_.get())
3159 color_chooser_info_->chooser->End();
3161 color_chooser_info_.reset(new ColorChooserInfo(
3162 render_frame_message_source_->GetProcess()->GetID(),
3163 render_frame_message_source_->GetRoutingID(),
3164 new_color_chooser,
3165 color_chooser_id));
3168 void WebContentsImpl::OnEndColorChooser(int color_chooser_id) {
3169 if (color_chooser_info_ &&
3170 color_chooser_id == color_chooser_info_->identifier)
3171 color_chooser_info_->chooser->End();
3174 void WebContentsImpl::OnSetSelectedColorInColorChooser(int color_chooser_id,
3175 SkColor color) {
3176 if (color_chooser_info_ &&
3177 color_chooser_id == color_chooser_info_->identifier)
3178 color_chooser_info_->chooser->SetSelectedColor(color);
3181 // This exists for render views that don't have a WebUI, but do have WebUI
3182 // bindings enabled.
3183 void WebContentsImpl::OnWebUISend(const GURL& source_url,
3184 const std::string& name,
3185 const base::ListValue& args) {
3186 if (delegate_)
3187 delegate_->WebUISend(this, source_url, name, args);
3190 #if defined(ENABLE_PLUGINS)
3191 void WebContentsImpl::OnPepperInstanceCreated() {
3192 FOR_EACH_OBSERVER(WebContentsObserver, observers_, PepperInstanceCreated());
3195 void WebContentsImpl::OnPepperInstanceDeleted() {
3196 FOR_EACH_OBSERVER(WebContentsObserver, observers_, PepperInstanceDeleted());
3199 void WebContentsImpl::OnPepperPluginHung(int plugin_child_id,
3200 const base::FilePath& path,
3201 bool is_hung) {
3202 UMA_HISTOGRAM_COUNTS("Pepper.PluginHung", 1);
3204 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3205 PluginHungStatusChanged(plugin_child_id, path, is_hung));
3208 void WebContentsImpl::OnPluginCrashed(const base::FilePath& plugin_path,
3209 base::ProcessId plugin_pid) {
3210 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3211 PluginCrashed(plugin_path, plugin_pid));
3214 void WebContentsImpl::OnRequestPpapiBrokerPermission(
3215 int routing_id,
3216 const GURL& url,
3217 const base::FilePath& plugin_path) {
3218 if (!delegate_) {
3219 OnPpapiBrokerPermissionResult(routing_id, false);
3220 return;
3223 if (!delegate_->RequestPpapiBrokerPermission(
3224 this, url, plugin_path,
3225 base::Bind(&WebContentsImpl::OnPpapiBrokerPermissionResult,
3226 base::Unretained(this), routing_id))) {
3227 NOTIMPLEMENTED();
3228 OnPpapiBrokerPermissionResult(routing_id, false);
3232 void WebContentsImpl::OnPpapiBrokerPermissionResult(int routing_id,
3233 bool result) {
3234 Send(new ViewMsg_PpapiBrokerPermissionResult(routing_id, result));
3237 void WebContentsImpl::OnBrowserPluginMessage(RenderFrameHost* render_frame_host,
3238 const IPC::Message& message) {
3239 CHECK(!browser_plugin_embedder_.get());
3240 CreateBrowserPluginEmbedderIfNecessary();
3241 browser_plugin_embedder_->OnMessageReceived(message, render_frame_host);
3243 #endif // defined(ENABLE_PLUGINS)
3245 void WebContentsImpl::OnUpdateFaviconURL(
3246 const std::vector<FaviconURL>& candidates) {
3247 // We get updated favicon URLs after the page stops loading. If a cross-site
3248 // navigation occurs while a page is still loading, the initial page
3249 // may stop loading and send us updated favicon URLs after the navigation
3250 // for the new page has committed.
3251 RenderViewHostImpl* rvhi =
3252 static_cast<RenderViewHostImpl*>(render_view_message_source_);
3253 if (!rvhi->is_active())
3254 return;
3256 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3257 DidUpdateFaviconURL(candidates));
3260 void WebContentsImpl::CreateAudioPowerSaveBlocker() {
3261 DCHECK(!audio_power_save_blocker_);
3262 audio_power_save_blocker_ = PowerSaveBlocker::Create(
3263 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension,
3264 PowerSaveBlocker::kReasonAudioPlayback, "Playing audio");
3267 void WebContentsImpl::CreateVideoPowerSaveBlocker() {
3268 DCHECK(!video_power_save_blocker_);
3269 DCHECK(!active_video_players_.empty());
3270 video_power_save_blocker_ = PowerSaveBlocker::Create(
3271 PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep,
3272 PowerSaveBlocker::kReasonVideoPlayback, "Playing video");
3273 #if defined(OS_ANDROID)
3274 static_cast<PowerSaveBlockerImpl*>(video_power_save_blocker_.get())
3275 ->InitDisplaySleepBlocker(this);
3276 #endif
3279 void WebContentsImpl::MaybeReleasePowerSaveBlockers() {
3280 // If there are no more audio players and we don't have audio stream
3281 // monitoring, release the audio power save blocker here instead of during
3282 // NotifyNavigationStateChanged().
3283 if (active_audio_players_.empty() &&
3284 !audio_state_provider_->IsAudioStateAvailable()) {
3285 audio_power_save_blocker_.reset();
3288 // If there are no more video players, clear the video power save blocker.
3289 if (active_video_players_.empty())
3290 video_power_save_blocker_.reset();
3293 void WebContentsImpl::OnMediaPlayingNotification(int64 player_cookie,
3294 bool has_video,
3295 bool has_audio,
3296 bool is_remote) {
3297 // Ignore the videos playing remotely and don't hold the wake lock for the
3298 // screen.
3299 if (is_remote) return;
3301 if (has_audio) {
3302 AddMediaPlayerEntry(player_cookie, &active_audio_players_);
3304 // If we don't have audio stream monitoring, allocate the audio power save
3305 // blocker here instead of during NotifyNavigationStateChanged().
3306 if (!audio_power_save_blocker_ &&
3307 !audio_state_provider_->IsAudioStateAvailable()) {
3308 CreateAudioPowerSaveBlocker();
3312 if (has_video) {
3313 AddMediaPlayerEntry(player_cookie, &active_video_players_);
3315 // If we're not hidden and have just created a player, create a blocker.
3316 if (!video_power_save_blocker_ && !IsHidden())
3317 CreateVideoPowerSaveBlocker();
3320 FOR_EACH_OBSERVER(WebContentsObserver, observers_, MediaStartedPlaying());
3323 void WebContentsImpl::OnMediaPausedNotification(int64 player_cookie) {
3324 RemoveMediaPlayerEntry(player_cookie, &active_audio_players_);
3325 RemoveMediaPlayerEntry(player_cookie, &active_video_players_);
3326 MaybeReleasePowerSaveBlockers();
3328 FOR_EACH_OBSERVER(WebContentsObserver, observers_, MediaPaused());
3331 #if defined(OS_ANDROID)
3333 void WebContentsImpl::OnMediaSessionStateChanged() {
3334 MediaSession* session = MediaSession::Get(this);
3335 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3336 MediaSessionStateChanged(session->IsControllable(),
3337 session->IsSuspended()));
3340 void WebContentsImpl::ResumeMediaSession() {
3341 MediaSession::Get(this)->Resume();
3344 void WebContentsImpl::SuspendMediaSession() {
3345 MediaSession::Get(this)->Suspend();
3348 #endif // defined(OS_ANDROID)
3350 void WebContentsImpl::OnFirstVisuallyNonEmptyPaint() {
3351 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3352 DidFirstVisuallyNonEmptyPaint());
3354 did_first_visually_non_empty_paint_ = true;
3356 if (theme_color_ != last_sent_theme_color_) {
3357 // Theme color should have updated by now if there was one.
3358 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3359 DidChangeThemeColor(theme_color_));
3360 last_sent_theme_color_ = theme_color_;
3364 void WebContentsImpl::DidChangeVisibleSSLState() {
3365 if (delegate_) {
3366 delegate_->VisibleSSLStateChanged(this);
3368 SecurityStyleExplanations security_style_explanations;
3369 SecurityStyle security_style =
3370 delegate_->GetSecurityStyle(this, &security_style_explanations);
3371 FOR_EACH_OBSERVER(
3372 WebContentsObserver, observers_,
3373 SecurityStyleChanged(security_style, security_style_explanations));
3377 void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
3378 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3379 BeforeFormRepostWarningShow());
3382 void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
3383 Activate();
3384 if (delegate_)
3385 delegate_->ShowRepostFormWarningDialog(this);
3388 bool WebContentsImpl::HasAccessedInitialDocument() {
3389 return has_accessed_initial_document_;
3392 // Notifies the RenderWidgetHost instance about the fact that the page is
3393 // loading, or done loading.
3394 void WebContentsImpl::SetIsLoading(bool is_loading,
3395 bool to_different_document,
3396 LoadNotificationDetails* details) {
3397 if (is_loading == is_loading_)
3398 return;
3400 if (!is_loading) {
3401 load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
3402 base::string16());
3403 load_state_host_.clear();
3404 upload_size_ = 0;
3405 upload_position_ = 0;
3408 GetRenderManager()->SetIsLoading(is_loading);
3410 is_loading_ = is_loading;
3411 waiting_for_response_ = is_loading;
3412 is_load_to_different_document_ = to_different_document;
3414 if (delegate_)
3415 delegate_->LoadingStateChanged(this, to_different_document);
3416 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
3418 std::string url = (details ? details->url.possibly_invalid_spec() : "NULL");
3419 if (is_loading) {
3420 TRACE_EVENT_ASYNC_BEGIN1("browser,navigation", "WebContentsImpl Loading",
3421 this, "URL", url);
3422 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidStartLoading());
3423 } else {
3424 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
3425 this, "URL", url);
3426 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidStopLoading());
3429 // TODO(avi): Remove. http://crbug.com/170921
3430 int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
3431 NotificationDetails det = NotificationService::NoDetails();
3432 if (details)
3433 det = Details<LoadNotificationDetails>(details);
3434 NotificationService::current()->Notify(
3435 type, Source<NavigationController>(&controller_), det);
3438 void WebContentsImpl::UpdateMaxPageIDIfNecessary(RenderViewHost* rvh) {
3439 // If we are creating a RVH for a restored controller, then we need to make
3440 // sure the RenderView starts with a next_page_id_ larger than the number
3441 // of restored entries. This must be called before the RenderView starts
3442 // navigating (to avoid a race between the browser updating max_page_id and
3443 // the renderer updating next_page_id_). Because of this, we only call this
3444 // from CreateRenderView and allow that to notify the RenderView for us.
3445 int max_restored_page_id = controller_.GetMaxRestoredPageID();
3446 if (max_restored_page_id >
3447 GetMaxPageIDForSiteInstance(rvh->GetSiteInstance()))
3448 UpdateMaxPageIDForSiteInstance(rvh->GetSiteInstance(),
3449 max_restored_page_id);
3452 bool WebContentsImpl::UpdateTitleForEntry(NavigationEntryImpl* entry,
3453 const base::string16& title) {
3454 // For file URLs without a title, use the pathname instead. In the case of a
3455 // synthesized title, we don't want the update to count toward the "one set
3456 // per page of the title to history."
3457 base::string16 final_title;
3458 bool explicit_set;
3459 if (entry && entry->GetURL().SchemeIsFile() && title.empty()) {
3460 final_title = base::UTF8ToUTF16(entry->GetURL().ExtractFileName());
3461 explicit_set = false; // Don't count synthetic titles toward the set limit.
3462 } else {
3463 base::TrimWhitespace(title, base::TRIM_ALL, &final_title);
3464 explicit_set = true;
3467 // If a page is created via window.open and never navigated,
3468 // there will be no navigation entry. In this situation,
3469 // |page_title_when_no_navigation_entry_| will be used for page title.
3470 if (entry) {
3471 if (final_title == entry->GetTitle())
3472 return false; // Nothing changed, don't bother.
3474 entry->SetTitle(final_title);
3475 } else {
3476 if (page_title_when_no_navigation_entry_ == final_title)
3477 return false; // Nothing changed, don't bother.
3479 page_title_when_no_navigation_entry_ = final_title;
3482 // Lastly, set the title for the view.
3483 view_->SetPageTitle(final_title);
3485 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3486 TitleWasSet(entry, explicit_set));
3488 return true;
3491 void WebContentsImpl::SendChangeLoadProgress() {
3492 loading_last_progress_update_ = base::TimeTicks::Now();
3493 if (delegate_)
3494 delegate_->LoadProgressChanged(this, frame_tree_.load_progress());
3497 void WebContentsImpl::ResetLoadProgressState() {
3498 frame_tree_.ResetLoadProgress();
3499 loading_weak_factory_.InvalidateWeakPtrs();
3500 loading_last_progress_update_ = base::TimeTicks();
3503 void WebContentsImpl::NotifyViewSwapped(RenderViewHost* old_host,
3504 RenderViewHost* new_host) {
3505 // After sending out a swap notification, we need to send a disconnect
3506 // notification so that clients that pick up a pointer to |this| can NULL the
3507 // pointer. See Bug 1230284.
3508 notify_disconnection_ = true;
3509 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3510 RenderViewHostChanged(old_host, new_host));
3512 // Ensure that the associated embedder gets cleared after a RenderViewHost
3513 // gets swapped, so we don't reuse the same embedder next time a
3514 // RenderViewHost is attached to this WebContents.
3515 RemoveBrowserPluginEmbedder();
3518 void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost* old_host,
3519 RenderFrameHost* new_host) {
3520 FOR_EACH_OBSERVER(WebContentsObserver,
3521 observers_,
3522 RenderFrameHostChanged(old_host, new_host));
3525 // TODO(avi): Remove this entire function because this notification is already
3526 // covered by two observer functions. http://crbug.com/170921
3527 void WebContentsImpl::NotifyDisconnected() {
3528 if (!notify_disconnection_)
3529 return;
3531 notify_disconnection_ = false;
3532 NotificationService::current()->Notify(
3533 NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
3534 Source<WebContents>(this),
3535 NotificationService::NoDetails());
3538 void WebContentsImpl::NotifyNavigationEntryCommitted(
3539 const LoadCommittedDetails& load_details) {
3540 FOR_EACH_OBSERVER(
3541 WebContentsObserver, observers_, NavigationEntryCommitted(load_details));
3544 bool WebContentsImpl::OnMessageReceived(RenderFrameHost* render_frame_host,
3545 const IPC::Message& message) {
3546 return OnMessageReceived(NULL, render_frame_host, message);
3549 const GURL& WebContentsImpl::GetMainFrameLastCommittedURL() const {
3550 return GetLastCommittedURL();
3553 void WebContentsImpl::RenderFrameCreated(RenderFrameHost* render_frame_host) {
3554 // Note this is only for subframes, the notification for the main frame
3555 // happens in RenderViewCreated.
3556 FOR_EACH_OBSERVER(WebContentsObserver,
3557 observers_,
3558 RenderFrameCreated(render_frame_host));
3559 SetAccessibilityModeOnFrame(accessibility_mode_, render_frame_host);
3562 void WebContentsImpl::RenderFrameDeleted(RenderFrameHost* render_frame_host) {
3563 ClearPowerSaveBlockers(render_frame_host);
3564 FOR_EACH_OBSERVER(WebContentsObserver,
3565 observers_,
3566 RenderFrameDeleted(render_frame_host));
3569 void WebContentsImpl::ShowContextMenu(RenderFrameHost* render_frame_host,
3570 const ContextMenuParams& params) {
3571 ContextMenuParams context_menu_params(params);
3572 // Allow WebContentsDelegates to handle the context menu operation first.
3573 if (delegate_ && delegate_->HandleContextMenu(context_menu_params))
3574 return;
3576 render_view_host_delegate_view_->ShowContextMenu(render_frame_host,
3577 context_menu_params);
3580 void WebContentsImpl::RunJavaScriptMessage(
3581 RenderFrameHost* render_frame_host,
3582 const base::string16& message,
3583 const base::string16& default_prompt,
3584 const GURL& frame_url,
3585 JavaScriptMessageType javascript_message_type,
3586 IPC::Message* reply_msg) {
3587 // Suppress JavaScript dialogs when requested. Also suppress messages when
3588 // showing an interstitial as it's shown over the previous page and we don't
3589 // want the hidden page's dialogs to interfere with the interstitial.
3590 bool suppress_this_message =
3591 static_cast<RenderFrameHostImpl*>(render_frame_host)->is_swapped_out() ||
3592 ShowingInterstitialPage() || !delegate_ ||
3593 delegate_->ShouldSuppressDialogs(this) ||
3594 !delegate_->GetJavaScriptDialogManager(this);
3596 if (!suppress_this_message) {
3597 std::string accept_lang = GetContentClient()->browser()->
3598 GetAcceptLangs(GetBrowserContext());
3599 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
3600 dialog_manager_->RunJavaScriptDialog(
3601 this,
3602 frame_url.GetOrigin(),
3603 accept_lang,
3604 javascript_message_type,
3605 message,
3606 default_prompt,
3607 base::Bind(&WebContentsImpl::OnDialogClosed,
3608 base::Unretained(this),
3609 render_frame_host->GetProcess()->GetID(),
3610 render_frame_host->GetRoutingID(),
3611 reply_msg,
3612 false),
3613 &suppress_this_message);
3616 if (suppress_this_message) {
3617 // If we are suppressing messages, just reply as if the user immediately
3618 // pressed "Cancel", passing true to |dialog_was_suppressed|.
3619 OnDialogClosed(render_frame_host->GetProcess()->GetID(),
3620 render_frame_host->GetRoutingID(), reply_msg,
3621 true, false, base::string16());
3624 // OnDialogClosed (two lines up) may have caused deletion of this object (see
3625 // http://crbug.com/288961 ). The only safe thing to do here is return.
3628 void WebContentsImpl::RunBeforeUnloadConfirm(
3629 RenderFrameHost* render_frame_host,
3630 const base::string16& message,
3631 bool is_reload,
3632 IPC::Message* reply_msg) {
3633 RenderFrameHostImpl* rfhi =
3634 static_cast<RenderFrameHostImpl*>(render_frame_host);
3635 if (delegate_)
3636 delegate_->WillRunBeforeUnloadConfirm();
3638 bool suppress_this_message =
3639 rfhi->rfh_state() != RenderFrameHostImpl::STATE_DEFAULT ||
3640 ShowingInterstitialPage() || !delegate_ ||
3641 delegate_->ShouldSuppressDialogs(this) ||
3642 !delegate_->GetJavaScriptDialogManager(this);
3643 if (suppress_this_message) {
3644 rfhi->JavaScriptDialogClosed(reply_msg, true, base::string16(), true);
3645 return;
3648 is_showing_before_unload_dialog_ = true;
3649 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
3650 dialog_manager_->RunBeforeUnloadDialog(
3651 this, message, is_reload,
3652 base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
3653 render_frame_host->GetProcess()->GetID(),
3654 render_frame_host->GetRoutingID(), reply_msg,
3655 false));
3658 WebContents* WebContentsImpl::GetAsWebContents() {
3659 return this;
3662 bool WebContentsImpl::IsNeverVisible() {
3663 if (!delegate_)
3664 return false;
3665 return delegate_->IsNeverVisible(this);
3668 #if defined(OS_WIN)
3669 gfx::NativeViewAccessible WebContentsImpl::GetParentNativeViewAccessible() {
3670 return accessible_parent_;
3672 #endif
3674 RenderViewHostDelegateView* WebContentsImpl::GetDelegateView() {
3675 return render_view_host_delegate_view_;
3678 RendererPreferences WebContentsImpl::GetRendererPrefs(
3679 BrowserContext* browser_context) const {
3680 return renderer_preferences_;
3683 gfx::Rect WebContentsImpl::GetRootWindowResizerRect() const {
3684 if (delegate_)
3685 return delegate_->GetRootWindowResizerRect();
3686 return gfx::Rect();
3689 void WebContentsImpl::RemoveBrowserPluginEmbedder() {
3690 if (browser_plugin_embedder_)
3691 browser_plugin_embedder_.reset();
3694 void WebContentsImpl::RenderViewCreated(RenderViewHost* render_view_host) {
3695 // Don't send notifications if we are just creating a swapped-out RVH for
3696 // the opener chain. These won't be used for view-source or WebUI, so it's
3697 // ok to return early.
3698 if (!static_cast<RenderViewHostImpl*>(render_view_host)->is_active())
3699 return;
3701 if (delegate_)
3702 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
3704 NotificationService::current()->Notify(
3705 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
3706 Source<WebContents>(this),
3707 Details<RenderViewHost>(render_view_host));
3709 // When we're creating views, we're still doing initial setup, so we always
3710 // use the pending Web UI rather than any possibly existing committed one.
3711 if (GetRenderManager()->pending_web_ui())
3712 GetRenderManager()->pending_web_ui()->RenderViewCreated(render_view_host);
3714 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
3715 switches::kEnableBrowserSideNavigation) &&
3716 GetRenderManager()->speculative_web_ui()) {
3717 GetRenderManager()->speculative_web_ui()->RenderViewCreated(
3718 render_view_host);
3721 NavigationEntry* entry = controller_.GetPendingEntry();
3722 if (entry && entry->IsViewSourceMode()) {
3723 // Put the renderer in view source mode.
3724 render_view_host->Send(
3725 new ViewMsg_EnableViewSourceMode(render_view_host->GetRoutingID()));
3728 view_->RenderViewCreated(render_view_host);
3730 FOR_EACH_OBSERVER(
3731 WebContentsObserver, observers_, RenderViewCreated(render_view_host));
3734 void WebContentsImpl::RenderViewReady(RenderViewHost* rvh) {
3735 if (rvh != GetRenderViewHost()) {
3736 // Don't notify the world, since this came from a renderer in the
3737 // background.
3738 return;
3741 notify_disconnection_ = true;
3742 // TODO(avi): Remove. http://crbug.com/170921
3743 NotificationService::current()->Notify(
3744 NOTIFICATION_WEB_CONTENTS_CONNECTED,
3745 Source<WebContents>(this),
3746 NotificationService::NoDetails());
3748 bool was_crashed = IsCrashed();
3749 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
3751 // Restore the focus to the tab (otherwise the focus will be on the top
3752 // window).
3753 if (was_crashed && !FocusLocationBarByDefault() &&
3754 (!delegate_ || delegate_->ShouldFocusPageAfterCrash())) {
3755 view_->Focus();
3758 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewReady());
3761 void WebContentsImpl::RenderViewTerminated(RenderViewHost* rvh,
3762 base::TerminationStatus status,
3763 int error_code) {
3764 if (rvh != GetRenderViewHost()) {
3765 // The pending page's RenderViewHost is gone.
3766 return;
3769 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
3770 // renderer may not have made a clean exit.
3771 if (IsFullscreenForCurrentTab())
3772 ExitFullscreenMode();
3774 // Cancel any visible dialogs so they are not left dangling over the sad tab.
3775 CancelActiveAndPendingDialogs();
3777 if (delegate_)
3778 delegate_->HideValidationMessage(this);
3780 SetIsLoading(false, true, nullptr);
3781 NotifyDisconnected();
3782 SetIsCrashed(status, error_code);
3784 // Reset the loading progress. TODO(avi): What does it mean to have a
3785 // "renderer crash" when there is more than one renderer process serving a
3786 // webpage? Once this function is called at a more granular frame level, we
3787 // probably will need to more granularly reset the state here.
3788 ResetLoadProgressState();
3790 FOR_EACH_OBSERVER(WebContentsObserver,
3791 observers_,
3792 RenderProcessGone(GetCrashedStatus()));
3795 void WebContentsImpl::RenderViewDeleted(RenderViewHost* rvh) {
3796 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewDeleted(rvh));
3799 void WebContentsImpl::UpdateState(RenderViewHost* rvh,
3800 int32 page_id,
3801 const PageState& page_state) {
3802 // Ensure that this state update comes from a RenderViewHost that belongs to
3803 // this WebContents.
3804 // TODO(nasko): This should go through RenderFrameHost.
3805 // TODO(creis): We can't update state for cross-process subframes until we
3806 // have FrameNavigationEntries. Once we do, this should be a DCHECK.
3807 if (rvh->GetDelegate()->GetAsWebContents() != this)
3808 return;
3810 // We must be prepared to handle state updates for any page, these occur
3811 // when the user is scrolling and entering form data, as well as when we're
3812 // leaving a page, in which case our state may have already been moved to
3813 // the next page. The navigation controller will look up the appropriate
3814 // NavigationEntry and update it when it is notified via the delegate.
3815 NavigationEntryImpl* entry = controller_.GetEntryWithPageID(
3816 rvh->GetSiteInstance(), page_id);
3818 if (!entry)
3819 return;
3821 if (page_state == entry->GetPageState())
3822 return; // Nothing to update.
3823 entry->SetPageState(page_state);
3824 controller_.NotifyEntryChanged(entry);
3827 void WebContentsImpl::UpdateTargetURL(RenderViewHost* render_view_host,
3828 const GURL& url) {
3829 if (fullscreen_widget_routing_id_ != MSG_ROUTING_NONE) {
3830 // If we're fullscreen only update the url if it's from the fullscreen
3831 // renderer.
3832 RenderWidgetHostView* fs = GetFullscreenRenderWidgetHostView();
3833 if (fs && fs->GetRenderWidgetHost() != render_view_host)
3834 return;
3836 if (delegate_)
3837 delegate_->UpdateTargetURL(this, url);
3840 void WebContentsImpl::Close(RenderViewHost* rvh) {
3841 #if defined(OS_MACOSX)
3842 // The UI may be in an event-tracking loop, such as between the
3843 // mouse-down and mouse-up in text selection or a button click.
3844 // Defer the close until after tracking is complete, so that we
3845 // don't free objects out from under the UI.
3846 // TODO(shess): This could get more fine-grained. For instance,
3847 // closing a tab in another window while selecting text in the
3848 // current window's Omnibox should be just fine.
3849 if (view_->IsEventTracking()) {
3850 view_->CloseTabAfterEventTracking();
3851 return;
3853 #endif
3855 // Ignore this if it comes from a RenderViewHost that we aren't showing.
3856 if (delegate_ && rvh == GetRenderViewHost())
3857 delegate_->CloseContents(this);
3860 void WebContentsImpl::SwappedOut(RenderFrameHost* rfh) {
3861 if (delegate_ && rfh->GetRenderViewHost() == GetRenderViewHost())
3862 delegate_->SwappedOut(this);
3865 void WebContentsImpl::RequestMove(const gfx::Rect& new_bounds) {
3866 if (delegate_ && delegate_->IsPopupOrPanel(this))
3867 delegate_->MoveContents(this, new_bounds);
3870 void WebContentsImpl::DidStartLoading(FrameTreeNode* frame_tree_node,
3871 bool to_different_document) {
3872 SetIsLoading(true, to_different_document, nullptr);
3874 // Notify accessibility that the user is navigating away from the
3875 // current document.
3877 // TODO(dmazzoni): do this using a WebContentsObserver.
3878 BrowserAccessibilityManager* manager =
3879 frame_tree_node->current_frame_host()->browser_accessibility_manager();
3880 if (manager)
3881 manager->UserIsNavigatingAway();
3884 void WebContentsImpl::DidStopLoading() {
3885 scoped_ptr<LoadNotificationDetails> details;
3887 // Use the last committed entry rather than the active one, in case a
3888 // pending entry has been created.
3889 NavigationEntry* entry = controller_.GetLastCommittedEntry();
3890 Navigator* navigator = frame_tree_.root()->navigator();
3892 // An entry may not exist for a stop when loading an initial blank page or
3893 // if an iframe injected by script into a blank page finishes loading.
3894 if (entry) {
3895 base::TimeDelta elapsed =
3896 base::TimeTicks::Now() - navigator->GetCurrentLoadStart();
3898 details.reset(new LoadNotificationDetails(
3899 entry->GetVirtualURL(),
3900 entry->GetTransitionType(),
3901 elapsed,
3902 &controller_,
3903 controller_.GetCurrentEntryIndex()));
3906 SetIsLoading(false, true, details.get());
3909 void WebContentsImpl::DidChangeLoadProgress() {
3910 double load_progress = frame_tree_.load_progress();
3912 // The delegate is notified immediately for the first and last updates. Also,
3913 // since the message loop may be pretty busy when a page is loaded, it might
3914 // not execute a posted task in a timely manner so the progress report is sent
3915 // immediately if enough time has passed.
3916 base::TimeDelta min_delay =
3917 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS);
3918 bool delay_elapsed = loading_last_progress_update_.is_null() ||
3919 base::TimeTicks::Now() - loading_last_progress_update_ > min_delay;
3921 if (load_progress == 0.0 || load_progress == 1.0 || delay_elapsed) {
3922 // If there is a pending task to send progress, it is now obsolete.
3923 loading_weak_factory_.InvalidateWeakPtrs();
3925 // Notify the load progress change.
3926 SendChangeLoadProgress();
3928 // Clean-up the states if needed.
3929 if (load_progress == 1.0)
3930 ResetLoadProgressState();
3931 return;
3934 if (loading_weak_factory_.HasWeakPtrs())
3935 return;
3937 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
3938 FROM_HERE, base::Bind(&WebContentsImpl::SendChangeLoadProgress,
3939 loading_weak_factory_.GetWeakPtr()),
3940 min_delay);
3943 void WebContentsImpl::DidCancelLoading() {
3944 controller_.DiscardNonCommittedEntries();
3946 // Update the URL display.
3947 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
3950 void WebContentsImpl::DidAccessInitialDocument() {
3951 has_accessed_initial_document_ = true;
3953 // We may have left a failed browser-initiated navigation in the address bar
3954 // to let the user edit it and try again. Clear it now that content might
3955 // show up underneath it.
3956 if (!IsLoading() && controller_.GetPendingEntry())
3957 controller_.DiscardPendingEntry(false);
3959 // Update the URL display.
3960 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
3963 void WebContentsImpl::DidChangeName(RenderFrameHost* render_frame_host,
3964 const std::string& name) {
3965 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3966 FrameNameChanged(render_frame_host, name));
3969 void WebContentsImpl::DocumentOnLoadCompleted(
3970 RenderFrameHost* render_frame_host) {
3971 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3972 DocumentOnLoadCompletedInMainFrame());
3974 // TODO(avi): Remove. http://crbug.com/170921
3975 NotificationService::current()->Notify(
3976 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
3977 Source<WebContents>(this),
3978 NotificationService::NoDetails());
3981 void WebContentsImpl::UpdateTitle(RenderFrameHost* render_frame_host,
3982 int32 page_id,
3983 const base::string16& title,
3984 base::i18n::TextDirection title_direction) {
3985 RenderViewHost* rvh = render_frame_host->GetRenderViewHost();
3987 // If we have a title, that's a pretty good indication that we've started
3988 // getting useful data.
3989 SetNotWaitingForResponse();
3991 // Try to find the navigation entry, which might not be the current one.
3992 // For example, it might be from a pending RVH for the pending entry.
3993 NavigationEntryImpl* entry = controller_.GetEntryWithPageID(
3994 rvh->GetSiteInstance(), page_id);
3996 // We can handle title updates when we don't have an entry in
3997 // UpdateTitleForEntry, but only if the update is from the current RVH.
3998 // TODO(avi): Change to make decisions based on the RenderFrameHost.
3999 if (!entry && rvh != GetRenderViewHost())
4000 return;
4002 // TODO(evan): make use of title_direction.
4003 // http://code.google.com/p/chromium/issues/detail?id=27094
4004 if (!UpdateTitleForEntry(entry, title))
4005 return;
4007 // Broadcast notifications when the UI should be updated.
4008 if (entry == controller_.GetEntryAtOffset(0))
4009 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
4012 void WebContentsImpl::UpdateEncoding(RenderFrameHost* render_frame_host,
4013 const std::string& encoding) {
4014 SetEncoding(encoding);
4017 void WebContentsImpl::DocumentAvailableInMainFrame(
4018 RenderViewHost* render_view_host) {
4019 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4020 DocumentAvailableInMainFrame());
4023 void WebContentsImpl::RouteCloseEvent(RenderViewHost* rvh) {
4024 // Tell the active RenderViewHost to run unload handlers and close, as long
4025 // as the request came from a RenderViewHost in the same BrowsingInstance.
4026 // In most cases, we receive this from a swapped out RenderViewHost.
4027 // It is possible to receive it from one that has just been swapped in,
4028 // in which case we might as well deliver the message anyway.
4029 if (rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()))
4030 ClosePage();
4033 bool WebContentsImpl::ShouldRouteMessageEvent(
4034 RenderFrameHost* target_rfh,
4035 SiteInstance* source_site_instance) const {
4036 // Allow the message if this WebContents is dedicated to a browser plugin
4037 // guest.
4038 // Note: This check means that an embedder could theoretically receive a
4039 // postMessage from anyone (not just its own guests). However, this is
4040 // probably not a risk for apps since other pages won't have references
4041 // to App windows.
4042 return GetBrowserPluginGuest() || GetBrowserPluginEmbedder();
4045 void WebContentsImpl::EnsureOpenerProxiesExist(RenderFrameHost* source_rfh) {
4046 WebContentsImpl* source_web_contents = static_cast<WebContentsImpl*>(
4047 WebContents::FromRenderFrameHost(source_rfh));
4049 if (source_web_contents) {
4050 // If this message is going to outer WebContents from inner WebContents,
4051 // then we should not create a RenderView. AttachToOuterWebContentsFrame()
4052 // already created a RenderFrameProxyHost for that purpose.
4053 if (GetBrowserPluginEmbedder() &&
4054 base::CommandLine::ForCurrentProcess()->HasSwitch(
4055 switches::kSitePerProcess)) {
4056 return;
4059 if (GetBrowserPluginGuest()) {
4060 // We create a swapped out RenderView for the embedder in the guest's
4061 // render process but we intentionally do not expose the embedder's
4062 // opener chain to it.
4063 source_web_contents->CreateSwappedOutRenderView(GetSiteInstance());
4064 } else {
4065 RenderFrameHostImpl* source_rfhi =
4066 static_cast<RenderFrameHostImpl*>(source_rfh);
4067 source_rfhi->frame_tree_node()->render_manager()->CreateOpenerProxies(
4068 GetSiteInstance());
4073 bool WebContentsImpl::AddMessageToConsole(int32 level,
4074 const base::string16& message,
4075 int32 line_no,
4076 const base::string16& source_id) {
4077 if (!delegate_)
4078 return false;
4079 return delegate_->AddMessageToConsole(this, level, message, line_no,
4080 source_id);
4083 int WebContentsImpl::CreateSwappedOutRenderView(
4084 SiteInstance* instance) {
4085 int render_view_routing_id = MSG_ROUTING_NONE;
4086 if (RenderFrameHostManager::IsSwappedOutStateForbidden()) {
4087 GetRenderManager()->CreateRenderFrameProxy(instance);
4088 } else {
4089 GetRenderManager()->CreateRenderFrame(
4090 instance, nullptr,
4091 CREATE_RF_SWAPPED_OUT | CREATE_RF_FOR_MAIN_FRAME_NAVIGATION |
4092 CREATE_RF_HIDDEN,
4093 &render_view_routing_id);
4095 return render_view_routing_id;
4098 void WebContentsImpl::OnUserGesture() {
4099 // Notify observers.
4100 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetUserGesture());
4102 ResourceDispatcherHostImpl* rdh = ResourceDispatcherHostImpl::Get();
4103 if (rdh) // NULL in unittests.
4104 rdh->OnUserGesture(this);
4107 void WebContentsImpl::OnIgnoredUIEvent() {
4108 // Notify observers.
4109 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetIgnoredUIEvent());
4112 void WebContentsImpl::RendererUnresponsive(RenderViewHost* render_view_host) {
4113 // Don't show hung renderer dialog for a swapped out RVH.
4114 if (render_view_host != GetRenderViewHost())
4115 return;
4117 RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(render_view_host);
4118 RenderFrameHostImpl* rfhi =
4119 static_cast<RenderFrameHostImpl*>(rvhi->GetMainFrame());
4121 // Ignore renderer unresponsive event if debugger is attached to the tab
4122 // since the event may be a result of the renderer sitting on a breakpoint.
4123 // See http://crbug.com/65458
4124 if (DevToolsAgentHost::IsDebuggerAttached(this))
4125 return;
4127 if (rfhi->is_waiting_for_beforeunload_ack() ||
4128 rfhi->IsWaitingForUnloadACK()) {
4129 // Hang occurred while firing the beforeunload/unload handler.
4130 // Pretend the handler fired so tab closing continues as if it had.
4131 rvhi->set_sudden_termination_allowed(true);
4133 if (!GetRenderManager()->ShouldCloseTabOnUnresponsiveRenderer())
4134 return;
4136 // If the tab hangs in the beforeunload/unload handler there's really
4137 // nothing we can do to recover. If the hang is in the beforeunload handler,
4138 // pretend the beforeunload listeners have all fired and allow the delegate
4139 // to continue closing; the user will not have the option of cancelling the
4140 // close. Otherwise, pretend the unload listeners have all fired and close
4141 // the tab.
4142 bool close = true;
4143 if (rfhi->is_waiting_for_beforeunload_ack() && delegate_) {
4144 delegate_->BeforeUnloadFired(this, true, &close);
4146 if (close)
4147 Close(rvhi);
4148 return;
4151 if (!GetRenderViewHost() || !GetRenderViewHost()->IsRenderViewLive())
4152 return;
4154 if (delegate_)
4155 delegate_->RendererUnresponsive(this);
4158 void WebContentsImpl::RendererResponsive(RenderViewHost* render_view_host) {
4159 if (delegate_)
4160 delegate_->RendererResponsive(this);
4163 void WebContentsImpl::LoadStateChanged(
4164 const GURL& url,
4165 const net::LoadStateWithParam& load_state,
4166 uint64 upload_position,
4167 uint64 upload_size) {
4168 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
4169 // is fixed.
4170 tracked_objects::ScopedTracker tracking_profile1(
4171 FROM_HERE_WITH_EXPLICIT_FUNCTION(
4172 "466285 WebContentsImpl::LoadStateChanged::Start"));
4173 load_state_ = load_state;
4174 upload_position_ = upload_position;
4175 upload_size_ = upload_size;
4176 load_state_host_ = net::IDNToUnicode(url.host(),
4177 GetContentClient()->browser()->GetAcceptLangs(
4178 GetBrowserContext()));
4179 if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
4180 SetNotWaitingForResponse();
4181 if (IsLoading()) {
4182 NotifyNavigationStateChanged(static_cast<InvalidateTypes>(
4183 INVALIDATE_TYPE_LOAD | INVALIDATE_TYPE_TAB));
4187 void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
4188 bool proceed, const base::TimeTicks& proceed_time,
4189 bool* proceed_to_fire_unload) {
4190 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4191 BeforeUnloadFired(proceed_time));
4192 if (delegate_)
4193 delegate_->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
4194 // Note: |this| might be deleted at this point.
4197 void WebContentsImpl::RenderProcessGoneFromRenderManager(
4198 RenderViewHost* render_view_host) {
4199 DCHECK(crashed_status_ != base::TERMINATION_STATUS_STILL_RUNNING);
4200 RenderViewTerminated(render_view_host, crashed_status_, crashed_error_code_);
4203 void WebContentsImpl::UpdateRenderViewSizeForRenderManager() {
4204 // TODO(brettw) this is a hack. See WebContentsView::SizeContents.
4205 gfx::Size size = GetSizeForNewRenderView();
4206 // 0x0 isn't a valid window size (minimal window size is 1x1) but it may be
4207 // here during container initialization and normal window size will be set
4208 // later. In case of tab duplication this resizing to 0x0 prevents setting
4209 // normal size later so just ignore it.
4210 if (!size.IsEmpty())
4211 view_->SizeContents(size);
4214 void WebContentsImpl::CancelModalDialogsForRenderManager() {
4215 // We need to cancel modal dialogs when doing a process swap, since the load
4216 // deferrer would prevent us from swapping out. We also clear the state
4217 // because this is a cross-process navigation, which means that it's a new
4218 // site that should not have to pay for the sins of its predecessor.
4220 // Note that we don't bother telling browser_plugin_embedder_ because the
4221 // cross-process navigation will either destroy the browser plugins or not
4222 // require their dialogs to close.
4223 if (dialog_manager_)
4224 dialog_manager_->ResetDialogState(this);
4227 void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost* old_host,
4228 RenderFrameHost* new_host,
4229 bool is_main_frame) {
4230 if (is_main_frame) {
4231 NotifyViewSwapped(old_host ? old_host->GetRenderViewHost() : nullptr,
4232 new_host->GetRenderViewHost());
4234 // Make sure the visible RVH reflects the new delegate's preferences.
4235 if (delegate_)
4236 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
4238 view_->RenderViewSwappedIn(new_host->GetRenderViewHost());
4241 NotifyFrameSwapped(old_host, new_host);
4244 void WebContentsImpl::NotifyMainFrameSwappedFromRenderManager(
4245 RenderViewHost* old_host,
4246 RenderViewHost* new_host) {
4247 NotifyViewSwapped(old_host, new_host);
4250 NavigationControllerImpl& WebContentsImpl::GetControllerForRenderManager() {
4251 return GetController();
4254 scoped_ptr<WebUIImpl> WebContentsImpl::CreateWebUIForRenderManager(
4255 const GURL& url) {
4256 return scoped_ptr<WebUIImpl>(static_cast<WebUIImpl*>(CreateWebUI(url)));
4259 NavigationEntry*
4260 WebContentsImpl::GetLastCommittedNavigationEntryForRenderManager() {
4261 return controller_.GetLastCommittedEntry();
4264 bool WebContentsImpl::CreateRenderViewForRenderManager(
4265 RenderViewHost* render_view_host,
4266 int opener_frame_routing_id,
4267 int proxy_routing_id,
4268 const FrameReplicationState& replicated_frame_state,
4269 bool for_main_frame_navigation) {
4270 TRACE_EVENT0("browser,navigation",
4271 "WebContentsImpl::CreateRenderViewForRenderManager");
4272 // Can be NULL during tests.
4273 RenderWidgetHostViewBase* rwh_view;
4274 // TODO(kenrb): RenderWidgetHostViewChildFrame special casing is temporary
4275 // until RenderWidgetHost is attached to RenderFrameHost. We need to special
4276 // case this because RWH is still a base class of RenderViewHost, and child
4277 // frame RWHVs are unique in that they do not have their own WebContents.
4278 bool is_guest_in_site_per_process =
4279 !!browser_plugin_guest_.get() &&
4280 base::CommandLine::ForCurrentProcess()->HasSwitch(
4281 switches::kSitePerProcess);
4282 if (!for_main_frame_navigation || is_guest_in_site_per_process) {
4283 RenderWidgetHostViewChildFrame* rwh_view_child =
4284 new RenderWidgetHostViewChildFrame(render_view_host);
4285 rwh_view = rwh_view_child;
4286 } else {
4287 rwh_view = view_->CreateViewForWidget(render_view_host, false);
4290 // Now that the RenderView has been created, we need to tell it its size.
4291 if (rwh_view)
4292 rwh_view->SetSize(GetSizeForNewRenderView());
4294 // Make sure we use the correct starting page_id in the new RenderView.
4295 UpdateMaxPageIDIfNecessary(render_view_host);
4296 int32 max_page_id =
4297 GetMaxPageIDForSiteInstance(render_view_host->GetSiteInstance());
4299 if (!static_cast<RenderViewHostImpl*>(render_view_host)
4300 ->CreateRenderView(opener_frame_routing_id, proxy_routing_id,
4301 max_page_id, replicated_frame_state,
4302 created_with_opener_)) {
4303 return false;
4306 SetHistoryOffsetAndLengthForView(render_view_host,
4307 controller_.GetLastCommittedEntryIndex(),
4308 controller_.GetEntryCount());
4310 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
4311 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
4312 // linux. See crbug.com/83941.
4313 if (rwh_view) {
4314 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
4315 render_widget_host->WasResized();
4317 #endif
4319 return true;
4322 bool WebContentsImpl::CreateRenderFrameForRenderManager(
4323 RenderFrameHost* render_frame_host,
4324 int parent_routing_id,
4325 int previous_sibling_routing_id,
4326 int proxy_routing_id) {
4327 TRACE_EVENT0("browser,navigation",
4328 "WebContentsImpl::CreateRenderFrameForRenderManager");
4330 RenderFrameHostImpl* rfh =
4331 static_cast<RenderFrameHostImpl*>(render_frame_host);
4332 if (!rfh->CreateRenderFrame(parent_routing_id, previous_sibling_routing_id,
4333 proxy_routing_id))
4334 return false;
4336 // TODO(nasko): When RenderWidgetHost is owned by RenderFrameHost, the passed
4337 // RenderFrameHost will have to be associated with the appropriate
4338 // RenderWidgetHostView or a new one should be created here.
4340 return true;
4343 #if defined(OS_ANDROID)
4345 base::android::ScopedJavaLocalRef<jobject>
4346 WebContentsImpl::GetJavaWebContents() {
4347 DCHECK_CURRENTLY_ON(BrowserThread::UI);
4348 return GetWebContentsAndroid()->GetJavaObject();
4351 WebContentsAndroid* WebContentsImpl::GetWebContentsAndroid() {
4352 WebContentsAndroid* web_contents_android =
4353 static_cast<WebContentsAndroid*>(GetUserData(kWebContentsAndroidKey));
4354 if (!web_contents_android) {
4355 web_contents_android = new WebContentsAndroid(this);
4356 SetUserData(kWebContentsAndroidKey, web_contents_android);
4358 return web_contents_android;
4361 bool WebContentsImpl::CreateRenderViewForInitialEmptyDocument() {
4362 return CreateRenderViewForRenderManager(
4363 GetRenderViewHost(), MSG_ROUTING_NONE, MSG_ROUTING_NONE,
4364 frame_tree_.root()->current_replication_state(), true);
4367 #elif defined(OS_MACOSX)
4369 void WebContentsImpl::SetAllowOtherViews(bool allow) {
4370 view_->SetAllowOtherViews(allow);
4373 bool WebContentsImpl::GetAllowOtherViews() {
4374 return view_->GetAllowOtherViews();
4377 #endif
4379 void WebContentsImpl::OnDialogClosed(int render_process_id,
4380 int render_frame_id,
4381 IPC::Message* reply_msg,
4382 bool dialog_was_suppressed,
4383 bool success,
4384 const base::string16& user_input) {
4385 RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(render_process_id,
4386 render_frame_id);
4387 last_dialog_suppressed_ = dialog_was_suppressed;
4389 if (is_showing_before_unload_dialog_ && !success) {
4390 // If a beforeunload dialog is canceled, we need to stop the throbber from
4391 // spinning, since we forced it to start spinning in Navigate.
4392 if (rfh)
4393 DidStopLoading();
4394 controller_.DiscardNonCommittedEntries();
4396 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4397 BeforeUnloadDialogCancelled());
4400 is_showing_before_unload_dialog_ = false;
4401 if (rfh) {
4402 rfh->JavaScriptDialogClosed(reply_msg, success, user_input,
4403 dialog_was_suppressed);
4404 } else {
4405 // Don't leak the sync IPC reply if the RFH or process is gone.
4406 delete reply_msg;
4410 void WebContentsImpl::SetEncoding(const std::string& encoding) {
4411 if (encoding == last_reported_encoding_)
4412 return;
4413 last_reported_encoding_ = encoding;
4415 canonical_encoding_ = GetContentClient()->browser()->
4416 GetCanonicalEncodingNameByAliasName(encoding);
4419 bool WebContentsImpl::IsHidden() {
4420 return capturer_count_ == 0 && !should_normally_be_visible_;
4423 int WebContentsImpl::GetOuterDelegateFrameTreeNodeID() {
4424 if (node_ && node_->outer_web_contents())
4425 return node_->outer_contents_frame_tree_node_id();
4427 return FrameTreeNode::kFrameTreeNodeInvalidID;
4430 RenderFrameHostManager* WebContentsImpl::GetRenderManager() const {
4431 return frame_tree_.root()->render_manager();
4434 BrowserPluginGuest* WebContentsImpl::GetBrowserPluginGuest() const {
4435 return browser_plugin_guest_.get();
4438 void WebContentsImpl::SetBrowserPluginGuest(BrowserPluginGuest* guest) {
4439 CHECK(!browser_plugin_guest_);
4440 CHECK(guest);
4441 browser_plugin_guest_.reset(guest);
4444 BrowserPluginEmbedder* WebContentsImpl::GetBrowserPluginEmbedder() const {
4445 return browser_plugin_embedder_.get();
4448 void WebContentsImpl::CreateBrowserPluginEmbedderIfNecessary() {
4449 if (browser_plugin_embedder_)
4450 return;
4451 browser_plugin_embedder_.reset(BrowserPluginEmbedder::Create(this));
4454 void WebContentsImpl::ClearPowerSaveBlockers(
4455 RenderFrameHost* render_frame_host) {
4456 RemoveAllMediaPlayerEntries(render_frame_host, &active_audio_players_);
4457 RemoveAllMediaPlayerEntries(render_frame_host, &active_video_players_);
4458 MaybeReleasePowerSaveBlockers();
4461 void WebContentsImpl::ClearAllPowerSaveBlockers() {
4462 active_audio_players_.clear();
4463 active_video_players_.clear();
4464 audio_power_save_blocker_.reset();
4465 video_power_save_blocker_.reset();
4468 gfx::Size WebContentsImpl::GetSizeForNewRenderView() {
4469 gfx::Size size;
4470 if (delegate_)
4471 size = delegate_->GetSizeForNewRenderView(this);
4472 if (size.IsEmpty())
4473 size = GetContainerBounds().size();
4474 return size;
4477 void WebContentsImpl::OnFrameRemoved(RenderFrameHost* render_frame_host) {
4478 FOR_EACH_OBSERVER(
4479 WebContentsObserver, observers_, FrameDeleted(render_frame_host));
4482 void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size& old_size) {
4483 if (!delegate_)
4484 return;
4485 const gfx::Size new_size = GetPreferredSize();
4486 if (new_size != old_size)
4487 delegate_->UpdatePreferredSize(this, new_size);
4490 void WebContentsImpl::AddMediaPlayerEntry(int64 player_cookie,
4491 ActiveMediaPlayerMap* player_map) {
4492 if (!HasValidFrameSource())
4493 return;
4495 const uintptr_t key =
4496 reinterpret_cast<uintptr_t>(render_frame_message_source_);
4497 DCHECK(std::find((*player_map)[key].begin(),
4498 (*player_map)[key].end(),
4499 player_cookie) == (*player_map)[key].end());
4500 (*player_map)[key].push_back(player_cookie);
4503 void WebContentsImpl::RemoveMediaPlayerEntry(int64 player_cookie,
4504 ActiveMediaPlayerMap* player_map) {
4505 if (!HasValidFrameSource())
4506 return;
4508 const uintptr_t key =
4509 reinterpret_cast<uintptr_t>(render_frame_message_source_);
4510 ActiveMediaPlayerMap::iterator it = player_map->find(key);
4511 if (it == player_map->end())
4512 return;
4514 // Remove the player.
4515 PlayerList::iterator player_it =
4516 std::find(it->second.begin(), it->second.end(), player_cookie);
4517 if (player_it != it->second.end())
4518 it->second.erase(player_it);
4520 // If there are no players left, remove the map entry.
4521 if (it->second.empty())
4522 player_map->erase(it);
4525 void WebContentsImpl::RemoveAllMediaPlayerEntries(
4526 RenderFrameHost* render_frame_host,
4527 ActiveMediaPlayerMap* player_map) {
4528 ActiveMediaPlayerMap::iterator it =
4529 player_map->find(reinterpret_cast<uintptr_t>(render_frame_host));
4530 if (it == player_map->end())
4531 return;
4532 player_map->erase(it);
4535 void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable) {
4536 force_disable_overscroll_content_ = force_disable;
4537 if (view_)
4538 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
4541 } // namespace content