Fix various typos, error handling for GN auto-roller.
[chromium-blink-merge.git] / content / browser / web_contents / web_contents_impl.cc
blob41e49ddfb92c1b619b4515dd3ece4c9b316b57fc
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/browser_plugin_guest_mode.h"
92 #include "content/public/common/content_constants.h"
93 #include "content/public/common/content_switches.h"
94 #include "content/public/common/page_zoom.h"
95 #include "content/public/common/result_codes.h"
96 #include "content/public/common/security_style.h"
97 #include "content/public/common/url_constants.h"
98 #include "content/public/common/url_utils.h"
99 #include "content/public/common/web_preferences.h"
100 #include "mojo/common/url_type_converters.h"
101 #include "mojo/converters/geometry/geometry_type_converters.h"
102 #include "net/base/net_util.h"
103 #include "net/http/http_cache.h"
104 #include "net/http/http_transaction_factory.h"
105 #include "net/url_request/url_request_context.h"
106 #include "net/url_request/url_request_context_getter.h"
107 #include "skia/public/type_converters.h"
108 #include "third_party/skia/include/core/SkBitmap.h"
109 #include "ui/base/layout.h"
110 #include "ui/gfx/display.h"
111 #include "ui/gfx/screen.h"
112 #include "ui/gl/gl_switches.h"
114 #if defined(ENABLE_BROWSER_CDMS)
115 #include "content/browser/media/media_web_contents_observer.h"
116 #endif
118 #if defined(OS_ANDROID)
119 #include "content/browser/android/content_video_view.h"
120 #include "content/browser/android/date_time_chooser_android.h"
121 #include "content/browser/android/media_players_observer.h"
122 #include "content/browser/media/android/media_session.h"
123 #include "content/browser/web_contents/web_contents_android.h"
124 #endif
126 #if defined(OS_MACOSX)
127 #include "base/mac/foundation_util.h"
128 #endif
130 namespace content {
131 namespace {
133 const int kMinimumDelayBetweenLoadingUpdatesMS = 100;
134 const char kDotGoogleDotCom[] = ".google.com";
136 #if defined(OS_ANDROID)
137 const char kWebContentsAndroidKey[] = "web_contents_android";
138 #endif // OS_ANDROID
140 base::LazyInstance<std::vector<WebContentsImpl::CreatedCallback> >
141 g_created_callbacks = LAZY_INSTANCE_INITIALIZER;
143 static void DidDownloadImage(const WebContents::ImageDownloadCallback& callback,
144 int id,
145 const GURL& image_url,
146 image_downloader::DownloadResultPtr result) {
147 DCHECK(result);
149 const std::vector<SkBitmap> images =
150 result->images.To<std::vector<SkBitmap>>();
151 const std::vector<gfx::Size> original_image_sizes =
152 result->original_image_sizes.To<std::vector<gfx::Size>>();
154 callback.Run(id, result->http_status_code, image_url, images,
155 original_image_sizes);
158 void NotifyCacheOnIO(
159 scoped_refptr<net::URLRequestContextGetter> request_context,
160 const GURL& url,
161 const std::string& http_method) {
162 net::HttpCache* cache = request_context->GetURLRequestContext()->
163 http_transaction_factory()->GetCache();
164 if (cache)
165 cache->OnExternalCacheHit(url, http_method);
168 // Helper function for retrieving all the sites in a frame tree.
169 bool CollectSites(BrowserContext* context,
170 std::set<GURL>* sites,
171 FrameTreeNode* node) {
172 sites->insert(SiteInstance::GetSiteForURL(context, node->current_url()));
173 return true;
176 bool FindMatchingProcess(int render_process_id,
177 bool* did_match_process,
178 FrameTreeNode* node) {
179 if (node->current_frame_host()->GetProcess()->GetID() == render_process_id) {
180 *did_match_process = true;
181 return false;
183 return true;
186 bool ForEachFrameInternal(
187 const base::Callback<void(RenderFrameHost*)>& on_frame,
188 FrameTreeNode* node) {
189 on_frame.Run(node->current_frame_host());
190 return true;
193 bool ForEachPendingFrameInternal(
194 const base::Callback<void(RenderFrameHost*)>& on_frame,
195 FrameTreeNode* node) {
196 RenderFrameHost* pending_frame_host =
197 node->render_manager()->pending_frame_host();
198 if (pending_frame_host)
199 on_frame.Run(pending_frame_host);
200 return true;
203 void SendToAllFramesInternal(IPC::Message* message, RenderFrameHost* rfh) {
204 IPC::Message* message_copy = new IPC::Message(*message);
205 message_copy->set_routing_id(rfh->GetRoutingID());
206 rfh->Send(message_copy);
209 void AddRenderWidgetHostViewToSet(std::set<RenderWidgetHostView*>* set,
210 RenderFrameHost* rfh) {
211 RenderWidgetHostView* rwhv = static_cast<RenderFrameHostImpl*>(rfh)
212 ->frame_tree_node()
213 ->render_manager()
214 ->GetRenderWidgetHostView();
215 set->insert(rwhv);
218 void SetAccessibilityModeOnFrame(AccessibilityMode mode,
219 RenderFrameHost* frame_host) {
220 static_cast<RenderFrameHostImpl*>(frame_host)->SetAccessibilityMode(mode);
223 void ResetAccessibility(RenderFrameHost* rfh) {
224 static_cast<RenderFrameHostImpl*>(rfh)->AccessibilityReset();
227 } // namespace
229 WebContents* WebContents::Create(const WebContents::CreateParams& params) {
230 FrameTreeNode* opener_node = nullptr;
231 if (params.opener_render_frame_id != MSG_ROUTING_NONE) {
232 RenderFrameHostImpl* opener_rfh = RenderFrameHostImpl::FromID(
233 params.opener_render_process_id, params.opener_render_frame_id);
234 if (opener_rfh)
235 opener_node = opener_rfh->frame_tree_node();
237 return WebContentsImpl::CreateWithOpener(params, opener_node);
240 WebContents* WebContents::CreateWithSessionStorage(
241 const WebContents::CreateParams& params,
242 const SessionStorageNamespaceMap& session_storage_namespace_map) {
243 WebContentsImpl* new_contents = new WebContentsImpl(params.browser_context);
245 for (SessionStorageNamespaceMap::const_iterator it =
246 session_storage_namespace_map.begin();
247 it != session_storage_namespace_map.end();
248 ++it) {
249 new_contents->GetController()
250 .SetSessionStorageNamespace(it->first, it->second.get());
253 new_contents->Init(params);
254 return new_contents;
257 void WebContentsImpl::FriendZone::AddCreatedCallbackForTesting(
258 const CreatedCallback& callback) {
259 g_created_callbacks.Get().push_back(callback);
262 void WebContentsImpl::FriendZone::RemoveCreatedCallbackForTesting(
263 const CreatedCallback& callback) {
264 for (size_t i = 0; i < g_created_callbacks.Get().size(); ++i) {
265 if (g_created_callbacks.Get().at(i).Equals(callback)) {
266 g_created_callbacks.Get().erase(g_created_callbacks.Get().begin() + i);
267 return;
272 WebContents* WebContents::FromRenderViewHost(const RenderViewHost* rvh) {
273 return rvh->GetDelegate()->GetAsWebContents();
276 WebContents* WebContents::FromRenderFrameHost(RenderFrameHost* rfh) {
277 RenderFrameHostImpl* rfh_impl = static_cast<RenderFrameHostImpl*>(rfh);
278 if (!rfh_impl)
279 return NULL;
280 return rfh_impl->delegate()->GetAsWebContents();
283 // WebContentsImpl::DestructionObserver ----------------------------------------
285 class WebContentsImpl::DestructionObserver : public WebContentsObserver {
286 public:
287 DestructionObserver(WebContentsImpl* owner, WebContents* watched_contents)
288 : WebContentsObserver(watched_contents),
289 owner_(owner) {
292 // WebContentsObserver:
293 void WebContentsDestroyed() override {
294 owner_->OnWebContentsDestroyed(
295 static_cast<WebContentsImpl*>(web_contents()));
298 private:
299 WebContentsImpl* owner_;
301 DISALLOW_COPY_AND_ASSIGN(DestructionObserver);
304 WebContentsImpl::ColorChooserInfo::ColorChooserInfo(int render_process_id,
305 int render_frame_id,
306 ColorChooser* chooser,
307 int identifier)
308 : render_process_id(render_process_id),
309 render_frame_id(render_frame_id),
310 chooser(chooser),
311 identifier(identifier) {
314 WebContentsImpl::ColorChooserInfo::~ColorChooserInfo() {
317 // WebContentsImpl::WebContentsTreeNode ----------------------------------------
318 WebContentsImpl::WebContentsTreeNode::WebContentsTreeNode()
319 : outer_web_contents_(nullptr),
320 outer_contents_frame_tree_node_id_(
321 FrameTreeNode::kFrameTreeNodeInvalidID) {
324 WebContentsImpl::WebContentsTreeNode::~WebContentsTreeNode() {
325 // Remove child pointer from our parent.
326 if (outer_web_contents_) {
327 ChildrenSet& child_ptrs_in_parent =
328 outer_web_contents_->node_->inner_web_contents_tree_nodes_;
329 ChildrenSet::iterator iter = child_ptrs_in_parent.find(this);
330 DCHECK(iter != child_ptrs_in_parent.end());
331 child_ptrs_in_parent.erase(this);
334 // Remove parent pointers from our children.
335 // TODO(lazyboy): We should destroy the children WebContentses too. If the
336 // children do not manage their own lifetime, then we would leak their
337 // WebContentses.
338 for (WebContentsTreeNode* child : inner_web_contents_tree_nodes_)
339 child->outer_web_contents_ = nullptr;
342 void WebContentsImpl::WebContentsTreeNode::ConnectToOuterWebContents(
343 WebContentsImpl* outer_web_contents,
344 RenderFrameHostImpl* outer_contents_frame) {
345 outer_web_contents_ = outer_web_contents;
346 outer_contents_frame_tree_node_id_ =
347 outer_contents_frame->frame_tree_node()->frame_tree_node_id();
349 if (!outer_web_contents_->node_)
350 outer_web_contents_->node_.reset(new WebContentsTreeNode());
352 outer_web_contents_->node_->inner_web_contents_tree_nodes_.insert(this);
355 // WebContentsImpl -------------------------------------------------------------
357 WebContentsImpl::WebContentsImpl(BrowserContext* browser_context)
358 : delegate_(NULL),
359 controller_(this, browser_context),
360 render_view_host_delegate_view_(NULL),
361 created_with_opener_(false),
362 #if defined(OS_WIN)
363 accessible_parent_(NULL),
364 #endif
365 frame_tree_(new NavigatorImpl(&controller_, this),
366 this,
367 this,
368 this,
369 this),
370 is_loading_(false),
371 is_load_to_different_document_(false),
372 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING),
373 crashed_error_code_(0),
374 waiting_for_response_(false),
375 load_state_(net::LOAD_STATE_IDLE, base::string16()),
376 upload_size_(0),
377 upload_position_(0),
378 is_resume_pending_(false),
379 displayed_insecure_content_(false),
380 has_accessed_initial_document_(false),
381 theme_color_(SK_ColorTRANSPARENT),
382 last_sent_theme_color_(SK_ColorTRANSPARENT),
383 did_first_visually_non_empty_paint_(false),
384 capturer_count_(0),
385 should_normally_be_visible_(true),
386 is_being_destroyed_(false),
387 notify_disconnection_(false),
388 dialog_manager_(NULL),
389 is_showing_before_unload_dialog_(false),
390 last_active_time_(base::TimeTicks::Now()),
391 closed_by_user_gesture_(false),
392 minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)),
393 maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)),
394 render_view_message_source_(NULL),
395 render_frame_message_source_(NULL),
396 fullscreen_widget_routing_id_(MSG_ROUTING_NONE),
397 fullscreen_widget_had_focus_at_shutdown_(false),
398 is_subframe_(false),
399 force_disable_overscroll_content_(false),
400 last_dialog_suppressed_(false),
401 geolocation_service_context_(new GeolocationServiceContext()),
402 accessibility_mode_(
403 BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()),
404 virtual_keyboard_requested_(false),
405 loading_weak_factory_(this) {
406 frame_tree_.SetFrameRemoveListener(
407 base::Bind(&WebContentsImpl::OnFrameRemoved,
408 base::Unretained(this)));
409 #if defined(ENABLE_BROWSER_CDMS)
410 media_web_contents_observer_.reset(new MediaWebContentsObserver(this));
411 #endif
413 #if defined(OS_ANDROID)
414 audio_state_provider_.reset(new MediaPlayersObserver(this));
415 #else
416 audio_state_provider_.reset(new AudioStreamMonitor(this));
417 #endif
420 WebContentsImpl::~WebContentsImpl() {
421 is_being_destroyed_ = true;
423 // Delete all RFH pending shutdown, which will lead the corresponding RVH to
424 // shutdown and be deleted as well.
425 frame_tree_.ForEach(
426 base::Bind(&RenderFrameHostManager::ClearRFHsPendingShutdown));
428 ClearAllPowerSaveBlockers();
430 for (std::set<RenderWidgetHostImpl*>::iterator iter =
431 created_widgets_.begin(); iter != created_widgets_.end(); ++iter) {
432 (*iter)->DetachDelegate();
434 created_widgets_.clear();
436 // Clear out any JavaScript state.
437 if (dialog_manager_)
438 dialog_manager_->ResetDialogState(this);
440 if (color_chooser_info_.get())
441 color_chooser_info_->chooser->End();
443 NotifyDisconnected();
445 // Notify any observer that have a reference on this WebContents.
446 NotificationService::current()->Notify(
447 NOTIFICATION_WEB_CONTENTS_DESTROYED,
448 Source<WebContents>(this),
449 NotificationService::NoDetails());
451 // Destroy all frame tree nodes except for the root; this notifies observers.
452 frame_tree_.root()->ResetForNewProcess();
453 GetRenderManager()->ResetProxyHosts();
455 // Manually call the observer methods for the root frame tree node.
456 RenderFrameHostManager* root = GetRenderManager();
458 if (root->pending_frame_host())
459 root->pending_frame_host()->SetRenderFrameCreated(false);
460 root->current_frame_host()->SetRenderFrameCreated(false);
462 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
463 FrameDeleted(root->current_frame_host()));
465 if (root->pending_render_view_host()) {
466 FOR_EACH_OBSERVER(WebContentsObserver,
467 observers_,
468 RenderViewDeleted(root->pending_render_view_host()));
471 FOR_EACH_OBSERVER(WebContentsObserver,
472 observers_,
473 RenderViewDeleted(root->current_host()));
475 FOR_EACH_OBSERVER(WebContentsObserver,
476 observers_,
477 WebContentsDestroyed());
479 FOR_EACH_OBSERVER(WebContentsObserver,
480 observers_,
481 ResetWebContents());
483 SetDelegate(NULL);
485 STLDeleteContainerPairSecondPointers(destruction_observers_.begin(),
486 destruction_observers_.end());
489 WebContentsImpl* WebContentsImpl::CreateWithOpener(
490 const WebContents::CreateParams& params,
491 FrameTreeNode* opener) {
492 TRACE_EVENT0("browser", "WebContentsImpl::CreateWithOpener");
493 WebContentsImpl* new_contents = new WebContentsImpl(params.browser_context);
495 if (!params.opener_suppressed && opener) {
496 new_contents->GetFrameTree()->root()->SetOpener(opener);
497 new_contents->created_with_opener_ = true;
500 // This may be true even when opener is null, such as when opening blocked
501 // popups.
502 if (params.created_with_opener)
503 new_contents->created_with_opener_ = true;
505 if (params.guest_delegate) {
506 // This makes |new_contents| act as a guest.
507 // For more info, see comment above class BrowserPluginGuest.
508 BrowserPluginGuest::Create(new_contents, params.guest_delegate);
509 // We are instantiating a WebContents for browser plugin. Set its subframe
510 // bit to true.
511 new_contents->is_subframe_ = true;
513 new_contents->Init(params);
514 return new_contents;
517 // static
518 std::vector<WebContentsImpl*> WebContentsImpl::GetAllWebContents() {
519 std::vector<WebContentsImpl*> result;
520 scoped_ptr<RenderWidgetHostIterator> widgets(
521 RenderWidgetHostImpl::GetRenderWidgetHosts());
522 std::set<WebContentsImpl*> web_contents_set;
523 while (RenderWidgetHost* rwh = widgets->GetNextHost()) {
524 if (!rwh->IsRenderView())
525 continue;
526 RenderViewHost* rvh = RenderViewHost::From(rwh);
527 if (!rvh)
528 continue;
529 WebContents* web_contents = WebContents::FromRenderViewHost(rvh);
530 if (!web_contents)
531 continue;
532 WebContentsImpl* wci = static_cast<WebContentsImpl*>(web_contents);
533 if (web_contents_set.find(wci) == web_contents_set.end()) {
534 web_contents_set.insert(wci);
535 result.push_back(wci);
538 return result;
541 // static
542 WebContentsImpl* WebContentsImpl::FromFrameTreeNode(
543 FrameTreeNode* frame_tree_node) {
544 return static_cast<WebContentsImpl*>(
545 WebContents::FromRenderFrameHost(frame_tree_node->current_frame_host()));
548 RenderFrameHostManager* WebContentsImpl::GetRenderManagerForTesting() {
549 return GetRenderManager();
552 bool WebContentsImpl::OnMessageReceived(RenderViewHost* render_view_host,
553 const IPC::Message& message) {
554 return OnMessageReceived(render_view_host, NULL, message);
557 bool WebContentsImpl::OnMessageReceived(RenderViewHost* render_view_host,
558 RenderFrameHost* render_frame_host,
559 const IPC::Message& message) {
560 DCHECK(render_view_host || render_frame_host);
561 if (GetWebUI() &&
562 static_cast<WebUIImpl*>(GetWebUI())->OnMessageReceived(message)) {
563 return true;
566 base::ObserverListBase<WebContentsObserver>::Iterator it(&observers_);
567 WebContentsObserver* observer;
568 if (render_frame_host) {
569 while ((observer = it.GetNext()) != NULL)
570 if (observer->OnMessageReceived(message, render_frame_host))
571 return true;
572 } else {
573 while ((observer = it.GetNext()) != NULL)
574 if (observer->OnMessageReceived(message))
575 return true;
578 // Message handlers should be aware of which
579 // RenderViewHost/RenderFrameHost sent the message, which is temporarily
580 // stored in render_(view|frame)_message_source_.
581 if (render_frame_host)
582 render_frame_message_source_ = render_frame_host;
583 else
584 render_view_message_source_ = render_view_host;
586 bool handled = true;
587 IPC_BEGIN_MESSAGE_MAP(WebContentsImpl, message)
588 IPC_MESSAGE_HANDLER(FrameHostMsg_DomOperationResponse,
589 OnDomOperationResponse)
590 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeThemeColor,
591 OnThemeColorChanged)
592 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishDocumentLoad,
593 OnDocumentLoadedInFrame)
594 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishLoad, OnDidFinishLoad)
595 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenColorChooser, OnOpenColorChooser)
596 IPC_MESSAGE_HANDLER(FrameHostMsg_EndColorChooser, OnEndColorChooser)
597 IPC_MESSAGE_HANDLER(FrameHostMsg_SetSelectedColorInColorChooser,
598 OnSetSelectedColorInColorChooser)
599 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPlayingNotification,
600 OnMediaPlayingNotification)
601 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPausedNotification,
602 OnMediaPausedNotification)
603 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFirstVisuallyNonEmptyPaint,
604 OnFirstVisuallyNonEmptyPaint)
605 IPC_MESSAGE_HANDLER(ViewHostMsg_DidLoadResourceFromMemoryCache,
606 OnDidLoadResourceFromMemoryCache)
607 IPC_MESSAGE_HANDLER(ViewHostMsg_DidDisplayInsecureContent,
608 OnDidDisplayInsecureContent)
609 IPC_MESSAGE_HANDLER(ViewHostMsg_DidRunInsecureContent,
610 OnDidRunInsecureContent)
611 IPC_MESSAGE_HANDLER(ViewHostMsg_GoToEntryAtOffset, OnGoToEntryAtOffset)
612 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateZoomLimits, OnUpdateZoomLimits)
613 IPC_MESSAGE_HANDLER(ViewHostMsg_EnumerateDirectory, OnEnumerateDirectory)
614 IPC_MESSAGE_HANDLER(FrameHostMsg_RegisterProtocolHandler,
615 OnRegisterProtocolHandler)
616 IPC_MESSAGE_HANDLER(FrameHostMsg_UnregisterProtocolHandler,
617 OnUnregisterProtocolHandler)
618 IPC_MESSAGE_HANDLER(ViewHostMsg_Find_Reply, OnFindReply)
619 IPC_MESSAGE_HANDLER(ViewHostMsg_AppCacheAccessed, OnAppCacheAccessed)
620 IPC_MESSAGE_HANDLER(ViewHostMsg_WebUISend, OnWebUISend)
621 #if defined(ENABLE_PLUGINS)
622 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceCreated,
623 OnPepperInstanceCreated)
624 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceDeleted,
625 OnPepperInstanceDeleted)
626 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung, OnPepperPluginHung)
627 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed, OnPluginCrashed)
628 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission,
629 OnRequestPpapiBrokerPermission)
630 IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_Attach,
631 OnBrowserPluginMessage(render_frame_host,
632 message))
633 #endif
634 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateFaviconURL, OnUpdateFaviconURL)
635 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowValidationMessage,
636 OnShowValidationMessage)
637 IPC_MESSAGE_HANDLER(ViewHostMsg_HideValidationMessage,
638 OnHideValidationMessage)
639 IPC_MESSAGE_HANDLER(ViewHostMsg_MoveValidationMessage,
640 OnMoveValidationMessage)
641 #if defined(OS_ANDROID)
642 IPC_MESSAGE_HANDLER(ViewHostMsg_FindMatchRects_Reply,
643 OnFindMatchRectsReply)
644 IPC_MESSAGE_HANDLER(ViewHostMsg_OpenDateTimeDialog,
645 OnOpenDateTimeDialog)
646 #endif
647 IPC_MESSAGE_UNHANDLED(handled = false)
648 IPC_END_MESSAGE_MAP()
649 render_view_message_source_ = NULL;
650 render_frame_message_source_ = NULL;
652 return handled;
655 bool WebContentsImpl::HasValidFrameSource() {
656 if (!render_frame_message_source_) {
657 DCHECK(render_view_message_source_);
658 bad_message::ReceivedBadMessage(GetRenderProcessHost(),
659 bad_message::WC_INVALID_FRAME_SOURCE);
660 return false;
663 return true;
666 void WebContentsImpl::RunFileChooser(
667 RenderViewHost* render_view_host,
668 const FileChooserParams& params) {
669 if (delegate_)
670 delegate_->RunFileChooser(this, params);
673 NavigationControllerImpl& WebContentsImpl::GetController() {
674 return controller_;
677 const NavigationControllerImpl& WebContentsImpl::GetController() const {
678 return controller_;
681 BrowserContext* WebContentsImpl::GetBrowserContext() const {
682 return controller_.GetBrowserContext();
685 const GURL& WebContentsImpl::GetURL() const {
686 // We may not have a navigation entry yet.
687 NavigationEntry* entry = controller_.GetVisibleEntry();
688 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
691 const GURL& WebContentsImpl::GetVisibleURL() const {
692 // We may not have a navigation entry yet.
693 NavigationEntry* entry = controller_.GetVisibleEntry();
694 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
697 const GURL& WebContentsImpl::GetLastCommittedURL() const {
698 // We may not have a navigation entry yet.
699 NavigationEntry* entry = controller_.GetLastCommittedEntry();
700 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
703 WebContentsDelegate* WebContentsImpl::GetDelegate() {
704 return delegate_;
707 void WebContentsImpl::SetDelegate(WebContentsDelegate* delegate) {
708 // TODO(cbentzel): remove this debugging code?
709 if (delegate == delegate_)
710 return;
711 if (delegate_)
712 delegate_->Detach(this);
713 delegate_ = delegate;
714 if (delegate_) {
715 delegate_->Attach(this);
716 // Ensure the visible RVH reflects the new delegate's preferences.
717 if (view_)
718 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
722 RenderProcessHost* WebContentsImpl::GetRenderProcessHost() const {
723 RenderViewHostImpl* host = GetRenderManager()->current_host();
724 return host ? host->GetProcess() : NULL;
727 RenderFrameHostImpl* WebContentsImpl::GetMainFrame() {
728 return frame_tree_.root()->current_frame_host();
731 RenderFrameHostImpl* WebContentsImpl::GetFocusedFrame() {
732 FrameTreeNode* focused_node = frame_tree_.GetFocusedFrame();
733 if (!focused_node)
734 return nullptr;
735 return focused_node->current_frame_host();
738 void WebContentsImpl::ForEachFrame(
739 const base::Callback<void(RenderFrameHost*)>& on_frame) {
740 frame_tree_.ForEach(base::Bind(&ForEachFrameInternal, on_frame));
743 void WebContentsImpl::SendToAllFrames(IPC::Message* message) {
744 ForEachFrame(base::Bind(&SendToAllFramesInternal, message));
745 delete message;
748 RenderViewHostImpl* WebContentsImpl::GetRenderViewHost() const {
749 return GetRenderManager()->current_host();
752 int WebContentsImpl::GetRoutingID() const {
753 if (!GetRenderViewHost())
754 return MSG_ROUTING_NONE;
756 return GetRenderViewHost()->GetRoutingID();
759 void WebContentsImpl::CancelActiveAndPendingDialogs() {
760 if (dialog_manager_)
761 dialog_manager_->CancelActiveAndPendingDialogs(this);
762 if (browser_plugin_embedder_)
763 browser_plugin_embedder_->CancelGuestDialogs();
766 int WebContentsImpl::GetFullscreenWidgetRoutingID() const {
767 return fullscreen_widget_routing_id_;
770 void WebContentsImpl::ClosePage() {
771 GetRenderViewHost()->ClosePage();
774 RenderWidgetHostView* WebContentsImpl::GetRenderWidgetHostView() const {
775 return GetRenderManager()->GetRenderWidgetHostView();
778 RenderWidgetHostView* WebContentsImpl::GetFullscreenRenderWidgetHostView()
779 const {
780 RenderWidgetHost* const widget_host =
781 RenderWidgetHostImpl::FromID(GetRenderProcessHost()->GetID(),
782 GetFullscreenWidgetRoutingID());
783 return widget_host ? widget_host->GetView() : NULL;
786 WebContentsView* WebContentsImpl::GetView() const {
787 return view_.get();
790 SkColor WebContentsImpl::GetThemeColor() const {
791 return theme_color_;
794 void WebContentsImpl::SetAccessibilityMode(AccessibilityMode mode) {
795 if (mode == accessibility_mode_)
796 return;
798 accessibility_mode_ = mode;
799 frame_tree_.ForEach(
800 base::Bind(&ForEachFrameInternal,
801 base::Bind(&SetAccessibilityModeOnFrame, mode)));
802 frame_tree_.ForEach(
803 base::Bind(&ForEachPendingFrameInternal,
804 base::Bind(&SetAccessibilityModeOnFrame, mode)));
807 void WebContentsImpl::AddAccessibilityMode(AccessibilityMode mode) {
808 SetAccessibilityMode(AddAccessibilityModeTo(accessibility_mode_, mode));
811 void WebContentsImpl::RemoveAccessibilityMode(AccessibilityMode mode) {
812 SetAccessibilityMode(RemoveAccessibilityModeFrom(accessibility_mode_, mode));
815 void WebContentsImpl::RequestAXTreeSnapshot(AXTreeSnapshotCallback callback) {
816 // TODO(dmazzoni): http://crbug.com/475608 This only returns the
817 // accessibility tree from the main frame and everything in the
818 // same site instance.
819 GetMainFrame()->RequestAXTreeSnapshot(callback);
822 WebUI* WebContentsImpl::CreateWebUI(const GURL& url) {
823 WebUIImpl* web_ui = new WebUIImpl(this);
824 WebUIController* controller = WebUIControllerFactoryRegistry::GetInstance()->
825 CreateWebUIControllerForURL(web_ui, url);
826 if (controller) {
827 web_ui->AddMessageHandler(new GenericHandler());
828 web_ui->SetController(controller);
829 return web_ui;
832 delete web_ui;
833 return NULL;
836 WebUI* WebContentsImpl::GetWebUI() const {
837 return GetRenderManager()->web_ui() ? GetRenderManager()->web_ui()
838 : GetRenderManager()->pending_web_ui();
841 WebUI* WebContentsImpl::GetCommittedWebUI() const {
842 return GetRenderManager()->web_ui();
845 void WebContentsImpl::SetUserAgentOverride(const std::string& override) {
846 if (GetUserAgentOverride() == override)
847 return;
849 renderer_preferences_.user_agent_override = override;
851 // Send the new override string to the renderer.
852 RenderViewHost* host = GetRenderViewHost();
853 if (host)
854 host->SyncRendererPrefs();
856 // Reload the page if a load is currently in progress to avoid having
857 // different parts of the page loaded using different user agents.
858 NavigationEntry* entry = controller_.GetVisibleEntry();
859 if (is_loading_ && entry != NULL && entry->GetIsOverridingUserAgent())
860 controller_.ReloadIgnoringCache(true);
862 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
863 UserAgentOverrideSet(override));
866 const std::string& WebContentsImpl::GetUserAgentOverride() const {
867 return renderer_preferences_.user_agent_override;
870 void WebContentsImpl::EnableTreeOnlyAccessibilityMode() {
871 if (GetAccessibilityMode() == AccessibilityModeTreeOnly)
872 ForEachFrame(base::Bind(&ResetAccessibility));
873 else
874 AddAccessibilityMode(AccessibilityModeTreeOnly);
877 bool WebContentsImpl::IsTreeOnlyAccessibilityModeForTesting() const {
878 return accessibility_mode_ == AccessibilityModeTreeOnly;
881 bool WebContentsImpl::IsFullAccessibilityModeForTesting() const {
882 return accessibility_mode_ == AccessibilityModeComplete;
885 #if defined(OS_WIN)
886 void WebContentsImpl::SetParentNativeViewAccessible(
887 gfx::NativeViewAccessible accessible_parent) {
888 accessible_parent_ = accessible_parent;
889 RenderFrameHostImpl* rfh = GetMainFrame();
890 if (rfh)
891 rfh->SetParentNativeViewAccessible(accessible_parent);
893 #endif
895 const base::string16& WebContentsImpl::GetTitle() const {
896 // Transient entries take precedence. They are used for interstitial pages
897 // that are shown on top of existing pages.
898 NavigationEntry* entry = controller_.GetTransientEntry();
899 std::string accept_languages =
900 GetContentClient()->browser()->GetAcceptLangs(
901 GetBrowserContext());
902 if (entry) {
903 return entry->GetTitleForDisplay(accept_languages);
905 WebUI* our_web_ui = GetRenderManager()->pending_web_ui() ?
906 GetRenderManager()->pending_web_ui() : GetRenderManager()->web_ui();
907 if (our_web_ui) {
908 // Don't override the title in view source mode.
909 entry = controller_.GetVisibleEntry();
910 if (!(entry && entry->IsViewSourceMode())) {
911 // Give the Web UI the chance to override our title.
912 const base::string16& title = our_web_ui->GetOverriddenTitle();
913 if (!title.empty())
914 return title;
918 // We use the title for the last committed entry rather than a pending
919 // navigation entry. For example, when the user types in a URL, we want to
920 // keep the old page's title until the new load has committed and we get a new
921 // title.
922 entry = controller_.GetLastCommittedEntry();
924 // We make an exception for initial navigations.
925 if (controller_.IsInitialNavigation()) {
926 // We only want to use the title from the visible entry in one of two cases:
927 // 1. There's already a committed entry for an initial navigation, in which
928 // case we are doing a history navigation in a new tab (e.g., Ctrl+Back).
929 // 2. The pending entry has been explicitly assigned a title to display.
931 // If there's no last committed entry and no assigned title, we should fall
932 // back to |page_title_when_no_navigation_entry_| rather than showing the
933 // URL.
934 if (entry ||
935 (controller_.GetVisibleEntry() &&
936 !controller_.GetVisibleEntry()->GetTitle().empty())) {
937 entry = controller_.GetVisibleEntry();
941 if (entry) {
942 return entry->GetTitleForDisplay(accept_languages);
945 // |page_title_when_no_navigation_entry_| is finally used
946 // if no title cannot be retrieved.
947 return page_title_when_no_navigation_entry_;
950 int32 WebContentsImpl::GetMaxPageID() {
951 return GetMaxPageIDForSiteInstance(GetSiteInstance());
954 int32 WebContentsImpl::GetMaxPageIDForSiteInstance(
955 SiteInstance* site_instance) {
956 if (max_page_ids_.find(site_instance->GetId()) == max_page_ids_.end())
957 max_page_ids_[site_instance->GetId()] = -1;
959 return max_page_ids_[site_instance->GetId()];
962 void WebContentsImpl::UpdateMaxPageID(int32 page_id) {
963 UpdateMaxPageIDForSiteInstance(GetSiteInstance(), page_id);
966 void WebContentsImpl::UpdateMaxPageIDForSiteInstance(
967 SiteInstance* site_instance, int32 page_id) {
968 if (GetMaxPageIDForSiteInstance(site_instance) < page_id)
969 max_page_ids_[site_instance->GetId()] = page_id;
972 void WebContentsImpl::CopyMaxPageIDsFrom(WebContents* web_contents) {
973 WebContentsImpl* contents = static_cast<WebContentsImpl*>(web_contents);
974 max_page_ids_ = contents->max_page_ids_;
977 SiteInstanceImpl* WebContentsImpl::GetSiteInstance() const {
978 return GetRenderManager()->current_host()->GetSiteInstance();
981 SiteInstanceImpl* WebContentsImpl::GetPendingSiteInstance() const {
982 RenderViewHostImpl* dest_rvh =
983 GetRenderManager()->pending_render_view_host() ?
984 GetRenderManager()->pending_render_view_host() :
985 GetRenderManager()->current_host();
986 return dest_rvh->GetSiteInstance();
989 bool WebContentsImpl::IsLoading() const {
990 return is_loading_;
993 bool WebContentsImpl::IsLoadingToDifferentDocument() const {
994 return is_loading_ && is_load_to_different_document_;
997 bool WebContentsImpl::IsWaitingForResponse() const {
998 return waiting_for_response_ && is_load_to_different_document_;
1001 const net::LoadStateWithParam& WebContentsImpl::GetLoadState() const {
1002 return load_state_;
1005 const base::string16& WebContentsImpl::GetLoadStateHost() const {
1006 return load_state_host_;
1009 uint64 WebContentsImpl::GetUploadSize() const {
1010 return upload_size_;
1013 uint64 WebContentsImpl::GetUploadPosition() const {
1014 return upload_position_;
1017 std::set<GURL> WebContentsImpl::GetSitesInTab() const {
1018 std::set<GURL> sites;
1019 frame_tree_.ForEach(base::Bind(&CollectSites,
1020 base::Unretained(GetBrowserContext()),
1021 base::Unretained(&sites)));
1022 return sites;
1025 const std::string& WebContentsImpl::GetEncoding() const {
1026 return canonical_encoding_;
1029 bool WebContentsImpl::DisplayedInsecureContent() const {
1030 return displayed_insecure_content_;
1033 void WebContentsImpl::IncrementCapturerCount(const gfx::Size& capture_size) {
1034 DCHECK(!is_being_destroyed_);
1035 ++capturer_count_;
1036 DVLOG(1) << "There are now " << capturer_count_
1037 << " capturing(s) of WebContentsImpl@" << this;
1039 // Note: This provides a hint to upstream code to size the views optimally
1040 // for quality (e.g., to avoid scaling).
1041 if (!capture_size.IsEmpty() && preferred_size_for_capture_.IsEmpty()) {
1042 preferred_size_for_capture_ = capture_size;
1043 OnPreferredSizeChanged(preferred_size_);
1046 // Ensure that all views are un-occluded before capture begins.
1047 WasUnOccluded();
1050 void WebContentsImpl::DecrementCapturerCount() {
1051 --capturer_count_;
1052 DVLOG(1) << "There are now " << capturer_count_
1053 << " capturing(s) of WebContentsImpl@" << this;
1054 DCHECK_LE(0, capturer_count_);
1056 if (is_being_destroyed_)
1057 return;
1059 if (capturer_count_ == 0) {
1060 const gfx::Size old_size = preferred_size_for_capture_;
1061 preferred_size_for_capture_ = gfx::Size();
1062 OnPreferredSizeChanged(old_size);
1065 if (IsHidden()) {
1066 DVLOG(1) << "Executing delayed WasHidden().";
1067 WasHidden();
1071 int WebContentsImpl::GetCapturerCount() const {
1072 return capturer_count_;
1075 bool WebContentsImpl::IsAudioMuted() const {
1076 return audio_muter_.get() && audio_muter_->is_muting();
1079 void WebContentsImpl::SetAudioMuted(bool mute) {
1080 DVLOG(1) << "SetAudioMuted(mute=" << mute << "), was " << IsAudioMuted()
1081 << " for WebContentsImpl@" << this;
1083 if (mute == IsAudioMuted())
1084 return;
1086 if (mute) {
1087 if (!audio_muter_)
1088 audio_muter_.reset(new WebContentsAudioMuter(this));
1089 audio_muter_->StartMuting();
1090 } else {
1091 DCHECK(audio_muter_);
1092 audio_muter_->StopMuting();
1095 // Notification for UI updates in response to the changed muting state.
1096 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
1099 bool WebContentsImpl::IsCrashed() const {
1100 return (crashed_status_ == base::TERMINATION_STATUS_PROCESS_CRASHED ||
1101 crashed_status_ == base::TERMINATION_STATUS_ABNORMAL_TERMINATION ||
1102 crashed_status_ == base::TERMINATION_STATUS_PROCESS_WAS_KILLED
1103 #if defined(OS_CHROMEOS)
1105 crashed_status_ == base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM
1106 #endif
1110 void WebContentsImpl::SetIsCrashed(base::TerminationStatus status,
1111 int error_code) {
1112 if (status == crashed_status_)
1113 return;
1115 crashed_status_ = status;
1116 crashed_error_code_ = error_code;
1117 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
1120 base::TerminationStatus WebContentsImpl::GetCrashedStatus() const {
1121 return crashed_status_;
1124 bool WebContentsImpl::IsBeingDestroyed() const {
1125 return is_being_destroyed_;
1128 void WebContentsImpl::NotifyNavigationStateChanged(
1129 InvalidateTypes changed_flags) {
1130 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1131 // is fixed.
1132 tracked_objects::ScopedTracker tracking_profile(
1133 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1134 "466285 WebContentsImpl::NotifyNavigationStateChanged"));
1135 // Create and release the audio power save blocker depending on whether the
1136 // tab is actively producing audio or not.
1137 if ((changed_flags & INVALIDATE_TYPE_TAB) &&
1138 audio_state_provider_->IsAudioStateAvailable()) {
1139 if (WasRecentlyAudible()) {
1140 if (!audio_power_save_blocker_)
1141 CreateAudioPowerSaveBlocker();
1142 } else {
1143 audio_power_save_blocker_.reset();
1147 if (delegate_)
1148 delegate_->NavigationStateChanged(this, changed_flags);
1151 base::TimeTicks WebContentsImpl::GetLastActiveTime() const {
1152 return last_active_time_;
1155 void WebContentsImpl::SetLastActiveTime(base::TimeTicks last_active_time) {
1156 last_active_time_ = last_active_time;
1159 void WebContentsImpl::WasShown() {
1160 controller_.SetActive(true);
1162 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1163 if (view) {
1164 view->Show();
1165 #if defined(OS_MACOSX)
1166 view->SetActive(true);
1167 #endif
1171 last_active_time_ = base::TimeTicks::Now();
1173 // The resize rect might have changed while this was inactive -- send the new
1174 // one to make sure it's up to date.
1175 RenderViewHostImpl* rvh = GetRenderViewHost();
1176 if (rvh)
1177 rvh->ResizeRectChanged(GetRootWindowResizerRect());
1179 // Restore power save blocker if there are active video players running.
1180 if (!active_video_players_.empty() && !video_power_save_blocker_)
1181 CreateVideoPowerSaveBlocker();
1183 FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasShown());
1185 should_normally_be_visible_ = true;
1188 void WebContentsImpl::WasHidden() {
1189 // If there are entities capturing screenshots or video (e.g., mirroring),
1190 // don't activate the "disable rendering" optimization.
1191 if (capturer_count_ == 0) {
1192 // |GetRenderViewHost()| can be NULL if the user middle clicks a link to
1193 // open a tab in the background, then closes the tab before selecting it.
1194 // This is because closing the tab calls WebContentsImpl::Destroy(), which
1195 // removes the |GetRenderViewHost()|; then when we actually destroy the
1196 // window, OnWindowPosChanged() notices and calls WasHidden() (which
1197 // calls us).
1198 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1199 if (view)
1200 view->Hide();
1203 // Release any video power save blockers held as video is not visible.
1204 video_power_save_blocker_.reset();
1207 FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasHidden());
1209 should_normally_be_visible_ = false;
1212 void WebContentsImpl::WasOccluded() {
1213 if (capturer_count_ > 0)
1214 return;
1216 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1217 if (view)
1218 view->WasOccluded();
1222 void WebContentsImpl::WasUnOccluded() {
1223 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1224 if (view)
1225 view->WasUnOccluded();
1229 bool WebContentsImpl::NeedToFireBeforeUnload() {
1230 // TODO(creis): Should we fire even for interstitial pages?
1231 return WillNotifyDisconnection() && !ShowingInterstitialPage() &&
1232 !GetRenderViewHost()->SuddenTerminationAllowed();
1235 void WebContentsImpl::DispatchBeforeUnload(bool for_cross_site_transition) {
1236 GetMainFrame()->DispatchBeforeUnload(for_cross_site_transition);
1239 void WebContentsImpl::AttachToOuterWebContentsFrame(
1240 WebContents* outer_web_contents,
1241 RenderFrameHost* outer_contents_frame) {
1242 CHECK(BrowserPluginGuestMode::UseCrossProcessFramesForGuests());
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 !BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
1337 scoped_ptr<WebContentsView> platform_view(CreateWebContentsView(
1338 this, delegate, &render_view_host_delegate_view_));
1340 WebContentsViewGuest* rv = new WebContentsViewGuest(
1341 this, browser_plugin_guest_.get(), platform_view.Pass(),
1342 render_view_host_delegate_view_);
1343 render_view_host_delegate_view_ = rv;
1344 view_.reset(rv);
1345 } else {
1346 // Regular WebContentsView.
1347 view_.reset(CreateWebContentsView(
1348 this, delegate, &render_view_host_delegate_view_));
1350 CHECK(render_view_host_delegate_view_);
1351 CHECK(view_.get());
1353 gfx::Size initial_size = params.initial_size;
1354 view_->CreateView(initial_size, params.context);
1356 #if defined(ENABLE_PLUGINS)
1357 plugin_content_origin_whitelist_.reset(
1358 new PluginContentOriginWhitelist(this));
1359 #endif
1361 registrar_.Add(this,
1362 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1363 NotificationService::AllBrowserContextsAndSources());
1365 screen_orientation_dispatcher_host_.reset(
1366 new ScreenOrientationDispatcherHostImpl(this));
1368 manifest_manager_host_.reset(new ManifestManagerHost(this));
1370 #if defined(OS_ANDROID)
1371 date_time_chooser_.reset(new DateTimeChooserAndroid());
1372 #endif
1374 // BrowserPluginGuest::Init needs to be called after this WebContents has
1375 // a RenderWidgetHostViewGuest. That is, |view_->CreateView| above.
1376 if (browser_plugin_guest_)
1377 browser_plugin_guest_->Init();
1379 for (size_t i = 0; i < g_created_callbacks.Get().size(); i++)
1380 g_created_callbacks.Get().at(i).Run(this);
1382 // If the WebContents creation was renderer-initiated, it means that the
1383 // corresponding RenderView and main RenderFrame have already been created.
1384 // Ensure observers are notified about this.
1385 if (params.renderer_initiated_creation) {
1386 GetRenderViewHost()->set_renderer_initialized(true);
1387 RenderViewCreated(GetRenderViewHost());
1388 GetRenderManager()->current_frame_host()->SetRenderFrameCreated(true);
1391 // Ensure that observers are notified of the creation of this WebContents's
1392 // main RenderFrameHost. It must be done here for main frames, since the
1393 // NotifySwappedFromRenderManager expects view_ to already be created and that
1394 // happens after RenderFrameHostManager::Init.
1395 NotifySwappedFromRenderManager(
1396 nullptr, GetRenderManager()->current_frame_host(), true);
1399 void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl* web_contents) {
1400 RemoveDestructionObserver(web_contents);
1402 // Clear a pending contents that has been closed before being shown.
1403 for (PendingContents::iterator iter = pending_contents_.begin();
1404 iter != pending_contents_.end();
1405 ++iter) {
1406 if (iter->second != web_contents)
1407 continue;
1408 pending_contents_.erase(iter);
1409 return;
1411 NOTREACHED();
1414 void WebContentsImpl::AddDestructionObserver(WebContentsImpl* web_contents) {
1415 if (!ContainsKey(destruction_observers_, web_contents)) {
1416 destruction_observers_[web_contents] =
1417 new DestructionObserver(this, web_contents);
1421 void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl* web_contents) {
1422 DestructionObservers::iterator iter =
1423 destruction_observers_.find(web_contents);
1424 if (iter != destruction_observers_.end()) {
1425 delete destruction_observers_[web_contents];
1426 destruction_observers_.erase(iter);
1430 void WebContentsImpl::AddObserver(WebContentsObserver* observer) {
1431 observers_.AddObserver(observer);
1434 void WebContentsImpl::RemoveObserver(WebContentsObserver* observer) {
1435 observers_.RemoveObserver(observer);
1438 std::set<RenderWidgetHostView*>
1439 WebContentsImpl::GetRenderWidgetHostViewsInTree() {
1440 std::set<RenderWidgetHostView*> set;
1441 if (ShowingInterstitialPage()) {
1442 set.insert(GetRenderWidgetHostView());
1443 } else {
1444 ForEachFrame(
1445 base::Bind(&AddRenderWidgetHostViewToSet, base::Unretained(&set)));
1447 return set;
1450 void WebContentsImpl::Activate() {
1451 if (delegate_)
1452 delegate_->ActivateContents(this);
1455 void WebContentsImpl::Deactivate() {
1456 if (delegate_)
1457 delegate_->DeactivateContents(this);
1460 void WebContentsImpl::LostCapture() {
1461 if (delegate_)
1462 delegate_->LostCapture();
1465 void WebContentsImpl::RenderWidgetDeleted(
1466 RenderWidgetHostImpl* render_widget_host) {
1467 if (is_being_destroyed_) {
1468 // |created_widgets_| might have been destroyed.
1469 return;
1472 std::set<RenderWidgetHostImpl*>::iterator iter =
1473 created_widgets_.find(render_widget_host);
1474 if (iter != created_widgets_.end())
1475 created_widgets_.erase(iter);
1477 if (render_widget_host &&
1478 render_widget_host->GetRoutingID() == fullscreen_widget_routing_id_) {
1479 if (delegate_ && delegate_->EmbedsFullscreenWidget())
1480 delegate_->ExitFullscreenModeForTab(this);
1481 FOR_EACH_OBSERVER(WebContentsObserver,
1482 observers_,
1483 DidDestroyFullscreenWidget(
1484 fullscreen_widget_routing_id_));
1485 fullscreen_widget_routing_id_ = MSG_ROUTING_NONE;
1486 if (fullscreen_widget_had_focus_at_shutdown_)
1487 view_->RestoreFocus();
1491 void WebContentsImpl::RenderWidgetGotFocus(
1492 RenderWidgetHostImpl* render_widget_host) {
1493 // Notify the observers if an embedded fullscreen widget was focused.
1494 if (delegate_ && render_widget_host && delegate_->EmbedsFullscreenWidget() &&
1495 render_widget_host->GetView() == GetFullscreenRenderWidgetHostView()) {
1496 NotifyWebContentsFocused();
1500 void WebContentsImpl::RenderWidgetWasResized(
1501 RenderWidgetHostImpl* render_widget_host,
1502 bool width_changed) {
1503 RenderFrameHostImpl* rfh = GetMainFrame();
1504 if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
1505 return;
1507 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1508 MainFrameWasResized(width_changed));
1511 void WebContentsImpl::ScreenInfoChanged() {
1512 if (browser_plugin_embedder_)
1513 browser_plugin_embedder_->ScreenInfoChanged();
1516 bool WebContentsImpl::PreHandleKeyboardEvent(
1517 const NativeWebKeyboardEvent& event,
1518 bool* is_keyboard_shortcut) {
1519 return delegate_ &&
1520 delegate_->PreHandleKeyboardEvent(this, event, is_keyboard_shortcut);
1523 void WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
1524 if (browser_plugin_embedder_ &&
1525 browser_plugin_embedder_->HandleKeyboardEvent(event)) {
1526 return;
1528 if (delegate_)
1529 delegate_->HandleKeyboardEvent(this, event);
1532 bool WebContentsImpl::HandleWheelEvent(
1533 const blink::WebMouseWheelEvent& event) {
1534 #if !defined(OS_MACOSX)
1535 // On platforms other than Mac, control+mousewheel may change zoom. On Mac,
1536 // this isn't done for two reasons:
1537 // -the OS already has a gesture to do this through pinch-zoom
1538 // -if a user starts an inertial scroll, let's go, and presses control
1539 // (i.e. control+tab) then the OS's buffered scroll events will come in
1540 // with control key set which isn't what the user wants
1541 if (delegate_ && event.wheelTicksY &&
1542 (event.modifiers & blink::WebInputEvent::ControlKey) &&
1543 !event.canScroll) {
1544 delegate_->ContentsZoomChange(event.wheelTicksY > 0);
1545 return true;
1547 #endif
1548 return false;
1551 bool WebContentsImpl::PreHandleGestureEvent(
1552 const blink::WebGestureEvent& event) {
1553 return delegate_ && delegate_->PreHandleGestureEvent(this, event);
1556 void WebContentsImpl::EnterFullscreenMode(const GURL& origin) {
1557 // This method is being called to enter renderer-initiated fullscreen mode.
1558 // Make sure any existing fullscreen widget is shut down first.
1559 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
1560 if (widget_view)
1561 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())->Shutdown();
1563 if (delegate_)
1564 delegate_->EnterFullscreenModeForTab(this, origin);
1566 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1567 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1570 void WebContentsImpl::ExitFullscreenMode() {
1571 // This method is being called to leave renderer-initiated fullscreen mode.
1572 // Make sure any existing fullscreen widget is shut down first.
1573 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
1574 if (widget_view)
1575 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())->Shutdown();
1577 #if defined(OS_ANDROID)
1578 ContentVideoView* video_view = ContentVideoView::GetInstance();
1579 if (video_view != NULL)
1580 video_view->OnExitFullscreen();
1581 #endif
1583 if (delegate_)
1584 delegate_->ExitFullscreenModeForTab(this);
1586 // Ensure web contents exit fullscreen state by sending a resize message,
1587 // which includes the fullscreen state. This is required for the situation
1588 // of the browser moving the view into a fullscreen state "browser fullscreen"
1589 // and then the contents entering "tab fullscreen". Exiting the contents
1590 // "tab fullscreen" then won't have the side effect of the view resizing,
1591 // hence the explicit call here is required.
1592 if (RenderWidgetHostView* rwh_view = GetRenderWidgetHostView()) {
1593 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
1594 render_widget_host->WasResized();
1597 FOR_EACH_OBSERVER(WebContentsObserver,
1598 observers_,
1599 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1602 bool WebContentsImpl::IsFullscreenForCurrentTab() const {
1603 return delegate_ ? delegate_->IsFullscreenForTabOrPending(this) : false;
1606 blink::WebDisplayMode WebContentsImpl::GetDisplayMode() const {
1607 return delegate_ ? delegate_->GetDisplayMode(this)
1608 : blink::WebDisplayModeBrowser;
1611 void WebContentsImpl::RequestToLockMouse(bool user_gesture,
1612 bool last_unlocked_by_target) {
1613 if (delegate_) {
1614 delegate_->RequestToLockMouse(this, user_gesture, last_unlocked_by_target);
1615 } else {
1616 GotResponseToLockMouseRequest(false);
1620 void WebContentsImpl::LostMouseLock() {
1621 if (delegate_)
1622 delegate_->LostMouseLock();
1625 void WebContentsImpl::CreateNewWindow(
1626 SiteInstance* source_site_instance,
1627 int route_id,
1628 int main_frame_route_id,
1629 const ViewHostMsg_CreateWindow_Params& params,
1630 SessionStorageNamespace* session_storage_namespace) {
1631 // We usually create the new window in the same BrowsingInstance (group of
1632 // script-related windows), by passing in the current SiteInstance. However,
1633 // if the opener is being suppressed (in a non-guest), we create a new
1634 // SiteInstance in its own BrowsingInstance.
1635 bool is_guest = BrowserPluginGuest::IsGuest(this);
1637 if (is_guest && BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
1638 // TODO(lazyboy): CreateNewWindow doesn't work for OOPIF-based <webview>
1639 // yet.
1640 NOTREACHED();
1643 // If the opener is to be suppressed, the new window can be in any process.
1644 // Since routing ids are process specific, we must not have one passed in
1645 // as argument here.
1646 DCHECK(!params.opener_suppressed || route_id == MSG_ROUTING_NONE);
1648 scoped_refptr<SiteInstance> site_instance =
1649 params.opener_suppressed && !is_guest
1650 ? SiteInstance::CreateForURL(GetBrowserContext(), params.target_url)
1651 : source_site_instance;
1653 // A message to create a new window can only come from a process for a frame
1654 // in this WebContents' FrameTree. If any other process sends the request, it
1655 // is invalid and the process must be terminated.
1656 int render_process_id = source_site_instance->GetProcess()->GetID();
1657 bool did_match_process = false;
1658 frame_tree_.ForEach(
1659 base::Bind(&FindMatchingProcess, render_process_id, &did_match_process));
1660 if (!did_match_process) {
1661 RenderProcessHost* rph = source_site_instance->GetProcess();
1662 base::ProcessHandle process_handle = rph->GetHandle();
1663 if (process_handle != base::kNullProcessHandle) {
1664 RecordAction(
1665 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWindow"));
1666 rph->Shutdown(RESULT_CODE_KILLED, false);
1668 return;
1671 // We must assign the SessionStorageNamespace before calling Init().
1673 // http://crbug.com/142685
1674 const std::string& partition_id =
1675 GetContentClient()->browser()->
1676 GetStoragePartitionIdForSite(GetBrowserContext(),
1677 site_instance->GetSiteURL());
1678 StoragePartition* partition = BrowserContext::GetStoragePartition(
1679 GetBrowserContext(), site_instance.get());
1680 DOMStorageContextWrapper* dom_storage_context =
1681 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
1682 SessionStorageNamespaceImpl* session_storage_namespace_impl =
1683 static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
1684 CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
1686 if (delegate_ &&
1687 !delegate_->ShouldCreateWebContents(this,
1688 route_id,
1689 main_frame_route_id,
1690 params.window_container_type,
1691 params.frame_name,
1692 params.target_url,
1693 partition_id,
1694 session_storage_namespace)) {
1695 if (route_id != MSG_ROUTING_NONE &&
1696 !RenderViewHost::FromID(render_process_id, route_id)) {
1697 // If the embedder didn't create a WebContents for this route, we need to
1698 // delete the RenderView that had already been created.
1699 Send(new ViewMsg_Close(route_id));
1701 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(route_id);
1702 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(
1703 main_frame_route_id);
1704 return;
1707 // Create the new web contents. This will automatically create the new
1708 // WebContentsView. In the future, we may want to create the view separately.
1709 CreateParams create_params(GetBrowserContext(), site_instance.get());
1710 create_params.routing_id = route_id;
1711 create_params.main_frame_routing_id = main_frame_route_id;
1712 create_params.main_frame_name = params.frame_name;
1713 create_params.opener_render_process_id = render_process_id;
1714 create_params.opener_render_frame_id = params.opener_render_frame_id;
1715 create_params.opener_suppressed = params.opener_suppressed;
1716 if (params.disposition == NEW_BACKGROUND_TAB)
1717 create_params.initially_hidden = true;
1718 create_params.renderer_initiated_creation =
1719 main_frame_route_id != MSG_ROUTING_NONE;
1721 WebContentsImpl* new_contents = NULL;
1722 if (!is_guest) {
1723 create_params.context = view_->GetNativeView();
1724 create_params.initial_size = GetContainerBounds().size();
1725 new_contents = static_cast<WebContentsImpl*>(
1726 WebContents::Create(create_params));
1727 } else {
1728 new_contents = GetBrowserPluginGuest()->CreateNewGuestWindow(create_params);
1730 new_contents->GetController().SetSessionStorageNamespace(
1731 partition_id,
1732 session_storage_namespace);
1734 // If the new frame has a name, make sure any SiteInstances that can find
1735 // this named frame have proxies for it. Must be called after
1736 // SetSessionStorageNamespace, since this calls CreateRenderView, which uses
1737 // GetSessionStorageNamespace.
1738 if (!params.frame_name.empty())
1739 new_contents->GetRenderManager()->CreateProxiesForNewNamedFrame();
1741 // Save the window for later if we're not suppressing the opener (since it
1742 // will be shown immediately).
1743 if (!params.opener_suppressed) {
1744 if (!is_guest) {
1745 WebContentsView* new_view = new_contents->view_.get();
1747 // TODO(brettw): It seems bogus that we have to call this function on the
1748 // newly created object and give it one of its own member variables.
1749 new_view->CreateViewForWidget(new_contents->GetRenderViewHost(), false);
1751 // Save the created window associated with the route so we can show it
1752 // later.
1753 DCHECK_NE(MSG_ROUTING_NONE, route_id);
1754 pending_contents_[route_id] = new_contents;
1755 AddDestructionObserver(new_contents);
1758 if (delegate_) {
1759 delegate_->WebContentsCreated(
1760 this, params.opener_render_frame_id, params.frame_name,
1761 params.target_url, new_contents);
1764 if (params.opener_suppressed) {
1765 // When the opener is suppressed, the original renderer cannot access the
1766 // new window. As a result, we need to show and navigate the window here.
1767 bool was_blocked = false;
1768 if (delegate_) {
1769 gfx::Rect initial_rect;
1770 delegate_->AddNewContents(
1771 this, new_contents, params.disposition, initial_rect,
1772 params.user_gesture, &was_blocked);
1774 if (!was_blocked) {
1775 OpenURLParams open_params(params.target_url,
1776 Referrer(),
1777 CURRENT_TAB,
1778 ui::PAGE_TRANSITION_LINK,
1779 true /* is_renderer_initiated */);
1780 open_params.user_gesture = params.user_gesture;
1782 if (delegate_ && !is_guest &&
1783 !delegate_->ShouldResumeRequestsForCreatedWindow()) {
1784 // We are in asynchronous add new contents path, delay opening url
1785 new_contents->delayed_open_url_params_.reset(
1786 new OpenURLParams(open_params));
1787 } else {
1788 new_contents->OpenURL(open_params);
1794 void WebContentsImpl::CreateNewWidget(int render_process_id,
1795 int route_id,
1796 blink::WebPopupType popup_type) {
1797 CreateNewWidget(render_process_id, route_id, false, popup_type);
1800 void WebContentsImpl::CreateNewFullscreenWidget(int render_process_id,
1801 int route_id) {
1802 CreateNewWidget(render_process_id, route_id, true, blink::WebPopupTypeNone);
1805 void WebContentsImpl::CreateNewWidget(int render_process_id,
1806 int route_id,
1807 bool is_fullscreen,
1808 blink::WebPopupType popup_type) {
1809 RenderProcessHost* process = GetRenderProcessHost();
1810 // A message to create a new widget can only come from the active process for
1811 // this WebContentsImpl instance. If any other process sends the request,
1812 // it is invalid and the process must be terminated.
1813 if (process->GetID() != render_process_id) {
1814 RenderProcessHost* rph = RenderProcessHost::FromID(render_process_id);
1815 base::ProcessHandle process_handle = rph->GetHandle();
1816 if (process_handle != base::kNullProcessHandle) {
1817 RecordAction(
1818 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWidget"));
1819 rph->Shutdown(RESULT_CODE_KILLED, false);
1821 return;
1824 RenderWidgetHostImpl* widget_host =
1825 new RenderWidgetHostImpl(this, process, route_id, IsHidden());
1826 created_widgets_.insert(widget_host);
1828 RenderWidgetHostViewBase* widget_view =
1829 static_cast<RenderWidgetHostViewBase*>(
1830 view_->CreateViewForPopupWidget(widget_host));
1831 if (!widget_view)
1832 return;
1833 if (!is_fullscreen) {
1834 // Popups should not get activated.
1835 widget_view->SetPopupType(popup_type);
1837 // Save the created widget associated with the route so we can show it later.
1838 pending_widget_views_[route_id] = widget_view;
1840 #if defined(OS_MACOSX)
1841 // A RenderWidgetHostViewMac has lifetime scoped to the view. We'll retain it
1842 // to allow it to survive the trip without being hosted.
1843 base::mac::NSObjectRetain(widget_view->GetNativeView());
1844 #endif
1847 void WebContentsImpl::ShowCreatedWindow(int route_id,
1848 WindowOpenDisposition disposition,
1849 const gfx::Rect& initial_rect,
1850 bool user_gesture) {
1851 WebContentsImpl* contents = GetCreatedWindow(route_id);
1852 if (contents) {
1853 WebContentsDelegate* delegate = GetDelegate();
1854 contents->is_resume_pending_ = true;
1855 if (!delegate || delegate->ShouldResumeRequestsForCreatedWindow())
1856 contents->ResumeLoadingCreatedWebContents();
1858 if (delegate) {
1859 delegate->AddNewContents(
1860 this, contents, disposition, initial_rect, user_gesture, NULL);
1865 void WebContentsImpl::ShowCreatedWidget(int route_id,
1866 const gfx::Rect& initial_rect) {
1867 ShowCreatedWidget(route_id, false, initial_rect);
1870 void WebContentsImpl::ShowCreatedFullscreenWidget(int route_id) {
1871 ShowCreatedWidget(route_id, true, gfx::Rect());
1874 void WebContentsImpl::ShowCreatedWidget(int route_id,
1875 bool is_fullscreen,
1876 const gfx::Rect& initial_rect) {
1877 RenderWidgetHostViewBase* widget_host_view =
1878 static_cast<RenderWidgetHostViewBase*>(GetCreatedWidget(route_id));
1879 if (!widget_host_view)
1880 return;
1882 RenderWidgetHostView* view = NULL;
1883 BrowserPluginGuest* guest = GetBrowserPluginGuest();
1884 if (guest && guest->embedder_web_contents()) {
1885 view = guest->embedder_web_contents()->GetRenderWidgetHostView();
1886 } else {
1887 view = GetRenderWidgetHostView();
1890 if (is_fullscreen) {
1891 DCHECK_EQ(MSG_ROUTING_NONE, fullscreen_widget_routing_id_);
1892 view_->StoreFocus();
1893 fullscreen_widget_routing_id_ = route_id;
1894 if (delegate_ && delegate_->EmbedsFullscreenWidget()) {
1895 widget_host_view->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
1896 delegate_->EnterFullscreenModeForTab(this, GURL());
1897 } else {
1898 widget_host_view->InitAsFullscreen(view);
1900 FOR_EACH_OBSERVER(WebContentsObserver,
1901 observers_,
1902 DidShowFullscreenWidget(route_id));
1903 if (!widget_host_view->HasFocus())
1904 widget_host_view->Focus();
1905 } else {
1906 widget_host_view->InitAsPopup(view, initial_rect);
1909 RenderWidgetHostImpl* render_widget_host_impl =
1910 RenderWidgetHostImpl::From(widget_host_view->GetRenderWidgetHost());
1911 render_widget_host_impl->Init();
1912 // Only allow privileged mouse lock for fullscreen render widget, which is
1913 // used to implement Pepper Flash fullscreen.
1914 render_widget_host_impl->set_allow_privileged_mouse_lock(is_fullscreen);
1916 #if defined(OS_MACOSX)
1917 // A RenderWidgetHostViewMac has lifetime scoped to the view. Now that it's
1918 // properly embedded (or purposefully ignored) we can release the retain we
1919 // took in CreateNewWidget().
1920 base::mac::NSObjectRelease(widget_host_view->GetNativeView());
1921 #endif
1924 WebContentsImpl* WebContentsImpl::GetCreatedWindow(int route_id) {
1925 PendingContents::iterator iter = pending_contents_.find(route_id);
1927 // Certain systems can block the creation of new windows. If we didn't succeed
1928 // in creating one, just return NULL.
1929 if (iter == pending_contents_.end()) {
1930 return NULL;
1933 WebContentsImpl* new_contents = iter->second;
1934 pending_contents_.erase(route_id);
1935 RemoveDestructionObserver(new_contents);
1937 // Don't initialize the guest WebContents immediately.
1938 if (BrowserPluginGuest::IsGuest(new_contents))
1939 return new_contents;
1941 if (!new_contents->GetRenderProcessHost()->HasConnection() ||
1942 !new_contents->GetRenderViewHost()->GetView())
1943 return NULL;
1945 return new_contents;
1948 RenderWidgetHostView* WebContentsImpl::GetCreatedWidget(int route_id) {
1949 PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id);
1950 if (iter == pending_widget_views_.end()) {
1951 DCHECK(false);
1952 return NULL;
1955 RenderWidgetHostView* widget_host_view = iter->second;
1956 pending_widget_views_.erase(route_id);
1958 RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
1959 if (!widget_host->GetProcess()->HasConnection()) {
1960 // The view has gone away or the renderer crashed. Nothing to do.
1961 return NULL;
1964 return widget_host_view;
1967 void WebContentsImpl::RequestMediaAccessPermission(
1968 const MediaStreamRequest& request,
1969 const MediaResponseCallback& callback) {
1970 if (delegate_) {
1971 delegate_->RequestMediaAccessPermission(this, request, callback);
1972 } else {
1973 callback.Run(MediaStreamDevices(),
1974 MEDIA_DEVICE_FAILED_DUE_TO_SHUTDOWN,
1975 scoped_ptr<MediaStreamUI>());
1979 bool WebContentsImpl::CheckMediaAccessPermission(const GURL& security_origin,
1980 MediaStreamType type) {
1981 DCHECK(type == MEDIA_DEVICE_AUDIO_CAPTURE ||
1982 type == MEDIA_DEVICE_VIDEO_CAPTURE);
1983 return delegate_ &&
1984 delegate_->CheckMediaAccessPermission(this, security_origin, type);
1987 SessionStorageNamespace* WebContentsImpl::GetSessionStorageNamespace(
1988 SiteInstance* instance) {
1989 return controller_.GetSessionStorageNamespace(instance);
1992 SessionStorageNamespaceMap WebContentsImpl::GetSessionStorageNamespaceMap() {
1993 return controller_.GetSessionStorageNamespaceMap();
1996 FrameTree* WebContentsImpl::GetFrameTree() {
1997 return &frame_tree_;
2000 void WebContentsImpl::SetIsVirtualKeyboardRequested(bool requested) {
2001 virtual_keyboard_requested_ = requested;
2004 bool WebContentsImpl::IsVirtualKeyboardRequested() {
2005 return virtual_keyboard_requested_;
2008 AccessibilityMode WebContentsImpl::GetAccessibilityMode() const {
2009 return accessibility_mode_;
2012 void WebContentsImpl::AccessibilityEventReceived(
2013 const std::vector<AXEventNotificationDetails>& details) {
2014 FOR_EACH_OBSERVER(
2015 WebContentsObserver, observers_, AccessibilityEventReceived(details));
2018 RenderFrameHost* WebContentsImpl::GetGuestByInstanceID(
2019 RenderFrameHost* render_frame_host,
2020 int browser_plugin_instance_id) {
2021 BrowserPluginGuestManager* guest_manager =
2022 GetBrowserContext()->GetGuestManager();
2023 if (!guest_manager)
2024 return nullptr;
2026 WebContents* guest = guest_manager->GetGuestByInstanceID(
2027 render_frame_host->GetProcess()->GetID(), browser_plugin_instance_id);
2028 if (!guest)
2029 return nullptr;
2031 return guest->GetMainFrame();
2034 GeolocationServiceContext* WebContentsImpl::GetGeolocationServiceContext() {
2035 return geolocation_service_context_.get();
2038 void WebContentsImpl::OnShowValidationMessage(
2039 const gfx::Rect& anchor_in_root_view,
2040 const base::string16& main_text,
2041 const base::string16& sub_text) {
2042 if (delegate_)
2043 delegate_->ShowValidationMessage(
2044 this, anchor_in_root_view, main_text, sub_text);
2047 void WebContentsImpl::OnHideValidationMessage() {
2048 if (delegate_)
2049 delegate_->HideValidationMessage(this);
2052 void WebContentsImpl::OnMoveValidationMessage(
2053 const gfx::Rect& anchor_in_root_view) {
2054 if (delegate_)
2055 delegate_->MoveValidationMessage(this, anchor_in_root_view);
2058 void WebContentsImpl::DidSendScreenRects(RenderWidgetHostImpl* rwh) {
2059 if (browser_plugin_embedder_)
2060 browser_plugin_embedder_->DidSendScreenRects();
2063 BrowserAccessibilityManager*
2064 WebContentsImpl::GetRootBrowserAccessibilityManager() {
2065 RenderFrameHostImpl* rfh = GetMainFrame();
2066 return rfh ? rfh->browser_accessibility_manager() : nullptr;
2069 BrowserAccessibilityManager*
2070 WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
2071 RenderFrameHostImpl* rfh = GetMainFrame();
2072 return rfh ? rfh->GetOrCreateBrowserAccessibilityManager() : nullptr;
2075 void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point& extent) {
2076 RenderFrameHost* focused_frame = GetFocusedFrame();
2077 if (!focused_frame)
2078 return;
2080 focused_frame->Send(new InputMsg_MoveRangeSelectionExtent(
2081 focused_frame->GetRoutingID(), extent));
2084 void WebContentsImpl::SelectRange(const gfx::Point& base,
2085 const gfx::Point& extent) {
2086 RenderFrameHost* focused_frame = GetFocusedFrame();
2087 if (!focused_frame)
2088 return;
2090 focused_frame->Send(
2091 new InputMsg_SelectRange(focused_frame->GetRoutingID(), base, extent));
2094 void WebContentsImpl::AdjustSelectionByCharacterOffset(int start_adjust,
2095 int end_adjust) {
2096 RenderFrameHost* focused_frame = GetFocusedFrame();
2097 if (!focused_frame)
2098 return;
2100 focused_frame->Send(new InputMsg_AdjustSelectionByCharacterOffset(
2101 focused_frame->GetRoutingID(), start_adjust, end_adjust));
2104 void WebContentsImpl::UpdatePreferredSize(const gfx::Size& pref_size) {
2105 const gfx::Size old_size = GetPreferredSize();
2106 preferred_size_ = pref_size;
2107 OnPreferredSizeChanged(old_size);
2110 void WebContentsImpl::ResizeDueToAutoResize(const gfx::Size& new_size) {
2111 if (delegate_)
2112 delegate_->ResizeDueToAutoResize(this, new_size);
2115 WebContents* WebContentsImpl::OpenURL(const OpenURLParams& params) {
2116 if (!delegate_)
2117 return NULL;
2119 WebContents* new_contents = delegate_->OpenURLFromTab(this, params);
2120 return new_contents;
2123 bool WebContentsImpl::Send(IPC::Message* message) {
2124 if (!GetRenderViewHost()) {
2125 delete message;
2126 return false;
2129 return GetRenderViewHost()->Send(message);
2132 void WebContentsImpl::RenderFrameForInterstitialPageCreated(
2133 RenderFrameHost* render_frame_host) {
2134 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2135 RenderFrameForInterstitialPageCreated(render_frame_host));
2138 void WebContentsImpl::AttachInterstitialPage(
2139 InterstitialPageImpl* interstitial_page) {
2140 DCHECK(interstitial_page);
2141 GetRenderManager()->set_interstitial_page(interstitial_page);
2143 // Cancel any visible dialogs so that they don't interfere with the
2144 // interstitial.
2145 CancelActiveAndPendingDialogs();
2147 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2148 DidAttachInterstitialPage());
2151 void WebContentsImpl::DetachInterstitialPage() {
2152 if (ShowingInterstitialPage())
2153 GetRenderManager()->remove_interstitial_page();
2154 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2155 DidDetachInterstitialPage());
2158 void WebContentsImpl::SetHistoryOffsetAndLength(int history_offset,
2159 int history_length) {
2160 SetHistoryOffsetAndLengthForView(
2161 GetRenderViewHost(), history_offset, history_length);
2164 void WebContentsImpl::SetHistoryOffsetAndLengthForView(
2165 RenderViewHost* render_view_host,
2166 int history_offset,
2167 int history_length) {
2168 render_view_host->Send(new ViewMsg_SetHistoryOffsetAndLength(
2169 render_view_host->GetRoutingID(), history_offset, history_length));
2172 void WebContentsImpl::ReloadFocusedFrame(bool ignore_cache) {
2173 RenderFrameHost* focused_frame = GetFocusedFrame();
2174 if (!focused_frame)
2175 return;
2177 focused_frame->Send(new FrameMsg_Reload(
2178 focused_frame->GetRoutingID(), ignore_cache));
2181 void WebContentsImpl::Undo() {
2182 RenderFrameHost* focused_frame = GetFocusedFrame();
2183 if (!focused_frame)
2184 return;
2186 focused_frame->Send(new InputMsg_Undo(focused_frame->GetRoutingID()));
2187 RecordAction(base::UserMetricsAction("Undo"));
2190 void WebContentsImpl::Redo() {
2191 RenderFrameHost* focused_frame = GetFocusedFrame();
2192 if (!focused_frame)
2193 return;
2194 focused_frame->Send(new InputMsg_Redo(focused_frame->GetRoutingID()));
2195 RecordAction(base::UserMetricsAction("Redo"));
2198 void WebContentsImpl::Cut() {
2199 RenderFrameHost* focused_frame = GetFocusedFrame();
2200 if (!focused_frame)
2201 return;
2203 focused_frame->Send(new InputMsg_Cut(focused_frame->GetRoutingID()));
2204 RecordAction(base::UserMetricsAction("Cut"));
2207 void WebContentsImpl::Copy() {
2208 RenderFrameHost* focused_frame = GetFocusedFrame();
2209 if (!focused_frame)
2210 return;
2212 focused_frame->Send(new InputMsg_Copy(focused_frame->GetRoutingID()));
2213 RecordAction(base::UserMetricsAction("Copy"));
2216 void WebContentsImpl::CopyToFindPboard() {
2217 #if defined(OS_MACOSX)
2218 RenderFrameHost* focused_frame = GetFocusedFrame();
2219 if (!focused_frame)
2220 return;
2222 // Windows/Linux don't have the concept of a find pasteboard.
2223 focused_frame->Send(
2224 new InputMsg_CopyToFindPboard(focused_frame->GetRoutingID()));
2225 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
2226 #endif
2229 void WebContentsImpl::Paste() {
2230 RenderFrameHost* focused_frame = GetFocusedFrame();
2231 if (!focused_frame)
2232 return;
2234 focused_frame->Send(new InputMsg_Paste(focused_frame->GetRoutingID()));
2235 RecordAction(base::UserMetricsAction("Paste"));
2238 void WebContentsImpl::PasteAndMatchStyle() {
2239 RenderFrameHost* focused_frame = GetFocusedFrame();
2240 if (!focused_frame)
2241 return;
2243 focused_frame->Send(new InputMsg_PasteAndMatchStyle(
2244 focused_frame->GetRoutingID()));
2245 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
2248 void WebContentsImpl::Delete() {
2249 RenderFrameHost* focused_frame = GetFocusedFrame();
2250 if (!focused_frame)
2251 return;
2253 focused_frame->Send(new InputMsg_Delete(focused_frame->GetRoutingID()));
2254 RecordAction(base::UserMetricsAction("DeleteSelection"));
2257 void WebContentsImpl::SelectAll() {
2258 RenderFrameHost* focused_frame = GetFocusedFrame();
2259 if (!focused_frame)
2260 return;
2262 focused_frame->Send(new InputMsg_SelectAll(focused_frame->GetRoutingID()));
2263 RecordAction(base::UserMetricsAction("SelectAll"));
2266 void WebContentsImpl::Unselect() {
2267 RenderFrameHost* focused_frame = GetFocusedFrame();
2268 if (!focused_frame)
2269 return;
2271 focused_frame->Send(new InputMsg_Unselect(focused_frame->GetRoutingID()));
2272 RecordAction(base::UserMetricsAction("Unselect"));
2275 void WebContentsImpl::Replace(const base::string16& word) {
2276 RenderFrameHost* focused_frame = GetFocusedFrame();
2277 if (!focused_frame)
2278 return;
2280 focused_frame->Send(new InputMsg_Replace(
2281 focused_frame->GetRoutingID(), word));
2284 void WebContentsImpl::ReplaceMisspelling(const base::string16& word) {
2285 RenderFrameHost* focused_frame = GetFocusedFrame();
2286 if (!focused_frame)
2287 return;
2289 focused_frame->Send(new InputMsg_ReplaceMisspelling(
2290 focused_frame->GetRoutingID(), word));
2293 void WebContentsImpl::NotifyContextMenuClosed(
2294 const CustomContextMenuContext& context) {
2295 RenderFrameHost* focused_frame = GetFocusedFrame();
2296 if (!focused_frame)
2297 return;
2299 focused_frame->Send(new FrameMsg_ContextMenuClosed(
2300 focused_frame->GetRoutingID(), context));
2303 void WebContentsImpl::ExecuteCustomContextMenuCommand(
2304 int action, const CustomContextMenuContext& context) {
2305 RenderFrameHost* focused_frame = GetFocusedFrame();
2306 if (!focused_frame)
2307 return;
2309 focused_frame->Send(new FrameMsg_CustomContextMenuAction(
2310 focused_frame->GetRoutingID(), context, action));
2313 gfx::NativeView WebContentsImpl::GetNativeView() {
2314 return view_->GetNativeView();
2317 gfx::NativeView WebContentsImpl::GetContentNativeView() {
2318 return view_->GetContentNativeView();
2321 gfx::NativeWindow WebContentsImpl::GetTopLevelNativeWindow() {
2322 return view_->GetTopLevelNativeWindow();
2325 gfx::Rect WebContentsImpl::GetViewBounds() {
2326 return view_->GetViewBounds();
2329 gfx::Rect WebContentsImpl::GetContainerBounds() {
2330 gfx::Rect rv;
2331 view_->GetContainerBounds(&rv);
2332 return rv;
2335 DropData* WebContentsImpl::GetDropData() {
2336 return view_->GetDropData();
2339 void WebContentsImpl::Focus() {
2340 view_->Focus();
2343 void WebContentsImpl::SetInitialFocus() {
2344 view_->SetInitialFocus();
2347 void WebContentsImpl::StoreFocus() {
2348 view_->StoreFocus();
2351 void WebContentsImpl::RestoreFocus() {
2352 view_->RestoreFocus();
2355 void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
2356 if (ShowingInterstitialPage()) {
2357 GetRenderManager()->interstitial_page()->FocusThroughTabTraversal(reverse);
2358 return;
2360 RenderWidgetHostView* const fullscreen_view =
2361 GetFullscreenRenderWidgetHostView();
2362 if (fullscreen_view) {
2363 fullscreen_view->Focus();
2364 return;
2366 GetRenderViewHost()->SetInitialFocus(reverse);
2369 bool WebContentsImpl::ShowingInterstitialPage() const {
2370 return GetRenderManager()->interstitial_page() != NULL;
2373 InterstitialPage* WebContentsImpl::GetInterstitialPage() const {
2374 return GetRenderManager()->interstitial_page();
2377 bool WebContentsImpl::IsSavable() {
2378 // WebKit creates Document object when MIME type is application/xhtml+xml,
2379 // so we also support this MIME type.
2380 return contents_mime_type_ == "text/html" ||
2381 contents_mime_type_ == "text/xml" ||
2382 contents_mime_type_ == "application/xhtml+xml" ||
2383 contents_mime_type_ == "text/plain" ||
2384 contents_mime_type_ == "text/css" ||
2385 mime_util::IsSupportedJavascriptMimeType(contents_mime_type_);
2388 void WebContentsImpl::OnSavePage() {
2389 // If we can not save the page, try to download it.
2390 if (!IsSavable()) {
2391 RecordDownloadSource(INITIATED_BY_SAVE_PACKAGE_ON_NON_HTML);
2392 SaveFrame(GetLastCommittedURL(), Referrer());
2393 return;
2396 Stop();
2398 // Create the save package and possibly prompt the user for the name to save
2399 // the page as. The user prompt is an asynchronous operation that runs on
2400 // another thread.
2401 save_package_ = new SavePackage(this);
2402 save_package_->GetSaveInfo();
2405 // Used in automated testing to bypass prompting the user for file names.
2406 // Instead, the names and paths are hard coded rather than running them through
2407 // file name sanitation and extension / mime checking.
2408 bool WebContentsImpl::SavePage(const base::FilePath& main_file,
2409 const base::FilePath& dir_path,
2410 SavePageType save_type) {
2411 // Stop the page from navigating.
2412 Stop();
2414 save_package_ = new SavePackage(this, save_type, main_file, dir_path);
2415 return save_package_->Init(SavePackageDownloadCreatedCallback());
2418 void WebContentsImpl::SaveFrame(const GURL& url,
2419 const Referrer& referrer) {
2420 SaveFrameWithHeaders(url, referrer, std::string());
2423 void WebContentsImpl::SaveFrameWithHeaders(const GURL& url,
2424 const Referrer& referrer,
2425 const std::string& headers) {
2426 if (!GetLastCommittedURL().is_valid())
2427 return;
2428 if (delegate_ && delegate_->SaveFrame(url, referrer))
2429 return;
2431 // TODO(nasko): This check for main frame is incorrect and should be fixed
2432 // by explicitly passing in which frame this method should target.
2433 bool is_main_frame = (url == GetLastCommittedURL());
2435 DownloadManager* dlm =
2436 BrowserContext::GetDownloadManager(GetBrowserContext());
2437 if (!dlm)
2438 return;
2439 int64 post_id = -1;
2440 if (is_main_frame) {
2441 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2442 if (entry)
2443 post_id = entry->GetPostID();
2445 scoped_ptr<DownloadUrlParameters> params(
2446 DownloadUrlParameters::FromWebContents(this, url));
2447 params->set_referrer(referrer);
2448 params->set_post_id(post_id);
2449 if (post_id >= 0)
2450 params->set_method("POST");
2451 params->set_prompt(true);
2453 if (headers.empty()) {
2454 params->set_prefer_cache(true);
2455 } else {
2456 std::vector<std::string> key_value_list;
2457 base::SplitString(headers, '\n', &key_value_list);
2458 for (const auto& key_value : key_value_list) {
2459 std::vector<std::string> pair;
2460 base::SplitString(key_value, ':', &pair);
2461 DCHECK_EQ(2ul, pair.size());
2462 params->add_request_header(pair[0], pair[1]);
2465 dlm->DownloadUrl(params.Pass());
2468 void WebContentsImpl::GenerateMHTML(
2469 const base::FilePath& file,
2470 const base::Callback<void(int64)>& callback) {
2471 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, file, callback);
2474 const std::string& WebContentsImpl::GetContentsMimeType() const {
2475 return contents_mime_type_;
2478 bool WebContentsImpl::WillNotifyDisconnection() const {
2479 return notify_disconnection_;
2482 void WebContentsImpl::SetOverrideEncoding(const std::string& encoding) {
2483 SetEncoding(encoding);
2484 Send(new ViewMsg_SetPageEncoding(GetRoutingID(), encoding));
2487 void WebContentsImpl::ResetOverrideEncoding() {
2488 canonical_encoding_.clear();
2489 Send(new ViewMsg_ResetPageEncodingToDefault(GetRoutingID()));
2492 RendererPreferences* WebContentsImpl::GetMutableRendererPrefs() {
2493 return &renderer_preferences_;
2496 void WebContentsImpl::Close() {
2497 Close(GetRenderViewHost());
2500 void WebContentsImpl::DragSourceEndedAt(int client_x, int client_y,
2501 int screen_x, int screen_y, blink::WebDragOperation operation) {
2502 if (browser_plugin_embedder_.get())
2503 browser_plugin_embedder_->DragSourceEndedAt(client_x, client_y,
2504 screen_x, screen_y, operation);
2505 if (GetRenderViewHost())
2506 GetRenderViewHost()->DragSourceEndedAt(client_x, client_y, screen_x,
2507 screen_y, operation);
2510 void WebContentsImpl::DidGetResourceResponseStart(
2511 const ResourceRequestDetails& details) {
2512 controller_.ssl_manager()->DidStartResourceResponse(details);
2514 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2515 DidGetResourceResponseStart(details));
2518 void WebContentsImpl::DidGetRedirectForResourceRequest(
2519 RenderFrameHost* render_frame_host,
2520 const ResourceRedirectDetails& details) {
2521 controller_.ssl_manager()->DidReceiveResourceRedirect(details);
2523 FOR_EACH_OBSERVER(
2524 WebContentsObserver,
2525 observers_,
2526 DidGetRedirectForResourceRequest(render_frame_host, details));
2528 // TODO(avi): Remove. http://crbug.com/170921
2529 NotificationService::current()->Notify(
2530 NOTIFICATION_RESOURCE_RECEIVED_REDIRECT,
2531 Source<WebContents>(this),
2532 Details<const ResourceRedirectDetails>(&details));
2535 void WebContentsImpl::NotifyWebContentsFocused() {
2536 FOR_EACH_OBSERVER(WebContentsObserver, observers_, OnWebContentsFocused());
2539 void WebContentsImpl::SystemDragEnded() {
2540 if (GetRenderViewHost())
2541 GetRenderViewHost()->DragSourceSystemDragEnded();
2542 if (browser_plugin_embedder_.get())
2543 browser_plugin_embedder_->SystemDragEnded();
2546 void WebContentsImpl::UserGestureDone() {
2547 OnUserGesture();
2550 void WebContentsImpl::SetClosedByUserGesture(bool value) {
2551 closed_by_user_gesture_ = value;
2554 bool WebContentsImpl::GetClosedByUserGesture() const {
2555 return closed_by_user_gesture_;
2558 void WebContentsImpl::ViewSource() {
2559 if (!delegate_)
2560 return;
2562 NavigationEntry* entry = GetController().GetLastCommittedEntry();
2563 if (!entry)
2564 return;
2566 delegate_->ViewSourceForTab(this, entry->GetURL());
2569 void WebContentsImpl::ViewFrameSource(const GURL& url,
2570 const PageState& page_state) {
2571 if (!delegate_)
2572 return;
2574 delegate_->ViewSourceForFrame(this, url, page_state);
2577 int WebContentsImpl::GetMinimumZoomPercent() const {
2578 return minimum_zoom_percent_;
2581 int WebContentsImpl::GetMaximumZoomPercent() const {
2582 return maximum_zoom_percent_;
2585 void WebContentsImpl::ResetPageScale() {
2586 Send(new ViewMsg_ResetPageScale(GetRoutingID()));
2589 gfx::Size WebContentsImpl::GetPreferredSize() const {
2590 return capturer_count_ == 0 ? preferred_size_ : preferred_size_for_capture_;
2593 bool WebContentsImpl::GotResponseToLockMouseRequest(bool allowed) {
2594 if (GetBrowserPluginGuest())
2595 return GetBrowserPluginGuest()->LockMouse(allowed);
2597 return GetRenderViewHost()
2598 ? GetRenderViewHost()->GotResponseToLockMouseRequest(allowed)
2599 : false;
2602 bool WebContentsImpl::HasOpener() const {
2603 return GetOpener() != NULL;
2606 WebContentsImpl* WebContentsImpl::GetOpener() const {
2607 FrameTreeNode* opener_ftn = frame_tree_.root()->opener();
2608 return opener_ftn ? FromFrameTreeNode(opener_ftn) : nullptr;
2611 void WebContentsImpl::DidChooseColorInColorChooser(SkColor color) {
2612 if (!color_chooser_info_.get())
2613 return;
2614 RenderFrameHost* rfh = RenderFrameHost::FromID(
2615 color_chooser_info_->render_process_id,
2616 color_chooser_info_->render_frame_id);
2617 if (!rfh)
2618 return;
2620 rfh->Send(new FrameMsg_DidChooseColorResponse(
2621 rfh->GetRoutingID(), color_chooser_info_->identifier, color));
2624 void WebContentsImpl::DidEndColorChooser() {
2625 if (!color_chooser_info_.get())
2626 return;
2627 RenderFrameHost* rfh = RenderFrameHost::FromID(
2628 color_chooser_info_->render_process_id,
2629 color_chooser_info_->render_frame_id);
2630 if (!rfh)
2631 return;
2633 rfh->Send(new FrameMsg_DidEndColorChooser(
2634 rfh->GetRoutingID(), color_chooser_info_->identifier));
2635 color_chooser_info_.reset();
2638 int WebContentsImpl::DownloadImage(
2639 const GURL& url,
2640 bool is_favicon,
2641 uint32_t max_bitmap_size,
2642 bool bypass_cache,
2643 const WebContents::ImageDownloadCallback& callback) {
2644 static int next_image_download_id = 0;
2645 const image_downloader::ImageDownloaderPtr& mojo_image_downloader =
2646 GetMainFrame()->GetMojoImageDownloader();
2647 image_downloader::DownloadRequestPtr req =
2648 image_downloader::DownloadRequest::New();
2650 req->url = mojo::String::From(url);
2651 req->is_favicon = is_favicon;
2652 req->max_bitmap_size = max_bitmap_size;
2653 req->bypass_cache = bypass_cache;
2655 mojo_image_downloader->DownloadImage(
2656 req.Pass(),
2657 base::Bind(&DidDownloadImage, callback, ++next_image_download_id, url));
2658 return next_image_download_id;
2661 bool WebContentsImpl::IsSubframe() const {
2662 return is_subframe_;
2665 void WebContentsImpl::Find(int request_id,
2666 const base::string16& search_text,
2667 const blink::WebFindOptions& options) {
2668 // See if a top level browser plugin handles the find request first.
2669 if (browser_plugin_embedder_) {
2670 BrowserPluginGuest* guest = browser_plugin_embedder_->GetFullPageGuest();
2671 if (guest && guest->Find(request_id, search_text, options))
2672 return;
2674 Send(new ViewMsg_Find(GetRoutingID(), request_id, search_text, options));
2677 void WebContentsImpl::StopFinding(StopFindAction action) {
2678 // See if a top level browser plugin handles the stop finding request first.
2679 if (browser_plugin_embedder_) {
2680 BrowserPluginGuest* guest = browser_plugin_embedder_->GetFullPageGuest();
2681 if (guest && guest->StopFinding(action))
2682 return;
2684 Send(new ViewMsg_StopFinding(GetRoutingID(), action));
2687 void WebContentsImpl::InsertCSS(const std::string& css) {
2688 GetMainFrame()->Send(new FrameMsg_CSSInsertRequest(
2689 GetMainFrame()->GetRoutingID(), css));
2692 bool WebContentsImpl::WasRecentlyAudible() {
2693 return audio_state_provider_->WasRecentlyAudible();
2696 void WebContentsImpl::GetManifest(const GetManifestCallback& callback) {
2697 manifest_manager_host_->GetManifest(GetMainFrame(), callback);
2700 void WebContentsImpl::ExitFullscreen() {
2701 // Clean up related state and initiate the fullscreen exit.
2702 GetRenderViewHost()->RejectMouseLockOrUnlockIfNecessary();
2703 ExitFullscreenMode();
2706 void WebContentsImpl::ResumeLoadingCreatedWebContents() {
2707 if (delayed_open_url_params_.get()) {
2708 OpenURL(*delayed_open_url_params_.get());
2709 delayed_open_url_params_.reset(nullptr);
2710 return;
2713 // Resume blocked requests for both the RenderViewHost and RenderFrameHost.
2714 // TODO(brettw): It seems bogus to reach into here and initialize the host.
2715 if (is_resume_pending_) {
2716 is_resume_pending_ = false;
2717 GetRenderViewHost()->Init();
2718 GetMainFrame()->Init();
2722 bool WebContentsImpl::FocusLocationBarByDefault() {
2723 NavigationEntry* entry = controller_.GetVisibleEntry();
2724 if (entry && entry->GetURL() == GURL(url::kAboutBlankURL))
2725 return true;
2726 return delegate_ && delegate_->ShouldFocusLocationBarByDefault(this);
2729 void WebContentsImpl::SetFocusToLocationBar(bool select_all) {
2730 if (delegate_)
2731 delegate_->SetFocusToLocationBar(select_all);
2734 void WebContentsImpl::DidStartProvisionalLoad(
2735 RenderFrameHostImpl* render_frame_host,
2736 const GURL& validated_url,
2737 bool is_error_page,
2738 bool is_iframe_srcdoc) {
2739 // Notify observers about the start of the provisional load.
2740 FOR_EACH_OBSERVER(
2741 WebContentsObserver,
2742 observers_,
2743 DidStartProvisionalLoadForFrame(
2744 render_frame_host, validated_url, is_error_page, is_iframe_srcdoc));
2746 // Notify accessibility if this is a reload.
2747 NavigationEntry* entry = controller_.GetVisibleEntry();
2748 if (entry && ui::PageTransitionCoreTypeIs(
2749 entry->GetTransitionType(), ui::PAGE_TRANSITION_RELOAD)) {
2750 FrameTreeNode* ftn = render_frame_host->frame_tree_node();
2751 BrowserAccessibilityManager* manager =
2752 ftn->current_frame_host()->browser_accessibility_manager();
2753 if (manager)
2754 manager->UserIsReloading();
2758 void WebContentsImpl::DidFailProvisionalLoadWithError(
2759 RenderFrameHostImpl* render_frame_host,
2760 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
2761 GURL validated_url(params.url);
2762 FOR_EACH_OBSERVER(WebContentsObserver,
2763 observers_,
2764 DidFailProvisionalLoad(render_frame_host,
2765 validated_url,
2766 params.error_code,
2767 params.error_description,
2768 params.was_ignored_by_handler));
2770 FrameTreeNode* ftn = render_frame_host->frame_tree_node();
2771 BrowserAccessibilityManager* manager =
2772 ftn->current_frame_host()->browser_accessibility_manager();
2773 if (manager)
2774 manager->NavigationFailed();
2777 void WebContentsImpl::DidFailLoadWithError(
2778 RenderFrameHostImpl* render_frame_host,
2779 const GURL& url,
2780 int error_code,
2781 const base::string16& error_description,
2782 bool was_ignored_by_handler) {
2783 FOR_EACH_OBSERVER(
2784 WebContentsObserver,
2785 observers_,
2786 DidFailLoad(render_frame_host, url, error_code, error_description,
2787 was_ignored_by_handler));
2790 void WebContentsImpl::NotifyChangedNavigationState(
2791 InvalidateTypes changed_flags) {
2792 NotifyNavigationStateChanged(changed_flags);
2795 void WebContentsImpl::AboutToNavigateRenderFrame(
2796 RenderFrameHostImpl* old_host,
2797 RenderFrameHostImpl* new_host) {
2798 // Notify observers that we will navigate in this RenderFrame.
2799 FOR_EACH_OBSERVER(
2800 WebContentsObserver,
2801 observers_,
2802 AboutToNavigateRenderFrame(old_host, new_host));
2805 void WebContentsImpl::DidStartNavigationToPendingEntry(
2806 const GURL& url,
2807 NavigationController::ReloadType reload_type) {
2808 // Notify observers about navigation.
2809 FOR_EACH_OBSERVER(
2810 WebContentsObserver,
2811 observers_,
2812 DidStartNavigationToPendingEntry(url, reload_type));
2815 void WebContentsImpl::RequestOpenURL(RenderFrameHostImpl* render_frame_host,
2816 const OpenURLParams& params) {
2817 // OpenURL can blow away the source RFH. Use the process/frame routing ID as a
2818 // weak pointer of sorts.
2819 const int32_t process_id = render_frame_host->GetProcess()->GetID();
2820 const int32_t frame_id = render_frame_host->GetRoutingID();
2822 WebContents* new_contents = OpenURL(params);
2824 if (new_contents && RenderFrameHost::FromID(process_id, frame_id)) {
2825 // Notify observers.
2826 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2827 DidOpenRequestedURL(new_contents,
2828 render_frame_host,
2829 params.url,
2830 params.referrer,
2831 params.disposition,
2832 params.transition));
2836 bool WebContentsImpl::ShouldPreserveAbortedURLs() {
2837 if (!delegate_)
2838 return false;
2839 return delegate_->ShouldPreserveAbortedURLs(this);
2842 void WebContentsImpl::DidCommitProvisionalLoad(
2843 RenderFrameHostImpl* render_frame_host,
2844 const GURL& url,
2845 ui::PageTransition transition_type) {
2846 // Notify observers about the commit of the provisional load.
2847 FOR_EACH_OBSERVER(WebContentsObserver,
2848 observers_,
2849 DidCommitProvisionalLoadForFrame(
2850 render_frame_host, url, transition_type));
2852 BrowserAccessibilityManager* manager =
2853 render_frame_host->browser_accessibility_manager();
2854 if (manager)
2855 manager->NavigationSucceeded();
2858 void WebContentsImpl::DidNavigateMainFramePreCommit(
2859 bool navigation_is_within_page) {
2860 // Ensure fullscreen mode is exited before committing the navigation to a
2861 // different page. The next page will not start out assuming it is in
2862 // fullscreen mode.
2863 if (navigation_is_within_page) {
2864 // No page change? Then, the renderer and browser can remain in fullscreen.
2865 return;
2867 if (IsFullscreenForCurrentTab())
2868 ExitFullscreen();
2869 DCHECK(!IsFullscreenForCurrentTab());
2872 void WebContentsImpl::DidNavigateMainFramePostCommit(
2873 RenderFrameHostImpl* render_frame_host,
2874 const LoadCommittedDetails& details,
2875 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
2876 if (details.is_navigation_to_different_page()) {
2877 // Clear the status bubble. This is a workaround for a bug where WebKit
2878 // doesn't let us know that the cursor left an element during a
2879 // transition (this is also why the mouse cursor remains as a hand after
2880 // clicking on a link); see bugs 1184641 and 980803. We don't want to
2881 // clear the bubble when a user navigates to a named anchor in the same
2882 // page.
2883 UpdateTargetURL(render_frame_host->GetRenderViewHost(), GURL());
2885 RenderWidgetHostViewBase* rwhvb =
2886 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
2887 if (rwhvb)
2888 rwhvb->OnDidNavigateMainFrameToNewPage();
2890 did_first_visually_non_empty_paint_ = false;
2892 // Reset theme color on navigation to new page.
2893 theme_color_ = SK_ColorTRANSPARENT;
2896 if (!details.is_in_page) {
2897 // Once the main frame is navigated, we're no longer considered to have
2898 // displayed insecure content.
2899 displayed_insecure_content_ = false;
2900 SSLManager::NotifySSLInternalStateChanged(
2901 GetController().GetBrowserContext());
2904 // Notify observers about navigation.
2905 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2906 DidNavigateMainFrame(details, params));
2908 if (delegate_)
2909 delegate_->DidNavigateMainFramePostCommit(this);
2910 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
2913 void WebContentsImpl::DidNavigateAnyFramePostCommit(
2914 RenderFrameHostImpl* render_frame_host,
2915 const LoadCommittedDetails& details,
2916 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
2917 // Now that something has committed, we don't need to track whether the
2918 // initial page has been accessed.
2919 has_accessed_initial_document_ = false;
2921 // If we navigate off the page, close all JavaScript dialogs.
2922 if (!details.is_in_page)
2923 CancelActiveAndPendingDialogs();
2925 // Notify observers about navigation.
2926 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2927 DidNavigateAnyFrame(render_frame_host, details, params));
2930 void WebContentsImpl::SetMainFrameMimeType(const std::string& mime_type) {
2931 contents_mime_type_ = mime_type;
2934 bool WebContentsImpl::CanOverscrollContent() const {
2935 // Disable overscroll when touch emulation is on. See crbug.com/369938.
2936 if (force_disable_overscroll_content_)
2937 return false;
2939 if (delegate_)
2940 return delegate_->CanOverscrollContent();
2942 return false;
2945 void WebContentsImpl::OnThemeColorChanged(SkColor theme_color) {
2946 // Update the theme color. This is to be published to observers after the
2947 // first visually non-empty paint.
2948 theme_color_ = theme_color;
2950 if (did_first_visually_non_empty_paint_ &&
2951 last_sent_theme_color_ != theme_color_) {
2952 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2953 DidChangeThemeColor(theme_color_));
2954 last_sent_theme_color_ = theme_color_;
2958 void WebContentsImpl::OnDidLoadResourceFromMemoryCache(
2959 const GURL& url,
2960 const std::string& security_info,
2961 const std::string& http_method,
2962 const std::string& mime_type,
2963 ResourceType resource_type) {
2964 SSLStatus status;
2965 if (!DeserializeSecurityInfo(security_info, &status)) {
2966 bad_message::ReceivedBadMessage(
2967 GetRenderProcessHost(),
2968 bad_message::WC_MEMORY_CACHE_RESOURCE_BAD_SECURITY_INFO);
2969 return;
2972 // Send out a notification that we loaded a resource from our memory cache.
2973 // TODO(alcutter,eranm): Pass signed_certificate_timestamp_ids into details.
2974 LoadFromMemoryCacheDetails details(
2975 url, GetRenderProcessHost()->GetID(), status.cert_id, status.cert_status,
2976 http_method, mime_type, resource_type);
2978 controller_.ssl_manager()->DidLoadFromMemoryCache(details);
2980 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2981 DidLoadResourceFromMemoryCache(details));
2983 if (url.is_valid() && url.SchemeIsHTTPOrHTTPS()) {
2984 scoped_refptr<net::URLRequestContextGetter> request_context(
2985 resource_type == RESOURCE_TYPE_MEDIA ?
2986 GetBrowserContext()->GetMediaRequestContextForRenderProcess(
2987 GetRenderProcessHost()->GetID()) :
2988 GetBrowserContext()->GetRequestContextForRenderProcess(
2989 GetRenderProcessHost()->GetID()));
2990 BrowserThread::PostTask(
2991 BrowserThread::IO,
2992 FROM_HERE,
2993 base::Bind(&NotifyCacheOnIO, request_context, url, http_method));
2997 void WebContentsImpl::OnDidDisplayInsecureContent() {
2998 RecordAction(base::UserMetricsAction("SSL.DisplayedInsecureContent"));
2999 displayed_insecure_content_ = true;
3000 SSLManager::NotifySSLInternalStateChanged(
3001 GetController().GetBrowserContext());
3004 void WebContentsImpl::OnDidRunInsecureContent(
3005 const std::string& security_origin, const GURL& target_url) {
3006 LOG(WARNING) << security_origin << " ran insecure content from "
3007 << target_url.possibly_invalid_spec();
3008 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
3009 if (base::EndsWith(security_origin, kDotGoogleDotCom,
3010 base::CompareCase::INSENSITIVE_ASCII))
3011 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
3012 controller_.ssl_manager()->DidRunInsecureContent(security_origin);
3013 displayed_insecure_content_ = true;
3014 SSLManager::NotifySSLInternalStateChanged(
3015 GetController().GetBrowserContext());
3018 void WebContentsImpl::OnDocumentLoadedInFrame() {
3019 if (!HasValidFrameSource())
3020 return;
3022 RenderFrameHostImpl* rfh =
3023 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
3024 FOR_EACH_OBSERVER(
3025 WebContentsObserver, observers_, DocumentLoadedInFrame(rfh));
3028 void WebContentsImpl::OnDidFinishLoad(const GURL& url) {
3029 if (!HasValidFrameSource())
3030 return;
3032 GURL validated_url(url);
3033 RenderProcessHost* render_process_host =
3034 render_frame_message_source_->GetProcess();
3035 render_process_host->FilterURL(false, &validated_url);
3037 RenderFrameHostImpl* rfh =
3038 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
3039 FOR_EACH_OBSERVER(
3040 WebContentsObserver, observers_, DidFinishLoad(rfh, validated_url));
3043 void WebContentsImpl::OnGoToEntryAtOffset(int offset) {
3044 if (!delegate_ || delegate_->OnGoToEntryOffset(offset))
3045 controller_.GoToOffset(offset);
3048 void WebContentsImpl::OnUpdateZoomLimits(int minimum_percent,
3049 int maximum_percent) {
3050 minimum_zoom_percent_ = minimum_percent;
3051 maximum_zoom_percent_ = maximum_percent;
3054 void WebContentsImpl::OnEnumerateDirectory(int request_id,
3055 const base::FilePath& path) {
3056 if (!delegate_)
3057 return;
3059 ChildProcessSecurityPolicyImpl* policy =
3060 ChildProcessSecurityPolicyImpl::GetInstance();
3061 if (policy->CanReadFile(GetRenderProcessHost()->GetID(), path))
3062 delegate_->EnumerateDirectory(this, request_id, path);
3065 void WebContentsImpl::OnRegisterProtocolHandler(const std::string& protocol,
3066 const GURL& url,
3067 const base::string16& title,
3068 bool user_gesture) {
3069 if (!delegate_)
3070 return;
3072 ChildProcessSecurityPolicyImpl* policy =
3073 ChildProcessSecurityPolicyImpl::GetInstance();
3074 if (policy->IsPseudoScheme(protocol))
3075 return;
3077 delegate_->RegisterProtocolHandler(this, protocol, url, user_gesture);
3080 void WebContentsImpl::OnUnregisterProtocolHandler(const std::string& protocol,
3081 const GURL& url,
3082 bool user_gesture) {
3083 if (!delegate_)
3084 return;
3086 ChildProcessSecurityPolicyImpl* policy =
3087 ChildProcessSecurityPolicyImpl::GetInstance();
3088 if (policy->IsPseudoScheme(protocol))
3089 return;
3091 delegate_->UnregisterProtocolHandler(this, protocol, url, user_gesture);
3094 void WebContentsImpl::OnFindReply(int request_id,
3095 int number_of_matches,
3096 const gfx::Rect& selection_rect,
3097 int active_match_ordinal,
3098 bool final_update) {
3099 if (delegate_) {
3100 delegate_->FindReply(this, request_id, number_of_matches, selection_rect,
3101 active_match_ordinal, final_update);
3105 #if defined(OS_ANDROID)
3106 void WebContentsImpl::OnFindMatchRectsReply(
3107 int version,
3108 const std::vector<gfx::RectF>& rects,
3109 const gfx::RectF& active_rect) {
3110 if (delegate_)
3111 delegate_->FindMatchRectsReply(this, version, rects, active_rect);
3114 void WebContentsImpl::OnOpenDateTimeDialog(
3115 const ViewHostMsg_DateTimeDialogValue_Params& value) {
3116 date_time_chooser_->ShowDialog(GetTopLevelNativeWindow(),
3117 GetRenderViewHost(),
3118 value.dialog_type,
3119 value.dialog_value,
3120 value.minimum,
3121 value.maximum,
3122 value.step,
3123 value.suggestions);
3125 #endif
3127 void WebContentsImpl::OnDomOperationResponse(const std::string& json_string,
3128 int automation_id) {
3129 DomOperationNotificationDetails details(json_string, automation_id);
3130 NotificationService::current()->Notify(
3131 NOTIFICATION_DOM_OPERATION_RESPONSE,
3132 Source<WebContents>(this),
3133 Details<DomOperationNotificationDetails>(&details));
3136 void WebContentsImpl::OnAppCacheAccessed(const GURL& manifest_url,
3137 bool blocked_by_policy) {
3138 // Notify observers about navigation.
3139 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3140 AppCacheAccessed(manifest_url, blocked_by_policy));
3143 void WebContentsImpl::OnOpenColorChooser(
3144 int color_chooser_id,
3145 SkColor color,
3146 const std::vector<ColorSuggestion>& suggestions) {
3147 if (!HasValidFrameSource())
3148 return;
3150 ColorChooser* new_color_chooser = delegate_ ?
3151 delegate_->OpenColorChooser(this, color, suggestions) :
3152 NULL;
3153 if (!new_color_chooser)
3154 return;
3155 if (color_chooser_info_.get())
3156 color_chooser_info_->chooser->End();
3158 color_chooser_info_.reset(new ColorChooserInfo(
3159 render_frame_message_source_->GetProcess()->GetID(),
3160 render_frame_message_source_->GetRoutingID(),
3161 new_color_chooser,
3162 color_chooser_id));
3165 void WebContentsImpl::OnEndColorChooser(int color_chooser_id) {
3166 if (color_chooser_info_ &&
3167 color_chooser_id == color_chooser_info_->identifier)
3168 color_chooser_info_->chooser->End();
3171 void WebContentsImpl::OnSetSelectedColorInColorChooser(int color_chooser_id,
3172 SkColor color) {
3173 if (color_chooser_info_ &&
3174 color_chooser_id == color_chooser_info_->identifier)
3175 color_chooser_info_->chooser->SetSelectedColor(color);
3178 // This exists for render views that don't have a WebUI, but do have WebUI
3179 // bindings enabled.
3180 void WebContentsImpl::OnWebUISend(const GURL& source_url,
3181 const std::string& name,
3182 const base::ListValue& args) {
3183 if (delegate_)
3184 delegate_->WebUISend(this, source_url, name, args);
3187 #if defined(ENABLE_PLUGINS)
3188 void WebContentsImpl::OnPepperInstanceCreated() {
3189 FOR_EACH_OBSERVER(WebContentsObserver, observers_, PepperInstanceCreated());
3192 void WebContentsImpl::OnPepperInstanceDeleted() {
3193 FOR_EACH_OBSERVER(WebContentsObserver, observers_, PepperInstanceDeleted());
3196 void WebContentsImpl::OnPepperPluginHung(int plugin_child_id,
3197 const base::FilePath& path,
3198 bool is_hung) {
3199 UMA_HISTOGRAM_COUNTS("Pepper.PluginHung", 1);
3201 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3202 PluginHungStatusChanged(plugin_child_id, path, is_hung));
3205 void WebContentsImpl::OnPluginCrashed(const base::FilePath& plugin_path,
3206 base::ProcessId plugin_pid) {
3207 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3208 PluginCrashed(plugin_path, plugin_pid));
3211 void WebContentsImpl::OnRequestPpapiBrokerPermission(
3212 int routing_id,
3213 const GURL& url,
3214 const base::FilePath& plugin_path) {
3215 if (!delegate_) {
3216 OnPpapiBrokerPermissionResult(routing_id, false);
3217 return;
3220 if (!delegate_->RequestPpapiBrokerPermission(
3221 this, url, plugin_path,
3222 base::Bind(&WebContentsImpl::OnPpapiBrokerPermissionResult,
3223 base::Unretained(this), routing_id))) {
3224 NOTIMPLEMENTED();
3225 OnPpapiBrokerPermissionResult(routing_id, false);
3229 void WebContentsImpl::OnPpapiBrokerPermissionResult(int routing_id,
3230 bool result) {
3231 Send(new ViewMsg_PpapiBrokerPermissionResult(routing_id, result));
3234 void WebContentsImpl::OnBrowserPluginMessage(RenderFrameHost* render_frame_host,
3235 const IPC::Message& message) {
3236 CHECK(!browser_plugin_embedder_.get());
3237 CreateBrowserPluginEmbedderIfNecessary();
3238 browser_plugin_embedder_->OnMessageReceived(message, render_frame_host);
3240 #endif // defined(ENABLE_PLUGINS)
3242 void WebContentsImpl::OnUpdateFaviconURL(
3243 const std::vector<FaviconURL>& candidates) {
3244 // We get updated favicon URLs after the page stops loading. If a cross-site
3245 // navigation occurs while a page is still loading, the initial page
3246 // may stop loading and send us updated favicon URLs after the navigation
3247 // for the new page has committed.
3248 RenderViewHostImpl* rvhi =
3249 static_cast<RenderViewHostImpl*>(render_view_message_source_);
3250 if (!rvhi->is_active())
3251 return;
3253 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3254 DidUpdateFaviconURL(candidates));
3257 void WebContentsImpl::CreateAudioPowerSaveBlocker() {
3258 DCHECK(!audio_power_save_blocker_);
3259 audio_power_save_blocker_ = PowerSaveBlocker::Create(
3260 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension,
3261 PowerSaveBlocker::kReasonAudioPlayback, "Playing audio");
3264 void WebContentsImpl::CreateVideoPowerSaveBlocker() {
3265 DCHECK(!video_power_save_blocker_);
3266 DCHECK(!active_video_players_.empty());
3267 video_power_save_blocker_ = PowerSaveBlocker::Create(
3268 PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep,
3269 PowerSaveBlocker::kReasonVideoPlayback, "Playing video");
3270 #if defined(OS_ANDROID)
3271 static_cast<PowerSaveBlockerImpl*>(video_power_save_blocker_.get())
3272 ->InitDisplaySleepBlocker(this);
3273 #endif
3276 void WebContentsImpl::MaybeReleasePowerSaveBlockers() {
3277 // If there are no more audio players and we don't have audio stream
3278 // monitoring, release the audio power save blocker here instead of during
3279 // NotifyNavigationStateChanged().
3280 if (active_audio_players_.empty() &&
3281 !audio_state_provider_->IsAudioStateAvailable()) {
3282 audio_power_save_blocker_.reset();
3285 // If there are no more video players, clear the video power save blocker.
3286 if (active_video_players_.empty())
3287 video_power_save_blocker_.reset();
3290 void WebContentsImpl::OnMediaPlayingNotification(int64 player_cookie,
3291 bool has_video,
3292 bool has_audio,
3293 bool is_remote) {
3294 // Ignore the videos playing remotely and don't hold the wake lock for the
3295 // screen.
3296 if (is_remote) return;
3298 if (has_audio) {
3299 AddMediaPlayerEntry(player_cookie, &active_audio_players_);
3301 // If we don't have audio stream monitoring, allocate the audio power save
3302 // blocker here instead of during NotifyNavigationStateChanged().
3303 if (!audio_power_save_blocker_ &&
3304 !audio_state_provider_->IsAudioStateAvailable()) {
3305 CreateAudioPowerSaveBlocker();
3309 if (has_video) {
3310 AddMediaPlayerEntry(player_cookie, &active_video_players_);
3312 // If we're not hidden and have just created a player, create a blocker.
3313 if (!video_power_save_blocker_ && !IsHidden())
3314 CreateVideoPowerSaveBlocker();
3317 FOR_EACH_OBSERVER(WebContentsObserver, observers_, MediaStartedPlaying());
3320 void WebContentsImpl::OnMediaPausedNotification(int64 player_cookie) {
3321 RemoveMediaPlayerEntry(player_cookie, &active_audio_players_);
3322 RemoveMediaPlayerEntry(player_cookie, &active_video_players_);
3323 MaybeReleasePowerSaveBlockers();
3325 FOR_EACH_OBSERVER(WebContentsObserver, observers_, MediaPaused());
3328 #if defined(OS_ANDROID)
3330 void WebContentsImpl::OnMediaSessionStateChanged() {
3331 MediaSession* session = MediaSession::Get(this);
3332 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3333 MediaSessionStateChanged(session->IsControllable(),
3334 session->IsSuspended()));
3337 void WebContentsImpl::ResumeMediaSession() {
3338 MediaSession::Get(this)->Resume();
3341 void WebContentsImpl::SuspendMediaSession() {
3342 MediaSession::Get(this)->Suspend();
3345 #endif // defined(OS_ANDROID)
3347 void WebContentsImpl::OnFirstVisuallyNonEmptyPaint() {
3348 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3349 DidFirstVisuallyNonEmptyPaint());
3351 did_first_visually_non_empty_paint_ = true;
3353 if (theme_color_ != last_sent_theme_color_) {
3354 // Theme color should have updated by now if there was one.
3355 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3356 DidChangeThemeColor(theme_color_));
3357 last_sent_theme_color_ = theme_color_;
3361 void WebContentsImpl::DidChangeVisibleSSLState() {
3362 if (delegate_) {
3363 delegate_->VisibleSSLStateChanged(this);
3365 SecurityStyleExplanations security_style_explanations;
3366 SecurityStyle security_style =
3367 delegate_->GetSecurityStyle(this, &security_style_explanations);
3368 FOR_EACH_OBSERVER(
3369 WebContentsObserver, observers_,
3370 SecurityStyleChanged(security_style, security_style_explanations));
3374 void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
3375 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3376 BeforeFormRepostWarningShow());
3379 void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
3380 Activate();
3381 if (delegate_)
3382 delegate_->ShowRepostFormWarningDialog(this);
3385 bool WebContentsImpl::HasAccessedInitialDocument() {
3386 return has_accessed_initial_document_;
3389 // Notifies the RenderWidgetHost instance about the fact that the page is
3390 // loading, or done loading.
3391 void WebContentsImpl::SetIsLoading(bool is_loading,
3392 bool to_different_document,
3393 LoadNotificationDetails* details) {
3394 if (is_loading == is_loading_)
3395 return;
3397 if (!is_loading) {
3398 load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
3399 base::string16());
3400 load_state_host_.clear();
3401 upload_size_ = 0;
3402 upload_position_ = 0;
3405 GetRenderManager()->SetIsLoading(is_loading);
3407 is_loading_ = is_loading;
3408 waiting_for_response_ = is_loading;
3409 is_load_to_different_document_ = to_different_document;
3411 if (delegate_)
3412 delegate_->LoadingStateChanged(this, to_different_document);
3413 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
3415 std::string url = (details ? details->url.possibly_invalid_spec() : "NULL");
3416 if (is_loading) {
3417 TRACE_EVENT_ASYNC_BEGIN1("browser,navigation", "WebContentsImpl Loading",
3418 this, "URL", url);
3419 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidStartLoading());
3420 } else {
3421 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
3422 this, "URL", url);
3423 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidStopLoading());
3426 // TODO(avi): Remove. http://crbug.com/170921
3427 int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
3428 NotificationDetails det = NotificationService::NoDetails();
3429 if (details)
3430 det = Details<LoadNotificationDetails>(details);
3431 NotificationService::current()->Notify(
3432 type, Source<NavigationController>(&controller_), det);
3435 void WebContentsImpl::UpdateMaxPageIDIfNecessary(RenderViewHost* rvh) {
3436 // If we are creating a RVH for a restored controller, then we need to make
3437 // sure the RenderView starts with a next_page_id_ larger than the number
3438 // of restored entries. This must be called before the RenderView starts
3439 // navigating (to avoid a race between the browser updating max_page_id and
3440 // the renderer updating next_page_id_). Because of this, we only call this
3441 // from CreateRenderView and allow that to notify the RenderView for us.
3442 int max_restored_page_id = controller_.GetMaxRestoredPageID();
3443 if (max_restored_page_id >
3444 GetMaxPageIDForSiteInstance(rvh->GetSiteInstance()))
3445 UpdateMaxPageIDForSiteInstance(rvh->GetSiteInstance(),
3446 max_restored_page_id);
3449 bool WebContentsImpl::UpdateTitleForEntry(NavigationEntryImpl* entry,
3450 const base::string16& title) {
3451 // For file URLs without a title, use the pathname instead. In the case of a
3452 // synthesized title, we don't want the update to count toward the "one set
3453 // per page of the title to history."
3454 base::string16 final_title;
3455 bool explicit_set;
3456 if (entry && entry->GetURL().SchemeIsFile() && title.empty()) {
3457 final_title = base::UTF8ToUTF16(entry->GetURL().ExtractFileName());
3458 explicit_set = false; // Don't count synthetic titles toward the set limit.
3459 } else {
3460 base::TrimWhitespace(title, base::TRIM_ALL, &final_title);
3461 explicit_set = true;
3464 // If a page is created via window.open and never navigated,
3465 // there will be no navigation entry. In this situation,
3466 // |page_title_when_no_navigation_entry_| will be used for page title.
3467 if (entry) {
3468 if (final_title == entry->GetTitle())
3469 return false; // Nothing changed, don't bother.
3471 entry->SetTitle(final_title);
3472 } else {
3473 if (page_title_when_no_navigation_entry_ == final_title)
3474 return false; // Nothing changed, don't bother.
3476 page_title_when_no_navigation_entry_ = final_title;
3479 // Lastly, set the title for the view.
3480 view_->SetPageTitle(final_title);
3482 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3483 TitleWasSet(entry, explicit_set));
3485 return true;
3488 void WebContentsImpl::SendChangeLoadProgress() {
3489 loading_last_progress_update_ = base::TimeTicks::Now();
3490 if (delegate_)
3491 delegate_->LoadProgressChanged(this, frame_tree_.load_progress());
3494 void WebContentsImpl::ResetLoadProgressState() {
3495 frame_tree_.ResetLoadProgress();
3496 loading_weak_factory_.InvalidateWeakPtrs();
3497 loading_last_progress_update_ = base::TimeTicks();
3500 void WebContentsImpl::NotifyViewSwapped(RenderViewHost* old_host,
3501 RenderViewHost* new_host) {
3502 // After sending out a swap notification, we need to send a disconnect
3503 // notification so that clients that pick up a pointer to |this| can NULL the
3504 // pointer. See Bug 1230284.
3505 notify_disconnection_ = true;
3506 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3507 RenderViewHostChanged(old_host, new_host));
3509 // Ensure that the associated embedder gets cleared after a RenderViewHost
3510 // gets swapped, so we don't reuse the same embedder next time a
3511 // RenderViewHost is attached to this WebContents.
3512 RemoveBrowserPluginEmbedder();
3515 void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost* old_host,
3516 RenderFrameHost* new_host) {
3517 FOR_EACH_OBSERVER(WebContentsObserver,
3518 observers_,
3519 RenderFrameHostChanged(old_host, new_host));
3522 // TODO(avi): Remove this entire function because this notification is already
3523 // covered by two observer functions. http://crbug.com/170921
3524 void WebContentsImpl::NotifyDisconnected() {
3525 if (!notify_disconnection_)
3526 return;
3528 notify_disconnection_ = false;
3529 NotificationService::current()->Notify(
3530 NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
3531 Source<WebContents>(this),
3532 NotificationService::NoDetails());
3535 void WebContentsImpl::NotifyNavigationEntryCommitted(
3536 const LoadCommittedDetails& load_details) {
3537 FOR_EACH_OBSERVER(
3538 WebContentsObserver, observers_, NavigationEntryCommitted(load_details));
3541 bool WebContentsImpl::OnMessageReceived(RenderFrameHost* render_frame_host,
3542 const IPC::Message& message) {
3543 return OnMessageReceived(NULL, render_frame_host, message);
3546 const GURL& WebContentsImpl::GetMainFrameLastCommittedURL() const {
3547 return GetLastCommittedURL();
3550 void WebContentsImpl::RenderFrameCreated(RenderFrameHost* render_frame_host) {
3551 // Note this is only for subframes, the notification for the main frame
3552 // happens in RenderViewCreated.
3553 FOR_EACH_OBSERVER(WebContentsObserver,
3554 observers_,
3555 RenderFrameCreated(render_frame_host));
3556 SetAccessibilityModeOnFrame(accessibility_mode_, render_frame_host);
3559 void WebContentsImpl::RenderFrameDeleted(RenderFrameHost* render_frame_host) {
3560 ClearPowerSaveBlockers(render_frame_host);
3561 FOR_EACH_OBSERVER(WebContentsObserver,
3562 observers_,
3563 RenderFrameDeleted(render_frame_host));
3566 void WebContentsImpl::ShowContextMenu(RenderFrameHost* render_frame_host,
3567 const ContextMenuParams& params) {
3568 ContextMenuParams context_menu_params(params);
3569 // Allow WebContentsDelegates to handle the context menu operation first.
3570 if (delegate_ && delegate_->HandleContextMenu(context_menu_params))
3571 return;
3573 render_view_host_delegate_view_->ShowContextMenu(render_frame_host,
3574 context_menu_params);
3577 void WebContentsImpl::RunJavaScriptMessage(
3578 RenderFrameHost* render_frame_host,
3579 const base::string16& message,
3580 const base::string16& default_prompt,
3581 const GURL& frame_url,
3582 JavaScriptMessageType javascript_message_type,
3583 IPC::Message* reply_msg) {
3584 // Suppress JavaScript dialogs when requested. Also suppress messages when
3585 // showing an interstitial as it's shown over the previous page and we don't
3586 // want the hidden page's dialogs to interfere with the interstitial.
3587 bool suppress_this_message =
3588 static_cast<RenderFrameHostImpl*>(render_frame_host)->is_swapped_out() ||
3589 ShowingInterstitialPage() || !delegate_ ||
3590 delegate_->ShouldSuppressDialogs(this) ||
3591 !delegate_->GetJavaScriptDialogManager(this);
3593 if (!suppress_this_message) {
3594 std::string accept_lang = GetContentClient()->browser()->
3595 GetAcceptLangs(GetBrowserContext());
3596 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
3597 dialog_manager_->RunJavaScriptDialog(
3598 this,
3599 frame_url.GetOrigin(),
3600 accept_lang,
3601 javascript_message_type,
3602 message,
3603 default_prompt,
3604 base::Bind(&WebContentsImpl::OnDialogClosed,
3605 base::Unretained(this),
3606 render_frame_host->GetProcess()->GetID(),
3607 render_frame_host->GetRoutingID(),
3608 reply_msg,
3609 false),
3610 &suppress_this_message);
3613 if (suppress_this_message) {
3614 // If we are suppressing messages, just reply as if the user immediately
3615 // pressed "Cancel", passing true to |dialog_was_suppressed|.
3616 OnDialogClosed(render_frame_host->GetProcess()->GetID(),
3617 render_frame_host->GetRoutingID(), reply_msg,
3618 true, false, base::string16());
3621 // OnDialogClosed (two lines up) may have caused deletion of this object (see
3622 // http://crbug.com/288961 ). The only safe thing to do here is return.
3625 void WebContentsImpl::RunBeforeUnloadConfirm(
3626 RenderFrameHost* render_frame_host,
3627 const base::string16& message,
3628 bool is_reload,
3629 IPC::Message* reply_msg) {
3630 RenderFrameHostImpl* rfhi =
3631 static_cast<RenderFrameHostImpl*>(render_frame_host);
3632 if (delegate_)
3633 delegate_->WillRunBeforeUnloadConfirm();
3635 bool suppress_this_message =
3636 rfhi->rfh_state() != RenderFrameHostImpl::STATE_DEFAULT ||
3637 ShowingInterstitialPage() || !delegate_ ||
3638 delegate_->ShouldSuppressDialogs(this) ||
3639 !delegate_->GetJavaScriptDialogManager(this);
3640 if (suppress_this_message) {
3641 rfhi->JavaScriptDialogClosed(reply_msg, true, base::string16(), true);
3642 return;
3645 is_showing_before_unload_dialog_ = true;
3646 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
3647 dialog_manager_->RunBeforeUnloadDialog(
3648 this, message, is_reload,
3649 base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
3650 render_frame_host->GetProcess()->GetID(),
3651 render_frame_host->GetRoutingID(), reply_msg,
3652 false));
3655 WebContents* WebContentsImpl::GetAsWebContents() {
3656 return this;
3659 bool WebContentsImpl::IsNeverVisible() {
3660 if (!delegate_)
3661 return false;
3662 return delegate_->IsNeverVisible(this);
3665 #if defined(OS_WIN)
3666 gfx::NativeViewAccessible WebContentsImpl::GetParentNativeViewAccessible() {
3667 return accessible_parent_;
3669 #endif
3671 RenderViewHostDelegateView* WebContentsImpl::GetDelegateView() {
3672 return render_view_host_delegate_view_;
3675 RendererPreferences WebContentsImpl::GetRendererPrefs(
3676 BrowserContext* browser_context) const {
3677 return renderer_preferences_;
3680 gfx::Rect WebContentsImpl::GetRootWindowResizerRect() const {
3681 if (delegate_)
3682 return delegate_->GetRootWindowResizerRect();
3683 return gfx::Rect();
3686 void WebContentsImpl::RemoveBrowserPluginEmbedder() {
3687 if (browser_plugin_embedder_)
3688 browser_plugin_embedder_.reset();
3691 void WebContentsImpl::RenderViewCreated(RenderViewHost* render_view_host) {
3692 // Don't send notifications if we are just creating a swapped-out RVH for
3693 // the opener chain. These won't be used for view-source or WebUI, so it's
3694 // ok to return early.
3695 if (!static_cast<RenderViewHostImpl*>(render_view_host)->is_active())
3696 return;
3698 if (delegate_)
3699 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
3701 NotificationService::current()->Notify(
3702 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
3703 Source<WebContents>(this),
3704 Details<RenderViewHost>(render_view_host));
3706 // When we're creating views, we're still doing initial setup, so we always
3707 // use the pending Web UI rather than any possibly existing committed one.
3708 if (GetRenderManager()->pending_web_ui())
3709 GetRenderManager()->pending_web_ui()->RenderViewCreated(render_view_host);
3711 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
3712 switches::kEnableBrowserSideNavigation) &&
3713 GetRenderManager()->speculative_web_ui()) {
3714 GetRenderManager()->speculative_web_ui()->RenderViewCreated(
3715 render_view_host);
3718 NavigationEntry* entry = controller_.GetPendingEntry();
3719 if (entry && entry->IsViewSourceMode()) {
3720 // Put the renderer in view source mode.
3721 render_view_host->Send(
3722 new ViewMsg_EnableViewSourceMode(render_view_host->GetRoutingID()));
3725 view_->RenderViewCreated(render_view_host);
3727 FOR_EACH_OBSERVER(
3728 WebContentsObserver, observers_, RenderViewCreated(render_view_host));
3731 void WebContentsImpl::RenderViewReady(RenderViewHost* rvh) {
3732 if (rvh != GetRenderViewHost()) {
3733 // Don't notify the world, since this came from a renderer in the
3734 // background.
3735 return;
3738 notify_disconnection_ = true;
3739 // TODO(avi): Remove. http://crbug.com/170921
3740 NotificationService::current()->Notify(
3741 NOTIFICATION_WEB_CONTENTS_CONNECTED,
3742 Source<WebContents>(this),
3743 NotificationService::NoDetails());
3745 bool was_crashed = IsCrashed();
3746 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
3748 // Restore the focus to the tab (otherwise the focus will be on the top
3749 // window).
3750 if (was_crashed && !FocusLocationBarByDefault() &&
3751 (!delegate_ || delegate_->ShouldFocusPageAfterCrash())) {
3752 view_->Focus();
3755 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewReady());
3758 void WebContentsImpl::RenderViewTerminated(RenderViewHost* rvh,
3759 base::TerminationStatus status,
3760 int error_code) {
3761 if (rvh != GetRenderViewHost()) {
3762 // The pending page's RenderViewHost is gone.
3763 return;
3766 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
3767 // renderer may not have made a clean exit.
3768 if (IsFullscreenForCurrentTab())
3769 ExitFullscreenMode();
3771 // Cancel any visible dialogs so they are not left dangling over the sad tab.
3772 CancelActiveAndPendingDialogs();
3774 if (delegate_)
3775 delegate_->HideValidationMessage(this);
3777 SetIsLoading(false, true, nullptr);
3778 NotifyDisconnected();
3779 SetIsCrashed(status, error_code);
3781 // Reset the loading progress. TODO(avi): What does it mean to have a
3782 // "renderer crash" when there is more than one renderer process serving a
3783 // webpage? Once this function is called at a more granular frame level, we
3784 // probably will need to more granularly reset the state here.
3785 ResetLoadProgressState();
3787 FOR_EACH_OBSERVER(WebContentsObserver,
3788 observers_,
3789 RenderProcessGone(GetCrashedStatus()));
3792 void WebContentsImpl::RenderViewDeleted(RenderViewHost* rvh) {
3793 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewDeleted(rvh));
3796 void WebContentsImpl::UpdateState(RenderViewHost* rvh,
3797 int32 page_id,
3798 const PageState& page_state) {
3799 // Ensure that this state update comes from a RenderViewHost that belongs to
3800 // this WebContents.
3801 // TODO(nasko): This should go through RenderFrameHost.
3802 // TODO(creis): We can't update state for cross-process subframes until we
3803 // have FrameNavigationEntries. Once we do, this should be a DCHECK.
3804 if (rvh->GetDelegate()->GetAsWebContents() != this)
3805 return;
3807 // We must be prepared to handle state updates for any page, these occur
3808 // when the user is scrolling and entering form data, as well as when we're
3809 // leaving a page, in which case our state may have already been moved to
3810 // the next page. The navigation controller will look up the appropriate
3811 // NavigationEntry and update it when it is notified via the delegate.
3812 NavigationEntryImpl* entry = controller_.GetEntryWithPageID(
3813 rvh->GetSiteInstance(), page_id);
3815 if (!entry)
3816 return;
3818 if (page_state == entry->GetPageState())
3819 return; // Nothing to update.
3820 entry->SetPageState(page_state);
3821 controller_.NotifyEntryChanged(entry);
3824 void WebContentsImpl::UpdateTargetURL(RenderViewHost* render_view_host,
3825 const GURL& url) {
3826 if (fullscreen_widget_routing_id_ != MSG_ROUTING_NONE) {
3827 // If we're fullscreen only update the url if it's from the fullscreen
3828 // renderer.
3829 RenderWidgetHostView* fs = GetFullscreenRenderWidgetHostView();
3830 if (fs && fs->GetRenderWidgetHost() != render_view_host)
3831 return;
3833 if (delegate_)
3834 delegate_->UpdateTargetURL(this, url);
3837 void WebContentsImpl::Close(RenderViewHost* rvh) {
3838 #if defined(OS_MACOSX)
3839 // The UI may be in an event-tracking loop, such as between the
3840 // mouse-down and mouse-up in text selection or a button click.
3841 // Defer the close until after tracking is complete, so that we
3842 // don't free objects out from under the UI.
3843 // TODO(shess): This could get more fine-grained. For instance,
3844 // closing a tab in another window while selecting text in the
3845 // current window's Omnibox should be just fine.
3846 if (view_->IsEventTracking()) {
3847 view_->CloseTabAfterEventTracking();
3848 return;
3850 #endif
3852 // Ignore this if it comes from a RenderViewHost that we aren't showing.
3853 if (delegate_ && rvh == GetRenderViewHost())
3854 delegate_->CloseContents(this);
3857 void WebContentsImpl::SwappedOut(RenderFrameHost* rfh) {
3858 if (delegate_ && rfh->GetRenderViewHost() == GetRenderViewHost())
3859 delegate_->SwappedOut(this);
3862 void WebContentsImpl::RequestMove(const gfx::Rect& new_bounds) {
3863 if (delegate_ && delegate_->IsPopupOrPanel(this))
3864 delegate_->MoveContents(this, new_bounds);
3867 void WebContentsImpl::DidStartLoading(FrameTreeNode* frame_tree_node,
3868 bool to_different_document) {
3869 SetIsLoading(true, to_different_document, nullptr);
3871 // Notify accessibility that the user is navigating away from the
3872 // current document.
3874 // TODO(dmazzoni): do this using a WebContentsObserver.
3875 BrowserAccessibilityManager* manager =
3876 frame_tree_node->current_frame_host()->browser_accessibility_manager();
3877 if (manager)
3878 manager->UserIsNavigatingAway();
3881 void WebContentsImpl::DidStopLoading() {
3882 scoped_ptr<LoadNotificationDetails> details;
3884 // Use the last committed entry rather than the active one, in case a
3885 // pending entry has been created.
3886 NavigationEntry* entry = controller_.GetLastCommittedEntry();
3887 Navigator* navigator = frame_tree_.root()->navigator();
3889 // An entry may not exist for a stop when loading an initial blank page or
3890 // if an iframe injected by script into a blank page finishes loading.
3891 if (entry) {
3892 base::TimeDelta elapsed =
3893 base::TimeTicks::Now() - navigator->GetCurrentLoadStart();
3895 details.reset(new LoadNotificationDetails(
3896 entry->GetVirtualURL(),
3897 entry->GetTransitionType(),
3898 elapsed,
3899 &controller_,
3900 controller_.GetCurrentEntryIndex()));
3903 SetIsLoading(false, true, details.get());
3906 void WebContentsImpl::DidChangeLoadProgress() {
3907 double load_progress = frame_tree_.load_progress();
3909 // The delegate is notified immediately for the first and last updates. Also,
3910 // since the message loop may be pretty busy when a page is loaded, it might
3911 // not execute a posted task in a timely manner so the progress report is sent
3912 // immediately if enough time has passed.
3913 base::TimeDelta min_delay =
3914 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS);
3915 bool delay_elapsed = loading_last_progress_update_.is_null() ||
3916 base::TimeTicks::Now() - loading_last_progress_update_ > min_delay;
3918 if (load_progress == 0.0 || load_progress == 1.0 || delay_elapsed) {
3919 // If there is a pending task to send progress, it is now obsolete.
3920 loading_weak_factory_.InvalidateWeakPtrs();
3922 // Notify the load progress change.
3923 SendChangeLoadProgress();
3925 // Clean-up the states if needed.
3926 if (load_progress == 1.0)
3927 ResetLoadProgressState();
3928 return;
3931 if (loading_weak_factory_.HasWeakPtrs())
3932 return;
3934 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
3935 FROM_HERE, base::Bind(&WebContentsImpl::SendChangeLoadProgress,
3936 loading_weak_factory_.GetWeakPtr()),
3937 min_delay);
3940 void WebContentsImpl::DidCancelLoading() {
3941 controller_.DiscardNonCommittedEntries();
3943 // Update the URL display.
3944 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
3947 void WebContentsImpl::DidAccessInitialDocument() {
3948 has_accessed_initial_document_ = true;
3950 // We may have left a failed browser-initiated navigation in the address bar
3951 // to let the user edit it and try again. Clear it now that content might
3952 // show up underneath it.
3953 if (!IsLoading() && controller_.GetPendingEntry())
3954 controller_.DiscardPendingEntry(false);
3956 // Update the URL display.
3957 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
3960 void WebContentsImpl::DidChangeName(RenderFrameHost* render_frame_host,
3961 const std::string& name) {
3962 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3963 FrameNameChanged(render_frame_host, name));
3966 void WebContentsImpl::DocumentOnLoadCompleted(
3967 RenderFrameHost* render_frame_host) {
3968 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3969 DocumentOnLoadCompletedInMainFrame());
3971 // TODO(avi): Remove. http://crbug.com/170921
3972 NotificationService::current()->Notify(
3973 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
3974 Source<WebContents>(this),
3975 NotificationService::NoDetails());
3978 void WebContentsImpl::UpdateTitle(RenderFrameHost* render_frame_host,
3979 int32 page_id,
3980 const base::string16& title,
3981 base::i18n::TextDirection title_direction) {
3982 RenderViewHost* rvh = render_frame_host->GetRenderViewHost();
3984 // If we have a title, that's a pretty good indication that we've started
3985 // getting useful data.
3986 SetNotWaitingForResponse();
3988 // Try to find the navigation entry, which might not be the current one.
3989 // For example, it might be from a pending RVH for the pending entry.
3990 NavigationEntryImpl* entry = controller_.GetEntryWithPageID(
3991 rvh->GetSiteInstance(), page_id);
3993 // We can handle title updates when we don't have an entry in
3994 // UpdateTitleForEntry, but only if the update is from the current RVH.
3995 // TODO(avi): Change to make decisions based on the RenderFrameHost.
3996 if (!entry && rvh != GetRenderViewHost())
3997 return;
3999 // TODO(evan): make use of title_direction.
4000 // http://code.google.com/p/chromium/issues/detail?id=27094
4001 if (!UpdateTitleForEntry(entry, title))
4002 return;
4004 // Broadcast notifications when the UI should be updated.
4005 if (entry == controller_.GetEntryAtOffset(0))
4006 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
4009 void WebContentsImpl::UpdateEncoding(RenderFrameHost* render_frame_host,
4010 const std::string& encoding) {
4011 SetEncoding(encoding);
4014 void WebContentsImpl::DocumentAvailableInMainFrame(
4015 RenderViewHost* render_view_host) {
4016 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4017 DocumentAvailableInMainFrame());
4020 void WebContentsImpl::RouteCloseEvent(RenderViewHost* rvh) {
4021 // Tell the active RenderViewHost to run unload handlers and close, as long
4022 // as the request came from a RenderViewHost in the same BrowsingInstance.
4023 // In most cases, we receive this from a swapped out RenderViewHost.
4024 // It is possible to receive it from one that has just been swapped in,
4025 // in which case we might as well deliver the message anyway.
4026 if (rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()))
4027 ClosePage();
4030 bool WebContentsImpl::ShouldRouteMessageEvent(
4031 RenderFrameHost* target_rfh,
4032 SiteInstance* source_site_instance) const {
4033 // Allow the message if this WebContents is dedicated to a browser plugin
4034 // guest.
4035 // Note: This check means that an embedder could theoretically receive a
4036 // postMessage from anyone (not just its own guests). However, this is
4037 // probably not a risk for apps since other pages won't have references
4038 // to App windows.
4039 return GetBrowserPluginGuest() || GetBrowserPluginEmbedder();
4042 void WebContentsImpl::EnsureOpenerProxiesExist(RenderFrameHost* source_rfh) {
4043 WebContentsImpl* source_web_contents = static_cast<WebContentsImpl*>(
4044 WebContents::FromRenderFrameHost(source_rfh));
4046 if (source_web_contents) {
4047 // If this message is going to outer WebContents from inner WebContents,
4048 // then we should not create a RenderView. AttachToOuterWebContentsFrame()
4049 // already created a RenderFrameProxyHost for that purpose.
4050 if (GetBrowserPluginEmbedder() &&
4051 BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
4052 return;
4055 if (GetBrowserPluginGuest()) {
4056 // We create a swapped out RenderView for the embedder in the guest's
4057 // render process but we intentionally do not expose the embedder's
4058 // opener chain to it.
4059 source_web_contents->CreateSwappedOutRenderView(GetSiteInstance());
4060 } else {
4061 RenderFrameHostImpl* source_rfhi =
4062 static_cast<RenderFrameHostImpl*>(source_rfh);
4063 source_rfhi->frame_tree_node()->render_manager()->CreateOpenerProxies(
4064 GetSiteInstance());
4069 bool WebContentsImpl::AddMessageToConsole(int32 level,
4070 const base::string16& message,
4071 int32 line_no,
4072 const base::string16& source_id) {
4073 if (!delegate_)
4074 return false;
4075 return delegate_->AddMessageToConsole(this, level, message, line_no,
4076 source_id);
4079 int WebContentsImpl::CreateSwappedOutRenderView(
4080 SiteInstance* instance) {
4081 int render_view_routing_id = MSG_ROUTING_NONE;
4082 if (RenderFrameHostManager::IsSwappedOutStateForbidden()) {
4083 GetRenderManager()->CreateRenderFrameProxy(instance);
4084 } else {
4085 GetRenderManager()->CreateRenderFrame(
4086 instance, nullptr,
4087 CREATE_RF_SWAPPED_OUT | CREATE_RF_FOR_MAIN_FRAME_NAVIGATION |
4088 CREATE_RF_HIDDEN,
4089 &render_view_routing_id);
4091 return render_view_routing_id;
4094 void WebContentsImpl::OnUserGesture() {
4095 // Notify observers.
4096 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetUserGesture());
4098 ResourceDispatcherHostImpl* rdh = ResourceDispatcherHostImpl::Get();
4099 if (rdh) // NULL in unittests.
4100 rdh->OnUserGesture(this);
4103 void WebContentsImpl::OnIgnoredUIEvent() {
4104 // Notify observers.
4105 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetIgnoredUIEvent());
4108 void WebContentsImpl::RendererUnresponsive(RenderViewHost* render_view_host) {
4109 // Don't show hung renderer dialog for a swapped out RVH.
4110 if (render_view_host != GetRenderViewHost())
4111 return;
4113 RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(render_view_host);
4114 RenderFrameHostImpl* rfhi =
4115 static_cast<RenderFrameHostImpl*>(rvhi->GetMainFrame());
4117 // Ignore renderer unresponsive event if debugger is attached to the tab
4118 // since the event may be a result of the renderer sitting on a breakpoint.
4119 // See http://crbug.com/65458
4120 if (DevToolsAgentHost::IsDebuggerAttached(this))
4121 return;
4123 if (rfhi->is_waiting_for_beforeunload_ack() ||
4124 rfhi->IsWaitingForUnloadACK()) {
4125 // Hang occurred while firing the beforeunload/unload handler.
4126 // Pretend the handler fired so tab closing continues as if it had.
4127 rvhi->set_sudden_termination_allowed(true);
4129 if (!GetRenderManager()->ShouldCloseTabOnUnresponsiveRenderer())
4130 return;
4132 // If the tab hangs in the beforeunload/unload handler there's really
4133 // nothing we can do to recover. If the hang is in the beforeunload handler,
4134 // pretend the beforeunload listeners have all fired and allow the delegate
4135 // to continue closing; the user will not have the option of cancelling the
4136 // close. Otherwise, pretend the unload listeners have all fired and close
4137 // the tab.
4138 bool close = true;
4139 if (rfhi->is_waiting_for_beforeunload_ack() && delegate_) {
4140 delegate_->BeforeUnloadFired(this, true, &close);
4142 if (close)
4143 Close(rvhi);
4144 return;
4147 if (!GetRenderViewHost() || !GetRenderViewHost()->IsRenderViewLive())
4148 return;
4150 if (delegate_)
4151 delegate_->RendererUnresponsive(this);
4154 void WebContentsImpl::RendererResponsive(RenderViewHost* render_view_host) {
4155 if (delegate_)
4156 delegate_->RendererResponsive(this);
4159 void WebContentsImpl::LoadStateChanged(
4160 const GURL& url,
4161 const net::LoadStateWithParam& load_state,
4162 uint64 upload_position,
4163 uint64 upload_size) {
4164 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
4165 // is fixed.
4166 tracked_objects::ScopedTracker tracking_profile1(
4167 FROM_HERE_WITH_EXPLICIT_FUNCTION(
4168 "466285 WebContentsImpl::LoadStateChanged::Start"));
4169 load_state_ = load_state;
4170 upload_position_ = upload_position;
4171 upload_size_ = upload_size;
4172 load_state_host_ = net::IDNToUnicode(url.host(),
4173 GetContentClient()->browser()->GetAcceptLangs(
4174 GetBrowserContext()));
4175 if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
4176 SetNotWaitingForResponse();
4177 if (IsLoading()) {
4178 NotifyNavigationStateChanged(static_cast<InvalidateTypes>(
4179 INVALIDATE_TYPE_LOAD | INVALIDATE_TYPE_TAB));
4183 void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
4184 bool proceed, const base::TimeTicks& proceed_time,
4185 bool* proceed_to_fire_unload) {
4186 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4187 BeforeUnloadFired(proceed_time));
4188 if (delegate_)
4189 delegate_->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
4190 // Note: |this| might be deleted at this point.
4193 void WebContentsImpl::RenderProcessGoneFromRenderManager(
4194 RenderViewHost* render_view_host) {
4195 DCHECK(crashed_status_ != base::TERMINATION_STATUS_STILL_RUNNING);
4196 RenderViewTerminated(render_view_host, crashed_status_, crashed_error_code_);
4199 void WebContentsImpl::UpdateRenderViewSizeForRenderManager() {
4200 // TODO(brettw) this is a hack. See WebContentsView::SizeContents.
4201 gfx::Size size = GetSizeForNewRenderView();
4202 // 0x0 isn't a valid window size (minimal window size is 1x1) but it may be
4203 // here during container initialization and normal window size will be set
4204 // later. In case of tab duplication this resizing to 0x0 prevents setting
4205 // normal size later so just ignore it.
4206 if (!size.IsEmpty())
4207 view_->SizeContents(size);
4210 void WebContentsImpl::CancelModalDialogsForRenderManager() {
4211 // We need to cancel modal dialogs when doing a process swap, since the load
4212 // deferrer would prevent us from swapping out. We also clear the state
4213 // because this is a cross-process navigation, which means that it's a new
4214 // site that should not have to pay for the sins of its predecessor.
4216 // Note that we don't bother telling browser_plugin_embedder_ because the
4217 // cross-process navigation will either destroy the browser plugins or not
4218 // require their dialogs to close.
4219 if (dialog_manager_)
4220 dialog_manager_->ResetDialogState(this);
4223 void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost* old_host,
4224 RenderFrameHost* new_host,
4225 bool is_main_frame) {
4226 if (is_main_frame) {
4227 NotifyViewSwapped(old_host ? old_host->GetRenderViewHost() : nullptr,
4228 new_host->GetRenderViewHost());
4230 // Make sure the visible RVH reflects the new delegate's preferences.
4231 if (delegate_)
4232 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
4234 view_->RenderViewSwappedIn(new_host->GetRenderViewHost());
4237 NotifyFrameSwapped(old_host, new_host);
4240 void WebContentsImpl::NotifyMainFrameSwappedFromRenderManager(
4241 RenderViewHost* old_host,
4242 RenderViewHost* new_host) {
4243 NotifyViewSwapped(old_host, new_host);
4246 NavigationControllerImpl& WebContentsImpl::GetControllerForRenderManager() {
4247 return GetController();
4250 scoped_ptr<WebUIImpl> WebContentsImpl::CreateWebUIForRenderManager(
4251 const GURL& url) {
4252 return scoped_ptr<WebUIImpl>(static_cast<WebUIImpl*>(CreateWebUI(url)));
4255 NavigationEntry*
4256 WebContentsImpl::GetLastCommittedNavigationEntryForRenderManager() {
4257 return controller_.GetLastCommittedEntry();
4260 bool WebContentsImpl::CreateRenderViewForRenderManager(
4261 RenderViewHost* render_view_host,
4262 int opener_frame_routing_id,
4263 int proxy_routing_id,
4264 const FrameReplicationState& replicated_frame_state,
4265 bool for_main_frame_navigation) {
4266 TRACE_EVENT0("browser,navigation",
4267 "WebContentsImpl::CreateRenderViewForRenderManager");
4268 // Can be NULL during tests.
4269 RenderWidgetHostViewBase* rwh_view;
4270 // TODO(kenrb): RenderWidgetHostViewChildFrame special casing is temporary
4271 // until RenderWidgetHost is attached to RenderFrameHost. We need to special
4272 // case this because RWH is still a base class of RenderViewHost, and child
4273 // frame RWHVs are unique in that they do not have their own WebContents.
4274 bool is_guest_in_site_per_process =
4275 !!browser_plugin_guest_.get() &&
4276 BrowserPluginGuestMode::UseCrossProcessFramesForGuests();
4277 if (!for_main_frame_navigation || is_guest_in_site_per_process) {
4278 RenderWidgetHostViewChildFrame* rwh_view_child =
4279 new RenderWidgetHostViewChildFrame(render_view_host);
4280 rwh_view = rwh_view_child;
4281 } else {
4282 rwh_view = view_->CreateViewForWidget(render_view_host, false);
4285 // Now that the RenderView has been created, we need to tell it its size.
4286 if (rwh_view)
4287 rwh_view->SetSize(GetSizeForNewRenderView());
4289 // Make sure we use the correct starting page_id in the new RenderView.
4290 UpdateMaxPageIDIfNecessary(render_view_host);
4291 int32 max_page_id =
4292 GetMaxPageIDForSiteInstance(render_view_host->GetSiteInstance());
4294 if (!static_cast<RenderViewHostImpl*>(render_view_host)
4295 ->CreateRenderView(opener_frame_routing_id, proxy_routing_id,
4296 max_page_id, replicated_frame_state,
4297 created_with_opener_)) {
4298 return false;
4301 SetHistoryOffsetAndLengthForView(render_view_host,
4302 controller_.GetLastCommittedEntryIndex(),
4303 controller_.GetEntryCount());
4305 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
4306 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
4307 // linux. See crbug.com/83941.
4308 if (rwh_view) {
4309 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
4310 render_widget_host->WasResized();
4312 #endif
4314 return true;
4317 bool WebContentsImpl::CreateRenderFrameForRenderManager(
4318 RenderFrameHost* render_frame_host,
4319 int parent_routing_id,
4320 int previous_sibling_routing_id,
4321 int proxy_routing_id) {
4322 TRACE_EVENT0("browser,navigation",
4323 "WebContentsImpl::CreateRenderFrameForRenderManager");
4325 RenderFrameHostImpl* rfh =
4326 static_cast<RenderFrameHostImpl*>(render_frame_host);
4327 if (!rfh->CreateRenderFrame(parent_routing_id, previous_sibling_routing_id,
4328 proxy_routing_id))
4329 return false;
4331 // TODO(nasko): When RenderWidgetHost is owned by RenderFrameHost, the passed
4332 // RenderFrameHost will have to be associated with the appropriate
4333 // RenderWidgetHostView or a new one should be created here.
4335 return true;
4338 #if defined(OS_ANDROID)
4340 base::android::ScopedJavaLocalRef<jobject>
4341 WebContentsImpl::GetJavaWebContents() {
4342 DCHECK_CURRENTLY_ON(BrowserThread::UI);
4343 return GetWebContentsAndroid()->GetJavaObject();
4346 WebContentsAndroid* WebContentsImpl::GetWebContentsAndroid() {
4347 WebContentsAndroid* web_contents_android =
4348 static_cast<WebContentsAndroid*>(GetUserData(kWebContentsAndroidKey));
4349 if (!web_contents_android) {
4350 web_contents_android = new WebContentsAndroid(this);
4351 SetUserData(kWebContentsAndroidKey, web_contents_android);
4353 return web_contents_android;
4356 bool WebContentsImpl::CreateRenderViewForInitialEmptyDocument() {
4357 return CreateRenderViewForRenderManager(
4358 GetRenderViewHost(), MSG_ROUTING_NONE, MSG_ROUTING_NONE,
4359 frame_tree_.root()->current_replication_state(), true);
4362 #elif defined(OS_MACOSX)
4364 void WebContentsImpl::SetAllowOtherViews(bool allow) {
4365 view_->SetAllowOtherViews(allow);
4368 bool WebContentsImpl::GetAllowOtherViews() {
4369 return view_->GetAllowOtherViews();
4372 #endif
4374 void WebContentsImpl::OnDialogClosed(int render_process_id,
4375 int render_frame_id,
4376 IPC::Message* reply_msg,
4377 bool dialog_was_suppressed,
4378 bool success,
4379 const base::string16& user_input) {
4380 RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(render_process_id,
4381 render_frame_id);
4382 last_dialog_suppressed_ = dialog_was_suppressed;
4384 if (is_showing_before_unload_dialog_ && !success) {
4385 // If a beforeunload dialog is canceled, we need to stop the throbber from
4386 // spinning, since we forced it to start spinning in Navigate.
4387 if (rfh)
4388 DidStopLoading();
4389 controller_.DiscardNonCommittedEntries();
4391 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4392 BeforeUnloadDialogCancelled());
4395 is_showing_before_unload_dialog_ = false;
4396 if (rfh) {
4397 rfh->JavaScriptDialogClosed(reply_msg, success, user_input,
4398 dialog_was_suppressed);
4399 } else {
4400 // Don't leak the sync IPC reply if the RFH or process is gone.
4401 delete reply_msg;
4405 void WebContentsImpl::SetEncoding(const std::string& encoding) {
4406 if (encoding == last_reported_encoding_)
4407 return;
4408 last_reported_encoding_ = encoding;
4410 canonical_encoding_ = GetContentClient()->browser()->
4411 GetCanonicalEncodingNameByAliasName(encoding);
4414 bool WebContentsImpl::IsHidden() {
4415 return capturer_count_ == 0 && !should_normally_be_visible_;
4418 int WebContentsImpl::GetOuterDelegateFrameTreeNodeID() {
4419 if (node_ && node_->outer_web_contents())
4420 return node_->outer_contents_frame_tree_node_id();
4422 return FrameTreeNode::kFrameTreeNodeInvalidID;
4425 RenderFrameHostManager* WebContentsImpl::GetRenderManager() const {
4426 return frame_tree_.root()->render_manager();
4429 BrowserPluginGuest* WebContentsImpl::GetBrowserPluginGuest() const {
4430 return browser_plugin_guest_.get();
4433 void WebContentsImpl::SetBrowserPluginGuest(BrowserPluginGuest* guest) {
4434 CHECK(!browser_plugin_guest_);
4435 CHECK(guest);
4436 browser_plugin_guest_.reset(guest);
4439 BrowserPluginEmbedder* WebContentsImpl::GetBrowserPluginEmbedder() const {
4440 return browser_plugin_embedder_.get();
4443 void WebContentsImpl::CreateBrowserPluginEmbedderIfNecessary() {
4444 if (browser_plugin_embedder_)
4445 return;
4446 browser_plugin_embedder_.reset(BrowserPluginEmbedder::Create(this));
4449 void WebContentsImpl::ClearPowerSaveBlockers(
4450 RenderFrameHost* render_frame_host) {
4451 RemoveAllMediaPlayerEntries(render_frame_host, &active_audio_players_);
4452 RemoveAllMediaPlayerEntries(render_frame_host, &active_video_players_);
4453 MaybeReleasePowerSaveBlockers();
4456 void WebContentsImpl::ClearAllPowerSaveBlockers() {
4457 active_audio_players_.clear();
4458 active_video_players_.clear();
4459 audio_power_save_blocker_.reset();
4460 video_power_save_blocker_.reset();
4463 gfx::Size WebContentsImpl::GetSizeForNewRenderView() {
4464 gfx::Size size;
4465 if (delegate_)
4466 size = delegate_->GetSizeForNewRenderView(this);
4467 if (size.IsEmpty())
4468 size = GetContainerBounds().size();
4469 return size;
4472 void WebContentsImpl::OnFrameRemoved(RenderFrameHost* render_frame_host) {
4473 FOR_EACH_OBSERVER(
4474 WebContentsObserver, observers_, FrameDeleted(render_frame_host));
4477 void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size& old_size) {
4478 if (!delegate_)
4479 return;
4480 const gfx::Size new_size = GetPreferredSize();
4481 if (new_size != old_size)
4482 delegate_->UpdatePreferredSize(this, new_size);
4485 void WebContentsImpl::AddMediaPlayerEntry(int64 player_cookie,
4486 ActiveMediaPlayerMap* player_map) {
4487 if (!HasValidFrameSource())
4488 return;
4490 const uintptr_t key =
4491 reinterpret_cast<uintptr_t>(render_frame_message_source_);
4492 DCHECK(std::find((*player_map)[key].begin(),
4493 (*player_map)[key].end(),
4494 player_cookie) == (*player_map)[key].end());
4495 (*player_map)[key].push_back(player_cookie);
4498 void WebContentsImpl::RemoveMediaPlayerEntry(int64 player_cookie,
4499 ActiveMediaPlayerMap* player_map) {
4500 if (!HasValidFrameSource())
4501 return;
4503 const uintptr_t key =
4504 reinterpret_cast<uintptr_t>(render_frame_message_source_);
4505 ActiveMediaPlayerMap::iterator it = player_map->find(key);
4506 if (it == player_map->end())
4507 return;
4509 // Remove the player.
4510 PlayerList::iterator player_it =
4511 std::find(it->second.begin(), it->second.end(), player_cookie);
4512 if (player_it != it->second.end())
4513 it->second.erase(player_it);
4515 // If there are no players left, remove the map entry.
4516 if (it->second.empty())
4517 player_map->erase(it);
4520 void WebContentsImpl::RemoveAllMediaPlayerEntries(
4521 RenderFrameHost* render_frame_host,
4522 ActiveMediaPlayerMap* player_map) {
4523 ActiveMediaPlayerMap::iterator it =
4524 player_map->find(reinterpret_cast<uintptr_t>(render_frame_host));
4525 if (it == player_map->end())
4526 return;
4527 player_map->erase(it);
4530 void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable) {
4531 force_disable_overscroll_content_ = force_disable;
4532 if (view_)
4533 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
4536 } // namespace content