Update V8 to version 4.6.55.
[chromium-blink-merge.git] / content / browser / web_contents / web_contents_impl.cc
blob287d01681cda15a27dfb693ec2606c1838bdc8cf
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/navigation_handle_impl.h"
40 #include "content/browser/frame_host/navigator_impl.h"
41 #include "content/browser/frame_host/render_frame_host_impl.h"
42 #include "content/browser/frame_host/render_widget_host_view_child_frame.h"
43 #include "content/browser/geolocation/geolocation_service_context.h"
44 #include "content/browser/host_zoom_map_impl.h"
45 #include "content/browser/loader/resource_dispatcher_host_impl.h"
46 #include "content/browser/manifest/manifest_manager_host.h"
47 #include "content/browser/media/audio_stream_monitor.h"
48 #include "content/browser/media/capture/web_contents_audio_muter.h"
49 #include "content/browser/message_port_message_filter.h"
50 #include "content/browser/plugin_content_origin_whitelist.h"
51 #include "content/browser/power_save_blocker_impl.h"
52 #include "content/browser/renderer_host/render_process_host_impl.h"
53 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
54 #include "content/browser/renderer_host/render_view_host_impl.h"
55 #include "content/browser/renderer_host/render_widget_host_impl.h"
56 #include "content/browser/renderer_host/render_widget_host_view_base.h"
57 #include "content/browser/screen_orientation/screen_orientation_dispatcher_host_impl.h"
58 #include "content/browser/site_instance_impl.h"
59 #include "content/browser/web_contents/web_contents_view_guest.h"
60 #include "content/browser/webui/generic_handler.h"
61 #include "content/browser/webui/web_ui_controller_factory_registry.h"
62 #include "content/browser/webui/web_ui_impl.h"
63 #include "content/common/browser_plugin/browser_plugin_constants.h"
64 #include "content/common/browser_plugin/browser_plugin_messages.h"
65 #include "content/common/frame_messages.h"
66 #include "content/common/input_messages.h"
67 #include "content/common/site_isolation_policy.h"
68 #include "content/common/ssl_status_serialization.h"
69 #include "content/common/view_messages.h"
70 #include "content/public/browser/ax_event_notification_details.h"
71 #include "content/public/browser/browser_context.h"
72 #include "content/public/browser/browser_plugin_guest_manager.h"
73 #include "content/public/browser/content_browser_client.h"
74 #include "content/public/browser/devtools_agent_host.h"
75 #include "content/public/browser/download_manager.h"
76 #include "content/public/browser/download_url_parameters.h"
77 #include "content/public/browser/invalidate_type.h"
78 #include "content/public/browser/javascript_dialog_manager.h"
79 #include "content/public/browser/load_from_memory_cache_details.h"
80 #include "content/public/browser/load_notification_details.h"
81 #include "content/public/browser/navigation_details.h"
82 #include "content/public/browser/notification_details.h"
83 #include "content/public/browser/notification_service.h"
84 #include "content/public/browser/render_widget_host_iterator.h"
85 #include "content/public/browser/resource_request_details.h"
86 #include "content/public/browser/screen_orientation_dispatcher_host.h"
87 #include "content/public/browser/security_style_explanations.h"
88 #include "content/public/browser/storage_partition.h"
89 #include "content/public/browser/user_metrics.h"
90 #include "content/public/browser/web_contents_delegate.h"
91 #include "content/public/browser/web_contents_observer.h"
92 #include "content/public/common/bindings_policy.h"
93 #include "content/public/common/browser_plugin_guest_mode.h"
94 #include "content/public/common/content_constants.h"
95 #include "content/public/common/content_switches.h"
96 #include "content/public/common/page_zoom.h"
97 #include "content/public/common/result_codes.h"
98 #include "content/public/common/security_style.h"
99 #include "content/public/common/url_constants.h"
100 #include "content/public/common/url_utils.h"
101 #include "content/public/common/web_preferences.h"
102 #include "mojo/common/url_type_converters.h"
103 #include "mojo/converters/geometry/geometry_type_converters.h"
104 #include "net/base/net_util.h"
105 #include "net/http/http_cache.h"
106 #include "net/http/http_transaction_factory.h"
107 #include "net/url_request/url_request_context.h"
108 #include "net/url_request/url_request_context_getter.h"
109 #include "skia/public/type_converters.h"
110 #include "third_party/skia/include/core/SkBitmap.h"
111 #include "ui/base/layout.h"
112 #include "ui/gfx/display.h"
113 #include "ui/gfx/screen.h"
114 #include "ui/gl/gl_switches.h"
116 #if defined(ENABLE_BROWSER_CDMS)
117 #include "content/browser/media/media_web_contents_observer.h"
118 #endif
120 #if defined(OS_ANDROID)
121 #include "content/browser/android/content_video_view.h"
122 #include "content/browser/android/date_time_chooser_android.h"
123 #include "content/browser/android/media_players_observer.h"
124 #include "content/browser/media/android/media_session.h"
125 #include "content/browser/web_contents/web_contents_android.h"
126 #endif
128 #if defined(OS_MACOSX)
129 #include "base/mac/foundation_util.h"
130 #endif
132 namespace content {
133 namespace {
135 const int kMinimumDelayBetweenLoadingUpdatesMS = 100;
136 const char kDotGoogleDotCom[] = ".google.com";
138 #if defined(OS_ANDROID)
139 const char kWebContentsAndroidKey[] = "web_contents_android";
140 #endif // OS_ANDROID
142 base::LazyInstance<std::vector<WebContentsImpl::CreatedCallback> >
143 g_created_callbacks = LAZY_INSTANCE_INITIALIZER;
145 static void DidDownloadImage(const WebContents::ImageDownloadCallback& callback,
146 int id,
147 const GURL& image_url,
148 image_downloader::DownloadResultPtr result) {
149 DCHECK(result);
151 const std::vector<SkBitmap> images =
152 result->images.To<std::vector<SkBitmap>>();
153 const std::vector<gfx::Size> original_image_sizes =
154 result->original_image_sizes.To<std::vector<gfx::Size>>();
156 callback.Run(id, result->http_status_code, image_url, images,
157 original_image_sizes);
160 void NotifyCacheOnIO(
161 scoped_refptr<net::URLRequestContextGetter> request_context,
162 const GURL& url,
163 const std::string& http_method) {
164 net::HttpCache* cache = request_context->GetURLRequestContext()->
165 http_transaction_factory()->GetCache();
166 if (cache)
167 cache->OnExternalCacheHit(url, http_method);
170 // Helper function for retrieving all the sites in a frame tree.
171 bool CollectSites(BrowserContext* context,
172 std::set<GURL>* sites,
173 FrameTreeNode* node) {
174 sites->insert(SiteInstance::GetSiteForURL(context, node->current_url()));
175 return true;
178 bool FindMatchingProcess(int render_process_id,
179 bool* did_match_process,
180 FrameTreeNode* node) {
181 if (node->current_frame_host()->GetProcess()->GetID() == render_process_id) {
182 *did_match_process = true;
183 return false;
185 return true;
188 bool ForEachFrameInternal(
189 const base::Callback<void(RenderFrameHost*)>& on_frame,
190 FrameTreeNode* node) {
191 on_frame.Run(node->current_frame_host());
192 return true;
195 bool ForEachPendingFrameInternal(
196 const base::Callback<void(RenderFrameHost*)>& on_frame,
197 FrameTreeNode* node) {
198 RenderFrameHost* pending_frame_host =
199 node->render_manager()->pending_frame_host();
200 if (pending_frame_host)
201 on_frame.Run(pending_frame_host);
202 return true;
205 void SendToAllFramesInternal(IPC::Message* message, RenderFrameHost* rfh) {
206 IPC::Message* message_copy = new IPC::Message(*message);
207 message_copy->set_routing_id(rfh->GetRoutingID());
208 rfh->Send(message_copy);
211 void AddRenderWidgetHostViewToSet(std::set<RenderWidgetHostView*>* set,
212 RenderFrameHost* rfh) {
213 RenderWidgetHostView* rwhv = static_cast<RenderFrameHostImpl*>(rfh)
214 ->frame_tree_node()
215 ->render_manager()
216 ->GetRenderWidgetHostView();
217 set->insert(rwhv);
220 void SetAccessibilityModeOnFrame(AccessibilityMode mode,
221 RenderFrameHost* frame_host) {
222 static_cast<RenderFrameHostImpl*>(frame_host)->SetAccessibilityMode(mode);
225 void ResetAccessibility(RenderFrameHost* rfh) {
226 static_cast<RenderFrameHostImpl*>(rfh)->AccessibilityReset();
229 } // namespace
231 WebContents* WebContents::Create(const WebContents::CreateParams& params) {
232 FrameTreeNode* opener_node = nullptr;
233 if (params.opener_render_frame_id != MSG_ROUTING_NONE) {
234 RenderFrameHostImpl* opener_rfh = RenderFrameHostImpl::FromID(
235 params.opener_render_process_id, params.opener_render_frame_id);
236 if (opener_rfh)
237 opener_node = opener_rfh->frame_tree_node();
239 return WebContentsImpl::CreateWithOpener(params, opener_node);
242 WebContents* WebContents::CreateWithSessionStorage(
243 const WebContents::CreateParams& params,
244 const SessionStorageNamespaceMap& session_storage_namespace_map) {
245 WebContentsImpl* new_contents = new WebContentsImpl(params.browser_context);
247 for (SessionStorageNamespaceMap::const_iterator it =
248 session_storage_namespace_map.begin();
249 it != session_storage_namespace_map.end();
250 ++it) {
251 new_contents->GetController()
252 .SetSessionStorageNamespace(it->first, it->second.get());
255 new_contents->Init(params);
256 return new_contents;
259 void WebContentsImpl::FriendZone::AddCreatedCallbackForTesting(
260 const CreatedCallback& callback) {
261 g_created_callbacks.Get().push_back(callback);
264 void WebContentsImpl::FriendZone::RemoveCreatedCallbackForTesting(
265 const CreatedCallback& callback) {
266 for (size_t i = 0; i < g_created_callbacks.Get().size(); ++i) {
267 if (g_created_callbacks.Get().at(i).Equals(callback)) {
268 g_created_callbacks.Get().erase(g_created_callbacks.Get().begin() + i);
269 return;
274 WebContents* WebContents::FromRenderViewHost(const RenderViewHost* rvh) {
275 return rvh->GetDelegate()->GetAsWebContents();
278 WebContents* WebContents::FromRenderFrameHost(RenderFrameHost* rfh) {
279 RenderFrameHostImpl* rfh_impl = static_cast<RenderFrameHostImpl*>(rfh);
280 if (!rfh_impl)
281 return NULL;
282 return rfh_impl->delegate()->GetAsWebContents();
285 // WebContentsImpl::DestructionObserver ----------------------------------------
287 class WebContentsImpl::DestructionObserver : public WebContentsObserver {
288 public:
289 DestructionObserver(WebContentsImpl* owner, WebContents* watched_contents)
290 : WebContentsObserver(watched_contents),
291 owner_(owner) {
294 // WebContentsObserver:
295 void WebContentsDestroyed() override {
296 owner_->OnWebContentsDestroyed(
297 static_cast<WebContentsImpl*>(web_contents()));
300 private:
301 WebContentsImpl* owner_;
303 DISALLOW_COPY_AND_ASSIGN(DestructionObserver);
306 WebContentsImpl::ColorChooserInfo::ColorChooserInfo(int render_process_id,
307 int render_frame_id,
308 ColorChooser* chooser,
309 int identifier)
310 : render_process_id(render_process_id),
311 render_frame_id(render_frame_id),
312 chooser(chooser),
313 identifier(identifier) {
316 WebContentsImpl::ColorChooserInfo::~ColorChooserInfo() {
319 // WebContentsImpl::WebContentsTreeNode ----------------------------------------
320 WebContentsImpl::WebContentsTreeNode::WebContentsTreeNode()
321 : outer_web_contents_(nullptr),
322 outer_contents_frame_tree_node_id_(
323 FrameTreeNode::kFrameTreeNodeInvalidID) {
326 WebContentsImpl::WebContentsTreeNode::~WebContentsTreeNode() {
327 // Remove child pointer from our parent.
328 if (outer_web_contents_) {
329 ChildrenSet& child_ptrs_in_parent =
330 outer_web_contents_->node_->inner_web_contents_tree_nodes_;
331 ChildrenSet::iterator iter = child_ptrs_in_parent.find(this);
332 DCHECK(iter != child_ptrs_in_parent.end());
333 child_ptrs_in_parent.erase(this);
336 // Remove parent pointers from our children.
337 // TODO(lazyboy): We should destroy the children WebContentses too. If the
338 // children do not manage their own lifetime, then we would leak their
339 // WebContentses.
340 for (WebContentsTreeNode* child : inner_web_contents_tree_nodes_)
341 child->outer_web_contents_ = nullptr;
344 void WebContentsImpl::WebContentsTreeNode::ConnectToOuterWebContents(
345 WebContentsImpl* outer_web_contents,
346 RenderFrameHostImpl* outer_contents_frame) {
347 outer_web_contents_ = outer_web_contents;
348 outer_contents_frame_tree_node_id_ =
349 outer_contents_frame->frame_tree_node()->frame_tree_node_id();
351 if (!outer_web_contents_->node_)
352 outer_web_contents_->node_.reset(new WebContentsTreeNode());
354 outer_web_contents_->node_->inner_web_contents_tree_nodes_.insert(this);
357 // WebContentsImpl -------------------------------------------------------------
359 WebContentsImpl::WebContentsImpl(BrowserContext* browser_context)
360 : delegate_(NULL),
361 controller_(this, browser_context),
362 render_view_host_delegate_view_(NULL),
363 created_with_opener_(false),
364 #if defined(OS_WIN)
365 accessible_parent_(NULL),
366 #endif
367 frame_tree_(new NavigatorImpl(&controller_, this),
368 this,
369 this,
370 this,
371 this),
372 is_loading_(false),
373 is_load_to_different_document_(false),
374 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING),
375 crashed_error_code_(0),
376 waiting_for_response_(false),
377 load_state_(net::LOAD_STATE_IDLE, base::string16()),
378 upload_size_(0),
379 upload_position_(0),
380 is_resume_pending_(false),
381 displayed_insecure_content_(false),
382 has_accessed_initial_document_(false),
383 theme_color_(SK_ColorTRANSPARENT),
384 last_sent_theme_color_(SK_ColorTRANSPARENT),
385 did_first_visually_non_empty_paint_(false),
386 capturer_count_(0),
387 should_normally_be_visible_(true),
388 is_being_destroyed_(false),
389 notify_disconnection_(false),
390 dialog_manager_(NULL),
391 is_showing_before_unload_dialog_(false),
392 last_active_time_(base::TimeTicks::Now()),
393 closed_by_user_gesture_(false),
394 minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)),
395 maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)),
396 render_view_message_source_(NULL),
397 render_frame_message_source_(NULL),
398 fullscreen_widget_routing_id_(MSG_ROUTING_NONE),
399 fullscreen_widget_had_focus_at_shutdown_(false),
400 is_subframe_(false),
401 force_disable_overscroll_content_(false),
402 last_dialog_suppressed_(false),
403 geolocation_service_context_(new GeolocationServiceContext()),
404 accessibility_mode_(
405 BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()),
406 virtual_keyboard_requested_(false),
407 loading_weak_factory_(this) {
408 frame_tree_.SetFrameRemoveListener(
409 base::Bind(&WebContentsImpl::OnFrameRemoved,
410 base::Unretained(this)));
411 #if defined(ENABLE_BROWSER_CDMS)
412 media_web_contents_observer_.reset(new MediaWebContentsObserver(this));
413 #endif
415 #if defined(OS_ANDROID)
416 audio_state_provider_.reset(new MediaPlayersObserver(this));
417 #else
418 audio_state_provider_.reset(new AudioStreamMonitor(this));
419 #endif
422 WebContentsImpl::~WebContentsImpl() {
423 is_being_destroyed_ = true;
425 // Delete all RFH pending shutdown, which will lead the corresponding RVH to
426 // shutdown and be deleted as well.
427 frame_tree_.ForEach(
428 base::Bind(&RenderFrameHostManager::ClearRFHsPendingShutdown));
430 ClearAllPowerSaveBlockers();
432 for (std::set<RenderWidgetHostImpl*>::iterator iter =
433 created_widgets_.begin(); iter != created_widgets_.end(); ++iter) {
434 (*iter)->DetachDelegate();
436 created_widgets_.clear();
438 // Clear out any JavaScript state.
439 if (dialog_manager_)
440 dialog_manager_->ResetDialogState(this);
442 if (color_chooser_info_.get())
443 color_chooser_info_->chooser->End();
445 NotifyDisconnected();
447 // Notify any observer that have a reference on this WebContents.
448 NotificationService::current()->Notify(
449 NOTIFICATION_WEB_CONTENTS_DESTROYED,
450 Source<WebContents>(this),
451 NotificationService::NoDetails());
453 // Destroy all frame tree nodes except for the root; this notifies observers.
454 frame_tree_.root()->ResetForNewProcess();
455 GetRenderManager()->ResetProxyHosts();
457 // Manually call the observer methods for the root frame tree node. It is
458 // necessary to manually delete all objects tracking navigations
459 // (NavigationHandle, NavigationRequest) for observers to be properly
460 // notified of these navigations stopping before the WebContents is
461 // destroyed.
462 RenderFrameHostManager* root = GetRenderManager();
464 if (root->pending_frame_host()) {
465 root->pending_frame_host()->SetRenderFrameCreated(false);
466 root->pending_frame_host()->SetNavigationHandle(
467 scoped_ptr<NavigationHandleImpl>());
469 root->current_frame_host()->SetRenderFrameCreated(false);
470 root->current_frame_host()->SetNavigationHandle(
471 scoped_ptr<NavigationHandleImpl>());
473 // PlzNavigate: clear up state specific to browser-side navigation.
474 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
475 switches::kEnableBrowserSideNavigation)) {
476 frame_tree_.root()->ResetNavigationRequest(false);
477 if (root->speculative_frame_host()) {
478 root->speculative_frame_host()->SetRenderFrameCreated(false);
479 root->speculative_frame_host()->SetNavigationHandle(
480 scoped_ptr<NavigationHandleImpl>());
484 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
485 FrameDeleted(root->current_frame_host()));
487 if (root->pending_render_view_host()) {
488 FOR_EACH_OBSERVER(WebContentsObserver,
489 observers_,
490 RenderViewDeleted(root->pending_render_view_host()));
493 FOR_EACH_OBSERVER(WebContentsObserver,
494 observers_,
495 RenderViewDeleted(root->current_host()));
497 FOR_EACH_OBSERVER(WebContentsObserver,
498 observers_,
499 WebContentsDestroyed());
501 FOR_EACH_OBSERVER(WebContentsObserver,
502 observers_,
503 ResetWebContents());
505 SetDelegate(NULL);
507 STLDeleteContainerPairSecondPointers(destruction_observers_.begin(),
508 destruction_observers_.end());
511 WebContentsImpl* WebContentsImpl::CreateWithOpener(
512 const WebContents::CreateParams& params,
513 FrameTreeNode* opener) {
514 TRACE_EVENT0("browser", "WebContentsImpl::CreateWithOpener");
515 WebContentsImpl* new_contents = new WebContentsImpl(params.browser_context);
517 if (!params.opener_suppressed && opener) {
518 new_contents->GetFrameTree()->root()->SetOpener(opener);
519 new_contents->created_with_opener_ = true;
522 // This may be true even when opener is null, such as when opening blocked
523 // popups.
524 if (params.created_with_opener)
525 new_contents->created_with_opener_ = true;
527 if (params.guest_delegate) {
528 // This makes |new_contents| act as a guest.
529 // For more info, see comment above class BrowserPluginGuest.
530 BrowserPluginGuest::Create(new_contents, params.guest_delegate);
531 // We are instantiating a WebContents for browser plugin. Set its subframe
532 // bit to true.
533 new_contents->is_subframe_ = true;
535 new_contents->Init(params);
536 return new_contents;
539 // static
540 std::vector<WebContentsImpl*> WebContentsImpl::GetAllWebContents() {
541 std::vector<WebContentsImpl*> result;
542 scoped_ptr<RenderWidgetHostIterator> widgets(
543 RenderWidgetHostImpl::GetRenderWidgetHosts());
544 std::set<WebContentsImpl*> web_contents_set;
545 while (RenderWidgetHost* rwh = widgets->GetNextHost()) {
546 if (!rwh->IsRenderView())
547 continue;
548 RenderViewHost* rvh = RenderViewHost::From(rwh);
549 if (!rvh)
550 continue;
551 WebContents* web_contents = WebContents::FromRenderViewHost(rvh);
552 if (!web_contents)
553 continue;
554 WebContentsImpl* wci = static_cast<WebContentsImpl*>(web_contents);
555 if (web_contents_set.find(wci) == web_contents_set.end()) {
556 web_contents_set.insert(wci);
557 result.push_back(wci);
560 return result;
563 // static
564 WebContentsImpl* WebContentsImpl::FromFrameTreeNode(
565 FrameTreeNode* frame_tree_node) {
566 return static_cast<WebContentsImpl*>(
567 WebContents::FromRenderFrameHost(frame_tree_node->current_frame_host()));
570 RenderFrameHostManager* WebContentsImpl::GetRenderManagerForTesting() {
571 return GetRenderManager();
574 bool WebContentsImpl::OnMessageReceived(RenderViewHost* render_view_host,
575 const IPC::Message& message) {
576 return OnMessageReceived(render_view_host, NULL, message);
579 bool WebContentsImpl::OnMessageReceived(RenderViewHost* render_view_host,
580 RenderFrameHost* render_frame_host,
581 const IPC::Message& message) {
582 DCHECK(render_view_host || render_frame_host);
583 if (GetWebUI() &&
584 static_cast<WebUIImpl*>(GetWebUI())->OnMessageReceived(message)) {
585 return true;
588 base::ObserverListBase<WebContentsObserver>::Iterator it(&observers_);
589 WebContentsObserver* observer;
590 if (render_frame_host) {
591 while ((observer = it.GetNext()) != NULL)
592 if (observer->OnMessageReceived(message, render_frame_host))
593 return true;
594 } else {
595 while ((observer = it.GetNext()) != NULL)
596 if (observer->OnMessageReceived(message))
597 return true;
600 // Message handlers should be aware of which
601 // RenderViewHost/RenderFrameHost sent the message, which is temporarily
602 // stored in render_(view|frame)_message_source_.
603 if (render_frame_host)
604 render_frame_message_source_ = render_frame_host;
605 else
606 render_view_message_source_ = render_view_host;
608 bool handled = true;
609 IPC_BEGIN_MESSAGE_MAP(WebContentsImpl, message)
610 IPC_MESSAGE_HANDLER(FrameHostMsg_DomOperationResponse,
611 OnDomOperationResponse)
612 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeThemeColor,
613 OnThemeColorChanged)
614 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishDocumentLoad,
615 OnDocumentLoadedInFrame)
616 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishLoad, OnDidFinishLoad)
617 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenColorChooser, OnOpenColorChooser)
618 IPC_MESSAGE_HANDLER(FrameHostMsg_EndColorChooser, OnEndColorChooser)
619 IPC_MESSAGE_HANDLER(FrameHostMsg_SetSelectedColorInColorChooser,
620 OnSetSelectedColorInColorChooser)
621 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPlayingNotification,
622 OnMediaPlayingNotification)
623 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPausedNotification,
624 OnMediaPausedNotification)
625 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFirstVisuallyNonEmptyPaint,
626 OnFirstVisuallyNonEmptyPaint)
627 IPC_MESSAGE_HANDLER(ViewHostMsg_DidLoadResourceFromMemoryCache,
628 OnDidLoadResourceFromMemoryCache)
629 IPC_MESSAGE_HANDLER(ViewHostMsg_DidDisplayInsecureContent,
630 OnDidDisplayInsecureContent)
631 IPC_MESSAGE_HANDLER(ViewHostMsg_DidRunInsecureContent,
632 OnDidRunInsecureContent)
633 IPC_MESSAGE_HANDLER(ViewHostMsg_GoToEntryAtOffset, OnGoToEntryAtOffset)
634 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateZoomLimits, OnUpdateZoomLimits)
635 IPC_MESSAGE_HANDLER(ViewHostMsg_EnumerateDirectory, OnEnumerateDirectory)
636 IPC_MESSAGE_HANDLER(FrameHostMsg_RegisterProtocolHandler,
637 OnRegisterProtocolHandler)
638 IPC_MESSAGE_HANDLER(FrameHostMsg_UnregisterProtocolHandler,
639 OnUnregisterProtocolHandler)
640 IPC_MESSAGE_HANDLER(ViewHostMsg_Find_Reply, OnFindReply)
641 IPC_MESSAGE_HANDLER(ViewHostMsg_AppCacheAccessed, OnAppCacheAccessed)
642 IPC_MESSAGE_HANDLER(ViewHostMsg_WebUISend, OnWebUISend)
643 #if defined(ENABLE_PLUGINS)
644 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceCreated,
645 OnPepperInstanceCreated)
646 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceDeleted,
647 OnPepperInstanceDeleted)
648 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung, OnPepperPluginHung)
649 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed, OnPluginCrashed)
650 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission,
651 OnRequestPpapiBrokerPermission)
652 IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_Attach,
653 OnBrowserPluginMessage(render_frame_host,
654 message))
655 #endif
656 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateFaviconURL, OnUpdateFaviconURL)
657 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowValidationMessage,
658 OnShowValidationMessage)
659 IPC_MESSAGE_HANDLER(ViewHostMsg_HideValidationMessage,
660 OnHideValidationMessage)
661 IPC_MESSAGE_HANDLER(ViewHostMsg_MoveValidationMessage,
662 OnMoveValidationMessage)
663 #if defined(OS_ANDROID)
664 IPC_MESSAGE_HANDLER(ViewHostMsg_FindMatchRects_Reply,
665 OnFindMatchRectsReply)
666 IPC_MESSAGE_HANDLER(ViewHostMsg_OpenDateTimeDialog,
667 OnOpenDateTimeDialog)
668 #endif
669 IPC_MESSAGE_UNHANDLED(handled = false)
670 IPC_END_MESSAGE_MAP()
671 render_view_message_source_ = NULL;
672 render_frame_message_source_ = NULL;
674 return handled;
677 bool WebContentsImpl::HasValidFrameSource() {
678 if (!render_frame_message_source_) {
679 DCHECK(render_view_message_source_);
680 bad_message::ReceivedBadMessage(GetRenderProcessHost(),
681 bad_message::WC_INVALID_FRAME_SOURCE);
682 return false;
685 return true;
688 void WebContentsImpl::RunFileChooser(
689 RenderViewHost* render_view_host,
690 const FileChooserParams& params) {
691 if (delegate_)
692 delegate_->RunFileChooser(this, params);
695 NavigationControllerImpl& WebContentsImpl::GetController() {
696 return controller_;
699 const NavigationControllerImpl& WebContentsImpl::GetController() const {
700 return controller_;
703 BrowserContext* WebContentsImpl::GetBrowserContext() const {
704 return controller_.GetBrowserContext();
707 const GURL& WebContentsImpl::GetURL() const {
708 // We may not have a navigation entry yet.
709 NavigationEntry* entry = controller_.GetVisibleEntry();
710 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
713 const GURL& WebContentsImpl::GetVisibleURL() const {
714 // We may not have a navigation entry yet.
715 NavigationEntry* entry = controller_.GetVisibleEntry();
716 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
719 const GURL& WebContentsImpl::GetLastCommittedURL() const {
720 // We may not have a navigation entry yet.
721 NavigationEntry* entry = controller_.GetLastCommittedEntry();
722 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
725 WebContentsDelegate* WebContentsImpl::GetDelegate() {
726 return delegate_;
729 void WebContentsImpl::SetDelegate(WebContentsDelegate* delegate) {
730 // TODO(cbentzel): remove this debugging code?
731 if (delegate == delegate_)
732 return;
733 if (delegate_)
734 delegate_->Detach(this);
735 delegate_ = delegate;
736 if (delegate_) {
737 delegate_->Attach(this);
738 // Ensure the visible RVH reflects the new delegate's preferences.
739 if (view_)
740 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
744 RenderProcessHost* WebContentsImpl::GetRenderProcessHost() const {
745 RenderViewHostImpl* host = GetRenderManager()->current_host();
746 return host ? host->GetProcess() : NULL;
749 RenderFrameHostImpl* WebContentsImpl::GetMainFrame() {
750 return frame_tree_.root()->current_frame_host();
753 RenderFrameHostImpl* WebContentsImpl::GetFocusedFrame() {
754 FrameTreeNode* focused_node = frame_tree_.GetFocusedFrame();
755 if (!focused_node)
756 return nullptr;
757 return focused_node->current_frame_host();
760 void WebContentsImpl::ForEachFrame(
761 const base::Callback<void(RenderFrameHost*)>& on_frame) {
762 frame_tree_.ForEach(base::Bind(&ForEachFrameInternal, on_frame));
765 void WebContentsImpl::SendToAllFrames(IPC::Message* message) {
766 ForEachFrame(base::Bind(&SendToAllFramesInternal, message));
767 delete message;
770 RenderViewHostImpl* WebContentsImpl::GetRenderViewHost() const {
771 return GetRenderManager()->current_host();
774 int WebContentsImpl::GetRoutingID() const {
775 if (!GetRenderViewHost())
776 return MSG_ROUTING_NONE;
778 return GetRenderViewHost()->GetRoutingID();
781 void WebContentsImpl::CancelActiveAndPendingDialogs() {
782 if (dialog_manager_)
783 dialog_manager_->CancelActiveAndPendingDialogs(this);
784 if (browser_plugin_embedder_)
785 browser_plugin_embedder_->CancelGuestDialogs();
788 int WebContentsImpl::GetFullscreenWidgetRoutingID() const {
789 return fullscreen_widget_routing_id_;
792 void WebContentsImpl::ClosePage() {
793 GetRenderViewHost()->ClosePage();
796 RenderWidgetHostView* WebContentsImpl::GetRenderWidgetHostView() const {
797 return GetRenderManager()->GetRenderWidgetHostView();
800 RenderWidgetHostView* WebContentsImpl::GetFullscreenRenderWidgetHostView()
801 const {
802 RenderWidgetHost* const widget_host =
803 RenderWidgetHostImpl::FromID(GetRenderProcessHost()->GetID(),
804 GetFullscreenWidgetRoutingID());
805 return widget_host ? widget_host->GetView() : NULL;
808 WebContentsView* WebContentsImpl::GetView() const {
809 return view_.get();
812 SkColor WebContentsImpl::GetThemeColor() const {
813 return theme_color_;
816 void WebContentsImpl::SetAccessibilityMode(AccessibilityMode mode) {
817 if (mode == accessibility_mode_)
818 return;
820 accessibility_mode_ = mode;
821 frame_tree_.ForEach(
822 base::Bind(&ForEachFrameInternal,
823 base::Bind(&SetAccessibilityModeOnFrame, mode)));
824 frame_tree_.ForEach(
825 base::Bind(&ForEachPendingFrameInternal,
826 base::Bind(&SetAccessibilityModeOnFrame, mode)));
829 void WebContentsImpl::AddAccessibilityMode(AccessibilityMode mode) {
830 SetAccessibilityMode(AddAccessibilityModeTo(accessibility_mode_, mode));
833 void WebContentsImpl::RemoveAccessibilityMode(AccessibilityMode mode) {
834 SetAccessibilityMode(RemoveAccessibilityModeFrom(accessibility_mode_, mode));
837 void WebContentsImpl::RequestAXTreeSnapshot(AXTreeSnapshotCallback callback) {
838 // TODO(dmazzoni): http://crbug.com/475608 This only returns the
839 // accessibility tree from the main frame and everything in the
840 // same site instance.
841 GetMainFrame()->RequestAXTreeSnapshot(callback);
844 WebUI* WebContentsImpl::CreateWebUI(const GURL& url) {
845 WebUIImpl* web_ui = new WebUIImpl(this);
846 WebUIController* controller = WebUIControllerFactoryRegistry::GetInstance()->
847 CreateWebUIControllerForURL(web_ui, url);
848 if (controller) {
849 web_ui->AddMessageHandler(new GenericHandler());
850 web_ui->SetController(controller);
851 return web_ui;
854 delete web_ui;
855 return NULL;
858 WebUI* WebContentsImpl::GetWebUI() const {
859 return GetRenderManager()->web_ui() ? GetRenderManager()->web_ui()
860 : GetRenderManager()->pending_web_ui();
863 WebUI* WebContentsImpl::GetCommittedWebUI() const {
864 return GetRenderManager()->web_ui();
867 void WebContentsImpl::SetUserAgentOverride(const std::string& override) {
868 if (GetUserAgentOverride() == override)
869 return;
871 renderer_preferences_.user_agent_override = override;
873 // Send the new override string to the renderer.
874 RenderViewHost* host = GetRenderViewHost();
875 if (host)
876 host->SyncRendererPrefs();
878 // Reload the page if a load is currently in progress to avoid having
879 // different parts of the page loaded using different user agents.
880 NavigationEntry* entry = controller_.GetVisibleEntry();
881 if (is_loading_ && entry != NULL && entry->GetIsOverridingUserAgent())
882 controller_.ReloadIgnoringCache(true);
884 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
885 UserAgentOverrideSet(override));
888 const std::string& WebContentsImpl::GetUserAgentOverride() const {
889 return renderer_preferences_.user_agent_override;
892 void WebContentsImpl::EnableTreeOnlyAccessibilityMode() {
893 if (GetAccessibilityMode() == AccessibilityModeTreeOnly)
894 ForEachFrame(base::Bind(&ResetAccessibility));
895 else
896 AddAccessibilityMode(AccessibilityModeTreeOnly);
899 bool WebContentsImpl::IsTreeOnlyAccessibilityModeForTesting() const {
900 return accessibility_mode_ == AccessibilityModeTreeOnly;
903 bool WebContentsImpl::IsFullAccessibilityModeForTesting() const {
904 return accessibility_mode_ == AccessibilityModeComplete;
907 #if defined(OS_WIN)
908 void WebContentsImpl::SetParentNativeViewAccessible(
909 gfx::NativeViewAccessible accessible_parent) {
910 accessible_parent_ = accessible_parent;
911 RenderFrameHostImpl* rfh = GetMainFrame();
912 if (rfh)
913 rfh->SetParentNativeViewAccessible(accessible_parent);
915 #endif
917 const base::string16& WebContentsImpl::GetTitle() const {
918 // Transient entries take precedence. They are used for interstitial pages
919 // that are shown on top of existing pages.
920 NavigationEntry* entry = controller_.GetTransientEntry();
921 std::string accept_languages =
922 GetContentClient()->browser()->GetAcceptLangs(
923 GetBrowserContext());
924 if (entry) {
925 return entry->GetTitleForDisplay(accept_languages);
927 WebUI* our_web_ui = GetRenderManager()->pending_web_ui() ?
928 GetRenderManager()->pending_web_ui() : GetRenderManager()->web_ui();
929 if (our_web_ui) {
930 // Don't override the title in view source mode.
931 entry = controller_.GetVisibleEntry();
932 if (!(entry && entry->IsViewSourceMode())) {
933 // Give the Web UI the chance to override our title.
934 const base::string16& title = our_web_ui->GetOverriddenTitle();
935 if (!title.empty())
936 return title;
940 // We use the title for the last committed entry rather than a pending
941 // navigation entry. For example, when the user types in a URL, we want to
942 // keep the old page's title until the new load has committed and we get a new
943 // title.
944 entry = controller_.GetLastCommittedEntry();
946 // We make an exception for initial navigations.
947 if (controller_.IsInitialNavigation()) {
948 // We only want to use the title from the visible entry in one of two cases:
949 // 1. There's already a committed entry for an initial navigation, in which
950 // case we are doing a history navigation in a new tab (e.g., Ctrl+Back).
951 // 2. The pending entry has been explicitly assigned a title to display.
953 // If there's no last committed entry and no assigned title, we should fall
954 // back to |page_title_when_no_navigation_entry_| rather than showing the
955 // URL.
956 if (entry ||
957 (controller_.GetVisibleEntry() &&
958 !controller_.GetVisibleEntry()->GetTitle().empty())) {
959 entry = controller_.GetVisibleEntry();
963 if (entry) {
964 return entry->GetTitleForDisplay(accept_languages);
967 // |page_title_when_no_navigation_entry_| is finally used
968 // if no title cannot be retrieved.
969 return page_title_when_no_navigation_entry_;
972 int32 WebContentsImpl::GetMaxPageID() {
973 return GetMaxPageIDForSiteInstance(GetSiteInstance());
976 int32 WebContentsImpl::GetMaxPageIDForSiteInstance(
977 SiteInstance* site_instance) {
978 if (max_page_ids_.find(site_instance->GetId()) == max_page_ids_.end())
979 max_page_ids_[site_instance->GetId()] = -1;
981 return max_page_ids_[site_instance->GetId()];
984 void WebContentsImpl::UpdateMaxPageID(int32 page_id) {
985 UpdateMaxPageIDForSiteInstance(GetSiteInstance(), page_id);
988 void WebContentsImpl::UpdateMaxPageIDForSiteInstance(
989 SiteInstance* site_instance, int32 page_id) {
990 if (GetMaxPageIDForSiteInstance(site_instance) < page_id)
991 max_page_ids_[site_instance->GetId()] = page_id;
994 void WebContentsImpl::CopyMaxPageIDsFrom(WebContents* web_contents) {
995 WebContentsImpl* contents = static_cast<WebContentsImpl*>(web_contents);
996 max_page_ids_ = contents->max_page_ids_;
999 SiteInstanceImpl* WebContentsImpl::GetSiteInstance() const {
1000 return GetRenderManager()->current_host()->GetSiteInstance();
1003 SiteInstanceImpl* WebContentsImpl::GetPendingSiteInstance() const {
1004 RenderViewHostImpl* dest_rvh =
1005 GetRenderManager()->pending_render_view_host() ?
1006 GetRenderManager()->pending_render_view_host() :
1007 GetRenderManager()->current_host();
1008 return dest_rvh->GetSiteInstance();
1011 bool WebContentsImpl::IsLoading() const {
1012 return is_loading_;
1015 bool WebContentsImpl::IsLoadingToDifferentDocument() const {
1016 return is_loading_ && is_load_to_different_document_;
1019 bool WebContentsImpl::IsWaitingForResponse() const {
1020 return waiting_for_response_ && is_load_to_different_document_;
1023 const net::LoadStateWithParam& WebContentsImpl::GetLoadState() const {
1024 return load_state_;
1027 const base::string16& WebContentsImpl::GetLoadStateHost() const {
1028 return load_state_host_;
1031 uint64 WebContentsImpl::GetUploadSize() const {
1032 return upload_size_;
1035 uint64 WebContentsImpl::GetUploadPosition() const {
1036 return upload_position_;
1039 std::set<GURL> WebContentsImpl::GetSitesInTab() const {
1040 std::set<GURL> sites;
1041 frame_tree_.ForEach(base::Bind(&CollectSites,
1042 base::Unretained(GetBrowserContext()),
1043 base::Unretained(&sites)));
1044 return sites;
1047 const std::string& WebContentsImpl::GetEncoding() const {
1048 return canonical_encoding_;
1051 bool WebContentsImpl::DisplayedInsecureContent() const {
1052 return displayed_insecure_content_;
1055 void WebContentsImpl::IncrementCapturerCount(const gfx::Size& capture_size) {
1056 DCHECK(!is_being_destroyed_);
1057 ++capturer_count_;
1058 DVLOG(1) << "There are now " << capturer_count_
1059 << " capturing(s) of WebContentsImpl@" << this;
1061 // Note: This provides a hint to upstream code to size the views optimally
1062 // for quality (e.g., to avoid scaling).
1063 if (!capture_size.IsEmpty() && preferred_size_for_capture_.IsEmpty()) {
1064 preferred_size_for_capture_ = capture_size;
1065 OnPreferredSizeChanged(preferred_size_);
1068 // Ensure that all views are un-occluded before capture begins.
1069 WasUnOccluded();
1072 void WebContentsImpl::DecrementCapturerCount() {
1073 --capturer_count_;
1074 DVLOG(1) << "There are now " << capturer_count_
1075 << " capturing(s) of WebContentsImpl@" << this;
1076 DCHECK_LE(0, capturer_count_);
1078 if (is_being_destroyed_)
1079 return;
1081 if (capturer_count_ == 0) {
1082 const gfx::Size old_size = preferred_size_for_capture_;
1083 preferred_size_for_capture_ = gfx::Size();
1084 OnPreferredSizeChanged(old_size);
1087 if (IsHidden()) {
1088 DVLOG(1) << "Executing delayed WasHidden().";
1089 WasHidden();
1093 int WebContentsImpl::GetCapturerCount() const {
1094 return capturer_count_;
1097 bool WebContentsImpl::IsAudioMuted() const {
1098 return audio_muter_.get() && audio_muter_->is_muting();
1101 void WebContentsImpl::SetAudioMuted(bool mute) {
1102 DVLOG(1) << "SetAudioMuted(mute=" << mute << "), was " << IsAudioMuted()
1103 << " for WebContentsImpl@" << this;
1105 if (mute == IsAudioMuted())
1106 return;
1108 if (mute) {
1109 if (!audio_muter_)
1110 audio_muter_.reset(new WebContentsAudioMuter(this));
1111 audio_muter_->StartMuting();
1112 } else {
1113 DCHECK(audio_muter_);
1114 audio_muter_->StopMuting();
1117 // Notification for UI updates in response to the changed muting state.
1118 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
1121 bool WebContentsImpl::IsCrashed() const {
1122 return (crashed_status_ == base::TERMINATION_STATUS_PROCESS_CRASHED ||
1123 crashed_status_ == base::TERMINATION_STATUS_ABNORMAL_TERMINATION ||
1124 crashed_status_ == base::TERMINATION_STATUS_PROCESS_WAS_KILLED
1125 #if defined(OS_CHROMEOS)
1127 crashed_status_ == base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM
1128 #endif
1132 void WebContentsImpl::SetIsCrashed(base::TerminationStatus status,
1133 int error_code) {
1134 if (status == crashed_status_)
1135 return;
1137 crashed_status_ = status;
1138 crashed_error_code_ = error_code;
1139 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
1142 base::TerminationStatus WebContentsImpl::GetCrashedStatus() const {
1143 return crashed_status_;
1146 bool WebContentsImpl::IsBeingDestroyed() const {
1147 return is_being_destroyed_;
1150 void WebContentsImpl::NotifyNavigationStateChanged(
1151 InvalidateTypes changed_flags) {
1152 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1153 // is fixed.
1154 tracked_objects::ScopedTracker tracking_profile(
1155 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1156 "466285 WebContentsImpl::NotifyNavigationStateChanged"));
1157 // Create and release the audio power save blocker depending on whether the
1158 // tab is actively producing audio or not.
1159 if ((changed_flags & INVALIDATE_TYPE_TAB) &&
1160 audio_state_provider_->IsAudioStateAvailable()) {
1161 if (WasRecentlyAudible()) {
1162 if (!audio_power_save_blocker_)
1163 CreateAudioPowerSaveBlocker();
1164 } else {
1165 audio_power_save_blocker_.reset();
1169 if (delegate_)
1170 delegate_->NavigationStateChanged(this, changed_flags);
1173 base::TimeTicks WebContentsImpl::GetLastActiveTime() const {
1174 return last_active_time_;
1177 void WebContentsImpl::SetLastActiveTime(base::TimeTicks last_active_time) {
1178 last_active_time_ = last_active_time;
1181 void WebContentsImpl::WasShown() {
1182 controller_.SetActive(true);
1184 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1185 if (view) {
1186 view->Show();
1187 #if defined(OS_MACOSX)
1188 view->SetActive(true);
1189 #endif
1193 last_active_time_ = base::TimeTicks::Now();
1195 // The resize rect might have changed while this was inactive -- send the new
1196 // one to make sure it's up to date.
1197 RenderViewHostImpl* rvh = GetRenderViewHost();
1198 if (rvh)
1199 rvh->ResizeRectChanged(GetRootWindowResizerRect());
1201 // Restore power save blocker if there are active video players running.
1202 if (!active_video_players_.empty() && !video_power_save_blocker_)
1203 CreateVideoPowerSaveBlocker();
1205 FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasShown());
1207 should_normally_be_visible_ = true;
1210 void WebContentsImpl::WasHidden() {
1211 // If there are entities capturing screenshots or video (e.g., mirroring),
1212 // don't activate the "disable rendering" optimization.
1213 if (capturer_count_ == 0) {
1214 // |GetRenderViewHost()| can be NULL if the user middle clicks a link to
1215 // open a tab in the background, then closes the tab before selecting it.
1216 // This is because closing the tab calls WebContentsImpl::Destroy(), which
1217 // removes the |GetRenderViewHost()|; then when we actually destroy the
1218 // window, OnWindowPosChanged() notices and calls WasHidden() (which
1219 // calls us).
1220 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1221 if (view)
1222 view->Hide();
1225 // Release any video power save blockers held as video is not visible.
1226 video_power_save_blocker_.reset();
1229 FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasHidden());
1231 should_normally_be_visible_ = false;
1234 void WebContentsImpl::WasOccluded() {
1235 if (capturer_count_ > 0)
1236 return;
1238 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1239 if (view)
1240 view->WasOccluded();
1244 void WebContentsImpl::WasUnOccluded() {
1245 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1246 if (view)
1247 view->WasUnOccluded();
1251 bool WebContentsImpl::NeedToFireBeforeUnload() {
1252 // TODO(creis): Should we fire even for interstitial pages?
1253 return WillNotifyDisconnection() && !ShowingInterstitialPage() &&
1254 !GetRenderViewHost()->SuddenTerminationAllowed();
1257 void WebContentsImpl::DispatchBeforeUnload(bool for_cross_site_transition) {
1258 GetMainFrame()->DispatchBeforeUnload(for_cross_site_transition);
1261 void WebContentsImpl::AttachToOuterWebContentsFrame(
1262 WebContents* outer_web_contents,
1263 RenderFrameHost* outer_contents_frame) {
1264 CHECK(BrowserPluginGuestMode::UseCrossProcessFramesForGuests());
1265 // Create a link to our outer WebContents.
1266 node_.reset(new WebContentsTreeNode());
1267 node_->ConnectToOuterWebContents(
1268 static_cast<WebContentsImpl*>(outer_web_contents),
1269 static_cast<RenderFrameHostImpl*>(outer_contents_frame));
1271 DCHECK(outer_contents_frame);
1273 // Create a proxy in top-level RenderFrameHostManager, pointing to the
1274 // SiteInstance of the outer WebContents. The proxy will be used to send
1275 // postMessage to the inner WebContents.
1276 GetRenderManager()->CreateOuterDelegateProxy(
1277 outer_contents_frame->GetSiteInstance(),
1278 static_cast<RenderFrameHostImpl*>(outer_contents_frame));
1280 GetRenderManager()->SetRWHViewForInnerContents(
1281 GetRenderManager()->GetRenderWidgetHostView());
1284 void WebContentsImpl::Stop() {
1285 frame_tree_.ForEach(base::Bind(&FrameTreeNode::StopLoading));
1286 FOR_EACH_OBSERVER(WebContentsObserver, observers_, NavigationStopped());
1289 WebContents* WebContentsImpl::Clone() {
1290 // We use our current SiteInstance since the cloned entry will use it anyway.
1291 // We pass our own opener so that the cloned page can access it if it was set
1292 // before.
1293 CreateParams create_params(GetBrowserContext(), GetSiteInstance());
1294 create_params.initial_size = GetContainerBounds().size();
1295 WebContentsImpl* tc =
1296 CreateWithOpener(create_params, frame_tree_.root()->opener());
1297 tc->GetController().CopyStateFrom(controller_);
1298 FOR_EACH_OBSERVER(WebContentsObserver,
1299 observers_,
1300 DidCloneToNewWebContents(this, tc));
1301 return tc;
1304 void WebContentsImpl::Observe(int type,
1305 const NotificationSource& source,
1306 const NotificationDetails& details) {
1307 switch (type) {
1308 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: {
1309 RenderWidgetHost* host = Source<RenderWidgetHost>(source).ptr();
1310 RenderWidgetHostView* view = host->GetView();
1311 if (view == GetFullscreenRenderWidgetHostView()) {
1312 // We cannot just call view_->RestoreFocus() here. On some platforms,
1313 // attempting to focus the currently-invisible WebContentsView will be
1314 // flat-out ignored. Therefore, this boolean is used to track whether
1315 // we will request focus after the fullscreen widget has been
1316 // destroyed.
1317 fullscreen_widget_had_focus_at_shutdown_ = (view && view->HasFocus());
1318 } else {
1319 for (PendingWidgetViews::iterator i = pending_widget_views_.begin();
1320 i != pending_widget_views_.end(); ++i) {
1321 if (host->GetView() == i->second) {
1322 pending_widget_views_.erase(i);
1323 break;
1327 break;
1329 default:
1330 NOTREACHED();
1334 WebContents* WebContentsImpl::GetWebContents() {
1335 return this;
1338 void WebContentsImpl::Init(const WebContents::CreateParams& params) {
1339 // This is set before initializing the render manager since
1340 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
1341 // it should be hidden.
1342 should_normally_be_visible_ = !params.initially_hidden;
1344 // Either both routing ids can be given, or neither can be.
1345 DCHECK((params.routing_id == MSG_ROUTING_NONE &&
1346 params.main_frame_routing_id == MSG_ROUTING_NONE) ||
1347 (params.routing_id != MSG_ROUTING_NONE &&
1348 params.main_frame_routing_id != MSG_ROUTING_NONE));
1349 GetRenderManager()->Init(
1350 params.browser_context, params.site_instance, params.routing_id,
1351 params.main_frame_routing_id);
1352 frame_tree_.root()->SetFrameName(params.main_frame_name);
1354 WebContentsViewDelegate* delegate =
1355 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
1357 if (browser_plugin_guest_ &&
1358 !BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
1359 scoped_ptr<WebContentsView> platform_view(CreateWebContentsView(
1360 this, delegate, &render_view_host_delegate_view_));
1362 WebContentsViewGuest* rv = new WebContentsViewGuest(
1363 this, browser_plugin_guest_.get(), platform_view.Pass(),
1364 render_view_host_delegate_view_);
1365 render_view_host_delegate_view_ = rv;
1366 view_.reset(rv);
1367 } else {
1368 // Regular WebContentsView.
1369 view_.reset(CreateWebContentsView(
1370 this, delegate, &render_view_host_delegate_view_));
1372 CHECK(render_view_host_delegate_view_);
1373 CHECK(view_.get());
1375 gfx::Size initial_size = params.initial_size;
1376 view_->CreateView(initial_size, params.context);
1378 #if defined(ENABLE_PLUGINS)
1379 plugin_content_origin_whitelist_.reset(
1380 new PluginContentOriginWhitelist(this));
1381 #endif
1383 registrar_.Add(this,
1384 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1385 NotificationService::AllBrowserContextsAndSources());
1387 screen_orientation_dispatcher_host_.reset(
1388 new ScreenOrientationDispatcherHostImpl(this));
1390 manifest_manager_host_.reset(new ManifestManagerHost(this));
1392 #if defined(OS_ANDROID)
1393 date_time_chooser_.reset(new DateTimeChooserAndroid());
1394 #endif
1396 // BrowserPluginGuest::Init needs to be called after this WebContents has
1397 // a RenderWidgetHostViewGuest. That is, |view_->CreateView| above.
1398 if (browser_plugin_guest_)
1399 browser_plugin_guest_->Init();
1401 for (size_t i = 0; i < g_created_callbacks.Get().size(); i++)
1402 g_created_callbacks.Get().at(i).Run(this);
1404 // If the WebContents creation was renderer-initiated, it means that the
1405 // corresponding RenderView and main RenderFrame have already been created.
1406 // Ensure observers are notified about this.
1407 if (params.renderer_initiated_creation) {
1408 GetRenderViewHost()->set_renderer_initialized(true);
1409 RenderViewCreated(GetRenderViewHost());
1410 GetRenderManager()->current_frame_host()->SetRenderFrameCreated(true);
1413 // Ensure that observers are notified of the creation of this WebContents's
1414 // main RenderFrameHost. It must be done here for main frames, since the
1415 // NotifySwappedFromRenderManager expects view_ to already be created and that
1416 // happens after RenderFrameHostManager::Init.
1417 NotifySwappedFromRenderManager(
1418 nullptr, GetRenderManager()->current_frame_host(), true);
1421 void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl* web_contents) {
1422 RemoveDestructionObserver(web_contents);
1424 // Clear a pending contents that has been closed before being shown.
1425 for (PendingContents::iterator iter = pending_contents_.begin();
1426 iter != pending_contents_.end();
1427 ++iter) {
1428 if (iter->second != web_contents)
1429 continue;
1430 pending_contents_.erase(iter);
1431 return;
1433 NOTREACHED();
1436 void WebContentsImpl::AddDestructionObserver(WebContentsImpl* web_contents) {
1437 if (!ContainsKey(destruction_observers_, web_contents)) {
1438 destruction_observers_[web_contents] =
1439 new DestructionObserver(this, web_contents);
1443 void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl* web_contents) {
1444 DestructionObservers::iterator iter =
1445 destruction_observers_.find(web_contents);
1446 if (iter != destruction_observers_.end()) {
1447 delete destruction_observers_[web_contents];
1448 destruction_observers_.erase(iter);
1452 void WebContentsImpl::AddObserver(WebContentsObserver* observer) {
1453 observers_.AddObserver(observer);
1456 void WebContentsImpl::RemoveObserver(WebContentsObserver* observer) {
1457 observers_.RemoveObserver(observer);
1460 std::set<RenderWidgetHostView*>
1461 WebContentsImpl::GetRenderWidgetHostViewsInTree() {
1462 std::set<RenderWidgetHostView*> set;
1463 if (ShowingInterstitialPage()) {
1464 set.insert(GetRenderWidgetHostView());
1465 } else {
1466 ForEachFrame(
1467 base::Bind(&AddRenderWidgetHostViewToSet, base::Unretained(&set)));
1469 return set;
1472 void WebContentsImpl::Activate() {
1473 if (delegate_)
1474 delegate_->ActivateContents(this);
1477 void WebContentsImpl::Deactivate() {
1478 if (delegate_)
1479 delegate_->DeactivateContents(this);
1482 void WebContentsImpl::LostCapture() {
1483 if (delegate_)
1484 delegate_->LostCapture();
1487 void WebContentsImpl::RenderWidgetDeleted(
1488 RenderWidgetHostImpl* render_widget_host) {
1489 if (is_being_destroyed_) {
1490 // |created_widgets_| might have been destroyed.
1491 return;
1494 std::set<RenderWidgetHostImpl*>::iterator iter =
1495 created_widgets_.find(render_widget_host);
1496 if (iter != created_widgets_.end())
1497 created_widgets_.erase(iter);
1499 if (render_widget_host &&
1500 render_widget_host->GetRoutingID() == fullscreen_widget_routing_id_) {
1501 if (delegate_ && delegate_->EmbedsFullscreenWidget())
1502 delegate_->ExitFullscreenModeForTab(this);
1503 FOR_EACH_OBSERVER(WebContentsObserver,
1504 observers_,
1505 DidDestroyFullscreenWidget(
1506 fullscreen_widget_routing_id_));
1507 fullscreen_widget_routing_id_ = MSG_ROUTING_NONE;
1508 if (fullscreen_widget_had_focus_at_shutdown_)
1509 view_->RestoreFocus();
1513 void WebContentsImpl::RenderWidgetGotFocus(
1514 RenderWidgetHostImpl* render_widget_host) {
1515 // Notify the observers if an embedded fullscreen widget was focused.
1516 if (delegate_ && render_widget_host && delegate_->EmbedsFullscreenWidget() &&
1517 render_widget_host->GetView() == GetFullscreenRenderWidgetHostView()) {
1518 NotifyWebContentsFocused();
1522 void WebContentsImpl::RenderWidgetWasResized(
1523 RenderWidgetHostImpl* render_widget_host,
1524 bool width_changed) {
1525 RenderFrameHostImpl* rfh = GetMainFrame();
1526 if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
1527 return;
1529 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1530 MainFrameWasResized(width_changed));
1533 void WebContentsImpl::ScreenInfoChanged() {
1534 if (browser_plugin_embedder_)
1535 browser_plugin_embedder_->ScreenInfoChanged();
1538 bool WebContentsImpl::PreHandleKeyboardEvent(
1539 const NativeWebKeyboardEvent& event,
1540 bool* is_keyboard_shortcut) {
1541 return delegate_ &&
1542 delegate_->PreHandleKeyboardEvent(this, event, is_keyboard_shortcut);
1545 void WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
1546 if (browser_plugin_embedder_ &&
1547 browser_plugin_embedder_->HandleKeyboardEvent(event)) {
1548 return;
1550 if (delegate_)
1551 delegate_->HandleKeyboardEvent(this, event);
1554 bool WebContentsImpl::HandleWheelEvent(
1555 const blink::WebMouseWheelEvent& event) {
1556 #if !defined(OS_MACOSX)
1557 // On platforms other than Mac, control+mousewheel may change zoom. On Mac,
1558 // this isn't done for two reasons:
1559 // -the OS already has a gesture to do this through pinch-zoom
1560 // -if a user starts an inertial scroll, let's go, and presses control
1561 // (i.e. control+tab) then the OS's buffered scroll events will come in
1562 // with control key set which isn't what the user wants
1563 if (delegate_ && event.wheelTicksY &&
1564 (event.modifiers & blink::WebInputEvent::ControlKey) &&
1565 !event.canScroll) {
1566 delegate_->ContentsZoomChange(event.wheelTicksY > 0);
1567 return true;
1569 #endif
1570 return false;
1573 bool WebContentsImpl::PreHandleGestureEvent(
1574 const blink::WebGestureEvent& event) {
1575 return delegate_ && delegate_->PreHandleGestureEvent(this, event);
1578 void WebContentsImpl::EnterFullscreenMode(const GURL& origin) {
1579 // This method is being called to enter renderer-initiated fullscreen mode.
1580 // Make sure any existing fullscreen widget is shut down first.
1581 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
1582 if (widget_view)
1583 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())->Shutdown();
1585 if (delegate_)
1586 delegate_->EnterFullscreenModeForTab(this, origin);
1588 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1589 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1592 void WebContentsImpl::ExitFullscreenMode() {
1593 // This method is being called to leave renderer-initiated fullscreen mode.
1594 // Make sure any existing fullscreen widget is shut down first.
1595 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
1596 if (widget_view)
1597 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())->Shutdown();
1599 #if defined(OS_ANDROID)
1600 ContentVideoView* video_view = ContentVideoView::GetInstance();
1601 if (video_view != NULL)
1602 video_view->OnExitFullscreen();
1603 #endif
1605 if (delegate_)
1606 delegate_->ExitFullscreenModeForTab(this);
1608 // Ensure web contents exit fullscreen state by sending a resize message,
1609 // which includes the fullscreen state. This is required for the situation
1610 // of the browser moving the view into a fullscreen state "browser fullscreen"
1611 // and then the contents entering "tab fullscreen". Exiting the contents
1612 // "tab fullscreen" then won't have the side effect of the view resizing,
1613 // hence the explicit call here is required.
1614 if (RenderWidgetHostView* rwh_view = GetRenderWidgetHostView()) {
1615 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
1616 render_widget_host->WasResized();
1619 FOR_EACH_OBSERVER(WebContentsObserver,
1620 observers_,
1621 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1624 bool WebContentsImpl::IsFullscreenForCurrentTab() const {
1625 return delegate_ ? delegate_->IsFullscreenForTabOrPending(this) : false;
1628 blink::WebDisplayMode WebContentsImpl::GetDisplayMode() const {
1629 return delegate_ ? delegate_->GetDisplayMode(this)
1630 : blink::WebDisplayModeBrowser;
1633 void WebContentsImpl::RequestToLockMouse(bool user_gesture,
1634 bool last_unlocked_by_target) {
1635 if (delegate_) {
1636 delegate_->RequestToLockMouse(this, user_gesture, last_unlocked_by_target);
1637 } else {
1638 GotResponseToLockMouseRequest(false);
1642 void WebContentsImpl::LostMouseLock() {
1643 if (delegate_)
1644 delegate_->LostMouseLock();
1647 void WebContentsImpl::CreateNewWindow(
1648 SiteInstance* source_site_instance,
1649 int route_id,
1650 int main_frame_route_id,
1651 const ViewHostMsg_CreateWindow_Params& params,
1652 SessionStorageNamespace* session_storage_namespace) {
1653 // We usually create the new window in the same BrowsingInstance (group of
1654 // script-related windows), by passing in the current SiteInstance. However,
1655 // if the opener is being suppressed (in a non-guest), we create a new
1656 // SiteInstance in its own BrowsingInstance.
1657 bool is_guest = BrowserPluginGuest::IsGuest(this);
1659 if (is_guest && BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
1660 // TODO(lazyboy): CreateNewWindow doesn't work for OOPIF-based <webview>
1661 // yet.
1662 NOTREACHED();
1665 // If the opener is to be suppressed, the new window can be in any process.
1666 // Since routing ids are process specific, we must not have one passed in
1667 // as argument here.
1668 DCHECK(!params.opener_suppressed || route_id == MSG_ROUTING_NONE);
1670 scoped_refptr<SiteInstance> site_instance =
1671 params.opener_suppressed && !is_guest
1672 ? SiteInstance::CreateForURL(GetBrowserContext(), params.target_url)
1673 : source_site_instance;
1675 // A message to create a new window can only come from a process for a frame
1676 // in this WebContents' FrameTree. If any other process sends the request, it
1677 // is invalid and the process must be terminated.
1678 int render_process_id = source_site_instance->GetProcess()->GetID();
1679 bool did_match_process = false;
1680 frame_tree_.ForEach(
1681 base::Bind(&FindMatchingProcess, render_process_id, &did_match_process));
1682 if (!did_match_process) {
1683 RenderProcessHost* rph = source_site_instance->GetProcess();
1684 base::ProcessHandle process_handle = rph->GetHandle();
1685 if (process_handle != base::kNullProcessHandle) {
1686 RecordAction(
1687 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWindow"));
1688 rph->Shutdown(RESULT_CODE_KILLED, false);
1690 return;
1693 // We must assign the SessionStorageNamespace before calling Init().
1695 // http://crbug.com/142685
1696 const std::string& partition_id =
1697 GetContentClient()->browser()->
1698 GetStoragePartitionIdForSite(GetBrowserContext(),
1699 site_instance->GetSiteURL());
1700 StoragePartition* partition = BrowserContext::GetStoragePartition(
1701 GetBrowserContext(), site_instance.get());
1702 DOMStorageContextWrapper* dom_storage_context =
1703 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
1704 SessionStorageNamespaceImpl* session_storage_namespace_impl =
1705 static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
1706 CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
1708 if (delegate_ &&
1709 !delegate_->ShouldCreateWebContents(this,
1710 route_id,
1711 main_frame_route_id,
1712 params.window_container_type,
1713 params.frame_name,
1714 params.target_url,
1715 partition_id,
1716 session_storage_namespace)) {
1717 if (route_id != MSG_ROUTING_NONE &&
1718 !RenderViewHost::FromID(render_process_id, route_id)) {
1719 // If the embedder didn't create a WebContents for this route, we need to
1720 // delete the RenderView that had already been created.
1721 Send(new ViewMsg_Close(route_id));
1723 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(route_id);
1724 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(
1725 main_frame_route_id);
1726 return;
1729 // Create the new web contents. This will automatically create the new
1730 // WebContentsView. In the future, we may want to create the view separately.
1731 CreateParams create_params(GetBrowserContext(), site_instance.get());
1732 create_params.routing_id = route_id;
1733 create_params.main_frame_routing_id = main_frame_route_id;
1734 create_params.main_frame_name = params.frame_name;
1735 create_params.opener_render_process_id = render_process_id;
1736 create_params.opener_render_frame_id = params.opener_render_frame_id;
1737 create_params.opener_suppressed = params.opener_suppressed;
1738 if (params.disposition == NEW_BACKGROUND_TAB)
1739 create_params.initially_hidden = true;
1740 create_params.renderer_initiated_creation =
1741 main_frame_route_id != MSG_ROUTING_NONE;
1743 WebContentsImpl* new_contents = NULL;
1744 if (!is_guest) {
1745 create_params.context = view_->GetNativeView();
1746 create_params.initial_size = GetContainerBounds().size();
1747 new_contents = static_cast<WebContentsImpl*>(
1748 WebContents::Create(create_params));
1749 } else {
1750 new_contents = GetBrowserPluginGuest()->CreateNewGuestWindow(create_params);
1752 new_contents->GetController().SetSessionStorageNamespace(
1753 partition_id,
1754 session_storage_namespace);
1756 // If the new frame has a name, make sure any SiteInstances that can find
1757 // this named frame have proxies for it. Must be called after
1758 // SetSessionStorageNamespace, since this calls CreateRenderView, which uses
1759 // GetSessionStorageNamespace.
1760 if (!params.frame_name.empty())
1761 new_contents->GetRenderManager()->CreateProxiesForNewNamedFrame();
1763 // Save the window for later if we're not suppressing the opener (since it
1764 // will be shown immediately).
1765 if (!params.opener_suppressed) {
1766 if (!is_guest) {
1767 WebContentsView* new_view = new_contents->view_.get();
1769 // TODO(brettw): It seems bogus that we have to call this function on the
1770 // newly created object and give it one of its own member variables.
1771 new_view->CreateViewForWidget(new_contents->GetRenderViewHost(), false);
1773 // Save the created window associated with the route so we can show it
1774 // later.
1775 DCHECK_NE(MSG_ROUTING_NONE, route_id);
1776 pending_contents_[route_id] = new_contents;
1777 AddDestructionObserver(new_contents);
1780 if (delegate_) {
1781 delegate_->WebContentsCreated(
1782 this, params.opener_render_frame_id, params.frame_name,
1783 params.target_url, new_contents);
1786 if (params.opener_suppressed) {
1787 // When the opener is suppressed, the original renderer cannot access the
1788 // new window. As a result, we need to show and navigate the window here.
1789 bool was_blocked = false;
1790 if (delegate_) {
1791 gfx::Rect initial_rect;
1792 delegate_->AddNewContents(
1793 this, new_contents, params.disposition, initial_rect,
1794 params.user_gesture, &was_blocked);
1796 if (!was_blocked) {
1797 OpenURLParams open_params(params.target_url,
1798 Referrer(),
1799 CURRENT_TAB,
1800 ui::PAGE_TRANSITION_LINK,
1801 true /* is_renderer_initiated */);
1802 open_params.user_gesture = params.user_gesture;
1804 if (delegate_ && !is_guest &&
1805 !delegate_->ShouldResumeRequestsForCreatedWindow()) {
1806 // We are in asynchronous add new contents path, delay opening url
1807 new_contents->delayed_open_url_params_.reset(
1808 new OpenURLParams(open_params));
1809 } else {
1810 new_contents->OpenURL(open_params);
1816 void WebContentsImpl::CreateNewWidget(int render_process_id,
1817 int route_id,
1818 blink::WebPopupType popup_type) {
1819 CreateNewWidget(render_process_id, route_id, false, popup_type);
1822 void WebContentsImpl::CreateNewFullscreenWidget(int render_process_id,
1823 int route_id) {
1824 CreateNewWidget(render_process_id, route_id, true, blink::WebPopupTypeNone);
1827 void WebContentsImpl::CreateNewWidget(int render_process_id,
1828 int route_id,
1829 bool is_fullscreen,
1830 blink::WebPopupType popup_type) {
1831 RenderProcessHost* process = GetRenderProcessHost();
1832 // A message to create a new widget can only come from the active process for
1833 // this WebContentsImpl instance. If any other process sends the request,
1834 // it is invalid and the process must be terminated.
1835 if (process->GetID() != render_process_id) {
1836 RenderProcessHost* rph = RenderProcessHost::FromID(render_process_id);
1837 base::ProcessHandle process_handle = rph->GetHandle();
1838 if (process_handle != base::kNullProcessHandle) {
1839 RecordAction(
1840 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWidget"));
1841 rph->Shutdown(RESULT_CODE_KILLED, false);
1843 return;
1846 RenderWidgetHostImpl* widget_host =
1847 new RenderWidgetHostImpl(this, process, route_id, IsHidden());
1848 created_widgets_.insert(widget_host);
1850 RenderWidgetHostViewBase* widget_view =
1851 static_cast<RenderWidgetHostViewBase*>(
1852 view_->CreateViewForPopupWidget(widget_host));
1853 if (!widget_view)
1854 return;
1855 if (!is_fullscreen) {
1856 // Popups should not get activated.
1857 widget_view->SetPopupType(popup_type);
1859 // Save the created widget associated with the route so we can show it later.
1860 pending_widget_views_[route_id] = widget_view;
1862 #if defined(OS_MACOSX)
1863 // A RenderWidgetHostViewMac has lifetime scoped to the view. We'll retain it
1864 // to allow it to survive the trip without being hosted.
1865 base::mac::NSObjectRetain(widget_view->GetNativeView());
1866 #endif
1869 void WebContentsImpl::ShowCreatedWindow(int route_id,
1870 WindowOpenDisposition disposition,
1871 const gfx::Rect& initial_rect,
1872 bool user_gesture) {
1873 WebContentsImpl* contents = GetCreatedWindow(route_id);
1874 if (contents) {
1875 WebContentsDelegate* delegate = GetDelegate();
1876 contents->is_resume_pending_ = true;
1877 if (!delegate || delegate->ShouldResumeRequestsForCreatedWindow())
1878 contents->ResumeLoadingCreatedWebContents();
1880 if (delegate) {
1881 delegate->AddNewContents(
1882 this, contents, disposition, initial_rect, user_gesture, NULL);
1887 void WebContentsImpl::ShowCreatedWidget(int route_id,
1888 const gfx::Rect& initial_rect) {
1889 ShowCreatedWidget(route_id, false, initial_rect);
1892 void WebContentsImpl::ShowCreatedFullscreenWidget(int route_id) {
1893 ShowCreatedWidget(route_id, true, gfx::Rect());
1896 void WebContentsImpl::ShowCreatedWidget(int route_id,
1897 bool is_fullscreen,
1898 const gfx::Rect& initial_rect) {
1899 RenderWidgetHostViewBase* widget_host_view =
1900 static_cast<RenderWidgetHostViewBase*>(GetCreatedWidget(route_id));
1901 if (!widget_host_view)
1902 return;
1904 RenderWidgetHostView* view = NULL;
1905 BrowserPluginGuest* guest = GetBrowserPluginGuest();
1906 if (guest && guest->embedder_web_contents()) {
1907 view = guest->embedder_web_contents()->GetRenderWidgetHostView();
1908 } else {
1909 view = GetRenderWidgetHostView();
1912 if (is_fullscreen) {
1913 DCHECK_EQ(MSG_ROUTING_NONE, fullscreen_widget_routing_id_);
1914 view_->StoreFocus();
1915 fullscreen_widget_routing_id_ = route_id;
1916 if (delegate_ && delegate_->EmbedsFullscreenWidget()) {
1917 widget_host_view->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
1918 delegate_->EnterFullscreenModeForTab(this, GURL());
1919 } else {
1920 widget_host_view->InitAsFullscreen(view);
1922 FOR_EACH_OBSERVER(WebContentsObserver,
1923 observers_,
1924 DidShowFullscreenWidget(route_id));
1925 if (!widget_host_view->HasFocus())
1926 widget_host_view->Focus();
1927 } else {
1928 widget_host_view->InitAsPopup(view, initial_rect);
1931 RenderWidgetHostImpl* render_widget_host_impl =
1932 RenderWidgetHostImpl::From(widget_host_view->GetRenderWidgetHost());
1933 render_widget_host_impl->Init();
1934 // Only allow privileged mouse lock for fullscreen render widget, which is
1935 // used to implement Pepper Flash fullscreen.
1936 render_widget_host_impl->set_allow_privileged_mouse_lock(is_fullscreen);
1938 #if defined(OS_MACOSX)
1939 // A RenderWidgetHostViewMac has lifetime scoped to the view. Now that it's
1940 // properly embedded (or purposefully ignored) we can release the retain we
1941 // took in CreateNewWidget().
1942 base::mac::NSObjectRelease(widget_host_view->GetNativeView());
1943 #endif
1946 WebContentsImpl* WebContentsImpl::GetCreatedWindow(int route_id) {
1947 PendingContents::iterator iter = pending_contents_.find(route_id);
1949 // Certain systems can block the creation of new windows. If we didn't succeed
1950 // in creating one, just return NULL.
1951 if (iter == pending_contents_.end()) {
1952 return NULL;
1955 WebContentsImpl* new_contents = iter->second;
1956 pending_contents_.erase(route_id);
1957 RemoveDestructionObserver(new_contents);
1959 // Don't initialize the guest WebContents immediately.
1960 if (BrowserPluginGuest::IsGuest(new_contents))
1961 return new_contents;
1963 if (!new_contents->GetRenderProcessHost()->HasConnection() ||
1964 !new_contents->GetRenderViewHost()->GetView())
1965 return NULL;
1967 return new_contents;
1970 RenderWidgetHostView* WebContentsImpl::GetCreatedWidget(int route_id) {
1971 PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id);
1972 if (iter == pending_widget_views_.end()) {
1973 DCHECK(false);
1974 return NULL;
1977 RenderWidgetHostView* widget_host_view = iter->second;
1978 pending_widget_views_.erase(route_id);
1980 RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
1981 if (!widget_host->GetProcess()->HasConnection()) {
1982 // The view has gone away or the renderer crashed. Nothing to do.
1983 return NULL;
1986 return widget_host_view;
1989 void WebContentsImpl::RequestMediaAccessPermission(
1990 const MediaStreamRequest& request,
1991 const MediaResponseCallback& callback) {
1992 if (delegate_) {
1993 delegate_->RequestMediaAccessPermission(this, request, callback);
1994 } else {
1995 callback.Run(MediaStreamDevices(),
1996 MEDIA_DEVICE_FAILED_DUE_TO_SHUTDOWN,
1997 scoped_ptr<MediaStreamUI>());
2001 bool WebContentsImpl::CheckMediaAccessPermission(const GURL& security_origin,
2002 MediaStreamType type) {
2003 DCHECK(type == MEDIA_DEVICE_AUDIO_CAPTURE ||
2004 type == MEDIA_DEVICE_VIDEO_CAPTURE);
2005 return delegate_ &&
2006 delegate_->CheckMediaAccessPermission(this, security_origin, type);
2009 SessionStorageNamespace* WebContentsImpl::GetSessionStorageNamespace(
2010 SiteInstance* instance) {
2011 return controller_.GetSessionStorageNamespace(instance);
2014 SessionStorageNamespaceMap WebContentsImpl::GetSessionStorageNamespaceMap() {
2015 return controller_.GetSessionStorageNamespaceMap();
2018 FrameTree* WebContentsImpl::GetFrameTree() {
2019 return &frame_tree_;
2022 void WebContentsImpl::SetIsVirtualKeyboardRequested(bool requested) {
2023 virtual_keyboard_requested_ = requested;
2026 bool WebContentsImpl::IsVirtualKeyboardRequested() {
2027 return virtual_keyboard_requested_;
2030 AccessibilityMode WebContentsImpl::GetAccessibilityMode() const {
2031 return accessibility_mode_;
2034 void WebContentsImpl::AccessibilityEventReceived(
2035 const std::vector<AXEventNotificationDetails>& details) {
2036 FOR_EACH_OBSERVER(
2037 WebContentsObserver, observers_, AccessibilityEventReceived(details));
2040 RenderFrameHost* WebContentsImpl::GetGuestByInstanceID(
2041 RenderFrameHost* render_frame_host,
2042 int browser_plugin_instance_id) {
2043 BrowserPluginGuestManager* guest_manager =
2044 GetBrowserContext()->GetGuestManager();
2045 if (!guest_manager)
2046 return nullptr;
2048 WebContents* guest = guest_manager->GetGuestByInstanceID(
2049 render_frame_host->GetProcess()->GetID(), browser_plugin_instance_id);
2050 if (!guest)
2051 return nullptr;
2053 return guest->GetMainFrame();
2056 GeolocationServiceContext* WebContentsImpl::GetGeolocationServiceContext() {
2057 return geolocation_service_context_.get();
2060 void WebContentsImpl::OnShowValidationMessage(
2061 const gfx::Rect& anchor_in_root_view,
2062 const base::string16& main_text,
2063 const base::string16& sub_text) {
2064 if (delegate_)
2065 delegate_->ShowValidationMessage(
2066 this, anchor_in_root_view, main_text, sub_text);
2069 void WebContentsImpl::OnHideValidationMessage() {
2070 if (delegate_)
2071 delegate_->HideValidationMessage(this);
2074 void WebContentsImpl::OnMoveValidationMessage(
2075 const gfx::Rect& anchor_in_root_view) {
2076 if (delegate_)
2077 delegate_->MoveValidationMessage(this, anchor_in_root_view);
2080 void WebContentsImpl::DidSendScreenRects(RenderWidgetHostImpl* rwh) {
2081 if (browser_plugin_embedder_)
2082 browser_plugin_embedder_->DidSendScreenRects();
2085 BrowserAccessibilityManager*
2086 WebContentsImpl::GetRootBrowserAccessibilityManager() {
2087 RenderFrameHostImpl* rfh = GetMainFrame();
2088 return rfh ? rfh->browser_accessibility_manager() : nullptr;
2091 BrowserAccessibilityManager*
2092 WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
2093 RenderFrameHostImpl* rfh = GetMainFrame();
2094 return rfh ? rfh->GetOrCreateBrowserAccessibilityManager() : nullptr;
2097 void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point& extent) {
2098 RenderFrameHost* focused_frame = GetFocusedFrame();
2099 if (!focused_frame)
2100 return;
2102 focused_frame->Send(new InputMsg_MoveRangeSelectionExtent(
2103 focused_frame->GetRoutingID(), extent));
2106 void WebContentsImpl::SelectRange(const gfx::Point& base,
2107 const gfx::Point& extent) {
2108 RenderFrameHost* focused_frame = GetFocusedFrame();
2109 if (!focused_frame)
2110 return;
2112 focused_frame->Send(
2113 new InputMsg_SelectRange(focused_frame->GetRoutingID(), base, extent));
2116 void WebContentsImpl::AdjustSelectionByCharacterOffset(int start_adjust,
2117 int end_adjust) {
2118 RenderFrameHost* focused_frame = GetFocusedFrame();
2119 if (!focused_frame)
2120 return;
2122 focused_frame->Send(new InputMsg_AdjustSelectionByCharacterOffset(
2123 focused_frame->GetRoutingID(), start_adjust, end_adjust));
2126 void WebContentsImpl::UpdatePreferredSize(const gfx::Size& pref_size) {
2127 const gfx::Size old_size = GetPreferredSize();
2128 preferred_size_ = pref_size;
2129 OnPreferredSizeChanged(old_size);
2132 void WebContentsImpl::ResizeDueToAutoResize(const gfx::Size& new_size) {
2133 if (delegate_)
2134 delegate_->ResizeDueToAutoResize(this, new_size);
2137 WebContents* WebContentsImpl::OpenURL(const OpenURLParams& params) {
2138 if (!delegate_)
2139 return NULL;
2141 WebContents* new_contents = delegate_->OpenURLFromTab(this, params);
2142 return new_contents;
2145 bool WebContentsImpl::Send(IPC::Message* message) {
2146 if (!GetRenderViewHost()) {
2147 delete message;
2148 return false;
2151 return GetRenderViewHost()->Send(message);
2154 void WebContentsImpl::RenderFrameForInterstitialPageCreated(
2155 RenderFrameHost* render_frame_host) {
2156 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2157 RenderFrameForInterstitialPageCreated(render_frame_host));
2160 void WebContentsImpl::AttachInterstitialPage(
2161 InterstitialPageImpl* interstitial_page) {
2162 DCHECK(interstitial_page);
2163 GetRenderManager()->set_interstitial_page(interstitial_page);
2165 // Cancel any visible dialogs so that they don't interfere with the
2166 // interstitial.
2167 CancelActiveAndPendingDialogs();
2169 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2170 DidAttachInterstitialPage());
2173 void WebContentsImpl::DetachInterstitialPage() {
2174 if (ShowingInterstitialPage())
2175 GetRenderManager()->remove_interstitial_page();
2176 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2177 DidDetachInterstitialPage());
2180 void WebContentsImpl::SetHistoryOffsetAndLength(int history_offset,
2181 int history_length) {
2182 SetHistoryOffsetAndLengthForView(
2183 GetRenderViewHost(), history_offset, history_length);
2186 void WebContentsImpl::SetHistoryOffsetAndLengthForView(
2187 RenderViewHost* render_view_host,
2188 int history_offset,
2189 int history_length) {
2190 render_view_host->Send(new ViewMsg_SetHistoryOffsetAndLength(
2191 render_view_host->GetRoutingID(), history_offset, history_length));
2194 void WebContentsImpl::ReloadFocusedFrame(bool ignore_cache) {
2195 RenderFrameHost* focused_frame = GetFocusedFrame();
2196 if (!focused_frame)
2197 return;
2199 focused_frame->Send(new FrameMsg_Reload(
2200 focused_frame->GetRoutingID(), ignore_cache));
2203 void WebContentsImpl::Undo() {
2204 RenderFrameHost* focused_frame = GetFocusedFrame();
2205 if (!focused_frame)
2206 return;
2208 focused_frame->Send(new InputMsg_Undo(focused_frame->GetRoutingID()));
2209 RecordAction(base::UserMetricsAction("Undo"));
2212 void WebContentsImpl::Redo() {
2213 RenderFrameHost* focused_frame = GetFocusedFrame();
2214 if (!focused_frame)
2215 return;
2216 focused_frame->Send(new InputMsg_Redo(focused_frame->GetRoutingID()));
2217 RecordAction(base::UserMetricsAction("Redo"));
2220 void WebContentsImpl::Cut() {
2221 RenderFrameHost* focused_frame = GetFocusedFrame();
2222 if (!focused_frame)
2223 return;
2225 focused_frame->Send(new InputMsg_Cut(focused_frame->GetRoutingID()));
2226 RecordAction(base::UserMetricsAction("Cut"));
2229 void WebContentsImpl::Copy() {
2230 RenderFrameHost* focused_frame = GetFocusedFrame();
2231 if (!focused_frame)
2232 return;
2234 focused_frame->Send(new InputMsg_Copy(focused_frame->GetRoutingID()));
2235 RecordAction(base::UserMetricsAction("Copy"));
2238 void WebContentsImpl::CopyToFindPboard() {
2239 #if defined(OS_MACOSX)
2240 RenderFrameHost* focused_frame = GetFocusedFrame();
2241 if (!focused_frame)
2242 return;
2244 // Windows/Linux don't have the concept of a find pasteboard.
2245 focused_frame->Send(
2246 new InputMsg_CopyToFindPboard(focused_frame->GetRoutingID()));
2247 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
2248 #endif
2251 void WebContentsImpl::Paste() {
2252 RenderFrameHost* focused_frame = GetFocusedFrame();
2253 if (!focused_frame)
2254 return;
2256 focused_frame->Send(new InputMsg_Paste(focused_frame->GetRoutingID()));
2257 RecordAction(base::UserMetricsAction("Paste"));
2260 void WebContentsImpl::PasteAndMatchStyle() {
2261 RenderFrameHost* focused_frame = GetFocusedFrame();
2262 if (!focused_frame)
2263 return;
2265 focused_frame->Send(new InputMsg_PasteAndMatchStyle(
2266 focused_frame->GetRoutingID()));
2267 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
2270 void WebContentsImpl::Delete() {
2271 RenderFrameHost* focused_frame = GetFocusedFrame();
2272 if (!focused_frame)
2273 return;
2275 focused_frame->Send(new InputMsg_Delete(focused_frame->GetRoutingID()));
2276 RecordAction(base::UserMetricsAction("DeleteSelection"));
2279 void WebContentsImpl::SelectAll() {
2280 RenderFrameHost* focused_frame = GetFocusedFrame();
2281 if (!focused_frame)
2282 return;
2284 focused_frame->Send(new InputMsg_SelectAll(focused_frame->GetRoutingID()));
2285 RecordAction(base::UserMetricsAction("SelectAll"));
2288 void WebContentsImpl::Unselect() {
2289 RenderFrameHost* focused_frame = GetFocusedFrame();
2290 if (!focused_frame)
2291 return;
2293 focused_frame->Send(new InputMsg_Unselect(focused_frame->GetRoutingID()));
2294 RecordAction(base::UserMetricsAction("Unselect"));
2297 void WebContentsImpl::Replace(const base::string16& word) {
2298 RenderFrameHost* focused_frame = GetFocusedFrame();
2299 if (!focused_frame)
2300 return;
2302 focused_frame->Send(new InputMsg_Replace(
2303 focused_frame->GetRoutingID(), word));
2306 void WebContentsImpl::ReplaceMisspelling(const base::string16& word) {
2307 RenderFrameHost* focused_frame = GetFocusedFrame();
2308 if (!focused_frame)
2309 return;
2311 focused_frame->Send(new InputMsg_ReplaceMisspelling(
2312 focused_frame->GetRoutingID(), word));
2315 void WebContentsImpl::NotifyContextMenuClosed(
2316 const CustomContextMenuContext& context) {
2317 RenderFrameHost* focused_frame = GetFocusedFrame();
2318 if (!focused_frame)
2319 return;
2321 focused_frame->Send(new FrameMsg_ContextMenuClosed(
2322 focused_frame->GetRoutingID(), context));
2325 void WebContentsImpl::ExecuteCustomContextMenuCommand(
2326 int action, const CustomContextMenuContext& context) {
2327 RenderFrameHost* focused_frame = GetFocusedFrame();
2328 if (!focused_frame)
2329 return;
2331 focused_frame->Send(new FrameMsg_CustomContextMenuAction(
2332 focused_frame->GetRoutingID(), context, action));
2335 gfx::NativeView WebContentsImpl::GetNativeView() {
2336 return view_->GetNativeView();
2339 gfx::NativeView WebContentsImpl::GetContentNativeView() {
2340 return view_->GetContentNativeView();
2343 gfx::NativeWindow WebContentsImpl::GetTopLevelNativeWindow() {
2344 return view_->GetTopLevelNativeWindow();
2347 gfx::Rect WebContentsImpl::GetViewBounds() {
2348 return view_->GetViewBounds();
2351 gfx::Rect WebContentsImpl::GetContainerBounds() {
2352 gfx::Rect rv;
2353 view_->GetContainerBounds(&rv);
2354 return rv;
2357 DropData* WebContentsImpl::GetDropData() {
2358 return view_->GetDropData();
2361 void WebContentsImpl::Focus() {
2362 view_->Focus();
2365 void WebContentsImpl::SetInitialFocus() {
2366 view_->SetInitialFocus();
2369 void WebContentsImpl::StoreFocus() {
2370 view_->StoreFocus();
2373 void WebContentsImpl::RestoreFocus() {
2374 view_->RestoreFocus();
2377 void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
2378 if (ShowingInterstitialPage()) {
2379 GetRenderManager()->interstitial_page()->FocusThroughTabTraversal(reverse);
2380 return;
2382 RenderWidgetHostView* const fullscreen_view =
2383 GetFullscreenRenderWidgetHostView();
2384 if (fullscreen_view) {
2385 fullscreen_view->Focus();
2386 return;
2388 GetRenderViewHost()->SetInitialFocus(reverse);
2391 bool WebContentsImpl::ShowingInterstitialPage() const {
2392 return GetRenderManager()->interstitial_page() != NULL;
2395 InterstitialPage* WebContentsImpl::GetInterstitialPage() const {
2396 return GetRenderManager()->interstitial_page();
2399 bool WebContentsImpl::IsSavable() {
2400 // WebKit creates Document object when MIME type is application/xhtml+xml,
2401 // so we also support this MIME type.
2402 return contents_mime_type_ == "text/html" ||
2403 contents_mime_type_ == "text/xml" ||
2404 contents_mime_type_ == "application/xhtml+xml" ||
2405 contents_mime_type_ == "text/plain" ||
2406 contents_mime_type_ == "text/css" ||
2407 mime_util::IsSupportedJavascriptMimeType(contents_mime_type_);
2410 void WebContentsImpl::OnSavePage() {
2411 // If we can not save the page, try to download it.
2412 if (!IsSavable()) {
2413 RecordDownloadSource(INITIATED_BY_SAVE_PACKAGE_ON_NON_HTML);
2414 SaveFrame(GetLastCommittedURL(), Referrer());
2415 return;
2418 Stop();
2420 // Create the save package and possibly prompt the user for the name to save
2421 // the page as. The user prompt is an asynchronous operation that runs on
2422 // another thread.
2423 save_package_ = new SavePackage(this);
2424 save_package_->GetSaveInfo();
2427 // Used in automated testing to bypass prompting the user for file names.
2428 // Instead, the names and paths are hard coded rather than running them through
2429 // file name sanitation and extension / mime checking.
2430 bool WebContentsImpl::SavePage(const base::FilePath& main_file,
2431 const base::FilePath& dir_path,
2432 SavePageType save_type) {
2433 // Stop the page from navigating.
2434 Stop();
2436 save_package_ = new SavePackage(this, save_type, main_file, dir_path);
2437 return save_package_->Init(SavePackageDownloadCreatedCallback());
2440 void WebContentsImpl::SaveFrame(const GURL& url,
2441 const Referrer& referrer) {
2442 SaveFrameWithHeaders(url, referrer, std::string());
2445 void WebContentsImpl::SaveFrameWithHeaders(const GURL& url,
2446 const Referrer& referrer,
2447 const std::string& headers) {
2448 if (!GetLastCommittedURL().is_valid())
2449 return;
2450 if (delegate_ && delegate_->SaveFrame(url, referrer))
2451 return;
2453 // TODO(nasko): This check for main frame is incorrect and should be fixed
2454 // by explicitly passing in which frame this method should target.
2455 bool is_main_frame = (url == GetLastCommittedURL());
2457 DownloadManager* dlm =
2458 BrowserContext::GetDownloadManager(GetBrowserContext());
2459 if (!dlm)
2460 return;
2461 int64 post_id = -1;
2462 if (is_main_frame) {
2463 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2464 if (entry)
2465 post_id = entry->GetPostID();
2467 scoped_ptr<DownloadUrlParameters> params(
2468 DownloadUrlParameters::FromWebContents(this, url));
2469 params->set_referrer(referrer);
2470 params->set_post_id(post_id);
2471 if (post_id >= 0)
2472 params->set_method("POST");
2473 params->set_prompt(true);
2475 if (headers.empty()) {
2476 params->set_prefer_cache(true);
2477 } else {
2478 std::vector<std::string> key_value_list;
2479 base::SplitString(headers, '\n', &key_value_list);
2480 for (const auto& key_value : key_value_list) {
2481 std::vector<std::string> pair;
2482 base::SplitString(key_value, ':', &pair);
2483 DCHECK_EQ(2ul, pair.size());
2484 params->add_request_header(pair[0], pair[1]);
2487 dlm->DownloadUrl(params.Pass());
2490 void WebContentsImpl::GenerateMHTML(
2491 const base::FilePath& file,
2492 const base::Callback<void(int64)>& callback) {
2493 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, file, callback);
2496 const std::string& WebContentsImpl::GetContentsMimeType() const {
2497 return contents_mime_type_;
2500 bool WebContentsImpl::WillNotifyDisconnection() const {
2501 return notify_disconnection_;
2504 void WebContentsImpl::SetOverrideEncoding(const std::string& encoding) {
2505 SetEncoding(encoding);
2506 Send(new ViewMsg_SetPageEncoding(GetRoutingID(), encoding));
2509 void WebContentsImpl::ResetOverrideEncoding() {
2510 canonical_encoding_.clear();
2511 Send(new ViewMsg_ResetPageEncodingToDefault(GetRoutingID()));
2514 RendererPreferences* WebContentsImpl::GetMutableRendererPrefs() {
2515 return &renderer_preferences_;
2518 void WebContentsImpl::Close() {
2519 Close(GetRenderViewHost());
2522 void WebContentsImpl::DragSourceEndedAt(int client_x, int client_y,
2523 int screen_x, int screen_y, blink::WebDragOperation operation) {
2524 if (browser_plugin_embedder_.get())
2525 browser_plugin_embedder_->DragSourceEndedAt(client_x, client_y,
2526 screen_x, screen_y, operation);
2527 if (GetRenderViewHost())
2528 GetRenderViewHost()->DragSourceEndedAt(client_x, client_y, screen_x,
2529 screen_y, operation);
2532 void WebContentsImpl::DidGetResourceResponseStart(
2533 const ResourceRequestDetails& details) {
2534 controller_.ssl_manager()->DidStartResourceResponse(details);
2536 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2537 DidGetResourceResponseStart(details));
2540 void WebContentsImpl::DidGetRedirectForResourceRequest(
2541 RenderFrameHost* render_frame_host,
2542 const ResourceRedirectDetails& details) {
2543 controller_.ssl_manager()->DidReceiveResourceRedirect(details);
2545 FOR_EACH_OBSERVER(
2546 WebContentsObserver,
2547 observers_,
2548 DidGetRedirectForResourceRequest(render_frame_host, details));
2550 // TODO(avi): Remove. http://crbug.com/170921
2551 NotificationService::current()->Notify(
2552 NOTIFICATION_RESOURCE_RECEIVED_REDIRECT,
2553 Source<WebContents>(this),
2554 Details<const ResourceRedirectDetails>(&details));
2556 if (IsResourceTypeFrame(details.resource_type)) {
2557 NavigationHandleImpl* navigation_handle =
2558 static_cast<RenderFrameHostImpl*>(render_frame_host)
2559 ->navigation_handle();
2560 if (navigation_handle)
2561 navigation_handle->DidRedirectNavigation(details.new_url);
2565 void WebContentsImpl::NotifyWebContentsFocused() {
2566 FOR_EACH_OBSERVER(WebContentsObserver, observers_, OnWebContentsFocused());
2569 void WebContentsImpl::SystemDragEnded() {
2570 if (GetRenderViewHost())
2571 GetRenderViewHost()->DragSourceSystemDragEnded();
2572 if (browser_plugin_embedder_.get())
2573 browser_plugin_embedder_->SystemDragEnded();
2576 void WebContentsImpl::UserGestureDone() {
2577 OnUserGesture();
2580 void WebContentsImpl::SetClosedByUserGesture(bool value) {
2581 closed_by_user_gesture_ = value;
2584 bool WebContentsImpl::GetClosedByUserGesture() const {
2585 return closed_by_user_gesture_;
2588 void WebContentsImpl::ViewSource() {
2589 if (!delegate_)
2590 return;
2592 NavigationEntry* entry = GetController().GetLastCommittedEntry();
2593 if (!entry)
2594 return;
2596 delegate_->ViewSourceForTab(this, entry->GetURL());
2599 void WebContentsImpl::ViewFrameSource(const GURL& url,
2600 const PageState& page_state) {
2601 if (!delegate_)
2602 return;
2604 delegate_->ViewSourceForFrame(this, url, page_state);
2607 int WebContentsImpl::GetMinimumZoomPercent() const {
2608 return minimum_zoom_percent_;
2611 int WebContentsImpl::GetMaximumZoomPercent() const {
2612 return maximum_zoom_percent_;
2615 void WebContentsImpl::ResetPageScale() {
2616 Send(new ViewMsg_ResetPageScale(GetRoutingID()));
2619 gfx::Size WebContentsImpl::GetPreferredSize() const {
2620 return capturer_count_ == 0 ? preferred_size_ : preferred_size_for_capture_;
2623 bool WebContentsImpl::GotResponseToLockMouseRequest(bool allowed) {
2624 if (GetBrowserPluginGuest())
2625 return GetBrowserPluginGuest()->LockMouse(allowed);
2627 return GetRenderViewHost()
2628 ? GetRenderViewHost()->GotResponseToLockMouseRequest(allowed)
2629 : false;
2632 bool WebContentsImpl::HasOpener() const {
2633 return GetOpener() != NULL;
2636 WebContentsImpl* WebContentsImpl::GetOpener() const {
2637 FrameTreeNode* opener_ftn = frame_tree_.root()->opener();
2638 return opener_ftn ? FromFrameTreeNode(opener_ftn) : nullptr;
2641 void WebContentsImpl::DidChooseColorInColorChooser(SkColor color) {
2642 if (!color_chooser_info_.get())
2643 return;
2644 RenderFrameHost* rfh = RenderFrameHost::FromID(
2645 color_chooser_info_->render_process_id,
2646 color_chooser_info_->render_frame_id);
2647 if (!rfh)
2648 return;
2650 rfh->Send(new FrameMsg_DidChooseColorResponse(
2651 rfh->GetRoutingID(), color_chooser_info_->identifier, color));
2654 void WebContentsImpl::DidEndColorChooser() {
2655 if (!color_chooser_info_.get())
2656 return;
2657 RenderFrameHost* rfh = RenderFrameHost::FromID(
2658 color_chooser_info_->render_process_id,
2659 color_chooser_info_->render_frame_id);
2660 if (!rfh)
2661 return;
2663 rfh->Send(new FrameMsg_DidEndColorChooser(
2664 rfh->GetRoutingID(), color_chooser_info_->identifier));
2665 color_chooser_info_.reset();
2668 int WebContentsImpl::DownloadImage(
2669 const GURL& url,
2670 bool is_favicon,
2671 uint32_t max_bitmap_size,
2672 bool bypass_cache,
2673 const WebContents::ImageDownloadCallback& callback) {
2674 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2675 static int next_image_download_id = 0;
2676 const image_downloader::ImageDownloaderPtr& mojo_image_downloader =
2677 GetMainFrame()->GetMojoImageDownloader();
2678 const int download_id = ++next_image_download_id;
2679 if (!mojo_image_downloader) {
2680 // If the renderer process is dead (i.e. crash, or memory pressure on
2681 // Android), the downloader service will be invalid. Pre-Mojo, this would
2682 // hang the callback indefinetly since the IPC would be dropped. Now,
2683 // respond with a 400 HTTP error code to indicate that something went wrong.
2684 BrowserThread::PostTask(
2685 BrowserThread::UI, FROM_HERE,
2686 base::Bind(&WebContents::ImageDownloadCallback::Run,
2687 base::Owned(new ImageDownloadCallback(callback)),
2688 download_id, 400, url, std::vector<SkBitmap>(),
2689 std::vector<gfx::Size>()));
2690 return download_id;
2693 image_downloader::DownloadRequestPtr req =
2694 image_downloader::DownloadRequest::New();
2696 req->url = mojo::String::From(url);
2697 req->is_favicon = is_favicon;
2698 req->max_bitmap_size = max_bitmap_size;
2699 req->bypass_cache = bypass_cache;
2701 mojo_image_downloader->DownloadImage(
2702 req.Pass(),
2703 base::Bind(&DidDownloadImage, callback, download_id, url));
2704 return download_id;
2707 bool WebContentsImpl::IsSubframe() const {
2708 return is_subframe_;
2711 void WebContentsImpl::Find(int request_id,
2712 const base::string16& search_text,
2713 const blink::WebFindOptions& options) {
2714 // See if a top level browser plugin handles the find request first.
2715 if (browser_plugin_embedder_) {
2716 BrowserPluginGuest* guest = browser_plugin_embedder_->GetFullPageGuest();
2717 if (guest && guest->Find(request_id, search_text, options))
2718 return;
2720 Send(new ViewMsg_Find(GetRoutingID(), request_id, search_text, options));
2723 void WebContentsImpl::StopFinding(StopFindAction action) {
2724 // See if a top level browser plugin handles the stop finding request first.
2725 if (browser_plugin_embedder_) {
2726 BrowserPluginGuest* guest = browser_plugin_embedder_->GetFullPageGuest();
2727 if (guest && guest->StopFinding(action))
2728 return;
2730 Send(new ViewMsg_StopFinding(GetRoutingID(), action));
2733 void WebContentsImpl::InsertCSS(const std::string& css) {
2734 GetMainFrame()->Send(new FrameMsg_CSSInsertRequest(
2735 GetMainFrame()->GetRoutingID(), css));
2738 bool WebContentsImpl::WasRecentlyAudible() {
2739 return audio_state_provider_->WasRecentlyAudible();
2742 void WebContentsImpl::GetManifest(const GetManifestCallback& callback) {
2743 manifest_manager_host_->GetManifest(GetMainFrame(), callback);
2746 void WebContentsImpl::ExitFullscreen() {
2747 // Clean up related state and initiate the fullscreen exit.
2748 GetRenderViewHost()->RejectMouseLockOrUnlockIfNecessary();
2749 ExitFullscreenMode();
2752 void WebContentsImpl::ResumeLoadingCreatedWebContents() {
2753 if (delayed_open_url_params_.get()) {
2754 OpenURL(*delayed_open_url_params_.get());
2755 delayed_open_url_params_.reset(nullptr);
2756 return;
2759 // Resume blocked requests for both the RenderViewHost and RenderFrameHost.
2760 // TODO(brettw): It seems bogus to reach into here and initialize the host.
2761 if (is_resume_pending_) {
2762 is_resume_pending_ = false;
2763 GetRenderViewHost()->Init();
2764 GetMainFrame()->Init();
2768 bool WebContentsImpl::FocusLocationBarByDefault() {
2769 NavigationEntry* entry = controller_.GetVisibleEntry();
2770 if (entry && entry->GetURL() == GURL(url::kAboutBlankURL))
2771 return true;
2772 return delegate_ && delegate_->ShouldFocusLocationBarByDefault(this);
2775 void WebContentsImpl::SetFocusToLocationBar(bool select_all) {
2776 if (delegate_)
2777 delegate_->SetFocusToLocationBar(select_all);
2780 void WebContentsImpl::DidStartNavigation(NavigationHandle* navigation_handle) {
2781 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2782 DidStartNavigation(navigation_handle));
2785 void WebContentsImpl::DidRedirectNavigation(
2786 NavigationHandle* navigation_handle) {
2787 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2788 DidRedirectNavigation(navigation_handle));
2791 void WebContentsImpl::DidCommitNavigation(NavigationHandle* navigation_handle) {
2792 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2793 DidCommitNavigation(navigation_handle));
2796 void WebContentsImpl::DidFinishNavigation(NavigationHandle* navigation_handle) {
2797 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2798 DidFinishNavigation(navigation_handle));
2801 void WebContentsImpl::DidStartProvisionalLoad(
2802 RenderFrameHostImpl* render_frame_host,
2803 const GURL& validated_url,
2804 bool is_error_page,
2805 bool is_iframe_srcdoc) {
2806 // Notify observers about the start of the provisional load.
2807 FOR_EACH_OBSERVER(
2808 WebContentsObserver,
2809 observers_,
2810 DidStartProvisionalLoadForFrame(
2811 render_frame_host, validated_url, is_error_page, is_iframe_srcdoc));
2813 // Notify accessibility if this is a reload.
2814 NavigationEntry* entry = controller_.GetVisibleEntry();
2815 if (entry && ui::PageTransitionCoreTypeIs(
2816 entry->GetTransitionType(), ui::PAGE_TRANSITION_RELOAD)) {
2817 FrameTreeNode* ftn = render_frame_host->frame_tree_node();
2818 BrowserAccessibilityManager* manager =
2819 ftn->current_frame_host()->browser_accessibility_manager();
2820 if (manager)
2821 manager->UserIsReloading();
2825 void WebContentsImpl::DidFailProvisionalLoadWithError(
2826 RenderFrameHostImpl* render_frame_host,
2827 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
2828 GURL validated_url(params.url);
2829 FOR_EACH_OBSERVER(WebContentsObserver,
2830 observers_,
2831 DidFailProvisionalLoad(render_frame_host,
2832 validated_url,
2833 params.error_code,
2834 params.error_description,
2835 params.was_ignored_by_handler));
2837 FrameTreeNode* ftn = render_frame_host->frame_tree_node();
2838 BrowserAccessibilityManager* manager =
2839 ftn->current_frame_host()->browser_accessibility_manager();
2840 if (manager)
2841 manager->NavigationFailed();
2844 void WebContentsImpl::DidFailLoadWithError(
2845 RenderFrameHostImpl* render_frame_host,
2846 const GURL& url,
2847 int error_code,
2848 const base::string16& error_description,
2849 bool was_ignored_by_handler) {
2850 FOR_EACH_OBSERVER(
2851 WebContentsObserver,
2852 observers_,
2853 DidFailLoad(render_frame_host, url, error_code, error_description,
2854 was_ignored_by_handler));
2857 void WebContentsImpl::NotifyChangedNavigationState(
2858 InvalidateTypes changed_flags) {
2859 NotifyNavigationStateChanged(changed_flags);
2862 void WebContentsImpl::AboutToNavigateRenderFrame(
2863 RenderFrameHostImpl* old_host,
2864 RenderFrameHostImpl* new_host) {
2865 // Notify observers that we will navigate in this RenderFrame.
2866 FOR_EACH_OBSERVER(
2867 WebContentsObserver,
2868 observers_,
2869 AboutToNavigateRenderFrame(old_host, new_host));
2872 void WebContentsImpl::DidStartNavigationToPendingEntry(
2873 const GURL& url,
2874 NavigationController::ReloadType reload_type) {
2875 // Notify observers about navigation.
2876 FOR_EACH_OBSERVER(
2877 WebContentsObserver,
2878 observers_,
2879 DidStartNavigationToPendingEntry(url, reload_type));
2882 void WebContentsImpl::RequestOpenURL(RenderFrameHostImpl* render_frame_host,
2883 const OpenURLParams& params) {
2884 // OpenURL can blow away the source RFH. Use the process/frame routing ID as a
2885 // weak pointer of sorts.
2886 const int32_t process_id = render_frame_host->GetProcess()->GetID();
2887 const int32_t frame_id = render_frame_host->GetRoutingID();
2889 WebContents* new_contents = OpenURL(params);
2891 if (new_contents && RenderFrameHost::FromID(process_id, frame_id)) {
2892 // Notify observers.
2893 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2894 DidOpenRequestedURL(new_contents,
2895 render_frame_host,
2896 params.url,
2897 params.referrer,
2898 params.disposition,
2899 params.transition));
2903 bool WebContentsImpl::ShouldPreserveAbortedURLs() {
2904 if (!delegate_)
2905 return false;
2906 return delegate_->ShouldPreserveAbortedURLs(this);
2909 void WebContentsImpl::DidCommitProvisionalLoad(
2910 RenderFrameHostImpl* render_frame_host,
2911 const GURL& url,
2912 ui::PageTransition transition_type) {
2913 // Notify observers about the commit of the provisional load.
2914 FOR_EACH_OBSERVER(WebContentsObserver,
2915 observers_,
2916 DidCommitProvisionalLoadForFrame(
2917 render_frame_host, url, transition_type));
2919 BrowserAccessibilityManager* manager =
2920 render_frame_host->browser_accessibility_manager();
2921 if (manager)
2922 manager->NavigationSucceeded();
2925 void WebContentsImpl::DidNavigateMainFramePreCommit(
2926 bool navigation_is_within_page) {
2927 // Ensure fullscreen mode is exited before committing the navigation to a
2928 // different page. The next page will not start out assuming it is in
2929 // fullscreen mode.
2930 if (navigation_is_within_page) {
2931 // No page change? Then, the renderer and browser can remain in fullscreen.
2932 return;
2934 if (IsFullscreenForCurrentTab())
2935 ExitFullscreen();
2936 DCHECK(!IsFullscreenForCurrentTab());
2939 void WebContentsImpl::DidNavigateMainFramePostCommit(
2940 RenderFrameHostImpl* render_frame_host,
2941 const LoadCommittedDetails& details,
2942 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
2943 if (details.is_navigation_to_different_page()) {
2944 // Clear the status bubble. This is a workaround for a bug where WebKit
2945 // doesn't let us know that the cursor left an element during a
2946 // transition (this is also why the mouse cursor remains as a hand after
2947 // clicking on a link); see bugs 1184641 and 980803. We don't want to
2948 // clear the bubble when a user navigates to a named anchor in the same
2949 // page.
2950 UpdateTargetURL(render_frame_host->GetRenderViewHost(), GURL());
2952 RenderWidgetHostViewBase* rwhvb =
2953 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
2954 if (rwhvb)
2955 rwhvb->OnDidNavigateMainFrameToNewPage();
2957 did_first_visually_non_empty_paint_ = false;
2959 // Reset theme color on navigation to new page.
2960 theme_color_ = SK_ColorTRANSPARENT;
2963 if (!details.is_in_page) {
2964 // Once the main frame is navigated, we're no longer considered to have
2965 // displayed insecure content.
2966 displayed_insecure_content_ = false;
2967 SSLManager::NotifySSLInternalStateChanged(
2968 GetController().GetBrowserContext());
2971 // Notify observers about navigation.
2972 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2973 DidNavigateMainFrame(details, params));
2975 if (delegate_)
2976 delegate_->DidNavigateMainFramePostCommit(this);
2977 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
2980 void WebContentsImpl::DidNavigateAnyFramePostCommit(
2981 RenderFrameHostImpl* render_frame_host,
2982 const LoadCommittedDetails& details,
2983 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
2984 // Now that something has committed, we don't need to track whether the
2985 // initial page has been accessed.
2986 has_accessed_initial_document_ = false;
2988 // If we navigate off the page, close all JavaScript dialogs.
2989 if (!details.is_in_page)
2990 CancelActiveAndPendingDialogs();
2992 // Notify observers about navigation.
2993 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2994 DidNavigateAnyFrame(render_frame_host, details, params));
2997 void WebContentsImpl::SetMainFrameMimeType(const std::string& mime_type) {
2998 contents_mime_type_ = mime_type;
3001 bool WebContentsImpl::CanOverscrollContent() const {
3002 // Disable overscroll when touch emulation is on. See crbug.com/369938.
3003 if (force_disable_overscroll_content_)
3004 return false;
3006 if (delegate_)
3007 return delegate_->CanOverscrollContent();
3009 return false;
3012 void WebContentsImpl::OnThemeColorChanged(SkColor theme_color) {
3013 // Update the theme color. This is to be published to observers after the
3014 // first visually non-empty paint.
3015 theme_color_ = theme_color;
3017 if (did_first_visually_non_empty_paint_ &&
3018 last_sent_theme_color_ != theme_color_) {
3019 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3020 DidChangeThemeColor(theme_color_));
3021 last_sent_theme_color_ = theme_color_;
3025 void WebContentsImpl::OnDidLoadResourceFromMemoryCache(
3026 const GURL& url,
3027 const std::string& security_info,
3028 const std::string& http_method,
3029 const std::string& mime_type,
3030 ResourceType resource_type) {
3031 SSLStatus status;
3032 if (!DeserializeSecurityInfo(security_info, &status)) {
3033 bad_message::ReceivedBadMessage(
3034 GetRenderProcessHost(),
3035 bad_message::WC_MEMORY_CACHE_RESOURCE_BAD_SECURITY_INFO);
3036 return;
3039 // Send out a notification that we loaded a resource from our memory cache.
3040 // TODO(alcutter,eranm): Pass signed_certificate_timestamp_ids into details.
3041 LoadFromMemoryCacheDetails details(
3042 url, GetRenderProcessHost()->GetID(), status.cert_id, status.cert_status,
3043 http_method, mime_type, resource_type);
3045 controller_.ssl_manager()->DidLoadFromMemoryCache(details);
3047 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3048 DidLoadResourceFromMemoryCache(details));
3050 if (url.is_valid() && url.SchemeIsHTTPOrHTTPS()) {
3051 scoped_refptr<net::URLRequestContextGetter> request_context(
3052 resource_type == RESOURCE_TYPE_MEDIA ?
3053 GetBrowserContext()->GetMediaRequestContextForRenderProcess(
3054 GetRenderProcessHost()->GetID()) :
3055 GetBrowserContext()->GetRequestContextForRenderProcess(
3056 GetRenderProcessHost()->GetID()));
3057 BrowserThread::PostTask(
3058 BrowserThread::IO,
3059 FROM_HERE,
3060 base::Bind(&NotifyCacheOnIO, request_context, url, http_method));
3064 void WebContentsImpl::OnDidDisplayInsecureContent() {
3065 RecordAction(base::UserMetricsAction("SSL.DisplayedInsecureContent"));
3066 displayed_insecure_content_ = true;
3067 SSLManager::NotifySSLInternalStateChanged(
3068 GetController().GetBrowserContext());
3071 void WebContentsImpl::OnDidRunInsecureContent(
3072 const std::string& security_origin, const GURL& target_url) {
3073 LOG(WARNING) << security_origin << " ran insecure content from "
3074 << target_url.possibly_invalid_spec();
3075 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
3076 if (base::EndsWith(security_origin, kDotGoogleDotCom,
3077 base::CompareCase::INSENSITIVE_ASCII))
3078 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
3079 controller_.ssl_manager()->DidRunInsecureContent(security_origin);
3080 displayed_insecure_content_ = true;
3081 SSLManager::NotifySSLInternalStateChanged(
3082 GetController().GetBrowserContext());
3085 void WebContentsImpl::OnDocumentLoadedInFrame() {
3086 if (!HasValidFrameSource())
3087 return;
3089 RenderFrameHostImpl* rfh =
3090 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
3091 FOR_EACH_OBSERVER(
3092 WebContentsObserver, observers_, DocumentLoadedInFrame(rfh));
3095 void WebContentsImpl::OnDidFinishLoad(const GURL& url) {
3096 if (!HasValidFrameSource())
3097 return;
3099 GURL validated_url(url);
3100 RenderProcessHost* render_process_host =
3101 render_frame_message_source_->GetProcess();
3102 render_process_host->FilterURL(false, &validated_url);
3104 RenderFrameHostImpl* rfh =
3105 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
3106 FOR_EACH_OBSERVER(
3107 WebContentsObserver, observers_, DidFinishLoad(rfh, validated_url));
3110 void WebContentsImpl::OnGoToEntryAtOffset(int offset) {
3111 if (!delegate_ || delegate_->OnGoToEntryOffset(offset))
3112 controller_.GoToOffset(offset);
3115 void WebContentsImpl::OnUpdateZoomLimits(int minimum_percent,
3116 int maximum_percent) {
3117 minimum_zoom_percent_ = minimum_percent;
3118 maximum_zoom_percent_ = maximum_percent;
3121 void WebContentsImpl::OnEnumerateDirectory(int request_id,
3122 const base::FilePath& path) {
3123 if (!delegate_)
3124 return;
3126 ChildProcessSecurityPolicyImpl* policy =
3127 ChildProcessSecurityPolicyImpl::GetInstance();
3128 if (policy->CanReadFile(GetRenderProcessHost()->GetID(), path))
3129 delegate_->EnumerateDirectory(this, request_id, path);
3132 void WebContentsImpl::OnRegisterProtocolHandler(const std::string& protocol,
3133 const GURL& url,
3134 const base::string16& title,
3135 bool user_gesture) {
3136 if (!delegate_)
3137 return;
3139 ChildProcessSecurityPolicyImpl* policy =
3140 ChildProcessSecurityPolicyImpl::GetInstance();
3141 if (policy->IsPseudoScheme(protocol))
3142 return;
3144 delegate_->RegisterProtocolHandler(this, protocol, url, user_gesture);
3147 void WebContentsImpl::OnUnregisterProtocolHandler(const std::string& protocol,
3148 const GURL& url,
3149 bool user_gesture) {
3150 if (!delegate_)
3151 return;
3153 ChildProcessSecurityPolicyImpl* policy =
3154 ChildProcessSecurityPolicyImpl::GetInstance();
3155 if (policy->IsPseudoScheme(protocol))
3156 return;
3158 delegate_->UnregisterProtocolHandler(this, protocol, url, user_gesture);
3161 void WebContentsImpl::OnFindReply(int request_id,
3162 int number_of_matches,
3163 const gfx::Rect& selection_rect,
3164 int active_match_ordinal,
3165 bool final_update) {
3166 if (delegate_) {
3167 delegate_->FindReply(this, request_id, number_of_matches, selection_rect,
3168 active_match_ordinal, final_update);
3172 #if defined(OS_ANDROID)
3173 void WebContentsImpl::OnFindMatchRectsReply(
3174 int version,
3175 const std::vector<gfx::RectF>& rects,
3176 const gfx::RectF& active_rect) {
3177 if (delegate_)
3178 delegate_->FindMatchRectsReply(this, version, rects, active_rect);
3181 void WebContentsImpl::OnOpenDateTimeDialog(
3182 const ViewHostMsg_DateTimeDialogValue_Params& value) {
3183 date_time_chooser_->ShowDialog(GetTopLevelNativeWindow(),
3184 GetRenderViewHost(),
3185 value.dialog_type,
3186 value.dialog_value,
3187 value.minimum,
3188 value.maximum,
3189 value.step,
3190 value.suggestions);
3192 #endif
3194 void WebContentsImpl::OnDomOperationResponse(const std::string& json_string,
3195 int automation_id) {
3196 DomOperationNotificationDetails details(json_string, automation_id);
3197 NotificationService::current()->Notify(
3198 NOTIFICATION_DOM_OPERATION_RESPONSE,
3199 Source<WebContents>(this),
3200 Details<DomOperationNotificationDetails>(&details));
3203 void WebContentsImpl::OnAppCacheAccessed(const GURL& manifest_url,
3204 bool blocked_by_policy) {
3205 // Notify observers about navigation.
3206 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3207 AppCacheAccessed(manifest_url, blocked_by_policy));
3210 void WebContentsImpl::OnOpenColorChooser(
3211 int color_chooser_id,
3212 SkColor color,
3213 const std::vector<ColorSuggestion>& suggestions) {
3214 if (!HasValidFrameSource())
3215 return;
3217 ColorChooser* new_color_chooser = delegate_ ?
3218 delegate_->OpenColorChooser(this, color, suggestions) :
3219 NULL;
3220 if (!new_color_chooser)
3221 return;
3222 if (color_chooser_info_.get())
3223 color_chooser_info_->chooser->End();
3225 color_chooser_info_.reset(new ColorChooserInfo(
3226 render_frame_message_source_->GetProcess()->GetID(),
3227 render_frame_message_source_->GetRoutingID(),
3228 new_color_chooser,
3229 color_chooser_id));
3232 void WebContentsImpl::OnEndColorChooser(int color_chooser_id) {
3233 if (color_chooser_info_ &&
3234 color_chooser_id == color_chooser_info_->identifier)
3235 color_chooser_info_->chooser->End();
3238 void WebContentsImpl::OnSetSelectedColorInColorChooser(int color_chooser_id,
3239 SkColor color) {
3240 if (color_chooser_info_ &&
3241 color_chooser_id == color_chooser_info_->identifier)
3242 color_chooser_info_->chooser->SetSelectedColor(color);
3245 // This exists for render views that don't have a WebUI, but do have WebUI
3246 // bindings enabled.
3247 void WebContentsImpl::OnWebUISend(const GURL& source_url,
3248 const std::string& name,
3249 const base::ListValue& args) {
3250 if (delegate_)
3251 delegate_->WebUISend(this, source_url, name, args);
3254 #if defined(ENABLE_PLUGINS)
3255 void WebContentsImpl::OnPepperInstanceCreated() {
3256 FOR_EACH_OBSERVER(WebContentsObserver, observers_, PepperInstanceCreated());
3259 void WebContentsImpl::OnPepperInstanceDeleted() {
3260 FOR_EACH_OBSERVER(WebContentsObserver, observers_, PepperInstanceDeleted());
3263 void WebContentsImpl::OnPepperPluginHung(int plugin_child_id,
3264 const base::FilePath& path,
3265 bool is_hung) {
3266 UMA_HISTOGRAM_COUNTS("Pepper.PluginHung", 1);
3268 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3269 PluginHungStatusChanged(plugin_child_id, path, is_hung));
3272 void WebContentsImpl::OnPluginCrashed(const base::FilePath& plugin_path,
3273 base::ProcessId plugin_pid) {
3274 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3275 PluginCrashed(plugin_path, plugin_pid));
3278 void WebContentsImpl::OnRequestPpapiBrokerPermission(
3279 int routing_id,
3280 const GURL& url,
3281 const base::FilePath& plugin_path) {
3282 if (!delegate_) {
3283 OnPpapiBrokerPermissionResult(routing_id, false);
3284 return;
3287 if (!delegate_->RequestPpapiBrokerPermission(
3288 this, url, plugin_path,
3289 base::Bind(&WebContentsImpl::OnPpapiBrokerPermissionResult,
3290 base::Unretained(this), routing_id))) {
3291 NOTIMPLEMENTED();
3292 OnPpapiBrokerPermissionResult(routing_id, false);
3296 void WebContentsImpl::OnPpapiBrokerPermissionResult(int routing_id,
3297 bool result) {
3298 Send(new ViewMsg_PpapiBrokerPermissionResult(routing_id, result));
3301 void WebContentsImpl::OnBrowserPluginMessage(RenderFrameHost* render_frame_host,
3302 const IPC::Message& message) {
3303 CHECK(!browser_plugin_embedder_.get());
3304 CreateBrowserPluginEmbedderIfNecessary();
3305 browser_plugin_embedder_->OnMessageReceived(message, render_frame_host);
3307 #endif // defined(ENABLE_PLUGINS)
3309 void WebContentsImpl::OnUpdateFaviconURL(
3310 const std::vector<FaviconURL>& candidates) {
3311 // We get updated favicon URLs after the page stops loading. If a cross-site
3312 // navigation occurs while a page is still loading, the initial page
3313 // may stop loading and send us updated favicon URLs after the navigation
3314 // for the new page has committed.
3315 RenderViewHostImpl* rvhi =
3316 static_cast<RenderViewHostImpl*>(render_view_message_source_);
3317 if (!rvhi->is_active())
3318 return;
3320 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3321 DidUpdateFaviconURL(candidates));
3324 void WebContentsImpl::CreateAudioPowerSaveBlocker() {
3325 DCHECK(!audio_power_save_blocker_);
3326 audio_power_save_blocker_ = PowerSaveBlocker::Create(
3327 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension,
3328 PowerSaveBlocker::kReasonAudioPlayback, "Playing audio");
3331 void WebContentsImpl::CreateVideoPowerSaveBlocker() {
3332 DCHECK(!video_power_save_blocker_);
3333 DCHECK(!active_video_players_.empty());
3334 video_power_save_blocker_ = PowerSaveBlocker::Create(
3335 PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep,
3336 PowerSaveBlocker::kReasonVideoPlayback, "Playing video");
3337 #if defined(OS_ANDROID)
3338 static_cast<PowerSaveBlockerImpl*>(video_power_save_blocker_.get())
3339 ->InitDisplaySleepBlocker(this);
3340 #endif
3343 void WebContentsImpl::MaybeReleasePowerSaveBlockers() {
3344 // If there are no more audio players and we don't have audio stream
3345 // monitoring, release the audio power save blocker here instead of during
3346 // NotifyNavigationStateChanged().
3347 if (active_audio_players_.empty() &&
3348 !audio_state_provider_->IsAudioStateAvailable()) {
3349 audio_power_save_blocker_.reset();
3352 // If there are no more video players, clear the video power save blocker.
3353 if (active_video_players_.empty())
3354 video_power_save_blocker_.reset();
3357 void WebContentsImpl::OnMediaPlayingNotification(int64 player_cookie,
3358 bool has_video,
3359 bool has_audio,
3360 bool is_remote) {
3361 // Ignore the videos playing remotely and don't hold the wake lock for the
3362 // screen.
3363 if (is_remote) return;
3365 if (has_audio) {
3366 AddMediaPlayerEntry(player_cookie, &active_audio_players_);
3368 // If we don't have audio stream monitoring, allocate the audio power save
3369 // blocker here instead of during NotifyNavigationStateChanged().
3370 if (!audio_power_save_blocker_ &&
3371 !audio_state_provider_->IsAudioStateAvailable()) {
3372 CreateAudioPowerSaveBlocker();
3376 if (has_video) {
3377 AddMediaPlayerEntry(player_cookie, &active_video_players_);
3379 // If we're not hidden and have just created a player, create a blocker.
3380 if (!video_power_save_blocker_ && !IsHidden())
3381 CreateVideoPowerSaveBlocker();
3384 FOR_EACH_OBSERVER(WebContentsObserver, observers_, MediaStartedPlaying());
3387 void WebContentsImpl::OnMediaPausedNotification(int64 player_cookie) {
3388 RemoveMediaPlayerEntry(player_cookie, &active_audio_players_);
3389 RemoveMediaPlayerEntry(player_cookie, &active_video_players_);
3390 MaybeReleasePowerSaveBlockers();
3392 FOR_EACH_OBSERVER(WebContentsObserver, observers_, MediaPaused());
3395 #if defined(OS_ANDROID)
3397 void WebContentsImpl::OnMediaSessionStateChanged() {
3398 MediaSession* session = MediaSession::Get(this);
3399 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3400 MediaSessionStateChanged(session->IsControllable(),
3401 session->IsSuspended()));
3404 void WebContentsImpl::ResumeMediaSession() {
3405 MediaSession::Get(this)->Resume();
3408 void WebContentsImpl::SuspendMediaSession() {
3409 MediaSession::Get(this)->Suspend();
3412 #endif // defined(OS_ANDROID)
3414 void WebContentsImpl::OnFirstVisuallyNonEmptyPaint() {
3415 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3416 DidFirstVisuallyNonEmptyPaint());
3418 did_first_visually_non_empty_paint_ = true;
3420 if (theme_color_ != last_sent_theme_color_) {
3421 // Theme color should have updated by now if there was one.
3422 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3423 DidChangeThemeColor(theme_color_));
3424 last_sent_theme_color_ = theme_color_;
3428 void WebContentsImpl::DidChangeVisibleSSLState() {
3429 if (delegate_) {
3430 delegate_->VisibleSSLStateChanged(this);
3432 SecurityStyleExplanations security_style_explanations;
3433 SecurityStyle security_style =
3434 delegate_->GetSecurityStyle(this, &security_style_explanations);
3435 FOR_EACH_OBSERVER(
3436 WebContentsObserver, observers_,
3437 SecurityStyleChanged(security_style, security_style_explanations));
3441 void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
3442 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3443 BeforeFormRepostWarningShow());
3446 void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
3447 Activate();
3448 if (delegate_)
3449 delegate_->ShowRepostFormWarningDialog(this);
3452 bool WebContentsImpl::HasAccessedInitialDocument() {
3453 return has_accessed_initial_document_;
3456 // Notifies the RenderWidgetHost instance about the fact that the page is
3457 // loading, or done loading.
3458 void WebContentsImpl::SetIsLoading(bool is_loading,
3459 bool to_different_document,
3460 LoadNotificationDetails* details) {
3461 if (is_loading == is_loading_)
3462 return;
3464 if (!is_loading) {
3465 load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
3466 base::string16());
3467 load_state_host_.clear();
3468 upload_size_ = 0;
3469 upload_position_ = 0;
3472 GetRenderManager()->SetIsLoading(is_loading);
3474 is_loading_ = is_loading;
3475 waiting_for_response_ = is_loading;
3476 is_load_to_different_document_ = to_different_document;
3478 if (delegate_)
3479 delegate_->LoadingStateChanged(this, to_different_document);
3480 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
3482 std::string url = (details ? details->url.possibly_invalid_spec() : "NULL");
3483 if (is_loading) {
3484 TRACE_EVENT_ASYNC_BEGIN1("browser,navigation", "WebContentsImpl Loading",
3485 this, "URL", url);
3486 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidStartLoading());
3487 } else {
3488 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
3489 this, "URL", url);
3490 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidStopLoading());
3493 // TODO(avi): Remove. http://crbug.com/170921
3494 int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
3495 NotificationDetails det = NotificationService::NoDetails();
3496 if (details)
3497 det = Details<LoadNotificationDetails>(details);
3498 NotificationService::current()->Notify(
3499 type, Source<NavigationController>(&controller_), det);
3502 void WebContentsImpl::UpdateMaxPageIDIfNecessary(RenderViewHost* rvh) {
3503 // If we are creating a RVH for a restored controller, then we need to make
3504 // sure the RenderView starts with a next_page_id_ larger than the number
3505 // of restored entries. This must be called before the RenderView starts
3506 // navigating (to avoid a race between the browser updating max_page_id and
3507 // the renderer updating next_page_id_). Because of this, we only call this
3508 // from CreateRenderView and allow that to notify the RenderView for us.
3509 int max_restored_page_id = controller_.GetMaxRestoredPageID();
3510 if (max_restored_page_id >
3511 GetMaxPageIDForSiteInstance(rvh->GetSiteInstance()))
3512 UpdateMaxPageIDForSiteInstance(rvh->GetSiteInstance(),
3513 max_restored_page_id);
3516 bool WebContentsImpl::UpdateTitleForEntry(NavigationEntryImpl* entry,
3517 const base::string16& title) {
3518 // For file URLs without a title, use the pathname instead. In the case of a
3519 // synthesized title, we don't want the update to count toward the "one set
3520 // per page of the title to history."
3521 base::string16 final_title;
3522 bool explicit_set;
3523 if (entry && entry->GetURL().SchemeIsFile() && title.empty()) {
3524 final_title = base::UTF8ToUTF16(entry->GetURL().ExtractFileName());
3525 explicit_set = false; // Don't count synthetic titles toward the set limit.
3526 } else {
3527 base::TrimWhitespace(title, base::TRIM_ALL, &final_title);
3528 explicit_set = true;
3531 // If a page is created via window.open and never navigated,
3532 // there will be no navigation entry. In this situation,
3533 // |page_title_when_no_navigation_entry_| will be used for page title.
3534 if (entry) {
3535 if (final_title == entry->GetTitle())
3536 return false; // Nothing changed, don't bother.
3538 entry->SetTitle(final_title);
3539 } else {
3540 if (page_title_when_no_navigation_entry_ == final_title)
3541 return false; // Nothing changed, don't bother.
3543 page_title_when_no_navigation_entry_ = final_title;
3546 // Lastly, set the title for the view.
3547 view_->SetPageTitle(final_title);
3549 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3550 TitleWasSet(entry, explicit_set));
3552 return true;
3555 void WebContentsImpl::SendChangeLoadProgress() {
3556 loading_last_progress_update_ = base::TimeTicks::Now();
3557 if (delegate_)
3558 delegate_->LoadProgressChanged(this, frame_tree_.load_progress());
3561 void WebContentsImpl::ResetLoadProgressState() {
3562 frame_tree_.ResetLoadProgress();
3563 loading_weak_factory_.InvalidateWeakPtrs();
3564 loading_last_progress_update_ = base::TimeTicks();
3567 void WebContentsImpl::NotifyViewSwapped(RenderViewHost* old_host,
3568 RenderViewHost* new_host) {
3569 // After sending out a swap notification, we need to send a disconnect
3570 // notification so that clients that pick up a pointer to |this| can NULL the
3571 // pointer. See Bug 1230284.
3572 notify_disconnection_ = true;
3573 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3574 RenderViewHostChanged(old_host, new_host));
3576 // Ensure that the associated embedder gets cleared after a RenderViewHost
3577 // gets swapped, so we don't reuse the same embedder next time a
3578 // RenderViewHost is attached to this WebContents.
3579 RemoveBrowserPluginEmbedder();
3582 void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost* old_host,
3583 RenderFrameHost* new_host) {
3584 FOR_EACH_OBSERVER(WebContentsObserver,
3585 observers_,
3586 RenderFrameHostChanged(old_host, new_host));
3589 // TODO(avi): Remove this entire function because this notification is already
3590 // covered by two observer functions. http://crbug.com/170921
3591 void WebContentsImpl::NotifyDisconnected() {
3592 if (!notify_disconnection_)
3593 return;
3595 notify_disconnection_ = false;
3596 NotificationService::current()->Notify(
3597 NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
3598 Source<WebContents>(this),
3599 NotificationService::NoDetails());
3602 void WebContentsImpl::NotifyNavigationEntryCommitted(
3603 const LoadCommittedDetails& load_details) {
3604 FOR_EACH_OBSERVER(
3605 WebContentsObserver, observers_, NavigationEntryCommitted(load_details));
3608 bool WebContentsImpl::OnMessageReceived(RenderFrameHost* render_frame_host,
3609 const IPC::Message& message) {
3610 return OnMessageReceived(NULL, render_frame_host, message);
3613 const GURL& WebContentsImpl::GetMainFrameLastCommittedURL() const {
3614 return GetLastCommittedURL();
3617 void WebContentsImpl::RenderFrameCreated(RenderFrameHost* render_frame_host) {
3618 // Note this is only for subframes, the notification for the main frame
3619 // happens in RenderViewCreated.
3620 FOR_EACH_OBSERVER(WebContentsObserver,
3621 observers_,
3622 RenderFrameCreated(render_frame_host));
3623 SetAccessibilityModeOnFrame(accessibility_mode_, render_frame_host);
3626 void WebContentsImpl::RenderFrameDeleted(RenderFrameHost* render_frame_host) {
3627 ClearPowerSaveBlockers(render_frame_host);
3628 FOR_EACH_OBSERVER(WebContentsObserver,
3629 observers_,
3630 RenderFrameDeleted(render_frame_host));
3633 void WebContentsImpl::ShowContextMenu(RenderFrameHost* render_frame_host,
3634 const ContextMenuParams& params) {
3635 ContextMenuParams context_menu_params(params);
3636 // Allow WebContentsDelegates to handle the context menu operation first.
3637 if (delegate_ && delegate_->HandleContextMenu(context_menu_params))
3638 return;
3640 render_view_host_delegate_view_->ShowContextMenu(render_frame_host,
3641 context_menu_params);
3644 void WebContentsImpl::RunJavaScriptMessage(
3645 RenderFrameHost* render_frame_host,
3646 const base::string16& message,
3647 const base::string16& default_prompt,
3648 const GURL& frame_url,
3649 JavaScriptMessageType javascript_message_type,
3650 IPC::Message* reply_msg) {
3651 // Suppress JavaScript dialogs when requested. Also suppress messages when
3652 // showing an interstitial as it's shown over the previous page and we don't
3653 // want the hidden page's dialogs to interfere with the interstitial.
3654 bool suppress_this_message =
3655 static_cast<RenderFrameHostImpl*>(render_frame_host)->is_swapped_out() ||
3656 ShowingInterstitialPage() || !delegate_ ||
3657 delegate_->ShouldSuppressDialogs(this) ||
3658 !delegate_->GetJavaScriptDialogManager(this);
3660 if (!suppress_this_message) {
3661 std::string accept_lang = GetContentClient()->browser()->
3662 GetAcceptLangs(GetBrowserContext());
3663 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
3664 dialog_manager_->RunJavaScriptDialog(
3665 this,
3666 frame_url.GetOrigin(),
3667 accept_lang,
3668 javascript_message_type,
3669 message,
3670 default_prompt,
3671 base::Bind(&WebContentsImpl::OnDialogClosed,
3672 base::Unretained(this),
3673 render_frame_host->GetProcess()->GetID(),
3674 render_frame_host->GetRoutingID(),
3675 reply_msg,
3676 false),
3677 &suppress_this_message);
3680 if (suppress_this_message) {
3681 // If we are suppressing messages, just reply as if the user immediately
3682 // pressed "Cancel", passing true to |dialog_was_suppressed|.
3683 OnDialogClosed(render_frame_host->GetProcess()->GetID(),
3684 render_frame_host->GetRoutingID(), reply_msg,
3685 true, false, base::string16());
3688 // OnDialogClosed (two lines up) may have caused deletion of this object (see
3689 // http://crbug.com/288961 ). The only safe thing to do here is return.
3692 void WebContentsImpl::RunBeforeUnloadConfirm(
3693 RenderFrameHost* render_frame_host,
3694 const base::string16& message,
3695 bool is_reload,
3696 IPC::Message* reply_msg) {
3697 RenderFrameHostImpl* rfhi =
3698 static_cast<RenderFrameHostImpl*>(render_frame_host);
3699 if (delegate_)
3700 delegate_->WillRunBeforeUnloadConfirm();
3702 bool suppress_this_message =
3703 rfhi->rfh_state() != RenderFrameHostImpl::STATE_DEFAULT ||
3704 ShowingInterstitialPage() || !delegate_ ||
3705 delegate_->ShouldSuppressDialogs(this) ||
3706 !delegate_->GetJavaScriptDialogManager(this);
3707 if (suppress_this_message) {
3708 rfhi->JavaScriptDialogClosed(reply_msg, true, base::string16(), true);
3709 return;
3712 is_showing_before_unload_dialog_ = true;
3713 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
3714 dialog_manager_->RunBeforeUnloadDialog(
3715 this, message, is_reload,
3716 base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
3717 render_frame_host->GetProcess()->GetID(),
3718 render_frame_host->GetRoutingID(), reply_msg,
3719 false));
3722 WebContents* WebContentsImpl::GetAsWebContents() {
3723 return this;
3726 bool WebContentsImpl::IsNeverVisible() {
3727 if (!delegate_)
3728 return false;
3729 return delegate_->IsNeverVisible(this);
3732 #if defined(OS_WIN)
3733 gfx::NativeViewAccessible WebContentsImpl::GetParentNativeViewAccessible() {
3734 return accessible_parent_;
3736 #endif
3738 RenderViewHostDelegateView* WebContentsImpl::GetDelegateView() {
3739 return render_view_host_delegate_view_;
3742 RendererPreferences WebContentsImpl::GetRendererPrefs(
3743 BrowserContext* browser_context) const {
3744 return renderer_preferences_;
3747 gfx::Rect WebContentsImpl::GetRootWindowResizerRect() const {
3748 if (delegate_)
3749 return delegate_->GetRootWindowResizerRect();
3750 return gfx::Rect();
3753 void WebContentsImpl::RemoveBrowserPluginEmbedder() {
3754 if (browser_plugin_embedder_)
3755 browser_plugin_embedder_.reset();
3758 void WebContentsImpl::RenderViewCreated(RenderViewHost* render_view_host) {
3759 // Don't send notifications if we are just creating a swapped-out RVH for
3760 // the opener chain. These won't be used for view-source or WebUI, so it's
3761 // ok to return early.
3762 if (!static_cast<RenderViewHostImpl*>(render_view_host)->is_active())
3763 return;
3765 if (delegate_)
3766 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
3768 NotificationService::current()->Notify(
3769 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
3770 Source<WebContents>(this),
3771 Details<RenderViewHost>(render_view_host));
3773 // When we're creating views, we're still doing initial setup, so we always
3774 // use the pending Web UI rather than any possibly existing committed one.
3775 if (GetRenderManager()->pending_web_ui())
3776 GetRenderManager()->pending_web_ui()->RenderViewCreated(render_view_host);
3778 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
3779 switches::kEnableBrowserSideNavigation) &&
3780 GetRenderManager()->speculative_web_ui()) {
3781 GetRenderManager()->speculative_web_ui()->RenderViewCreated(
3782 render_view_host);
3785 NavigationEntry* entry = controller_.GetPendingEntry();
3786 if (entry && entry->IsViewSourceMode()) {
3787 // Put the renderer in view source mode.
3788 render_view_host->Send(
3789 new ViewMsg_EnableViewSourceMode(render_view_host->GetRoutingID()));
3792 view_->RenderViewCreated(render_view_host);
3794 FOR_EACH_OBSERVER(
3795 WebContentsObserver, observers_, RenderViewCreated(render_view_host));
3798 void WebContentsImpl::RenderViewReady(RenderViewHost* rvh) {
3799 if (rvh != GetRenderViewHost()) {
3800 // Don't notify the world, since this came from a renderer in the
3801 // background.
3802 return;
3805 notify_disconnection_ = true;
3806 // TODO(avi): Remove. http://crbug.com/170921
3807 NotificationService::current()->Notify(
3808 NOTIFICATION_WEB_CONTENTS_CONNECTED,
3809 Source<WebContents>(this),
3810 NotificationService::NoDetails());
3812 bool was_crashed = IsCrashed();
3813 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
3815 // Restore the focus to the tab (otherwise the focus will be on the top
3816 // window).
3817 if (was_crashed && !FocusLocationBarByDefault() &&
3818 (!delegate_ || delegate_->ShouldFocusPageAfterCrash())) {
3819 view_->Focus();
3822 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewReady());
3825 void WebContentsImpl::RenderViewTerminated(RenderViewHost* rvh,
3826 base::TerminationStatus status,
3827 int error_code) {
3828 if (rvh != GetRenderViewHost()) {
3829 // The pending page's RenderViewHost is gone.
3830 return;
3833 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
3834 // renderer may not have made a clean exit.
3835 if (IsFullscreenForCurrentTab())
3836 ExitFullscreenMode();
3838 // Cancel any visible dialogs so they are not left dangling over the sad tab.
3839 CancelActiveAndPendingDialogs();
3841 if (delegate_)
3842 delegate_->HideValidationMessage(this);
3844 SetIsLoading(false, true, nullptr);
3845 NotifyDisconnected();
3846 SetIsCrashed(status, error_code);
3848 // Reset the loading progress. TODO(avi): What does it mean to have a
3849 // "renderer crash" when there is more than one renderer process serving a
3850 // webpage? Once this function is called at a more granular frame level, we
3851 // probably will need to more granularly reset the state here.
3852 ResetLoadProgressState();
3854 FOR_EACH_OBSERVER(WebContentsObserver,
3855 observers_,
3856 RenderProcessGone(GetCrashedStatus()));
3859 void WebContentsImpl::RenderViewDeleted(RenderViewHost* rvh) {
3860 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewDeleted(rvh));
3863 void WebContentsImpl::UpdateState(RenderViewHost* rvh,
3864 int32 page_id,
3865 const PageState& page_state) {
3866 // Ensure that this state update comes from a RenderViewHost that belongs to
3867 // this WebContents.
3868 // TODO(nasko): This should go through RenderFrameHost.
3869 if (rvh->GetDelegate()->GetAsWebContents() != this)
3870 return;
3872 // We must be prepared to handle state updates for any page. They occur
3873 // when the user is scrolling and entering form data, as well as when we're
3874 // leaving a page, in which case our state may have already been moved to
3875 // the next page. The navigation controller will look up the appropriate
3876 // NavigationEntry and update it when it is notified via the delegate.
3877 RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(rvh);
3878 NavigationEntryImpl* entry = controller_.GetEntryWithPageID(
3879 rvhi->GetSiteInstance(), page_id);
3880 if (!entry)
3881 return;
3883 NavigationEntryImpl* new_entry = controller_.GetEntryWithUniqueID(
3884 rvhi->nav_entry_id());
3886 if (SiteIsolationPolicy::UseSubframeNavigationEntries()) {
3887 // TODO(creis): We can't properly update state for cross-process subframes
3888 // until PageState is decomposed into FrameStates. Until then, use the new
3889 // method.
3890 entry = new_entry;
3891 } else {
3892 DCHECK_EQ(entry, new_entry);
3895 if (page_state == entry->GetPageState())
3896 return; // Nothing to update.
3897 entry->SetPageState(page_state);
3898 controller_.NotifyEntryChanged(entry);
3901 void WebContentsImpl::UpdateTargetURL(RenderViewHost* render_view_host,
3902 const GURL& url) {
3903 if (fullscreen_widget_routing_id_ != MSG_ROUTING_NONE) {
3904 // If we're fullscreen only update the url if it's from the fullscreen
3905 // renderer.
3906 RenderWidgetHostView* fs = GetFullscreenRenderWidgetHostView();
3907 if (fs && fs->GetRenderWidgetHost() != render_view_host)
3908 return;
3910 if (delegate_)
3911 delegate_->UpdateTargetURL(this, url);
3914 void WebContentsImpl::Close(RenderViewHost* rvh) {
3915 #if defined(OS_MACOSX)
3916 // The UI may be in an event-tracking loop, such as between the
3917 // mouse-down and mouse-up in text selection or a button click.
3918 // Defer the close until after tracking is complete, so that we
3919 // don't free objects out from under the UI.
3920 // TODO(shess): This could get more fine-grained. For instance,
3921 // closing a tab in another window while selecting text in the
3922 // current window's Omnibox should be just fine.
3923 if (view_->IsEventTracking()) {
3924 view_->CloseTabAfterEventTracking();
3925 return;
3927 #endif
3929 // Ignore this if it comes from a RenderViewHost that we aren't showing.
3930 if (delegate_ && rvh == GetRenderViewHost())
3931 delegate_->CloseContents(this);
3934 void WebContentsImpl::SwappedOut(RenderFrameHost* rfh) {
3935 if (delegate_ && rfh->GetRenderViewHost() == GetRenderViewHost())
3936 delegate_->SwappedOut(this);
3939 void WebContentsImpl::RequestMove(const gfx::Rect& new_bounds) {
3940 if (delegate_ && delegate_->IsPopupOrPanel(this))
3941 delegate_->MoveContents(this, new_bounds);
3944 void WebContentsImpl::DidStartLoading(FrameTreeNode* frame_tree_node,
3945 bool to_different_document) {
3946 SetIsLoading(true, to_different_document, nullptr);
3948 // Notify accessibility that the user is navigating away from the
3949 // current document.
3951 // TODO(dmazzoni): do this using a WebContentsObserver.
3952 BrowserAccessibilityManager* manager =
3953 frame_tree_node->current_frame_host()->browser_accessibility_manager();
3954 if (manager)
3955 manager->UserIsNavigatingAway();
3958 void WebContentsImpl::DidStopLoading() {
3959 scoped_ptr<LoadNotificationDetails> details;
3961 // Use the last committed entry rather than the active one, in case a
3962 // pending entry has been created.
3963 NavigationEntry* entry = controller_.GetLastCommittedEntry();
3964 Navigator* navigator = frame_tree_.root()->navigator();
3966 // An entry may not exist for a stop when loading an initial blank page or
3967 // if an iframe injected by script into a blank page finishes loading.
3968 if (entry) {
3969 base::TimeDelta elapsed =
3970 base::TimeTicks::Now() - navigator->GetCurrentLoadStart();
3972 details.reset(new LoadNotificationDetails(
3973 entry->GetVirtualURL(),
3974 entry->GetTransitionType(),
3975 elapsed,
3976 &controller_,
3977 controller_.GetCurrentEntryIndex()));
3980 SetIsLoading(false, true, details.get());
3983 void WebContentsImpl::DidChangeLoadProgress() {
3984 double load_progress = frame_tree_.load_progress();
3986 // The delegate is notified immediately for the first and last updates. Also,
3987 // since the message loop may be pretty busy when a page is loaded, it might
3988 // not execute a posted task in a timely manner so the progress report is sent
3989 // immediately if enough time has passed.
3990 base::TimeDelta min_delay =
3991 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS);
3992 bool delay_elapsed = loading_last_progress_update_.is_null() ||
3993 base::TimeTicks::Now() - loading_last_progress_update_ > min_delay;
3995 if (load_progress == 0.0 || load_progress == 1.0 || delay_elapsed) {
3996 // If there is a pending task to send progress, it is now obsolete.
3997 loading_weak_factory_.InvalidateWeakPtrs();
3999 // Notify the load progress change.
4000 SendChangeLoadProgress();
4002 // Clean-up the states if needed.
4003 if (load_progress == 1.0)
4004 ResetLoadProgressState();
4005 return;
4008 if (loading_weak_factory_.HasWeakPtrs())
4009 return;
4011 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
4012 FROM_HERE, base::Bind(&WebContentsImpl::SendChangeLoadProgress,
4013 loading_weak_factory_.GetWeakPtr()),
4014 min_delay);
4017 void WebContentsImpl::DidCancelLoading() {
4018 controller_.DiscardNonCommittedEntries();
4020 // Update the URL display.
4021 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
4024 void WebContentsImpl::DidAccessInitialDocument() {
4025 has_accessed_initial_document_ = true;
4027 // We may have left a failed browser-initiated navigation in the address bar
4028 // to let the user edit it and try again. Clear it now that content might
4029 // show up underneath it.
4030 if (!IsLoading() && controller_.GetPendingEntry())
4031 controller_.DiscardPendingEntry(false);
4033 // Update the URL display.
4034 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
4037 void WebContentsImpl::DidChangeName(RenderFrameHost* render_frame_host,
4038 const std::string& name) {
4039 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4040 FrameNameChanged(render_frame_host, name));
4043 void WebContentsImpl::DocumentOnLoadCompleted(
4044 RenderFrameHost* render_frame_host) {
4045 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4046 DocumentOnLoadCompletedInMainFrame());
4048 // TODO(avi): Remove. http://crbug.com/170921
4049 NotificationService::current()->Notify(
4050 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
4051 Source<WebContents>(this),
4052 NotificationService::NoDetails());
4055 void WebContentsImpl::UpdateTitle(RenderFrameHost* render_frame_host,
4056 int32 page_id,
4057 const base::string16& title,
4058 base::i18n::TextDirection title_direction) {
4059 // If we have a title, that's a pretty good indication that we've started
4060 // getting useful data.
4061 SetNotWaitingForResponse();
4063 // Try to find the navigation entry, which might not be the current one.
4064 // For example, it might be from a recently swapped out RFH.
4065 NavigationEntryImpl* entry = controller_.GetEntryWithPageID(
4066 render_frame_host->GetSiteInstance(), page_id);
4068 RenderViewHostImpl* rvhi =
4069 static_cast<RenderViewHostImpl*>(render_frame_host->GetRenderViewHost());
4070 NavigationEntryImpl* new_entry = controller_.GetEntryWithUniqueID(
4071 rvhi->nav_entry_id());
4072 DCHECK_EQ(entry, new_entry);
4074 // We can handle title updates when we don't have an entry in
4075 // UpdateTitleForEntry, but only if the update is from the current RVH.
4076 // TODO(avi): Change to make decisions based on the RenderFrameHost.
4077 if (!entry && render_frame_host != GetMainFrame())
4078 return;
4080 // TODO(evan): make use of title_direction.
4081 // http://code.google.com/p/chromium/issues/detail?id=27094
4082 if (!UpdateTitleForEntry(entry, title))
4083 return;
4085 // Broadcast notifications when the UI should be updated.
4086 if (entry == controller_.GetEntryAtOffset(0))
4087 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
4090 void WebContentsImpl::UpdateEncoding(RenderFrameHost* render_frame_host,
4091 const std::string& encoding) {
4092 SetEncoding(encoding);
4095 void WebContentsImpl::DocumentAvailableInMainFrame(
4096 RenderViewHost* render_view_host) {
4097 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4098 DocumentAvailableInMainFrame());
4101 void WebContentsImpl::RouteCloseEvent(RenderViewHost* rvh) {
4102 // Tell the active RenderViewHost to run unload handlers and close, as long
4103 // as the request came from a RenderViewHost in the same BrowsingInstance.
4104 // In most cases, we receive this from a swapped out RenderViewHost.
4105 // It is possible to receive it from one that has just been swapped in,
4106 // in which case we might as well deliver the message anyway.
4107 if (rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()))
4108 ClosePage();
4111 bool WebContentsImpl::ShouldRouteMessageEvent(
4112 RenderFrameHost* target_rfh,
4113 SiteInstance* source_site_instance) const {
4114 // Allow the message if this WebContents is dedicated to a browser plugin
4115 // guest.
4116 // Note: This check means that an embedder could theoretically receive a
4117 // postMessage from anyone (not just its own guests). However, this is
4118 // probably not a risk for apps since other pages won't have references
4119 // to App windows.
4120 return GetBrowserPluginGuest() || GetBrowserPluginEmbedder();
4123 void WebContentsImpl::EnsureOpenerProxiesExist(RenderFrameHost* source_rfh) {
4124 WebContentsImpl* source_web_contents = static_cast<WebContentsImpl*>(
4125 WebContents::FromRenderFrameHost(source_rfh));
4127 if (source_web_contents) {
4128 // If this message is going to outer WebContents from inner WebContents,
4129 // then we should not create a RenderView. AttachToOuterWebContentsFrame()
4130 // already created a RenderFrameProxyHost for that purpose.
4131 if (GetBrowserPluginEmbedder() &&
4132 BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
4133 return;
4136 if (GetBrowserPluginGuest()) {
4137 // We create a swapped out RenderView for the embedder in the guest's
4138 // render process but we intentionally do not expose the embedder's
4139 // opener chain to it.
4140 source_web_contents->CreateSwappedOutRenderView(GetSiteInstance());
4141 } else {
4142 RenderFrameHostImpl* source_rfhi =
4143 static_cast<RenderFrameHostImpl*>(source_rfh);
4144 source_rfhi->frame_tree_node()->render_manager()->CreateOpenerProxies(
4145 GetSiteInstance());
4150 bool WebContentsImpl::AddMessageToConsole(int32 level,
4151 const base::string16& message,
4152 int32 line_no,
4153 const base::string16& source_id) {
4154 if (!delegate_)
4155 return false;
4156 return delegate_->AddMessageToConsole(this, level, message, line_no,
4157 source_id);
4160 int WebContentsImpl::CreateSwappedOutRenderView(
4161 SiteInstance* instance) {
4162 int render_view_routing_id = MSG_ROUTING_NONE;
4163 if (SiteIsolationPolicy::IsSwappedOutStateForbidden()) {
4164 GetRenderManager()->CreateRenderFrameProxy(instance);
4165 } else {
4166 GetRenderManager()->CreateRenderFrame(
4167 instance, nullptr,
4168 CREATE_RF_SWAPPED_OUT | CREATE_RF_FOR_MAIN_FRAME_NAVIGATION |
4169 CREATE_RF_HIDDEN,
4170 &render_view_routing_id);
4172 return render_view_routing_id;
4175 void WebContentsImpl::OnUserGesture() {
4176 // Notify observers.
4177 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetUserGesture());
4179 ResourceDispatcherHostImpl* rdh = ResourceDispatcherHostImpl::Get();
4180 if (rdh) // NULL in unittests.
4181 rdh->OnUserGesture(this);
4184 void WebContentsImpl::OnIgnoredUIEvent() {
4185 // Notify observers.
4186 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetIgnoredUIEvent());
4189 void WebContentsImpl::RendererUnresponsive(RenderViewHost* render_view_host) {
4190 // Don't show hung renderer dialog for a swapped out RVH.
4191 if (render_view_host != GetRenderViewHost())
4192 return;
4194 RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(render_view_host);
4195 RenderFrameHostImpl* rfhi =
4196 static_cast<RenderFrameHostImpl*>(rvhi->GetMainFrame());
4198 // Ignore renderer unresponsive event if debugger is attached to the tab
4199 // since the event may be a result of the renderer sitting on a breakpoint.
4200 // See http://crbug.com/65458
4201 if (DevToolsAgentHost::IsDebuggerAttached(this))
4202 return;
4204 if (rfhi->is_waiting_for_beforeunload_ack() ||
4205 rfhi->IsWaitingForUnloadACK()) {
4206 // Hang occurred while firing the beforeunload/unload handler.
4207 // Pretend the handler fired so tab closing continues as if it had.
4208 rvhi->set_sudden_termination_allowed(true);
4210 if (!GetRenderManager()->ShouldCloseTabOnUnresponsiveRenderer())
4211 return;
4213 // If the tab hangs in the beforeunload/unload handler there's really
4214 // nothing we can do to recover. If the hang is in the beforeunload handler,
4215 // pretend the beforeunload listeners have all fired and allow the delegate
4216 // to continue closing; the user will not have the option of cancelling the
4217 // close. Otherwise, pretend the unload listeners have all fired and close
4218 // the tab.
4219 bool close = true;
4220 if (rfhi->is_waiting_for_beforeunload_ack() && delegate_) {
4221 delegate_->BeforeUnloadFired(this, true, &close);
4223 if (close)
4224 Close(rvhi);
4225 return;
4228 if (!GetRenderViewHost() || !GetRenderViewHost()->IsRenderViewLive())
4229 return;
4231 if (delegate_)
4232 delegate_->RendererUnresponsive(this);
4235 void WebContentsImpl::RendererResponsive(RenderViewHost* render_view_host) {
4236 if (delegate_)
4237 delegate_->RendererResponsive(this);
4240 void WebContentsImpl::LoadStateChanged(
4241 const GURL& url,
4242 const net::LoadStateWithParam& load_state,
4243 uint64 upload_position,
4244 uint64 upload_size) {
4245 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
4246 // is fixed.
4247 tracked_objects::ScopedTracker tracking_profile1(
4248 FROM_HERE_WITH_EXPLICIT_FUNCTION(
4249 "466285 WebContentsImpl::LoadStateChanged::Start"));
4250 load_state_ = load_state;
4251 upload_position_ = upload_position;
4252 upload_size_ = upload_size;
4253 load_state_host_ = net::IDNToUnicode(url.host(),
4254 GetContentClient()->browser()->GetAcceptLangs(
4255 GetBrowserContext()));
4256 if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
4257 SetNotWaitingForResponse();
4258 if (IsLoading()) {
4259 NotifyNavigationStateChanged(static_cast<InvalidateTypes>(
4260 INVALIDATE_TYPE_LOAD | INVALIDATE_TYPE_TAB));
4264 void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
4265 bool proceed, const base::TimeTicks& proceed_time,
4266 bool* proceed_to_fire_unload) {
4267 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4268 BeforeUnloadFired(proceed_time));
4269 if (delegate_)
4270 delegate_->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
4271 // Note: |this| might be deleted at this point.
4274 void WebContentsImpl::RenderProcessGoneFromRenderManager(
4275 RenderViewHost* render_view_host) {
4276 DCHECK(crashed_status_ != base::TERMINATION_STATUS_STILL_RUNNING);
4277 RenderViewTerminated(render_view_host, crashed_status_, crashed_error_code_);
4280 void WebContentsImpl::UpdateRenderViewSizeForRenderManager() {
4281 // TODO(brettw) this is a hack. See WebContentsView::SizeContents.
4282 gfx::Size size = GetSizeForNewRenderView();
4283 // 0x0 isn't a valid window size (minimal window size is 1x1) but it may be
4284 // here during container initialization and normal window size will be set
4285 // later. In case of tab duplication this resizing to 0x0 prevents setting
4286 // normal size later so just ignore it.
4287 if (!size.IsEmpty())
4288 view_->SizeContents(size);
4291 void WebContentsImpl::CancelModalDialogsForRenderManager() {
4292 // We need to cancel modal dialogs when doing a process swap, since the load
4293 // deferrer would prevent us from swapping out. We also clear the state
4294 // because this is a cross-process navigation, which means that it's a new
4295 // site that should not have to pay for the sins of its predecessor.
4297 // Note that we don't bother telling browser_plugin_embedder_ because the
4298 // cross-process navigation will either destroy the browser plugins or not
4299 // require their dialogs to close.
4300 if (dialog_manager_)
4301 dialog_manager_->ResetDialogState(this);
4304 void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost* old_host,
4305 RenderFrameHost* new_host,
4306 bool is_main_frame) {
4307 if (is_main_frame) {
4308 NotifyViewSwapped(old_host ? old_host->GetRenderViewHost() : nullptr,
4309 new_host->GetRenderViewHost());
4311 // Make sure the visible RVH reflects the new delegate's preferences.
4312 if (delegate_)
4313 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
4315 view_->RenderViewSwappedIn(new_host->GetRenderViewHost());
4318 NotifyFrameSwapped(old_host, new_host);
4321 void WebContentsImpl::NotifyMainFrameSwappedFromRenderManager(
4322 RenderViewHost* old_host,
4323 RenderViewHost* new_host) {
4324 NotifyViewSwapped(old_host, new_host);
4327 NavigationControllerImpl& WebContentsImpl::GetControllerForRenderManager() {
4328 return GetController();
4331 scoped_ptr<WebUIImpl> WebContentsImpl::CreateWebUIForRenderManager(
4332 const GURL& url) {
4333 return scoped_ptr<WebUIImpl>(static_cast<WebUIImpl*>(CreateWebUI(url)));
4336 NavigationEntry*
4337 WebContentsImpl::GetLastCommittedNavigationEntryForRenderManager() {
4338 return controller_.GetLastCommittedEntry();
4341 bool WebContentsImpl::CreateRenderViewForRenderManager(
4342 RenderViewHost* render_view_host,
4343 int opener_frame_routing_id,
4344 int proxy_routing_id,
4345 const FrameReplicationState& replicated_frame_state,
4346 bool for_main_frame_navigation) {
4347 TRACE_EVENT0("browser,navigation",
4348 "WebContentsImpl::CreateRenderViewForRenderManager");
4349 // Can be NULL during tests.
4350 RenderWidgetHostViewBase* rwh_view;
4351 // TODO(kenrb): RenderWidgetHostViewChildFrame special casing is temporary
4352 // until RenderWidgetHost is attached to RenderFrameHost. We need to special
4353 // case this because RWH is still a base class of RenderViewHost, and child
4354 // frame RWHVs are unique in that they do not have their own WebContents.
4355 bool is_guest_in_site_per_process =
4356 !!browser_plugin_guest_.get() &&
4357 BrowserPluginGuestMode::UseCrossProcessFramesForGuests();
4358 if (!for_main_frame_navigation || is_guest_in_site_per_process) {
4359 RenderWidgetHostViewChildFrame* rwh_view_child =
4360 new RenderWidgetHostViewChildFrame(render_view_host);
4361 rwh_view = rwh_view_child;
4362 } else {
4363 rwh_view = view_->CreateViewForWidget(render_view_host, false);
4366 // Now that the RenderView has been created, we need to tell it its size.
4367 if (rwh_view)
4368 rwh_view->SetSize(GetSizeForNewRenderView());
4370 // Make sure we use the correct starting page_id in the new RenderView.
4371 UpdateMaxPageIDIfNecessary(render_view_host);
4372 int32 max_page_id =
4373 GetMaxPageIDForSiteInstance(render_view_host->GetSiteInstance());
4375 if (!static_cast<RenderViewHostImpl*>(render_view_host)
4376 ->CreateRenderView(opener_frame_routing_id, proxy_routing_id,
4377 max_page_id, replicated_frame_state,
4378 created_with_opener_)) {
4379 return false;
4382 SetHistoryOffsetAndLengthForView(render_view_host,
4383 controller_.GetLastCommittedEntryIndex(),
4384 controller_.GetEntryCount());
4386 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
4387 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
4388 // linux. See crbug.com/83941.
4389 if (rwh_view) {
4390 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
4391 render_widget_host->WasResized();
4393 #endif
4395 return true;
4398 bool WebContentsImpl::CreateRenderFrameForRenderManager(
4399 RenderFrameHost* render_frame_host,
4400 int parent_routing_id,
4401 int previous_sibling_routing_id,
4402 int proxy_routing_id) {
4403 TRACE_EVENT0("browser,navigation",
4404 "WebContentsImpl::CreateRenderFrameForRenderManager");
4406 RenderFrameHostImpl* rfh =
4407 static_cast<RenderFrameHostImpl*>(render_frame_host);
4408 if (!rfh->CreateRenderFrame(parent_routing_id, previous_sibling_routing_id,
4409 proxy_routing_id))
4410 return false;
4412 // TODO(nasko): When RenderWidgetHost is owned by RenderFrameHost, the passed
4413 // RenderFrameHost will have to be associated with the appropriate
4414 // RenderWidgetHostView or a new one should be created here.
4416 return true;
4419 #if defined(OS_ANDROID)
4421 base::android::ScopedJavaLocalRef<jobject>
4422 WebContentsImpl::GetJavaWebContents() {
4423 DCHECK_CURRENTLY_ON(BrowserThread::UI);
4424 return GetWebContentsAndroid()->GetJavaObject();
4427 WebContentsAndroid* WebContentsImpl::GetWebContentsAndroid() {
4428 WebContentsAndroid* web_contents_android =
4429 static_cast<WebContentsAndroid*>(GetUserData(kWebContentsAndroidKey));
4430 if (!web_contents_android) {
4431 web_contents_android = new WebContentsAndroid(this);
4432 SetUserData(kWebContentsAndroidKey, web_contents_android);
4434 return web_contents_android;
4437 bool WebContentsImpl::CreateRenderViewForInitialEmptyDocument() {
4438 return CreateRenderViewForRenderManager(
4439 GetRenderViewHost(), MSG_ROUTING_NONE, MSG_ROUTING_NONE,
4440 frame_tree_.root()->current_replication_state(), true);
4443 #elif defined(OS_MACOSX)
4445 void WebContentsImpl::SetAllowOtherViews(bool allow) {
4446 view_->SetAllowOtherViews(allow);
4449 bool WebContentsImpl::GetAllowOtherViews() {
4450 return view_->GetAllowOtherViews();
4453 #endif
4455 void WebContentsImpl::OnDialogClosed(int render_process_id,
4456 int render_frame_id,
4457 IPC::Message* reply_msg,
4458 bool dialog_was_suppressed,
4459 bool success,
4460 const base::string16& user_input) {
4461 RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(render_process_id,
4462 render_frame_id);
4463 last_dialog_suppressed_ = dialog_was_suppressed;
4465 if (is_showing_before_unload_dialog_ && !success) {
4466 // If a beforeunload dialog is canceled, we need to stop the throbber from
4467 // spinning, since we forced it to start spinning in Navigate.
4468 if (rfh)
4469 DidStopLoading();
4470 controller_.DiscardNonCommittedEntries();
4472 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4473 BeforeUnloadDialogCancelled());
4476 is_showing_before_unload_dialog_ = false;
4477 if (rfh) {
4478 rfh->JavaScriptDialogClosed(reply_msg, success, user_input,
4479 dialog_was_suppressed);
4480 } else {
4481 // Don't leak the sync IPC reply if the RFH or process is gone.
4482 delete reply_msg;
4486 void WebContentsImpl::SetEncoding(const std::string& encoding) {
4487 if (encoding == last_reported_encoding_)
4488 return;
4489 last_reported_encoding_ = encoding;
4491 canonical_encoding_ = GetContentClient()->browser()->
4492 GetCanonicalEncodingNameByAliasName(encoding);
4495 bool WebContentsImpl::IsHidden() {
4496 return capturer_count_ == 0 && !should_normally_be_visible_;
4499 int WebContentsImpl::GetOuterDelegateFrameTreeNodeID() {
4500 if (node_ && node_->outer_web_contents())
4501 return node_->outer_contents_frame_tree_node_id();
4503 return FrameTreeNode::kFrameTreeNodeInvalidID;
4506 RenderFrameHostManager* WebContentsImpl::GetRenderManager() const {
4507 return frame_tree_.root()->render_manager();
4510 BrowserPluginGuest* WebContentsImpl::GetBrowserPluginGuest() const {
4511 return browser_plugin_guest_.get();
4514 void WebContentsImpl::SetBrowserPluginGuest(BrowserPluginGuest* guest) {
4515 CHECK(!browser_plugin_guest_);
4516 CHECK(guest);
4517 browser_plugin_guest_.reset(guest);
4520 BrowserPluginEmbedder* WebContentsImpl::GetBrowserPluginEmbedder() const {
4521 return browser_plugin_embedder_.get();
4524 void WebContentsImpl::CreateBrowserPluginEmbedderIfNecessary() {
4525 if (browser_plugin_embedder_)
4526 return;
4527 browser_plugin_embedder_.reset(BrowserPluginEmbedder::Create(this));
4530 void WebContentsImpl::ClearPowerSaveBlockers(
4531 RenderFrameHost* render_frame_host) {
4532 RemoveAllMediaPlayerEntries(render_frame_host, &active_audio_players_);
4533 RemoveAllMediaPlayerEntries(render_frame_host, &active_video_players_);
4534 MaybeReleasePowerSaveBlockers();
4537 void WebContentsImpl::ClearAllPowerSaveBlockers() {
4538 active_audio_players_.clear();
4539 active_video_players_.clear();
4540 audio_power_save_blocker_.reset();
4541 video_power_save_blocker_.reset();
4544 gfx::Size WebContentsImpl::GetSizeForNewRenderView() {
4545 gfx::Size size;
4546 if (delegate_)
4547 size = delegate_->GetSizeForNewRenderView(this);
4548 if (size.IsEmpty())
4549 size = GetContainerBounds().size();
4550 return size;
4553 void WebContentsImpl::OnFrameRemoved(RenderFrameHost* render_frame_host) {
4554 FOR_EACH_OBSERVER(
4555 WebContentsObserver, observers_, FrameDeleted(render_frame_host));
4558 void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size& old_size) {
4559 if (!delegate_)
4560 return;
4561 const gfx::Size new_size = GetPreferredSize();
4562 if (new_size != old_size)
4563 delegate_->UpdatePreferredSize(this, new_size);
4566 void WebContentsImpl::AddMediaPlayerEntry(int64 player_cookie,
4567 ActiveMediaPlayerMap* player_map) {
4568 if (!HasValidFrameSource())
4569 return;
4571 const uintptr_t key =
4572 reinterpret_cast<uintptr_t>(render_frame_message_source_);
4573 DCHECK(std::find((*player_map)[key].begin(),
4574 (*player_map)[key].end(),
4575 player_cookie) == (*player_map)[key].end());
4576 (*player_map)[key].push_back(player_cookie);
4579 void WebContentsImpl::RemoveMediaPlayerEntry(int64 player_cookie,
4580 ActiveMediaPlayerMap* player_map) {
4581 if (!HasValidFrameSource())
4582 return;
4584 const uintptr_t key =
4585 reinterpret_cast<uintptr_t>(render_frame_message_source_);
4586 ActiveMediaPlayerMap::iterator it = player_map->find(key);
4587 if (it == player_map->end())
4588 return;
4590 // Remove the player.
4591 PlayerList::iterator player_it =
4592 std::find(it->second.begin(), it->second.end(), player_cookie);
4593 if (player_it != it->second.end())
4594 it->second.erase(player_it);
4596 // If there are no players left, remove the map entry.
4597 if (it->second.empty())
4598 player_map->erase(it);
4601 void WebContentsImpl::RemoveAllMediaPlayerEntries(
4602 RenderFrameHost* render_frame_host,
4603 ActiveMediaPlayerMap* player_map) {
4604 ActiveMediaPlayerMap::iterator it =
4605 player_map->find(reinterpret_cast<uintptr_t>(render_frame_host));
4606 if (it == player_map->end())
4607 return;
4608 player_map->erase(it);
4611 void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable) {
4612 force_disable_overscroll_content_ = force_disable;
4613 if (view_)
4614 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
4617 } // namespace content