blob: 66e110ef1f33c5170e3f0ce455afa2723f3063e8 [file] [log] [blame]
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001// 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.
4
5#include "content/browser/web_contents/web_contents_impl.h"
6
7#include <utility>
8
9#include "base/command_line.h"
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +010010#include "base/debug/trace_event.h"
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +010011#include "base/lazy_instance.h"
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +010012#include "base/logging.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000013#include "base/metrics/histogram.h"
14#include "base/metrics/stats_counters.h"
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +010015#include "base/strings/string16.h"
16#include "base/strings/string_number_conversions.h"
17#include "base/strings/string_util.h"
18#include "base/strings/utf_string_conversions.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000019#include "base/sys_info.h"
Ben Murdocheb525c52013-07-10 11:40:50 +010020#include "base/time/time.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000021#include "cc/base/switches.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000022#include "content/browser/browser_plugin/browser_plugin_embedder.h"
23#include "content/browser/browser_plugin/browser_plugin_guest.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000024#include "content/browser/browser_plugin/browser_plugin_guest_manager.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000025#include "content/browser/child_process_security_policy_impl.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000026#include "content/browser/devtools/devtools_manager_impl.h"
Ben Murdochbb1529c2013-08-08 10:24:53 +010027#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000028#include "content/browser/dom_storage/session_storage_namespace_impl.h"
29#include "content/browser/download/download_stats.h"
30#include "content/browser/download/mhtml_generation_manager.h"
31#include "content/browser/download/save_package.h"
32#include "content/browser/gpu/gpu_data_manager_impl.h"
33#include "content/browser/gpu/gpu_process_host.h"
34#include "content/browser/host_zoom_map_impl.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000035#include "content/browser/loader/resource_dispatcher_host_impl.h"
Ben Murdochca12bfa2013-07-23 11:17:05 +010036#include "content/browser/power_save_blocker_impl.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000037#include "content/browser/renderer_host/render_process_host_impl.h"
38#include "content/browser/renderer_host/render_view_host_impl.h"
39#include "content/browser/renderer_host/render_widget_host_impl.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000040#include "content/browser/site_instance_impl.h"
41#include "content/browser/web_contents/interstitial_page_impl.h"
42#include "content/browser/web_contents/navigation_entry_impl.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000043#include "content/browser/web_contents/web_contents_view_guest.h"
44#include "content/browser/webui/generic_handler.h"
45#include "content/browser/webui/web_ui_controller_factory_registry.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000046#include "content/browser/webui/web_ui_impl.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000047#include "content/common/browser_plugin/browser_plugin_constants.h"
48#include "content/common/browser_plugin/browser_plugin_messages.h"
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +010049#include "content/common/image_messages.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000050#include "content/common/ssl_status_serialization.h"
51#include "content/common/view_messages.h"
52#include "content/port/browser/render_view_host_delegate_view.h"
53#include "content/port/browser/render_widget_host_view_port.h"
54#include "content/public/browser/browser_context.h"
55#include "content/public/browser/color_chooser.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000056#include "content/public/browser/compositor_util.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000057#include "content/public/browser/content_browser_client.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000058#include "content/public/browser/devtools_agent_host.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000059#include "content/public/browser/download_manager.h"
60#include "content/public/browser/download_url_parameters.h"
61#include "content/public/browser/invalidate_type.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000062#include "content/public/browser/javascript_dialog_manager.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000063#include "content/public/browser/load_from_memory_cache_details.h"
64#include "content/public/browser/load_notification_details.h"
65#include "content/public/browser/navigation_details.h"
66#include "content/public/browser/notification_details.h"
67#include "content/public/browser/notification_service.h"
68#include "content/public/browser/resource_request_details.h"
69#include "content/public/browser/storage_partition.h"
70#include "content/public/browser/user_metrics.h"
71#include "content/public/browser/web_contents_delegate.h"
72#include "content/public/browser/web_contents_observer.h"
73#include "content/public/browser/web_contents_view.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000074#include "content/public/common/bindings_policy.h"
75#include "content/public/common/content_constants.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000076#include "content/public/common/content_switches.h"
Ben Murdoch58e6fbe2013-07-26 10:20:38 +010077#include "content/public/common/page_zoom.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000078#include "content/public/common/url_constants.h"
79#include "net/base/mime_util.h"
80#include "net/base/net_util.h"
81#include "net/base/network_change_notifier.h"
82#include "net/url_request/url_request_context_getter.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000083#include "ui/base/layout.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000084#include "ui/base/touch/touch_device.h"
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +010085#include "ui/base/touch/touch_enabled.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000086#include "ui/base/ui_base_switches.h"
87#include "ui/gfx/display.h"
88#include "ui/gfx/screen.h"
89#include "ui/gl/gl_switches.h"
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +010090#include "webkit/common/webpreferences.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000091
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000092#if defined(OS_ANDROID)
93#include "content/browser/android/date_time_chooser_android.h"
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +010094#include "content/public/browser/android/content_view_core.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000095#endif
96
Torne (Richard Coles)58218062012-11-14 11:43:16 +000097#if defined(OS_MACOSX)
98#include "base/mac/foundation_util.h"
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +010099#include "ui/gl/io_surface_support_mac.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000100#endif
101
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +0100102#if defined(OS_ANDROID)
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000103#include "content/browser/renderer_host/java/java_bridge_dispatcher_host_manager.h"
104#endif
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000105
106// Cross-Site Navigations
107//
108// If a WebContentsImpl is told to navigate to a different web site (as
109// determined by SiteInstance), it will replace its current RenderViewHost with
110// a new RenderViewHost dedicated to the new SiteInstance. This works as
111// follows:
112//
113// - Navigate determines whether the destination is cross-site, and if so,
114// it creates a pending_render_view_host_.
115// - The pending RVH is "suspended," so that no navigation messages are sent to
116// its renderer until the onbeforeunload JavaScript handler has a chance to
117// run in the current RVH.
118// - The pending RVH tells CrossSiteRequestManager (a thread-safe singleton)
119// that it has a pending cross-site request. ResourceDispatcherHost will
120// check for this when the response arrives.
121// - The current RVH runs its onbeforeunload handler. If it returns false, we
122// cancel all the pending logic. Otherwise we allow the pending RVH to send
123// the navigation request to its renderer.
124// - ResourceDispatcherHost receives a ResourceRequest on the IO thread for the
125// main resource load on the pending RVH. It checks CrossSiteRequestManager
126// to see that it is a cross-site request, and installs a
127// CrossSiteResourceHandler.
128// - When RDH receives a response, the BufferedResourceHandler determines
129// whether it is a download. If so, it sends a message to the new renderer
130// causing it to cancel the request, and the download proceeds. For now, the
131// pending RVH remains until the next DidNavigate event for this
132// WebContentsImpl. This isn't ideal, but it doesn't affect any functionality.
133// - After RDH receives a response and determines that it is safe and not a
134// download, it pauses the response to first run the old page's onunload
135// handler. It does this by asynchronously calling the OnCrossSiteResponse
136// method of WebContentsImpl on the UI thread, which sends a SwapOut message
137// to the current RVH.
138// - Once the onunload handler is finished, a SwapOut_ACK message is sent to
139// the ResourceDispatcherHost, who unpauses the response. Data is then sent
140// to the pending RVH.
141// - The pending renderer sends a FrameNavigate message that invokes the
142// DidNavigate method. This replaces the current RVH with the
143// pending RVH.
144// - The previous renderer is kept swapped out in RenderViewHostManager in case
145// the user goes back. The process only stays live if another tab is using
146// it, but if so, the existing frame relationships will be maintained.
147
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000148namespace content {
149namespace {
150
151// Amount of time we wait between when a key event is received and the renderer
152// is queried for its state and pushed to the NavigationEntry.
153const int kQueryStateDelay = 5000;
154
155const int kSyncWaitDelay = 40;
156
157const char kDotGoogleDotCom[] = ".google.com";
158
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +0100159base::LazyInstance<std::vector<WebContents::CreatedCallback> >
160g_created_callbacks = LAZY_INSTANCE_INITIALIZER;
161
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000162static int StartDownload(content::RenderViewHost* rvh,
163 const GURL& url,
164 bool is_favicon,
Ben Murdocheb525c52013-07-10 11:40:50 +0100165 uint32_t preferred_image_size,
166 uint32_t max_image_size) {
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100167 static int g_next_image_download_id = 0;
168 rvh->Send(new ImageMsg_DownloadImage(rvh->GetRoutingID(),
169 ++g_next_image_download_id,
170 url,
171 is_favicon,
Ben Murdocheb525c52013-07-10 11:40:50 +0100172 preferred_image_size,
173 max_image_size));
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100174 return g_next_image_download_id;
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000175}
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000176
177ViewMsg_Navigate_Type::Value GetNavigationType(
178 BrowserContext* browser_context, const NavigationEntryImpl& entry,
179 NavigationController::ReloadType reload_type) {
180 switch (reload_type) {
181 case NavigationControllerImpl::RELOAD:
182 return ViewMsg_Navigate_Type::RELOAD;
183 case NavigationControllerImpl::RELOAD_IGNORING_CACHE:
184 return ViewMsg_Navigate_Type::RELOAD_IGNORING_CACHE;
185 case NavigationControllerImpl::RELOAD_ORIGINAL_REQUEST_URL:
186 return ViewMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL;
187 case NavigationControllerImpl::NO_RELOAD:
188 break; // Fall through to rest of function.
189 }
190
191 // |RenderViewImpl::PopulateStateFromPendingNavigationParams| differentiates
192 // between |RESTORE_WITH_POST| and |RESTORE|.
193 if (entry.restore_type() ==
194 NavigationEntryImpl::RESTORE_LAST_SESSION_EXITED_CLEANLY) {
195 if (entry.GetHasPostData())
196 return ViewMsg_Navigate_Type::RESTORE_WITH_POST;
197 return ViewMsg_Navigate_Type::RESTORE;
198 }
199
200 return ViewMsg_Navigate_Type::NORMAL;
201}
202
203void MakeNavigateParams(const NavigationEntryImpl& entry,
204 const NavigationControllerImpl& controller,
205 WebContentsDelegate* delegate,
206 NavigationController::ReloadType reload_type,
207 ViewMsg_Navigate_Params* params) {
208 params->page_id = entry.GetPageID();
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100209 params->should_clear_history_list = entry.should_clear_history_list();
210 if (entry.should_clear_history_list()) {
211 // Set the history list related parameters to the same values a
212 // NavigationController would return before its first navigation. This will
213 // fully clear the RenderView's view of the session history.
214 params->pending_history_list_offset = -1;
215 params->current_history_list_offset = -1;
216 params->current_history_list_length = 0;
217 } else {
218 params->pending_history_list_offset = controller.GetIndexOfEntry(&entry);
219 params->current_history_list_offset =
220 controller.GetLastCommittedEntryIndex();
221 params->current_history_list_length = controller.GetEntryCount();
222 }
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000223 if (!entry.GetBaseURLForDataURL().is_empty()) {
224 params->base_url_for_data_url = entry.GetBaseURLForDataURL();
225 params->history_url_for_data_url = entry.GetVirtualURL();
226 }
227 params->referrer = entry.GetReferrer();
228 params->transition = entry.GetTransitionType();
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100229 params->page_state = entry.GetPageState();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000230 params->navigation_type =
231 GetNavigationType(controller.GetBrowserContext(), entry, reload_type);
232 params->request_time = base::Time::Now();
233 params->extra_headers = entry.extra_headers();
234 params->transferred_request_child_id =
235 entry.transferred_global_request_id().child_id;
236 params->transferred_request_request_id =
237 entry.transferred_global_request_id().request_id;
238 params->is_overriding_user_agent = entry.GetIsOverridingUserAgent();
239 // Avoid downloading when in view-source mode.
240 params->allow_download = !entry.IsViewSourceMode();
241 params->is_post = entry.GetHasPostData();
242 if(entry.GetBrowserInitiatedPostData()) {
243 params->browser_initiated_post_data.assign(
244 entry.GetBrowserInitiatedPostData()->front(),
245 entry.GetBrowserInitiatedPostData()->front() +
246 entry.GetBrowserInitiatedPostData()->size());
247
248 }
249
250 if (reload_type == NavigationControllerImpl::RELOAD_ORIGINAL_REQUEST_URL &&
251 entry.GetOriginalRequestURL().is_valid() && !entry.GetHasPostData()) {
252 // We may have been redirected when navigating to the current URL.
253 // Use the URL the user originally intended to visit, if it's valid and if a
254 // POST wasn't involved; the latter case avoids issues with sending data to
255 // the wrong page.
256 params->url = entry.GetOriginalRequestURL();
257 } else {
258 params->url = entry.GetURL();
259 }
260
261 params->can_load_local_resources = entry.GetCanLoadLocalResources();
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000262 params->frame_to_navigate = entry.GetFrameToNavigate();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000263
264 if (delegate)
265 delegate->AddNavigationHeaders(params->url, &params->extra_headers);
266}
267
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000268} // namespace
269
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000270WebContents* WebContents::Create(const WebContents::CreateParams& params) {
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100271 return WebContentsImpl::CreateWithOpener(
272 params, static_cast<WebContentsImpl*>(params.opener));
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000273}
274
275WebContents* WebContents::CreateWithSessionStorage(
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000276 const WebContents::CreateParams& params,
Ben Murdochca12bfa2013-07-23 11:17:05 +0100277 const SessionStorageNamespaceMap& session_storage_namespace_map) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000278 WebContentsImpl* new_contents = new WebContentsImpl(
279 params.browser_context, NULL);
Ben Murdochca12bfa2013-07-23 11:17:05 +0100280
281 for (SessionStorageNamespaceMap::const_iterator it =
282 session_storage_namespace_map.begin();
283 it != session_storage_namespace_map.end();
284 ++it) {
285 new_contents->GetController()
286 .SetSessionStorageNamespace(it->first, it->second.get());
287 }
288
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000289 new_contents->Init(params);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000290 return new_contents;
291}
292
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +0100293void WebContents::AddCreatedCallback(const CreatedCallback& callback) {
294 g_created_callbacks.Get().push_back(callback);
295}
296
297void WebContents::RemoveCreatedCallback(const CreatedCallback& callback) {
298 for (size_t i = 0; i < g_created_callbacks.Get().size(); ++i) {
299 if (g_created_callbacks.Get().at(i).Equals(callback)) {
300 g_created_callbacks.Get().erase(g_created_callbacks.Get().begin() + i);
301 return;
302 }
303 }
304}
305
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000306WebContents* WebContents::FromRenderViewHost(const RenderViewHost* rvh) {
307 return rvh->GetDelegate()->GetAsWebContents();
308}
309
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100310// WebContentsImpl::DestructionObserver ----------------------------------------
311
312class WebContentsImpl::DestructionObserver : public WebContentsObserver {
313 public:
314 DestructionObserver(WebContentsImpl* owner, WebContents* watched_contents)
315 : WebContentsObserver(watched_contents),
316 owner_(owner) {
317 }
318
319 // WebContentsObserver:
320 virtual void WebContentsDestroyed(WebContents* web_contents) OVERRIDE {
321 owner_->OnWebContentsDestroyed(static_cast<WebContentsImpl*>(web_contents));
322 }
323
324 private:
325 WebContentsImpl* owner_;
326
327 DISALLOW_COPY_AND_ASSIGN(DestructionObserver);
328};
329
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000330// WebContentsImpl -------------------------------------------------------------
331
332WebContentsImpl::WebContentsImpl(
333 BrowserContext* browser_context,
334 WebContentsImpl* opener)
335 : delegate_(NULL),
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100336 controller_(this, browser_context),
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000337 render_view_host_delegate_view_(NULL),
338 opener_(opener),
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100339#if defined(OS_WIN) && defined(USE_AURA)
340 accessible_parent_(NULL),
341#endif
342 render_manager_(this, this, this),
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000343 is_loading_(false),
344 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING),
345 crashed_error_code_(0),
346 waiting_for_response_(false),
347 load_state_(net::LOAD_STATE_IDLE, string16()),
348 upload_size_(0),
349 upload_position_(0),
350 displayed_insecure_content_(false),
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000351 capturer_count_(0),
352 should_normally_be_visible_(true),
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000353 is_being_destroyed_(false),
354 notify_disconnection_(false),
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000355 dialog_manager_(NULL),
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000356 is_showing_before_unload_dialog_(false),
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000357 closed_by_user_gesture_(false),
358 minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)),
359 maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)),
360 temporary_zoom_settings_(false),
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100361 color_chooser_identifier_(0),
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000362 message_source_(NULL),
363 fullscreen_widget_routing_id_(MSG_ROUTING_NONE) {
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +0100364 for (size_t i = 0; i < g_created_callbacks.Get().size(); i++)
365 g_created_callbacks.Get().at(i).Run(this);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000366}
367
368WebContentsImpl::~WebContentsImpl() {
369 is_being_destroyed_ = true;
370
Ben Murdochca12bfa2013-07-23 11:17:05 +0100371 ClearAllPowerSaveBlockers();
372
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000373 for (std::set<RenderWidgetHostImpl*>::iterator iter =
374 created_widgets_.begin(); iter != created_widgets_.end(); ++iter) {
375 (*iter)->DetachDelegate();
376 }
377 created_widgets_.clear();
378
379 // Clear out any JavaScript state.
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000380 if (dialog_manager_)
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100381 dialog_manager_->WebContentsDestroyed(this);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000382
383 if (color_chooser_)
384 color_chooser_->End();
385
386 NotifyDisconnected();
387
388 // Notify any observer that have a reference on this WebContents.
389 NotificationService::current()->Notify(
390 NOTIFICATION_WEB_CONTENTS_DESTROYED,
391 Source<WebContents>(this),
392 NotificationService::NoDetails());
393
394 // TODO(brettw) this should be moved to the view.
395#if defined(OS_WIN) && !defined(USE_AURA)
396 // If we still have a window handle, destroy it. GetNativeView can return
397 // NULL if this contents was part of a window that closed.
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000398 if (view_->GetNativeView()) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000399 RenderViewHost* host = GetRenderViewHost();
400 if (host && host->GetView())
401 RenderWidgetHostViewPort::FromRWHV(host->GetView())->WillWmDestroy();
402 }
403#endif
404
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000405 FOR_EACH_OBSERVER(WebContentsObserver,
406 observers_,
407 WebContentsImplDestroyed());
408
409 SetDelegate(NULL);
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100410
411 STLDeleteContainerPairSecondPointers(destruction_observers_.begin(),
412 destruction_observers_.end());
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000413}
414
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000415WebContentsImpl* WebContentsImpl::CreateWithOpener(
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000416 const WebContents::CreateParams& params,
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000417 WebContentsImpl* opener) {
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +0100418 TRACE_EVENT0("browser", "WebContentsImpl::CreateWithOpener");
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000419 WebContentsImpl* new_contents = new WebContentsImpl(
420 params.browser_context, opener);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000421
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000422 new_contents->Init(params);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000423 return new_contents;
424}
425
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000426// static
427BrowserPluginGuest* WebContentsImpl::CreateGuest(
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000428 BrowserContext* browser_context,
429 SiteInstance* site_instance,
Ben Murdocheb525c52013-07-10 11:40:50 +0100430 int guest_instance_id,
431 scoped_ptr<base::DictionaryValue> extra_params) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000432 WebContentsImpl* new_contents = new WebContentsImpl(browser_context, NULL);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000433
434 // This makes |new_contents| act as a guest.
435 // For more info, see comment above class BrowserPluginGuest.
Ben Murdocheb525c52013-07-10 11:40:50 +0100436 BrowserPluginGuest::Create(
437 guest_instance_id, new_contents, extra_params.Pass());
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000438
439 WebContents::CreateParams create_params(browser_context, site_instance);
440 new_contents->Init(create_params);
441
442 // We are instantiating a WebContents for browser plugin. Set its subframe bit
443 // to true.
444 static_cast<RenderViewHostImpl*>(
445 new_contents->GetRenderViewHost())->set_is_subframe(true);
446
447 return new_contents->browser_plugin_guest_.get();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000448}
449
450WebPreferences WebContentsImpl::GetWebkitPrefs(RenderViewHost* rvh,
451 const GURL& url) {
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +0100452 TRACE_EVENT0("browser", "WebContentsImpl::GetWebkitPrefs");
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000453 WebPreferences prefs;
454
455 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
456
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000457 prefs.javascript_enabled =
458 !command_line.HasSwitch(switches::kDisableJavaScript);
459 prefs.web_security_enabled =
460 !command_line.HasSwitch(switches::kDisableWebSecurity);
461 prefs.plugins_enabled =
462 !command_line.HasSwitch(switches::kDisablePlugins);
463 prefs.java_enabled =
464 !command_line.HasSwitch(switches::kDisableJava);
465
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000466 prefs.remote_fonts_enabled =
467 !command_line.HasSwitch(switches::kDisableRemoteFonts);
468 prefs.xss_auditor_enabled =
469 !command_line.HasSwitch(switches::kDisableXSSAuditor);
470 prefs.application_cache_enabled =
471 !command_line.HasSwitch(switches::kDisableApplicationCache);
472
473 prefs.local_storage_enabled =
474 !command_line.HasSwitch(switches::kDisableLocalStorage);
475 prefs.databases_enabled =
476 !command_line.HasSwitch(switches::kDisableDatabases);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000477 prefs.webaudio_enabled =
478 !command_line.HasSwitch(switches::kDisableWebAudio);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000479
480 prefs.experimental_webgl_enabled =
481 GpuProcessHost::gpu_enabled() &&
482 !command_line.HasSwitch(switches::kDisable3DAPIs) &&
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000483 !command_line.HasSwitch(switches::kDisableExperimentalWebGL);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000484
485 prefs.flash_3d_enabled =
486 GpuProcessHost::gpu_enabled() &&
487 !command_line.HasSwitch(switches::kDisableFlash3d);
488 prefs.flash_stage3d_enabled =
489 GpuProcessHost::gpu_enabled() &&
490 !command_line.HasSwitch(switches::kDisableFlashStage3d);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000491 prefs.flash_stage3d_baseline_enabled =
492 GpuProcessHost::gpu_enabled() &&
493 !command_line.HasSwitch(switches::kDisableFlashStage3d);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000494
495 prefs.gl_multisampling_enabled =
496 !command_line.HasSwitch(switches::kDisableGLMultisampling);
497 prefs.privileged_webgl_extensions_enabled =
498 command_line.HasSwitch(switches::kEnablePrivilegedWebGLExtensions);
499 prefs.site_specific_quirks_enabled =
500 !command_line.HasSwitch(switches::kDisableSiteSpecificQuirks);
501 prefs.allow_file_access_from_file_urls =
502 command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000503
504 prefs.accelerated_compositing_for_overflow_scroll_enabled = false;
505 if (command_line.HasSwitch(switches::kEnableAcceleratedOverflowScroll))
506 prefs.accelerated_compositing_for_overflow_scroll_enabled = true;
507 if (command_line.HasSwitch(switches::kDisableAcceleratedOverflowScroll))
508 prefs.accelerated_compositing_for_overflow_scroll_enabled = false;
509
510 prefs.accelerated_compositing_for_scrollable_frames_enabled =
511 command_line.HasSwitch(switches::kEnableAcceleratedScrollableFrames);
512 prefs.composited_scrolling_for_frames_enabled =
513 command_line.HasSwitch(switches::kEnableCompositedScrollingForFrames);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000514 prefs.show_paint_rects =
515 command_line.HasSwitch(switches::kShowPaintRects);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000516 prefs.accelerated_compositing_enabled =
517 GpuProcessHost::gpu_enabled() &&
518 !command_line.HasSwitch(switches::kDisableAcceleratedCompositing);
519 prefs.force_compositing_mode =
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000520 content::IsForceCompositingModeEnabled() &&
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000521 !command_line.HasSwitch(switches::kDisableForceCompositingMode);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000522 prefs.accelerated_2d_canvas_enabled =
523 GpuProcessHost::gpu_enabled() &&
524 !command_line.HasSwitch(switches::kDisableAccelerated2dCanvas);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000525 prefs.antialiased_2d_canvas_disabled =
526 command_line.HasSwitch(switches::kDisable2dCanvasAntialiasing);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000527 prefs.accelerated_filters_enabled =
528 GpuProcessHost::gpu_enabled() &&
529 command_line.HasSwitch(switches::kEnableAcceleratedFilters);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000530 prefs.accelerated_compositing_for_3d_transforms_enabled =
531 prefs.accelerated_compositing_for_animation_enabled =
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000532 !command_line.HasSwitch(switches::kDisableAcceleratedLayers);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000533 prefs.accelerated_compositing_for_plugins_enabled =
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000534 !command_line.HasSwitch(switches::kDisableAcceleratedPlugins);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000535 prefs.accelerated_compositing_for_video_enabled =
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000536 !command_line.HasSwitch(switches::kDisableAcceleratedVideo);
537 prefs.fullscreen_enabled =
538 !command_line.HasSwitch(switches::kDisableFullScreen);
539 prefs.css_sticky_position_enabled =
Ben Murdoch7dbb3d52013-07-17 14:55:54 +0100540 command_line.HasSwitch(switches::kEnableExperimentalWebPlatformFeatures);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000541 prefs.css_shaders_enabled =
542 command_line.HasSwitch(switches::kEnableCssShaders);
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100543 prefs.lazy_layout_enabled =
Ben Murdoch7dbb3d52013-07-17 14:55:54 +0100544 command_line.HasSwitch(switches::kEnableExperimentalWebPlatformFeatures);
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +0100545 prefs.region_based_columns_enabled =
546 command_line.HasSwitch(switches::kEnableRegionBasedColumns);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000547 prefs.threaded_html_parser =
548 !command_line.HasSwitch(switches::kDisableThreadedHTMLParser);
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100549 prefs.experimental_websocket_enabled =
550 command_line.HasSwitch(switches::kEnableExperimentalWebSocket);
Ben Murdocheb525c52013-07-10 11:40:50 +0100551 if (command_line.HasSwitch(cc::switches::kEnablePinchVirtualViewport)) {
552 prefs.pinch_virtual_viewport_enabled = true;
553 prefs.pinch_overlay_scrollbar_thickness = 10;
554 }
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100555
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000556#if defined(OS_ANDROID)
557 prefs.user_gesture_required_for_media_playback = !command_line.HasSwitch(
558 switches::kDisableGestureRequirementForMediaPlayback);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000559#endif
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000560
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100561 prefs.touch_enabled = ui::AreTouchEventsEnabled();
562 prefs.device_supports_touch = prefs.touch_enabled &&
563 ui::IsTouchDevicePresent();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000564#if defined(OS_ANDROID)
565 prefs.device_supports_mouse = false;
566#endif
567
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000568 prefs.touch_adjustment_enabled =
569 !command_line.HasSwitch(switches::kDisableTouchAdjustment);
570
571#if defined(OS_MACOSX) || defined(OS_CHROMEOS)
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000572 bool default_enable_scroll_animator = true;
573#else
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000574 bool default_enable_scroll_animator = false;
575#endif
576 prefs.enable_scroll_animator = default_enable_scroll_animator;
577 if (command_line.HasSwitch(switches::kEnableSmoothScrolling))
578 prefs.enable_scroll_animator = true;
579 if (command_line.HasSwitch(switches::kDisableSmoothScrolling))
580 prefs.enable_scroll_animator = false;
581
582 prefs.visual_word_movement_enabled =
583 command_line.HasSwitch(switches::kEnableVisualWordMovement);
584
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100585 // Certain GPU features might have been blacklisted.
586 GpuDataManagerImpl::GetInstance()->UpdateRendererWebPrefs(&prefs);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000587
588 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
589 rvh->GetProcess()->GetID())) {
590 prefs.loads_images_automatically = true;
591 prefs.javascript_enabled = true;
592 }
593
594 prefs.is_online = !net::NetworkChangeNotifier::IsOffline();
595
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +0100596#if !defined(USE_AURA)
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000597 // Force accelerated compositing and 2d canvas off for chrome: and about:
598 // pages (unless it's specifically allowed).
599 if ((url.SchemeIs(chrome::kChromeUIScheme) ||
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000600 (url.SchemeIs(chrome::kAboutScheme) &&
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100601 url.spec() != kAboutBlankURL)) &&
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000602 !command_line.HasSwitch(switches::kAllowWebUICompositing)) {
603 prefs.accelerated_compositing_enabled = false;
604 prefs.accelerated_2d_canvas_enabled = false;
605 }
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +0100606#endif
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000607
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000608 prefs.fixed_position_creates_stacking_context = !command_line.HasSwitch(
609 switches::kDisableFixedPositionCreatesStackingContext);
610
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000611#if defined(OS_CHROMEOS)
612 prefs.gesture_tap_highlight_enabled = !command_line.HasSwitch(
613 switches::kDisableGestureTapHighlight);
614#else
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000615 prefs.gesture_tap_highlight_enabled = command_line.HasSwitch(
616 switches::kEnableGestureTapHighlight);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000617#endif
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000618
619 prefs.number_of_cpu_cores = base::SysInfo::NumberOfProcessors();
620
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000621 prefs.viewport_enabled = command_line.HasSwitch(switches::kEnableViewport);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000622
623 prefs.deferred_image_decoding_enabled =
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000624 command_line.HasSwitch(switches::kEnableDeferredImageDecoding) ||
625 cc::switches::IsImplSidePaintingEnabled();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000626
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100627 prefs.spatial_navigation_enabled = command_line.HasSwitch(
628 switches::kEnableSpatialNavigation);
629
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000630 GetContentClient()->browser()->OverrideWebkitPrefs(rvh, url, &prefs);
631
632 // Disable compositing in guests until we have compositing path implemented
633 // for guests.
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000634 bool guest_compositing_enabled = !command_line.HasSwitch(
635 switches::kDisableBrowserPluginCompositing);
636 if (rvh->GetProcess()->IsGuest() && !guest_compositing_enabled) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000637 prefs.force_compositing_mode = false;
638 prefs.accelerated_compositing_enabled = false;
639 }
640
641 return prefs;
642}
643
644RenderViewHostManager* WebContentsImpl::GetRenderManagerForTesting() {
645 return &render_manager_;
646}
647
648bool WebContentsImpl::OnMessageReceived(RenderViewHost* render_view_host,
649 const IPC::Message& message) {
650 if (GetWebUI() &&
651 static_cast<WebUIImpl*>(GetWebUI())->OnMessageReceived(message)) {
652 return true;
653 }
654
655 ObserverListBase<WebContentsObserver>::Iterator it(observers_);
656 WebContentsObserver* observer;
657 while ((observer = it.GetNext()) != NULL)
658 if (observer->OnMessageReceived(message))
659 return true;
660
661 // Message handlers should be aware of which RenderViewHost sent the
662 // message, which is temporarily stored in message_source_.
663 message_source_ = render_view_host;
664 bool handled = true;
665 bool message_is_ok = true;
666 IPC_BEGIN_MESSAGE_MAP_EX(WebContentsImpl, message, message_is_ok)
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000667 IPC_MESSAGE_HANDLER(ViewHostMsg_DidLoadResourceFromMemoryCache,
668 OnDidLoadResourceFromMemoryCache)
669 IPC_MESSAGE_HANDLER(ViewHostMsg_DidDisplayInsecureContent,
670 OnDidDisplayInsecureContent)
671 IPC_MESSAGE_HANDLER(ViewHostMsg_DidRunInsecureContent,
672 OnDidRunInsecureContent)
673 IPC_MESSAGE_HANDLER(ViewHostMsg_DocumentLoadedInFrame,
674 OnDocumentLoadedInFrame)
675 IPC_MESSAGE_HANDLER(ViewHostMsg_DidFinishLoad, OnDidFinishLoad)
676 IPC_MESSAGE_HANDLER(ViewHostMsg_DidFailLoadWithError,
677 OnDidFailLoadWithError)
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000678 IPC_MESSAGE_HANDLER(ViewHostMsg_GoToEntryAtOffset, OnGoToEntryAtOffset)
679 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateZoomLimits, OnUpdateZoomLimits)
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000680 IPC_MESSAGE_HANDLER(ViewHostMsg_EnumerateDirectory, OnEnumerateDirectory)
681 IPC_MESSAGE_HANDLER(ViewHostMsg_JSOutOfMemory, OnJSOutOfMemory)
682 IPC_MESSAGE_HANDLER(ViewHostMsg_RegisterProtocolHandler,
683 OnRegisterProtocolHandler)
684 IPC_MESSAGE_HANDLER(ViewHostMsg_Find_Reply, OnFindReply)
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100685 IPC_MESSAGE_HANDLER(ViewHostMsg_DidProgrammaticallyScroll,
686 OnDidProgrammaticallyScroll)
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000687 IPC_MESSAGE_HANDLER(ViewHostMsg_CrashedPlugin, OnCrashedPlugin)
688 IPC_MESSAGE_HANDLER(ViewHostMsg_AppCacheAccessed, OnAppCacheAccessed)
689 IPC_MESSAGE_HANDLER(ViewHostMsg_OpenColorChooser, OnOpenColorChooser)
690 IPC_MESSAGE_HANDLER(ViewHostMsg_EndColorChooser, OnEndColorChooser)
691 IPC_MESSAGE_HANDLER(ViewHostMsg_SetSelectedColorInColorChooser,
692 OnSetSelectedColorInColorChooser)
693 IPC_MESSAGE_HANDLER(ViewHostMsg_PepperPluginHung, OnPepperPluginHung)
694 IPC_MESSAGE_HANDLER(ViewHostMsg_WebUISend, OnWebUISend)
695 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission,
696 OnRequestPpapiBrokerPermission)
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000697 IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_AllocateInstanceID,
698 OnBrowserPluginMessage(message))
699 IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_Attach,
700 OnBrowserPluginMessage(message))
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100701 IPC_MESSAGE_HANDLER(ImageHostMsg_DidDownloadImage, OnDidDownloadImage)
702 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateFaviconURL, OnUpdateFaviconURL)
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000703#if defined(OS_ANDROID)
704 IPC_MESSAGE_HANDLER(ViewHostMsg_FindMatchRects_Reply,
705 OnFindMatchRectsReply)
706 IPC_MESSAGE_HANDLER(ViewHostMsg_OpenDateTimeDialog,
707 OnOpenDateTimeDialog)
708#endif
Torne (Richard Coles)b2df76e2013-05-13 16:52:09 +0100709 IPC_MESSAGE_HANDLER(ViewHostMsg_FrameAttached, OnFrameAttached)
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000710 IPC_MESSAGE_HANDLER(ViewHostMsg_FrameDetached, OnFrameDetached)
Ben Murdochca12bfa2013-07-23 11:17:05 +0100711 IPC_MESSAGE_HANDLER(ViewHostMsg_MediaNotification, OnMediaNotification)
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000712 IPC_MESSAGE_UNHANDLED(handled = false)
713 IPC_END_MESSAGE_MAP_EX()
714 message_source_ = NULL;
715
716 if (!message_is_ok) {
717 RecordAction(UserMetricsAction("BadMessageTerminate_RVD"));
718 GetRenderProcessHost()->ReceivedBadMessage();
719 }
720
721 return handled;
722}
723
724void WebContentsImpl::RunFileChooser(
725 RenderViewHost* render_view_host,
726 const FileChooserParams& params) {
727 if (delegate_)
728 delegate_->RunFileChooser(this, params);
729}
730
731NavigationControllerImpl& WebContentsImpl::GetController() {
732 return controller_;
733}
734
735const NavigationControllerImpl& WebContentsImpl::GetController() const {
736 return controller_;
737}
738
739BrowserContext* WebContentsImpl::GetBrowserContext() const {
740 return controller_.GetBrowserContext();
741}
742
743const GURL& WebContentsImpl::GetURL() const {
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100744 // We may not have a navigation entry yet.
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +0100745 NavigationEntry* entry = controller_.GetVisibleEntry();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000746 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
747}
748
Ben Murdochca12bfa2013-07-23 11:17:05 +0100749const GURL& WebContentsImpl::GetVisibleURL() const {
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100750 // We may not have a navigation entry yet.
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +0100751 NavigationEntry* entry = controller_.GetVisibleEntry();
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100752 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
753}
754
755const GURL& WebContentsImpl::GetLastCommittedURL() const {
756 // We may not have a navigation entry yet.
757 NavigationEntry* entry = controller_.GetLastCommittedEntry();
758 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
759}
760
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000761WebContentsDelegate* WebContentsImpl::GetDelegate() {
762 return delegate_;
763}
764
765void WebContentsImpl::SetDelegate(WebContentsDelegate* delegate) {
766 // TODO(cbentzel): remove this debugging code?
767 if (delegate == delegate_)
768 return;
769 if (delegate_)
770 delegate_->Detach(this);
771 delegate_ = delegate;
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000772 if (delegate_) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000773 delegate_->Attach(this);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000774 // Ensure the visible RVH reflects the new delegate's preferences.
775 if (view_)
776 view_->SetOverscrollControllerEnabled(delegate->CanOverscrollContent());
777 }
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000778}
779
780RenderProcessHost* WebContentsImpl::GetRenderProcessHost() const {
781 RenderViewHostImpl* host = render_manager_.current_host();
782 return host ? host->GetProcess() : NULL;
783}
784
785RenderViewHost* WebContentsImpl::GetRenderViewHost() const {
786 return render_manager_.current_host();
787}
788
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000789void WebContentsImpl::GetRenderViewHostAtPosition(
790 int x,
791 int y,
792 const base::Callback<void(RenderViewHost*, int, int)>& callback) {
793 BrowserPluginEmbedder* embedder = GetBrowserPluginEmbedder();
794 if (embedder)
795 embedder->GetRenderViewHostAtPosition(x, y, callback);
796 else
797 callback.Run(GetRenderViewHost(), x, y);
798}
799
800WebContents* WebContentsImpl::GetEmbedderWebContents() const {
801 BrowserPluginGuest* guest = GetBrowserPluginGuest();
802 if (guest)
803 return guest->embedder_web_contents();
804 return NULL;
805}
806
807int WebContentsImpl::GetEmbeddedInstanceID() const {
808 BrowserPluginGuest* guest = GetBrowserPluginGuest();
809 if (guest)
810 return guest->instance_id();
811 return 0;
812}
813
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000814int WebContentsImpl::GetRoutingID() const {
815 if (!GetRenderViewHost())
816 return MSG_ROUTING_NONE;
817
818 return GetRenderViewHost()->GetRoutingID();
819}
820
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000821int WebContentsImpl::GetFullscreenWidgetRoutingID() const {
822 return fullscreen_widget_routing_id_;
823}
824
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000825RenderWidgetHostView* WebContentsImpl::GetRenderWidgetHostView() const {
826 return render_manager_.GetRenderWidgetHostView();
827}
828
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000829RenderWidgetHostViewPort* WebContentsImpl::GetRenderWidgetHostViewPort() const {
830 BrowserPluginGuest* guest = GetBrowserPluginGuest();
831 if (guest && guest->embedder_web_contents()) {
832 return guest->embedder_web_contents()->GetRenderWidgetHostViewPort();
833 }
834 return RenderWidgetHostViewPort::FromRWHV(GetRenderWidgetHostView());
835}
836
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000837WebContentsView* WebContentsImpl::GetView() const {
838 return view_.get();
839}
840
841WebUI* WebContentsImpl::CreateWebUI(const GURL& url) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000842 WebUIImpl* web_ui = new WebUIImpl(this);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000843 WebUIController* controller = WebUIControllerFactoryRegistry::GetInstance()->
844 CreateWebUIControllerForURL(web_ui, url);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000845 if (controller) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000846 web_ui->AddMessageHandler(new GenericHandler());
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000847 web_ui->SetController(controller);
848 return web_ui;
849 }
850
851 delete web_ui;
852 return NULL;
853}
854
855WebUI* WebContentsImpl::GetWebUI() const {
856 return render_manager_.web_ui() ? render_manager_.web_ui()
857 : render_manager_.pending_web_ui();
858}
859
860WebUI* WebContentsImpl::GetCommittedWebUI() const {
861 return render_manager_.web_ui();
862}
863
864void WebContentsImpl::SetUserAgentOverride(const std::string& override) {
865 if (GetUserAgentOverride() == override)
866 return;
867
868 renderer_preferences_.user_agent_override = override;
869
870 // Send the new override string to the renderer.
871 RenderViewHost* host = GetRenderViewHost();
872 if (host)
873 host->SyncRendererPrefs();
874
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_.GetActiveEntry();
878 if (is_loading_ && entry != NULL && entry->GetIsOverridingUserAgent())
879 controller_.ReloadIgnoringCache(true);
880
881 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
882 UserAgentOverrideSet(override));
883}
884
885const std::string& WebContentsImpl::GetUserAgentOverride() const {
886 return renderer_preferences_.user_agent_override;
887}
888
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100889#if defined(OS_WIN) && defined(USE_AURA)
890void WebContentsImpl::SetParentNativeViewAccessible(
891gfx::NativeViewAccessible accessible_parent) {
892 accessible_parent_ = accessible_parent;
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100893 if (GetRenderViewHost())
894 GetRenderViewHostImpl()->SetParentNativeViewAccessible(accessible_parent);
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100895}
896#endif
897
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000898const string16& WebContentsImpl::GetTitle() const {
899 // Transient entries take precedence. They are used for interstitial pages
900 // that are shown on top of existing pages.
901 NavigationEntry* entry = controller_.GetTransientEntry();
902 std::string accept_languages =
903 GetContentClient()->browser()->GetAcceptLangs(
904 GetBrowserContext());
905 if (entry) {
906 return entry->GetTitleForDisplay(accept_languages);
907 }
908 WebUI* our_web_ui = render_manager_.pending_web_ui() ?
909 render_manager_.pending_web_ui() : render_manager_.web_ui();
910 if (our_web_ui) {
911 // Don't override the title in view source mode.
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +0100912 entry = controller_.GetVisibleEntry();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000913 if (!(entry && entry->IsViewSourceMode())) {
914 // Give the Web UI the chance to override our title.
915 const string16& title = our_web_ui->GetOverriddenTitle();
916 if (!title.empty())
917 return title;
918 }
919 }
920
921 // We use the title for the last committed entry rather than a pending
922 // navigation entry. For example, when the user types in a URL, we want to
923 // keep the old page's title until the new load has committed and we get a new
924 // title.
925 entry = controller_.GetLastCommittedEntry();
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +0100926
927 // We make an exception for initial navigations, because we can have a
928 // committed entry for an initial navigation when doing a history navigation
929 // in a new tab, such as Ctrl+Back.
930 if (entry && controller_.IsInitialNavigation())
931 entry = controller_.GetVisibleEntry();
932
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000933 if (entry) {
934 return entry->GetTitleForDisplay(accept_languages);
935 }
936
937 // |page_title_when_no_navigation_entry_| is finally used
938 // if no title cannot be retrieved.
939 return page_title_when_no_navigation_entry_;
940}
941
942int32 WebContentsImpl::GetMaxPageID() {
943 return GetMaxPageIDForSiteInstance(GetSiteInstance());
944}
945
946int32 WebContentsImpl::GetMaxPageIDForSiteInstance(
947 SiteInstance* site_instance) {
948 if (max_page_ids_.find(site_instance->GetId()) == max_page_ids_.end())
949 max_page_ids_[site_instance->GetId()] = -1;
950
951 return max_page_ids_[site_instance->GetId()];
952}
953
954void WebContentsImpl::UpdateMaxPageID(int32 page_id) {
955 UpdateMaxPageIDForSiteInstance(GetSiteInstance(), page_id);
956}
957
958void WebContentsImpl::UpdateMaxPageIDForSiteInstance(
959 SiteInstance* site_instance, int32 page_id) {
960 if (GetMaxPageIDForSiteInstance(site_instance) < page_id)
961 max_page_ids_[site_instance->GetId()] = page_id;
962}
963
964void WebContentsImpl::CopyMaxPageIDsFrom(WebContentsImpl* web_contents) {
965 max_page_ids_ = web_contents->max_page_ids_;
966}
967
968SiteInstance* WebContentsImpl::GetSiteInstance() const {
969 return render_manager_.current_host()->GetSiteInstance();
970}
971
972SiteInstance* WebContentsImpl::GetPendingSiteInstance() const {
973 RenderViewHost* dest_rvh = render_manager_.pending_render_view_host() ?
974 render_manager_.pending_render_view_host() :
975 render_manager_.current_host();
976 return dest_rvh->GetSiteInstance();
977}
978
979bool WebContentsImpl::IsLoading() const {
980 return is_loading_;
981}
982
983bool WebContentsImpl::IsWaitingForResponse() const {
984 return waiting_for_response_;
985}
986
987const net::LoadStateWithParam& WebContentsImpl::GetLoadState() const {
988 return load_state_;
989}
990
991const string16& WebContentsImpl::GetLoadStateHost() const {
992 return load_state_host_;
993}
994
995uint64 WebContentsImpl::GetUploadSize() const {
996 return upload_size_;
997}
998
999uint64 WebContentsImpl::GetUploadPosition() const {
1000 return upload_position_;
1001}
1002
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +01001003std::set<GURL> WebContentsImpl::GetSitesInTab() const {
1004 BrowserContext* browser_context = GetBrowserContext();
1005 std::set<GURL> sites;
1006 if (!frame_tree_root_.get())
1007 return sites;
1008
1009 // Iterates over the FrameTreeNodes to find each unique site URL that is
1010 // currently committed.
1011 FrameTreeNode* node = NULL;
1012 std::queue<FrameTreeNode*> queue;
1013 queue.push(frame_tree_root_.get());
1014
1015 while (!queue.empty()) {
1016 node = queue.front();
1017 queue.pop();
1018 sites.insert(SiteInstance::GetSiteForURL(browser_context,
1019 node->current_url()));
1020
1021 for (size_t i = 0; i < node->child_count(); ++i)
1022 queue.push(node->child_at(i));
1023 }
1024
1025 return sites;
1026}
1027
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001028const std::string& WebContentsImpl::GetEncoding() const {
1029 return encoding_;
1030}
1031
1032bool WebContentsImpl::DisplayedInsecureContent() const {
1033 return displayed_insecure_content_;
1034}
1035
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001036void WebContentsImpl::IncrementCapturerCount() {
1037 DCHECK(!is_being_destroyed_);
1038 ++capturer_count_;
1039 DVLOG(1) << "There are now " << capturer_count_
1040 << " capturing(s) of WebContentsImpl@" << this;
1041}
1042
1043void WebContentsImpl::DecrementCapturerCount() {
1044 --capturer_count_;
1045 DVLOG(1) << "There are now " << capturer_count_
1046 << " capturing(s) of WebContentsImpl@" << this;
1047 DCHECK_LE(0, capturer_count_);
1048
1049 if (is_being_destroyed_)
1050 return;
1051
1052 // While capturer_count_ was greater than zero, the WasHidden() calls to RWHV
1053 // were being prevented. If there are no more capturers, make the call now.
1054 if (capturer_count_ == 0 && !should_normally_be_visible_) {
1055 DVLOG(1) << "Executing delayed WasHidden().";
1056 WasHidden();
1057 }
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001058}
1059
Ben Murdochca12bfa2013-07-23 11:17:05 +01001060int WebContentsImpl::GetCapturerCount() const {
1061 return capturer_count_;
1062}
1063
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001064bool WebContentsImpl::IsCrashed() const {
1065 return (crashed_status_ == base::TERMINATION_STATUS_PROCESS_CRASHED ||
1066 crashed_status_ == base::TERMINATION_STATUS_ABNORMAL_TERMINATION ||
1067 crashed_status_ == base::TERMINATION_STATUS_PROCESS_WAS_KILLED);
1068}
1069
1070void WebContentsImpl::SetIsCrashed(base::TerminationStatus status,
1071 int error_code) {
1072 if (status == crashed_status_)
1073 return;
1074
1075 crashed_status_ = status;
1076 crashed_error_code_ = error_code;
1077 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
1078}
1079
1080base::TerminationStatus WebContentsImpl::GetCrashedStatus() const {
1081 return crashed_status_;
1082}
1083
1084bool WebContentsImpl::IsBeingDestroyed() const {
1085 return is_being_destroyed_;
1086}
1087
1088void WebContentsImpl::NotifyNavigationStateChanged(unsigned changed_flags) {
1089 if (delegate_)
1090 delegate_->NavigationStateChanged(this, changed_flags);
1091}
1092
1093base::TimeTicks WebContentsImpl::GetLastSelectedTime() const {
1094 return last_selected_time_;
1095}
1096
1097void WebContentsImpl::WasShown() {
1098 controller_.SetActive(true);
1099 RenderWidgetHostViewPort* rwhv =
1100 RenderWidgetHostViewPort::FromRWHV(GetRenderWidgetHostView());
1101 if (rwhv) {
1102 rwhv->WasShown();
1103#if defined(OS_MACOSX)
1104 rwhv->SetActive(true);
1105#endif
1106 }
1107
1108 last_selected_time_ = base::TimeTicks::Now();
1109
1110 FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasShown());
1111
1112 // The resize rect might have changed while this was inactive -- send the new
1113 // one to make sure it's up to date.
1114 RenderViewHostImpl* rvh =
1115 static_cast<RenderViewHostImpl*>(GetRenderViewHost());
1116 if (rvh) {
1117 rvh->ResizeRectChanged(GetRootWindowResizerRect());
1118 }
1119
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001120 should_normally_be_visible_ = true;
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001121 NotificationService::current()->Notify(
1122 NOTIFICATION_WEB_CONTENTS_VISIBILITY_CHANGED,
1123 Source<WebContents>(this),
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001124 Details<const bool>(&should_normally_be_visible_));
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001125}
1126
1127void WebContentsImpl::WasHidden() {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001128 // If there are entities capturing screenshots or video (e.g., mirroring),
1129 // don't activate the "disable rendering" optimization.
1130 if (capturer_count_ == 0) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001131 // |GetRenderViewHost()| can be NULL if the user middle clicks a link to
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001132 // open a tab in the background, then closes the tab before selecting it.
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001133 // This is because closing the tab calls WebContentsImpl::Destroy(), which
1134 // removes the |GetRenderViewHost()|; then when we actually destroy the
1135 // window, OnWindowPosChanged() notices and calls WasHidden() (which
1136 // calls us).
1137 RenderWidgetHostViewPort* rwhv =
1138 RenderWidgetHostViewPort::FromRWHV(GetRenderWidgetHostView());
1139 if (rwhv)
1140 rwhv->WasHidden();
1141 }
1142
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001143 should_normally_be_visible_ = false;
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001144 NotificationService::current()->Notify(
1145 NOTIFICATION_WEB_CONTENTS_VISIBILITY_CHANGED,
1146 Source<WebContents>(this),
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001147 Details<const bool>(&should_normally_be_visible_));
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001148}
1149
1150bool WebContentsImpl::NeedToFireBeforeUnload() {
1151 // TODO(creis): Should we fire even for interstitial pages?
1152 return WillNotifyDisconnection() &&
1153 !ShowingInterstitialPage() &&
1154 !static_cast<RenderViewHostImpl*>(
1155 GetRenderViewHost())->SuddenTerminationAllowed();
1156}
1157
1158void WebContentsImpl::Stop() {
1159 render_manager_.Stop();
1160 FOR_EACH_OBSERVER(WebContentsObserver, observers_, StopNavigation());
1161}
1162
1163WebContents* WebContentsImpl::Clone() {
1164 // We use our current SiteInstance since the cloned entry will use it anyway.
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001165 // We pass our own opener so that the cloned page can access it if it was
1166 // before.
1167 CreateParams create_params(GetBrowserContext(), GetSiteInstance());
1168 create_params.initial_size = view_->GetContainerSize();
1169 WebContentsImpl* tc = CreateWithOpener(create_params, opener_);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001170 tc->GetController().CopyStateFrom(controller_);
1171 FOR_EACH_OBSERVER(WebContentsObserver,
1172 observers_,
1173 DidCloneToNewWebContents(this, tc));
1174 return tc;
1175}
1176
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001177void WebContentsImpl::Observe(int type,
1178 const NotificationSource& source,
1179 const NotificationDetails& details) {
1180 switch (type) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001181 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: {
1182 RenderWidgetHost* host = Source<RenderWidgetHost>(source).ptr();
1183 for (PendingWidgetViews::iterator i = pending_widget_views_.begin();
1184 i != pending_widget_views_.end(); ++i) {
1185 if (host->GetView() == i->second) {
1186 pending_widget_views_.erase(i);
1187 break;
1188 }
1189 }
1190 break;
1191 }
1192 default:
1193 NOTREACHED();
1194 }
1195}
1196
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001197void WebContentsImpl::Init(const WebContents::CreateParams& params) {
1198 render_manager_.Init(
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01001199 params.browser_context, params.site_instance, params.routing_id,
1200 params.main_frame_routing_id);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001201
1202 view_.reset(GetContentClient()->browser()->
1203 OverrideCreateWebContentsView(this, &render_view_host_delegate_view_));
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01001204 if (view_) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001205 CHECK(render_view_host_delegate_view_);
1206 } else {
1207 WebContentsViewDelegate* delegate =
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001208 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
1209
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01001210 if (browser_plugin_guest_) {
Ben Murdoch7dbb3d52013-07-17 14:55:54 +01001211 scoped_ptr<WebContentsViewPort> platform_view(CreateWebContentsView(
1212 this, delegate, &render_view_host_delegate_view_));
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001213
1214 WebContentsViewGuest* rv = new WebContentsViewGuest(
Ben Murdoch7dbb3d52013-07-17 14:55:54 +01001215 this, browser_plugin_guest_.get(), platform_view.Pass(),
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +01001216 render_view_host_delegate_view_);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001217 render_view_host_delegate_view_ = rv;
1218 view_.reset(rv);
1219 } else {
1220 // Regular WebContentsView.
1221 view_.reset(CreateWebContentsView(
1222 this, delegate, &render_view_host_delegate_view_));
1223 }
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001224 CHECK(render_view_host_delegate_view_);
1225 }
1226 CHECK(view_.get());
1227
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001228 gfx::Size initial_size = params.initial_size;
1229 view_->CreateView(initial_size, params.context);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001230
1231 // Listen for whether our opener gets destroyed.
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01001232 if (opener_)
1233 AddDestructionObserver(opener_);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001234
1235 registrar_.Add(this,
1236 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1237 NotificationService::AllBrowserContextsAndSources());
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +01001238#if defined(OS_ANDROID)
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001239 java_bridge_dispatcher_host_manager_.reset(
1240 new JavaBridgeDispatcherHostManager(this));
1241#endif
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001242
1243#if defined(OS_ANDROID)
1244 date_time_chooser_.reset(new DateTimeChooserAndroid());
1245#endif
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001246}
1247
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01001248void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl* web_contents) {
1249 RemoveDestructionObserver(web_contents);
1250
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001251 // Clear the opener if it has been closed.
1252 if (web_contents == opener_) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001253 opener_ = NULL;
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001254 return;
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001255 }
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001256 // Clear a pending contents that has been closed before being shown.
1257 for (PendingContents::iterator iter = pending_contents_.begin();
1258 iter != pending_contents_.end();
1259 ++iter) {
1260 if (iter->second != web_contents)
1261 continue;
1262 pending_contents_.erase(iter);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001263 return;
1264 }
1265 NOTREACHED();
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001266}
1267
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01001268void WebContentsImpl::AddDestructionObserver(WebContentsImpl* web_contents) {
1269 if (!ContainsKey(destruction_observers_, web_contents)) {
1270 destruction_observers_[web_contents] =
1271 new DestructionObserver(this, web_contents);
1272 }
1273}
1274
1275void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl* web_contents) {
1276 DestructionObservers::iterator iter =
1277 destruction_observers_.find(web_contents);
1278 if (iter != destruction_observers_.end()) {
1279 delete destruction_observers_[web_contents];
1280 destruction_observers_.erase(iter);
1281 }
1282}
1283
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001284void WebContentsImpl::AddObserver(WebContentsObserver* observer) {
1285 observers_.AddObserver(observer);
1286}
1287
1288void WebContentsImpl::RemoveObserver(WebContentsObserver* observer) {
1289 observers_.RemoveObserver(observer);
1290}
1291
1292void WebContentsImpl::Activate() {
1293 if (delegate_)
1294 delegate_->ActivateContents(this);
1295}
1296
1297void WebContentsImpl::Deactivate() {
1298 if (delegate_)
1299 delegate_->DeactivateContents(this);
1300}
1301
1302void WebContentsImpl::LostCapture() {
1303 if (delegate_)
1304 delegate_->LostCapture();
1305}
1306
1307void WebContentsImpl::RenderWidgetDeleted(
1308 RenderWidgetHostImpl* render_widget_host) {
1309 if (is_being_destroyed_) {
1310 // |created_widgets_| might have been destroyed.
1311 return;
1312 }
1313
1314 std::set<RenderWidgetHostImpl*>::iterator iter =
1315 created_widgets_.find(render_widget_host);
1316 if (iter != created_widgets_.end())
1317 created_widgets_.erase(iter);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001318
1319 if (render_widget_host &&
1320 render_widget_host->GetRoutingID() == fullscreen_widget_routing_id_) {
1321 FOR_EACH_OBSERVER(WebContentsObserver,
1322 observers_,
1323 DidDestroyFullscreenWidget(
1324 fullscreen_widget_routing_id_));
1325 fullscreen_widget_routing_id_ = MSG_ROUTING_NONE;
1326 }
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001327}
1328
1329bool WebContentsImpl::PreHandleKeyboardEvent(
1330 const NativeWebKeyboardEvent& event,
1331 bool* is_keyboard_shortcut) {
1332 return delegate_ &&
1333 delegate_->PreHandleKeyboardEvent(this, event, is_keyboard_shortcut);
1334}
1335
1336void WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +01001337 if (browser_plugin_embedder_ &&
1338 browser_plugin_embedder_->HandleKeyboardEvent(event)) {
1339 return;
1340 }
1341
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001342 if (delegate_)
1343 delegate_->HandleKeyboardEvent(this, event);
1344}
1345
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001346bool WebContentsImpl::PreHandleWheelEvent(
1347 const WebKit::WebMouseWheelEvent& event) {
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01001348#if !defined(OS_MACOSX)
1349 // On platforms other than Mac, control+mousewheel changes zoom. On Mac, this
1350 // isn't done for two reasons:
1351 // -the OS already has a gesture to do this through pinch-zoom
1352 // -if a user starts an inertial scroll, let's go, and presses control
1353 // (i.e. control+tab) then the OS's buffered scroll events will come in
1354 // with control key set which isn't what the user wants
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001355 if (delegate_ &&
1356 event.wheelTicksY &&
1357 (event.modifiers & WebKit::WebInputEvent::ControlKey)) {
1358 delegate_->ContentsZoomChange(event.wheelTicksY > 0);
1359 return true;
1360 }
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01001361#endif
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001362
1363 return false;
1364}
1365
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01001366#if defined(OS_WIN) && defined(USE_AURA)
1367gfx::NativeViewAccessible WebContentsImpl::GetParentNativeViewAccessible() {
1368 return accessible_parent_;
1369}
1370#endif
1371
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001372void WebContentsImpl::HandleMouseDown() {
1373 if (delegate_)
1374 delegate_->HandleMouseDown();
1375}
1376
1377void WebContentsImpl::HandleMouseUp() {
1378 if (delegate_)
1379 delegate_->HandleMouseUp();
1380}
1381
1382void WebContentsImpl::HandlePointerActivate() {
1383 if (delegate_)
1384 delegate_->HandlePointerActivate();
1385}
1386
1387void WebContentsImpl::HandleGestureBegin() {
1388 if (delegate_)
1389 delegate_->HandleGestureBegin();
1390}
1391
1392void WebContentsImpl::HandleGestureEnd() {
1393 if (delegate_)
1394 delegate_->HandleGestureEnd();
1395}
1396
1397void WebContentsImpl::ToggleFullscreenMode(bool enter_fullscreen) {
1398 if (delegate_)
1399 delegate_->ToggleFullscreenModeForTab(this, enter_fullscreen);
1400}
1401
1402bool WebContentsImpl::IsFullscreenForCurrentTab() const {
1403 return delegate_ ? delegate_->IsFullscreenForTabOrPending(this) : false;
1404}
1405
1406void WebContentsImpl::RequestToLockMouse(bool user_gesture,
1407 bool last_unlocked_by_target) {
1408 if (delegate_) {
1409 delegate_->RequestToLockMouse(this, user_gesture, last_unlocked_by_target);
1410 } else {
1411 GotResponseToLockMouseRequest(false);
1412 }
1413}
1414
1415void WebContentsImpl::LostMouseLock() {
1416 if (delegate_)
1417 delegate_->LostMouseLock();
1418}
1419
1420void WebContentsImpl::CreateNewWindow(
1421 int route_id,
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01001422 int main_frame_route_id,
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001423 const ViewHostMsg_CreateWindow_Params& params,
1424 SessionStorageNamespace* session_storage_namespace) {
Ben Murdocha3f7b4e2013-07-24 10:36:34 +01001425 if (delegate_ &&
1426 !delegate_->ShouldCreateWebContents(this,
1427 route_id,
1428 params.window_container_type,
1429 params.frame_name,
1430 params.target_url,
1431 params.referrer,
1432 params.disposition,
1433 params.features,
1434 params.user_gesture,
1435 params.opener_suppressed)) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001436 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(route_id);
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01001437 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(
1438 main_frame_route_id);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001439 return;
1440 }
1441
1442 // We usually create the new window in the same BrowsingInstance (group of
1443 // script-related windows), by passing in the current SiteInstance. However,
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001444 // if the opener is being suppressed (in a non-guest), we create a new
1445 // SiteInstance in its own BrowsingInstance.
1446 bool is_guest = GetRenderProcessHost()->IsGuest();
1447
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001448 scoped_refptr<SiteInstance> site_instance =
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001449 params.opener_suppressed && !is_guest ?
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001450 SiteInstance::CreateForURL(GetBrowserContext(), params.target_url) :
1451 GetSiteInstance();
1452
1453 // Create the new web contents. This will automatically create the new
1454 // WebContentsView. In the future, we may want to create the view separately.
1455 WebContentsImpl* new_contents =
1456 new WebContentsImpl(GetBrowserContext(),
1457 params.opener_suppressed ? NULL : this);
1458
1459 // We must assign the SessionStorageNamespace before calling Init().
1460 //
1461 // http://crbug.com/142685
Ben Murdochca12bfa2013-07-23 11:17:05 +01001462 const std::string& partition_id =
1463 GetContentClient()->browser()->
1464 GetStoragePartitionIdForSite(GetBrowserContext(),
1465 site_instance->GetSiteURL());
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01001466 StoragePartition* partition = BrowserContext::GetStoragePartition(
1467 GetBrowserContext(), site_instance.get());
Ben Murdochbb1529c2013-08-08 10:24:53 +01001468 DOMStorageContextWrapper* dom_storage_context =
1469 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001470 SessionStorageNamespaceImpl* session_storage_namespace_impl =
1471 static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
1472 CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
1473 new_contents->GetController().SetSessionStorageNamespace(
Ben Murdochca12bfa2013-07-23 11:17:05 +01001474 partition_id,
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001475 session_storage_namespace);
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01001476 CreateParams create_params(GetBrowserContext(), site_instance.get());
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001477 create_params.routing_id = route_id;
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01001478 create_params.main_frame_routing_id = main_frame_route_id;
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001479 if (!is_guest) {
1480 create_params.context = view_->GetNativeView();
1481 create_params.initial_size = view_->GetContainerSize();
1482 } else {
1483 // This makes |new_contents| act as a guest.
1484 // For more info, see comment above class BrowserPluginGuest.
1485 int instance_id = GetBrowserPluginGuestManager()->get_next_instance_id();
1486 WebContentsImpl* new_contents_impl =
1487 static_cast<WebContentsImpl*>(new_contents);
Ben Murdocheb525c52013-07-10 11:40:50 +01001488 BrowserPluginGuest::CreateWithOpener(instance_id, new_contents_impl,
1489 GetBrowserPluginGuest(), !!new_contents_impl->opener());
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001490 }
1491 new_contents->Init(create_params);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001492
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001493 // Save the window for later if we're not suppressing the opener (since it
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01001494 // will be shown immediately).
1495 if (!params.opener_suppressed) {
1496 if (!is_guest) {
1497 WebContentsViewPort* new_view = new_contents->view_.get();
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001498
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01001499 // TODO(brettw): It seems bogus that we have to call this function on the
1500 // newly created object and give it one of its own member variables.
1501 new_view->CreateViewForWidget(new_contents->GetRenderViewHost());
1502 }
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001503 // Save the created window associated with the route so we can show it
1504 // later.
1505 DCHECK_NE(MSG_ROUTING_NONE, route_id);
1506 pending_contents_[route_id] = new_contents;
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01001507 AddDestructionObserver(new_contents);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001508 }
1509
1510 if (delegate_) {
1511 delegate_->WebContentsCreated(
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001512 this, params.opener_frame_id, params.frame_name,
1513 params.target_url, new_contents);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001514 }
1515
1516 if (params.opener_suppressed) {
1517 // When the opener is suppressed, the original renderer cannot access the
1518 // new window. As a result, we need to show and navigate the window here.
1519 bool was_blocked = false;
1520 if (delegate_) {
1521 gfx::Rect initial_pos;
1522 delegate_->AddNewContents(
1523 this, new_contents, params.disposition, initial_pos,
1524 params.user_gesture, &was_blocked);
1525 }
1526 if (!was_blocked) {
1527 OpenURLParams open_params(params.target_url,
1528 Referrer(),
1529 CURRENT_TAB,
1530 PAGE_TRANSITION_LINK,
1531 true /* is_renderer_initiated */);
Ben Murdoch7dbb3d52013-07-17 14:55:54 +01001532 open_params.user_gesture = params.user_gesture;
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001533 new_contents->OpenURL(open_params);
1534 }
1535 }
1536}
1537
1538void WebContentsImpl::CreateNewWidget(int route_id,
1539 WebKit::WebPopupType popup_type) {
1540 CreateNewWidget(route_id, false, popup_type);
1541}
1542
1543void WebContentsImpl::CreateNewFullscreenWidget(int route_id) {
1544 CreateNewWidget(route_id, true, WebKit::WebPopupTypeNone);
1545}
1546
1547void WebContentsImpl::CreateNewWidget(int route_id,
1548 bool is_fullscreen,
1549 WebKit::WebPopupType popup_type) {
1550 RenderProcessHost* process = GetRenderProcessHost();
1551 RenderWidgetHostImpl* widget_host =
1552 new RenderWidgetHostImpl(this, process, route_id);
1553 created_widgets_.insert(widget_host);
1554
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001555 RenderWidgetHostViewPort* widget_view = RenderWidgetHostViewPort::FromRWHV(
1556 view_->CreateViewForPopupWidget(widget_host));
1557 if (!widget_view)
1558 return;
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001559 if (!is_fullscreen) {
1560 // Popups should not get activated.
1561 widget_view->SetPopupType(popup_type);
1562 }
1563 // Save the created widget associated with the route so we can show it later.
1564 pending_widget_views_[route_id] = widget_view;
1565
1566#if defined(OS_MACOSX)
1567 // A RenderWidgetHostViewMac has lifetime scoped to the view. We'll retain it
1568 // to allow it to survive the trip without being hosted.
1569 base::mac::NSObjectRetain(widget_view->GetNativeView());
1570#endif
1571}
1572
1573void WebContentsImpl::ShowCreatedWindow(int route_id,
1574 WindowOpenDisposition disposition,
1575 const gfx::Rect& initial_pos,
1576 bool user_gesture) {
1577 WebContentsImpl* contents = GetCreatedWindow(route_id);
1578 if (contents) {
1579 WebContentsDelegate* delegate = GetDelegate();
1580 if (delegate) {
1581 delegate->AddNewContents(
1582 this, contents, disposition, initial_pos, user_gesture, NULL);
1583 }
1584 }
1585}
1586
1587void WebContentsImpl::ShowCreatedWidget(int route_id,
1588 const gfx::Rect& initial_pos) {
1589 ShowCreatedWidget(route_id, false, initial_pos);
1590}
1591
1592void WebContentsImpl::ShowCreatedFullscreenWidget(int route_id) {
1593 ShowCreatedWidget(route_id, true, gfx::Rect());
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001594
1595 DCHECK_EQ(MSG_ROUTING_NONE, fullscreen_widget_routing_id_);
1596 fullscreen_widget_routing_id_ = route_id;
1597 FOR_EACH_OBSERVER(WebContentsObserver,
1598 observers_,
1599 DidShowFullscreenWidget(route_id));
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001600}
1601
1602void WebContentsImpl::ShowCreatedWidget(int route_id,
1603 bool is_fullscreen,
1604 const gfx::Rect& initial_pos) {
1605 if (delegate_)
1606 delegate_->RenderWidgetShowing();
1607
1608 RenderWidgetHostViewPort* widget_host_view =
1609 RenderWidgetHostViewPort::FromRWHV(GetCreatedWidget(route_id));
1610 if (!widget_host_view)
1611 return;
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001612 if (is_fullscreen)
1613 widget_host_view->InitAsFullscreen(GetRenderWidgetHostViewPort());
1614 else
1615 widget_host_view->InitAsPopup(GetRenderWidgetHostViewPort(), initial_pos);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001616
1617 RenderWidgetHostImpl* render_widget_host_impl =
1618 RenderWidgetHostImpl::From(widget_host_view->GetRenderWidgetHost());
1619 render_widget_host_impl->Init();
1620 // Only allow privileged mouse lock for fullscreen render widget, which is
1621 // used to implement Pepper Flash fullscreen.
1622 render_widget_host_impl->set_allow_privileged_mouse_lock(is_fullscreen);
1623
1624#if defined(OS_MACOSX)
1625 // A RenderWidgetHostViewMac has lifetime scoped to the view. Now that it's
1626 // properly embedded (or purposefully ignored) we can release the retain we
1627 // took in CreateNewWidget().
1628 base::mac::NSObjectRelease(widget_host_view->GetNativeView());
1629#endif
1630}
1631
1632WebContentsImpl* WebContentsImpl::GetCreatedWindow(int route_id) {
1633 PendingContents::iterator iter = pending_contents_.find(route_id);
1634
1635 // Certain systems can block the creation of new windows. If we didn't succeed
1636 // in creating one, just return NULL.
1637 if (iter == pending_contents_.end()) {
1638 return NULL;
1639 }
1640
1641 WebContentsImpl* new_contents = iter->second;
1642 pending_contents_.erase(route_id);
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01001643 RemoveDestructionObserver(new_contents);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001644
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01001645 // Don't initialize the guest WebContents immediately.
1646 if (new_contents->GetRenderProcessHost()->IsGuest())
1647 return new_contents;
1648
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001649 if (!new_contents->GetRenderProcessHost()->HasConnection() ||
1650 !new_contents->GetRenderViewHost()->GetView())
1651 return NULL;
1652
1653 // TODO(brettw): It seems bogus to reach into here and initialize the host.
1654 static_cast<RenderViewHostImpl*>(new_contents->GetRenderViewHost())->Init();
1655 return new_contents;
1656}
1657
1658RenderWidgetHostView* WebContentsImpl::GetCreatedWidget(int route_id) {
1659 PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id);
1660 if (iter == pending_widget_views_.end()) {
1661 DCHECK(false);
1662 return NULL;
1663 }
1664
1665 RenderWidgetHostView* widget_host_view = iter->second;
1666 pending_widget_views_.erase(route_id);
1667
1668 RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
1669 if (!widget_host->GetProcess()->HasConnection()) {
1670 // The view has gone away or the renderer crashed. Nothing to do.
1671 return NULL;
1672 }
1673
1674 return widget_host_view;
1675}
1676
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +01001677void WebContentsImpl::ShowContextMenu(const ContextMenuParams& params) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001678 // Allow WebContentsDelegates to handle the context menu operation first.
1679 if (delegate_ && delegate_->HandleContextMenu(params))
1680 return;
1681
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +01001682 render_view_host_delegate_view_->ShowContextMenu(params);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001683}
1684
1685void WebContentsImpl::RequestMediaAccessPermission(
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001686 const MediaStreamRequest& request,
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001687 const MediaResponseCallback& callback) {
1688 if (delegate_)
1689 delegate_->RequestMediaAccessPermission(this, request, callback);
1690 else
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01001691 callback.Run(MediaStreamDevices(), scoped_ptr<MediaStreamUI>());
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001692}
1693
Ben Murdocha3f7b4e2013-07-24 10:36:34 +01001694SessionStorageNamespace* WebContentsImpl::GetSessionStorageNamespace(
1695 SiteInstance* instance) {
1696 return controller_.GetSessionStorageNamespace(instance);
1697}
1698
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01001699void WebContentsImpl::DidSendScreenRects(RenderWidgetHostImpl* rwh) {
1700 if (browser_plugin_embedder_)
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +01001701 browser_plugin_embedder_->DidSendScreenRects();
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01001702}
1703
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001704void WebContentsImpl::UpdatePreferredSize(const gfx::Size& pref_size) {
1705 preferred_size_ = pref_size;
1706 if (delegate_)
1707 delegate_->UpdatePreferredSize(this, pref_size);
1708}
1709
1710void WebContentsImpl::ResizeDueToAutoResize(const gfx::Size& new_size) {
1711 if (delegate_)
1712 delegate_->ResizeDueToAutoResize(this, new_size);
1713}
1714
1715WebContents* WebContentsImpl::OpenURL(const OpenURLParams& params) {
1716 if (!delegate_)
1717 return NULL;
1718
1719 WebContents* new_contents = delegate_->OpenURLFromTab(this, params);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001720 return new_contents;
1721}
1722
1723bool WebContentsImpl::Send(IPC::Message* message) {
1724 if (!GetRenderViewHost()) {
1725 delete message;
1726 return false;
1727 }
1728
1729 return GetRenderViewHost()->Send(message);
1730}
1731
1732bool WebContentsImpl::NavigateToPendingEntry(
1733 NavigationController::ReloadType reload_type) {
1734 return NavigateToEntry(
1735 *NavigationEntryImpl::FromNavigationEntry(controller_.GetPendingEntry()),
1736 reload_type);
1737}
1738
1739void WebContentsImpl::RenderViewForInterstitialPageCreated(
1740 RenderViewHost* render_view_host) {
1741 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1742 RenderViewForInterstitialPageCreated(render_view_host));
1743}
1744
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001745void WebContentsImpl::AttachInterstitialPage(
1746 InterstitialPageImpl* interstitial_page) {
1747 DCHECK(interstitial_page);
1748 render_manager_.set_interstitial_page(interstitial_page);
1749 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1750 DidAttachInterstitialPage());
1751}
1752
1753void WebContentsImpl::DetachInterstitialPage() {
1754 if (GetInterstitialPage())
1755 render_manager_.remove_interstitial_page();
1756 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1757 DidDetachInterstitialPage());
1758}
1759
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001760bool WebContentsImpl::NavigateToEntry(
1761 const NavigationEntryImpl& entry,
1762 NavigationController::ReloadType reload_type) {
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +01001763 TRACE_EVENT0("browser", "WebContentsImpl::NavigateToEntry");
1764
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001765 // The renderer will reject IPC messages with URLs longer than
1766 // this limit, so don't attempt to navigate with a longer URL.
1767 if (entry.GetURL().spec().size() > kMaxURLChars)
1768 return false;
1769
1770 RenderViewHostImpl* dest_render_view_host =
1771 static_cast<RenderViewHostImpl*>(render_manager_.Navigate(entry));
1772 if (!dest_render_view_host)
1773 return false; // Unable to create the desired render view host.
1774
1775 // For security, we should never send non-Web-UI URLs to a Web UI renderer.
1776 // Double check that here.
1777 int enabled_bindings = dest_render_view_host->GetEnabledBindings();
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001778 bool data_urls_allowed = delegate_ && delegate_->CanLoadDataURLsInWebUI();
1779 bool is_allowed_in_web_ui_renderer =
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001780 WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
1781 GetBrowserContext(), entry.GetURL(), data_urls_allowed);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001782 if ((enabled_bindings & BINDINGS_POLICY_WEB_UI) &&
1783 !is_allowed_in_web_ui_renderer) {
1784 // Log the URL to help us diagnose any future failures of this CHECK.
1785 GetContentClient()->SetActiveURL(entry.GetURL());
1786 CHECK(0);
1787 }
1788
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001789 // Notify observers that we will navigate in this RV.
1790 FOR_EACH_OBSERVER(WebContentsObserver,
1791 observers_,
1792 AboutToNavigateRenderView(dest_render_view_host));
1793
1794 // Used for page load time metrics.
1795 current_load_start_ = base::TimeTicks::Now();
1796
1797 // Navigate in the desired RenderViewHost.
1798 ViewMsg_Navigate_Params navigate_params;
1799 MakeNavigateParams(entry, controller_, delegate_, reload_type,
1800 &navigate_params);
1801 dest_render_view_host->Navigate(navigate_params);
1802
1803 if (entry.GetPageID() == -1) {
1804 // HACK!! This code suppresses javascript: URLs from being added to
1805 // session history, which is what we want to do for javascript: URLs that
1806 // do not generate content. What we really need is a message from the
1807 // renderer telling us that a new page was not created. The same message
1808 // could be used for mailto: URLs and the like.
1809 if (entry.GetURL().SchemeIs(chrome::kJavaScriptScheme))
1810 return false;
1811 }
1812
1813 // Notify observers about navigation.
1814 FOR_EACH_OBSERVER(WebContentsObserver,
1815 observers_,
1816 NavigateToPendingEntry(entry.GetURL(), reload_type));
1817
1818 if (delegate_)
1819 delegate_->DidNavigateToPendingEntry(this);
1820
1821 return true;
1822}
1823
1824void WebContentsImpl::SetHistoryLengthAndPrune(
1825 const SiteInstance* site_instance,
1826 int history_length,
1827 int32 minimum_page_id) {
1828 // SetHistoryLengthAndPrune doesn't work when there are pending cross-site
1829 // navigations. Callers should ensure that this is the case.
1830 if (render_manager_.pending_render_view_host()) {
1831 NOTREACHED();
1832 return;
1833 }
1834 RenderViewHostImpl* rvh = GetRenderViewHostImpl();
1835 if (!rvh) {
1836 NOTREACHED();
1837 return;
1838 }
1839 if (site_instance && rvh->GetSiteInstance() != site_instance) {
1840 NOTREACHED();
1841 return;
1842 }
1843 Send(new ViewMsg_SetHistoryLengthAndPrune(GetRoutingID(),
1844 history_length,
1845 minimum_page_id));
1846}
1847
1848void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
1849 if (ShowingInterstitialPage()) {
1850 render_manager_.interstitial_page()->FocusThroughTabTraversal(reverse);
1851 return;
1852 }
1853 GetRenderViewHostImpl()->SetInitialFocus(reverse);
1854}
1855
1856bool WebContentsImpl::ShowingInterstitialPage() const {
1857 return render_manager_.interstitial_page() != NULL;
1858}
1859
1860InterstitialPage* WebContentsImpl::GetInterstitialPage() const {
1861 return render_manager_.interstitial_page();
1862}
1863
1864bool WebContentsImpl::IsSavable() {
1865 // WebKit creates Document object when MIME type is application/xhtml+xml,
1866 // so we also support this MIME type.
1867 return contents_mime_type_ == "text/html" ||
1868 contents_mime_type_ == "text/xml" ||
1869 contents_mime_type_ == "application/xhtml+xml" ||
1870 contents_mime_type_ == "text/plain" ||
1871 contents_mime_type_ == "text/css" ||
1872 net::IsSupportedJavascriptMimeType(contents_mime_type_.c_str());
1873}
1874
1875void WebContentsImpl::OnSavePage() {
1876 // If we can not save the page, try to download it.
1877 if (!IsSavable()) {
1878 RecordDownloadSource(INITIATED_BY_SAVE_PACKAGE_ON_NON_HTML);
Ben Murdochca12bfa2013-07-23 11:17:05 +01001879 SaveFrame(GetURL(), Referrer());
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001880 return;
1881 }
1882
1883 Stop();
1884
1885 // Create the save package and possibly prompt the user for the name to save
1886 // the page as. The user prompt is an asynchronous operation that runs on
1887 // another thread.
1888 save_package_ = new SavePackage(this);
1889 save_package_->GetSaveInfo();
1890}
1891
1892// Used in automated testing to bypass prompting the user for file names.
1893// Instead, the names and paths are hard coded rather than running them through
1894// file name sanitation and extension / mime checking.
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001895bool WebContentsImpl::SavePage(const base::FilePath& main_file,
1896 const base::FilePath& dir_path,
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001897 SavePageType save_type) {
1898 // Stop the page from navigating.
1899 Stop();
1900
1901 save_package_ = new SavePackage(this, save_type, main_file, dir_path);
1902 return save_package_->Init(SavePackageDownloadCreatedCallback());
1903}
1904
Ben Murdochca12bfa2013-07-23 11:17:05 +01001905void WebContentsImpl::SaveFrame(const GURL& url,
1906 const Referrer& referrer) {
1907 if (!GetURL().is_valid())
1908 return;
1909 bool is_main_frame = (url == GetURL());
1910
1911 DownloadManager* dlm =
1912 BrowserContext::GetDownloadManager(GetBrowserContext());
1913 if (!dlm)
1914 return;
1915 int64 post_id = -1;
1916 if (is_main_frame) {
1917 const NavigationEntry* entry = controller_.GetActiveEntry();
1918 if (entry)
1919 post_id = entry->GetPostID();
1920 }
1921 scoped_ptr<DownloadUrlParameters> params(
1922 DownloadUrlParameters::FromWebContents(this, url));
1923 params->set_referrer(referrer);
1924 params->set_post_id(post_id);
1925 params->set_prefer_cache(true);
1926 if (post_id >= 0)
1927 params->set_method("POST");
1928 params->set_prompt(true);
1929 dlm->DownloadUrl(params.Pass());
1930}
1931
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001932void WebContentsImpl::GenerateMHTML(
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001933 const base::FilePath& file,
1934 const base::Callback<void(const base::FilePath&, int64)>& callback) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001935 MHTMLGenerationManager::GetInstance()->GenerateMHTML(this, file, callback);
1936}
1937
1938bool WebContentsImpl::IsActiveEntry(int32 page_id) {
1939 NavigationEntryImpl* active_entry =
1940 NavigationEntryImpl::FromNavigationEntry(controller_.GetActiveEntry());
1941 return (active_entry != NULL &&
1942 active_entry->site_instance() == GetSiteInstance() &&
1943 active_entry->GetPageID() == page_id);
1944}
1945
1946const std::string& WebContentsImpl::GetContentsMimeType() const {
1947 return contents_mime_type_;
1948}
1949
1950bool WebContentsImpl::WillNotifyDisconnection() const {
1951 return notify_disconnection_;
1952}
1953
1954void WebContentsImpl::SetOverrideEncoding(const std::string& encoding) {
1955 SetEncoding(encoding);
1956 Send(new ViewMsg_SetPageEncoding(GetRoutingID(), encoding));
1957}
1958
1959void WebContentsImpl::ResetOverrideEncoding() {
1960 encoding_.clear();
1961 Send(new ViewMsg_ResetPageEncodingToDefault(GetRoutingID()));
1962}
1963
1964RendererPreferences* WebContentsImpl::GetMutableRendererPrefs() {
1965 return &renderer_preferences_;
1966}
1967
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001968void WebContentsImpl::Close() {
1969 Close(GetRenderViewHost());
1970}
1971
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01001972void WebContentsImpl::DragSourceEndedAt(int client_x, int client_y,
1973 int screen_x, int screen_y, WebKit::WebDragOperation operation) {
1974 if (browser_plugin_embedder_.get())
1975 browser_plugin_embedder_->DragSourceEndedAt(client_x, client_y,
1976 screen_x, screen_y, operation);
1977 if (GetRenderViewHost())
1978 GetRenderViewHostImpl()->DragSourceEndedAt(client_x, client_y,
1979 screen_x, screen_y, operation);
1980}
1981
1982void WebContentsImpl::DragSourceMovedTo(int client_x, int client_y,
1983 int screen_x, int screen_y) {
1984 if (browser_plugin_embedder_.get())
1985 browser_plugin_embedder_->DragSourceMovedTo(client_x, client_y,
1986 screen_x, screen_y);
1987 if (GetRenderViewHost())
1988 GetRenderViewHostImpl()->DragSourceMovedTo(client_x, client_y,
1989 screen_x, screen_y);
1990}
1991
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001992void WebContentsImpl::SystemDragEnded() {
1993 if (GetRenderViewHost())
1994 GetRenderViewHostImpl()->DragSourceSystemDragEnded();
1995 if (delegate_)
1996 delegate_->DragEnded();
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01001997 if (browser_plugin_embedder_.get())
1998 browser_plugin_embedder_->SystemDragEnded();
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001999}
2000
2001void WebContentsImpl::UserGestureDone() {
2002 OnUserGesture();
2003}
2004
2005void WebContentsImpl::SetClosedByUserGesture(bool value) {
2006 closed_by_user_gesture_ = value;
2007}
2008
2009bool WebContentsImpl::GetClosedByUserGesture() const {
2010 return closed_by_user_gesture_;
2011}
2012
2013double WebContentsImpl::GetZoomLevel() const {
2014 HostZoomMapImpl* zoom_map = static_cast<HostZoomMapImpl*>(
2015 HostZoomMap::GetForBrowserContext(GetBrowserContext()));
2016 if (!zoom_map)
2017 return 0;
2018
2019 double zoom_level;
2020 if (temporary_zoom_settings_) {
2021 zoom_level = zoom_map->GetTemporaryZoomLevel(
2022 GetRenderProcessHost()->GetID(), GetRenderViewHost()->GetRoutingID());
2023 } else {
2024 GURL url;
2025 NavigationEntry* active_entry = GetController().GetActiveEntry();
2026 // Since zoom map is updated using rewritten URL, use rewritten URL
2027 // to get the zoom level.
2028 url = active_entry ? active_entry->GetURL() : GURL::EmptyGURL();
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002029 zoom_level = zoom_map->GetZoomLevelForHostAndScheme(url.scheme(),
2030 net::GetHostOrSpecFromURL(url));
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002031 }
2032 return zoom_level;
2033}
2034
2035int WebContentsImpl::GetZoomPercent(bool* enable_increment,
2036 bool* enable_decrement) const {
2037 *enable_decrement = *enable_increment = false;
2038 // Calculate the zoom percent from the factor. Round up to the nearest whole
2039 // number.
2040 int percent = static_cast<int>(
Ben Murdoch58e6fbe2013-07-26 10:20:38 +01002041 ZoomLevelToZoomFactor(GetZoomLevel()) * 100 + 0.5);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002042 *enable_decrement = percent > minimum_zoom_percent_;
2043 *enable_increment = percent < maximum_zoom_percent_;
2044 return percent;
2045}
2046
2047void WebContentsImpl::ViewSource() {
2048 if (!delegate_)
2049 return;
2050
2051 NavigationEntry* active_entry = GetController().GetActiveEntry();
2052 if (!active_entry)
2053 return;
2054
2055 delegate_->ViewSourceForTab(this, active_entry->GetURL());
2056}
2057
2058void WebContentsImpl::ViewFrameSource(const GURL& url,
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01002059 const PageState& page_state) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002060 if (!delegate_)
2061 return;
2062
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01002063 delegate_->ViewSourceForFrame(this, url, page_state);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002064}
2065
2066int WebContentsImpl::GetMinimumZoomPercent() const {
2067 return minimum_zoom_percent_;
2068}
2069
2070int WebContentsImpl::GetMaximumZoomPercent() const {
2071 return maximum_zoom_percent_;
2072}
2073
2074gfx::Size WebContentsImpl::GetPreferredSize() const {
2075 return preferred_size_;
2076}
2077
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002078bool WebContentsImpl::GotResponseToLockMouseRequest(bool allowed) {
2079 return GetRenderViewHost() ?
2080 GetRenderViewHostImpl()->GotResponseToLockMouseRequest(allowed) : false;
2081}
2082
2083bool WebContentsImpl::HasOpener() const {
2084 return opener_ != NULL;
2085}
2086
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01002087void WebContentsImpl::DidChooseColorInColorChooser(SkColor color) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002088 Send(new ViewMsg_DidChooseColorResponse(
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01002089 GetRoutingID(), color_chooser_identifier_, color));
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002090}
2091
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01002092void WebContentsImpl::DidEndColorChooser() {
2093 Send(new ViewMsg_DidEndColorChooser(GetRoutingID(),
2094 color_chooser_identifier_));
2095 color_chooser_.reset();
2096 color_chooser_identifier_ = 0;
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002097}
2098
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01002099int WebContentsImpl::DownloadImage(const GURL& url,
2100 bool is_favicon,
Ben Murdocheb525c52013-07-10 11:40:50 +01002101 uint32_t preferred_image_size,
2102 uint32_t max_image_size,
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01002103 const ImageDownloadCallback& callback) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002104 RenderViewHost* host = GetRenderViewHost();
Ben Murdocheb525c52013-07-10 11:40:50 +01002105 int id = StartDownload(
2106 host, url, is_favicon, preferred_image_size, max_image_size);
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01002107 image_download_map_[id] = callback;
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002108 return id;
2109}
2110
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002111bool WebContentsImpl::FocusLocationBarByDefault() {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002112 NavigationEntry* entry = controller_.GetActiveEntry();
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01002113 if (entry && entry->GetURL() == GURL(kAboutBlankURL))
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002114 return true;
2115 return delegate_ && delegate_->ShouldFocusLocationBarByDefault(this);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002116}
2117
2118void WebContentsImpl::SetFocusToLocationBar(bool select_all) {
2119 if (delegate_)
2120 delegate_->SetFocusToLocationBar(select_all);
2121}
2122
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002123void WebContentsImpl::DidStartProvisionalLoadForFrame(
2124 RenderViewHost* render_view_host,
2125 int64 frame_id,
2126 int64 parent_frame_id,
2127 bool is_main_frame,
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002128 const GURL& url) {
2129 bool is_error_page = (url.spec() == kUnreachableWebDataURL);
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01002130 bool is_iframe_srcdoc = (url.spec() == kAboutSrcDocURL);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002131 GURL validated_url(url);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002132 RenderProcessHost* render_process_host =
2133 render_view_host->GetProcess();
2134 RenderViewHost::FilterURL(render_process_host, false, &validated_url);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002135
Ben Murdoch32409262013-08-07 11:04:47 +01002136 if (is_main_frame)
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002137 DidChangeLoadProgress(0);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002138
Ben Murdoch32409262013-08-07 11:04:47 +01002139 // Create a pending entry for this provisional load (if none exists) using the
2140 // current SiteInstance, and ensure the address bar updates accordingly.
2141 // We don't know the referrer or extra headers at this point, but the referrer
2142 // will be set properly upon commit.
2143 if (is_main_frame && !controller_.GetPendingEntry()) {
2144 NavigationEntryImpl* entry = NavigationEntryImpl::FromNavigationEntry(
2145 controller_.CreateNavigationEntry(validated_url,
2146 content::Referrer(),
2147 content::PAGE_TRANSITION_LINK,
2148 true /* is_renderer_initiated */,
2149 std::string(), GetBrowserContext()));
2150 entry->set_site_instance(
2151 static_cast<SiteInstanceImpl*>(GetSiteInstance()));
2152 controller_.SetPendingEntry(entry);
2153 NotifyNavigationStateChanged(content::INVALIDATE_TYPE_URL);
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01002154 }
2155
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002156 // Notify observers about the start of the provisional load.
2157 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2158 DidStartProvisionalLoadForFrame(frame_id, parent_frame_id,
2159 is_main_frame, validated_url, is_error_page,
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002160 is_iframe_srcdoc, render_view_host));
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002161
2162 if (is_main_frame) {
2163 // Notify observers about the provisional change in the main frame URL.
2164 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2165 ProvisionalChangeToMainFrameUrl(validated_url,
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002166 render_view_host));
2167 }
2168}
2169
2170void WebContentsImpl::DidRedirectProvisionalLoad(
2171 RenderViewHost* render_view_host,
2172 int32 page_id,
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002173 const GURL& source_url,
2174 const GURL& target_url) {
2175 // TODO(creis): Remove this method and have the pre-rendering code listen to
2176 // the ResourceDispatcherHost's RESOURCE_RECEIVED_REDIRECT notification
2177 // instead. See http://crbug.com/78512.
2178 GURL validated_source_url(source_url);
2179 GURL validated_target_url(target_url);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002180 RenderProcessHost* render_process_host =
2181 render_view_host->GetProcess();
2182 RenderViewHost::FilterURL(render_process_host, false, &validated_source_url);
2183 RenderViewHost::FilterURL(render_process_host, false, &validated_target_url);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002184 NavigationEntry* entry;
2185 if (page_id == -1) {
2186 entry = controller_.GetPendingEntry();
2187 } else {
2188 entry = controller_.GetEntryWithPageID(render_view_host->GetSiteInstance(),
2189 page_id);
2190 }
2191 if (!entry || entry->GetURL() != validated_source_url)
2192 return;
2193
2194 // Notify observers about the provisional change in the main frame URL.
2195 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2196 ProvisionalChangeToMainFrameUrl(validated_target_url,
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002197 render_view_host));
2198}
2199
2200void WebContentsImpl::DidFailProvisionalLoadWithError(
2201 RenderViewHost* render_view_host,
2202 const ViewHostMsg_DidFailProvisionalLoadWithError_Params& params) {
2203 VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec()
2204 << ", error_code: " << params.error_code
2205 << ", error_description: " << params.error_description
2206 << ", is_main_frame: " << params.is_main_frame
2207 << ", showing_repost_interstitial: " <<
2208 params.showing_repost_interstitial
2209 << ", frame_id: " << params.frame_id;
2210 GURL validated_url(params.url);
2211 RenderProcessHost* render_process_host =
2212 render_view_host->GetProcess();
2213 RenderViewHost::FilterURL(render_process_host, false, &validated_url);
2214
2215 if (net::ERR_ABORTED == params.error_code) {
2216 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
2217 // This means that the interstitial won't be torn down properly, which is
2218 // bad. But if we have an interstitial, go back to another tab type, and
2219 // then load the same interstitial again, we could end up getting the first
2220 // interstitial's "failed" message (as a result of the cancel) when we're on
2221 // the second one.
2222 //
2223 // We can't tell this apart, so we think we're tearing down the current page
2224 // which will cause a crash later one. There is also some code in
2225 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
2226 // out because of this problem.
2227 //
2228 // http://code.google.com/p/chromium/issues/detail?id=2855
2229 // Because this will not tear down the interstitial properly, if "back" is
2230 // back to another tab type, the interstitial will still be somewhat alive
2231 // in the previous tab type. If you navigate somewhere that activates the
2232 // tab with the interstitial again, you'll see a flash before the new load
2233 // commits of the interstitial page.
2234 if (ShowingInterstitialPage()) {
2235 LOG(WARNING) << "Discarding message during interstitial.";
2236 return;
2237 }
2238
2239 // Do not clear the pending entry if one exists, so that the user's typed
2240 // URL is not lost when a navigation fails or is aborted. We'll allow
2241 // the view to clear the pending entry and typed URL if the user requests.
2242
2243 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
2244 }
2245
2246 FOR_EACH_OBSERVER(WebContentsObserver,
2247 observers_,
2248 DidFailProvisionalLoad(params.frame_id,
2249 params.is_main_frame,
2250 validated_url,
2251 params.error_code,
2252 params.error_description,
2253 render_view_host));
2254}
2255
2256void WebContentsImpl::OnDidLoadResourceFromMemoryCache(
2257 const GURL& url,
2258 const std::string& security_info,
2259 const std::string& http_method,
2260 const std::string& mime_type,
2261 ResourceType::Type resource_type) {
2262 base::StatsCounter cache("WebKit.CacheHit");
2263 cache.Increment();
2264
2265 // Send out a notification that we loaded a resource from our memory cache.
2266 int cert_id = 0;
2267 net::CertStatus cert_status = 0;
2268 int security_bits = -1;
2269 int connection_status = 0;
2270 DeserializeSecurityInfo(security_info, &cert_id, &cert_status,
2271 &security_bits, &connection_status);
2272 LoadFromMemoryCacheDetails details(
2273 url, GetRenderProcessHost()->GetID(), cert_id, cert_status, http_method,
2274 mime_type, resource_type);
2275
2276 NotificationService::current()->Notify(
2277 NOTIFICATION_LOAD_FROM_MEMORY_CACHE,
2278 Source<NavigationController>(&controller_),
2279 Details<LoadFromMemoryCacheDetails>(&details));
2280}
2281
2282void WebContentsImpl::OnDidDisplayInsecureContent() {
2283 RecordAction(UserMetricsAction("SSL.DisplayedInsecureContent"));
2284 displayed_insecure_content_ = true;
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002285 SSLManager::NotifySSLInternalStateChanged(
2286 GetController().GetBrowserContext());
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002287}
2288
2289void WebContentsImpl::OnDidRunInsecureContent(
2290 const std::string& security_origin, const GURL& target_url) {
2291 LOG(INFO) << security_origin << " ran insecure content from "
2292 << target_url.possibly_invalid_spec();
2293 RecordAction(UserMetricsAction("SSL.RanInsecureContent"));
2294 if (EndsWith(security_origin, kDotGoogleDotCom, false))
2295 RecordAction(UserMetricsAction("SSL.RanInsecureContentGoogle"));
2296 controller_.ssl_manager()->DidRunInsecureContent(security_origin);
2297 displayed_insecure_content_ = true;
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002298 SSLManager::NotifySSLInternalStateChanged(
2299 GetController().GetBrowserContext());
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002300}
2301
2302void WebContentsImpl::OnDocumentLoadedInFrame(int64 frame_id) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002303 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2304 DocumentLoadedInFrame(frame_id, message_source_));
2305}
2306
2307void WebContentsImpl::OnDidFinishLoad(
2308 int64 frame_id,
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002309 const GURL& url,
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002310 bool is_main_frame) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002311 GURL validated_url(url);
2312 RenderProcessHost* render_process_host = message_source_->GetProcess();
2313 RenderViewHost::FilterURL(render_process_host, false, &validated_url);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002314 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2315 DidFinishLoad(frame_id, validated_url, is_main_frame,
2316 message_source_));
2317}
2318
2319void WebContentsImpl::OnDidFailLoadWithError(
2320 int64 frame_id,
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002321 const GURL& url,
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002322 bool is_main_frame,
2323 int error_code,
2324 const string16& error_description) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002325 GURL validated_url(url);
2326 RenderProcessHost* render_process_host = message_source_->GetProcess();
2327 RenderViewHost::FilterURL(render_process_host, false, &validated_url);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002328 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2329 DidFailLoad(frame_id, validated_url, is_main_frame,
2330 error_code, error_description,
2331 message_source_));
2332}
2333
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002334void WebContentsImpl::OnGoToEntryAtOffset(int offset) {
2335 if (!delegate_ || delegate_->OnGoToEntryOffset(offset)) {
2336 NavigationEntryImpl* entry = NavigationEntryImpl::FromNavigationEntry(
2337 controller_.GetEntryAtOffset(offset));
2338 if (!entry)
2339 return;
2340 // Note that we don't call NavigationController::GotToOffset() as we don't
2341 // want to create a pending navigation entry (it might end up lingering
2342 // http://crbug.com/51680).
2343 entry->SetTransitionType(
2344 PageTransitionFromInt(
2345 entry->GetTransitionType() |
2346 PAGE_TRANSITION_FORWARD_BACK));
2347 NavigateToEntry(*entry, NavigationControllerImpl::NO_RELOAD);
2348
2349 // If the entry is being restored and doesn't have a SiteInstance yet, fill
2350 // it in now that we know. This allows us to find the entry when it commits.
2351 if (!entry->site_instance() &&
2352 entry->restore_type() != NavigationEntryImpl::RESTORE_NONE) {
2353 entry->set_site_instance(
2354 static_cast<SiteInstanceImpl*>(GetPendingSiteInstance()));
2355 }
2356 }
2357}
2358
2359void WebContentsImpl::OnUpdateZoomLimits(int minimum_percent,
2360 int maximum_percent,
2361 bool remember) {
2362 minimum_zoom_percent_ = minimum_percent;
2363 maximum_zoom_percent_ = maximum_percent;
2364 temporary_zoom_settings_ = !remember;
2365}
2366
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002367void WebContentsImpl::OnEnumerateDirectory(int request_id,
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002368 const base::FilePath& path) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002369 if (!delegate_)
2370 return;
2371
2372 ChildProcessSecurityPolicyImpl* policy =
2373 ChildProcessSecurityPolicyImpl::GetInstance();
2374 if (policy->CanReadDirectory(GetRenderProcessHost()->GetID(), path))
2375 delegate_->EnumerateDirectory(this, request_id, path);
2376}
2377
2378void WebContentsImpl::OnJSOutOfMemory() {
2379 if (delegate_)
2380 delegate_->JSOutOfMemory(this);
2381}
2382
2383void WebContentsImpl::OnRegisterProtocolHandler(const std::string& protocol,
2384 const GURL& url,
2385 const string16& title,
2386 bool user_gesture) {
2387 if (!delegate_)
2388 return;
2389
2390 ChildProcessSecurityPolicyImpl* policy =
2391 ChildProcessSecurityPolicyImpl::GetInstance();
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01002392 if (policy->IsPseudoScheme(protocol))
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002393 return;
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01002394
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002395 delegate_->RegisterProtocolHandler(this, protocol, url, title, user_gesture);
2396}
2397
2398void WebContentsImpl::OnFindReply(int request_id,
2399 int number_of_matches,
2400 const gfx::Rect& selection_rect,
2401 int active_match_ordinal,
2402 bool final_update) {
2403 if (delegate_) {
2404 delegate_->FindReply(this, request_id, number_of_matches, selection_rect,
2405 active_match_ordinal, final_update);
2406 }
2407}
2408
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01002409void WebContentsImpl::OnDidProgrammaticallyScroll(
2410 const gfx::Vector2d& scroll_point) {
2411 if (delegate_)
2412 delegate_->DidProgrammaticallyScroll(this, scroll_point);
2413}
2414
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002415#if defined(OS_ANDROID)
2416void WebContentsImpl::OnFindMatchRectsReply(
2417 int version,
2418 const std::vector<gfx::RectF>& rects,
2419 const gfx::RectF& active_rect) {
2420 if (delegate_)
2421 delegate_->FindMatchRectsReply(this, version, rects, active_rect);
2422}
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002423
2424void WebContentsImpl::OnOpenDateTimeDialog(
2425 const ViewHostMsg_DateTimeDialogValue_Params& value) {
2426 date_time_chooser_->ShowDialog(
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01002427 ContentViewCore::FromWebContents(this), GetRenderViewHost(),
2428 value.dialog_type, value.year, value.month, value.day, value.hour,
Ben Murdocheb525c52013-07-10 11:40:50 +01002429 value.minute, value.second, value.week, value.minimum, value.maximum);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002430}
2431
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002432#endif
2433
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002434void WebContentsImpl::OnCrashedPlugin(const base::FilePath& plugin_path,
2435 base::ProcessId plugin_pid) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002436 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002437 PluginCrashed(plugin_path, plugin_pid));
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002438}
2439
2440void WebContentsImpl::OnAppCacheAccessed(const GURL& manifest_url,
2441 bool blocked_by_policy) {
2442 // Notify observers about navigation.
2443 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2444 AppCacheAccessed(manifest_url, blocked_by_policy));
2445}
2446
2447void WebContentsImpl::OnOpenColorChooser(int color_chooser_id,
2448 SkColor color) {
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01002449 ColorChooser* new_color_chooser = delegate_->OpenColorChooser(this, color);
2450 if (color_chooser_ == new_color_chooser)
2451 return;
2452 color_chooser_.reset(new_color_chooser);
2453 color_chooser_identifier_ = color_chooser_id;
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002454}
2455
2456void WebContentsImpl::OnEndColorChooser(int color_chooser_id) {
2457 if (color_chooser_ &&
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01002458 color_chooser_id == color_chooser_identifier_)
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002459 color_chooser_->End();
2460}
2461
2462void WebContentsImpl::OnSetSelectedColorInColorChooser(int color_chooser_id,
2463 SkColor color) {
2464 if (color_chooser_ &&
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01002465 color_chooser_id == color_chooser_identifier_)
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002466 color_chooser_->SetSelectedColor(color);
2467}
2468
2469void WebContentsImpl::OnPepperPluginHung(int plugin_child_id,
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002470 const base::FilePath& path,
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002471 bool is_hung) {
2472 UMA_HISTOGRAM_COUNTS("Pepper.PluginHung", 1);
2473
2474 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2475 PluginHungStatusChanged(plugin_child_id, path, is_hung));
2476}
2477
2478// This exists for render views that don't have a WebUI, but do have WebUI
2479// bindings enabled.
2480void WebContentsImpl::OnWebUISend(const GURL& source_url,
2481 const std::string& name,
2482 const base::ListValue& args) {
2483 if (delegate_)
2484 delegate_->WebUISend(this, source_url, name, args);
2485}
2486
2487void WebContentsImpl::OnRequestPpapiBrokerPermission(
Ben Murdoch32409262013-08-07 11:04:47 +01002488 int routing_id,
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002489 const GURL& url,
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002490 const base::FilePath& plugin_path) {
2491 if (!delegate_) {
Ben Murdoch32409262013-08-07 11:04:47 +01002492 OnPpapiBrokerPermissionResult(routing_id, false);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002493 return;
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002494 }
2495
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002496 if (!delegate_->RequestPpapiBrokerPermission(
2497 this, url, plugin_path,
2498 base::Bind(&WebContentsImpl::OnPpapiBrokerPermissionResult,
Ben Murdoch32409262013-08-07 11:04:47 +01002499 base::Unretained(this), routing_id))) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002500 NOTIMPLEMENTED();
Ben Murdoch32409262013-08-07 11:04:47 +01002501 OnPpapiBrokerPermissionResult(routing_id, false);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002502 }
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002503}
2504
Ben Murdoch32409262013-08-07 11:04:47 +01002505void WebContentsImpl::OnPpapiBrokerPermissionResult(int routing_id,
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002506 bool result) {
Ben Murdoch32409262013-08-07 11:04:47 +01002507 Send(new ViewMsg_PpapiBrokerPermissionResult(routing_id, result));
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002508}
2509
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002510void WebContentsImpl::OnBrowserPluginMessage(const IPC::Message& message) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002511 // This creates a BrowserPluginEmbedder, which handles all the BrowserPlugin
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002512 // specific messages for this WebContents. This means that any message from
2513 // a BrowserPlugin prior to this will be ignored.
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002514 // For more info, see comment above classes BrowserPluginEmbedder and
2515 // BrowserPluginGuest.
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002516 CHECK(!browser_plugin_embedder_.get());
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002517 browser_plugin_embedder_.reset(BrowserPluginEmbedder::Create(this));
2518 browser_plugin_embedder_->OnMessageReceived(message);
2519}
2520
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01002521void WebContentsImpl::OnDidDownloadImage(
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002522 int id,
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01002523 int http_status_code,
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002524 const GURL& image_url,
2525 int requested_size,
2526 const std::vector<SkBitmap>& bitmaps) {
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01002527 ImageDownloadMap::iterator iter = image_download_map_.find(id);
2528 if (iter == image_download_map_.end()) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002529 // Currently WebContents notifies us of ANY downloads so that it is
2530 // possible to get here.
2531 return;
2532 }
2533 if (!iter->second.is_null()) {
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01002534 iter->second.Run(id, http_status_code, image_url, requested_size, bitmaps);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002535 }
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01002536 image_download_map_.erase(id);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002537}
2538
2539void WebContentsImpl::OnUpdateFaviconURL(
2540 int32 page_id,
2541 const std::vector<FaviconURL>& candidates) {
2542 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2543 DidUpdateFaviconURL(page_id, candidates));
2544}
2545
Torne (Richard Coles)b2df76e2013-05-13 16:52:09 +01002546FrameTreeNode* WebContentsImpl::FindFrameTreeNodeByID(int64 frame_id) {
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01002547 // TODO(nasko): Remove this check once we move to creating the root node
2548 // through RenderFrameHost creation.
2549 if (!frame_tree_root_.get())
2550 return NULL;
2551
Torne (Richard Coles)b2df76e2013-05-13 16:52:09 +01002552 FrameTreeNode* node = NULL;
2553 std::queue<FrameTreeNode*> queue;
2554 queue.push(frame_tree_root_.get());
2555
2556 while (!queue.empty()) {
2557 node = queue.front();
2558 queue.pop();
2559 if (node->frame_id() == frame_id)
2560 return node;
2561
2562 for (size_t i = 0; i < node->child_count(); ++i)
2563 queue.push(node->child_at(i));
2564 }
2565
2566 return NULL;
2567}
2568
2569void WebContentsImpl::OnFrameAttached(
2570 int64 parent_frame_id,
2571 int64 frame_id,
2572 const std::string& frame_name) {
2573 FrameTreeNode* parent = FindFrameTreeNodeByID(parent_frame_id);
2574 if (!parent)
2575 return;
2576
2577 FrameTreeNode* node = new FrameTreeNode(frame_id, frame_name);
2578 parent->AddChild(node);
2579}
2580
2581void WebContentsImpl::OnFrameDetached(int64 parent_frame_id, int64 frame_id) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002582 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2583 FrameDetached(message_source_, frame_id));
Torne (Richard Coles)b2df76e2013-05-13 16:52:09 +01002584
2585 FrameTreeNode* parent = FindFrameTreeNodeByID(parent_frame_id);
2586 if (!parent)
2587 return;
2588
2589 parent->RemoveChild(frame_id);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002590}
2591
Ben Murdochca12bfa2013-07-23 11:17:05 +01002592void WebContentsImpl::OnMediaNotification(int64 player_cookie,
2593 bool has_video,
2594 bool has_audio,
2595 bool is_playing) {
2596 // Chrome OS does its own detection of audio and video.
2597#if !defined(OS_CHROMEOS)
2598 if (is_playing) {
2599 scoped_ptr<PowerSaveBlocker> blocker;
2600 if (has_video) {
2601 blocker = PowerSaveBlocker::Create(
2602 PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep,
2603 "Playing video");
2604#if defined(OS_ANDROID)
2605 static_cast<PowerSaveBlockerImpl*>(blocker.get())->
2606 InitDisplaySleepBlocker(GetView()->GetTopLevelNativeWindow());
2607#endif
2608 } else if (has_audio) {
2609 blocker = PowerSaveBlocker::Create(
2610 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension,
2611 "Playing audio");
2612 }
2613
2614 if (blocker)
2615 power_save_blockers_[message_source_][player_cookie] = blocker.release();
2616 } else {
2617 delete power_save_blockers_[message_source_][player_cookie];
2618 power_save_blockers_[message_source_].erase(player_cookie);
2619 }
2620#endif // !defined(OS_CHROMEOS)
2621}
2622
2623
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002624void WebContentsImpl::DidChangeVisibleSSLState() {
2625 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2626 DidChangeVisibleSSLState());
2627}
2628
2629void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
2630 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2631 BeforeFormRepostWarningShow());
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002632}
2633
2634// Notifies the RenderWidgetHost instance about the fact that the page is
2635// loading, or done loading and calls the base implementation.
2636void WebContentsImpl::SetIsLoading(bool is_loading,
2637 LoadNotificationDetails* details) {
2638 if (is_loading == is_loading_)
2639 return;
2640
2641 if (!is_loading) {
2642 load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE, string16());
2643 load_state_host_.clear();
2644 upload_size_ = 0;
2645 upload_position_ = 0;
2646 }
2647
2648 render_manager_.SetIsLoading(is_loading);
2649
2650 is_loading_ = is_loading;
2651 waiting_for_response_ = is_loading;
2652
2653 if (delegate_)
2654 delegate_->LoadingStateChanged(this);
2655 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
2656
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002657 if (is_loading)
2658 TRACE_EVENT_ASYNC_BEGIN0("browser", "WebContentsImpl Loading", this);
2659 else
2660 TRACE_EVENT_ASYNC_END0("browser", "WebContentsImpl Loading", this);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002661 int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
2662 NotificationDetails det = NotificationService::NoDetails();
2663 if (details)
2664 det = Details<LoadNotificationDetails>(details);
2665 NotificationService::current()->Notify(
2666 type, Source<NavigationController>(&controller_), det);
2667}
2668
2669void WebContentsImpl::DidNavigateMainFramePostCommit(
2670 const LoadCommittedDetails& details,
2671 const ViewHostMsg_FrameNavigate_Params& params) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002672 if (details.is_navigation_to_different_page()) {
2673 // Clear the status bubble. This is a workaround for a bug where WebKit
2674 // doesn't let us know that the cursor left an element during a
2675 // transition (this is also why the mouse cursor remains as a hand after
2676 // clicking on a link); see bugs 1184641 and 980803. We don't want to
2677 // clear the bubble when a user navigates to a named anchor in the same
2678 // page.
2679 UpdateTargetURL(details.entry->GetPageID(), GURL());
2680 }
2681
2682 if (!details.is_in_page) {
2683 // Once the main frame is navigated, we're no longer considered to have
2684 // displayed insecure content.
2685 displayed_insecure_content_ = false;
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +01002686 SSLManager::NotifySSLInternalStateChanged(
2687 GetController().GetBrowserContext());
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002688 }
2689
2690 // Notify observers about navigation.
2691 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2692 DidNavigateMainFrame(details, params));
2693}
2694
2695void WebContentsImpl::DidNavigateAnyFramePostCommit(
2696 RenderViewHost* render_view_host,
2697 const LoadCommittedDetails& details,
2698 const ViewHostMsg_FrameNavigate_Params& params) {
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +01002699 // If we navigate off the page, close all JavaScript dialogs.
2700 if (dialog_manager_ && !details.is_in_page)
2701 dialog_manager_->CancelActiveAndPendingDialogs(this);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002702
2703 // Notify observers about navigation.
2704 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2705 DidNavigateAnyFrame(details, params));
2706}
2707
Ben Murdocheb525c52013-07-10 11:40:50 +01002708bool WebContentsImpl::ShouldAssignSiteForURL(const GURL& url) {
Ben Murdoch7dbb3d52013-07-17 14:55:54 +01002709 // about:blank should not "use up" a new SiteInstance. The SiteInstance can
2710 // still be used for a normal web site.
2711 if (url == GURL(kAboutBlankURL))
2712 return false;
2713
2714 // The embedder will then have the opportunity to determine if the URL
2715 // should "use up" the SiteInstance.
2716 return GetContentClient()->browser()->ShouldAssignSiteForURL(url);
Ben Murdocheb525c52013-07-10 11:40:50 +01002717}
2718
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002719void WebContentsImpl::UpdateMaxPageIDIfNecessary(RenderViewHost* rvh) {
2720 // If we are creating a RVH for a restored controller, then we need to make
2721 // sure the RenderView starts with a next_page_id_ larger than the number
2722 // of restored entries. This must be called before the RenderView starts
2723 // navigating (to avoid a race between the browser updating max_page_id and
2724 // the renderer updating next_page_id_). Because of this, we only call this
2725 // from CreateRenderView and allow that to notify the RenderView for us.
2726 int max_restored_page_id = controller_.GetMaxRestoredPageID();
2727 if (max_restored_page_id >
2728 GetMaxPageIDForSiteInstance(rvh->GetSiteInstance()))
2729 UpdateMaxPageIDForSiteInstance(rvh->GetSiteInstance(),
2730 max_restored_page_id);
2731}
2732
2733bool WebContentsImpl::UpdateTitleForEntry(NavigationEntryImpl* entry,
2734 const string16& title) {
2735 // For file URLs without a title, use the pathname instead. In the case of a
2736 // synthesized title, we don't want the update to count toward the "one set
2737 // per page of the title to history."
2738 string16 final_title;
2739 bool explicit_set;
2740 if (entry && entry->GetURL().SchemeIsFile() && title.empty()) {
2741 final_title = UTF8ToUTF16(entry->GetURL().ExtractFileName());
2742 explicit_set = false; // Don't count synthetic titles toward the set limit.
2743 } else {
2744 TrimWhitespace(title, TRIM_ALL, &final_title);
2745 explicit_set = true;
2746 }
2747
2748 // If a page is created via window.open and never navigated,
2749 // there will be no navigation entry. In this situation,
2750 // |page_title_when_no_navigation_entry_| will be used for page title.
2751 if (entry) {
2752 if (final_title == entry->GetTitle())
2753 return false; // Nothing changed, don't bother.
2754
2755 entry->SetTitle(final_title);
2756 } else {
2757 if (page_title_when_no_navigation_entry_ == final_title)
2758 return false; // Nothing changed, don't bother.
2759
2760 page_title_when_no_navigation_entry_ = final_title;
2761 }
2762
2763 // Lastly, set the title for the view.
2764 view_->SetPageTitle(final_title);
2765
2766 std::pair<NavigationEntry*, bool> details =
2767 std::make_pair(entry, explicit_set);
2768
2769 NotificationService::current()->Notify(
2770 NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED,
2771 Source<WebContents>(this),
2772 Details<std::pair<NavigationEntry*, bool> >(&details));
2773
2774 return true;
2775}
2776
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002777void WebContentsImpl::NotifySwapped(RenderViewHost* old_render_view_host) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002778 // After sending out a swap notification, we need to send a disconnect
2779 // notification so that clients that pick up a pointer to |this| can NULL the
2780 // pointer. See Bug 1230284.
2781 notify_disconnection_ = true;
2782 NotificationService::current()->Notify(
2783 NOTIFICATION_WEB_CONTENTS_SWAPPED,
2784 Source<WebContents>(this),
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002785 Details<RenderViewHost>(old_render_view_host));
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002786
2787 // Ensure that the associated embedder gets cleared after a RenderViewHost
2788 // gets swapped, so we don't reuse the same embedder next time a
2789 // RenderViewHost is attached to this WebContents.
2790 RemoveBrowserPluginEmbedder();
2791}
2792
2793void WebContentsImpl::NotifyConnected() {
2794 notify_disconnection_ = true;
2795 NotificationService::current()->Notify(
2796 NOTIFICATION_WEB_CONTENTS_CONNECTED,
2797 Source<WebContents>(this),
2798 NotificationService::NoDetails());
2799}
2800
2801void WebContentsImpl::NotifyDisconnected() {
2802 if (!notify_disconnection_)
2803 return;
2804
2805 notify_disconnection_ = false;
2806 NotificationService::current()->Notify(
2807 NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
2808 Source<WebContents>(this),
2809 NotificationService::NoDetails());
2810}
2811
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01002812void WebContentsImpl::NotifyNavigationEntryCommitted(
2813 const LoadCommittedDetails& load_details) {
2814 FOR_EACH_OBSERVER(
2815 WebContentsObserver, observers_, NavigationEntryCommitted(load_details));
2816}
2817
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002818RenderViewHostDelegateView* WebContentsImpl::GetDelegateView() {
2819 return render_view_host_delegate_view_;
2820}
2821
2822RenderViewHostDelegate::RendererManagement*
2823WebContentsImpl::GetRendererManagementDelegate() {
2824 return &render_manager_;
2825}
2826
2827RendererPreferences WebContentsImpl::GetRendererPrefs(
2828 BrowserContext* browser_context) const {
2829 return renderer_preferences_;
2830}
2831
2832WebContents* WebContentsImpl::GetAsWebContents() {
2833 return this;
2834}
2835
2836gfx::Rect WebContentsImpl::GetRootWindowResizerRect() const {
2837 if (delegate_)
2838 return delegate_->GetRootWindowResizerRect();
2839 return gfx::Rect();
2840}
2841
2842void WebContentsImpl::RemoveBrowserPluginEmbedder() {
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01002843 if (browser_plugin_embedder_)
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002844 browser_plugin_embedder_.reset();
2845}
2846
2847void WebContentsImpl::RenderViewCreated(RenderViewHost* render_view_host) {
2848 // Don't send notifications if we are just creating a swapped-out RVH for
2849 // the opener chain. These won't be used for view-source or WebUI, so it's
2850 // ok to return early.
2851 if (static_cast<RenderViewHostImpl*>(render_view_host)->is_swapped_out())
2852 return;
2853
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002854 if (delegate_)
2855 view_->SetOverscrollControllerEnabled(delegate_->CanOverscrollContent());
2856
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002857 NotificationService::current()->Notify(
2858 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
2859 Source<WebContents>(this),
2860 Details<RenderViewHost>(render_view_host));
2861 NavigationEntry* entry = controller_.GetActiveEntry();
2862 if (!entry)
2863 return;
2864
2865 // When we're creating views, we're still doing initial setup, so we always
2866 // use the pending Web UI rather than any possibly existing committed one.
2867 if (render_manager_.pending_web_ui())
2868 render_manager_.pending_web_ui()->RenderViewCreated(render_view_host);
2869
2870 if (entry->IsViewSourceMode()) {
2871 // Put the renderer in view source mode.
2872 render_view_host->Send(
2873 new ViewMsg_EnableViewSourceMode(render_view_host->GetRoutingID()));
2874 }
2875
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002876 view_->RenderViewCreated(render_view_host);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002877
2878 FOR_EACH_OBSERVER(
2879 WebContentsObserver, observers_, RenderViewCreated(render_view_host));
2880}
2881
2882void WebContentsImpl::RenderViewReady(RenderViewHost* rvh) {
2883 if (rvh != GetRenderViewHost()) {
2884 // Don't notify the world, since this came from a renderer in the
2885 // background.
2886 return;
2887 }
2888
2889 NotifyConnected();
2890 bool was_crashed = IsCrashed();
2891 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
2892
2893 // Restore the focus to the tab (otherwise the focus will be on the top
2894 // window).
2895 if (was_crashed && !FocusLocationBarByDefault() &&
2896 (!delegate_ || delegate_->ShouldFocusPageAfterCrash())) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002897 view_->Focus();
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002898 }
2899
2900 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewReady());
2901}
2902
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01002903void WebContentsImpl::RenderViewTerminated(RenderViewHost* rvh,
2904 base::TerminationStatus status,
2905 int error_code) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002906 if (rvh != GetRenderViewHost()) {
2907 // The pending page's RenderViewHost is gone.
2908 return;
2909 }
2910
Ben Murdochca12bfa2013-07-23 11:17:05 +01002911 ClearPowerSaveBlockers(rvh);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002912 SetIsLoading(false, NULL);
2913 NotifyDisconnected();
2914 SetIsCrashed(status, error_code);
2915 GetView()->OnTabCrashed(GetCrashedStatus(), crashed_error_code_);
2916
2917 FOR_EACH_OBSERVER(WebContentsObserver,
2918 observers_,
Ben Murdoch7dbb3d52013-07-17 14:55:54 +01002919 RenderProcessGone(GetCrashedStatus()));
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002920}
2921
2922void WebContentsImpl::RenderViewDeleted(RenderViewHost* rvh) {
Ben Murdochca12bfa2013-07-23 11:17:05 +01002923 ClearPowerSaveBlockers(rvh);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002924 render_manager_.RenderViewDeleted(rvh);
2925 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewDeleted(rvh));
2926}
2927
2928void WebContentsImpl::DidNavigate(
2929 RenderViewHost* rvh,
2930 const ViewHostMsg_FrameNavigate_Params& params) {
Torne (Richard Coles)b2df76e2013-05-13 16:52:09 +01002931 // If we don't have a frame tree root yet, this is the first navigation in
2932 // using the current RenderViewHost, so we need to create it with the proper
2933 // frame id.
2934 if (!frame_tree_root_.get()) {
2935 DCHECK(PageTransitionIsMainFrame(params.transition));
2936 frame_tree_root_.reset(new FrameTreeNode(params.frame_id, std::string()));
2937 }
2938
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002939 if (PageTransitionIsMainFrame(params.transition)) {
2940 // When overscroll navigation gesture is enabled, a screenshot of the page
2941 // in its current state is taken so that it can be used during the
2942 // nav-gesture. It is necessary to take the screenshot here, before calling
2943 // RenderViewHostManager::DidNavigateMainFrame, because that can change
2944 // WebContents::GetRenderViewHost to return the new host, instead of the one
2945 // that may have just been swapped out.
2946 if (delegate_ && delegate_->CanOverscrollContent())
2947 controller_.TakeScreenshot();
2948
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002949 render_manager_.DidNavigateMainFrame(rvh);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002950 }
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002951
Torne (Richard Coles)b2df76e2013-05-13 16:52:09 +01002952 // We expect to have a valid frame tree root node at all times when
2953 // navigating.
2954 DCHECK(frame_tree_root_.get());
2955
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002956 // Update the site of the SiteInstance if it doesn't have one yet, unless
Ben Murdocheb525c52013-07-10 11:40:50 +01002957 // assigning a site is not necessary for this URL. In that case, the
2958 // SiteInstance can still be considered unused until a navigation to a real
2959 // page.
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002960 if (!static_cast<SiteInstanceImpl*>(GetSiteInstance())->HasSite() &&
Ben Murdocheb525c52013-07-10 11:40:50 +01002961 ShouldAssignSiteForURL(params.url)) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002962 static_cast<SiteInstanceImpl*>(GetSiteInstance())->SetSite(params.url);
2963 }
2964
2965 // Need to update MIME type here because it's referred to in
2966 // UpdateNavigationCommands() called by RendererDidNavigate() to
2967 // determine whether or not to enable the encoding menu.
2968 // It's updated only for the main frame. For a subframe,
2969 // RenderView::UpdateURL does not set params.contents_mime_type.
2970 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
2971 // TODO(jungshik): Add a test for the encoding menu to avoid
2972 // regressing it again.
2973 if (PageTransitionIsMainFrame(params.transition))
2974 contents_mime_type_ = params.contents_mime_type;
2975
2976 LoadCommittedDetails details;
2977 bool did_navigate = controller_.RendererDidNavigate(params, &details);
2978
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +01002979 // For now, keep track of each frame's URL in its FrameTreeNode. This lets
2980 // us estimate our process count for implementing OOP iframes.
2981 // TODO(creis): Remove this when we track which pages commit in each frame.
2982 FrameTreeNode* node = FindFrameTreeNodeByID(params.frame_id);
2983 if (node)
2984 node->set_current_url(params.url);
2985
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002986 // Send notification about committed provisional loads. This notification is
2987 // different from the NAV_ENTRY_COMMITTED notification which doesn't include
2988 // the actual URL navigated to and isn't sent for AUTO_SUBFRAME navigations.
2989 if (details.type != NAVIGATION_TYPE_NAV_IGNORE) {
2990 // For AUTO_SUBFRAME navigations, an event for the main frame is generated
2991 // that is not recorded in the navigation history. For the purpose of
2992 // tracking navigation events, we treat this event as a sub frame navigation
2993 // event.
2994 bool is_main_frame = did_navigate ? details.is_main_frame : false;
2995 PageTransition transition_type = params.transition;
2996 // Whether or not a page transition was triggered by going backward or
2997 // forward in the history is only stored in the navigation controller's
2998 // entry list.
2999 if (did_navigate &&
3000 (controller_.GetActiveEntry()->GetTransitionType() &
3001 PAGE_TRANSITION_FORWARD_BACK)) {
3002 transition_type = PageTransitionFromInt(
3003 params.transition | PAGE_TRANSITION_FORWARD_BACK);
3004 }
3005 // Notify observers about the commit of the provisional load.
3006 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3007 DidCommitProvisionalLoadForFrame(params.frame_id,
3008 is_main_frame, params.url, transition_type, rvh));
3009 }
3010
3011 if (!did_navigate)
3012 return; // No navigation happened.
3013
3014 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
3015 // for the appropriate notification (best) or you can add it to
3016 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
3017 // necessary, please).
3018
3019 // Run post-commit tasks.
3020 if (details.is_main_frame) {
3021 DidNavigateMainFramePostCommit(details, params);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00003022 if (delegate_) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003023 delegate_->DidNavigateMainFramePostCommit(this);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00003024 view_->SetOverscrollControllerEnabled(delegate_->CanOverscrollContent());
3025 }
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003026 }
3027 DidNavigateAnyFramePostCommit(rvh, details, params);
3028}
3029
3030void WebContentsImpl::UpdateState(RenderViewHost* rvh,
3031 int32 page_id,
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01003032 const PageState& page_state) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003033 // Ensure that this state update comes from either the active RVH or one of
3034 // the swapped out RVHs. We don't expect to hear from any other RVHs.
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01003035 DCHECK(rvh == GetRenderViewHost() || render_manager_.IsOnSwappedOutList(rvh));
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003036
3037 // We must be prepared to handle state updates for any page, these occur
3038 // when the user is scrolling and entering form data, as well as when we're
3039 // leaving a page, in which case our state may have already been moved to
3040 // the next page. The navigation controller will look up the appropriate
3041 // NavigationEntry and update it when it is notified via the delegate.
3042
3043 int entry_index = controller_.GetEntryIndexWithPageID(
3044 rvh->GetSiteInstance(), page_id);
3045 if (entry_index < 0)
3046 return;
3047 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
3048
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01003049 if (page_state == entry->GetPageState())
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003050 return; // Nothing to update.
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01003051 entry->SetPageState(page_state);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003052 controller_.NotifyEntryChanged(entry, entry_index);
3053}
3054
3055void WebContentsImpl::UpdateTitle(RenderViewHost* rvh,
3056 int32 page_id,
3057 const string16& title,
3058 base::i18n::TextDirection title_direction) {
3059 // If we have a title, that's a pretty good indication that we've started
3060 // getting useful data.
3061 SetNotWaitingForResponse();
3062
3063 // Try to find the navigation entry, which might not be the current one.
3064 // For example, it might be from a pending RVH for the pending entry.
3065 NavigationEntryImpl* entry = controller_.GetEntryWithPageID(
3066 rvh->GetSiteInstance(), page_id);
3067
3068 // We can handle title updates when we don't have an entry in
3069 // UpdateTitleForEntry, but only if the update is from the current RVH.
3070 if (!entry && rvh != GetRenderViewHost())
3071 return;
3072
3073 // TODO(evan): make use of title_direction.
3074 // http://code.google.com/p/chromium/issues/detail?id=27094
3075 if (!UpdateTitleForEntry(entry, title))
3076 return;
3077
3078 // Broadcast notifications when the UI should be updated.
3079 if (entry == controller_.GetEntryAtOffset(0))
3080 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
3081}
3082
3083void WebContentsImpl::UpdateEncoding(RenderViewHost* render_view_host,
3084 const std::string& encoding) {
3085 SetEncoding(encoding);
3086}
3087
3088void WebContentsImpl::UpdateTargetURL(int32 page_id, const GURL& url) {
3089 if (delegate_)
3090 delegate_->UpdateTargetURL(this, page_id, url);
3091}
3092
3093void WebContentsImpl::Close(RenderViewHost* rvh) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00003094#if defined(OS_MACOSX)
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003095 // The UI may be in an event-tracking loop, such as between the
3096 // mouse-down and mouse-up in text selection or a button click.
3097 // Defer the close until after tracking is complete, so that we
3098 // don't free objects out from under the UI.
3099 // TODO(shess): This could get more fine-grained. For instance,
3100 // closing a tab in another window while selecting text in the
3101 // current window's Omnibox should be just fine.
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00003102 if (view_->IsEventTracking()) {
3103 view_->CloseTabAfterEventTracking();
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003104 return;
3105 }
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00003106#endif
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003107
3108 // Ignore this if it comes from a RenderViewHost that we aren't showing.
3109 if (delegate_ && rvh == GetRenderViewHost())
3110 delegate_->CloseContents(this);
3111}
3112
3113void WebContentsImpl::SwappedOut(RenderViewHost* rvh) {
3114 if (delegate_ && rvh == GetRenderViewHost())
3115 delegate_->SwappedOut(this);
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +01003116
3117 // Allow the navigation to proceed.
3118 render_manager_.SwappedOut(rvh);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003119}
3120
3121void WebContentsImpl::RequestMove(const gfx::Rect& new_bounds) {
3122 if (delegate_ && delegate_->IsPopupOrPanel(this))
3123 delegate_->MoveContents(this, new_bounds);
3124}
3125
3126void WebContentsImpl::DidStartLoading(RenderViewHost* render_view_host) {
3127 SetIsLoading(true, NULL);
3128
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003129 // Notify observers about navigation.
3130 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3131 DidStartLoading(render_view_host));
3132}
3133
3134void WebContentsImpl::DidStopLoading(RenderViewHost* render_view_host) {
3135 scoped_ptr<LoadNotificationDetails> details;
3136
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01003137 // Use the last committed entry rather than the active one, in case a
3138 // pending entry has been created.
3139 NavigationEntry* entry = controller_.GetLastCommittedEntry();
3140
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003141 // An entry may not exist for a stop when loading an initial blank page or
3142 // if an iframe injected by script into a blank page finishes loading.
3143 if (entry) {
3144 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
3145
3146 details.reset(new LoadNotificationDetails(
3147 entry->GetVirtualURL(),
3148 entry->GetTransitionType(),
3149 elapsed,
3150 &controller_,
3151 controller_.GetCurrentEntryIndex()));
3152 }
3153
3154 SetIsLoading(false, details.get());
3155
3156 // Notify observers about navigation.
3157 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3158 DidStopLoading(render_view_host));
3159}
3160
3161void WebContentsImpl::DidCancelLoading() {
3162 controller_.DiscardNonCommittedEntries();
3163
3164 // Update the URL display.
3165 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
3166}
3167
3168void WebContentsImpl::DidChangeLoadProgress(double progress) {
3169#if defined(OS_ANDROID)
3170 if (delegate_)
3171 delegate_->LoadProgressChanged(this, progress);
3172#endif
3173}
3174
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00003175void WebContentsImpl::DidDisownOpener(RenderViewHost* rvh) {
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01003176 if (opener_) {
3177 // Clear our opener so that future cross-process navigations don't have an
3178 // opener assigned.
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01003179 RemoveDestructionObserver(opener_);
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01003180 opener_ = NULL;
3181 }
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00003182
3183 // Notify all swapped out RenderViewHosts for this tab. This is important
3184 // in case we go back to them, or if another window in those processes tries
3185 // to access window.opener.
3186 render_manager_.DidDisownOpener(rvh);
3187}
3188
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01003189void WebContentsImpl::DidAccessInitialDocument() {
3190 // Update the URL display.
3191 NotifyNavigationStateChanged(content::INVALIDATE_TYPE_URL);
3192}
3193
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003194void WebContentsImpl::DocumentAvailableInMainFrame(
3195 RenderViewHost* render_view_host) {
3196 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3197 DocumentAvailableInMainFrame());
3198}
3199
3200void WebContentsImpl::DocumentOnLoadCompletedInMainFrame(
3201 RenderViewHost* render_view_host,
3202 int32 page_id) {
3203 NotificationService::current()->Notify(
3204 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
3205 Source<WebContents>(this),
3206 Details<int>(&page_id));
3207}
3208
3209void WebContentsImpl::RequestOpenURL(RenderViewHost* rvh,
3210 const GURL& url,
3211 const Referrer& referrer,
3212 WindowOpenDisposition disposition,
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00003213 int64 source_frame_id,
Ben Murdochca12bfa2013-07-23 11:17:05 +01003214 bool should_replace_current_entry,
Ben Murdoch7dbb3d52013-07-17 14:55:54 +01003215 bool user_gesture) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003216 // If this came from a swapped out RenderViewHost, we only allow the request
3217 // if we are still in the same BrowsingInstance.
3218 if (static_cast<RenderViewHostImpl*>(rvh)->is_swapped_out() &&
3219 !rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance())) {
3220 return;
3221 }
3222
3223 // Delegate to RequestTransferURL because this is just the generic
3224 // case where |old_request_id| is empty.
3225 RequestTransferURL(url, referrer, disposition, source_frame_id,
Ben Murdochca12bfa2013-07-23 11:17:05 +01003226 GlobalRequestID(),
3227 should_replace_current_entry, user_gesture);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003228}
3229
3230void WebContentsImpl::RequestTransferURL(
3231 const GURL& url,
3232 const Referrer& referrer,
3233 WindowOpenDisposition disposition,
3234 int64 source_frame_id,
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00003235 const GlobalRequestID& old_request_id,
Ben Murdochca12bfa2013-07-23 11:17:05 +01003236 bool should_replace_current_entry,
Ben Murdoch7dbb3d52013-07-17 14:55:54 +01003237 bool user_gesture) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003238 WebContents* new_contents = NULL;
3239 PageTransition transition_type = PAGE_TRANSITION_LINK;
3240 if (render_manager_.web_ui()) {
3241 // When we're a Web UI, it will provide a page transition type for us (this
3242 // is so the new tab page can specify AUTO_BOOKMARK for automatically
3243 // generated suggestions).
3244 //
3245 // Note also that we hide the referrer for Web UI pages. We don't really
3246 // want web sites to see a referrer of "chrome://blah" (and some
3247 // chrome: URLs might have search terms or other stuff we don't want to
3248 // send to the site), so we send no referrer.
3249 OpenURLParams params(url, Referrer(), source_frame_id, disposition,
3250 render_manager_.web_ui()->GetLinkTransitionType(),
3251 false /* is_renderer_initiated */);
3252 params.transferred_global_request_id = old_request_id;
3253 new_contents = OpenURL(params);
3254 transition_type = render_manager_.web_ui()->GetLinkTransitionType();
3255 } else {
3256 OpenURLParams params(url, referrer, source_frame_id, disposition,
3257 PAGE_TRANSITION_LINK, true /* is_renderer_initiated */);
3258 params.transferred_global_request_id = old_request_id;
Ben Murdochca12bfa2013-07-23 11:17:05 +01003259 params.should_replace_current_entry = should_replace_current_entry;
Ben Murdoch7dbb3d52013-07-17 14:55:54 +01003260 params.user_gesture = user_gesture;
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003261 new_contents = OpenURL(params);
3262 }
3263 if (new_contents) {
3264 // Notify observers.
3265 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3266 DidOpenRequestedURL(new_contents,
3267 url,
3268 referrer,
3269 disposition,
3270 transition_type,
3271 source_frame_id));
3272 }
3273}
3274
3275void WebContentsImpl::RouteCloseEvent(RenderViewHost* rvh) {
3276 // Tell the active RenderViewHost to run unload handlers and close, as long
3277 // as the request came from a RenderViewHost in the same BrowsingInstance.
3278 // In most cases, we receive this from a swapped out RenderViewHost.
3279 // It is possible to receive it from one that has just been swapped in,
3280 // in which case we might as well deliver the message anyway.
3281 if (rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()))
3282 GetRenderViewHost()->ClosePage();
3283}
3284
3285void WebContentsImpl::RouteMessageEvent(
3286 RenderViewHost* rvh,
3287 const ViewMsg_PostMessage_Params& params) {
3288 // Only deliver the message to the active RenderViewHost if the request
3289 // came from a RenderViewHost in the same BrowsingInstance or if this
3290 // WebContents is dedicated to a browser plugin guest.
3291 // Note: This check means that an embedder could theoretically receive a
3292 // postMessage from anyone (not just its own guests). However, this is
3293 // probably not a risk for apps since other pages won't have references
3294 // to App windows.
3295 if (!rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()) &&
3296 !GetBrowserPluginGuest() && !GetBrowserPluginEmbedder())
3297 return;
3298
3299 ViewMsg_PostMessage_Params new_params(params);
3300
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003301 // If there is a source_routing_id, translate it to the routing ID for
3302 // the equivalent swapped out RVH in the target process. If we need
3303 // to create a swapped out RVH for the source tab, we create its opener
3304 // chain as well, since those will also be accessible to the target page.
3305 if (new_params.source_routing_id != MSG_ROUTING_NONE) {
3306 // Try to look up the WebContents for the source page.
3307 WebContentsImpl* source_contents = NULL;
3308 RenderViewHostImpl* source_rvh = RenderViewHostImpl::FromID(
3309 rvh->GetProcess()->GetID(), params.source_routing_id);
3310 if (source_rvh) {
3311 source_contents = static_cast<WebContentsImpl*>(
3312 source_rvh->GetDelegate()->GetAsWebContents());
3313 }
3314
3315 if (source_contents) {
3316 if (GetBrowserPluginGuest()) {
3317 // We create a swapped out RenderView for the embedder in the guest's
3318 // render process but we intentionally do not expose the embedder's
3319 // opener chain to it.
3320 new_params.source_routing_id =
3321 source_contents->CreateSwappedOutRenderView(GetSiteInstance());
3322 } else {
3323 new_params.source_routing_id =
3324 source_contents->CreateOpenerRenderViews(GetSiteInstance());
3325 }
3326 } else {
3327 // We couldn't find it, so don't pass a source frame.
3328 new_params.source_routing_id = MSG_ROUTING_NONE;
3329 }
3330 }
3331
3332 // In most cases, we receive this from a swapped out RenderViewHost.
3333 // It is possible to receive it from one that has just been swapped in,
3334 // in which case we might as well deliver the message anyway.
3335 Send(new ViewMsg_PostMessageEvent(GetRoutingID(), new_params));
3336}
3337
3338void WebContentsImpl::RunJavaScriptMessage(
3339 RenderViewHost* rvh,
3340 const string16& message,
3341 const string16& default_prompt,
3342 const GURL& frame_url,
3343 JavaScriptMessageType javascript_message_type,
3344 IPC::Message* reply_msg,
3345 bool* did_suppress_message) {
3346 // Suppress JavaScript dialogs when requested. Also suppress messages when
3347 // showing an interstitial as it's shown over the previous page and we don't
3348 // want the hidden page's dialogs to interfere with the interstitial.
3349 bool suppress_this_message =
3350 static_cast<RenderViewHostImpl*>(rvh)->is_swapped_out() ||
3351 ShowingInterstitialPage() ||
3352 !delegate_ ||
3353 delegate_->ShouldSuppressDialogs() ||
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00003354 !delegate_->GetJavaScriptDialogManager();
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003355
3356 if (!suppress_this_message) {
3357 std::string accept_lang = GetContentClient()->browser()->
3358 GetAcceptLangs(GetBrowserContext());
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00003359 dialog_manager_ = delegate_->GetJavaScriptDialogManager();
3360 dialog_manager_->RunJavaScriptDialog(
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003361 this,
3362 frame_url.GetOrigin(),
3363 accept_lang,
3364 javascript_message_type,
3365 message,
3366 default_prompt,
3367 base::Bind(&WebContentsImpl::OnDialogClosed,
3368 base::Unretained(this),
3369 rvh,
3370 reply_msg),
3371 &suppress_this_message);
3372 }
3373
3374 if (suppress_this_message) {
3375 // If we are suppressing messages, just reply as if the user immediately
3376 // pressed "Cancel".
3377 OnDialogClosed(rvh, reply_msg, false, string16());
3378 }
3379
3380 *did_suppress_message = suppress_this_message;
3381}
3382
3383void WebContentsImpl::RunBeforeUnloadConfirm(RenderViewHost* rvh,
3384 const string16& message,
3385 bool is_reload,
3386 IPC::Message* reply_msg) {
3387 RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(rvh);
3388 if (delegate_)
3389 delegate_->WillRunBeforeUnloadConfirm();
3390
3391 bool suppress_this_message =
3392 rvhi->is_swapped_out() ||
3393 !delegate_ ||
3394 delegate_->ShouldSuppressDialogs() ||
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00003395 !delegate_->GetJavaScriptDialogManager();
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003396 if (suppress_this_message) {
3397 // The reply must be sent to the RVH that sent the request.
3398 rvhi->JavaScriptDialogClosed(reply_msg, true, string16());
3399 return;
3400 }
3401
3402 is_showing_before_unload_dialog_ = true;
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00003403 dialog_manager_ = delegate_->GetJavaScriptDialogManager();
3404 dialog_manager_->RunBeforeUnloadDialog(
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003405 this, message, is_reload,
3406 base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this), rvh,
3407 reply_msg));
3408}
3409
3410bool WebContentsImpl::AddMessageToConsole(int32 level,
3411 const string16& message,
3412 int32 line_no,
3413 const string16& source_id) {
3414 if (!delegate_)
3415 return false;
3416 return delegate_->AddMessageToConsole(this, level, message, line_no,
3417 source_id);
3418}
3419
3420WebPreferences WebContentsImpl::GetWebkitPrefs() {
3421 // We want to base the page config off of the real URL, rather than the
3422 // display URL.
3423 GURL url = controller_.GetActiveEntry()
3424 ? controller_.GetActiveEntry()->GetURL() : GURL::EmptyGURL();
3425 return GetWebkitPrefs(GetRenderViewHost(), url);
3426}
3427
3428int WebContentsImpl::CreateSwappedOutRenderView(
3429 SiteInstance* instance) {
3430 return render_manager_.CreateRenderView(instance, MSG_ROUTING_NONE, true);
3431}
3432
3433void WebContentsImpl::OnUserGesture() {
3434 // Notify observers.
3435 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetUserGesture());
3436
3437 ResourceDispatcherHostImpl* rdh = ResourceDispatcherHostImpl::Get();
3438 if (rdh) // NULL in unittests.
3439 rdh->OnUserGesture(this);
3440}
3441
3442void WebContentsImpl::OnIgnoredUIEvent() {
3443 // Notify observers.
3444 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetIgnoredUIEvent());
3445}
3446
3447void WebContentsImpl::RendererUnresponsive(RenderViewHost* rvh,
3448 bool is_during_unload) {
3449 // Don't show hung renderer dialog for a swapped out RVH.
3450 if (rvh != GetRenderViewHost())
3451 return;
3452
3453 RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(rvh);
3454
3455 // Ignore renderer unresponsive event if debugger is attached to the tab
3456 // since the event may be a result of the renderer sitting on a breakpoint.
3457 // See http://crbug.com/65458
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00003458 if (DevToolsAgentHost::IsDebuggerAttached(this))
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003459 return;
3460
3461 if (is_during_unload) {
3462 // Hang occurred while firing the beforeunload/unload handler.
3463 // Pretend the handler fired so tab closing continues as if it had.
3464 rvhi->set_sudden_termination_allowed(true);
3465
3466 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
3467 return;
3468
3469 // If the tab hangs in the beforeunload/unload handler there's really
3470 // nothing we can do to recover. Pretend the unload listeners have
3471 // all fired and close the tab. If the hang is in the beforeunload handler
3472 // then the user will not have the option of cancelling the close.
3473 Close(rvh);
3474 return;
3475 }
3476
3477 if (!GetRenderViewHostImpl() || !GetRenderViewHostImpl()->IsRenderViewLive())
3478 return;
3479
3480 if (delegate_)
3481 delegate_->RendererUnresponsive(this);
3482}
3483
3484void WebContentsImpl::RendererResponsive(RenderViewHost* render_view_host) {
3485 if (delegate_)
3486 delegate_->RendererResponsive(this);
3487}
3488
3489void WebContentsImpl::LoadStateChanged(
3490 const GURL& url,
3491 const net::LoadStateWithParam& load_state,
3492 uint64 upload_position,
3493 uint64 upload_size) {
3494 load_state_ = load_state;
3495 upload_position_ = upload_position;
3496 upload_size_ = upload_size;
3497 load_state_host_ = net::IDNToUnicode(url.host(),
3498 GetContentClient()->browser()->GetAcceptLangs(
3499 GetBrowserContext()));
3500 if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
3501 SetNotWaitingForResponse();
3502 if (IsLoading()) {
3503 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD | INVALIDATE_TYPE_TAB);
3504 }
3505}
3506
3507void WebContentsImpl::WorkerCrashed() {
3508 if (delegate_)
3509 delegate_->WorkerCrashed(this);
3510}
3511
3512void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
3513 bool proceed, const base::TimeTicks& proceed_time,
3514 bool* proceed_to_fire_unload) {
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +01003515 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3516 BeforeUnloadFired(proceed_time));
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003517 if (delegate_)
3518 delegate_->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
Ben Murdocheb525c52013-07-10 11:40:50 +01003519 // Note: |this| might be deleted at this point.
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003520}
3521
Ben Murdoch7dbb3d52013-07-17 14:55:54 +01003522void WebContentsImpl::RenderProcessGoneFromRenderManager(
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003523 RenderViewHost* render_view_host) {
3524 DCHECK(crashed_status_ != base::TERMINATION_STATUS_STILL_RUNNING);
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01003525 RenderViewTerminated(render_view_host, crashed_status_, crashed_error_code_);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003526}
3527
3528void WebContentsImpl::UpdateRenderViewSizeForRenderManager() {
3529 // TODO(brettw) this is a hack. See WebContentsView::SizeContents.
3530 gfx::Size size = view_->GetContainerSize();
3531 // 0x0 isn't a valid window size (minimal window size is 1x1) but it may be
3532 // here during container initialization and normal window size will be set
3533 // later. In case of tab duplication this resizing to 0x0 prevents setting
3534 // normal size later so just ignore it.
3535 if (!size.IsEmpty())
3536 view_->SizeContents(size);
3537}
3538
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00003539void WebContentsImpl::NotifySwappedFromRenderManager(RenderViewHost* rvh) {
3540 NotifySwapped(rvh);
3541
3542 // Make sure the visible RVH reflects the new delegate's preferences.
3543 if (delegate_)
3544 view_->SetOverscrollControllerEnabled(delegate_->CanOverscrollContent());
3545
3546 view_->RenderViewSwappedIn(render_manager_.current_host());
Torne (Richard Coles)b2df76e2013-05-13 16:52:09 +01003547
3548 FrameTreeNode* root = NULL;
3549 RenderViewHostImpl* new_rvh = static_cast<RenderViewHostImpl*>(
3550 render_manager_.current_host());
3551
3552 // We are doing a cross-site navigation and swapping processes. Since frame
3553 // ids are unique to a process, we need to recreate the frame tree with the
3554 // proper main frame id.
3555 // Note that it is possible for this method to be called before the new RVH
3556 // has committed a navigation (if RenderViewHostManager short-circuits the
3557 // CommitPending call because the current RVH is dead). In that case, we
3558 // haven't heard a valid frame id to use to initialize the root node, so clear
3559 // out the root node and the first subsequent navigation message will set it
3560 // correctly.
3561 if (new_rvh->main_frame_id() != -1)
3562 root = new FrameTreeNode(new_rvh->main_frame_id(), std::string());
3563
3564 frame_tree_root_.reset(root);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003565}
3566
3567int WebContentsImpl::CreateOpenerRenderViewsForRenderManager(
3568 SiteInstance* instance) {
3569 if (!opener_)
3570 return MSG_ROUTING_NONE;
3571
3572 // Recursively create RenderViews for anything else in the opener chain.
3573 return opener_->CreateOpenerRenderViews(instance);
3574}
3575
3576int WebContentsImpl::CreateOpenerRenderViews(SiteInstance* instance) {
3577 int opener_route_id = MSG_ROUTING_NONE;
3578
3579 // If this tab has an opener, ensure it has a RenderView in the given
3580 // SiteInstance as well.
3581 if (opener_)
3582 opener_route_id = opener_->CreateOpenerRenderViews(instance);
3583
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00003584 // If any of the renderers (current, pending, or swapped out) for this
3585 // WebContents has the same SiteInstance, use it.
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003586 if (render_manager_.current_host()->GetSiteInstance() == instance)
3587 return render_manager_.current_host()->GetRoutingID();
3588
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00003589 if (render_manager_.pending_render_view_host() &&
3590 render_manager_.pending_render_view_host()->GetSiteInstance() == instance)
3591 return render_manager_.pending_render_view_host()->GetRoutingID();
3592
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003593 RenderViewHostImpl* rvh = render_manager_.GetSwappedOutRenderViewHost(
3594 instance);
3595 if (rvh)
3596 return rvh->GetRoutingID();
3597
3598 // Create a swapped out RenderView in the given SiteInstance if none exists,
3599 // setting its opener to the given route_id. Return the new view's route_id.
3600 return render_manager_.CreateRenderView(instance, opener_route_id, true);
3601}
3602
3603NavigationControllerImpl& WebContentsImpl::GetControllerForRenderManager() {
3604 return GetController();
3605}
3606
3607WebUIImpl* WebContentsImpl::CreateWebUIForRenderManager(const GURL& url) {
3608 return static_cast<WebUIImpl*>(CreateWebUI(url));
3609}
3610
3611NavigationEntry*
3612 WebContentsImpl::GetLastCommittedNavigationEntryForRenderManager() {
3613 return controller_.GetLastCommittedEntry();
3614}
3615
3616bool WebContentsImpl::CreateRenderViewForRenderManager(
3617 RenderViewHost* render_view_host, int opener_route_id) {
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +01003618 TRACE_EVENT0("browser", "WebContentsImpl::CreateRenderViewForRenderManager");
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003619 // Can be NULL during tests.
3620 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
3621
3622 // Now that the RenderView has been created, we need to tell it its size.
3623 if (rwh_view)
3624 rwh_view->SetSize(view_->GetContainerSize());
3625
3626 // Make sure we use the correct starting page_id in the new RenderView.
3627 UpdateMaxPageIDIfNecessary(render_view_host);
3628 int32 max_page_id =
3629 GetMaxPageIDForSiteInstance(render_view_host->GetSiteInstance());
3630
3631 if (!static_cast<RenderViewHostImpl*>(
3632 render_view_host)->CreateRenderView(string16(),
3633 opener_route_id,
3634 max_page_id)) {
3635 return false;
3636 }
3637
3638#if defined(OS_LINUX) || defined(OS_OPENBSD)
3639 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
3640 // linux. See crbug.com/83941.
3641 if (rwh_view) {
3642 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
3643 render_widget_host->WasResized();
3644 }
3645#endif
3646
3647 return true;
3648}
3649
3650void WebContentsImpl::OnDialogClosed(RenderViewHost* rvh,
3651 IPC::Message* reply_msg,
3652 bool success,
3653 const string16& user_input) {
3654 if (is_showing_before_unload_dialog_ && !success) {
3655 // If a beforeunload dialog is canceled, we need to stop the throbber from
3656 // spinning, since we forced it to start spinning in Navigate.
3657 DidStopLoading(rvh);
3658 controller_.DiscardNonCommittedEntries();
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +01003659
3660 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3661 BeforeUnloadDialogCancelled());
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003662 }
3663 is_showing_before_unload_dialog_ = false;
3664 static_cast<RenderViewHostImpl*>(
3665 rvh)->JavaScriptDialogClosed(reply_msg, success, user_input);
3666}
3667
3668void WebContentsImpl::SetEncoding(const std::string& encoding) {
3669 encoding_ = GetContentClient()->browser()->
3670 GetCanonicalEncodingNameByAliasName(encoding);
3671}
3672
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003673void WebContentsImpl::CreateViewAndSetSizeForRVH(RenderViewHost* rvh) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00003674 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(rvh);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003675 // Can be NULL during tests.
3676 if (rwh_view)
3677 rwh_view->SetSize(GetView()->GetContainerSize());
3678}
3679
3680RenderViewHostImpl* WebContentsImpl::GetRenderViewHostImpl() {
3681 return static_cast<RenderViewHostImpl*>(GetRenderViewHost());
3682}
3683
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00003684BrowserPluginGuest* WebContentsImpl::GetBrowserPluginGuest() const {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003685 return browser_plugin_guest_.get();
3686}
3687
Ben Murdocheb525c52013-07-10 11:40:50 +01003688void WebContentsImpl::SetBrowserPluginGuest(BrowserPluginGuest* guest) {
3689 CHECK(!browser_plugin_guest_);
3690 browser_plugin_guest_.reset(guest);
3691}
3692
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00003693BrowserPluginEmbedder* WebContentsImpl::GetBrowserPluginEmbedder() const {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003694 return browser_plugin_embedder_.get();
3695}
3696
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00003697BrowserPluginGuestManager*
3698 WebContentsImpl::GetBrowserPluginGuestManager() const {
3699 return static_cast<BrowserPluginGuestManager*>(
3700 GetBrowserContext()->GetUserData(
3701 browser_plugin::kBrowserPluginGuestManagerKeyName));
3702}
3703
Ben Murdochca12bfa2013-07-23 11:17:05 +01003704void WebContentsImpl::ClearPowerSaveBlockers(
3705 RenderViewHost* render_view_host) {
3706 STLDeleteValues(&power_save_blockers_[render_view_host]);
3707 power_save_blockers_.erase(render_view_host);
3708}
3709
3710void WebContentsImpl::ClearAllPowerSaveBlockers() {
3711 for (PowerSaveBlockerMap::iterator i(power_save_blockers_.begin());
3712 i != power_save_blockers_.end(); ++i)
3713 STLDeleteValues(&power_save_blockers_[i->first]);
3714 power_save_blockers_.clear();
3715}
3716
Torne (Richard Coles)58218062012-11-14 11:43:16 +00003717} // namespace content