[refactor] More post-NSS WebCrypto cleanups (utility functions).
[chromium-blink-merge.git] / content / browser / web_contents / web_contents_impl.cc
blob78689f2f694ead9c86e9618ce32b762feadb76b4
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 "components/url_formatter/url_formatter.h"
26 #include "content/browser/accessibility/accessibility_mode_helper.h"
27 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
28 #include "content/browser/bad_message.h"
29 #include "content/browser/browser_plugin/browser_plugin_embedder.h"
30 #include "content/browser/browser_plugin/browser_plugin_guest.h"
31 #include "content/browser/child_process_security_policy_impl.h"
32 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
33 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
34 #include "content/browser/download/download_stats.h"
35 #include "content/browser/download/mhtml_generation_manager.h"
36 #include "content/browser/download/save_package.h"
37 #include "content/browser/frame_host/cross_process_frame_connector.h"
38 #include "content/browser/frame_host/interstitial_page_impl.h"
39 #include "content/browser/frame_host/navigation_entry_impl.h"
40 #include "content/browser/frame_host/navigation_handle_impl.h"
41 #include "content/browser/frame_host/navigator_impl.h"
42 #include "content/browser/frame_host/render_frame_host_impl.h"
43 #include "content/browser/frame_host/render_widget_host_view_child_frame.h"
44 #include "content/browser/geolocation/geolocation_service_context.h"
45 #include "content/browser/host_zoom_map_impl.h"
46 #include "content/browser/loader/resource_dispatcher_host_impl.h"
47 #include "content/browser/manifest/manifest_manager_host.h"
48 #include "content/browser/media/audio_stream_monitor.h"
49 #include "content/browser/media/capture/web_contents_audio_muter.h"
50 #include "content/browser/message_port_message_filter.h"
51 #include "content/browser/plugin_content_origin_whitelist.h"
52 #include "content/browser/power_save_blocker_impl.h"
53 #include "content/browser/renderer_host/render_process_host_impl.h"
54 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
55 #include "content/browser/renderer_host/render_view_host_impl.h"
56 #include "content/browser/renderer_host/render_widget_host_impl.h"
57 #include "content/browser/renderer_host/render_widget_host_input_event_router.h"
58 #include "content/browser/renderer_host/render_widget_host_view_base.h"
59 #include "content/browser/screen_orientation/screen_orientation_dispatcher_host_impl.h"
60 #include "content/browser/site_instance_impl.h"
61 #include "content/browser/web_contents/web_contents_view_guest.h"
62 #include "content/browser/webui/generic_handler.h"
63 #include "content/browser/webui/web_ui_controller_factory_registry.h"
64 #include "content/browser/webui/web_ui_impl.h"
65 #include "content/common/browser_plugin/browser_plugin_constants.h"
66 #include "content/common/browser_plugin/browser_plugin_messages.h"
67 #include "content/common/frame_messages.h"
68 #include "content/common/input_messages.h"
69 #include "content/common/site_isolation_policy.h"
70 #include "content/common/ssl_status_serialization.h"
71 #include "content/common/view_messages.h"
72 #include "content/public/browser/ax_event_notification_details.h"
73 #include "content/public/browser/browser_context.h"
74 #include "content/public/browser/browser_plugin_guest_manager.h"
75 #include "content/public/browser/content_browser_client.h"
76 #include "content/public/browser/devtools_agent_host.h"
77 #include "content/public/browser/download_manager.h"
78 #include "content/public/browser/download_url_parameters.h"
79 #include "content/public/browser/invalidate_type.h"
80 #include "content/public/browser/javascript_dialog_manager.h"
81 #include "content/public/browser/load_from_memory_cache_details.h"
82 #include "content/public/browser/load_notification_details.h"
83 #include "content/public/browser/navigation_details.h"
84 #include "content/public/browser/notification_details.h"
85 #include "content/public/browser/notification_service.h"
86 #include "content/public/browser/render_widget_host_iterator.h"
87 #include "content/public/browser/resource_request_details.h"
88 #include "content/public/browser/screen_orientation_dispatcher_host.h"
89 #include "content/public/browser/security_style_explanations.h"
90 #include "content/public/browser/storage_partition.h"
91 #include "content/public/browser/user_metrics.h"
92 #include "content/public/browser/web_contents_delegate.h"
93 #include "content/public/browser/web_contents_observer.h"
94 #include "content/public/common/bindings_policy.h"
95 #include "content/public/common/browser_plugin_guest_mode.h"
96 #include "content/public/common/content_constants.h"
97 #include "content/public/common/content_switches.h"
98 #include "content/public/common/page_zoom.h"
99 #include "content/public/common/result_codes.h"
100 #include "content/public/common/security_style.h"
101 #include "content/public/common/url_constants.h"
102 #include "content/public/common/url_utils.h"
103 #include "content/public/common/web_preferences.h"
104 #include "mojo/common/url_type_converters.h"
105 #include "mojo/converters/geometry/geometry_type_converters.h"
106 #include "net/http/http_cache.h"
107 #include "net/http/http_transaction_factory.h"
108 #include "net/url_request/url_request_context.h"
109 #include "net/url_request/url_request_context_getter.h"
110 #include "skia/public/type_converters.h"
111 #include "third_party/skia/include/core/SkBitmap.h"
112 #include "ui/base/layout.h"
113 #include "ui/gfx/display.h"
114 #include "ui/gfx/screen.h"
115 #include "ui/gl/gl_switches.h"
117 #if defined(ENABLE_BROWSER_CDMS)
118 #include "content/browser/media/media_web_contents_observer.h"
119 #endif
121 #if defined(OS_ANDROID)
122 #include "content/browser/android/content_video_view.h"
123 #include "content/browser/android/date_time_chooser_android.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 // Record about:blank as a real (process-having) site only if the SiteInstance
175 // is unassigned. Do not otherwise depend on the siteinstance's site URL,
176 // since its value reflects the current process model, and this function
177 // should behave identically across all process models.
178 if (node->current_url() == GURL(url::kAboutBlankURL) &&
179 node->current_frame_host()->GetSiteInstance()->HasSite()) {
180 return true;
182 sites->insert(SiteInstance::GetSiteForURL(context, node->current_url()));
183 return true;
186 bool FindMatchingProcess(int render_process_id,
187 bool* did_match_process,
188 FrameTreeNode* node) {
189 if (node->current_frame_host()->GetProcess()->GetID() == render_process_id) {
190 *did_match_process = true;
191 return false;
193 return true;
196 bool ForEachFrameInternal(
197 const base::Callback<void(RenderFrameHost*)>& on_frame,
198 FrameTreeNode* node) {
199 on_frame.Run(node->current_frame_host());
200 return true;
203 bool ForEachPendingFrameInternal(
204 const base::Callback<void(RenderFrameHost*)>& on_frame,
205 FrameTreeNode* node) {
206 RenderFrameHost* pending_frame_host =
207 node->render_manager()->pending_frame_host();
208 if (pending_frame_host)
209 on_frame.Run(pending_frame_host);
210 return true;
213 void SendToAllFramesInternal(IPC::Message* message, RenderFrameHost* rfh) {
214 IPC::Message* message_copy = new IPC::Message(*message);
215 message_copy->set_routing_id(rfh->GetRoutingID());
216 rfh->Send(message_copy);
219 void AddRenderWidgetHostViewToSet(std::set<RenderWidgetHostView*>* set,
220 RenderFrameHost* rfh) {
221 RenderWidgetHostView* rwhv = static_cast<RenderFrameHostImpl*>(rfh)
222 ->frame_tree_node()
223 ->render_manager()
224 ->GetRenderWidgetHostView();
225 set->insert(rwhv);
228 void SetAccessibilityModeOnFrame(AccessibilityMode mode,
229 RenderFrameHost* frame_host) {
230 static_cast<RenderFrameHostImpl*>(frame_host)->SetAccessibilityMode(mode);
233 void ResetAccessibility(RenderFrameHost* rfh) {
234 static_cast<RenderFrameHostImpl*>(rfh)->AccessibilityReset();
237 } // namespace
239 WebContents* WebContents::Create(const WebContents::CreateParams& params) {
240 FrameTreeNode* opener_node = nullptr;
241 if (params.opener_render_frame_id != MSG_ROUTING_NONE) {
242 RenderFrameHostImpl* opener_rfh = RenderFrameHostImpl::FromID(
243 params.opener_render_process_id, params.opener_render_frame_id);
244 if (opener_rfh)
245 opener_node = opener_rfh->frame_tree_node();
247 return WebContentsImpl::CreateWithOpener(params, opener_node);
250 WebContents* WebContents::CreateWithSessionStorage(
251 const WebContents::CreateParams& params,
252 const SessionStorageNamespaceMap& session_storage_namespace_map) {
253 WebContentsImpl* new_contents = new WebContentsImpl(params.browser_context);
255 for (SessionStorageNamespaceMap::const_iterator it =
256 session_storage_namespace_map.begin();
257 it != session_storage_namespace_map.end();
258 ++it) {
259 new_contents->GetController()
260 .SetSessionStorageNamespace(it->first, it->second.get());
263 new_contents->Init(params);
264 return new_contents;
267 void WebContentsImpl::FriendZone::AddCreatedCallbackForTesting(
268 const CreatedCallback& callback) {
269 g_created_callbacks.Get().push_back(callback);
272 void WebContentsImpl::FriendZone::RemoveCreatedCallbackForTesting(
273 const CreatedCallback& callback) {
274 for (size_t i = 0; i < g_created_callbacks.Get().size(); ++i) {
275 if (g_created_callbacks.Get().at(i).Equals(callback)) {
276 g_created_callbacks.Get().erase(g_created_callbacks.Get().begin() + i);
277 return;
282 WebContents* WebContents::FromRenderViewHost(const RenderViewHost* rvh) {
283 return rvh->GetDelegate()->GetAsWebContents();
286 WebContents* WebContents::FromRenderFrameHost(RenderFrameHost* rfh) {
287 RenderFrameHostImpl* rfh_impl = static_cast<RenderFrameHostImpl*>(rfh);
288 if (!rfh_impl)
289 return NULL;
290 return rfh_impl->delegate()->GetAsWebContents();
293 // WebContentsImpl::DestructionObserver ----------------------------------------
295 class WebContentsImpl::DestructionObserver : public WebContentsObserver {
296 public:
297 DestructionObserver(WebContentsImpl* owner, WebContents* watched_contents)
298 : WebContentsObserver(watched_contents),
299 owner_(owner) {
302 // WebContentsObserver:
303 void WebContentsDestroyed() override {
304 owner_->OnWebContentsDestroyed(
305 static_cast<WebContentsImpl*>(web_contents()));
308 private:
309 WebContentsImpl* owner_;
311 DISALLOW_COPY_AND_ASSIGN(DestructionObserver);
314 WebContentsImpl::ColorChooserInfo::ColorChooserInfo(int render_process_id,
315 int render_frame_id,
316 ColorChooser* chooser,
317 int identifier)
318 : render_process_id(render_process_id),
319 render_frame_id(render_frame_id),
320 chooser(chooser),
321 identifier(identifier) {
324 WebContentsImpl::ColorChooserInfo::~ColorChooserInfo() {
327 // WebContentsImpl::WebContentsTreeNode ----------------------------------------
328 WebContentsImpl::WebContentsTreeNode::WebContentsTreeNode()
329 : outer_web_contents_(nullptr),
330 outer_contents_frame_tree_node_id_(
331 FrameTreeNode::kFrameTreeNodeInvalidID) {
334 WebContentsImpl::WebContentsTreeNode::~WebContentsTreeNode() {
335 // Remove child pointer from our parent.
336 if (outer_web_contents_) {
337 ChildrenSet& child_ptrs_in_parent =
338 outer_web_contents_->node_->inner_web_contents_tree_nodes_;
339 ChildrenSet::iterator iter = child_ptrs_in_parent.find(this);
340 DCHECK(iter != child_ptrs_in_parent.end());
341 child_ptrs_in_parent.erase(this);
344 // Remove parent pointers from our children.
345 // TODO(lazyboy): We should destroy the children WebContentses too. If the
346 // children do not manage their own lifetime, then we would leak their
347 // WebContentses.
348 for (WebContentsTreeNode* child : inner_web_contents_tree_nodes_)
349 child->outer_web_contents_ = nullptr;
352 void WebContentsImpl::WebContentsTreeNode::ConnectToOuterWebContents(
353 WebContentsImpl* outer_web_contents,
354 RenderFrameHostImpl* outer_contents_frame) {
355 outer_web_contents_ = outer_web_contents;
356 outer_contents_frame_tree_node_id_ =
357 outer_contents_frame->frame_tree_node()->frame_tree_node_id();
359 if (!outer_web_contents_->node_)
360 outer_web_contents_->node_.reset(new WebContentsTreeNode());
362 outer_web_contents_->node_->inner_web_contents_tree_nodes_.insert(this);
365 // WebContentsImpl -------------------------------------------------------------
367 WebContentsImpl::WebContentsImpl(BrowserContext* browser_context)
368 : delegate_(NULL),
369 controller_(this, browser_context),
370 render_view_host_delegate_view_(NULL),
371 created_with_opener_(false),
372 #if defined(OS_WIN)
373 accessible_parent_(NULL),
374 #endif
375 frame_tree_(new NavigatorImpl(&controller_, this),
376 this,
377 this,
378 this,
379 this),
380 is_loading_(false),
381 is_load_to_different_document_(false),
382 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING),
383 crashed_error_code_(0),
384 waiting_for_response_(false),
385 load_state_(net::LOAD_STATE_IDLE, base::string16()),
386 upload_size_(0),
387 upload_position_(0),
388 is_resume_pending_(false),
389 displayed_insecure_content_(false),
390 has_accessed_initial_document_(false),
391 theme_color_(SK_ColorTRANSPARENT),
392 last_sent_theme_color_(SK_ColorTRANSPARENT),
393 did_first_visually_non_empty_paint_(false),
394 capturer_count_(0),
395 should_normally_be_visible_(true),
396 is_being_destroyed_(false),
397 notify_disconnection_(false),
398 dialog_manager_(NULL),
399 is_showing_before_unload_dialog_(false),
400 last_active_time_(base::TimeTicks::Now()),
401 closed_by_user_gesture_(false),
402 minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)),
403 maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)),
404 render_view_message_source_(NULL),
405 render_frame_message_source_(NULL),
406 fullscreen_widget_routing_id_(MSG_ROUTING_NONE),
407 fullscreen_widget_had_focus_at_shutdown_(false),
408 is_subframe_(false),
409 force_disable_overscroll_content_(false),
410 last_dialog_suppressed_(false),
411 geolocation_service_context_(new GeolocationServiceContext()),
412 accessibility_mode_(
413 BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()),
414 audio_stream_monitor_(this),
415 virtual_keyboard_requested_(false),
416 loading_weak_factory_(this) {
417 frame_tree_.SetFrameRemoveListener(
418 base::Bind(&WebContentsImpl::OnFrameRemoved,
419 base::Unretained(this)));
420 #if defined(ENABLE_BROWSER_CDMS)
421 media_web_contents_observer_.reset(new MediaWebContentsObserver(this));
422 #endif
425 WebContentsImpl::~WebContentsImpl() {
426 is_being_destroyed_ = true;
428 rwh_input_event_router_.reset();
430 // Delete all RFH pending shutdown, which will lead the corresponding RVH to
431 // shutdown and be deleted as well.
432 frame_tree_.ForEach(
433 base::Bind(&RenderFrameHostManager::ClearRFHsPendingShutdown));
435 ClearAllPowerSaveBlockers();
437 for (std::set<RenderWidgetHostImpl*>::iterator iter =
438 created_widgets_.begin(); iter != created_widgets_.end(); ++iter) {
439 (*iter)->DetachDelegate();
441 created_widgets_.clear();
443 // Clear out any JavaScript state.
444 if (dialog_manager_)
445 dialog_manager_->ResetDialogState(this);
447 if (color_chooser_info_.get())
448 color_chooser_info_->chooser->End();
450 NotifyDisconnected();
452 // Notify any observer that have a reference on this WebContents.
453 NotificationService::current()->Notify(
454 NOTIFICATION_WEB_CONTENTS_DESTROYED,
455 Source<WebContents>(this),
456 NotificationService::NoDetails());
458 // Destroy all frame tree nodes except for the root; this notifies observers.
459 frame_tree_.root()->ResetForNewProcess();
460 GetRenderManager()->ResetProxyHosts();
462 // Manually call the observer methods for the root frame tree node. It is
463 // necessary to manually delete all objects tracking navigations
464 // (NavigationHandle, NavigationRequest) for observers to be properly
465 // notified of these navigations stopping before the WebContents is
466 // destroyed.
467 RenderFrameHostManager* root = GetRenderManager();
469 if (root->pending_frame_host()) {
470 root->pending_frame_host()->SetRenderFrameCreated(false);
471 root->pending_frame_host()->SetNavigationHandle(
472 scoped_ptr<NavigationHandleImpl>());
474 root->current_frame_host()->SetRenderFrameCreated(false);
475 root->current_frame_host()->SetNavigationHandle(
476 scoped_ptr<NavigationHandleImpl>());
478 // PlzNavigate: clear up state specific to browser-side navigation.
479 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
480 switches::kEnableBrowserSideNavigation)) {
481 frame_tree_.root()->ResetNavigationRequest(false);
482 if (root->speculative_frame_host()) {
483 root->speculative_frame_host()->SetRenderFrameCreated(false);
484 root->speculative_frame_host()->SetNavigationHandle(
485 scoped_ptr<NavigationHandleImpl>());
489 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
490 FrameDeleted(root->current_frame_host()));
492 if (root->pending_render_view_host()) {
493 FOR_EACH_OBSERVER(WebContentsObserver,
494 observers_,
495 RenderViewDeleted(root->pending_render_view_host()));
498 FOR_EACH_OBSERVER(WebContentsObserver,
499 observers_,
500 RenderViewDeleted(root->current_host()));
502 FOR_EACH_OBSERVER(WebContentsObserver,
503 observers_,
504 WebContentsDestroyed());
506 FOR_EACH_OBSERVER(WebContentsObserver,
507 observers_,
508 ResetWebContents());
510 SetDelegate(NULL);
512 STLDeleteContainerPairSecondPointers(destruction_observers_.begin(),
513 destruction_observers_.end());
516 WebContentsImpl* WebContentsImpl::CreateWithOpener(
517 const WebContents::CreateParams& params,
518 FrameTreeNode* opener) {
519 TRACE_EVENT0("browser", "WebContentsImpl::CreateWithOpener");
520 WebContentsImpl* new_contents = new WebContentsImpl(params.browser_context);
522 if (!params.opener_suppressed && opener) {
523 new_contents->GetFrameTree()->root()->SetOpener(opener);
524 new_contents->created_with_opener_ = true;
527 // This may be true even when opener is null, such as when opening blocked
528 // popups.
529 if (params.created_with_opener)
530 new_contents->created_with_opener_ = true;
532 if (params.guest_delegate) {
533 // This makes |new_contents| act as a guest.
534 // For more info, see comment above class BrowserPluginGuest.
535 BrowserPluginGuest::Create(new_contents, params.guest_delegate);
536 // We are instantiating a WebContents for browser plugin. Set its subframe
537 // bit to true.
538 new_contents->is_subframe_ = true;
540 new_contents->Init(params);
541 return new_contents;
544 // static
545 std::vector<WebContentsImpl*> WebContentsImpl::GetAllWebContents() {
546 std::vector<WebContentsImpl*> result;
547 scoped_ptr<RenderWidgetHostIterator> widgets(
548 RenderWidgetHostImpl::GetRenderWidgetHosts());
549 std::set<WebContentsImpl*> web_contents_set;
550 while (RenderWidgetHost* rwh = widgets->GetNextHost()) {
551 if (!rwh->IsRenderView())
552 continue;
553 RenderViewHost* rvh = RenderViewHost::From(rwh);
554 if (!rvh)
555 continue;
556 WebContents* web_contents = WebContents::FromRenderViewHost(rvh);
557 if (!web_contents)
558 continue;
559 WebContentsImpl* wci = static_cast<WebContentsImpl*>(web_contents);
560 if (web_contents_set.find(wci) == web_contents_set.end()) {
561 web_contents_set.insert(wci);
562 result.push_back(wci);
565 return result;
568 // static
569 WebContentsImpl* WebContentsImpl::FromFrameTreeNode(
570 FrameTreeNode* frame_tree_node) {
571 return static_cast<WebContentsImpl*>(
572 WebContents::FromRenderFrameHost(frame_tree_node->current_frame_host()));
575 RenderFrameHostManager* WebContentsImpl::GetRenderManagerForTesting() {
576 return GetRenderManager();
579 bool WebContentsImpl::OnMessageReceived(RenderViewHost* render_view_host,
580 const IPC::Message& message) {
581 return OnMessageReceived(render_view_host, NULL, message);
584 bool WebContentsImpl::OnMessageReceived(RenderViewHost* render_view_host,
585 RenderFrameHost* render_frame_host,
586 const IPC::Message& message) {
587 DCHECK(render_view_host || render_frame_host);
588 if (GetWebUI() &&
589 static_cast<WebUIImpl*>(GetWebUI())->OnMessageReceived(message)) {
590 return true;
593 base::ObserverListBase<WebContentsObserver>::Iterator it(&observers_);
594 WebContentsObserver* observer;
595 if (render_frame_host) {
596 while ((observer = it.GetNext()) != NULL)
597 if (observer->OnMessageReceived(message, render_frame_host))
598 return true;
599 } else {
600 while ((observer = it.GetNext()) != NULL)
601 if (observer->OnMessageReceived(message))
602 return true;
605 // Message handlers should be aware of which
606 // RenderViewHost/RenderFrameHost sent the message, which is temporarily
607 // stored in render_(view|frame)_message_source_.
608 if (render_frame_host)
609 render_frame_message_source_ = render_frame_host;
610 else
611 render_view_message_source_ = render_view_host;
613 bool handled = true;
614 IPC_BEGIN_MESSAGE_MAP(WebContentsImpl, message)
615 IPC_MESSAGE_HANDLER(FrameHostMsg_DomOperationResponse,
616 OnDomOperationResponse)
617 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeThemeColor,
618 OnThemeColorChanged)
619 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishDocumentLoad,
620 OnDocumentLoadedInFrame)
621 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishLoad, OnDidFinishLoad)
622 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenColorChooser, OnOpenColorChooser)
623 IPC_MESSAGE_HANDLER(FrameHostMsg_EndColorChooser, OnEndColorChooser)
624 IPC_MESSAGE_HANDLER(FrameHostMsg_SetSelectedColorInColorChooser,
625 OnSetSelectedColorInColorChooser)
626 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPlayingNotification,
627 OnMediaPlayingNotification)
628 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPausedNotification,
629 OnMediaPausedNotification)
630 IPC_MESSAGE_HANDLER(ViewHostMsg_DidFirstVisuallyNonEmptyPaint,
631 OnFirstVisuallyNonEmptyPaint)
632 IPC_MESSAGE_HANDLER(FrameHostMsg_DidLoadResourceFromMemoryCache,
633 OnDidLoadResourceFromMemoryCache)
634 IPC_MESSAGE_HANDLER(FrameHostMsg_DidDisplayInsecureContent,
635 OnDidDisplayInsecureContent)
636 IPC_MESSAGE_HANDLER(FrameHostMsg_DidRunInsecureContent,
637 OnDidRunInsecureContent)
638 IPC_MESSAGE_HANDLER(ViewHostMsg_GoToEntryAtOffset, OnGoToEntryAtOffset)
639 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateZoomLimits, OnUpdateZoomLimits)
640 IPC_MESSAGE_HANDLER(ViewHostMsg_EnumerateDirectory, OnEnumerateDirectory)
641 IPC_MESSAGE_HANDLER(FrameHostMsg_RegisterProtocolHandler,
642 OnRegisterProtocolHandler)
643 IPC_MESSAGE_HANDLER(FrameHostMsg_UnregisterProtocolHandler,
644 OnUnregisterProtocolHandler)
645 IPC_MESSAGE_HANDLER(ViewHostMsg_Find_Reply, OnFindReply)
646 IPC_MESSAGE_HANDLER(ViewHostMsg_AppCacheAccessed, OnAppCacheAccessed)
647 IPC_MESSAGE_HANDLER(ViewHostMsg_WebUISend, OnWebUISend)
648 #if defined(ENABLE_PLUGINS)
649 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceCreated,
650 OnPepperInstanceCreated)
651 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceDeleted,
652 OnPepperInstanceDeleted)
653 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung, OnPepperPluginHung)
654 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed, OnPluginCrashed)
655 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission,
656 OnRequestPpapiBrokerPermission)
657 IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_Attach,
658 OnBrowserPluginMessage(render_frame_host,
659 message))
660 #endif
661 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateFaviconURL, OnUpdateFaviconURL)
662 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowValidationMessage,
663 OnShowValidationMessage)
664 IPC_MESSAGE_HANDLER(ViewHostMsg_HideValidationMessage,
665 OnHideValidationMessage)
666 IPC_MESSAGE_HANDLER(ViewHostMsg_MoveValidationMessage,
667 OnMoveValidationMessage)
668 #if defined(OS_ANDROID)
669 IPC_MESSAGE_HANDLER(ViewHostMsg_FindMatchRects_Reply,
670 OnFindMatchRectsReply)
671 IPC_MESSAGE_HANDLER(ViewHostMsg_OpenDateTimeDialog,
672 OnOpenDateTimeDialog)
673 #endif
674 IPC_MESSAGE_UNHANDLED(handled = false)
675 IPC_END_MESSAGE_MAP()
676 render_view_message_source_ = NULL;
677 render_frame_message_source_ = NULL;
679 return handled;
682 bool WebContentsImpl::HasValidFrameSource() {
683 if (!render_frame_message_source_) {
684 DCHECK(render_view_message_source_);
685 bad_message::ReceivedBadMessage(GetRenderProcessHost(),
686 bad_message::WC_INVALID_FRAME_SOURCE);
687 return false;
690 return true;
693 void WebContentsImpl::RunFileChooser(
694 RenderViewHost* render_view_host,
695 const FileChooserParams& params) {
696 if (delegate_)
697 delegate_->RunFileChooser(this, params);
700 NavigationControllerImpl& WebContentsImpl::GetController() {
701 return controller_;
704 const NavigationControllerImpl& WebContentsImpl::GetController() const {
705 return controller_;
708 BrowserContext* WebContentsImpl::GetBrowserContext() const {
709 return controller_.GetBrowserContext();
712 const GURL& WebContentsImpl::GetURL() const {
713 // We may not have a navigation entry yet.
714 NavigationEntry* entry = controller_.GetVisibleEntry();
715 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
718 const GURL& WebContentsImpl::GetVisibleURL() const {
719 // We may not have a navigation entry yet.
720 NavigationEntry* entry = controller_.GetVisibleEntry();
721 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
724 const GURL& WebContentsImpl::GetLastCommittedURL() const {
725 // We may not have a navigation entry yet.
726 NavigationEntry* entry = controller_.GetLastCommittedEntry();
727 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
730 WebContentsDelegate* WebContentsImpl::GetDelegate() {
731 return delegate_;
734 void WebContentsImpl::SetDelegate(WebContentsDelegate* delegate) {
735 // TODO(cbentzel): remove this debugging code?
736 if (delegate == delegate_)
737 return;
738 if (delegate_)
739 delegate_->Detach(this);
740 delegate_ = delegate;
741 if (delegate_) {
742 delegate_->Attach(this);
743 // Ensure the visible RVH reflects the new delegate's preferences.
744 if (view_)
745 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
749 RenderProcessHost* WebContentsImpl::GetRenderProcessHost() const {
750 RenderViewHostImpl* host = GetRenderManager()->current_host();
751 return host ? host->GetProcess() : NULL;
754 RenderFrameHostImpl* WebContentsImpl::GetMainFrame() {
755 return frame_tree_.root()->current_frame_host();
758 RenderFrameHostImpl* WebContentsImpl::GetFocusedFrame() {
759 FrameTreeNode* focused_node = frame_tree_.GetFocusedFrame();
760 if (!focused_node)
761 return nullptr;
762 return focused_node->current_frame_host();
765 void WebContentsImpl::ForEachFrame(
766 const base::Callback<void(RenderFrameHost*)>& on_frame) {
767 frame_tree_.ForEach(base::Bind(&ForEachFrameInternal, on_frame));
770 void WebContentsImpl::SendToAllFrames(IPC::Message* message) {
771 ForEachFrame(base::Bind(&SendToAllFramesInternal, message));
772 delete message;
775 RenderViewHostImpl* WebContentsImpl::GetRenderViewHost() const {
776 return GetRenderManager()->current_host();
779 int WebContentsImpl::GetRoutingID() const {
780 if (!GetRenderViewHost())
781 return MSG_ROUTING_NONE;
783 return GetRenderViewHost()->GetRoutingID();
786 void WebContentsImpl::CancelActiveAndPendingDialogs() {
787 if (dialog_manager_)
788 dialog_manager_->CancelActiveAndPendingDialogs(this);
789 if (browser_plugin_embedder_)
790 browser_plugin_embedder_->CancelGuestDialogs();
793 int WebContentsImpl::GetFullscreenWidgetRoutingID() const {
794 return fullscreen_widget_routing_id_;
797 void WebContentsImpl::ClosePage() {
798 GetRenderViewHost()->ClosePage();
801 RenderWidgetHostView* WebContentsImpl::GetRenderWidgetHostView() const {
802 return GetRenderManager()->GetRenderWidgetHostView();
805 RenderWidgetHostView* WebContentsImpl::GetFullscreenRenderWidgetHostView()
806 const {
807 RenderWidgetHost* const widget_host =
808 RenderWidgetHostImpl::FromID(GetRenderProcessHost()->GetID(),
809 GetFullscreenWidgetRoutingID());
810 return widget_host ? widget_host->GetView() : NULL;
813 WebContentsView* WebContentsImpl::GetView() const {
814 return view_.get();
817 SkColor WebContentsImpl::GetThemeColor() const {
818 return theme_color_;
821 void WebContentsImpl::SetAccessibilityMode(AccessibilityMode mode) {
822 if (mode == accessibility_mode_)
823 return;
825 accessibility_mode_ = mode;
826 frame_tree_.ForEach(
827 base::Bind(&ForEachFrameInternal,
828 base::Bind(&SetAccessibilityModeOnFrame, mode)));
829 frame_tree_.ForEach(
830 base::Bind(&ForEachPendingFrameInternal,
831 base::Bind(&SetAccessibilityModeOnFrame, mode)));
834 void WebContentsImpl::AddAccessibilityMode(AccessibilityMode mode) {
835 SetAccessibilityMode(AddAccessibilityModeTo(accessibility_mode_, mode));
838 void WebContentsImpl::RemoveAccessibilityMode(AccessibilityMode mode) {
839 SetAccessibilityMode(RemoveAccessibilityModeFrom(accessibility_mode_, mode));
842 void WebContentsImpl::RequestAXTreeSnapshot(AXTreeSnapshotCallback callback) {
843 // TODO(dmazzoni): http://crbug.com/475608 This only returns the
844 // accessibility tree from the main frame and everything in the
845 // same site instance.
846 GetMainFrame()->RequestAXTreeSnapshot(callback);
849 WebUI* WebContentsImpl::CreateSubframeWebUI(const GURL& url,
850 const std::string& frame_name) {
851 DCHECK(!frame_name.empty());
852 return CreateWebUI(url, frame_name);
855 WebUI* WebContentsImpl::GetWebUI() const {
856 return GetRenderManager()->web_ui() ? GetRenderManager()->web_ui()
857 : GetRenderManager()->pending_web_ui();
860 WebUI* WebContentsImpl::GetCommittedWebUI() const {
861 return GetRenderManager()->web_ui();
864 void WebContentsImpl::SetUserAgentOverride(const std::string& override) {
865 if (GetUserAgentOverride() == override)
866 return;
868 renderer_preferences_.user_agent_override = override;
870 // Send the new override string to the renderer.
871 RenderViewHost* host = GetRenderViewHost();
872 if (host)
873 host->SyncRendererPrefs();
875 // Reload the page if a load is currently in progress to avoid having
876 // different parts of the page loaded using different user agents.
877 NavigationEntry* entry = controller_.GetVisibleEntry();
878 if (is_loading_ && entry != NULL && entry->GetIsOverridingUserAgent())
879 controller_.ReloadIgnoringCache(true);
881 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
882 UserAgentOverrideSet(override));
885 const std::string& WebContentsImpl::GetUserAgentOverride() const {
886 return renderer_preferences_.user_agent_override;
889 void WebContentsImpl::EnableTreeOnlyAccessibilityMode() {
890 if (GetAccessibilityMode() == AccessibilityModeTreeOnly)
891 ForEachFrame(base::Bind(&ResetAccessibility));
892 else
893 AddAccessibilityMode(AccessibilityModeTreeOnly);
896 bool WebContentsImpl::IsTreeOnlyAccessibilityModeForTesting() const {
897 return accessibility_mode_ == AccessibilityModeTreeOnly;
900 bool WebContentsImpl::IsFullAccessibilityModeForTesting() const {
901 return accessibility_mode_ == AccessibilityModeComplete;
904 #if defined(OS_WIN)
905 void WebContentsImpl::SetParentNativeViewAccessible(
906 gfx::NativeViewAccessible accessible_parent) {
907 accessible_parent_ = accessible_parent;
908 RenderFrameHostImpl* rfh = GetMainFrame();
909 if (rfh)
910 rfh->SetParentNativeViewAccessible(accessible_parent);
912 #endif
914 const base::string16& WebContentsImpl::GetTitle() const {
915 // Transient entries take precedence. They are used for interstitial pages
916 // that are shown on top of existing pages.
917 NavigationEntry* entry = controller_.GetTransientEntry();
918 std::string accept_languages =
919 GetContentClient()->browser()->GetAcceptLangs(
920 GetBrowserContext());
921 if (entry) {
922 return entry->GetTitleForDisplay(accept_languages);
924 WebUI* our_web_ui = GetRenderManager()->pending_web_ui() ?
925 GetRenderManager()->pending_web_ui() : GetRenderManager()->web_ui();
926 if (our_web_ui) {
927 // Don't override the title in view source mode.
928 entry = controller_.GetVisibleEntry();
929 if (!(entry && entry->IsViewSourceMode())) {
930 // Give the Web UI the chance to override our title.
931 const base::string16& title = our_web_ui->GetOverriddenTitle();
932 if (!title.empty())
933 return title;
937 // We use the title for the last committed entry rather than a pending
938 // navigation entry. For example, when the user types in a URL, we want to
939 // keep the old page's title until the new load has committed and we get a new
940 // title.
941 entry = controller_.GetLastCommittedEntry();
943 // We make an exception for initial navigations.
944 if (controller_.IsInitialNavigation()) {
945 // We only want to use the title from the visible entry in one of two cases:
946 // 1. There's already a committed entry for an initial navigation, in which
947 // case we are doing a history navigation in a new tab (e.g., Ctrl+Back).
948 // 2. The pending entry has been explicitly assigned a title to display.
950 // If there's no last committed entry and no assigned title, we should fall
951 // back to |page_title_when_no_navigation_entry_| rather than showing the
952 // URL.
953 if (entry ||
954 (controller_.GetVisibleEntry() &&
955 !controller_.GetVisibleEntry()->GetTitle().empty())) {
956 entry = controller_.GetVisibleEntry();
960 if (entry) {
961 return entry->GetTitleForDisplay(accept_languages);
964 // |page_title_when_no_navigation_entry_| is finally used
965 // if no title cannot be retrieved.
966 return page_title_when_no_navigation_entry_;
969 int32 WebContentsImpl::GetMaxPageID() {
970 return GetMaxPageIDForSiteInstance(GetSiteInstance());
973 int32 WebContentsImpl::GetMaxPageIDForSiteInstance(
974 SiteInstance* site_instance) {
975 if (max_page_ids_.find(site_instance->GetId()) == max_page_ids_.end())
976 max_page_ids_[site_instance->GetId()] = -1;
978 return max_page_ids_[site_instance->GetId()];
981 void WebContentsImpl::UpdateMaxPageID(int32 page_id) {
982 UpdateMaxPageIDForSiteInstance(GetSiteInstance(), page_id);
985 void WebContentsImpl::UpdateMaxPageIDForSiteInstance(
986 SiteInstance* site_instance, int32 page_id) {
987 if (GetMaxPageIDForSiteInstance(site_instance) < page_id)
988 max_page_ids_[site_instance->GetId()] = page_id;
991 void WebContentsImpl::CopyMaxPageIDsFrom(WebContents* web_contents) {
992 WebContentsImpl* contents = static_cast<WebContentsImpl*>(web_contents);
993 max_page_ids_ = contents->max_page_ids_;
996 SiteInstanceImpl* WebContentsImpl::GetSiteInstance() const {
997 return GetRenderManager()->current_host()->GetSiteInstance();
1000 SiteInstanceImpl* WebContentsImpl::GetPendingSiteInstance() const {
1001 RenderViewHostImpl* dest_rvh =
1002 GetRenderManager()->pending_render_view_host() ?
1003 GetRenderManager()->pending_render_view_host() :
1004 GetRenderManager()->current_host();
1005 return dest_rvh->GetSiteInstance();
1008 bool WebContentsImpl::IsLoading() const {
1009 return is_loading_;
1012 bool WebContentsImpl::IsLoadingToDifferentDocument() const {
1013 return is_loading_ && is_load_to_different_document_;
1016 bool WebContentsImpl::IsWaitingForResponse() const {
1017 return waiting_for_response_ && is_load_to_different_document_;
1020 const net::LoadStateWithParam& WebContentsImpl::GetLoadState() const {
1021 return load_state_;
1024 const base::string16& WebContentsImpl::GetLoadStateHost() const {
1025 return load_state_host_;
1028 uint64 WebContentsImpl::GetUploadSize() const {
1029 return upload_size_;
1032 uint64 WebContentsImpl::GetUploadPosition() const {
1033 return upload_position_;
1036 std::set<GURL> WebContentsImpl::GetSitesInTab() const {
1037 std::set<GURL> sites;
1038 frame_tree_.ForEach(base::Bind(&CollectSites,
1039 base::Unretained(GetBrowserContext()),
1040 base::Unretained(&sites)));
1041 return sites;
1044 const std::string& WebContentsImpl::GetEncoding() const {
1045 return canonical_encoding_;
1048 bool WebContentsImpl::DisplayedInsecureContent() const {
1049 return displayed_insecure_content_;
1052 void WebContentsImpl::IncrementCapturerCount(const gfx::Size& capture_size) {
1053 DCHECK(!is_being_destroyed_);
1054 ++capturer_count_;
1055 DVLOG(1) << "There are now " << capturer_count_
1056 << " capturing(s) of WebContentsImpl@" << this;
1058 // Note: This provides a hint to upstream code to size the views optimally
1059 // for quality (e.g., to avoid scaling).
1060 if (!capture_size.IsEmpty() && preferred_size_for_capture_.IsEmpty()) {
1061 preferred_size_for_capture_ = capture_size;
1062 OnPreferredSizeChanged(preferred_size_);
1065 // Ensure that all views are un-occluded before capture begins.
1066 WasUnOccluded();
1069 void WebContentsImpl::DecrementCapturerCount() {
1070 --capturer_count_;
1071 DVLOG(1) << "There are now " << capturer_count_
1072 << " capturing(s) of WebContentsImpl@" << this;
1073 DCHECK_LE(0, capturer_count_);
1075 if (is_being_destroyed_)
1076 return;
1078 if (capturer_count_ == 0) {
1079 const gfx::Size old_size = preferred_size_for_capture_;
1080 preferred_size_for_capture_ = gfx::Size();
1081 OnPreferredSizeChanged(old_size);
1084 if (IsHidden()) {
1085 DVLOG(1) << "Executing delayed WasHidden().";
1086 WasHidden();
1090 int WebContentsImpl::GetCapturerCount() const {
1091 return capturer_count_;
1094 bool WebContentsImpl::IsAudioMuted() const {
1095 return audio_muter_.get() && audio_muter_->is_muting();
1098 void WebContentsImpl::SetAudioMuted(bool mute) {
1099 DVLOG(1) << "SetAudioMuted(mute=" << mute << "), was " << IsAudioMuted()
1100 << " for WebContentsImpl@" << this;
1102 if (mute == IsAudioMuted())
1103 return;
1105 if (mute) {
1106 if (!audio_muter_)
1107 audio_muter_.reset(new WebContentsAudioMuter(this));
1108 audio_muter_->StartMuting();
1109 } else {
1110 DCHECK(audio_muter_);
1111 audio_muter_->StopMuting();
1114 // Notification for UI updates in response to the changed muting state.
1115 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
1118 bool WebContentsImpl::IsCrashed() const {
1119 return (crashed_status_ == base::TERMINATION_STATUS_PROCESS_CRASHED ||
1120 crashed_status_ == base::TERMINATION_STATUS_ABNORMAL_TERMINATION ||
1121 crashed_status_ == base::TERMINATION_STATUS_PROCESS_WAS_KILLED ||
1122 #if defined(OS_CHROMEOS)
1123 crashed_status_ ==
1124 base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM ||
1125 #endif
1126 crashed_status_ == base::TERMINATION_STATUS_LAUNCH_FAILED
1130 void WebContentsImpl::SetIsCrashed(base::TerminationStatus status,
1131 int error_code) {
1132 if (status == crashed_status_)
1133 return;
1135 crashed_status_ = status;
1136 crashed_error_code_ = error_code;
1137 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
1140 base::TerminationStatus WebContentsImpl::GetCrashedStatus() const {
1141 return crashed_status_;
1144 bool WebContentsImpl::IsBeingDestroyed() const {
1145 return is_being_destroyed_;
1148 void WebContentsImpl::NotifyNavigationStateChanged(
1149 InvalidateTypes changed_flags) {
1150 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1151 // is fixed.
1152 tracked_objects::ScopedTracker tracking_profile(
1153 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1154 "466285 WebContentsImpl::NotifyNavigationStateChanged"));
1155 // Create and release the audio power save blocker depending on whether the
1156 // tab is actively producing audio or not.
1157 if ((changed_flags & INVALIDATE_TYPE_TAB) &&
1158 AudioStreamMonitor::monitoring_available()) {
1159 if (WasRecentlyAudible()) {
1160 if (!audio_power_save_blocker_)
1161 CreateAudioPowerSaveBlocker();
1162 } else {
1163 audio_power_save_blocker_.reset();
1167 if (delegate_)
1168 delegate_->NavigationStateChanged(this, changed_flags);
1171 base::TimeTicks WebContentsImpl::GetLastActiveTime() const {
1172 return last_active_time_;
1175 void WebContentsImpl::SetLastActiveTime(base::TimeTicks last_active_time) {
1176 last_active_time_ = last_active_time;
1179 void WebContentsImpl::WasShown() {
1180 controller_.SetActive(true);
1182 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1183 if (view) {
1184 view->Show();
1185 #if defined(OS_MACOSX)
1186 view->SetActive(true);
1187 #endif
1191 last_active_time_ = base::TimeTicks::Now();
1193 // The resize rect might have changed while this was inactive -- send the new
1194 // one to make sure it's up to date.
1195 RenderViewHostImpl* rvh = GetRenderViewHost();
1196 if (rvh)
1197 rvh->ResizeRectChanged(GetRootWindowResizerRect());
1199 // Restore power save blocker if there are active video players running.
1200 if (!active_video_players_.empty() && !video_power_save_blocker_)
1201 CreateVideoPowerSaveBlocker();
1203 FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasShown());
1205 should_normally_be_visible_ = true;
1208 void WebContentsImpl::WasHidden() {
1209 // If there are entities capturing screenshots or video (e.g., mirroring),
1210 // don't activate the "disable rendering" optimization.
1211 if (capturer_count_ == 0) {
1212 // |GetRenderViewHost()| can be NULL if the user middle clicks a link to
1213 // open a tab in the background, then closes the tab before selecting it.
1214 // This is because closing the tab calls WebContentsImpl::Destroy(), which
1215 // removes the |GetRenderViewHost()|; then when we actually destroy the
1216 // window, OnWindowPosChanged() notices and calls WasHidden() (which
1217 // calls us).
1218 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1219 if (view)
1220 view->Hide();
1223 // Release any video power save blockers held as video is not visible.
1224 video_power_save_blocker_.reset();
1227 FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasHidden());
1229 should_normally_be_visible_ = false;
1232 void WebContentsImpl::WasOccluded() {
1233 if (capturer_count_ > 0)
1234 return;
1236 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1237 if (view)
1238 view->WasOccluded();
1242 void WebContentsImpl::WasUnOccluded() {
1243 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1244 if (view)
1245 view->WasUnOccluded();
1249 bool WebContentsImpl::NeedToFireBeforeUnload() {
1250 // TODO(creis): Should we fire even for interstitial pages?
1251 return WillNotifyDisconnection() && !ShowingInterstitialPage() &&
1252 !GetRenderViewHost()->SuddenTerminationAllowed();
1255 void WebContentsImpl::DispatchBeforeUnload(bool for_cross_site_transition) {
1256 GetMainFrame()->DispatchBeforeUnload(for_cross_site_transition);
1259 void WebContentsImpl::AttachToOuterWebContentsFrame(
1260 WebContents* outer_web_contents,
1261 RenderFrameHost* outer_contents_frame) {
1262 CHECK(BrowserPluginGuestMode::UseCrossProcessFramesForGuests());
1263 // Create a link to our outer WebContents.
1264 node_.reset(new WebContentsTreeNode());
1265 node_->ConnectToOuterWebContents(
1266 static_cast<WebContentsImpl*>(outer_web_contents),
1267 static_cast<RenderFrameHostImpl*>(outer_contents_frame));
1269 DCHECK(outer_contents_frame);
1271 // Create a proxy in top-level RenderFrameHostManager, pointing to the
1272 // SiteInstance of the outer WebContents. The proxy will be used to send
1273 // postMessage to the inner WebContents.
1274 GetRenderManager()->CreateOuterDelegateProxy(
1275 outer_contents_frame->GetSiteInstance(),
1276 static_cast<RenderFrameHostImpl*>(outer_contents_frame));
1278 GetRenderManager()->SetRWHViewForInnerContents(
1279 GetRenderManager()->GetRenderWidgetHostView());
1282 void WebContentsImpl::Stop() {
1283 frame_tree_.ForEach(base::Bind(&FrameTreeNode::StopLoading));
1284 FOR_EACH_OBSERVER(WebContentsObserver, observers_, NavigationStopped());
1287 WebContents* WebContentsImpl::Clone() {
1288 // We use our current SiteInstance since the cloned entry will use it anyway.
1289 // We pass our own opener so that the cloned page can access it if it was set
1290 // before.
1291 CreateParams create_params(GetBrowserContext(), GetSiteInstance());
1292 create_params.initial_size = GetContainerBounds().size();
1293 WebContentsImpl* tc =
1294 CreateWithOpener(create_params, frame_tree_.root()->opener());
1295 tc->GetController().CopyStateFrom(controller_);
1296 FOR_EACH_OBSERVER(WebContentsObserver,
1297 observers_,
1298 DidCloneToNewWebContents(this, tc));
1299 return tc;
1302 void WebContentsImpl::Observe(int type,
1303 const NotificationSource& source,
1304 const NotificationDetails& details) {
1305 switch (type) {
1306 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: {
1307 RenderWidgetHost* host = Source<RenderWidgetHost>(source).ptr();
1308 RenderWidgetHostView* view = host->GetView();
1309 if (view == GetFullscreenRenderWidgetHostView()) {
1310 // We cannot just call view_->RestoreFocus() here. On some platforms,
1311 // attempting to focus the currently-invisible WebContentsView will be
1312 // flat-out ignored. Therefore, this boolean is used to track whether
1313 // we will request focus after the fullscreen widget has been
1314 // destroyed.
1315 fullscreen_widget_had_focus_at_shutdown_ = (view && view->HasFocus());
1316 } else {
1317 for (PendingWidgetViews::iterator i = pending_widget_views_.begin();
1318 i != pending_widget_views_.end(); ++i) {
1319 if (host->GetView() == i->second) {
1320 pending_widget_views_.erase(i);
1321 break;
1325 break;
1327 default:
1328 NOTREACHED();
1332 WebContents* WebContentsImpl::GetWebContents() {
1333 return this;
1336 void WebContentsImpl::Init(const WebContents::CreateParams& params) {
1337 // This is set before initializing the render manager since
1338 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
1339 // it should be hidden.
1340 should_normally_be_visible_ = !params.initially_hidden;
1342 // Either both routing ids can be given, or neither can be.
1343 DCHECK((params.routing_id == MSG_ROUTING_NONE &&
1344 params.main_frame_routing_id == MSG_ROUTING_NONE) ||
1345 (params.routing_id != MSG_ROUTING_NONE &&
1346 params.main_frame_routing_id != MSG_ROUTING_NONE));
1347 GetRenderManager()->Init(params.browser_context, params.site_instance,
1348 params.routing_id, params.main_frame_routing_id,
1349 MSG_ROUTING_NONE, 0 /* surface_id */);
1350 frame_tree_.root()->SetFrameName(params.main_frame_name);
1352 WebContentsViewDelegate* delegate =
1353 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
1355 if (browser_plugin_guest_ &&
1356 !BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
1357 scoped_ptr<WebContentsView> platform_view(CreateWebContentsView(
1358 this, delegate, &render_view_host_delegate_view_));
1360 WebContentsViewGuest* rv = new WebContentsViewGuest(
1361 this, browser_plugin_guest_.get(), platform_view.Pass(),
1362 render_view_host_delegate_view_);
1363 render_view_host_delegate_view_ = rv;
1364 view_.reset(rv);
1365 } else {
1366 // Regular WebContentsView.
1367 view_.reset(CreateWebContentsView(
1368 this, delegate, &render_view_host_delegate_view_));
1370 CHECK(render_view_host_delegate_view_);
1371 CHECK(view_.get());
1373 gfx::Size initial_size = params.initial_size;
1374 view_->CreateView(initial_size, params.context);
1376 #if defined(ENABLE_PLUGINS)
1377 plugin_content_origin_whitelist_.reset(
1378 new PluginContentOriginWhitelist(this));
1379 #endif
1381 registrar_.Add(this,
1382 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1383 NotificationService::AllBrowserContextsAndSources());
1385 screen_orientation_dispatcher_host_.reset(
1386 new ScreenOrientationDispatcherHostImpl(this));
1388 manifest_manager_host_.reset(new ManifestManagerHost(this));
1390 #if defined(OS_ANDROID)
1391 date_time_chooser_.reset(new DateTimeChooserAndroid());
1392 #endif
1394 // BrowserPluginGuest::Init needs to be called after this WebContents has
1395 // a RenderWidgetHostViewGuest. That is, |view_->CreateView| above.
1396 if (browser_plugin_guest_)
1397 browser_plugin_guest_->Init();
1399 for (size_t i = 0; i < g_created_callbacks.Get().size(); i++)
1400 g_created_callbacks.Get().at(i).Run(this);
1402 // If the WebContents creation was renderer-initiated, it means that the
1403 // corresponding RenderView and main RenderFrame have already been created.
1404 // Ensure observers are notified about this.
1405 if (params.renderer_initiated_creation) {
1406 GetRenderViewHost()->set_renderer_initialized(true);
1407 RenderViewCreated(GetRenderViewHost());
1408 GetRenderManager()->current_frame_host()->SetRenderFrameCreated(true);
1411 // Ensure that observers are notified of the creation of this WebContents's
1412 // main RenderFrameHost. It must be done here for main frames, since the
1413 // NotifySwappedFromRenderManager expects view_ to already be created and that
1414 // happens after RenderFrameHostManager::Init.
1415 NotifySwappedFromRenderManager(
1416 nullptr, GetRenderManager()->current_frame_host(), true);
1419 void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl* web_contents) {
1420 RemoveDestructionObserver(web_contents);
1422 // Clear a pending contents that has been closed before being shown.
1423 for (PendingContents::iterator iter = pending_contents_.begin();
1424 iter != pending_contents_.end();
1425 ++iter) {
1426 if (iter->second != web_contents)
1427 continue;
1428 pending_contents_.erase(iter);
1429 return;
1431 NOTREACHED();
1434 void WebContentsImpl::AddDestructionObserver(WebContentsImpl* web_contents) {
1435 if (!ContainsKey(destruction_observers_, web_contents)) {
1436 destruction_observers_[web_contents] =
1437 new DestructionObserver(this, web_contents);
1441 void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl* web_contents) {
1442 DestructionObservers::iterator iter =
1443 destruction_observers_.find(web_contents);
1444 if (iter != destruction_observers_.end()) {
1445 delete destruction_observers_[web_contents];
1446 destruction_observers_.erase(iter);
1450 void WebContentsImpl::AddObserver(WebContentsObserver* observer) {
1451 observers_.AddObserver(observer);
1454 void WebContentsImpl::RemoveObserver(WebContentsObserver* observer) {
1455 observers_.RemoveObserver(observer);
1458 std::set<RenderWidgetHostView*>
1459 WebContentsImpl::GetRenderWidgetHostViewsInTree() {
1460 std::set<RenderWidgetHostView*> set;
1461 if (ShowingInterstitialPage()) {
1462 set.insert(GetRenderWidgetHostView());
1463 } else {
1464 ForEachFrame(
1465 base::Bind(&AddRenderWidgetHostViewToSet, base::Unretained(&set)));
1467 return set;
1470 void WebContentsImpl::Activate() {
1471 if (delegate_)
1472 delegate_->ActivateContents(this);
1475 void WebContentsImpl::Deactivate() {
1476 if (delegate_)
1477 delegate_->DeactivateContents(this);
1480 void WebContentsImpl::LostCapture() {
1481 if (delegate_)
1482 delegate_->LostCapture();
1485 void WebContentsImpl::RenderWidgetDeleted(
1486 RenderWidgetHostImpl* render_widget_host) {
1487 if (is_being_destroyed_) {
1488 // |created_widgets_| might have been destroyed.
1489 return;
1492 std::set<RenderWidgetHostImpl*>::iterator iter =
1493 created_widgets_.find(render_widget_host);
1494 if (iter != created_widgets_.end())
1495 created_widgets_.erase(iter);
1497 if (render_widget_host &&
1498 render_widget_host->GetRoutingID() == fullscreen_widget_routing_id_) {
1499 if (delegate_ && delegate_->EmbedsFullscreenWidget())
1500 delegate_->ExitFullscreenModeForTab(this);
1501 FOR_EACH_OBSERVER(WebContentsObserver,
1502 observers_,
1503 DidDestroyFullscreenWidget(
1504 fullscreen_widget_routing_id_));
1505 fullscreen_widget_routing_id_ = MSG_ROUTING_NONE;
1506 if (fullscreen_widget_had_focus_at_shutdown_)
1507 view_->RestoreFocus();
1511 void WebContentsImpl::RenderWidgetGotFocus(
1512 RenderWidgetHostImpl* render_widget_host) {
1513 // Notify the observers if an embedded fullscreen widget was focused.
1514 if (delegate_ && render_widget_host && delegate_->EmbedsFullscreenWidget() &&
1515 render_widget_host->GetView() == GetFullscreenRenderWidgetHostView()) {
1516 NotifyWebContentsFocused();
1520 void WebContentsImpl::RenderWidgetWasResized(
1521 RenderWidgetHostImpl* render_widget_host,
1522 bool width_changed) {
1523 RenderFrameHostImpl* rfh = GetMainFrame();
1524 if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
1525 return;
1527 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1528 MainFrameWasResized(width_changed));
1531 void WebContentsImpl::ScreenInfoChanged() {
1532 if (browser_plugin_embedder_)
1533 browser_plugin_embedder_->ScreenInfoChanged();
1536 bool WebContentsImpl::PreHandleKeyboardEvent(
1537 const NativeWebKeyboardEvent& event,
1538 bool* is_keyboard_shortcut) {
1539 return delegate_ &&
1540 delegate_->PreHandleKeyboardEvent(this, event, is_keyboard_shortcut);
1543 void WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
1544 if (browser_plugin_embedder_ &&
1545 browser_plugin_embedder_->HandleKeyboardEvent(event)) {
1546 return;
1548 if (delegate_)
1549 delegate_->HandleKeyboardEvent(this, event);
1552 bool WebContentsImpl::HandleWheelEvent(
1553 const blink::WebMouseWheelEvent& event) {
1554 #if !defined(OS_MACOSX)
1555 // On platforms other than Mac, control+mousewheel may change zoom. On Mac,
1556 // this isn't done for two reasons:
1557 // -the OS already has a gesture to do this through pinch-zoom
1558 // -if a user starts an inertial scroll, let's go, and presses control
1559 // (i.e. control+tab) then the OS's buffered scroll events will come in
1560 // with control key set which isn't what the user wants
1561 if (delegate_ && event.wheelTicksY &&
1562 (event.modifiers & blink::WebInputEvent::ControlKey) &&
1563 !event.canScroll) {
1564 delegate_->ContentsZoomChange(event.wheelTicksY > 0);
1565 return true;
1567 #endif
1568 return false;
1571 bool WebContentsImpl::PreHandleGestureEvent(
1572 const blink::WebGestureEvent& event) {
1573 return delegate_ && delegate_->PreHandleGestureEvent(this, event);
1576 RenderWidgetHostInputEventRouter* WebContentsImpl::GetInputEventRouter() {
1577 // Currently only supported in site per process mode (--site-per-process).
1578 if (!rwh_input_event_router_.get() && !is_being_destroyed_ &&
1579 SiteIsolationPolicy::AreCrossProcessFramesPossible())
1580 rwh_input_event_router_.reset(new RenderWidgetHostInputEventRouter);
1581 return rwh_input_event_router_.get();
1584 void WebContentsImpl::EnterFullscreenMode(const GURL& origin) {
1585 // This method is being called to enter renderer-initiated fullscreen mode.
1586 // Make sure any existing fullscreen widget is shut down first.
1587 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
1588 if (widget_view)
1589 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())->Shutdown();
1591 if (delegate_)
1592 delegate_->EnterFullscreenModeForTab(this, origin);
1594 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1595 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1598 void WebContentsImpl::ExitFullscreenMode() {
1599 // This method is being called to leave renderer-initiated fullscreen mode.
1600 // Make sure any existing fullscreen widget is shut down first.
1601 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
1602 if (widget_view)
1603 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())->Shutdown();
1605 #if defined(OS_ANDROID)
1606 ContentVideoView* video_view = ContentVideoView::GetInstance();
1607 if (video_view != NULL)
1608 video_view->OnExitFullscreen();
1609 #endif
1611 if (delegate_)
1612 delegate_->ExitFullscreenModeForTab(this);
1614 // Ensure web contents exit fullscreen state by sending a resize message,
1615 // which includes the fullscreen state. This is required for the situation
1616 // of the browser moving the view into a fullscreen state "browser fullscreen"
1617 // and then the contents entering "tab fullscreen". Exiting the contents
1618 // "tab fullscreen" then won't have the side effect of the view resizing,
1619 // hence the explicit call here is required.
1620 if (RenderWidgetHostView* rwh_view = GetRenderWidgetHostView()) {
1621 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
1622 render_widget_host->WasResized();
1625 FOR_EACH_OBSERVER(WebContentsObserver,
1626 observers_,
1627 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1630 bool WebContentsImpl::IsFullscreenForCurrentTab() const {
1631 return delegate_ ? delegate_->IsFullscreenForTabOrPending(this) : false;
1634 blink::WebDisplayMode WebContentsImpl::GetDisplayMode() const {
1635 return delegate_ ? delegate_->GetDisplayMode(this)
1636 : blink::WebDisplayModeBrowser;
1639 void WebContentsImpl::RequestToLockMouse(bool user_gesture,
1640 bool last_unlocked_by_target) {
1641 if (delegate_) {
1642 delegate_->RequestToLockMouse(this, user_gesture, last_unlocked_by_target);
1643 } else {
1644 GotResponseToLockMouseRequest(false);
1648 void WebContentsImpl::LostMouseLock() {
1649 if (delegate_)
1650 delegate_->LostMouseLock();
1653 void WebContentsImpl::CreateNewWindow(
1654 SiteInstance* source_site_instance,
1655 int route_id,
1656 int main_frame_route_id,
1657 const ViewHostMsg_CreateWindow_Params& params,
1658 SessionStorageNamespace* session_storage_namespace) {
1659 // We usually create the new window in the same BrowsingInstance (group of
1660 // script-related windows), by passing in the current SiteInstance. However,
1661 // if the opener is being suppressed (in a non-guest), we create a new
1662 // SiteInstance in its own BrowsingInstance.
1663 bool is_guest = BrowserPluginGuest::IsGuest(this);
1665 if (is_guest && BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
1666 // TODO(lazyboy): CreateNewWindow doesn't work for OOPIF-based <webview>
1667 // yet.
1668 NOTREACHED();
1671 // If the opener is to be suppressed, the new window can be in any process.
1672 // Since routing ids are process specific, we must not have one passed in
1673 // as argument here.
1674 DCHECK(!params.opener_suppressed || route_id == MSG_ROUTING_NONE);
1676 scoped_refptr<SiteInstance> site_instance =
1677 params.opener_suppressed && !is_guest
1678 ? SiteInstance::CreateForURL(GetBrowserContext(), params.target_url)
1679 : source_site_instance;
1681 // A message to create a new window can only come from a process for a frame
1682 // in this WebContents' FrameTree. If any other process sends the request, it
1683 // is invalid and the process must be terminated.
1684 int render_process_id = source_site_instance->GetProcess()->GetID();
1685 bool did_match_process = false;
1686 frame_tree_.ForEach(
1687 base::Bind(&FindMatchingProcess, render_process_id, &did_match_process));
1688 if (!did_match_process) {
1689 RenderProcessHost* rph = source_site_instance->GetProcess();
1690 base::ProcessHandle process_handle = rph->GetHandle();
1691 if (process_handle != base::kNullProcessHandle) {
1692 RecordAction(
1693 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWindow"));
1694 rph->Shutdown(RESULT_CODE_KILLED, false);
1696 return;
1699 // We must assign the SessionStorageNamespace before calling Init().
1701 // http://crbug.com/142685
1702 const std::string& partition_id =
1703 GetContentClient()->browser()->
1704 GetStoragePartitionIdForSite(GetBrowserContext(),
1705 site_instance->GetSiteURL());
1706 StoragePartition* partition = BrowserContext::GetStoragePartition(
1707 GetBrowserContext(), site_instance.get());
1708 DOMStorageContextWrapper* dom_storage_context =
1709 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
1710 SessionStorageNamespaceImpl* session_storage_namespace_impl =
1711 static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
1712 CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
1714 if (delegate_ &&
1715 !delegate_->ShouldCreateWebContents(this,
1716 route_id,
1717 main_frame_route_id,
1718 params.window_container_type,
1719 params.frame_name,
1720 params.target_url,
1721 partition_id,
1722 session_storage_namespace)) {
1723 if (route_id != MSG_ROUTING_NONE &&
1724 !RenderViewHost::FromID(render_process_id, route_id)) {
1725 // If the embedder didn't create a WebContents for this route, we need to
1726 // delete the RenderView that had already been created.
1727 Send(new ViewMsg_Close(route_id));
1729 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(route_id);
1730 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(
1731 main_frame_route_id);
1732 return;
1735 // Create the new web contents. This will automatically create the new
1736 // WebContentsView. In the future, we may want to create the view separately.
1737 CreateParams create_params(GetBrowserContext(), site_instance.get());
1738 create_params.routing_id = route_id;
1739 create_params.main_frame_routing_id = main_frame_route_id;
1740 create_params.main_frame_name = params.frame_name;
1741 create_params.opener_render_process_id = render_process_id;
1742 create_params.opener_render_frame_id = params.opener_render_frame_id;
1743 create_params.opener_suppressed = params.opener_suppressed;
1744 if (params.disposition == NEW_BACKGROUND_TAB)
1745 create_params.initially_hidden = true;
1746 create_params.renderer_initiated_creation =
1747 main_frame_route_id != MSG_ROUTING_NONE;
1749 WebContentsImpl* new_contents = NULL;
1750 if (!is_guest) {
1751 create_params.context = view_->GetNativeView();
1752 create_params.initial_size = GetContainerBounds().size();
1753 new_contents = static_cast<WebContentsImpl*>(
1754 WebContents::Create(create_params));
1755 } else {
1756 new_contents = GetBrowserPluginGuest()->CreateNewGuestWindow(create_params);
1758 new_contents->GetController().SetSessionStorageNamespace(
1759 partition_id,
1760 session_storage_namespace);
1762 // If the new frame has a name, make sure any SiteInstances that can find
1763 // this named frame have proxies for it. Must be called after
1764 // SetSessionStorageNamespace, since this calls CreateRenderView, which uses
1765 // GetSessionStorageNamespace.
1766 if (!params.frame_name.empty())
1767 new_contents->GetRenderManager()->CreateProxiesForNewNamedFrame();
1769 // Save the window for later if we're not suppressing the opener (since it
1770 // will be shown immediately).
1771 if (!params.opener_suppressed) {
1772 if (!is_guest) {
1773 WebContentsView* new_view = new_contents->view_.get();
1775 // TODO(brettw): It seems bogus that we have to call this function on the
1776 // newly created object and give it one of its own member variables.
1777 new_view->CreateViewForWidget(new_contents->GetRenderViewHost(), false);
1779 // Save the created window associated with the route so we can show it
1780 // later.
1781 DCHECK_NE(MSG_ROUTING_NONE, route_id);
1782 pending_contents_[route_id] = new_contents;
1783 AddDestructionObserver(new_contents);
1786 if (delegate_) {
1787 delegate_->WebContentsCreated(
1788 this, params.opener_render_frame_id, params.frame_name,
1789 params.target_url, new_contents);
1792 if (params.opener_suppressed) {
1793 // When the opener is suppressed, the original renderer cannot access the
1794 // new window. As a result, we need to show and navigate the window here.
1795 bool was_blocked = false;
1796 if (delegate_) {
1797 gfx::Rect initial_rect;
1798 delegate_->AddNewContents(
1799 this, new_contents, params.disposition, initial_rect,
1800 params.user_gesture, &was_blocked);
1802 if (!was_blocked) {
1803 OpenURLParams open_params(params.target_url,
1804 Referrer(),
1805 CURRENT_TAB,
1806 ui::PAGE_TRANSITION_LINK,
1807 true /* is_renderer_initiated */);
1808 open_params.user_gesture = params.user_gesture;
1810 if (delegate_ && !is_guest &&
1811 !delegate_->ShouldResumeRequestsForCreatedWindow()) {
1812 // We are in asynchronous add new contents path, delay opening url
1813 new_contents->delayed_open_url_params_.reset(
1814 new OpenURLParams(open_params));
1815 } else {
1816 new_contents->OpenURL(open_params);
1822 void WebContentsImpl::CreateNewWidget(int32 render_process_id,
1823 int32 route_id,
1824 int32 surface_id,
1825 blink::WebPopupType popup_type) {
1826 CreateNewWidget(render_process_id, route_id, surface_id, false, popup_type);
1829 void WebContentsImpl::CreateNewFullscreenWidget(int32 render_process_id,
1830 int32 route_id,
1831 int32 surface_id) {
1832 CreateNewWidget(render_process_id, route_id, surface_id, true,
1833 blink::WebPopupTypeNone);
1836 void WebContentsImpl::CreateNewWidget(int32 render_process_id,
1837 int32 route_id,
1838 int32 surface_id,
1839 bool is_fullscreen,
1840 blink::WebPopupType popup_type) {
1841 RenderProcessHost* process = GetRenderProcessHost();
1842 // A message to create a new widget can only come from the active process for
1843 // this WebContentsImpl instance. If any other process sends the request,
1844 // it is invalid and the process must be terminated.
1845 if (process->GetID() != render_process_id) {
1846 RenderProcessHost* rph = RenderProcessHost::FromID(render_process_id);
1847 base::ProcessHandle process_handle = rph->GetHandle();
1848 if (process_handle != base::kNullProcessHandle) {
1849 RecordAction(
1850 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWidget"));
1851 rph->Shutdown(RESULT_CODE_KILLED, false);
1853 return;
1856 RenderWidgetHostImpl* widget_host =
1857 new RenderWidgetHostImpl(this, process, route_id, surface_id, IsHidden());
1858 created_widgets_.insert(widget_host);
1860 RenderWidgetHostViewBase* widget_view =
1861 static_cast<RenderWidgetHostViewBase*>(
1862 view_->CreateViewForPopupWidget(widget_host));
1863 if (!widget_view)
1864 return;
1865 if (!is_fullscreen) {
1866 // Popups should not get activated.
1867 widget_view->SetPopupType(popup_type);
1869 // Save the created widget associated with the route so we can show it later.
1870 pending_widget_views_[route_id] = widget_view;
1872 #if defined(OS_MACOSX)
1873 // A RenderWidgetHostViewMac has lifetime scoped to the view. We'll retain it
1874 // to allow it to survive the trip without being hosted.
1875 base::mac::NSObjectRetain(widget_view->GetNativeView());
1876 #endif
1879 void WebContentsImpl::ShowCreatedWindow(int route_id,
1880 WindowOpenDisposition disposition,
1881 const gfx::Rect& initial_rect,
1882 bool user_gesture) {
1883 WebContentsImpl* contents = GetCreatedWindow(route_id);
1884 if (contents) {
1885 WebContentsDelegate* delegate = GetDelegate();
1886 contents->is_resume_pending_ = true;
1887 if (!delegate || delegate->ShouldResumeRequestsForCreatedWindow())
1888 contents->ResumeLoadingCreatedWebContents();
1890 if (delegate) {
1891 delegate->AddNewContents(
1892 this, contents, disposition, initial_rect, user_gesture, NULL);
1897 void WebContentsImpl::ShowCreatedWidget(int route_id,
1898 const gfx::Rect& initial_rect) {
1899 ShowCreatedWidget(route_id, false, initial_rect);
1902 void WebContentsImpl::ShowCreatedFullscreenWidget(int route_id) {
1903 ShowCreatedWidget(route_id, true, gfx::Rect());
1906 void WebContentsImpl::ShowCreatedWidget(int route_id,
1907 bool is_fullscreen,
1908 const gfx::Rect& initial_rect) {
1909 RenderWidgetHostViewBase* widget_host_view =
1910 static_cast<RenderWidgetHostViewBase*>(GetCreatedWidget(route_id));
1911 if (!widget_host_view)
1912 return;
1914 RenderWidgetHostView* view = NULL;
1915 BrowserPluginGuest* guest = GetBrowserPluginGuest();
1916 if (guest && guest->embedder_web_contents()) {
1917 view = guest->embedder_web_contents()->GetRenderWidgetHostView();
1918 } else {
1919 view = GetRenderWidgetHostView();
1922 if (is_fullscreen) {
1923 DCHECK_EQ(MSG_ROUTING_NONE, fullscreen_widget_routing_id_);
1924 view_->StoreFocus();
1925 fullscreen_widget_routing_id_ = route_id;
1926 if (delegate_ && delegate_->EmbedsFullscreenWidget()) {
1927 widget_host_view->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
1928 delegate_->EnterFullscreenModeForTab(this, GURL());
1929 } else {
1930 widget_host_view->InitAsFullscreen(view);
1932 FOR_EACH_OBSERVER(WebContentsObserver,
1933 observers_,
1934 DidShowFullscreenWidget(route_id));
1935 if (!widget_host_view->HasFocus())
1936 widget_host_view->Focus();
1937 } else {
1938 widget_host_view->InitAsPopup(view, initial_rect);
1941 RenderWidgetHostImpl* render_widget_host_impl =
1942 RenderWidgetHostImpl::From(widget_host_view->GetRenderWidgetHost());
1943 render_widget_host_impl->Init();
1944 // Only allow privileged mouse lock for fullscreen render widget, which is
1945 // used to implement Pepper Flash fullscreen.
1946 render_widget_host_impl->set_allow_privileged_mouse_lock(is_fullscreen);
1948 #if defined(OS_MACOSX)
1949 // A RenderWidgetHostViewMac has lifetime scoped to the view. Now that it's
1950 // properly embedded (or purposefully ignored) we can release the retain we
1951 // took in CreateNewWidget().
1952 base::mac::NSObjectRelease(widget_host_view->GetNativeView());
1953 #endif
1956 WebContentsImpl* WebContentsImpl::GetCreatedWindow(int route_id) {
1957 PendingContents::iterator iter = pending_contents_.find(route_id);
1959 // Certain systems can block the creation of new windows. If we didn't succeed
1960 // in creating one, just return NULL.
1961 if (iter == pending_contents_.end()) {
1962 return NULL;
1965 WebContentsImpl* new_contents = iter->second;
1966 pending_contents_.erase(route_id);
1967 RemoveDestructionObserver(new_contents);
1969 // Don't initialize the guest WebContents immediately.
1970 if (BrowserPluginGuest::IsGuest(new_contents))
1971 return new_contents;
1973 if (!new_contents->GetRenderProcessHost()->HasConnection() ||
1974 !new_contents->GetRenderViewHost()->GetView())
1975 return NULL;
1977 return new_contents;
1980 RenderWidgetHostView* WebContentsImpl::GetCreatedWidget(int route_id) {
1981 PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id);
1982 if (iter == pending_widget_views_.end()) {
1983 DCHECK(false);
1984 return NULL;
1987 RenderWidgetHostView* widget_host_view = iter->second;
1988 pending_widget_views_.erase(route_id);
1990 RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
1991 if (!widget_host->GetProcess()->HasConnection()) {
1992 // The view has gone away or the renderer crashed. Nothing to do.
1993 return NULL;
1996 return widget_host_view;
1999 void WebContentsImpl::RequestMediaAccessPermission(
2000 const MediaStreamRequest& request,
2001 const MediaResponseCallback& callback) {
2002 if (delegate_) {
2003 delegate_->RequestMediaAccessPermission(this, request, callback);
2004 } else {
2005 callback.Run(MediaStreamDevices(),
2006 MEDIA_DEVICE_FAILED_DUE_TO_SHUTDOWN,
2007 scoped_ptr<MediaStreamUI>());
2011 bool WebContentsImpl::CheckMediaAccessPermission(const GURL& security_origin,
2012 MediaStreamType type) {
2013 DCHECK(type == MEDIA_DEVICE_AUDIO_CAPTURE ||
2014 type == MEDIA_DEVICE_VIDEO_CAPTURE);
2015 return delegate_ &&
2016 delegate_->CheckMediaAccessPermission(this, security_origin, type);
2019 SessionStorageNamespace* WebContentsImpl::GetSessionStorageNamespace(
2020 SiteInstance* instance) {
2021 return controller_.GetSessionStorageNamespace(instance);
2024 SessionStorageNamespaceMap WebContentsImpl::GetSessionStorageNamespaceMap() {
2025 return controller_.GetSessionStorageNamespaceMap();
2028 FrameTree* WebContentsImpl::GetFrameTree() {
2029 return &frame_tree_;
2032 void WebContentsImpl::SetIsVirtualKeyboardRequested(bool requested) {
2033 virtual_keyboard_requested_ = requested;
2036 bool WebContentsImpl::IsVirtualKeyboardRequested() {
2037 return virtual_keyboard_requested_;
2040 AccessibilityMode WebContentsImpl::GetAccessibilityMode() const {
2041 return accessibility_mode_;
2044 void WebContentsImpl::AccessibilityEventReceived(
2045 const std::vector<AXEventNotificationDetails>& details) {
2046 FOR_EACH_OBSERVER(
2047 WebContentsObserver, observers_, AccessibilityEventReceived(details));
2050 RenderFrameHost* WebContentsImpl::GetGuestByInstanceID(
2051 RenderFrameHost* render_frame_host,
2052 int browser_plugin_instance_id) {
2053 BrowserPluginGuestManager* guest_manager =
2054 GetBrowserContext()->GetGuestManager();
2055 if (!guest_manager)
2056 return nullptr;
2058 WebContents* guest = guest_manager->GetGuestByInstanceID(
2059 render_frame_host->GetProcess()->GetID(), browser_plugin_instance_id);
2060 if (!guest)
2061 return nullptr;
2063 return guest->GetMainFrame();
2066 GeolocationServiceContext* WebContentsImpl::GetGeolocationServiceContext() {
2067 return geolocation_service_context_.get();
2070 void WebContentsImpl::OnShowValidationMessage(
2071 const gfx::Rect& anchor_in_root_view,
2072 const base::string16& main_text,
2073 const base::string16& sub_text) {
2074 if (delegate_)
2075 delegate_->ShowValidationMessage(
2076 this, anchor_in_root_view, main_text, sub_text);
2079 void WebContentsImpl::OnHideValidationMessage() {
2080 if (delegate_)
2081 delegate_->HideValidationMessage(this);
2084 void WebContentsImpl::OnMoveValidationMessage(
2085 const gfx::Rect& anchor_in_root_view) {
2086 if (delegate_)
2087 delegate_->MoveValidationMessage(this, anchor_in_root_view);
2090 void WebContentsImpl::DidSendScreenRects(RenderWidgetHostImpl* rwh) {
2091 if (browser_plugin_embedder_)
2092 browser_plugin_embedder_->DidSendScreenRects();
2095 BrowserAccessibilityManager*
2096 WebContentsImpl::GetRootBrowserAccessibilityManager() {
2097 RenderFrameHostImpl* rfh = GetMainFrame();
2098 return rfh ? rfh->browser_accessibility_manager() : nullptr;
2101 BrowserAccessibilityManager*
2102 WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
2103 RenderFrameHostImpl* rfh = GetMainFrame();
2104 return rfh ? rfh->GetOrCreateBrowserAccessibilityManager() : nullptr;
2107 void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point& extent) {
2108 RenderFrameHost* focused_frame = GetFocusedFrame();
2109 if (!focused_frame)
2110 return;
2112 focused_frame->Send(new InputMsg_MoveRangeSelectionExtent(
2113 focused_frame->GetRoutingID(), extent));
2116 void WebContentsImpl::SelectRange(const gfx::Point& base,
2117 const gfx::Point& extent) {
2118 RenderFrameHost* focused_frame = GetFocusedFrame();
2119 if (!focused_frame)
2120 return;
2122 focused_frame->Send(
2123 new InputMsg_SelectRange(focused_frame->GetRoutingID(), base, extent));
2126 void WebContentsImpl::AdjustSelectionByCharacterOffset(int start_adjust,
2127 int end_adjust) {
2128 RenderFrameHost* focused_frame = GetFocusedFrame();
2129 if (!focused_frame)
2130 return;
2132 focused_frame->Send(new InputMsg_AdjustSelectionByCharacterOffset(
2133 focused_frame->GetRoutingID(), start_adjust, end_adjust));
2136 void WebContentsImpl::UpdatePreferredSize(const gfx::Size& pref_size) {
2137 const gfx::Size old_size = GetPreferredSize();
2138 preferred_size_ = pref_size;
2139 OnPreferredSizeChanged(old_size);
2142 void WebContentsImpl::ResizeDueToAutoResize(const gfx::Size& new_size) {
2143 if (delegate_)
2144 delegate_->ResizeDueToAutoResize(this, new_size);
2147 WebContents* WebContentsImpl::OpenURL(const OpenURLParams& params) {
2148 if (!delegate_)
2149 return NULL;
2151 WebContents* new_contents = delegate_->OpenURLFromTab(this, params);
2152 return new_contents;
2155 bool WebContentsImpl::Send(IPC::Message* message) {
2156 if (!GetRenderViewHost()) {
2157 delete message;
2158 return false;
2161 return GetRenderViewHost()->Send(message);
2164 void WebContentsImpl::RenderFrameForInterstitialPageCreated(
2165 RenderFrameHost* render_frame_host) {
2166 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2167 RenderFrameForInterstitialPageCreated(render_frame_host));
2170 void WebContentsImpl::AttachInterstitialPage(
2171 InterstitialPageImpl* interstitial_page) {
2172 DCHECK(interstitial_page);
2173 GetRenderManager()->set_interstitial_page(interstitial_page);
2175 // Cancel any visible dialogs so that they don't interfere with the
2176 // interstitial.
2177 CancelActiveAndPendingDialogs();
2179 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2180 DidAttachInterstitialPage());
2183 void WebContentsImpl::DetachInterstitialPage() {
2184 if (ShowingInterstitialPage())
2185 GetRenderManager()->remove_interstitial_page();
2186 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2187 DidDetachInterstitialPage());
2190 void WebContentsImpl::SetHistoryOffsetAndLength(int history_offset,
2191 int history_length) {
2192 SetHistoryOffsetAndLengthForView(
2193 GetRenderViewHost(), history_offset, history_length);
2196 void WebContentsImpl::SetHistoryOffsetAndLengthForView(
2197 RenderViewHost* render_view_host,
2198 int history_offset,
2199 int history_length) {
2200 render_view_host->Send(new ViewMsg_SetHistoryOffsetAndLength(
2201 render_view_host->GetRoutingID(), history_offset, history_length));
2204 void WebContentsImpl::ReloadFocusedFrame(bool ignore_cache) {
2205 RenderFrameHost* focused_frame = GetFocusedFrame();
2206 if (!focused_frame)
2207 return;
2209 focused_frame->Send(new FrameMsg_Reload(
2210 focused_frame->GetRoutingID(), ignore_cache));
2213 void WebContentsImpl::Undo() {
2214 RenderFrameHost* focused_frame = GetFocusedFrame();
2215 if (!focused_frame)
2216 return;
2218 focused_frame->Send(new InputMsg_Undo(focused_frame->GetRoutingID()));
2219 RecordAction(base::UserMetricsAction("Undo"));
2222 void WebContentsImpl::Redo() {
2223 RenderFrameHost* focused_frame = GetFocusedFrame();
2224 if (!focused_frame)
2225 return;
2226 focused_frame->Send(new InputMsg_Redo(focused_frame->GetRoutingID()));
2227 RecordAction(base::UserMetricsAction("Redo"));
2230 void WebContentsImpl::Cut() {
2231 RenderFrameHost* focused_frame = GetFocusedFrame();
2232 if (!focused_frame)
2233 return;
2235 focused_frame->Send(new InputMsg_Cut(focused_frame->GetRoutingID()));
2236 RecordAction(base::UserMetricsAction("Cut"));
2239 void WebContentsImpl::Copy() {
2240 RenderFrameHost* focused_frame = GetFocusedFrame();
2241 if (!focused_frame)
2242 return;
2244 focused_frame->Send(new InputMsg_Copy(focused_frame->GetRoutingID()));
2245 RecordAction(base::UserMetricsAction("Copy"));
2248 void WebContentsImpl::CopyToFindPboard() {
2249 #if defined(OS_MACOSX)
2250 RenderFrameHost* focused_frame = GetFocusedFrame();
2251 if (!focused_frame)
2252 return;
2254 // Windows/Linux don't have the concept of a find pasteboard.
2255 focused_frame->Send(
2256 new InputMsg_CopyToFindPboard(focused_frame->GetRoutingID()));
2257 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
2258 #endif
2261 void WebContentsImpl::Paste() {
2262 RenderFrameHost* focused_frame = GetFocusedFrame();
2263 if (!focused_frame)
2264 return;
2266 focused_frame->Send(new InputMsg_Paste(focused_frame->GetRoutingID()));
2267 RecordAction(base::UserMetricsAction("Paste"));
2270 void WebContentsImpl::PasteAndMatchStyle() {
2271 RenderFrameHost* focused_frame = GetFocusedFrame();
2272 if (!focused_frame)
2273 return;
2275 focused_frame->Send(new InputMsg_PasteAndMatchStyle(
2276 focused_frame->GetRoutingID()));
2277 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
2280 void WebContentsImpl::Delete() {
2281 RenderFrameHost* focused_frame = GetFocusedFrame();
2282 if (!focused_frame)
2283 return;
2285 focused_frame->Send(new InputMsg_Delete(focused_frame->GetRoutingID()));
2286 RecordAction(base::UserMetricsAction("DeleteSelection"));
2289 void WebContentsImpl::SelectAll() {
2290 RenderFrameHost* focused_frame = GetFocusedFrame();
2291 if (!focused_frame)
2292 return;
2294 focused_frame->Send(new InputMsg_SelectAll(focused_frame->GetRoutingID()));
2295 RecordAction(base::UserMetricsAction("SelectAll"));
2298 void WebContentsImpl::Unselect() {
2299 RenderFrameHost* focused_frame = GetFocusedFrame();
2300 if (!focused_frame)
2301 return;
2303 focused_frame->Send(new InputMsg_Unselect(focused_frame->GetRoutingID()));
2304 RecordAction(base::UserMetricsAction("Unselect"));
2307 void WebContentsImpl::Replace(const base::string16& word) {
2308 RenderFrameHost* focused_frame = GetFocusedFrame();
2309 if (!focused_frame)
2310 return;
2312 focused_frame->Send(new InputMsg_Replace(
2313 focused_frame->GetRoutingID(), word));
2316 void WebContentsImpl::ReplaceMisspelling(const base::string16& word) {
2317 RenderFrameHost* focused_frame = GetFocusedFrame();
2318 if (!focused_frame)
2319 return;
2321 focused_frame->Send(new InputMsg_ReplaceMisspelling(
2322 focused_frame->GetRoutingID(), word));
2325 void WebContentsImpl::NotifyContextMenuClosed(
2326 const CustomContextMenuContext& context) {
2327 RenderFrameHost* focused_frame = GetFocusedFrame();
2328 if (!focused_frame)
2329 return;
2331 focused_frame->Send(new FrameMsg_ContextMenuClosed(
2332 focused_frame->GetRoutingID(), context));
2335 void WebContentsImpl::ExecuteCustomContextMenuCommand(
2336 int action, const CustomContextMenuContext& context) {
2337 RenderFrameHost* focused_frame = GetFocusedFrame();
2338 if (!focused_frame)
2339 return;
2341 focused_frame->Send(new FrameMsg_CustomContextMenuAction(
2342 focused_frame->GetRoutingID(), context, action));
2345 gfx::NativeView WebContentsImpl::GetNativeView() {
2346 return view_->GetNativeView();
2349 gfx::NativeView WebContentsImpl::GetContentNativeView() {
2350 return view_->GetContentNativeView();
2353 gfx::NativeWindow WebContentsImpl::GetTopLevelNativeWindow() {
2354 return view_->GetTopLevelNativeWindow();
2357 gfx::Rect WebContentsImpl::GetViewBounds() {
2358 return view_->GetViewBounds();
2361 gfx::Rect WebContentsImpl::GetContainerBounds() {
2362 gfx::Rect rv;
2363 view_->GetContainerBounds(&rv);
2364 return rv;
2367 DropData* WebContentsImpl::GetDropData() {
2368 return view_->GetDropData();
2371 void WebContentsImpl::Focus() {
2372 view_->Focus();
2375 void WebContentsImpl::SetInitialFocus() {
2376 view_->SetInitialFocus();
2379 void WebContentsImpl::StoreFocus() {
2380 view_->StoreFocus();
2383 void WebContentsImpl::RestoreFocus() {
2384 view_->RestoreFocus();
2387 void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
2388 if (ShowingInterstitialPage()) {
2389 GetRenderManager()->interstitial_page()->FocusThroughTabTraversal(reverse);
2390 return;
2392 RenderWidgetHostView* const fullscreen_view =
2393 GetFullscreenRenderWidgetHostView();
2394 if (fullscreen_view) {
2395 fullscreen_view->Focus();
2396 return;
2398 GetRenderViewHost()->SetInitialFocus(reverse);
2401 bool WebContentsImpl::ShowingInterstitialPage() const {
2402 return GetRenderManager()->interstitial_page() != NULL;
2405 InterstitialPage* WebContentsImpl::GetInterstitialPage() const {
2406 return GetRenderManager()->interstitial_page();
2409 bool WebContentsImpl::IsSavable() {
2410 // WebKit creates Document object when MIME type is application/xhtml+xml,
2411 // so we also support this MIME type.
2412 return contents_mime_type_ == "text/html" ||
2413 contents_mime_type_ == "text/xml" ||
2414 contents_mime_type_ == "application/xhtml+xml" ||
2415 contents_mime_type_ == "text/plain" ||
2416 contents_mime_type_ == "text/css" ||
2417 mime_util::IsSupportedJavascriptMimeType(contents_mime_type_);
2420 void WebContentsImpl::OnSavePage() {
2421 // If we can not save the page, try to download it.
2422 if (!IsSavable()) {
2423 RecordDownloadSource(INITIATED_BY_SAVE_PACKAGE_ON_NON_HTML);
2424 SaveFrame(GetLastCommittedURL(), Referrer());
2425 return;
2428 Stop();
2430 // Create the save package and possibly prompt the user for the name to save
2431 // the page as. The user prompt is an asynchronous operation that runs on
2432 // another thread.
2433 save_package_ = new SavePackage(this);
2434 save_package_->GetSaveInfo();
2437 // Used in automated testing to bypass prompting the user for file names.
2438 // Instead, the names and paths are hard coded rather than running them through
2439 // file name sanitation and extension / mime checking.
2440 bool WebContentsImpl::SavePage(const base::FilePath& main_file,
2441 const base::FilePath& dir_path,
2442 SavePageType save_type) {
2443 // Stop the page from navigating.
2444 Stop();
2446 save_package_ = new SavePackage(this, save_type, main_file, dir_path);
2447 return save_package_->Init(SavePackageDownloadCreatedCallback());
2450 void WebContentsImpl::SaveFrame(const GURL& url,
2451 const Referrer& referrer) {
2452 SaveFrameWithHeaders(url, referrer, std::string());
2455 void WebContentsImpl::SaveFrameWithHeaders(const GURL& url,
2456 const Referrer& referrer,
2457 const std::string& headers) {
2458 if (!GetLastCommittedURL().is_valid())
2459 return;
2460 if (delegate_ && delegate_->SaveFrame(url, referrer))
2461 return;
2463 // TODO(nasko): This check for main frame is incorrect and should be fixed
2464 // by explicitly passing in which frame this method should target.
2465 bool is_main_frame = (url == GetLastCommittedURL());
2467 DownloadManager* dlm =
2468 BrowserContext::GetDownloadManager(GetBrowserContext());
2469 if (!dlm)
2470 return;
2471 int64 post_id = -1;
2472 if (is_main_frame) {
2473 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2474 if (entry)
2475 post_id = entry->GetPostID();
2477 scoped_ptr<DownloadUrlParameters> params(
2478 DownloadUrlParameters::FromWebContents(this, url));
2479 params->set_referrer(referrer);
2480 params->set_post_id(post_id);
2481 if (post_id >= 0)
2482 params->set_method("POST");
2483 params->set_prompt(true);
2485 if (headers.empty()) {
2486 params->set_prefer_cache(true);
2487 } else {
2488 for (const base::StringPiece& key_value :
2489 base::SplitStringPiece(
2490 headers, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
2491 std::vector<std::string> pair = base::SplitString(
2492 key_value, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
2493 DCHECK_EQ(2ul, pair.size());
2494 params->add_request_header(pair[0], pair[1]);
2497 dlm->DownloadUrl(params.Pass());
2500 void WebContentsImpl::GenerateMHTML(
2501 const base::FilePath& file,
2502 const base::Callback<void(int64)>& callback) {
2503 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, file, callback);
2506 const std::string& WebContentsImpl::GetContentsMimeType() const {
2507 return contents_mime_type_;
2510 bool WebContentsImpl::WillNotifyDisconnection() const {
2511 return notify_disconnection_;
2514 void WebContentsImpl::SetOverrideEncoding(const std::string& encoding) {
2515 SetEncoding(encoding);
2516 Send(new ViewMsg_SetPageEncoding(GetRoutingID(), encoding));
2519 void WebContentsImpl::ResetOverrideEncoding() {
2520 canonical_encoding_.clear();
2521 Send(new ViewMsg_ResetPageEncodingToDefault(GetRoutingID()));
2524 RendererPreferences* WebContentsImpl::GetMutableRendererPrefs() {
2525 return &renderer_preferences_;
2528 void WebContentsImpl::Close() {
2529 Close(GetRenderViewHost());
2532 void WebContentsImpl::DragSourceEndedAt(int client_x, int client_y,
2533 int screen_x, int screen_y, blink::WebDragOperation operation) {
2534 if (browser_plugin_embedder_.get())
2535 browser_plugin_embedder_->DragSourceEndedAt(client_x, client_y,
2536 screen_x, screen_y, operation);
2537 if (GetRenderViewHost())
2538 GetRenderViewHost()->DragSourceEndedAt(client_x, client_y, screen_x,
2539 screen_y, operation);
2542 void WebContentsImpl::DidGetResourceResponseStart(
2543 const ResourceRequestDetails& details) {
2544 controller_.ssl_manager()->DidStartResourceResponse(details);
2546 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2547 DidGetResourceResponseStart(details));
2550 void WebContentsImpl::DidGetRedirectForResourceRequest(
2551 RenderFrameHost* render_frame_host,
2552 const ResourceRedirectDetails& details) {
2553 controller_.ssl_manager()->DidReceiveResourceRedirect(details);
2555 FOR_EACH_OBSERVER(
2556 WebContentsObserver,
2557 observers_,
2558 DidGetRedirectForResourceRequest(render_frame_host, details));
2560 // TODO(avi): Remove. http://crbug.com/170921
2561 NotificationService::current()->Notify(
2562 NOTIFICATION_RESOURCE_RECEIVED_REDIRECT,
2563 Source<WebContents>(this),
2564 Details<const ResourceRedirectDetails>(&details));
2566 if (IsResourceTypeFrame(details.resource_type)) {
2567 NavigationHandleImpl* navigation_handle =
2568 static_cast<RenderFrameHostImpl*>(render_frame_host)
2569 ->navigation_handle();
2570 if (navigation_handle)
2571 navigation_handle->DidRedirectNavigation(details.new_url);
2575 void WebContentsImpl::NotifyWebContentsFocused() {
2576 FOR_EACH_OBSERVER(WebContentsObserver, observers_, OnWebContentsFocused());
2579 void WebContentsImpl::SystemDragEnded() {
2580 if (GetRenderViewHost())
2581 GetRenderViewHost()->DragSourceSystemDragEnded();
2582 if (browser_plugin_embedder_.get())
2583 browser_plugin_embedder_->SystemDragEnded();
2586 void WebContentsImpl::UserGestureDone() {
2587 OnUserGesture();
2590 void WebContentsImpl::SetClosedByUserGesture(bool value) {
2591 closed_by_user_gesture_ = value;
2594 bool WebContentsImpl::GetClosedByUserGesture() const {
2595 return closed_by_user_gesture_;
2598 void WebContentsImpl::ViewSource() {
2599 if (!delegate_)
2600 return;
2602 NavigationEntry* entry = GetController().GetLastCommittedEntry();
2603 if (!entry)
2604 return;
2606 delegate_->ViewSourceForTab(this, entry->GetURL());
2609 void WebContentsImpl::ViewFrameSource(const GURL& url,
2610 const PageState& page_state) {
2611 if (!delegate_)
2612 return;
2614 delegate_->ViewSourceForFrame(this, url, page_state);
2617 int WebContentsImpl::GetMinimumZoomPercent() const {
2618 return minimum_zoom_percent_;
2621 int WebContentsImpl::GetMaximumZoomPercent() const {
2622 return maximum_zoom_percent_;
2625 void WebContentsImpl::ResetPageScale() {
2626 Send(new ViewMsg_ResetPageScale(GetRoutingID()));
2629 gfx::Size WebContentsImpl::GetPreferredSize() const {
2630 return capturer_count_ == 0 ? preferred_size_ : preferred_size_for_capture_;
2633 bool WebContentsImpl::GotResponseToLockMouseRequest(bool allowed) {
2634 if (GetBrowserPluginGuest())
2635 return GetBrowserPluginGuest()->LockMouse(allowed);
2637 return GetRenderViewHost()
2638 ? GetRenderViewHost()->GotResponseToLockMouseRequest(allowed)
2639 : false;
2642 bool WebContentsImpl::HasOpener() const {
2643 return GetOpener() != NULL;
2646 WebContentsImpl* WebContentsImpl::GetOpener() const {
2647 FrameTreeNode* opener_ftn = frame_tree_.root()->opener();
2648 return opener_ftn ? FromFrameTreeNode(opener_ftn) : nullptr;
2651 void WebContentsImpl::DidChooseColorInColorChooser(SkColor color) {
2652 if (!color_chooser_info_.get())
2653 return;
2654 RenderFrameHost* rfh = RenderFrameHost::FromID(
2655 color_chooser_info_->render_process_id,
2656 color_chooser_info_->render_frame_id);
2657 if (!rfh)
2658 return;
2660 rfh->Send(new FrameMsg_DidChooseColorResponse(
2661 rfh->GetRoutingID(), color_chooser_info_->identifier, color));
2664 void WebContentsImpl::DidEndColorChooser() {
2665 if (!color_chooser_info_.get())
2666 return;
2667 RenderFrameHost* rfh = RenderFrameHost::FromID(
2668 color_chooser_info_->render_process_id,
2669 color_chooser_info_->render_frame_id);
2670 if (!rfh)
2671 return;
2673 rfh->Send(new FrameMsg_DidEndColorChooser(
2674 rfh->GetRoutingID(), color_chooser_info_->identifier));
2675 color_chooser_info_.reset();
2678 int WebContentsImpl::DownloadImage(
2679 const GURL& url,
2680 bool is_favicon,
2681 uint32_t max_bitmap_size,
2682 bool bypass_cache,
2683 const WebContents::ImageDownloadCallback& callback) {
2684 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2685 static int next_image_download_id = 0;
2686 const image_downloader::ImageDownloaderPtr& mojo_image_downloader =
2687 GetMainFrame()->GetMojoImageDownloader();
2688 const int download_id = ++next_image_download_id;
2689 if (!mojo_image_downloader) {
2690 // If the renderer process is dead (i.e. crash, or memory pressure on
2691 // Android), the downloader service will be invalid. Pre-Mojo, this would
2692 // hang the callback indefinetly since the IPC would be dropped. Now,
2693 // respond with a 400 HTTP error code to indicate that something went wrong.
2694 BrowserThread::PostTask(
2695 BrowserThread::UI, FROM_HERE,
2696 base::Bind(&WebContents::ImageDownloadCallback::Run,
2697 base::Owned(new ImageDownloadCallback(callback)),
2698 download_id, 400, url, std::vector<SkBitmap>(),
2699 std::vector<gfx::Size>()));
2700 return download_id;
2703 image_downloader::DownloadRequestPtr req =
2704 image_downloader::DownloadRequest::New();
2706 req->url = mojo::String::From(url);
2707 req->is_favicon = is_favicon;
2708 req->max_bitmap_size = max_bitmap_size;
2709 req->bypass_cache = bypass_cache;
2711 mojo_image_downloader->DownloadImage(
2712 req.Pass(),
2713 base::Bind(&DidDownloadImage, callback, download_id, url));
2714 return download_id;
2717 bool WebContentsImpl::IsSubframe() const {
2718 return is_subframe_;
2721 void WebContentsImpl::Find(int request_id,
2722 const base::string16& search_text,
2723 const blink::WebFindOptions& options) {
2724 // See if a top level browser plugin handles the find request first.
2725 if (browser_plugin_embedder_ &&
2726 browser_plugin_embedder_->Find(request_id, search_text, options)) {
2727 return;
2729 Send(new ViewMsg_Find(GetRoutingID(), request_id, search_text, options));
2732 void WebContentsImpl::StopFinding(StopFindAction action) {
2733 // See if a top level browser plugin handles the stop finding request first.
2734 if (browser_plugin_embedder_ &&
2735 browser_plugin_embedder_->StopFinding(action)) {
2736 return;
2738 Send(new ViewMsg_StopFinding(GetRoutingID(), action));
2741 void WebContentsImpl::InsertCSS(const std::string& css) {
2742 GetMainFrame()->Send(new FrameMsg_CSSInsertRequest(
2743 GetMainFrame()->GetRoutingID(), css));
2746 bool WebContentsImpl::WasRecentlyAudible() {
2747 return audio_stream_monitor_.WasRecentlyAudible();
2750 void WebContentsImpl::GetManifest(const GetManifestCallback& callback) {
2751 manifest_manager_host_->GetManifest(GetMainFrame(), callback);
2754 void WebContentsImpl::ExitFullscreen() {
2755 // Clean up related state and initiate the fullscreen exit.
2756 GetRenderViewHost()->RejectMouseLockOrUnlockIfNecessary();
2757 ExitFullscreenMode();
2760 void WebContentsImpl::ResumeLoadingCreatedWebContents() {
2761 if (delayed_open_url_params_.get()) {
2762 OpenURL(*delayed_open_url_params_.get());
2763 delayed_open_url_params_.reset(nullptr);
2764 return;
2767 // Resume blocked requests for both the RenderViewHost and RenderFrameHost.
2768 // TODO(brettw): It seems bogus to reach into here and initialize the host.
2769 if (is_resume_pending_) {
2770 is_resume_pending_ = false;
2771 GetRenderViewHost()->Init();
2772 GetMainFrame()->Init();
2776 bool WebContentsImpl::FocusLocationBarByDefault() {
2777 NavigationEntry* entry = controller_.GetVisibleEntry();
2778 if (entry && entry->GetURL() == GURL(url::kAboutBlankURL))
2779 return true;
2780 return delegate_ && delegate_->ShouldFocusLocationBarByDefault(this);
2783 void WebContentsImpl::SetFocusToLocationBar(bool select_all) {
2784 if (delegate_)
2785 delegate_->SetFocusToLocationBar(select_all);
2788 void WebContentsImpl::DidStartNavigation(NavigationHandle* navigation_handle) {
2789 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2790 DidStartNavigation(navigation_handle));
2793 void WebContentsImpl::DidRedirectNavigation(
2794 NavigationHandle* navigation_handle) {
2795 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2796 DidRedirectNavigation(navigation_handle));
2799 void WebContentsImpl::ReadyToCommitNavigation(
2800 NavigationHandle* navigation_handle) {
2801 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2802 ReadyToCommitNavigation(navigation_handle));
2805 void WebContentsImpl::DidCommitNavigation(NavigationHandle* navigation_handle) {
2806 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2807 DidCommitNavigation(navigation_handle));
2810 void WebContentsImpl::DidFinishNavigation(NavigationHandle* navigation_handle) {
2811 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2812 DidFinishNavigation(navigation_handle));
2815 void WebContentsImpl::DidStartProvisionalLoad(
2816 RenderFrameHostImpl* render_frame_host,
2817 const GURL& validated_url,
2818 bool is_error_page,
2819 bool is_iframe_srcdoc) {
2820 // Notify observers about the start of the provisional load.
2821 FOR_EACH_OBSERVER(
2822 WebContentsObserver,
2823 observers_,
2824 DidStartProvisionalLoadForFrame(
2825 render_frame_host, validated_url, is_error_page, is_iframe_srcdoc));
2827 // Notify accessibility if this is a reload.
2828 NavigationEntry* entry = controller_.GetVisibleEntry();
2829 if (entry && ui::PageTransitionCoreTypeIs(
2830 entry->GetTransitionType(), ui::PAGE_TRANSITION_RELOAD)) {
2831 FrameTreeNode* ftn = render_frame_host->frame_tree_node();
2832 BrowserAccessibilityManager* manager =
2833 ftn->current_frame_host()->browser_accessibility_manager();
2834 if (manager)
2835 manager->UserIsReloading();
2839 void WebContentsImpl::DidFailProvisionalLoadWithError(
2840 RenderFrameHostImpl* render_frame_host,
2841 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
2842 GURL validated_url(params.url);
2843 FOR_EACH_OBSERVER(WebContentsObserver,
2844 observers_,
2845 DidFailProvisionalLoad(render_frame_host,
2846 validated_url,
2847 params.error_code,
2848 params.error_description,
2849 params.was_ignored_by_handler));
2851 FrameTreeNode* ftn = render_frame_host->frame_tree_node();
2852 BrowserAccessibilityManager* manager =
2853 ftn->current_frame_host()->browser_accessibility_manager();
2854 if (manager)
2855 manager->NavigationFailed();
2858 void WebContentsImpl::DidFailLoadWithError(
2859 RenderFrameHostImpl* render_frame_host,
2860 const GURL& url,
2861 int error_code,
2862 const base::string16& error_description,
2863 bool was_ignored_by_handler) {
2864 FOR_EACH_OBSERVER(
2865 WebContentsObserver,
2866 observers_,
2867 DidFailLoad(render_frame_host, url, error_code, error_description,
2868 was_ignored_by_handler));
2871 void WebContentsImpl::NotifyChangedNavigationState(
2872 InvalidateTypes changed_flags) {
2873 NotifyNavigationStateChanged(changed_flags);
2876 void WebContentsImpl::AboutToNavigateRenderFrame(
2877 RenderFrameHostImpl* old_host,
2878 RenderFrameHostImpl* new_host) {
2879 // Notify observers that we will navigate in this RenderFrame.
2880 FOR_EACH_OBSERVER(
2881 WebContentsObserver,
2882 observers_,
2883 AboutToNavigateRenderFrame(old_host, new_host));
2886 void WebContentsImpl::DidStartNavigationToPendingEntry(
2887 const GURL& url,
2888 NavigationController::ReloadType reload_type) {
2889 // Notify observers about navigation.
2890 FOR_EACH_OBSERVER(
2891 WebContentsObserver,
2892 observers_,
2893 DidStartNavigationToPendingEntry(url, reload_type));
2896 void WebContentsImpl::RequestOpenURL(RenderFrameHostImpl* render_frame_host,
2897 const OpenURLParams& params) {
2898 // OpenURL can blow away the source RFH. Use the process/frame routing ID as a
2899 // weak pointer of sorts.
2900 const int32_t process_id = render_frame_host->GetProcess()->GetID();
2901 const int32_t frame_id = render_frame_host->GetRoutingID();
2903 WebContents* new_contents = OpenURL(params);
2905 if (new_contents && RenderFrameHost::FromID(process_id, frame_id)) {
2906 // Notify observers.
2907 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2908 DidOpenRequestedURL(new_contents,
2909 render_frame_host,
2910 params.url,
2911 params.referrer,
2912 params.disposition,
2913 params.transition));
2917 bool WebContentsImpl::ShouldPreserveAbortedURLs() {
2918 if (!delegate_)
2919 return false;
2920 return delegate_->ShouldPreserveAbortedURLs(this);
2923 void WebContentsImpl::DidCommitProvisionalLoad(
2924 RenderFrameHostImpl* render_frame_host,
2925 const GURL& url,
2926 ui::PageTransition transition_type) {
2927 // Notify observers about the commit of the provisional load.
2928 FOR_EACH_OBSERVER(WebContentsObserver,
2929 observers_,
2930 DidCommitProvisionalLoadForFrame(
2931 render_frame_host, url, transition_type));
2933 BrowserAccessibilityManager* manager =
2934 render_frame_host->browser_accessibility_manager();
2935 if (manager)
2936 manager->NavigationSucceeded();
2939 void WebContentsImpl::DidNavigateMainFramePreCommit(
2940 bool navigation_is_within_page) {
2941 // Ensure fullscreen mode is exited before committing the navigation to a
2942 // different page. The next page will not start out assuming it is in
2943 // fullscreen mode.
2944 if (navigation_is_within_page) {
2945 // No page change? Then, the renderer and browser can remain in fullscreen.
2946 return;
2948 if (IsFullscreenForCurrentTab())
2949 ExitFullscreen();
2950 DCHECK(!IsFullscreenForCurrentTab());
2953 void WebContentsImpl::DidNavigateMainFramePostCommit(
2954 RenderFrameHostImpl* render_frame_host,
2955 const LoadCommittedDetails& details,
2956 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
2957 if (details.is_navigation_to_different_page()) {
2958 // Clear the status bubble. This is a workaround for a bug where WebKit
2959 // doesn't let us know that the cursor left an element during a
2960 // transition (this is also why the mouse cursor remains as a hand after
2961 // clicking on a link); see bugs 1184641 and 980803. We don't want to
2962 // clear the bubble when a user navigates to a named anchor in the same
2963 // page.
2964 UpdateTargetURL(render_frame_host->GetRenderViewHost(), GURL());
2966 RenderWidgetHostViewBase* rwhvb =
2967 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
2968 if (rwhvb)
2969 rwhvb->OnDidNavigateMainFrameToNewPage();
2971 did_first_visually_non_empty_paint_ = false;
2973 // Reset theme color on navigation to new page.
2974 theme_color_ = SK_ColorTRANSPARENT;
2977 if (!details.is_in_page) {
2978 // Once the main frame is navigated, we're no longer considered to have
2979 // displayed insecure content.
2980 displayed_insecure_content_ = false;
2981 SSLManager::NotifySSLInternalStateChanged(
2982 GetController().GetBrowserContext());
2985 // Notify observers about navigation.
2986 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2987 DidNavigateMainFrame(details, params));
2989 if (delegate_)
2990 delegate_->DidNavigateMainFramePostCommit(this);
2991 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
2994 void WebContentsImpl::DidNavigateAnyFramePostCommit(
2995 RenderFrameHostImpl* render_frame_host,
2996 const LoadCommittedDetails& details,
2997 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
2998 // Now that something has committed, we don't need to track whether the
2999 // initial page has been accessed.
3000 has_accessed_initial_document_ = false;
3002 // If we navigate off the page, close all JavaScript dialogs.
3003 if (!details.is_in_page)
3004 CancelActiveAndPendingDialogs();
3006 // Notify observers about navigation.
3007 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3008 DidNavigateAnyFrame(render_frame_host, details, params));
3011 void WebContentsImpl::SetMainFrameMimeType(const std::string& mime_type) {
3012 contents_mime_type_ = mime_type;
3015 bool WebContentsImpl::CanOverscrollContent() const {
3016 // Disable overscroll when touch emulation is on. See crbug.com/369938.
3017 if (force_disable_overscroll_content_)
3018 return false;
3020 if (delegate_)
3021 return delegate_->CanOverscrollContent();
3023 return false;
3026 void WebContentsImpl::OnThemeColorChanged(SkColor theme_color) {
3027 // Update the theme color. This is to be published to observers after the
3028 // first visually non-empty paint.
3029 theme_color_ = theme_color;
3031 if (did_first_visually_non_empty_paint_ &&
3032 last_sent_theme_color_ != theme_color_) {
3033 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3034 DidChangeThemeColor(theme_color_));
3035 last_sent_theme_color_ = theme_color_;
3039 void WebContentsImpl::OnDidLoadResourceFromMemoryCache(
3040 const GURL& url,
3041 const std::string& security_info,
3042 const std::string& http_method,
3043 const std::string& mime_type,
3044 ResourceType resource_type) {
3045 SSLStatus status;
3046 if (!DeserializeSecurityInfo(security_info, &status)) {
3047 bad_message::ReceivedBadMessage(
3048 GetRenderProcessHost(),
3049 bad_message::WC_MEMORY_CACHE_RESOURCE_BAD_SECURITY_INFO);
3050 return;
3053 // Send out a notification that we loaded a resource from our memory cache.
3054 // TODO(alcutter,eranm): Pass signed_certificate_timestamp_ids into details.
3055 LoadFromMemoryCacheDetails details(
3056 url, GetRenderProcessHost()->GetID(), status.cert_id, status.cert_status,
3057 http_method, mime_type, resource_type);
3059 controller_.ssl_manager()->DidLoadFromMemoryCache(details);
3061 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3062 DidLoadResourceFromMemoryCache(details));
3064 if (url.is_valid() && url.SchemeIsHTTPOrHTTPS()) {
3065 scoped_refptr<net::URLRequestContextGetter> request_context(
3066 resource_type == RESOURCE_TYPE_MEDIA ?
3067 GetBrowserContext()->GetMediaRequestContextForRenderProcess(
3068 GetRenderProcessHost()->GetID()) :
3069 GetBrowserContext()->GetRequestContextForRenderProcess(
3070 GetRenderProcessHost()->GetID()));
3071 BrowserThread::PostTask(
3072 BrowserThread::IO,
3073 FROM_HERE,
3074 base::Bind(&NotifyCacheOnIO, request_context, url, http_method));
3078 void WebContentsImpl::OnDidDisplayInsecureContent() {
3079 RecordAction(base::UserMetricsAction("SSL.DisplayedInsecureContent"));
3080 displayed_insecure_content_ = true;
3081 SSLManager::NotifySSLInternalStateChanged(
3082 GetController().GetBrowserContext());
3085 void WebContentsImpl::OnDidRunInsecureContent(
3086 const std::string& security_origin, const GURL& target_url) {
3087 LOG(WARNING) << security_origin << " ran insecure content from "
3088 << target_url.possibly_invalid_spec();
3089 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
3090 if (base::EndsWith(security_origin, kDotGoogleDotCom,
3091 base::CompareCase::INSENSITIVE_ASCII))
3092 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
3093 controller_.ssl_manager()->DidRunInsecureContent(security_origin);
3094 displayed_insecure_content_ = true;
3095 SSLManager::NotifySSLInternalStateChanged(
3096 GetController().GetBrowserContext());
3099 void WebContentsImpl::OnDocumentLoadedInFrame() {
3100 if (!HasValidFrameSource())
3101 return;
3103 RenderFrameHostImpl* rfh =
3104 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
3105 FOR_EACH_OBSERVER(
3106 WebContentsObserver, observers_, DocumentLoadedInFrame(rfh));
3109 void WebContentsImpl::OnDidFinishLoad(const GURL& url) {
3110 if (!HasValidFrameSource())
3111 return;
3113 GURL validated_url(url);
3114 RenderProcessHost* render_process_host =
3115 render_frame_message_source_->GetProcess();
3116 render_process_host->FilterURL(false, &validated_url);
3118 RenderFrameHostImpl* rfh =
3119 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
3120 FOR_EACH_OBSERVER(
3121 WebContentsObserver, observers_, DidFinishLoad(rfh, validated_url));
3124 void WebContentsImpl::OnGoToEntryAtOffset(int offset) {
3125 if (!delegate_ || delegate_->OnGoToEntryOffset(offset))
3126 controller_.GoToOffset(offset);
3129 void WebContentsImpl::OnUpdateZoomLimits(int minimum_percent,
3130 int maximum_percent) {
3131 minimum_zoom_percent_ = minimum_percent;
3132 maximum_zoom_percent_ = maximum_percent;
3135 void WebContentsImpl::OnEnumerateDirectory(int request_id,
3136 const base::FilePath& path) {
3137 if (!delegate_)
3138 return;
3140 ChildProcessSecurityPolicyImpl* policy =
3141 ChildProcessSecurityPolicyImpl::GetInstance();
3142 if (policy->CanReadFile(GetRenderProcessHost()->GetID(), path))
3143 delegate_->EnumerateDirectory(this, request_id, path);
3146 void WebContentsImpl::OnRegisterProtocolHandler(const std::string& protocol,
3147 const GURL& url,
3148 const base::string16& title,
3149 bool user_gesture) {
3150 if (!delegate_)
3151 return;
3153 ChildProcessSecurityPolicyImpl* policy =
3154 ChildProcessSecurityPolicyImpl::GetInstance();
3155 if (policy->IsPseudoScheme(protocol))
3156 return;
3158 delegate_->RegisterProtocolHandler(this, protocol, url, user_gesture);
3161 void WebContentsImpl::OnUnregisterProtocolHandler(const std::string& protocol,
3162 const GURL& url,
3163 bool user_gesture) {
3164 if (!delegate_)
3165 return;
3167 ChildProcessSecurityPolicyImpl* policy =
3168 ChildProcessSecurityPolicyImpl::GetInstance();
3169 if (policy->IsPseudoScheme(protocol))
3170 return;
3172 delegate_->UnregisterProtocolHandler(this, protocol, url, user_gesture);
3175 void WebContentsImpl::OnFindReply(int request_id,
3176 int number_of_matches,
3177 const gfx::Rect& selection_rect,
3178 int active_match_ordinal,
3179 bool final_update) {
3180 if (delegate_) {
3181 delegate_->FindReply(this, request_id, number_of_matches, selection_rect,
3182 active_match_ordinal, final_update);
3186 #if defined(OS_ANDROID)
3187 void WebContentsImpl::OnFindMatchRectsReply(
3188 int version,
3189 const std::vector<gfx::RectF>& rects,
3190 const gfx::RectF& active_rect) {
3191 if (delegate_)
3192 delegate_->FindMatchRectsReply(this, version, rects, active_rect);
3195 void WebContentsImpl::OnOpenDateTimeDialog(
3196 const ViewHostMsg_DateTimeDialogValue_Params& value) {
3197 date_time_chooser_->ShowDialog(GetTopLevelNativeWindow(),
3198 GetRenderViewHost(),
3199 value.dialog_type,
3200 value.dialog_value,
3201 value.minimum,
3202 value.maximum,
3203 value.step,
3204 value.suggestions);
3206 #endif
3208 void WebContentsImpl::OnDomOperationResponse(const std::string& json_string,
3209 int automation_id) {
3210 DomOperationNotificationDetails details(json_string, automation_id);
3211 NotificationService::current()->Notify(
3212 NOTIFICATION_DOM_OPERATION_RESPONSE,
3213 Source<WebContents>(this),
3214 Details<DomOperationNotificationDetails>(&details));
3217 void WebContentsImpl::OnAppCacheAccessed(const GURL& manifest_url,
3218 bool blocked_by_policy) {
3219 // Notify observers about navigation.
3220 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3221 AppCacheAccessed(manifest_url, blocked_by_policy));
3224 void WebContentsImpl::OnOpenColorChooser(
3225 int color_chooser_id,
3226 SkColor color,
3227 const std::vector<ColorSuggestion>& suggestions) {
3228 if (!HasValidFrameSource())
3229 return;
3231 ColorChooser* new_color_chooser = delegate_ ?
3232 delegate_->OpenColorChooser(this, color, suggestions) :
3233 NULL;
3234 if (!new_color_chooser)
3235 return;
3236 if (color_chooser_info_.get())
3237 color_chooser_info_->chooser->End();
3239 color_chooser_info_.reset(new ColorChooserInfo(
3240 render_frame_message_source_->GetProcess()->GetID(),
3241 render_frame_message_source_->GetRoutingID(),
3242 new_color_chooser,
3243 color_chooser_id));
3246 void WebContentsImpl::OnEndColorChooser(int color_chooser_id) {
3247 if (color_chooser_info_ &&
3248 color_chooser_id == color_chooser_info_->identifier)
3249 color_chooser_info_->chooser->End();
3252 void WebContentsImpl::OnSetSelectedColorInColorChooser(int color_chooser_id,
3253 SkColor color) {
3254 if (color_chooser_info_ &&
3255 color_chooser_id == color_chooser_info_->identifier)
3256 color_chooser_info_->chooser->SetSelectedColor(color);
3259 // This exists for render views that don't have a WebUI, but do have WebUI
3260 // bindings enabled.
3261 void WebContentsImpl::OnWebUISend(const GURL& source_url,
3262 const std::string& name,
3263 const base::ListValue& args) {
3264 if (delegate_)
3265 delegate_->WebUISend(this, source_url, name, args);
3268 #if defined(ENABLE_PLUGINS)
3269 void WebContentsImpl::OnPepperInstanceCreated() {
3270 FOR_EACH_OBSERVER(WebContentsObserver, observers_, PepperInstanceCreated());
3273 void WebContentsImpl::OnPepperInstanceDeleted() {
3274 FOR_EACH_OBSERVER(WebContentsObserver, observers_, PepperInstanceDeleted());
3277 void WebContentsImpl::OnPepperPluginHung(int plugin_child_id,
3278 const base::FilePath& path,
3279 bool is_hung) {
3280 UMA_HISTOGRAM_COUNTS("Pepper.PluginHung", 1);
3282 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3283 PluginHungStatusChanged(plugin_child_id, path, is_hung));
3286 void WebContentsImpl::OnPluginCrashed(const base::FilePath& plugin_path,
3287 base::ProcessId plugin_pid) {
3288 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3289 PluginCrashed(plugin_path, plugin_pid));
3292 void WebContentsImpl::OnRequestPpapiBrokerPermission(
3293 int routing_id,
3294 const GURL& url,
3295 const base::FilePath& plugin_path) {
3296 if (!delegate_) {
3297 OnPpapiBrokerPermissionResult(routing_id, false);
3298 return;
3301 if (!delegate_->RequestPpapiBrokerPermission(
3302 this, url, plugin_path,
3303 base::Bind(&WebContentsImpl::OnPpapiBrokerPermissionResult,
3304 base::Unretained(this), routing_id))) {
3305 NOTIMPLEMENTED();
3306 OnPpapiBrokerPermissionResult(routing_id, false);
3310 void WebContentsImpl::OnPpapiBrokerPermissionResult(int routing_id,
3311 bool result) {
3312 Send(new ViewMsg_PpapiBrokerPermissionResult(routing_id, result));
3315 void WebContentsImpl::OnBrowserPluginMessage(RenderFrameHost* render_frame_host,
3316 const IPC::Message& message) {
3317 CHECK(!browser_plugin_embedder_.get());
3318 CreateBrowserPluginEmbedderIfNecessary();
3319 browser_plugin_embedder_->OnMessageReceived(message, render_frame_host);
3321 #endif // defined(ENABLE_PLUGINS)
3323 void WebContentsImpl::OnUpdateFaviconURL(
3324 const std::vector<FaviconURL>& candidates) {
3325 // We get updated favicon URLs after the page stops loading. If a cross-site
3326 // navigation occurs while a page is still loading, the initial page
3327 // may stop loading and send us updated favicon URLs after the navigation
3328 // for the new page has committed.
3329 RenderViewHostImpl* rvhi =
3330 static_cast<RenderViewHostImpl*>(render_view_message_source_);
3331 if (!rvhi->is_active())
3332 return;
3334 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3335 DidUpdateFaviconURL(candidates));
3338 void WebContentsImpl::CreateAudioPowerSaveBlocker() {
3339 DCHECK(!audio_power_save_blocker_);
3340 audio_power_save_blocker_ = PowerSaveBlocker::Create(
3341 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension,
3342 PowerSaveBlocker::kReasonAudioPlayback, "Playing audio");
3345 void WebContentsImpl::CreateVideoPowerSaveBlocker() {
3346 DCHECK(!video_power_save_blocker_);
3347 DCHECK(!active_video_players_.empty());
3348 video_power_save_blocker_ = PowerSaveBlocker::Create(
3349 PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep,
3350 PowerSaveBlocker::kReasonVideoPlayback, "Playing video");
3351 #if defined(OS_ANDROID)
3352 static_cast<PowerSaveBlockerImpl*>(video_power_save_blocker_.get())
3353 ->InitDisplaySleepBlocker(this);
3354 #endif
3357 void WebContentsImpl::MaybeReleasePowerSaveBlockers() {
3358 // If there are no more audio players and we don't have audio stream
3359 // monitoring, release the audio power save blocker here instead of during
3360 // NotifyNavigationStateChanged().
3361 if (active_audio_players_.empty() &&
3362 !AudioStreamMonitor::monitoring_available()) {
3363 audio_power_save_blocker_.reset();
3366 // If there are no more video players, clear the video power save blocker.
3367 if (active_video_players_.empty())
3368 video_power_save_blocker_.reset();
3371 void WebContentsImpl::OnMediaPlayingNotification(int64 player_cookie,
3372 bool has_video,
3373 bool has_audio,
3374 bool is_remote) {
3375 // Ignore the videos playing remotely and don't hold the wake lock for the
3376 // screen.
3377 if (is_remote) return;
3379 if (has_audio) {
3380 AddMediaPlayerEntry(player_cookie, &active_audio_players_);
3382 // If we don't have audio stream monitoring, allocate the audio power save
3383 // blocker here instead of during NotifyNavigationStateChanged().
3384 if (!audio_power_save_blocker_ &&
3385 !AudioStreamMonitor::monitoring_available()) {
3386 CreateAudioPowerSaveBlocker();
3390 if (has_video) {
3391 AddMediaPlayerEntry(player_cookie, &active_video_players_);
3393 // If we're not hidden and have just created a player, create a blocker.
3394 if (!video_power_save_blocker_ && !IsHidden())
3395 CreateVideoPowerSaveBlocker();
3398 FOR_EACH_OBSERVER(WebContentsObserver, observers_, MediaStartedPlaying());
3401 void WebContentsImpl::OnMediaPausedNotification(int64 player_cookie) {
3402 RemoveMediaPlayerEntry(player_cookie, &active_audio_players_);
3403 RemoveMediaPlayerEntry(player_cookie, &active_video_players_);
3404 MaybeReleasePowerSaveBlockers();
3406 FOR_EACH_OBSERVER(WebContentsObserver, observers_, MediaPaused());
3409 #if defined(OS_ANDROID)
3411 void WebContentsImpl::OnMediaSessionStateChanged() {
3412 MediaSession* session = MediaSession::Get(this);
3413 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3414 MediaSessionStateChanged(session->IsControllable(),
3415 session->IsSuspended()));
3418 void WebContentsImpl::ResumeMediaSession() {
3419 MediaSession::Get(this)->Resume();
3422 void WebContentsImpl::SuspendMediaSession() {
3423 MediaSession::Get(this)->Suspend();
3426 void WebContentsImpl::StopMediaSession() {
3427 MediaSession::Get(this)->Stop();
3430 #endif // defined(OS_ANDROID)
3432 void WebContentsImpl::OnFirstVisuallyNonEmptyPaint() {
3433 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3434 DidFirstVisuallyNonEmptyPaint());
3436 did_first_visually_non_empty_paint_ = true;
3438 if (theme_color_ != last_sent_theme_color_) {
3439 // Theme color should have updated by now if there was one.
3440 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3441 DidChangeThemeColor(theme_color_));
3442 last_sent_theme_color_ = theme_color_;
3446 void WebContentsImpl::DidChangeVisibleSSLState() {
3447 if (delegate_) {
3448 delegate_->VisibleSSLStateChanged(this);
3450 SecurityStyleExplanations security_style_explanations;
3451 SecurityStyle security_style =
3452 delegate_->GetSecurityStyle(this, &security_style_explanations);
3453 FOR_EACH_OBSERVER(
3454 WebContentsObserver, observers_,
3455 SecurityStyleChanged(security_style, security_style_explanations));
3459 void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
3460 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3461 BeforeFormRepostWarningShow());
3464 void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
3465 Activate();
3466 if (delegate_)
3467 delegate_->ShowRepostFormWarningDialog(this);
3470 bool WebContentsImpl::HasAccessedInitialDocument() {
3471 return has_accessed_initial_document_;
3474 // Notifies the RenderWidgetHost instance about the fact that the page is
3475 // loading, or done loading.
3476 void WebContentsImpl::SetIsLoading(bool is_loading,
3477 bool to_different_document,
3478 LoadNotificationDetails* details) {
3479 if (is_loading == is_loading_)
3480 return;
3482 if (!is_loading) {
3483 load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
3484 base::string16());
3485 load_state_host_.clear();
3486 upload_size_ = 0;
3487 upload_position_ = 0;
3490 GetRenderManager()->SetIsLoading(is_loading);
3492 is_loading_ = is_loading;
3493 waiting_for_response_ = is_loading;
3494 is_load_to_different_document_ = to_different_document;
3496 if (delegate_)
3497 delegate_->LoadingStateChanged(this, to_different_document);
3498 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
3500 std::string url = (details ? details->url.possibly_invalid_spec() : "NULL");
3501 if (is_loading) {
3502 TRACE_EVENT_ASYNC_BEGIN1("browser,navigation", "WebContentsImpl Loading",
3503 this, "URL", url);
3504 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidStartLoading());
3505 } else {
3506 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
3507 this, "URL", url);
3508 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidStopLoading());
3511 // TODO(avi): Remove. http://crbug.com/170921
3512 int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
3513 NotificationDetails det = NotificationService::NoDetails();
3514 if (details)
3515 det = Details<LoadNotificationDetails>(details);
3516 NotificationService::current()->Notify(
3517 type, Source<NavigationController>(&controller_), det);
3520 void WebContentsImpl::UpdateMaxPageIDIfNecessary(RenderViewHost* rvh) {
3521 // If we are creating a RVH for a restored controller, then we need to make
3522 // sure the RenderView starts with a next_page_id_ larger than the number
3523 // of restored entries. This must be called before the RenderView starts
3524 // navigating (to avoid a race between the browser updating max_page_id and
3525 // the renderer updating next_page_id_). Because of this, we only call this
3526 // from CreateRenderView and allow that to notify the RenderView for us.
3527 int max_restored_page_id = controller_.GetMaxRestoredPageID();
3528 if (max_restored_page_id >
3529 GetMaxPageIDForSiteInstance(rvh->GetSiteInstance()))
3530 UpdateMaxPageIDForSiteInstance(rvh->GetSiteInstance(),
3531 max_restored_page_id);
3534 bool WebContentsImpl::UpdateTitleForEntry(NavigationEntryImpl* entry,
3535 const base::string16& title) {
3536 // For file URLs without a title, use the pathname instead. In the case of a
3537 // synthesized title, we don't want the update to count toward the "one set
3538 // per page of the title to history."
3539 base::string16 final_title;
3540 bool explicit_set;
3541 if (entry && entry->GetURL().SchemeIsFile() && title.empty()) {
3542 final_title = base::UTF8ToUTF16(entry->GetURL().ExtractFileName());
3543 explicit_set = false; // Don't count synthetic titles toward the set limit.
3544 } else {
3545 base::TrimWhitespace(title, base::TRIM_ALL, &final_title);
3546 explicit_set = true;
3549 // If a page is created via window.open and never navigated,
3550 // there will be no navigation entry. In this situation,
3551 // |page_title_when_no_navigation_entry_| will be used for page title.
3552 if (entry) {
3553 if (final_title == entry->GetTitle())
3554 return false; // Nothing changed, don't bother.
3556 entry->SetTitle(final_title);
3557 } else {
3558 if (page_title_when_no_navigation_entry_ == final_title)
3559 return false; // Nothing changed, don't bother.
3561 page_title_when_no_navigation_entry_ = final_title;
3564 // Lastly, set the title for the view.
3565 view_->SetPageTitle(final_title);
3567 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3568 TitleWasSet(entry, explicit_set));
3570 return true;
3573 void WebContentsImpl::SendChangeLoadProgress() {
3574 loading_last_progress_update_ = base::TimeTicks::Now();
3575 if (delegate_)
3576 delegate_->LoadProgressChanged(this, frame_tree_.load_progress());
3579 void WebContentsImpl::ResetLoadProgressState() {
3580 frame_tree_.ResetLoadProgress();
3581 loading_weak_factory_.InvalidateWeakPtrs();
3582 loading_last_progress_update_ = base::TimeTicks();
3585 void WebContentsImpl::NotifyViewSwapped(RenderViewHost* old_host,
3586 RenderViewHost* new_host) {
3587 // After sending out a swap notification, we need to send a disconnect
3588 // notification so that clients that pick up a pointer to |this| can NULL the
3589 // pointer. See Bug 1230284.
3590 notify_disconnection_ = true;
3591 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3592 RenderViewHostChanged(old_host, new_host));
3594 // Ensure that the associated embedder gets cleared after a RenderViewHost
3595 // gets swapped, so we don't reuse the same embedder next time a
3596 // RenderViewHost is attached to this WebContents.
3597 RemoveBrowserPluginEmbedder();
3600 void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost* old_host,
3601 RenderFrameHost* new_host) {
3602 FOR_EACH_OBSERVER(WebContentsObserver,
3603 observers_,
3604 RenderFrameHostChanged(old_host, new_host));
3607 // TODO(avi): Remove this entire function because this notification is already
3608 // covered by two observer functions. http://crbug.com/170921
3609 void WebContentsImpl::NotifyDisconnected() {
3610 if (!notify_disconnection_)
3611 return;
3613 notify_disconnection_ = false;
3614 NotificationService::current()->Notify(
3615 NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
3616 Source<WebContents>(this),
3617 NotificationService::NoDetails());
3620 void WebContentsImpl::NotifyNavigationEntryCommitted(
3621 const LoadCommittedDetails& load_details) {
3622 FOR_EACH_OBSERVER(
3623 WebContentsObserver, observers_, NavigationEntryCommitted(load_details));
3626 bool WebContentsImpl::OnMessageReceived(RenderFrameHost* render_frame_host,
3627 const IPC::Message& message) {
3628 return OnMessageReceived(NULL, render_frame_host, message);
3631 const GURL& WebContentsImpl::GetMainFrameLastCommittedURL() const {
3632 return GetLastCommittedURL();
3635 void WebContentsImpl::RenderFrameCreated(RenderFrameHost* render_frame_host) {
3636 // Note this is only for subframes, the notification for the main frame
3637 // happens in RenderViewCreated.
3638 FOR_EACH_OBSERVER(WebContentsObserver,
3639 observers_,
3640 RenderFrameCreated(render_frame_host));
3641 SetAccessibilityModeOnFrame(accessibility_mode_, render_frame_host);
3644 void WebContentsImpl::RenderFrameDeleted(RenderFrameHost* render_frame_host) {
3645 ClearPowerSaveBlockers(render_frame_host);
3646 FOR_EACH_OBSERVER(WebContentsObserver,
3647 observers_,
3648 RenderFrameDeleted(render_frame_host));
3651 void WebContentsImpl::ShowContextMenu(RenderFrameHost* render_frame_host,
3652 const ContextMenuParams& params) {
3653 ContextMenuParams context_menu_params(params);
3654 // Allow WebContentsDelegates to handle the context menu operation first.
3655 if (delegate_ && delegate_->HandleContextMenu(context_menu_params))
3656 return;
3658 render_view_host_delegate_view_->ShowContextMenu(render_frame_host,
3659 context_menu_params);
3662 void WebContentsImpl::RunJavaScriptMessage(
3663 RenderFrameHost* render_frame_host,
3664 const base::string16& message,
3665 const base::string16& default_prompt,
3666 const GURL& frame_url,
3667 JavaScriptMessageType javascript_message_type,
3668 IPC::Message* reply_msg) {
3669 // Suppress JavaScript dialogs when requested. Also suppress messages when
3670 // showing an interstitial as it's shown over the previous page and we don't
3671 // want the hidden page's dialogs to interfere with the interstitial.
3672 bool suppress_this_message =
3673 static_cast<RenderFrameHostImpl*>(render_frame_host)->is_swapped_out() ||
3674 ShowingInterstitialPage() || !delegate_ ||
3675 delegate_->ShouldSuppressDialogs(this) ||
3676 !delegate_->GetJavaScriptDialogManager(this);
3678 if (!suppress_this_message) {
3679 std::string accept_lang = GetContentClient()->browser()->
3680 GetAcceptLangs(GetBrowserContext());
3681 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
3682 dialog_manager_->RunJavaScriptDialog(
3683 this, frame_url, accept_lang, javascript_message_type, message,
3684 default_prompt,
3685 base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
3686 render_frame_host->GetProcess()->GetID(),
3687 render_frame_host->GetRoutingID(), reply_msg, false),
3688 &suppress_this_message);
3691 if (suppress_this_message) {
3692 // If we are suppressing messages, just reply as if the user immediately
3693 // pressed "Cancel", passing true to |dialog_was_suppressed|.
3694 OnDialogClosed(render_frame_host->GetProcess()->GetID(),
3695 render_frame_host->GetRoutingID(), reply_msg,
3696 true, false, base::string16());
3699 // OnDialogClosed (two lines up) may have caused deletion of this object (see
3700 // http://crbug.com/288961 ). The only safe thing to do here is return.
3703 void WebContentsImpl::RunBeforeUnloadConfirm(
3704 RenderFrameHost* render_frame_host,
3705 const base::string16& message,
3706 bool is_reload,
3707 IPC::Message* reply_msg) {
3708 RenderFrameHostImpl* rfhi =
3709 static_cast<RenderFrameHostImpl*>(render_frame_host);
3710 if (delegate_)
3711 delegate_->WillRunBeforeUnloadConfirm();
3713 bool suppress_this_message =
3714 rfhi->rfh_state() != RenderFrameHostImpl::STATE_DEFAULT ||
3715 ShowingInterstitialPage() || !delegate_ ||
3716 delegate_->ShouldSuppressDialogs(this) ||
3717 !delegate_->GetJavaScriptDialogManager(this);
3718 if (suppress_this_message) {
3719 rfhi->JavaScriptDialogClosed(reply_msg, true, base::string16(), true);
3720 return;
3723 is_showing_before_unload_dialog_ = true;
3724 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
3725 dialog_manager_->RunBeforeUnloadDialog(
3726 this, message, is_reload,
3727 base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
3728 render_frame_host->GetProcess()->GetID(),
3729 render_frame_host->GetRoutingID(), reply_msg,
3730 false));
3733 WebContents* WebContentsImpl::GetAsWebContents() {
3734 return this;
3737 bool WebContentsImpl::IsNeverVisible() {
3738 if (!delegate_)
3739 return false;
3740 return delegate_->IsNeverVisible(this);
3743 #if defined(OS_WIN)
3744 gfx::NativeViewAccessible WebContentsImpl::GetParentNativeViewAccessible() {
3745 return accessible_parent_;
3747 #endif
3749 RenderViewHostDelegateView* WebContentsImpl::GetDelegateView() {
3750 return render_view_host_delegate_view_;
3753 RendererPreferences WebContentsImpl::GetRendererPrefs(
3754 BrowserContext* browser_context) const {
3755 return renderer_preferences_;
3758 gfx::Rect WebContentsImpl::GetRootWindowResizerRect() const {
3759 if (delegate_)
3760 return delegate_->GetRootWindowResizerRect();
3761 return gfx::Rect();
3764 void WebContentsImpl::RemoveBrowserPluginEmbedder() {
3765 if (browser_plugin_embedder_)
3766 browser_plugin_embedder_.reset();
3769 void WebContentsImpl::RenderViewCreated(RenderViewHost* render_view_host) {
3770 // Don't send notifications if we are just creating a swapped-out RVH for
3771 // the opener chain. These won't be used for view-source or WebUI, so it's
3772 // ok to return early.
3773 if (!static_cast<RenderViewHostImpl*>(render_view_host)->is_active())
3774 return;
3776 if (delegate_)
3777 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
3779 NotificationService::current()->Notify(
3780 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
3781 Source<WebContents>(this),
3782 Details<RenderViewHost>(render_view_host));
3784 // When we're creating views, we're still doing initial setup, so we always
3785 // use the pending Web UI rather than any possibly existing committed one.
3786 if (GetRenderManager()->pending_web_ui())
3787 GetRenderManager()->pending_web_ui()->RenderViewCreated(render_view_host);
3789 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
3790 switches::kEnableBrowserSideNavigation) &&
3791 GetRenderManager()->speculative_web_ui()) {
3792 GetRenderManager()->speculative_web_ui()->RenderViewCreated(
3793 render_view_host);
3796 NavigationEntry* entry = controller_.GetPendingEntry();
3797 if (entry && entry->IsViewSourceMode()) {
3798 // Put the renderer in view source mode.
3799 render_view_host->Send(
3800 new ViewMsg_EnableViewSourceMode(render_view_host->GetRoutingID()));
3803 view_->RenderViewCreated(render_view_host);
3805 FOR_EACH_OBSERVER(
3806 WebContentsObserver, observers_, RenderViewCreated(render_view_host));
3809 void WebContentsImpl::RenderViewReady(RenderViewHost* rvh) {
3810 if (rvh != GetRenderViewHost()) {
3811 // Don't notify the world, since this came from a renderer in the
3812 // background.
3813 return;
3816 notify_disconnection_ = true;
3817 // TODO(avi): Remove. http://crbug.com/170921
3818 NotificationService::current()->Notify(
3819 NOTIFICATION_WEB_CONTENTS_CONNECTED,
3820 Source<WebContents>(this),
3821 NotificationService::NoDetails());
3823 bool was_crashed = IsCrashed();
3824 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
3826 // Restore the focus to the tab (otherwise the focus will be on the top
3827 // window).
3828 if (was_crashed && !FocusLocationBarByDefault() &&
3829 (!delegate_ || delegate_->ShouldFocusPageAfterCrash())) {
3830 view_->Focus();
3833 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewReady());
3836 void WebContentsImpl::RenderViewTerminated(RenderViewHost* rvh,
3837 base::TerminationStatus status,
3838 int error_code) {
3839 if (rvh != GetRenderViewHost()) {
3840 // The pending page's RenderViewHost is gone.
3841 return;
3844 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
3845 // renderer may not have made a clean exit.
3846 if (IsFullscreenForCurrentTab())
3847 ExitFullscreenMode();
3849 // Cancel any visible dialogs so they are not left dangling over the sad tab.
3850 CancelActiveAndPendingDialogs();
3852 if (delegate_)
3853 delegate_->HideValidationMessage(this);
3855 SetIsLoading(false, true, nullptr);
3856 NotifyDisconnected();
3857 SetIsCrashed(status, error_code);
3859 // Reset the loading progress. TODO(avi): What does it mean to have a
3860 // "renderer crash" when there is more than one renderer process serving a
3861 // webpage? Once this function is called at a more granular frame level, we
3862 // probably will need to more granularly reset the state here.
3863 ResetLoadProgressState();
3865 FOR_EACH_OBSERVER(WebContentsObserver,
3866 observers_,
3867 RenderProcessGone(GetCrashedStatus()));
3870 void WebContentsImpl::RenderViewDeleted(RenderViewHost* rvh) {
3871 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewDeleted(rvh));
3874 void WebContentsImpl::UpdateState(RenderViewHost* rvh,
3875 int32 page_id,
3876 const PageState& page_state) {
3877 // Ensure that this state update comes from a RenderViewHost that belongs to
3878 // this WebContents.
3879 // TODO(nasko): This should go through RenderFrameHost.
3880 if (rvh->GetDelegate()->GetAsWebContents() != this)
3881 return;
3883 // We must be prepared to handle state updates for any page. They occur
3884 // when the user is scrolling and entering form data, as well as when we're
3885 // leaving a page, in which case our state may have already been moved to
3886 // the next page. The navigation controller will look up the appropriate
3887 // NavigationEntry and update it when it is notified via the delegate.
3888 RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(rvh);
3889 NavigationEntryImpl* entry = controller_.GetEntryWithPageID(
3890 rvhi->GetSiteInstance(), page_id);
3891 if (!entry)
3892 return;
3894 NavigationEntryImpl* new_entry = controller_.GetEntryWithUniqueID(
3895 rvhi->nav_entry_id());
3897 if (SiteIsolationPolicy::UseSubframeNavigationEntries()) {
3898 // TODO(creis): We can't properly update state for cross-process subframes
3899 // until PageState is decomposed into FrameStates. Until then, use the new
3900 // method.
3901 entry = new_entry;
3902 } else {
3903 DCHECK_EQ(entry, new_entry);
3906 if (page_state == entry->GetPageState())
3907 return; // Nothing to update.
3908 entry->SetPageState(page_state);
3909 controller_.NotifyEntryChanged(entry);
3912 void WebContentsImpl::UpdateTargetURL(RenderViewHost* render_view_host,
3913 const GURL& url) {
3914 if (fullscreen_widget_routing_id_ != MSG_ROUTING_NONE) {
3915 // If we're fullscreen only update the url if it's from the fullscreen
3916 // renderer.
3917 RenderWidgetHostView* fs = GetFullscreenRenderWidgetHostView();
3918 if (fs && fs->GetRenderWidgetHost() != render_view_host)
3919 return;
3921 if (delegate_)
3922 delegate_->UpdateTargetURL(this, url);
3925 void WebContentsImpl::Close(RenderViewHost* rvh) {
3926 #if defined(OS_MACOSX)
3927 // The UI may be in an event-tracking loop, such as between the
3928 // mouse-down and mouse-up in text selection or a button click.
3929 // Defer the close until after tracking is complete, so that we
3930 // don't free objects out from under the UI.
3931 // TODO(shess): This could get more fine-grained. For instance,
3932 // closing a tab in another window while selecting text in the
3933 // current window's Omnibox should be just fine.
3934 if (view_->IsEventTracking()) {
3935 view_->CloseTabAfterEventTracking();
3936 return;
3938 #endif
3940 // Ignore this if it comes from a RenderViewHost that we aren't showing.
3941 if (delegate_ && rvh == GetRenderViewHost())
3942 delegate_->CloseContents(this);
3945 void WebContentsImpl::SwappedOut(RenderFrameHost* rfh) {
3946 if (delegate_ && rfh->GetRenderViewHost() == GetRenderViewHost())
3947 delegate_->SwappedOut(this);
3950 void WebContentsImpl::RequestMove(const gfx::Rect& new_bounds) {
3951 if (delegate_ && delegate_->IsPopupOrPanel(this))
3952 delegate_->MoveContents(this, new_bounds);
3955 void WebContentsImpl::DidStartLoading(FrameTreeNode* frame_tree_node,
3956 bool to_different_document) {
3957 SetIsLoading(true, to_different_document, nullptr);
3959 // Notify accessibility that the user is navigating away from the
3960 // current document.
3962 // TODO(dmazzoni): do this using a WebContentsObserver.
3963 BrowserAccessibilityManager* manager =
3964 frame_tree_node->current_frame_host()->browser_accessibility_manager();
3965 if (manager)
3966 manager->UserIsNavigatingAway();
3969 void WebContentsImpl::DidStopLoading() {
3970 scoped_ptr<LoadNotificationDetails> details;
3972 // Use the last committed entry rather than the active one, in case a
3973 // pending entry has been created.
3974 NavigationEntry* entry = controller_.GetLastCommittedEntry();
3975 Navigator* navigator = frame_tree_.root()->navigator();
3977 // An entry may not exist for a stop when loading an initial blank page or
3978 // if an iframe injected by script into a blank page finishes loading.
3979 if (entry) {
3980 base::TimeDelta elapsed =
3981 base::TimeTicks::Now() - navigator->GetCurrentLoadStart();
3983 details.reset(new LoadNotificationDetails(
3984 entry->GetVirtualURL(),
3985 entry->GetTransitionType(),
3986 elapsed,
3987 &controller_,
3988 controller_.GetCurrentEntryIndex()));
3991 SetIsLoading(false, true, details.get());
3994 void WebContentsImpl::DidChangeLoadProgress() {
3995 double load_progress = frame_tree_.load_progress();
3997 // The delegate is notified immediately for the first and last updates. Also,
3998 // since the message loop may be pretty busy when a page is loaded, it might
3999 // not execute a posted task in a timely manner so the progress report is sent
4000 // immediately if enough time has passed.
4001 base::TimeDelta min_delay =
4002 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS);
4003 bool delay_elapsed = loading_last_progress_update_.is_null() ||
4004 base::TimeTicks::Now() - loading_last_progress_update_ > min_delay;
4006 if (load_progress == 0.0 || load_progress == 1.0 || delay_elapsed) {
4007 // If there is a pending task to send progress, it is now obsolete.
4008 loading_weak_factory_.InvalidateWeakPtrs();
4010 // Notify the load progress change.
4011 SendChangeLoadProgress();
4013 // Clean-up the states if needed.
4014 if (load_progress == 1.0)
4015 ResetLoadProgressState();
4016 return;
4019 if (loading_weak_factory_.HasWeakPtrs())
4020 return;
4022 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
4023 FROM_HERE, base::Bind(&WebContentsImpl::SendChangeLoadProgress,
4024 loading_weak_factory_.GetWeakPtr()),
4025 min_delay);
4028 void WebContentsImpl::DidCancelLoading() {
4029 controller_.DiscardNonCommittedEntries();
4031 // Update the URL display.
4032 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
4035 void WebContentsImpl::DidAccessInitialDocument() {
4036 has_accessed_initial_document_ = true;
4038 // We may have left a failed browser-initiated navigation in the address bar
4039 // to let the user edit it and try again. Clear it now that content might
4040 // show up underneath it.
4041 if (!IsLoading() && controller_.GetPendingEntry())
4042 controller_.DiscardPendingEntry(false);
4044 // Update the URL display.
4045 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
4048 void WebContentsImpl::DidChangeName(RenderFrameHost* render_frame_host,
4049 const std::string& name) {
4050 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4051 FrameNameChanged(render_frame_host, name));
4054 void WebContentsImpl::DocumentOnLoadCompleted(
4055 RenderFrameHost* render_frame_host) {
4056 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4057 DocumentOnLoadCompletedInMainFrame());
4059 // TODO(avi): Remove. http://crbug.com/170921
4060 NotificationService::current()->Notify(
4061 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
4062 Source<WebContents>(this),
4063 NotificationService::NoDetails());
4066 void WebContentsImpl::UpdateTitle(RenderFrameHost* render_frame_host,
4067 int32 page_id,
4068 const base::string16& title,
4069 base::i18n::TextDirection title_direction) {
4070 // If we have a title, that's a pretty good indication that we've started
4071 // getting useful data.
4072 SetNotWaitingForResponse();
4074 // Try to find the navigation entry, which might not be the current one.
4075 // For example, it might be from a recently swapped out RFH.
4076 NavigationEntryImpl* entry = controller_.GetEntryWithPageID(
4077 render_frame_host->GetSiteInstance(), page_id);
4079 RenderViewHostImpl* rvhi =
4080 static_cast<RenderViewHostImpl*>(render_frame_host->GetRenderViewHost());
4081 NavigationEntryImpl* new_entry = controller_.GetEntryWithUniqueID(
4082 rvhi->nav_entry_id());
4083 DCHECK_EQ(entry, new_entry);
4085 // We can handle title updates when we don't have an entry in
4086 // UpdateTitleForEntry, but only if the update is from the current RVH.
4087 // TODO(avi): Change to make decisions based on the RenderFrameHost.
4088 if (!entry && render_frame_host != GetMainFrame())
4089 return;
4091 // TODO(evan): make use of title_direction.
4092 // http://code.google.com/p/chromium/issues/detail?id=27094
4093 if (!UpdateTitleForEntry(entry, title))
4094 return;
4096 // Broadcast notifications when the UI should be updated.
4097 if (entry == controller_.GetEntryAtOffset(0))
4098 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
4101 void WebContentsImpl::UpdateEncoding(RenderFrameHost* render_frame_host,
4102 const std::string& encoding) {
4103 SetEncoding(encoding);
4106 void WebContentsImpl::DocumentAvailableInMainFrame(
4107 RenderViewHost* render_view_host) {
4108 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4109 DocumentAvailableInMainFrame());
4112 void WebContentsImpl::RouteCloseEvent(RenderViewHost* rvh) {
4113 // Tell the active RenderViewHost to run unload handlers and close, as long
4114 // as the request came from a RenderViewHost in the same BrowsingInstance.
4115 // In most cases, we receive this from a swapped out RenderViewHost.
4116 // It is possible to receive it from one that has just been swapped in,
4117 // in which case we might as well deliver the message anyway.
4118 if (rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()))
4119 ClosePage();
4122 bool WebContentsImpl::ShouldRouteMessageEvent(
4123 RenderFrameHost* target_rfh,
4124 SiteInstance* source_site_instance) const {
4125 // Allow the message if this WebContents is dedicated to a browser plugin
4126 // guest.
4127 // Note: This check means that an embedder could theoretically receive a
4128 // postMessage from anyone (not just its own guests). However, this is
4129 // probably not a risk for apps since other pages won't have references
4130 // to App windows.
4131 return GetBrowserPluginGuest() || GetBrowserPluginEmbedder();
4134 void WebContentsImpl::EnsureOpenerProxiesExist(RenderFrameHost* source_rfh) {
4135 WebContentsImpl* source_web_contents = static_cast<WebContentsImpl*>(
4136 WebContents::FromRenderFrameHost(source_rfh));
4138 if (source_web_contents) {
4139 // If this message is going to outer WebContents from inner WebContents,
4140 // then we should not create a RenderView. AttachToOuterWebContentsFrame()
4141 // already created a RenderFrameProxyHost for that purpose.
4142 if (GetBrowserPluginEmbedder() &&
4143 BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
4144 return;
4147 if (GetBrowserPluginGuest()) {
4148 // We create a swapped out RenderView or RenderFrameProxyHost for the
4149 // embedder in the guest's render process but we intentionally do not
4150 // expose the embedder's opener chain to it.
4151 if (SiteIsolationPolicy::IsSwappedOutStateForbidden()) {
4152 source_web_contents->GetRenderManager()->CreateRenderFrameProxy(
4153 GetSiteInstance());
4154 } else {
4155 source_web_contents->CreateSwappedOutRenderView(GetSiteInstance());
4157 } else {
4158 RenderFrameHostImpl* source_rfhi =
4159 static_cast<RenderFrameHostImpl*>(source_rfh);
4160 source_rfhi->frame_tree_node()->render_manager()->CreateOpenerProxies(
4161 GetSiteInstance(), nullptr);
4166 bool WebContentsImpl::AddMessageToConsole(int32 level,
4167 const base::string16& message,
4168 int32 line_no,
4169 const base::string16& source_id) {
4170 if (!delegate_)
4171 return false;
4172 return delegate_->AddMessageToConsole(this, level, message, line_no,
4173 source_id);
4176 int WebContentsImpl::CreateSwappedOutRenderView(
4177 SiteInstance* instance) {
4178 int render_view_routing_id = MSG_ROUTING_NONE;
4179 if (SiteIsolationPolicy::IsSwappedOutStateForbidden()) {
4180 GetRenderManager()->CreateRenderFrameProxy(instance);
4181 } else {
4182 GetRenderManager()->CreateRenderFrame(
4183 instance, nullptr, CREATE_RF_SWAPPED_OUT | CREATE_RF_HIDDEN,
4184 &render_view_routing_id);
4186 return render_view_routing_id;
4189 void WebContentsImpl::OnUserGesture() {
4190 // Notify observers.
4191 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetUserGesture());
4193 ResourceDispatcherHostImpl* rdh = ResourceDispatcherHostImpl::Get();
4194 if (rdh) // NULL in unittests.
4195 rdh->OnUserGesture(this);
4198 void WebContentsImpl::OnIgnoredUIEvent() {
4199 // Notify observers.
4200 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetIgnoredUIEvent());
4203 void WebContentsImpl::RendererUnresponsive(RenderViewHost* render_view_host) {
4204 // Don't show hung renderer dialog for a swapped out RVH.
4205 if (render_view_host != GetRenderViewHost())
4206 return;
4208 RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(render_view_host);
4209 RenderFrameHostImpl* rfhi =
4210 static_cast<RenderFrameHostImpl*>(rvhi->GetMainFrame());
4212 // Ignore renderer unresponsive event if debugger is attached to the tab
4213 // since the event may be a result of the renderer sitting on a breakpoint.
4214 // See http://crbug.com/65458
4215 if (DevToolsAgentHost::IsDebuggerAttached(this))
4216 return;
4218 if (rfhi->is_waiting_for_beforeunload_ack() ||
4219 rfhi->IsWaitingForUnloadACK()) {
4220 // Hang occurred while firing the beforeunload/unload handler.
4221 // Pretend the handler fired so tab closing continues as if it had.
4222 rvhi->set_sudden_termination_allowed(true);
4224 if (!GetRenderManager()->ShouldCloseTabOnUnresponsiveRenderer())
4225 return;
4227 // If the tab hangs in the beforeunload/unload handler there's really
4228 // nothing we can do to recover. If the hang is in the beforeunload handler,
4229 // pretend the beforeunload listeners have all fired and allow the delegate
4230 // to continue closing; the user will not have the option of cancelling the
4231 // close. Otherwise, pretend the unload listeners have all fired and close
4232 // the tab.
4233 bool close = true;
4234 if (rfhi->is_waiting_for_beforeunload_ack() && delegate_) {
4235 delegate_->BeforeUnloadFired(this, true, &close);
4237 if (close)
4238 Close(rvhi);
4239 return;
4242 if (!GetRenderViewHost() || !GetRenderViewHost()->IsRenderViewLive())
4243 return;
4245 if (delegate_)
4246 delegate_->RendererUnresponsive(this);
4249 void WebContentsImpl::RendererResponsive(RenderViewHost* render_view_host) {
4250 if (delegate_)
4251 delegate_->RendererResponsive(this);
4254 void WebContentsImpl::LoadStateChanged(
4255 const GURL& url,
4256 const net::LoadStateWithParam& load_state,
4257 uint64 upload_position,
4258 uint64 upload_size) {
4259 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
4260 // is fixed.
4261 tracked_objects::ScopedTracker tracking_profile1(
4262 FROM_HERE_WITH_EXPLICIT_FUNCTION(
4263 "466285 WebContentsImpl::LoadStateChanged::Start"));
4264 load_state_ = load_state;
4265 upload_position_ = upload_position;
4266 upload_size_ = upload_size;
4267 load_state_host_ = url_formatter::IDNToUnicode(
4268 url.host(),
4269 GetContentClient()->browser()->GetAcceptLangs(GetBrowserContext()));
4270 if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
4271 SetNotWaitingForResponse();
4272 if (IsLoading()) {
4273 NotifyNavigationStateChanged(static_cast<InvalidateTypes>(
4274 INVALIDATE_TYPE_LOAD | INVALIDATE_TYPE_TAB));
4278 void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
4279 bool proceed, const base::TimeTicks& proceed_time,
4280 bool* proceed_to_fire_unload) {
4281 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4282 BeforeUnloadFired(proceed_time));
4283 if (delegate_)
4284 delegate_->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
4285 // Note: |this| might be deleted at this point.
4288 void WebContentsImpl::RenderProcessGoneFromRenderManager(
4289 RenderViewHost* render_view_host) {
4290 DCHECK(crashed_status_ != base::TERMINATION_STATUS_STILL_RUNNING);
4291 RenderViewTerminated(render_view_host, crashed_status_, crashed_error_code_);
4294 void WebContentsImpl::UpdateRenderViewSizeForRenderManager() {
4295 // TODO(brettw) this is a hack. See WebContentsView::SizeContents.
4296 gfx::Size size = GetSizeForNewRenderView();
4297 // 0x0 isn't a valid window size (minimal window size is 1x1) but it may be
4298 // here during container initialization and normal window size will be set
4299 // later. In case of tab duplication this resizing to 0x0 prevents setting
4300 // normal size later so just ignore it.
4301 if (!size.IsEmpty())
4302 view_->SizeContents(size);
4305 void WebContentsImpl::CancelModalDialogsForRenderManager() {
4306 // We need to cancel modal dialogs when doing a process swap, since the load
4307 // deferrer would prevent us from swapping out. We also clear the state
4308 // because this is a cross-process navigation, which means that it's a new
4309 // site that should not have to pay for the sins of its predecessor.
4311 // Note that we don't bother telling browser_plugin_embedder_ because the
4312 // cross-process navigation will either destroy the browser plugins or not
4313 // require their dialogs to close.
4314 if (dialog_manager_)
4315 dialog_manager_->ResetDialogState(this);
4318 void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost* old_host,
4319 RenderFrameHost* new_host,
4320 bool is_main_frame) {
4321 if (is_main_frame) {
4322 NotifyViewSwapped(old_host ? old_host->GetRenderViewHost() : nullptr,
4323 new_host->GetRenderViewHost());
4325 // Make sure the visible RVH reflects the new delegate's preferences.
4326 if (delegate_)
4327 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
4329 view_->RenderViewSwappedIn(new_host->GetRenderViewHost());
4332 NotifyFrameSwapped(old_host, new_host);
4335 void WebContentsImpl::NotifyMainFrameSwappedFromRenderManager(
4336 RenderViewHost* old_host,
4337 RenderViewHost* new_host) {
4338 NotifyViewSwapped(old_host, new_host);
4341 NavigationControllerImpl& WebContentsImpl::GetControllerForRenderManager() {
4342 return GetController();
4345 scoped_ptr<WebUIImpl> WebContentsImpl::CreateWebUIForRenderManager(
4346 const GURL& url) {
4347 return scoped_ptr<WebUIImpl>(static_cast<WebUIImpl*>(CreateWebUI(
4348 url, std::string())));
4351 NavigationEntry*
4352 WebContentsImpl::GetLastCommittedNavigationEntryForRenderManager() {
4353 return controller_.GetLastCommittedEntry();
4356 void WebContentsImpl::CreateRenderWidgetHostViewForRenderManager(
4357 RenderViewHost* render_view_host) {
4358 RenderWidgetHostViewBase* rwh_view = nullptr;
4359 bool is_guest_in_site_per_process =
4360 !!browser_plugin_guest_.get() &&
4361 BrowserPluginGuestMode::UseCrossProcessFramesForGuests();
4362 if (is_guest_in_site_per_process) {
4363 RenderWidgetHostViewChildFrame* rwh_view_child =
4364 new RenderWidgetHostViewChildFrame(render_view_host);
4365 rwh_view = rwh_view_child;
4366 } else {
4367 rwh_view = view_->CreateViewForWidget(render_view_host, false);
4370 // Now that the RenderView has been created, we need to tell it its size.
4371 if (rwh_view)
4372 rwh_view->SetSize(GetSizeForNewRenderView());
4375 bool WebContentsImpl::CreateRenderViewForRenderManager(
4376 RenderViewHost* render_view_host,
4377 int opener_frame_routing_id,
4378 int proxy_routing_id,
4379 const FrameReplicationState& replicated_frame_state) {
4380 TRACE_EVENT0("browser,navigation",
4381 "WebContentsImpl::CreateRenderViewForRenderManager");
4383 if (proxy_routing_id == MSG_ROUTING_NONE)
4384 CreateRenderWidgetHostViewForRenderManager(render_view_host);
4386 // Make sure we use the correct starting page_id in the new RenderView.
4387 UpdateMaxPageIDIfNecessary(render_view_host);
4388 int32 max_page_id =
4389 GetMaxPageIDForSiteInstance(render_view_host->GetSiteInstance());
4391 if (!static_cast<RenderViewHostImpl*>(render_view_host)
4392 ->CreateRenderView(opener_frame_routing_id, proxy_routing_id,
4393 max_page_id, replicated_frame_state,
4394 created_with_opener_)) {
4395 return false;
4398 SetHistoryOffsetAndLengthForView(render_view_host,
4399 controller_.GetLastCommittedEntryIndex(),
4400 controller_.GetEntryCount());
4402 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
4403 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
4404 // linux. See crbug.com/83941.
4405 RenderWidgetHostView* rwh_view = render_view_host->GetView();
4406 if (rwh_view) {
4407 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
4408 render_widget_host->WasResized();
4410 #endif
4412 return true;
4415 bool WebContentsImpl::CreateRenderFrameForRenderManager(
4416 RenderFrameHost* render_frame_host,
4417 int proxy_routing_id,
4418 int opener_routing_id,
4419 int parent_routing_id,
4420 int previous_sibling_routing_id) {
4421 TRACE_EVENT0("browser,navigation",
4422 "WebContentsImpl::CreateRenderFrameForRenderManager");
4424 RenderFrameHostImpl* rfh =
4425 static_cast<RenderFrameHostImpl*>(render_frame_host);
4426 if (!rfh->CreateRenderFrame(proxy_routing_id, opener_routing_id,
4427 parent_routing_id, previous_sibling_routing_id))
4428 return false;
4430 // TODO(nasko): When RenderWidgetHost is owned by RenderFrameHost, the passed
4431 // RenderFrameHost will have to be associated with the appropriate
4432 // RenderWidgetHostView or a new one should be created here.
4434 return true;
4437 #if defined(OS_ANDROID)
4439 base::android::ScopedJavaLocalRef<jobject>
4440 WebContentsImpl::GetJavaWebContents() {
4441 DCHECK_CURRENTLY_ON(BrowserThread::UI);
4442 return GetWebContentsAndroid()->GetJavaObject();
4445 WebContentsAndroid* WebContentsImpl::GetWebContentsAndroid() {
4446 WebContentsAndroid* web_contents_android =
4447 static_cast<WebContentsAndroid*>(GetUserData(kWebContentsAndroidKey));
4448 if (!web_contents_android) {
4449 web_contents_android = new WebContentsAndroid(this);
4450 SetUserData(kWebContentsAndroidKey, web_contents_android);
4452 return web_contents_android;
4455 bool WebContentsImpl::CreateRenderViewForInitialEmptyDocument() {
4456 return CreateRenderViewForRenderManager(
4457 GetRenderViewHost(), MSG_ROUTING_NONE, MSG_ROUTING_NONE,
4458 frame_tree_.root()->current_replication_state());
4461 #elif defined(OS_MACOSX)
4463 void WebContentsImpl::SetAllowOtherViews(bool allow) {
4464 view_->SetAllowOtherViews(allow);
4467 bool WebContentsImpl::GetAllowOtherViews() {
4468 return view_->GetAllowOtherViews();
4471 #endif
4473 void WebContentsImpl::OnDialogClosed(int render_process_id,
4474 int render_frame_id,
4475 IPC::Message* reply_msg,
4476 bool dialog_was_suppressed,
4477 bool success,
4478 const base::string16& user_input) {
4479 RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(render_process_id,
4480 render_frame_id);
4481 last_dialog_suppressed_ = dialog_was_suppressed;
4483 if (is_showing_before_unload_dialog_ && !success) {
4484 // If a beforeunload dialog is canceled, we need to stop the throbber from
4485 // spinning, since we forced it to start spinning in Navigate.
4486 if (rfh)
4487 DidStopLoading();
4488 controller_.DiscardNonCommittedEntries();
4490 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4491 BeforeUnloadDialogCancelled());
4494 is_showing_before_unload_dialog_ = false;
4495 if (rfh) {
4496 rfh->JavaScriptDialogClosed(reply_msg, success, user_input,
4497 dialog_was_suppressed);
4498 } else {
4499 // Don't leak the sync IPC reply if the RFH or process is gone.
4500 delete reply_msg;
4504 void WebContentsImpl::SetEncoding(const std::string& encoding) {
4505 if (encoding == last_reported_encoding_)
4506 return;
4507 last_reported_encoding_ = encoding;
4509 canonical_encoding_ = GetContentClient()->browser()->
4510 GetCanonicalEncodingNameByAliasName(encoding);
4513 bool WebContentsImpl::IsHidden() {
4514 return capturer_count_ == 0 && !should_normally_be_visible_;
4517 int WebContentsImpl::GetOuterDelegateFrameTreeNodeID() {
4518 if (node_ && node_->outer_web_contents())
4519 return node_->outer_contents_frame_tree_node_id();
4521 return FrameTreeNode::kFrameTreeNodeInvalidID;
4524 RenderFrameHostManager* WebContentsImpl::GetRenderManager() const {
4525 return frame_tree_.root()->render_manager();
4528 BrowserPluginGuest* WebContentsImpl::GetBrowserPluginGuest() const {
4529 return browser_plugin_guest_.get();
4532 void WebContentsImpl::SetBrowserPluginGuest(BrowserPluginGuest* guest) {
4533 CHECK(!browser_plugin_guest_);
4534 CHECK(guest);
4535 browser_plugin_guest_.reset(guest);
4538 BrowserPluginEmbedder* WebContentsImpl::GetBrowserPluginEmbedder() const {
4539 return browser_plugin_embedder_.get();
4542 void WebContentsImpl::CreateBrowserPluginEmbedderIfNecessary() {
4543 if (browser_plugin_embedder_)
4544 return;
4545 browser_plugin_embedder_.reset(BrowserPluginEmbedder::Create(this));
4548 void WebContentsImpl::ClearPowerSaveBlockers(
4549 RenderFrameHost* render_frame_host) {
4550 RemoveAllMediaPlayerEntries(render_frame_host, &active_audio_players_);
4551 RemoveAllMediaPlayerEntries(render_frame_host, &active_video_players_);
4552 MaybeReleasePowerSaveBlockers();
4555 void WebContentsImpl::ClearAllPowerSaveBlockers() {
4556 active_audio_players_.clear();
4557 active_video_players_.clear();
4558 audio_power_save_blocker_.reset();
4559 video_power_save_blocker_.reset();
4562 gfx::Size WebContentsImpl::GetSizeForNewRenderView() {
4563 gfx::Size size;
4564 if (delegate_)
4565 size = delegate_->GetSizeForNewRenderView(this);
4566 if (size.IsEmpty())
4567 size = GetContainerBounds().size();
4568 return size;
4571 void WebContentsImpl::OnFrameRemoved(RenderFrameHost* render_frame_host) {
4572 FOR_EACH_OBSERVER(
4573 WebContentsObserver, observers_, FrameDeleted(render_frame_host));
4576 void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size& old_size) {
4577 if (!delegate_)
4578 return;
4579 const gfx::Size new_size = GetPreferredSize();
4580 if (new_size != old_size)
4581 delegate_->UpdatePreferredSize(this, new_size);
4584 void WebContentsImpl::AddMediaPlayerEntry(int64 player_cookie,
4585 ActiveMediaPlayerMap* player_map) {
4586 if (!HasValidFrameSource())
4587 return;
4589 const uintptr_t key =
4590 reinterpret_cast<uintptr_t>(render_frame_message_source_);
4591 DCHECK(std::find((*player_map)[key].begin(),
4592 (*player_map)[key].end(),
4593 player_cookie) == (*player_map)[key].end());
4594 (*player_map)[key].push_back(player_cookie);
4597 void WebContentsImpl::RemoveMediaPlayerEntry(int64 player_cookie,
4598 ActiveMediaPlayerMap* player_map) {
4599 if (!HasValidFrameSource())
4600 return;
4602 const uintptr_t key =
4603 reinterpret_cast<uintptr_t>(render_frame_message_source_);
4604 ActiveMediaPlayerMap::iterator it = player_map->find(key);
4605 if (it == player_map->end())
4606 return;
4608 // Remove the player.
4609 PlayerList::iterator player_it =
4610 std::find(it->second.begin(), it->second.end(), player_cookie);
4611 if (player_it != it->second.end())
4612 it->second.erase(player_it);
4614 // If there are no players left, remove the map entry.
4615 if (it->second.empty())
4616 player_map->erase(it);
4619 void WebContentsImpl::RemoveAllMediaPlayerEntries(
4620 RenderFrameHost* render_frame_host,
4621 ActiveMediaPlayerMap* player_map) {
4622 ActiveMediaPlayerMap::iterator it =
4623 player_map->find(reinterpret_cast<uintptr_t>(render_frame_host));
4624 if (it == player_map->end())
4625 return;
4626 player_map->erase(it);
4629 WebUI* WebContentsImpl::CreateWebUI(const GURL& url,
4630 const std::string& frame_name) {
4631 WebUIImpl* web_ui = new WebUIImpl(this, frame_name);
4632 WebUIController* controller = WebUIControllerFactoryRegistry::GetInstance()->
4633 CreateWebUIControllerForURL(web_ui, url);
4634 if (controller) {
4635 web_ui->AddMessageHandler(new GenericHandler());
4636 web_ui->SetController(controller);
4637 return web_ui;
4640 delete web_ui;
4641 return NULL;
4644 void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable) {
4645 force_disable_overscroll_content_ = force_disable;
4646 if (view_)
4647 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
4650 } // namespace content