blob: dfde98b4901581428049b7540d36d4891e690146 [file] [log] [blame]
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/web_contents/web_contents_impl.h"
#include <stddef.h>
#include <cmath>
#include <utility>
#include <vector>
#include "base/command_line.h"
#include "base/debug/dump_without_crashing.h"
#include "base/feature_list.h"
#include "base/i18n/character_encoding.h"
#include "base/lazy_instance.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/histogram_macros.h"
#include "base/process/process.h"
#include "base/profiler/scoped_tracker.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string16.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "components/mime_util/mime_util.h"
#include "components/rappor/public/rappor_utils.h"
#include "components/url_formatter/url_formatter.h"
#include "content/browser/accessibility/browser_accessibility_state_impl.h"
#include "content/browser/bad_message.h"
#include "content/browser/browser_plugin/browser_plugin_embedder.h"
#include "content/browser/browser_plugin/browser_plugin_guest.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/devtools/render_frame_devtools_agent_host.h"
#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
#include "content/browser/dom_storage/session_storage_namespace_impl.h"
#include "content/browser/download/download_stats.h"
#include "content/browser/download/mhtml_generation_manager.h"
#include "content/browser/download/save_package.h"
#include "content/browser/find_request_manager.h"
#include "content/browser/frame_host/cross_process_frame_connector.h"
#include "content/browser/frame_host/frame_tree_node.h"
#include "content/browser/frame_host/interstitial_page_impl.h"
#include "content/browser/frame_host/navigation_entry_impl.h"
#include "content/browser/frame_host/navigation_handle_impl.h"
#include "content/browser/frame_host/navigator_impl.h"
#include "content/browser/frame_host/render_frame_host_impl.h"
#include "content/browser/frame_host/render_frame_proxy_host.h"
#include "content/browser/frame_host/render_widget_host_view_child_frame.h"
#include "content/browser/host_zoom_map_impl.h"
#include "content/browser/host_zoom_map_observer.h"
#include "content/browser/loader/loader_io_thread_notifier.h"
#include "content/browser/loader/resource_dispatcher_host_impl.h"
#include "content/browser/manifest/manifest_manager_host.h"
#include "content/browser/media/audio_stream_monitor.h"
#include "content/browser/media/capture/web_contents_audio_muter.h"
#include "content/browser/media/media_web_contents_observer.h"
#include "content/browser/media/session/media_session_impl.h"
#include "content/browser/plugin_content_origin_whitelist.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/renderer_host/render_view_host_delegate_view.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_input_event_router.h"
#include "content/browser/renderer_host/render_widget_host_view_base.h"
#include "content/browser/renderer_host/text_input_manager.h"
#include "content/browser/screen_orientation/screen_orientation_provider.h"
#include "content/browser/site_instance_impl.h"
#include "content/browser/web_contents/web_contents_view_child_frame.h"
#include "content/browser/web_contents/web_contents_view_guest.h"
#include "content/browser/webui/generic_handler.h"
#include "content/browser/webui/web_ui_controller_factory_registry.h"
#include "content/browser/webui/web_ui_impl.h"
#include "content/common/browser_plugin/browser_plugin_constants.h"
#include "content/common/browser_plugin/browser_plugin_messages.h"
#include "content/common/drag_messages.h"
#include "content/common/frame_messages.h"
#include "content/common/input_messages.h"
#include "content/common/page_messages.h"
#include "content/common/page_state_serialization.h"
#include "content/common/render_message_filter.mojom.h"
#include "content/common/site_isolation_policy.h"
#include "content/common/view_messages.h"
#include "content/public/browser/ax_event_notification_details.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_plugin_guest_manager.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/download_url_parameters.h"
#include "content/public/browser/focused_node_details.h"
#include "content/public/browser/guest_mode.h"
#include "content/public/browser/invalidate_type.h"
#include "content/public/browser/javascript_dialog_manager.h"
#include "content/public/browser/load_notification_details.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_widget_host_iterator.h"
#include "content/public/browser/resource_request_details.h"
#include "content/public/browser/security_style_explanations.h"
#include "content/public/browser/ssl_status.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents_binding_set.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/browser/web_contents_unresponsive_state.h"
#include "content/public/common/bindings_policy.h"
#include "content/public/common/browser_side_navigation_policy.h"
#include "content/public/common/child_process_host.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/page_zoom.h"
#include "content/public/common/result_codes.h"
#include "content/public/common/url_utils.h"
#include "content/public/common/web_preferences.h"
#include "device/geolocation/geolocation_service_context.h"
#include "device/nfc/nfc.mojom.h"
#include "device/wake_lock/wake_lock_service_context.h"
#include "net/base/url_util.h"
#include "net/http/http_cache.h"
#include "net/http/http_transaction_factory.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "ppapi/features/features.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "third_party/WebKit/public/platform/WebSecurityStyle.h"
#include "third_party/WebKit/public/web/WebSandboxFlags.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/accessibility/ax_tree_combiner.h"
#include "ui/base/layout.h"
#include "ui/events/blink/web_input_event_traits.h"
#include "ui/gl/gl_switches.h"
#if defined(OS_WIN)
#include "content/browser/renderer_host/dip_util.h"
#include "ui/gfx/geometry/dip_util.h"
#endif
#if defined(OS_ANDROID)
#include "content/browser/android/content_video_view.h"
#include "content/browser/android/date_time_chooser_android.h"
#include "content/browser/android/java_interfaces_impl.h"
#include "content/browser/media/android/media_web_contents_observer_android.h"
#include "content/browser/web_contents/web_contents_android.h"
#endif // OS_ANDROID
#if defined(OS_MACOSX)
#include "base/mac/foundation_util.h"
#endif
#if defined(USE_AURA)
#include "content/public/common/service_manager_connection.h"
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/browser/media/session/pepper_playback_observer.h"
#endif // ENABLE_PLUGINS
namespace content {
namespace {
const int kMinimumDelayBetweenLoadingUpdatesMS = 100;
const char kDotGoogleDotCom[] = ".google.com";
#if defined(OS_ANDROID)
const void* const kWebContentsAndroidKey = &kWebContentsAndroidKey;
#endif // OS_ANDROID
base::LazyInstance<std::vector<WebContentsImpl::CreatedCallback>>::
DestructorAtExit g_created_callbacks = LAZY_INSTANCE_INITIALIZER;
void NotifyCacheOnIO(
scoped_refptr<net::URLRequestContextGetter> request_context,
const GURL& url,
const std::string& http_method) {
net::HttpCache* cache = request_context->GetURLRequestContext()->
http_transaction_factory()->GetCache();
if (cache)
cache->OnExternalCacheHit(url, http_method);
}
bool HasMatchingProcess(FrameTree* tree, int render_process_id) {
for (FrameTreeNode* node : tree->Nodes()) {
if (node->current_frame_host()->GetProcess()->GetID() == render_process_id)
return true;
}
return false;
}
bool HasMatchingWidgetHost(FrameTree* tree, RenderWidgetHost* host) {
// This method scans the frame tree rather than checking whether
// host->delegate() == this, which allows it to return false when the host
// for a frame that is pending or pending deletion.
if (!host)
return false;
for (FrameTreeNode* node : tree->Nodes()) {
if (node->current_frame_host()->GetRenderWidgetHost() == host)
return true;
}
return false;
}
void UpdateAccessibilityModeOnFrame(RenderFrameHost* frame_host) {
static_cast<RenderFrameHostImpl*>(frame_host)->UpdateAccessibilityMode();
}
void ResetAccessibility(RenderFrameHost* rfh) {
static_cast<RenderFrameHostImpl*>(rfh)->AccessibilityReset();
}
using AXTreeSnapshotCallback =
base::Callback<void(const ui::AXTreeUpdate&)>;
// Helper class used by WebContentsImpl::RequestAXTreeSnapshot.
// Handles the callbacks from parallel snapshot requests to each frame,
// and feeds the results to an AXTreeCombiner, which converts them into a
// single combined accessibility tree.
class AXTreeSnapshotCombiner : public base::RefCounted<AXTreeSnapshotCombiner> {
public:
explicit AXTreeSnapshotCombiner(AXTreeSnapshotCallback callback)
: callback_(callback) {
}
AXTreeSnapshotCallback AddFrame(bool is_root) {
// Adds a reference to |this|.
return base::Bind(&AXTreeSnapshotCombiner::ReceiveSnapshot,
this,
is_root);
}
void ReceiveSnapshot(bool is_root, const ui::AXTreeUpdate& snapshot) {
combiner_.AddTree(snapshot, is_root);
}
private:
friend class base::RefCounted<AXTreeSnapshotCombiner>;
// This is called automatically after the last call to ReceiveSnapshot
// when there are no more references to this object.
~AXTreeSnapshotCombiner() {
combiner_.Combine();
callback_.Run(combiner_.combined());
}
ui::AXTreeCombiner combiner_;
AXTreeSnapshotCallback callback_;
};
} // namespace
WebContents* WebContents::Create(const WebContents::CreateParams& params) {
FrameTreeNode* opener_node = nullptr;
if (params.opener_render_frame_id != MSG_ROUTING_NONE) {
RenderFrameHostImpl* opener_rfh = RenderFrameHostImpl::FromID(
params.opener_render_process_id, params.opener_render_frame_id);
if (opener_rfh)
opener_node = opener_rfh->frame_tree_node();
}
return WebContentsImpl::CreateWithOpener(params, opener_node);
}
WebContents* WebContents::CreateWithSessionStorage(
const WebContents::CreateParams& params,
const SessionStorageNamespaceMap& session_storage_namespace_map) {
WebContentsImpl* new_contents = new WebContentsImpl(params.browser_context);
for (SessionStorageNamespaceMap::const_iterator it =
session_storage_namespace_map.begin();
it != session_storage_namespace_map.end();
++it) {
new_contents->GetController()
.SetSessionStorageNamespace(it->first, it->second.get());
}
new_contents->Init(params);
return new_contents;
}
void WebContentsImpl::FriendZone::AddCreatedCallbackForTesting(
const CreatedCallback& callback) {
g_created_callbacks.Get().push_back(callback);
}
void WebContentsImpl::FriendZone::RemoveCreatedCallbackForTesting(
const CreatedCallback& callback) {
for (size_t i = 0; i < g_created_callbacks.Get().size(); ++i) {
if (g_created_callbacks.Get().at(i).Equals(callback)) {
g_created_callbacks.Get().erase(g_created_callbacks.Get().begin() + i);
return;
}
}
}
WebContents* WebContents::FromRenderViewHost(RenderViewHost* rvh) {
if (!rvh)
return nullptr;
return rvh->GetDelegate()->GetAsWebContents();
}
WebContents* WebContents::FromRenderFrameHost(RenderFrameHost* rfh) {
if (!rfh)
return nullptr;
return static_cast<RenderFrameHostImpl*>(rfh)->delegate()->GetAsWebContents();
}
WebContents* WebContents::FromFrameTreeNodeId(int frame_tree_node_id) {
FrameTreeNode* frame_tree_node =
FrameTreeNode::GloballyFindByID(frame_tree_node_id);
if (!frame_tree_node)
return nullptr;
return FromRenderFrameHost(frame_tree_node->current_frame_host());
}
void WebContents::SetScreenOrientationDelegate(
ScreenOrientationDelegate* delegate) {
ScreenOrientationProvider::SetDelegate(delegate);
}
// WebContentsImpl::DestructionObserver ----------------------------------------
class WebContentsImpl::DestructionObserver : public WebContentsObserver {
public:
DestructionObserver(WebContentsImpl* owner, WebContents* watched_contents)
: WebContentsObserver(watched_contents),
owner_(owner) {
}
// WebContentsObserver:
void WebContentsDestroyed() override {
owner_->OnWebContentsDestroyed(
static_cast<WebContentsImpl*>(web_contents()));
}
private:
WebContentsImpl* owner_;
DISALLOW_COPY_AND_ASSIGN(DestructionObserver);
};
WebContentsImpl::ColorChooserInfo::ColorChooserInfo(int render_process_id,
int render_frame_id,
ColorChooser* chooser,
int identifier)
: render_process_id(render_process_id),
render_frame_id(render_frame_id),
chooser(chooser),
identifier(identifier) {
}
WebContentsImpl::ColorChooserInfo::~ColorChooserInfo() {
}
bool WebContentsImpl::ColorChooserInfo::Matches(
RenderFrameHostImpl* render_frame_host,
int color_chooser_id) {
return this->render_process_id == render_frame_host->GetProcess()->GetID() &&
this->render_frame_id == render_frame_host->GetRoutingID() &&
this->identifier == color_chooser_id;
}
// WebContentsImpl::WebContentsTreeNode ----------------------------------------
WebContentsImpl::WebContentsTreeNode::WebContentsTreeNode(
WebContentsImpl* current_web_contents)
: current_web_contents_(current_web_contents),
outer_web_contents_(nullptr),
outer_contents_frame_tree_node_id_(
FrameTreeNode::kFrameTreeNodeInvalidId),
focused_web_contents_(current_web_contents) {}
WebContentsImpl::WebContentsTreeNode::~WebContentsTreeNode() {
if (OuterContentsFrameTreeNode())
OuterContentsFrameTreeNode()->RemoveObserver(this);
}
void WebContentsImpl::WebContentsTreeNode::ConnectToOuterWebContents(
WebContentsImpl* outer_web_contents,
RenderFrameHostImpl* outer_contents_frame) {
focused_web_contents_ = nullptr;
outer_web_contents_ = outer_web_contents;
outer_contents_frame_tree_node_id_ =
outer_contents_frame->frame_tree_node()->frame_tree_node_id();
outer_contents_frame->frame_tree_node()->AddObserver(this);
}
FrameTreeNode*
WebContentsImpl::WebContentsTreeNode::OuterContentsFrameTreeNode() const {
return FrameTreeNode::GloballyFindByID(outer_contents_frame_tree_node_id_);
}
void WebContentsImpl::WebContentsTreeNode::OnFrameTreeNodeDestroyed(
FrameTreeNode* node) {
DCHECK_EQ(outer_contents_frame_tree_node_id_, node->frame_tree_node_id())
<< "WebContentsTreeNode should only receive notifications for the "
"FrameTreeNode in its outer WebContents that hosts it.";
delete current_web_contents_; // deletes |this| too.
}
void WebContentsImpl::WebContentsTreeNode::SetFocusedWebContents(
WebContentsImpl* web_contents) {
DCHECK(!outer_web_contents())
<< "Only the outermost WebContents tracks focus.";
focused_web_contents_ = web_contents;
}
// WebContentsImpl -------------------------------------------------------------
WebContentsImpl::WebContentsImpl(BrowserContext* browser_context)
: delegate_(NULL),
controller_(this, browser_context),
render_view_host_delegate_view_(NULL),
created_with_opener_(false),
frame_tree_(new NavigatorImpl(&controller_, this),
this,
this,
this,
this),
node_(this),
is_load_to_different_document_(false),
crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING),
crashed_error_code_(0),
waiting_for_response_(false),
load_state_(net::LOAD_STATE_IDLE, base::string16()),
upload_size_(0),
upload_position_(0),
is_resume_pending_(false),
has_accessed_initial_document_(false),
theme_color_(SK_ColorTRANSPARENT),
last_sent_theme_color_(SK_ColorTRANSPARENT),
did_first_visually_non_empty_paint_(false),
capturer_count_(0),
should_normally_be_visible_(true),
did_first_set_visible_(false),
is_being_destroyed_(false),
is_notifying_observers_(false),
notify_disconnection_(false),
dialog_manager_(NULL),
is_showing_before_unload_dialog_(false),
last_active_time_(base::TimeTicks::Now()),
closed_by_user_gesture_(false),
minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)),
maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)),
zoom_scroll_remainder_(0),
fullscreen_widget_process_id_(ChildProcessHost::kInvalidUniqueID),
fullscreen_widget_routing_id_(MSG_ROUTING_NONE),
fullscreen_widget_had_focus_at_shutdown_(false),
is_subframe_(false),
force_disable_overscroll_content_(false),
last_dialog_suppressed_(false),
geolocation_service_context_(new device::GeolocationServiceContext()),
accessibility_mode_(
BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()),
audio_stream_monitor_(this),
bluetooth_connected_device_count_(0),
virtual_keyboard_requested_(false),
page_scale_factor_is_one_(true),
mouse_lock_widget_(nullptr),
is_overlay_content_(false),
loading_weak_factory_(this),
weak_factory_(this) {
frame_tree_.SetFrameRemoveListener(
base::Bind(&WebContentsImpl::OnFrameRemoved,
base::Unretained(this)));
#if defined(OS_ANDROID)
media_web_contents_observer_.reset(new MediaWebContentsObserverAndroid(this));
#else
media_web_contents_observer_.reset(new MediaWebContentsObserver(this));
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
pepper_playback_observer_.reset(new PepperPlaybackObserver(this));
#endif
loader_io_thread_notifier_.reset(new LoaderIOThreadNotifier(this));
wake_lock_service_context_.reset(new device::WakeLockServiceContext(
BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE),
base::Bind(&WebContentsImpl::GetNativeView, base::Unretained(this))));
host_zoom_map_observer_.reset(new HostZoomMapObserver(this));
}
WebContentsImpl::~WebContentsImpl() {
is_being_destroyed_ = true;
// A WebContents should never be deleted while it is notifying observers,
// since this will lead to a use-after-free as it continues to notfiy later
// observers.
CHECK(!is_notifying_observers_);
rwh_input_event_router_.reset();
for (auto& entry : binding_sets_)
entry.second->CloseAllBindings();
WebContentsImpl* outermost = GetOutermostWebContents();
if (this != outermost && ContainsOrIsFocusedWebContents()) {
// If the current WebContents is in focus, unset it.
outermost->SetAsFocusedWebContentsIfNecessary();
}
for (FrameTreeNode* node : frame_tree_.Nodes()) {
// Delete all RFHs pending shutdown, which will lead the corresponding RVHs
// to be shutdown and be deleted as well.
node->render_manager()->ClearRFHsPendingShutdown();
node->render_manager()->ClearWebUIInstances();
}
for (RenderWidgetHostImpl* widget : created_widgets_)
widget->DetachDelegate();
created_widgets_.clear();
// Clear out any JavaScript state.
if (dialog_manager_) {
dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
}
if (color_chooser_info_.get())
color_chooser_info_->chooser->End();
NotifyDisconnected();
// Notify any observer that have a reference on this WebContents.
NotificationService::current()->Notify(
NOTIFICATION_WEB_CONTENTS_DESTROYED,
Source<WebContents>(this),
NotificationService::NoDetails());
// Destroy all frame tree nodes except for the root; this notifies observers.
frame_tree_.root()->ResetForNewProcess();
GetRenderManager()->ResetProxyHosts();
// Manually call the observer methods for the root frame tree node. It is
// necessary to manually delete all objects tracking navigations
// (NavigationHandle, NavigationRequest) for observers to be properly
// notified of these navigations stopping before the WebContents is
// destroyed.
RenderFrameHostManager* root = GetRenderManager();
if (root->pending_frame_host()) {
root->pending_frame_host()->SetRenderFrameCreated(false);
root->pending_frame_host()->SetNavigationHandle(
std::unique_ptr<NavigationHandleImpl>());
}
root->current_frame_host()->SetRenderFrameCreated(false);
root->current_frame_host()->SetNavigationHandle(
std::unique_ptr<NavigationHandleImpl>());
// PlzNavigate: clear up state specific to browser-side navigation.
if (IsBrowserSideNavigationEnabled()) {
// Do not update state as the WebContents is being destroyed.
frame_tree_.root()->ResetNavigationRequest(true);
if (root->speculative_frame_host()) {
root->speculative_frame_host()->SetRenderFrameCreated(false);
root->speculative_frame_host()->SetNavigationHandle(
std::unique_ptr<NavigationHandleImpl>());
}
}
#if BUILDFLAG(ENABLE_PLUGINS)
// Call this before WebContentsDestroyed() is broadcasted since
// AudioFocusManager will be destroyed after that.
pepper_playback_observer_.reset();
#endif // defined(ENABLED_PLUGINS)
for (auto& observer : observers_)
observer.FrameDeleted(root->current_frame_host());
if (root->pending_render_view_host()) {
for (auto& observer : observers_)
observer.RenderViewDeleted(root->pending_render_view_host());
}
for (auto& observer : observers_)
observer.RenderViewDeleted(root->current_host());
for (auto& observer : observers_)
observer.WebContentsDestroyed();
for (auto& observer : observers_)
observer.ResetWebContents();
SetDelegate(NULL);
}
WebContentsImpl* WebContentsImpl::CreateWithOpener(
const WebContents::CreateParams& params,
FrameTreeNode* opener) {
TRACE_EVENT0("browser", "WebContentsImpl::CreateWithOpener");
WebContentsImpl* new_contents = new WebContentsImpl(params.browser_context);
FrameTreeNode* new_root = new_contents->GetFrameTree()->root();
if (opener) {
new_root->SetOriginalOpener(opener);
if (!params.opener_suppressed) {
new_root->SetOpener(opener);
new_contents->created_with_opener_ = true;
}
}
// If the opener is sandboxed, a new popup must inherit the opener's sandbox
// flags, and these flags take effect immediately. An exception is if the
// opener's sandbox flags lack the PropagatesToAuxiliaryBrowsingContexts
// bit (which is controlled by the "allow-popups-to-escape-sandbox" token).
// See https://html.spec.whatwg.org/#attr-iframe-sandbox.
if (opener) {
blink::WebSandboxFlags opener_flags = opener->effective_sandbox_flags();
const blink::WebSandboxFlags inherit_flag =
blink::WebSandboxFlags::PropagatesToAuxiliaryBrowsingContexts;
if ((opener_flags & inherit_flag) == inherit_flag) {
new_root->SetPendingSandboxFlags(opener_flags);
new_root->CommitPendingSandboxFlags();
}
}
// This may be true even when opener is null, such as when opening blocked
// popups.
if (params.created_with_opener)
new_contents->created_with_opener_ = true;
if (params.guest_delegate) {
// This makes |new_contents| act as a guest.
// For more info, see comment above class BrowserPluginGuest.
BrowserPluginGuest::Create(new_contents, params.guest_delegate);
// We are instantiating a WebContents for browser plugin. Set its subframe
// bit to true.
new_contents->is_subframe_ = true;
}
new_contents->Init(params);
return new_contents;
}
// static
std::vector<WebContentsImpl*> WebContentsImpl::GetAllWebContents() {
std::vector<WebContentsImpl*> result;
std::unique_ptr<RenderWidgetHostIterator> widgets(
RenderWidgetHostImpl::GetRenderWidgetHosts());
while (RenderWidgetHost* rwh = widgets->GetNextHost()) {
RenderViewHost* rvh = RenderViewHost::From(rwh);
if (!rvh)
continue;
WebContents* web_contents = WebContents::FromRenderViewHost(rvh);
if (!web_contents)
continue;
if (web_contents->GetRenderViewHost() != rvh)
continue;
// Because a WebContents can only have one current RVH at a time, there will
// be no duplicate WebContents here.
result.push_back(static_cast<WebContentsImpl*>(web_contents));
}
return result;
}
// static
WebContentsImpl* WebContentsImpl::FromFrameTreeNode(
FrameTreeNode* frame_tree_node) {
return static_cast<WebContentsImpl*>(
WebContents::FromRenderFrameHost(frame_tree_node->current_frame_host()));
}
// static
WebContents* WebContentsImpl::FromRenderFrameHostID(int render_process_host_id,
int render_frame_host_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
RenderFrameHost* render_frame_host =
RenderFrameHost::FromID(render_process_host_id, render_frame_host_id);
if (!render_frame_host)
return nullptr;
return WebContents::FromRenderFrameHost(render_frame_host);
}
RenderFrameHostManager* WebContentsImpl::GetRenderManagerForTesting() {
return GetRenderManager();
}
bool WebContentsImpl::OnMessageReceived(RenderViewHostImpl* render_view_host,
const IPC::Message& message) {
RenderFrameHost* main_frame = render_view_host->GetMainFrame();
if (main_frame) {
WebUIImpl* web_ui = static_cast<RenderFrameHostImpl*>(main_frame)->web_ui();
if (web_ui && web_ui->OnMessageReceived(message))
return true;
}
for (auto& observer : observers_) {
// TODO(nick, creis): Replace all uses of this variant of OnMessageReceived
// with the version that takes a RenderFrameHost, and delete it.
if (observer.OnMessageReceived(message))
return true;
}
bool handled = true;
IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(WebContentsImpl, message, render_view_host)
IPC_MESSAGE_HANDLER(ViewHostMsg_DidFirstVisuallyNonEmptyPaint,
OnFirstVisuallyNonEmptyPaint)
IPC_MESSAGE_HANDLER(ViewHostMsg_GoToEntryAtOffset, OnGoToEntryAtOffset)
IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateZoomLimits, OnUpdateZoomLimits)
IPC_MESSAGE_HANDLER(ViewHostMsg_PageScaleFactorChanged,
OnPageScaleFactorChanged)
IPC_MESSAGE_HANDLER(ViewHostMsg_EnumerateDirectory, OnEnumerateDirectory)
IPC_MESSAGE_HANDLER(ViewHostMsg_AppCacheAccessed, OnAppCacheAccessed)
IPC_MESSAGE_HANDLER(ViewHostMsg_WebUISend, OnWebUISend)
#if BUILDFLAG(ENABLE_PLUGINS)
IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission,
OnRequestPpapiBrokerPermission)
#endif
IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateFaviconURL, OnUpdateFaviconURL)
IPC_MESSAGE_HANDLER(ViewHostMsg_ShowValidationMessage,
OnShowValidationMessage)
IPC_MESSAGE_HANDLER(ViewHostMsg_HideValidationMessage,
OnHideValidationMessage)
IPC_MESSAGE_HANDLER(ViewHostMsg_MoveValidationMessage,
OnMoveValidationMessage)
#if defined(OS_ANDROID)
IPC_MESSAGE_HANDLER(ViewHostMsg_OpenDateTimeDialog, OnOpenDateTimeDialog)
#endif
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
bool WebContentsImpl::OnMessageReceived(RenderFrameHostImpl* render_frame_host,
const IPC::Message& message) {
for (auto& observer : observers_) {
if (observer.OnMessageReceived(message, render_frame_host))
return true;
}
bool handled = true;
IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(WebContentsImpl, message, render_frame_host)
IPC_MESSAGE_HANDLER(FrameHostMsg_DomOperationResponse,
OnDomOperationResponse)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeThemeColor,
OnThemeColorChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishDocumentLoad,
OnDocumentLoadedInFrame)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishLoad, OnDidFinishLoad)
IPC_MESSAGE_HANDLER(FrameHostMsg_OpenColorChooser, OnOpenColorChooser)
IPC_MESSAGE_HANDLER(FrameHostMsg_EndColorChooser, OnEndColorChooser)
IPC_MESSAGE_HANDLER(FrameHostMsg_SetSelectedColorInColorChooser,
OnSetSelectedColorInColorChooser)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidLoadResourceFromMemoryCache,
OnDidLoadResourceFromMemoryCache)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidDisplayInsecureContent,
OnDidDisplayInsecureContent)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidRunInsecureContent,
OnDidRunInsecureContent)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidDisplayContentWithCertificateErrors,
OnDidDisplayContentWithCertificateErrors)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidRunContentWithCertificateErrors,
OnDidRunContentWithCertificateErrors)
IPC_MESSAGE_HANDLER(FrameHostMsg_RegisterProtocolHandler,
OnRegisterProtocolHandler)
IPC_MESSAGE_HANDLER(FrameHostMsg_UnregisterProtocolHandler,
OnUnregisterProtocolHandler)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdatePageImportanceSignals,
OnUpdatePageImportanceSignals)
IPC_MESSAGE_HANDLER(FrameHostMsg_Find_Reply, OnFindReply)
#if BUILDFLAG(ENABLE_PLUGINS)
IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceCreated,
OnPepperInstanceCreated)
IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceDeleted,
OnPepperInstanceDeleted)
IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung, OnPepperPluginHung)
IPC_MESSAGE_HANDLER(FrameHostMsg_PepperStartsPlayback,
OnPepperStartsPlayback)
IPC_MESSAGE_HANDLER(FrameHostMsg_PepperStopsPlayback,
OnPepperStopsPlayback)
IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed, OnPluginCrashed)
IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_Attach,
OnBrowserPluginMessage(render_frame_host,
message))
#endif
#if defined(OS_ANDROID)
IPC_MESSAGE_HANDLER(FrameHostMsg_FindMatchRects_Reply,
OnFindMatchRectsReply)
IPC_MESSAGE_HANDLER(FrameHostMsg_GetNearestFindResult_Reply,
OnGetNearestFindResultReply)
#endif
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
NavigationControllerImpl& WebContentsImpl::GetController() {
return controller_;
}
const NavigationControllerImpl& WebContentsImpl::GetController() const {
return controller_;
}
BrowserContext* WebContentsImpl::GetBrowserContext() const {
return controller_.GetBrowserContext();
}
const GURL& WebContentsImpl::GetURL() const {
// We may not have a navigation entry yet.
NavigationEntry* entry = controller_.GetVisibleEntry();
return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
}
const GURL& WebContentsImpl::GetVisibleURL() const {
// We may not have a navigation entry yet.
NavigationEntry* entry = controller_.GetVisibleEntry();
return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
}
const GURL& WebContentsImpl::GetLastCommittedURL() const {
// We may not have a navigation entry yet.
NavigationEntry* entry = controller_.GetLastCommittedEntry();
return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
}
WebContentsDelegate* WebContentsImpl::GetDelegate() {
return delegate_;
}
void WebContentsImpl::SetDelegate(WebContentsDelegate* delegate) {
// TODO(cbentzel): remove this debugging code?
if (delegate == delegate_)
return;
if (delegate_)
delegate_->Detach(this);
delegate_ = delegate;
if (delegate_) {
delegate_->Attach(this);
// Ensure the visible RVH reflects the new delegate's preferences.
if (view_)
view_->SetOverscrollControllerEnabled(CanOverscrollContent());
}
}
RenderProcessHost* WebContentsImpl::GetRenderProcessHost() const {
RenderViewHostImpl* host = GetRenderManager()->current_host();
return host ? host->GetProcess() : NULL;
}
RenderFrameHostImpl* WebContentsImpl::GetMainFrame() {
return frame_tree_.root()->current_frame_host();
}
RenderFrameHostImpl* WebContentsImpl::GetFocusedFrame() {
FrameTreeNode* focused_node = frame_tree_.GetFocusedFrame();
if (!focused_node)
return nullptr;
return focused_node->current_frame_host();
}
RenderFrameHostImpl* WebContentsImpl::FindFrameByFrameTreeNodeId(
int frame_tree_node_id) {
FrameTreeNode* frame = frame_tree_.FindByID(frame_tree_node_id);
return frame ? frame->current_frame_host() : nullptr;
}
void WebContentsImpl::ForEachFrame(
const base::Callback<void(RenderFrameHost*)>& on_frame) {
for (FrameTreeNode* node : frame_tree_.Nodes()) {
on_frame.Run(node->current_frame_host());
}
}
std::vector<RenderFrameHost*> WebContentsImpl::GetAllFrames() {
std::vector<RenderFrameHost*> frame_hosts;
for (FrameTreeNode* node : frame_tree_.Nodes())
frame_hosts.push_back(node->current_frame_host());
return frame_hosts;
}
int WebContentsImpl::SendToAllFrames(IPC::Message* message) {
int number_of_messages = 0;
for (RenderFrameHost* rfh : GetAllFrames()) {
if (!rfh->IsRenderFrameLive())
continue;
++number_of_messages;
IPC::Message* message_copy = new IPC::Message(*message);
message_copy->set_routing_id(rfh->GetRoutingID());
rfh->Send(message_copy);
}
delete message;
return number_of_messages;
}
void WebContentsImpl::SendPageMessage(IPC::Message* msg) {
frame_tree_.root()->render_manager()->SendPageMessage(msg, nullptr);
}
RenderViewHostImpl* WebContentsImpl::GetRenderViewHost() const {
return GetRenderManager()->current_host();
}
void WebContentsImpl::CancelActiveAndPendingDialogs() {
if (dialog_manager_) {
dialog_manager_->CancelDialogs(this, /*reset_state=*/false);
}
if (browser_plugin_embedder_)
browser_plugin_embedder_->CancelGuestDialogs();
}
void WebContentsImpl::ClosePage() {
GetRenderViewHost()->ClosePage();
}
RenderWidgetHostView* WebContentsImpl::GetRenderWidgetHostView() const {
return GetRenderManager()->GetRenderWidgetHostView();
}
RenderWidgetHostView* WebContentsImpl::GetTopLevelRenderWidgetHostView() {
if (GetOuterWebContents())
return GetOuterWebContents()->GetTopLevelRenderWidgetHostView();
return GetRenderManager()->GetRenderWidgetHostView();
}
RenderWidgetHostView* WebContentsImpl::GetFullscreenRenderWidgetHostView()
const {
if (auto* widget_host = GetFullscreenRenderWidgetHost())
return widget_host->GetView();
return nullptr;
}
WebContentsView* WebContentsImpl::GetView() const {
return view_.get();
}
void WebContentsImpl::OnScreenOrientationChange() {
DCHECK(screen_orientation_provider_);
return screen_orientation_provider_->OnOrientationChange();
}
SkColor WebContentsImpl::GetThemeColor() const {
return theme_color_;
}
void WebContentsImpl::SetAccessibilityMode(AccessibilityMode mode) {
if (mode == accessibility_mode_)
return;
// Don't allow accessibility to be enabled for WebContents that are never
// visible, like background pages.
if (IsNeverVisible())
return;
accessibility_mode_ = mode;
for (FrameTreeNode* node : frame_tree_.Nodes()) {
UpdateAccessibilityModeOnFrame(node->current_frame_host());
RenderFrameHost* pending_frame_host =
node->render_manager()->pending_frame_host();
if (pending_frame_host)
UpdateAccessibilityModeOnFrame(pending_frame_host);
}
}
void WebContentsImpl::AddAccessibilityMode(AccessibilityMode mode) {
SetAccessibilityMode(accessibility_mode_ | mode);
}
void WebContentsImpl::RequestAXTreeSnapshot(AXTreeSnapshotCallback callback) {
// Send a request to each of the frames in parallel. Each one will return
// an accessibility tree snapshot, and AXTreeSnapshotCombiner will combine
// them into a single tree and call |callback| with that result, then
// delete |combiner|.
AXTreeSnapshotCombiner* combiner = new AXTreeSnapshotCombiner(callback);
for (FrameTreeNode* frame_tree_node : frame_tree_.Nodes()) {
bool is_root = frame_tree_node->parent() == nullptr;
frame_tree_node->current_frame_host()->RequestAXTreeSnapshot(
combiner->AddFrame(is_root));
}
}
void WebContentsImpl::SetTemporaryZoomLevel(double level,
bool temporary_zoom_enabled) {
SendPageMessage(new PageMsg_SetZoomLevel(
MSG_ROUTING_NONE,
temporary_zoom_enabled ? PageMsg_SetZoomLevel_Command::SET_TEMPORARY
: PageMsg_SetZoomLevel_Command::CLEAR_TEMPORARY,
level));
}
void WebContentsImpl::UpdateZoom(double level) {
// Individual frames may still ignore the new zoom level if their RenderView
// contains a plugin document or if it uses a temporary zoom level.
SendPageMessage(new PageMsg_SetZoomLevel(
MSG_ROUTING_NONE,
PageMsg_SetZoomLevel_Command::USE_CURRENT_TEMPORARY_MODE, level));
}
void WebContentsImpl::UpdateZoomIfNecessary(const std::string& scheme,
const std::string& host,
double level) {
NavigationEntry* entry = GetController().GetLastCommittedEntry();
if (!entry)
return;
GURL url = HostZoomMap::GetURLFromEntry(entry);
if (host != net::GetHostOrSpecFromURL(url) ||
(!scheme.empty() && !url.SchemeIs(scheme))) {
return;
}
UpdateZoom(level);
}
base::Closure WebContentsImpl::AddBindingSet(
const std::string& interface_name,
WebContentsBindingSet* binding_set) {
auto result =
binding_sets_.insert(std::make_pair(interface_name, binding_set));
DCHECK(result.second);
return base::Bind(&WebContentsImpl::RemoveBindingSet,
weak_factory_.GetWeakPtr(), interface_name);
}
void WebContentsImpl::UpdateDeviceScaleFactor(double device_scale_factor) {
SendPageMessage(
new PageMsg_SetDeviceScaleFactor(MSG_ROUTING_NONE, device_scale_factor));
}
void WebContentsImpl::GetScreenInfo(ScreenInfo* screen_info) {
if (GetView())
GetView()->GetScreenInfo(screen_info);
}
std::unique_ptr<WebUI> WebContentsImpl::CreateSubframeWebUI(
const GURL& url,
const std::string& frame_name) {
DCHECK(!frame_name.empty());
return CreateWebUI(url, frame_name);
}
WebUI* WebContentsImpl::GetWebUI() const {
WebUI* commited_web_ui = GetCommittedWebUI();
return commited_web_ui ? commited_web_ui
: GetRenderManager()->GetNavigatingWebUI();
}
WebUI* WebContentsImpl::GetCommittedWebUI() const {
return frame_tree_.root()->current_frame_host()->web_ui();
}
void WebContentsImpl::SetUserAgentOverride(const std::string& override) {
if (GetUserAgentOverride() == override)
return;
renderer_preferences_.user_agent_override = override;
// Send the new override string to the renderer.
RenderViewHost* host = GetRenderViewHost();
if (host)
host->SyncRendererPrefs();
// Reload the page if a load is currently in progress to avoid having
// different parts of the page loaded using different user agents.
NavigationEntry* entry = controller_.GetVisibleEntry();
if (IsLoading() && entry != NULL && entry->GetIsOverridingUserAgent())
controller_.Reload(ReloadType::BYPASSING_CACHE, true);
for (auto& observer : observers_)
observer.UserAgentOverrideSet(override);
}
const std::string& WebContentsImpl::GetUserAgentOverride() const {
return renderer_preferences_.user_agent_override;
}
void WebContentsImpl::EnableWebContentsOnlyAccessibilityMode() {
if (GetAccessibilityMode() != AccessibilityModeOff) {
for (RenderFrameHost* rfh : GetAllFrames())
ResetAccessibility(rfh);
} else {
AddAccessibilityMode(ACCESSIBILITY_MODE_WEB_CONTENTS_ONLY);
}
}
bool WebContentsImpl::IsWebContentsOnlyAccessibilityModeForTesting() const {
return accessibility_mode_ == ACCESSIBILITY_MODE_WEB_CONTENTS_ONLY;
}
bool WebContentsImpl::IsFullAccessibilityModeForTesting() const {
return accessibility_mode_ == ACCESSIBILITY_MODE_COMPLETE;
}
const PageImportanceSignals& WebContentsImpl::GetPageImportanceSignals() const {
return page_importance_signals_;
}
const base::string16& WebContentsImpl::GetTitle() const {
// Transient entries take precedence. They are used for interstitial pages
// that are shown on top of existing pages.
NavigationEntry* entry = controller_.GetTransientEntry();
if (entry) {
return entry->GetTitleForDisplay();
}
WebUI* navigating_web_ui = GetRenderManager()->GetNavigatingWebUI();
WebUI* our_web_ui = navigating_web_ui
? navigating_web_ui
: GetRenderManager()->current_frame_host()->web_ui();
if (our_web_ui) {
// Don't override the title in view source mode.
entry = controller_.GetVisibleEntry();
if (!(entry && entry->IsViewSourceMode())) {
// Give the Web UI the chance to override our title.
const base::string16& title = our_web_ui->GetOverriddenTitle();
if (!title.empty())
return title;
}
}
// We use the title for the last committed entry rather than a pending
// navigation entry. For example, when the user types in a URL, we want to
// keep the old page's title until the new load has committed and we get a new
// title.
entry = controller_.GetLastCommittedEntry();
// We make an exception for initial navigations. We only want to use the title
// from the visible entry if:
// 1. The pending entry has been explicitly assigned a title to display.
// 2. The user is doing a history navigation in a new tab (e.g., Ctrl+Back),
// which case there is a pending entry index other than -1.
//
// Otherwise, we want to stick with the last committed entry's title during
// new navigations, which have pending entries at index -1 with no title.
if (controller_.IsInitialNavigation() &&
((controller_.GetVisibleEntry() &&
!controller_.GetVisibleEntry()->GetTitle().empty()) ||
controller_.GetPendingEntryIndex() != -1)) {
entry = controller_.GetVisibleEntry();
}
if (entry) {
return entry->GetTitleForDisplay();
}
// |page_title_when_no_navigation_entry_| is finally used
// if no title cannot be retrieved.
return page_title_when_no_navigation_entry_;
}
SiteInstanceImpl* WebContentsImpl::GetSiteInstance() const {
return GetRenderManager()->current_host()->GetSiteInstance();
}
SiteInstanceImpl* WebContentsImpl::GetPendingSiteInstance() const {
RenderViewHostImpl* dest_rvh =
GetRenderManager()->pending_render_view_host() ?
GetRenderManager()->pending_render_view_host() :
GetRenderManager()->current_host();
return dest_rvh->GetSiteInstance();
}
bool WebContentsImpl::IsLoading() const {
return frame_tree_.IsLoading() &&
!(ShowingInterstitialPage() &&
GetRenderManager()->interstitial_page()->pause_throbber());
}
bool WebContentsImpl::IsLoadingToDifferentDocument() const {
return IsLoading() && is_load_to_different_document_;
}
bool WebContentsImpl::IsWaitingForResponse() const {
return waiting_for_response_ && is_load_to_different_document_;
}
const net::LoadStateWithParam& WebContentsImpl::GetLoadState() const {
return load_state_;
}
const base::string16& WebContentsImpl::GetLoadStateHost() const {
return load_state_host_;
}
uint64_t WebContentsImpl::GetUploadSize() const {
return upload_size_;
}
uint64_t WebContentsImpl::GetUploadPosition() const {
return upload_position_;
}
const std::string& WebContentsImpl::GetEncoding() const {
return canonical_encoding_;
}
void WebContentsImpl::IncrementCapturerCount(const gfx::Size& capture_size) {
DCHECK(!is_being_destroyed_);
++capturer_count_;
DVLOG(1) << "There are now " << capturer_count_
<< " capturing(s) of WebContentsImpl@" << this;
// Note: This provides a hint to upstream code to size the views optimally
// for quality (e.g., to avoid scaling).
if (!capture_size.IsEmpty() && preferred_size_for_capture_.IsEmpty()) {
preferred_size_for_capture_ = capture_size;
OnPreferredSizeChanged(preferred_size_);
}
// Ensure that all views are un-occluded before capture begins.
WasUnOccluded();
}
void WebContentsImpl::DecrementCapturerCount() {
--capturer_count_;
DVLOG(1) << "There are now " << capturer_count_
<< " capturing(s) of WebContentsImpl@" << this;
DCHECK_LE(0, capturer_count_);
if (is_being_destroyed_)
return;
if (capturer_count_ == 0) {
const gfx::Size old_size = preferred_size_for_capture_;
preferred_size_for_capture_ = gfx::Size();
OnPreferredSizeChanged(old_size);
}
if (IsHidden()) {
DVLOG(1) << "Executing delayed WasHidden().";
WasHidden();
}
}
int WebContentsImpl::GetCapturerCount() const {
return capturer_count_;
}
bool WebContentsImpl::IsAudioMuted() const {
return audio_muter_.get() && audio_muter_->is_muting();
}
void WebContentsImpl::SetAudioMuted(bool mute) {
DVLOG(1) << "SetAudioMuted(mute=" << mute << "), was " << IsAudioMuted()
<< " for WebContentsImpl@" << this;
if (mute == IsAudioMuted())
return;
if (mute) {
if (!audio_muter_)
audio_muter_.reset(new WebContentsAudioMuter(this));
audio_muter_->StartMuting();
} else {
DCHECK(audio_muter_);
audio_muter_->StopMuting();
}
for (auto& observer : observers_)
observer.DidUpdateAudioMutingState(mute);
OnAudioStateChanged(!mute && audio_stream_monitor_.IsCurrentlyAudible());
}
bool WebContentsImpl::IsConnectedToBluetoothDevice() const {
return bluetooth_connected_device_count_ > 0;
}
bool WebContentsImpl::IsCrashed() const {
return (crashed_status_ == base::TERMINATION_STATUS_PROCESS_CRASHED ||
crashed_status_ == base::TERMINATION_STATUS_ABNORMAL_TERMINATION ||
crashed_status_ == base::TERMINATION_STATUS_PROCESS_WAS_KILLED ||
#if defined(OS_CHROMEOS)
crashed_status_ ==
base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM ||
#endif
crashed_status_ == base::TERMINATION_STATUS_LAUNCH_FAILED);
}
void WebContentsImpl::SetIsCrashed(base::TerminationStatus status,
int error_code) {
if (status == crashed_status_)
return;
crashed_status_ = status;
crashed_error_code_ = error_code;
NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
}
base::TerminationStatus WebContentsImpl::GetCrashedStatus() const {
return crashed_status_;
}
int WebContentsImpl::GetCrashedErrorCode() const {
return crashed_error_code_;
}
bool WebContentsImpl::IsBeingDestroyed() const {
return is_being_destroyed_;
}
void WebContentsImpl::NotifyNavigationStateChanged(
InvalidateTypes changed_flags) {
// TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
// is fixed.
tracked_objects::ScopedTracker tracking_profile(
FROM_HERE_WITH_EXPLICIT_FUNCTION(
"466285 WebContentsImpl::NotifyNavigationStateChanged"));
// Notify the media observer of potential audibility changes.
if (changed_flags & INVALIDATE_TYPE_TAB) {
media_web_contents_observer_->MaybeUpdateAudibleState();
}
if (delegate_)
delegate_->NavigationStateChanged(this, changed_flags);
if (GetOuterWebContents())
GetOuterWebContents()->NotifyNavigationStateChanged(changed_flags);
}
void WebContentsImpl::OnAudioStateChanged(bool is_audible) {
SendPageMessage(new PageMsg_AudioStateChanged(MSG_ROUTING_NONE, is_audible));
// Notification for UI updates in response to the changed audio state.
NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
}
base::TimeTicks WebContentsImpl::GetLastActiveTime() const {
return last_active_time_;
}
void WebContentsImpl::SetLastActiveTime(base::TimeTicks last_active_time) {
last_active_time_ = last_active_time;
}
base::TimeTicks WebContentsImpl::GetLastHiddenTime() const {
return last_hidden_time_;
}
void WebContentsImpl::WasShown() {
controller_.SetActive(true);
for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
if (view) {
view->Show();
#if defined(OS_MACOSX)
view->SetActive(true);
#endif
}
}
SendPageMessage(new PageMsg_WasShown(MSG_ROUTING_NONE));
last_active_time_ = base::TimeTicks::Now();
for (auto& observer : observers_)
observer.WasShown();
should_normally_be_visible_ = true;
}
void WebContentsImpl::WasHidden() {
// If there are entities capturing screenshots or video (e.g., mirroring),
// don't activate the "disable rendering" optimization.
if (capturer_count_ == 0) {
// |GetRenderViewHost()| can be NULL if the user middle clicks a link to
// open a tab in the background, then closes the tab before selecting it.
// This is because closing the tab calls WebContentsImpl::Destroy(), which
// removes the |GetRenderViewHost()|; then when we actually destroy the
// window, OnWindowPosChanged() notices and calls WasHidden() (which
// calls us).
for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
if (view)
view->Hide();
}
SendPageMessage(new PageMsg_WasHidden(MSG_ROUTING_NONE));
}
last_hidden_time_ = base::TimeTicks::Now();
for (auto& observer : observers_)
observer.WasHidden();
should_normally_be_visible_ = false;
}
void WebContentsImpl::WasOccluded() {
if (capturer_count_ > 0)
return;
for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
if (view)
view->WasOccluded();
}
}
void WebContentsImpl::WasUnOccluded() {
for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
if (view)
view->WasUnOccluded();
}
}
bool WebContentsImpl::NeedToFireBeforeUnload() {
// TODO(creis): Should we fire even for interstitial pages?
return WillNotifyDisconnection() && !ShowingInterstitialPage() &&
!GetRenderViewHost()->SuddenTerminationAllowed();
}
void WebContentsImpl::DispatchBeforeUnload() {
bool for_cross_site_transition = false;
GetMainFrame()->DispatchBeforeUnload(for_cross_site_transition, false);
}
void WebContentsImpl::AttachToOuterWebContentsFrame(
WebContents* outer_web_contents,
RenderFrameHost* outer_contents_frame) {
CHECK(GuestMode::IsCrossProcessFrameGuest(this));
RenderFrameHostManager* render_manager = GetRenderManager();
// When the WebContents being initialized has an opener, the browser side
// Render{View,Frame}Host must be initialized and the RenderWidgetHostView
// created. This is needed because the usual initialization happens during
// the first navigation, but when attaching a new window we don't navigate
// before attaching. If the browser side is already initialized, the calls
// below will just early return.
render_manager->InitRenderView(GetRenderViewHost(), nullptr);
GetMainFrame()->Init();
if (!render_manager->GetRenderWidgetHostView())
CreateRenderWidgetHostViewForRenderManager(GetRenderViewHost());
// Create a link to our outer WebContents.
node_.ConnectToOuterWebContents(
static_cast<WebContentsImpl*>(outer_web_contents),
static_cast<RenderFrameHostImpl*>(outer_contents_frame));
DCHECK(outer_contents_frame);
// Create a proxy in top-level RenderFrameHostManager, pointing to the
// SiteInstance of the outer WebContents. The proxy will be used to send
// postMessage to the inner WebContents.
render_manager->CreateOuterDelegateProxy(
outer_contents_frame->GetSiteInstance(),
static_cast<RenderFrameHostImpl*>(outer_contents_frame));
render_manager->SetRWHViewForInnerContents(
render_manager->GetRenderWidgetHostView());
static_cast<RenderWidgetHostViewChildFrame*>(
render_manager->GetRenderWidgetHostView())
->RegisterFrameSinkId();
// At this point, we should destroy the TextInputManager which will notify all
// the RWHV in this WebContents. The RWHV in this WebContents should use the
// TextInputManager owned by the outer WebContents.
// TODO(ekaramad): Is it possible to have TextInputState before attaching to
// outer WebContents? In such a case, is this still the right way to hand off
// state tracking from inner WebContents's TextInputManager to that of the
// outer WebContent (crbug.com/609846)?
text_input_manager_.reset(nullptr);
}
void WebContentsImpl::DidChangeVisibleSecurityState() {
if (delegate_) {
delegate_->VisibleSecurityStateChanged(this);
for (auto& observer : observers_)
observer.DidChangeVisibleSecurityState();
}
}
void WebContentsImpl::Stop() {
for (FrameTreeNode* node : frame_tree_.Nodes())
node->StopLoading();
for (auto& observer : observers_)
observer.NavigationStopped();
}
WebContents* WebContentsImpl::Clone() {
// We use our current SiteInstance since the cloned entry will use it anyway.
// We pass our own opener so that the cloned page can access it if it was set
// before.
CreateParams create_params(GetBrowserContext(), GetSiteInstance());
create_params.initial_size = GetContainerBounds().size();
WebContentsImpl* tc =
CreateWithOpener(create_params, frame_tree_.root()->opener());
tc->GetController().CopyStateFrom(controller_);
for (auto& observer : observers_)
observer.DidCloneToNewWebContents(this, tc);
return tc;
}
void WebContentsImpl::Observe(int type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type) {
case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: {
RenderWidgetHost* host = Source<RenderWidgetHost>(source).ptr();
RenderWidgetHostView* view = host->GetView();
if (view == GetFullscreenRenderWidgetHostView()) {
// We cannot just call view_->RestoreFocus() here. On some platforms,
// attempting to focus the currently-invisible WebContentsView will be
// flat-out ignored. Therefore, this boolean is used to track whether
// we will request focus after the fullscreen widget has been
// destroyed.
fullscreen_widget_had_focus_at_shutdown_ = (view && view->HasFocus());
} else {
for (auto i = pending_widget_views_.begin();
i != pending_widget_views_.end(); ++i) {
if (host->GetView() == i->second) {
pending_widget_views_.erase(i);
break;
}
}
}
break;
}
default:
NOTREACHED();
}
}
WebContents* WebContentsImpl::GetWebContents() {
return this;
}
void WebContentsImpl::Init(const WebContents::CreateParams& params) {
// This is set before initializing the render manager since
// RenderFrameHostManager::Init calls back into us via its delegate to ask if
// it should be hidden.
should_normally_be_visible_ = !params.initially_hidden;
// The routing ids must either all be set or all be unset.
DCHECK((params.routing_id == MSG_ROUTING_NONE &&
params.main_frame_routing_id == MSG_ROUTING_NONE &&
params.main_frame_widget_routing_id == MSG_ROUTING_NONE) ||
(params.routing_id != MSG_ROUTING_NONE &&
params.main_frame_routing_id != MSG_ROUTING_NONE &&
params.main_frame_widget_routing_id != MSG_ROUTING_NONE));
scoped_refptr<SiteInstance> site_instance = params.site_instance;
if (!site_instance)
site_instance = SiteInstance::Create(params.browser_context);
// A main RenderFrameHost always has a RenderWidgetHost, since it is always a
// local root by definition.
// TODO(avi): Once RenderViewHostImpl has-a RenderWidgetHostImpl, it will no
// longer be necessary to eagerly grab a routing ID for the view.
// https://crbug.com/545684
int32_t view_routing_id = params.routing_id;
int32_t main_frame_widget_routing_id = params.main_frame_widget_routing_id;
if (main_frame_widget_routing_id == MSG_ROUTING_NONE) {
view_routing_id = main_frame_widget_routing_id =
site_instance->GetProcess()->GetNextRoutingID();
}
GetRenderManager()->Init(site_instance.get(), view_routing_id,
params.main_frame_routing_id,
main_frame_widget_routing_id,
params.renderer_initiated_creation);
// blink::FrameTree::setName always keeps |unique_name| empty in case of a
// main frame - let's do the same thing here.
std::string unique_name;
frame_tree_.root()->SetFrameName(params.main_frame_name, unique_name);
WebContentsViewDelegate* delegate =
GetContentClient()->browser()->GetWebContentsViewDelegate(this);
if (GuestMode::IsCrossProcessFrameGuest(this)) {
view_.reset(new WebContentsViewChildFrame(
this, delegate, &render_view_host_delegate_view_));
} else {
view_.reset(CreateWebContentsView(this, delegate,
&render_view_host_delegate_view_));
}
if (browser_plugin_guest_ && !GuestMode::IsCrossProcessFrameGuest(this)) {
view_.reset(new WebContentsViewGuest(this, browser_plugin_guest_.get(),
std::move(view_),
&render_view_host_delegate_view_));
}
CHECK(render_view_host_delegate_view_);
CHECK(view_.get());
gfx::Size initial_size = params.initial_size;
view_->CreateView(initial_size, params.context);
#if BUILDFLAG(ENABLE_PLUGINS)
plugin_content_origin_whitelist_.reset(
new PluginContentOriginWhitelist(this));
#endif
registrar_.Add(this,
NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
NotificationService::AllBrowserContextsAndSources());
screen_orientation_provider_.reset(new ScreenOrientationProvider(this));
manifest_manager_host_.reset(new ManifestManagerHost(this));
#if defined(OS_ANDROID)
date_time_chooser_.reset(new DateTimeChooserAndroid());
#endif
// BrowserPluginGuest::Init needs to be called after this WebContents has
// a RenderWidgetHostViewGuest. That is, |view_->CreateView| above.
if (browser_plugin_guest_)
browser_plugin_guest_->Init();
for (size_t i = 0; i < g_created_callbacks.Get().size(); i++)
g_created_callbacks.Get().at(i).Run(this);
// If the WebContents creation was renderer-initiated, it means that the
// corresponding RenderView and main RenderFrame have already been created.
// Ensure observers are notified about this.
if (params.renderer_initiated_creation) {
GetRenderViewHost()->GetWidget()->set_renderer_initialized(true);
RenderViewCreated(GetRenderViewHost());
GetRenderManager()->current_frame_host()->SetRenderFrameCreated(true);
}
// Create the renderer process in advance if requested.
if (params.initialize_renderer) {
if (!GetRenderManager()->current_frame_host()->IsRenderFrameLive()) {
GetRenderManager()->InitRenderView(GetRenderViewHost(), nullptr);
}
}
// Ensure that observers are notified of the creation of this WebContents's
// main RenderFrameHost. It must be done here for main frames, since the
// NotifySwappedFromRenderManager expects view_ to already be created and that
// happens after RenderFrameHostManager::Init.
NotifySwappedFromRenderManager(
nullptr, GetRenderManager()->current_frame_host(), true);
}
void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl* web_contents) {
RemoveDestructionObserver(web_contents);
// Clear a pending contents that has been closed before being shown.
for (auto iter = pending_contents_.begin(); iter != pending_contents_.end();
++iter) {
if (iter->second != web_contents)
continue;
pending_contents_.erase(iter);
return;
}
NOTREACHED();
}
void WebContentsImpl::AddDestructionObserver(WebContentsImpl* web_contents) {
if (!ContainsKey(destruction_observers_, web_contents)) {
destruction_observers_[web_contents] =
base::MakeUnique<DestructionObserver>(this, web_contents);
}
}
void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl* web_contents) {
destruction_observers_.erase(web_contents);
}
void WebContentsImpl::AddObserver(WebContentsObserver* observer) {
observers_.AddObserver(observer);
}
void WebContentsImpl::RemoveObserver(WebContentsObserver* observer) {
observers_.RemoveObserver(observer);
}
std::set<RenderWidgetHostView*>
WebContentsImpl::GetRenderWidgetHostViewsInTree() {
std::set<RenderWidgetHostView*> set;
if (ShowingInterstitialPage()) {
set.insert(GetRenderWidgetHostView());
} else {
for (RenderFrameHost* rfh : GetAllFrames()) {
RenderWidgetHostView* rwhv = static_cast<RenderFrameHostImpl*>(rfh)
->frame_tree_node()
->render_manager()
->GetRenderWidgetHostView();
set.insert(rwhv);
}
}
return set;
}
void WebContentsImpl::Activate() {
if (delegate_)
delegate_->ActivateContents(this);
}
void WebContentsImpl::LostCapture(RenderWidgetHostImpl* render_widget_host) {
if (!RenderViewHostImpl::From(render_widget_host))
return;
if (delegate_)
delegate_->LostCapture();
}
void WebContentsImpl::RenderWidgetCreated(
RenderWidgetHostImpl* render_widget_host) {
created_widgets_.insert(render_widget_host);
}
void WebContentsImpl::RenderWidgetDeleted(
RenderWidgetHostImpl* render_widget_host) {
// Note that |is_being_destroyed_| can be true at this point as
// ~WebContentsImpl() calls RFHM::ClearRFHsPendingShutdown(), which might lead
// us here.
created_widgets_.erase(render_widget_host);
if (is_being_destroyed_)
return;
if (render_widget_host &&
render_widget_host->GetRoutingID() == fullscreen_widget_routing_id_ &&
render_widget_host->GetProcess()->GetID() ==
fullscreen_widget_process_id_) {
if (delegate_ && delegate_->EmbedsFullscreenWidget())
delegate_->ExitFullscreenModeForTab(this);
for (auto& observer : observers_)
observer.DidDestroyFullscreenWidget();
fullscreen_widget_process_id_ = ChildProcessHost::kInvalidUniqueID;
fullscreen_widget_routing_id_ = MSG_ROUTING_NONE;
if (fullscreen_widget_had_focus_at_shutdown_)
view_->RestoreFocus();
}
if (mouse_lock_widget_)
LostMouseLock(mouse_lock_widget_);
}
void WebContentsImpl::RenderWidgetGotFocus(
RenderWidgetHostImpl* render_widget_host) {
// Notify the observers if an embedded fullscreen widget was focused.
if (delegate_ && render_widget_host && delegate_->EmbedsFullscreenWidget() &&
render_widget_host->GetView() == GetFullscreenRenderWidgetHostView()) {
NotifyWebContentsFocused();
}
}
void WebContentsImpl::RenderWidgetWasResized(
RenderWidgetHostImpl* render_widget_host,
bool width_changed) {
RenderFrameHostImpl* rfh = GetMainFrame();
if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
return;
for (auto& observer : observers_)
observer.MainFrameWasResized(width_changed);
}
void WebContentsImpl::ScreenInfoChanged() {
if (browser_plugin_embedder_)
browser_plugin_embedder_->ScreenInfoChanged();
}
bool WebContentsImpl::PreHandleKeyboardEvent(
const NativeWebKeyboardEvent& event,
bool* is_keyboard_shortcut) {
return delegate_ &&
delegate_->PreHandleKeyboardEvent(this, event, is_keyboard_shortcut);
}
void WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
if (browser_plugin_embedder_ &&
browser_plugin_embedder_->HandleKeyboardEvent(event)) {
return;
}
if (delegate_)
delegate_->HandleKeyboardEvent(this, event);
}
bool WebContentsImpl::HandleWheelEvent(
const blink::WebMouseWheelEvent& event) {
#if !defined(OS_MACOSX)
// On platforms other than Mac, control+mousewheel may change zoom. On Mac,
// this isn't done for two reasons:
// -the OS already has a gesture to do this through pinch-zoom
// -if a user starts an inertial scroll, let's go, and presses control
// (i.e. control+tab) then the OS's buffered scroll events will come in
// with control key set which isn't what the user wants
if (delegate_ && event.wheelTicksY &&
!ui::WebInputEventTraits::CanCauseScroll(event)) {
// Count only integer cumulative scrolls as zoom events; this handles
// smooth scroll and regular scroll device behavior.
zoom_scroll_remainder_ += event.wheelTicksY;
int whole_zoom_scroll_remainder_ = std::lround(zoom_scroll_remainder_);
zoom_scroll_remainder_ -= whole_zoom_scroll_remainder_;
if (whole_zoom_scroll_remainder_ != 0) {
delegate_->ContentsZoomChange(whole_zoom_scroll_remainder_ > 0);
}
return true;
}
#endif
return false;
}
bool WebContentsImpl::PreHandleGestureEvent(
const blink::WebGestureEvent& event) {
return delegate_ && delegate_->PreHandleGestureEvent(this, event);
}
RenderWidgetHostInputEventRouter* WebContentsImpl::GetInputEventRouter() {
if (!is_being_destroyed_ && GetOuterWebContents())
return GetOuterWebContents()->GetInputEventRouter();
if (!rwh_input_event_router_.get() && !is_being_destroyed_)
rwh_input_event_router_.reset(new RenderWidgetHostInputEventRouter);
return rwh_input_event_router_.get();
}
void WebContentsImpl::ReplicatePageFocus(bool is_focused) {
// Focus loss may occur while this WebContents is being destroyed. Don't
// send the message in this case, as the main frame's RenderFrameHost and
// other state has already been cleared.
if (is_being_destroyed_)
return;
frame_tree_.ReplicatePageFocus(is_focused);
}
RenderWidgetHostImpl* WebContentsImpl::GetFocusedRenderWidgetHost(
RenderWidgetHostImpl* receiving_widget) {
if (!SiteIsolationPolicy::AreCrossProcessFramesPossible())
return receiving_widget;
// Events for widgets other than the main frame (e.g., popup menus) should be
// forwarded directly to the widget they arrived on.
if (receiving_widget != GetMainFrame()->GetRenderWidgetHost())
return receiving_widget;
FrameTreeNode* focused_frame =
GetFocusedWebContents()->frame_tree_.GetFocusedFrame();
if (!focused_frame)
return receiving_widget;
// The view may be null if a subframe's renderer process has crashed while
// the subframe has focus. Drop the event in that case. Do not give
// it to the main frame, so that the user doesn't unexpectedly type into the
// wrong frame if a focused subframe renderer crashes while they type.
RenderWidgetHostView* view = focused_frame->current_frame_host()->GetView();
if (!view)
return nullptr;
return RenderWidgetHostImpl::From(view->GetRenderWidgetHost());
}
RenderWidgetHostImpl* WebContentsImpl::GetRenderWidgetHostWithPageFocus() {
return GetFocusedWebContents()->GetMainFrame()->GetRenderWidgetHost();
}
void WebContentsImpl::EnterFullscreenMode(const GURL& origin) {
// This method is being called to enter renderer-initiated fullscreen mode.
// Make sure any existing fullscreen widget is shut down first.
RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
if (widget_view) {
RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())
->ShutdownAndDestroyWidget(true);
}
if (delegate_)
delegate_->EnterFullscreenModeForTab(this, origin);
for (auto& observer : observers_)
observer.DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab(), false);
}
void WebContentsImpl::ExitFullscreenMode(bool will_cause_resize) {
// This method is being called to leave renderer-initiated fullscreen mode.
// Make sure any existing fullscreen widget is shut down first.
RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
if (widget_view) {
RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())
->ShutdownAndDestroyWidget(true);
}
#if defined(OS_ANDROID)
ContentVideoView* video_view = ContentVideoView::GetInstance();
if (video_view != NULL)
video_view->ExitFullscreen();
#endif
if (delegate_)
delegate_->ExitFullscreenModeForTab(this);
// The fullscreen state is communicated to the renderer through a resize
// message. If the change in fullscreen state doesn't cause a view resize
// then we must ensure web contents exit the fullscreen state by explicitly
// sending a resize message. This is required for the situation of the browser
// moving the view into a "browser fullscreen" state and then the contents
// entering "tab fullscreen". Exiting the contents "tab fullscreen" then won't
// have the side effect of the view resizing, hence the explicit call here is
// required.
if (!will_cause_resize) {
if (RenderWidgetHostView* rwhv = GetRenderWidgetHostView()) {
if (RenderWidgetHost* render_widget_host = rwhv->GetRenderWidgetHost())
render_widget_host->WasResized();
}
}
for (auto& observer : observers_) {
observer.DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab(),
will_cause_resize);
}
}
bool WebContentsImpl::IsFullscreenForCurrentTab() const {
return delegate_ ? delegate_->IsFullscreenForTabOrPending(this) : false;
}
bool WebContentsImpl::IsFullscreen() {
return IsFullscreenForCurrentTab();
}
blink::WebDisplayMode WebContentsImpl::GetDisplayMode(
RenderWidgetHostImpl* render_widget_host) const {
if (!RenderViewHostImpl::From(render_widget_host))
return blink::WebDisplayModeBrowser;
return delegate_ ? delegate_->GetDisplayMode(this)
: blink::WebDisplayModeBrowser;
}
void WebContentsImpl::RequestToLockMouse(
RenderWidgetHostImpl* render_widget_host,
bool user_gesture,
bool last_unlocked_by_target,
bool privileged) {
for (WebContentsImpl* current = this; current;
current = current->GetOuterWebContents()) {
if (current->mouse_lock_widget_) {
render_widget_host->GotResponseToLockMouseRequest(false);
return;
}
}
if (privileged) {
DCHECK(!GetOuterWebContents());
mouse_lock_widget_ = render_widget_host;
render_widget_host->GotResponseToLockMouseRequest(true);
return;
}
bool widget_in_frame_tree = false;
for (FrameTreeNode* node : frame_tree_.Nodes()) {
if (node->current_frame_host()->GetRenderWidgetHost() ==
render_widget_host) {
widget_in_frame_tree = true;
break;
}
}
if (widget_in_frame_tree && delegate_) {
for (WebContentsImpl* current = this; current;
current = current->GetOuterWebContents()) {
current->mouse_lock_widget_ = render_widget_host;
}
delegate_->RequestToLockMouse(this, user_gesture, last_unlocked_by_target);
} else {
render_widget_host->GotResponseToLockMouseRequest(false);
}
}
void WebContentsImpl::LostMouseLock(RenderWidgetHostImpl* render_widget_host) {
CHECK(mouse_lock_widget_);
if (mouse_lock_widget_->delegate()->GetAsWebContents() != this)
return mouse_lock_widget_->delegate()->LostMouseLock(render_widget_host);
mouse_lock_widget_->SendMouseLockLost();
for (WebContentsImpl* current = this; current;
current = current->GetOuterWebContents()) {
current->mouse_lock_widget_ = nullptr;
}
if (delegate_)
delegate_->LostMouseLock();
}
bool WebContentsImpl::HasMouseLock(RenderWidgetHostImpl* render_widget_host) {
// To verify if the mouse is locked, the mouse_lock_widget_ needs to be
// assigned to the widget that requested the mouse lock, and the top-level
// platform RenderWidgetHostView needs to hold the mouse lock from the OS.
return mouse_lock_widget_ == render_widget_host &&
GetTopLevelRenderWidgetHostView()->IsMouseLocked();
}
RenderWidgetHostImpl* WebContentsImpl::GetMouseLockWidget() {
if (GetTopLevelRenderWidgetHostView()->IsMouseLocked())
return mouse_lock_widget_;
return nullptr;
}
void WebContentsImpl::OnRenderFrameProxyVisibilityChanged(bool visible) {
if (visible && !GetOuterWebContents()->IsHidden())
WasShown();
else if (!visible)
WasHidden();
}
void WebContentsImpl::CreateNewWindow(
SiteInstance* source_site_instance,
int32_t render_view_route_id,
int32_t main_frame_route_id,
int32_t main_frame_widget_route_id,
const mojom::CreateNewWindowParams& params,
SessionStorageNamespace* session_storage_namespace) {
// We should have zero valid routing ids, or three valid routing IDs.
DCHECK_EQ((render_view_route_id == MSG_ROUTING_NONE),
(main_frame_route_id == MSG_ROUTING_NONE));
DCHECK_EQ((render_view_route_id == MSG_ROUTING_NONE),
(main_frame_widget_route_id == MSG_ROUTING_NONE));
int render_process_id = source_site_instance->GetProcess()->GetID();
// The route IDs passed into this function can be trusted not to already be in
// use; they were allocated by the RenderWidgetHelper on the IO thread.
DCHECK(!RenderFrameHostImpl::FromID(render_process_id, main_frame_route_id));
// We usually create the new window in the same BrowsingInstance (group of
// script-related windows), by passing in the current SiteInstance. However,
// if the opener is being suppressed (in a non-guest), we create a new
// SiteInstance in its own BrowsingInstance.
bool is_guest = BrowserPluginGuest::IsGuest(this);
// If the opener is to be suppressed, the new window can be in any process.
// Since routing ids are process specific, we must not have one passed in
// as argument here.
DCHECK(!params.opener_suppressed || render_view_route_id == MSG_ROUTING_NONE);
scoped_refptr<SiteInstance> site_instance =
params.opener_suppressed && !is_guest
? SiteInstance::CreateForURL(GetBrowserContext(), params.target_url)
: source_site_instance;
// We must assign the SessionStorageNamespace before calling Init().
//
// http://crbug.com/142685
const std::string& partition_id =
GetContentClient()->browser()->
GetStoragePartitionIdForSite(GetBrowserContext(),
site_instance->GetSiteURL());
StoragePartition* partition = BrowserContext::GetStoragePartition(
GetBrowserContext(), site_instance.get());
DOMStorageContextWrapper* dom_storage_context =
static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
SessionStorageNamespaceImpl* session_storage_namespace_impl =
static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
if (delegate_ &&
!delegate_->ShouldCreateWebContents(
this, source_site_instance, render_view_route_id, main_frame_route_id,
main_frame_widget_route_id, params.window_container_type,
params.opener_url, params.frame_name, params.target_url, partition_id,
session_storage_namespace)) {
// Note: even though we're not creating a WebContents here, it could have
// been created by the embedder so ensure that the RenderFrameHost is
// properly initialized.
// It's safe to only target the frame because the render process will not
// have a chance to create more frames at this point.
RenderFrameHostImpl* rfh =
RenderFrameHostImpl::FromID(render_process_id, main_frame_route_id);
if (rfh) {
DCHECK(rfh->IsRenderFrameLive());
rfh->Init();
}
return;
}
// Create the new web contents. This will automatically create the new
// WebContentsView. In the future, we may want to create the view separately.
CreateParams create_params(GetBrowserContext(), site_instance.get());
create_params.routing_id = render_view_route_id;
create_params.main_frame_routing_id = main_frame_route_id;
create_params.main_frame_widget_routing_id = main_frame_widget_route_id;
create_params.main_frame_name = params.frame_name;
create_params.opener_render_process_id = render_process_id;
create_params.opener_render_frame_id = params.opener_render_frame_id;
create_params.opener_suppressed = params.opener_suppressed;
if (params.disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB)
create_params.initially_hidden = true;
create_params.renderer_initiated_creation =
main_frame_route_id != MSG_ROUTING_NONE;
WebContentsImpl* new_contents = NULL;
if (!is_guest) {
create_params.context = view_->GetNativeView();
create_params.initial_size = GetContainerBounds().size();
new_contents = static_cast<WebContentsImpl*>(
WebContents::Create(create_params));
} else {
new_contents = GetBrowserPluginGuest()->CreateNewGuestWindow(create_params);
}
new_contents->GetController().SetSessionStorageNamespace(
partition_id,
session_storage_namespace);
// If the new frame has a name, make sure any SiteInstances that can find
// this named frame have proxies for it. Must be called after
// SetSessionStorageNamespace, since this calls CreateRenderView, which uses
// GetSessionStorageNamespace.
if (!params.frame_name.empty())
new_contents->GetRenderManager()->CreateProxiesForNewNamedFrame();
// Save the window for later if we're not suppressing the opener (since it
// will be shown immediately).
if (!params.opener_suppressed) {
if (!is_guest) {
WebContentsView* new_view = new_contents->view_.get();
// TODO(brettw): It seems bogus that we have to call this function on the
// newly created object and give it one of its own member variables.
new_view->CreateViewForWidget(
new_contents->GetRenderViewHost()->GetWidget(), false);
}
// Save the created window associated with the route so we can show it
// later.
DCHECK_NE(MSG_ROUTING_NONE, main_frame_widget_route_id);
pending_contents_[std::make_pair(
render_process_id, main_frame_widget_route_id)] = new_contents;
AddDestructionObserver(new_contents);
}
if (delegate_) {
delegate_->WebContentsCreated(
this, render_process_id, params.opener_render_frame_id,
params.frame_name, params.target_url, new_contents);
}
RenderFrameHost* source_render_frame_host =
RenderFrameHost::FromID(render_process_id, params.opener_render_frame_id);
if (source_render_frame_host) {
for (auto& observer : observers_) {
observer.DidOpenRequestedURL(new_contents, source_render_frame_host,
params.target_url, params.referrer,
params.disposition, ui::PAGE_TRANSITION_LINK,
false, // started_from_context_menu
true); // renderer_initiated
}
}
if (params.opener_suppressed) {
// When the opener is suppressed, the original renderer cannot access the
// new window. As a result, we need to show and navigate the window here.
bool was_blocked = false;
if (delegate_) {
gfx::Rect initial_rect;
base::WeakPtr<WebContentsImpl> weak_new_contents =
new_contents->weak_factory_.GetWeakPtr();
delegate_->AddNewContents(
this, new_contents, params.disposition, initial_rect,
params.user_gesture, &was_blocked);
if (!weak_new_contents)
return; // The delegate deleted |new_contents| during AddNewContents().
}
if (!was_blocked) {
OpenURLParams open_params(params.target_url, params.referrer,
WindowOpenDisposition::CURRENT_TAB,
ui::PAGE_TRANSITION_LINK,
true /* is_renderer_initiated */);
open_params.user_gesture = params.user_gesture;
if (delegate_ && !is_guest &&
!delegate_->ShouldResumeRequestsForCreatedWindow()) {
// We are in asynchronous add new contents path, delay opening url
new_contents->delayed_open_url_params_.reset(
new OpenURLParams(open_params));
} else {
new_contents->OpenURL(open_params);
}
}
}
}
void WebContentsImpl::CreateNewWidget(int32_t render_process_id,
int32_t route_id,
blink::WebPopupType popup_type) {
CreateNewWidget(render_process_id, route_id, false, popup_type);
}
void WebContentsImpl::CreateNewFullscreenWidget(int32_t render_process_id,
int32_t route_id) {
CreateNewWidget(render_process_id, route_id, true, blink::WebPopupTypeNone);
}
void WebContentsImpl::CreateNewWidget(int32_t render_process_id,
int32_t route_id,
bool is_fullscreen,
blink::WebPopupType popup_type) {
RenderProcessHost* process = RenderProcessHost::FromID(render_process_id);
// A message to create a new widget can only come from an active process for
// this WebContentsImpl instance. If any other process sends the request,
// it is invalid and the process must be terminated.
if (!HasMatchingProcess(&frame_tree_, render_process_id)) {
base::ProcessHandle process_handle = process->GetHandle();
if (process_handle != base::kNullProcessHandle) {
RecordAction(
base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWidget"));
process->Shutdown(RESULT_CODE_KILLED, false);
}
return;
}
RenderWidgetHostImpl* widget_host =
new RenderWidgetHostImpl(this, process, route_id, IsHidden());
RenderWidgetHostViewBase* widget_view =
static_cast<RenderWidgetHostViewBase*>(
view_->CreateViewForPopupWidget(widget_host));
if (!widget_view)
return;
if (!is_fullscreen) {
// Popups should not get activated.
widget_view->SetPopupType(popup_type);
}
// Save the created widget associated with the route so we can show it later.
pending_widget_views_[std::make_pair(render_process_id, route_id)] =
widget_view;
#if defined(OS_MACOSX)
// A RenderWidgetHostViewMac has lifetime scoped to the view. We'll retain it
// to allow it to survive the trip without being hosted.
base::mac::NSObjectRetain(widget_view->GetNativeView());
#endif
}
void WebContentsImpl::ShowCreatedWindow(int process_id,
int main_frame_widget_route_id,
WindowOpenDisposition disposition,
const gfx::Rect& initial_rect,
bool user_gesture) {
WebContentsImpl* popup =
GetCreatedWindow(process_id, main_frame_widget_route_id);
if (popup) {
WebContentsDelegate* delegate = GetDelegate();
popup->is_resume_pending_ = true;
if (!delegate || delegate->ShouldResumeRequestsForCreatedWindow())
popup->ResumeLoadingCreatedWebContents();
if (delegate) {
base::WeakPtr<WebContentsImpl> weak_popup =
popup->weak_factory_.GetWeakPtr();
delegate->AddNewContents(this, popup, disposition, initial_rect,
user_gesture, nullptr);
if (!weak_popup)
return; // The delegate deleted |popup| during AddNewContents().
}
RenderWidgetHostImpl* rwh = popup->GetMainFrame()->GetRenderWidgetHost();
DCHECK_EQ(main_frame_widget_route_id, rwh->GetRoutingID());
rwh->Send(new ViewMsg_Move_ACK(rwh->GetRoutingID()));
}
}
void WebContentsImpl::ShowCreatedWidget(int process_id,
int route_id,
const gfx::Rect& initial_rect) {
ShowCreatedWidget(process_id, route_id, false, initial_rect);
}
void WebContentsImpl::ShowCreatedFullscreenWidget(int process_id,
int route_id) {
ShowCreatedWidget(process_id, route_id, true, gfx::Rect());
}
void WebContentsImpl::ShowCreatedWidget(int process_id,
int route_id,
bool is_fullscreen,
const gfx::Rect& initial_rect) {
RenderWidgetHostViewBase* widget_host_view =
static_cast<RenderWidgetHostViewBase*>(
GetCreatedWidget(process_id, route_id));
if (!widget_host_view)
return;
RenderWidgetHostView* view = NULL;
if (GetOuterWebContents()) {
view = GetOuterWebContents()->GetRenderWidgetHostView();
} else {
view = GetRenderWidgetHostView();
}
if (is_fullscreen) {
DCHECK_EQ(MSG_ROUTING_NONE, fullscreen_widget_routing_id_);
view_->StoreFocus();
fullscreen_widget_process_id_ =
widget_host_view->GetRenderWidgetHost()->GetProcess()->GetID();
fullscreen_widget_routing_id_ = route_id;
if (delegate_ && delegate_->EmbedsFullscreenWidget()) {
widget_host_view->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
delegate_->EnterFullscreenModeForTab(this, GURL());
} else {
widget_host_view->InitAsFullscreen(view);
}
for (auto& observer : observers_)
observer.DidShowFullscreenWidget();
if (!widget_host_view->HasFocus())
widget_host_view->Focus();
} else {
widget_host_view->InitAsPopup(view, initial_rect);
}
RenderWidgetHostImpl* render_widget_host_impl =
RenderWidgetHostImpl::From(widget_host_view->GetRenderWidgetHost());
render_widget_host_impl->Init();
// Only allow privileged mouse lock for fullscreen render widget, which is
// used to implement Pepper Flash fullscreen.
render_widget_host_impl->set_allow_privileged_mouse_lock(is_fullscreen);
#if defined(OS_MACOSX)
// A RenderWidgetHostViewMac has lifetime scoped to the view. Now that it's
// properly embedded (or purposefully ignored) we can release the retain we
// took in CreateNewWidget().
base::mac::NSObjectRelease(widget_host_view->GetNativeView());
#endif
}
WebContentsImpl* WebContentsImpl::GetCreatedWindow(
int process_id,
int main_frame_widget_route_id) {
auto key = std::make_pair(process_id, main_frame_widget_route_id);
auto iter = pending_contents_.find(key);
// Certain systems can block the creation of new windows. If we didn't succeed
// in creating one, just return NULL.
if (iter == pending_contents_.end())
return nullptr;
WebContentsImpl* new_contents = iter->second;
pending_contents_.erase(key);
RemoveDestructionObserver(new_contents);
// Don't initialize the guest WebContents immediately.
if (BrowserPluginGuest::IsGuest(new_contents))
return new_contents;
if (!new_contents->GetMainFrame()->GetProcess()->HasConnection() ||
!new_contents->GetMainFrame()->GetView()) {
// TODO(nick): http://crbug.com/674318 -- Who deletes |new_contents|?
return nullptr;
}
return new_contents;
}
RenderWidgetHostView* WebContentsImpl::GetCreatedWidget(int process_id,
int route_id) {
auto iter = pending_widget_views_.find(std::make_pair(process_id, route_id));
if (iter == pending_widget_views_.end()) {
DCHECK(false);
return nullptr;
}
RenderWidgetHostView* widget_host_view = iter->second;
pending_widget_views_.erase(std::make_pair(process_id, route_id));
RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
if (!widget_host->GetProcess()->HasConnection()) {
// The view has gone away or the renderer crashed. Nothing to do.
return nullptr;
}
return widget_host_view;
}
void WebContentsImpl::RequestMediaAccessPermission(
const MediaStreamRequest& request,
const MediaResponseCallback& callback) {
if (delegate_) {
delegate_->RequestMediaAccessPermission(this, request, callback);
} else {
callback.Run(MediaStreamDevices(), MEDIA_DEVICE_FAILED_DUE_TO_SHUTDOWN,
std::unique_ptr<MediaStreamUI>());
}
}
bool WebContentsImpl::CheckMediaAccessPermission(const GURL& security_origin,
MediaStreamType type) {
DCHECK(type == MEDIA_DEVICE_AUDIO_CAPTURE ||
type == MEDIA_DEVICE_VIDEO_CAPTURE);
return delegate_ &&
delegate_->CheckMediaAccessPermission(this, security_origin, type);
}
std::string WebContentsImpl::GetDefaultMediaDeviceID(MediaStreamType type) {
if (!delegate_)
return std::string();
return delegate_->GetDefaultMediaDeviceID(this, type);
}
SessionStorageNamespace* WebContentsImpl::GetSessionStorageNamespace(
SiteInstance* instance) {
return controller_.GetSessionStorageNamespace(instance);
}
SessionStorageNamespaceMap WebContentsImpl::GetSessionStorageNamespaceMap() {
return controller_.GetSessionStorageNamespaceMap();
}
FrameTree* WebContentsImpl::GetFrameTree() {
return &frame_tree_;
}
void WebContentsImpl::SetIsVirtualKeyboardRequested(bool requested) {
virtual_keyboard_requested_ = requested;
}
bool WebContentsImpl::IsVirtualKeyboardRequested() {
return virtual_keyboard_requested_;
}
bool WebContentsImpl::IsOverridingUserAgent() {
return GetController().GetVisibleEntry() &&
GetController().GetVisibleEntry()->GetIsOverridingUserAgent();
}
bool WebContentsImpl::IsJavaScriptDialogShowing() const {
return is_showing_javascript_dialog_;
}
bool WebContentsImpl::ShouldIgnoreUnresponsiveRenderer() {
// Ignore unresponsive renderers if the debugger is attached to them since the
// unresponsiveness might be a result of the renderer sitting on a breakpoint.
//
// TODO(pfeldman): Fix this to only return true if the renderer is *actually*
// sitting on a breakpoint. https://crbug.com/684202
return DevToolsAgentHost::IsDebuggerAttached(this);
}
AccessibilityMode WebContentsImpl::GetAccessibilityMode() const {
return accessibility_mode_;
}
void WebContentsImpl::AccessibilityEventReceived(
const std::vector<AXEventNotificationDetails>& details) {
for (auto& observer : observers_)
observer.AccessibilityEventReceived(details);
}
void WebContentsImpl::AccessibilityLocationChangesReceived(
const std::vector<AXLocationChangeNotificationDetails>& details) {
for (auto& observer : observers_)
observer.AccessibilityLocationChangesReceived(details);
}
RenderFrameHost* WebContentsImpl::GetGuestByInstanceID(
RenderFrameHost* render_frame_host,
int browser_plugin_instance_id) {
BrowserPluginGuestManager* guest_manager =
GetBrowserContext()->GetGuestManager();
if (!guest_manager)
return nullptr;
WebContents* guest = guest_manager->GetGuestByInstanceID(
render_frame_host->GetProcess()->GetID(), browser_plugin_instance_id);
if (!guest)
return nullptr;
return guest->GetMainFrame();
}
device::GeolocationServiceContext*
WebContentsImpl::GetGeolocationServiceContext() {
return geolocation_service_context_.get();
}
device::WakeLockServiceContext* WebContentsImpl::GetWakeLockServiceContext() {
return wake_lock_service_context_.get();
}
void WebContentsImpl::OnShowValidationMessage(
RenderViewHostImpl* source,
const gfx::Rect& anchor_in_root_view,
const base::string16& main_text,
const base::string16& sub_text) {
// TODO(nick): Should we consider |source| here or pass it to the delegate?
if (delegate_)
delegate_->ShowValidationMessage(
this, anchor_in_root_view, main_text, sub_text);
}
void WebContentsImpl::OnHideValidationMessage(RenderViewHostImpl* source) {
// TODO(nick): Should we consider |source| here or pass it to the delegate?
if (delegate_)
delegate_->HideValidationMessage(this);
}
void WebContentsImpl::OnMoveValidationMessage(
RenderViewHostImpl* source,
const gfx::Rect& anchor_in_root_view) {
// TODO(nick): Should we consider |source| here or pass it to the delegate?
if (delegate_)
delegate_->MoveValidationMessage(this, anchor_in_root_view);
}
void WebContentsImpl::SendScreenRects() {
for (FrameTreeNode* node : frame_tree_.Nodes()) {
if (node->current_frame_host()->is_local_root())
node->current_frame_host()->GetRenderWidgetHost()->SendScreenRects();
}
RenderWidgetHostViewBase* rwhv =
static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
if (rwhv) {
SendPageMessage(new PageMsg_UpdateWindowScreenRect(
MSG_ROUTING_NONE, rwhv->GetBoundsInRootWindow()));
}
if (browser_plugin_embedder_ && !is_being_destroyed_)
browser_plugin_embedder_->DidSendScreenRects();
}
void WebContentsImpl::OnFirstPaintAfterLoad(
RenderWidgetHostImpl* render_widget_host) {
for (auto& observer : observers_)
observer.DidFirstPaintAfterLoad(render_widget_host);
}
TextInputManager* WebContentsImpl::GetTextInputManager() {
if (GetOuterWebContents())
return GetOuterWebContents()->GetTextInputManager();
if (!text_input_manager_)
text_input_manager_.reset(new TextInputManager());
return text_input_manager_.get();
}
bool WebContentsImpl::OnUpdateDragCursor() {
if (browser_plugin_embedder_)
return browser_plugin_embedder_->OnUpdateDragCursor();
return false;
}
BrowserAccessibilityManager*
WebContentsImpl::GetRootBrowserAccessibilityManager() {
RenderFrameHostImpl* rfh = GetMainFrame();
return rfh ? rfh->browser_accessibility_manager() : nullptr;
}
BrowserAccessibilityManager*
WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
RenderFrameHostImpl* rfh = GetMainFrame();
return rfh ? rfh->GetOrCreateBrowserAccessibilityManager() : nullptr;
}
void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point& extent) {
RenderFrameHost* focused_frame = GetFocusedFrame();
if (!focused_frame)
return;
focused_frame->Send(new InputMsg_MoveRangeSelectionExtent(
focused_frame->GetRoutingID(), extent));
}
void WebContentsImpl::SelectRange(const gfx::Point& base,
const gfx::Point& extent) {
RenderFrameHost* focused_frame = GetFocusedFrame();
if (!focused_frame)
return;
focused_frame->Send(
new InputMsg_SelectRange(focused_frame->GetRoutingID(), base, extent));
}
void WebContentsImpl::AdjustSelectionByCharacterOffset(int start_adjust,
int end_adjust) {
RenderFrameHost* focused_frame = GetFocusedFrame();
if (!focused_frame)
return;
focused_frame->Send(new InputMsg_AdjustSelectionByCharacterOffset(
focused_frame->GetRoutingID(), start_adjust, end_adjust));
}
void WebContentsImpl::UpdatePreferredSize(const gfx::Size& pref_size) {
const gfx::Size old_size = GetPreferredSize();
preferred_size_ = pref_size;
OnPreferredSizeChanged(old_size);
}
void WebContentsImpl::ResizeDueToAutoResize(
RenderWidgetHostImpl* render_widget_host,
const gfx::Size& new_size) {
if (render_widget_host != GetRenderViewHost()->GetWidget())
return;
if (delegate_)
delegate_->ResizeDueToAutoResize(this, new_size);
}
WebContents* WebContentsImpl::OpenURL(const OpenURLParams& params) {
if (!delegate_)
return NULL;
WebContents* new_contents = delegate_->OpenURLFromTab(this, params);
RenderFrameHost* source_render_frame_host = RenderFrameHost::FromID(
params.source_render_process_id, params.source_render_frame_id);
if (source_render_frame_host && params.source_site_instance) {
CHECK_EQ(source_render_frame_host->GetSiteInstance(),
params.source_site_instance.get());
}
if (new_contents && source_render_frame_host && new_contents != this) {
for (auto& observer : observers_) {
observer.DidOpenRequestedURL(new_contents, source_render_frame_host,
params.url, params.referrer,
params.disposition, params.transition,
params.started_from_context_menu, false);
}
}
return new_contents;
}
bool WebContentsImpl::Send(IPC::Message* message) {
if (!GetRenderViewHost()) {
delete message;
return false;
}
return GetRenderViewHost()->Send(message);
}
void WebContentsImpl::RenderFrameForInterstitialPageCreated(
RenderFrameHost* render_frame_host) {
for (auto& observer : observers_)
observer.RenderFrameForInterstitialPageCreated(render_frame_host);
}
void WebContentsImpl::AttachInterstitialPage(
InterstitialPageImpl* interstitial_page) {
DCHECK(interstitial_page);
GetRenderManager()->set_interstitial_page(interstitial_page);
// Cancel any visible dialogs so that they don't interfere with the
// interstitial.
CancelActiveAndPendingDialogs();
for (auto& observer : observers_)
observer.DidAttachInterstitialPage();
// Stop the throbber if needed while the interstitial page is shown.
if (frame_tree_.IsLoading())
LoadingStateChanged(true, true, nullptr);
}
void WebContentsImpl::DidProceedOnInterstitial() {
// The interstitial page should no longer be pausing the throbber.
DCHECK(!(ShowingInterstitialPage() &&
GetRenderManager()->interstitial_page()->pause_throbber()));
// Restart the throbber now that the interstitial page no longer pauses it.
if (ShowingInterstitialPage() && frame_tree_.IsLoading())
LoadingStateChanged(true, true, nullptr);
}
void WebContentsImpl::DetachInterstitialPage() {
bool interstitial_pausing_throbber =
ShowingInterstitialPage() &&
GetRenderManager()->interstitial_page()->pause_throbber();
if (ShowingInterstitialPage())
GetRenderManager()->remove_interstitial_page();
for (auto& observer : observers_)
observer.DidDetachInterstitialPage();
// Restart the throbber if needed now that the interstitial page is going
// away.
if (interstitial_pausing_throbber && frame_tree_.IsLoading())
LoadingStateChanged(true, true, nullptr);
}
void WebContentsImpl::SetHistoryOffsetAndLength(int history_offset,
int history_length) {
SendPageMessage(new PageMsg_SetHistoryOffsetAndLength(
MSG_ROUTING_NONE, history_offset, history_length));
}
void WebContentsImpl::SetHistoryOffsetAndLengthForView(
RenderViewHost* render_view_host,
int history_offset,
int history_length) {
render_view_host->Send(new PageMsg_SetHistoryOffsetAndLength(
render_view_host->GetRoutingID(), history_offset, history_length));
}
void WebContentsImpl::ReloadFocusedFrame(bool bypass_cache) {
RenderFrameHost* focused_frame = GetFocusedFrame();
if (!focused_frame)
return;
focused_frame->Send(new FrameMsg_Reload(
focused_frame->GetRoutingID(), bypass_cache));
}
void WebContentsImpl::ReloadLoFiImages() {
SendToAllFrames(new FrameMsg_ReloadLoFiImages(MSG_ROUTING_NONE));
}
void WebContentsImpl::Undo() {
RenderFrameHost* focused_frame = GetFocusedFrame();
if (!focused_frame)
return;
focused_frame->Send(new InputMsg_Undo(focused_frame->GetRoutingID()));
RecordAction(base::UserMetricsAction("Undo"));
}
void WebContentsImpl::Redo() {
RenderFrameHost* focused_frame = GetFocusedFrame();
if (!focused_frame)
return;
focused_frame->Send(new InputMsg_Redo(focused_frame->GetRoutingID()));
RecordAction(base::UserMetricsAction("Redo"));
}
void WebContentsImpl::Cut() {
RenderFrameHost* focused_frame = GetFocusedFrame();
if (!focused_frame)
return;
focused_frame->Send(new InputMsg_Cut(focused_frame->GetRoutingID()));
RecordAction(base::UserMetricsAction("Cut"));
}
void WebContentsImpl::Copy() {
RenderFrameHost* focused_frame = GetFocusedFrame();
if