Clang roll script: fix error when GYP_DEFINES isn't defined
[chromium-blink-merge.git] / content / browser / web_contents / web_contents_impl.cc
blob8fec4e016f74d876e583b6f6ecb8f34c8dbbc3d3
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/web_contents/web_contents_impl.h"
7 #include <utility>
9 #include "base/command_line.h"
10 #include "base/debug/trace_event.h"
11 #include "base/lazy_instance.h"
12 #include "base/logging.h"
13 #include "base/metrics/histogram.h"
14 #include "base/metrics/stats_counters.h"
15 #include "base/process/process.h"
16 #include "base/strings/string16.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/time/time.h"
21 #include "content/browser/browser_plugin/browser_plugin_embedder.h"
22 #include "content/browser/browser_plugin/browser_plugin_guest.h"
23 #include "content/browser/browser_plugin/browser_plugin_guest_manager.h"
24 #include "content/browser/child_process_security_policy_impl.h"
25 #include "content/browser/devtools/devtools_manager_impl.h"
26 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
27 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
28 #include "content/browser/download/download_stats.h"
29 #include "content/browser/download/mhtml_generation_manager.h"
30 #include "content/browser/download/save_package.h"
31 #include "content/browser/frame_host/interstitial_page_impl.h"
32 #include "content/browser/frame_host/navigation_entry_impl.h"
33 #include "content/browser/frame_host/navigator_impl.h"
34 #include "content/browser/frame_host/render_frame_host_impl.h"
35 #include "content/browser/host_zoom_map_impl.h"
36 #include "content/browser/loader/resource_dispatcher_host_impl.h"
37 #include "content/browser/message_port_message_filter.h"
38 #include "content/browser/message_port_service.h"
39 #include "content/browser/power_save_blocker_impl.h"
40 #include "content/browser/renderer_host/render_process_host_impl.h"
41 #include "content/browser/renderer_host/render_view_host_impl.h"
42 #include "content/browser/renderer_host/render_widget_host_impl.h"
43 #include "content/browser/site_instance_impl.h"
44 #include "content/browser/web_contents/web_contents_view_guest.h"
45 #include "content/browser/webui/generic_handler.h"
46 #include "content/browser/webui/web_ui_controller_factory_registry.h"
47 #include "content/browser/webui/web_ui_impl.h"
48 #include "content/common/browser_plugin/browser_plugin_constants.h"
49 #include "content/common/browser_plugin/browser_plugin_messages.h"
50 #include "content/common/frame_messages.h"
51 #include "content/common/image_messages.h"
52 #include "content/common/ssl_status_serialization.h"
53 #include "content/common/view_messages.h"
54 #include "content/port/browser/render_view_host_delegate_view.h"
55 #include "content/port/browser/render_widget_host_view_port.h"
56 #include "content/public/browser/browser_context.h"
57 #include "content/public/browser/color_chooser.h"
58 #include "content/public/browser/content_browser_client.h"
59 #include "content/public/browser/devtools_agent_host.h"
60 #include "content/public/browser/download_manager.h"
61 #include "content/public/browser/download_url_parameters.h"
62 #include "content/public/browser/invalidate_type.h"
63 #include "content/public/browser/javascript_dialog_manager.h"
64 #include "content/public/browser/load_from_memory_cache_details.h"
65 #include "content/public/browser/load_notification_details.h"
66 #include "content/public/browser/navigation_details.h"
67 #include "content/public/browser/notification_details.h"
68 #include "content/public/browser/notification_service.h"
69 #include "content/public/browser/resource_request_details.h"
70 #include "content/public/browser/storage_partition.h"
71 #include "content/public/browser/user_metrics.h"
72 #include "content/public/browser/web_contents_delegate.h"
73 #include "content/public/browser/web_contents_observer.h"
74 #include "content/public/browser/web_contents_view.h"
75 #include "content/public/common/bindings_policy.h"
76 #include "content/public/common/content_constants.h"
77 #include "content/public/common/content_switches.h"
78 #include "content/public/common/page_zoom.h"
79 #include "content/public/common/result_codes.h"
80 #include "content/public/common/url_constants.h"
81 #include "content/public/common/url_utils.h"
82 #include "net/base/mime_util.h"
83 #include "net/base/net_util.h"
84 #include "net/http/http_cache.h"
85 #include "net/http/http_transaction_factory.h"
86 #include "net/url_request/url_request_context.h"
87 #include "net/url_request/url_request_context_getter.h"
88 #include "ui/base/layout.h"
89 #include "ui/gfx/display.h"
90 #include "ui/gfx/screen.h"
91 #include "ui/gl/gl_switches.h"
92 #include "webkit/common/webpreferences.h"
94 #if defined(OS_ANDROID)
95 #include "content/browser/android/date_time_chooser_android.h"
96 #include "content/browser/renderer_host/java/java_bridge_dispatcher_host_manager.h"
97 #include "content/browser/web_contents/web_contents_android.h"
98 #include "content/common/java_bridge_messages.h"
99 #include "content/public/browser/android/content_view_core.h"
100 #endif
102 #if defined(OS_MACOSX)
103 #include "base/mac/foundation_util.h"
104 #include "ui/gl/io_surface_support_mac.h"
105 #endif
107 // Cross-Site Navigations
109 // If a WebContentsImpl is told to navigate to a different web site (as
110 // determined by SiteInstance), it will replace its current RenderViewHost with
111 // a new RenderViewHost dedicated to the new SiteInstance. This works as
112 // follows:
114 // - RVHM::Navigate determines whether the destination is cross-site, and if so,
115 // it creates a pending_render_view_host_.
116 // - The pending RVH is "suspended," so that no navigation messages are sent to
117 // its renderer until the beforeunload JavaScript handler has a chance to
118 // run in the current RVH.
119 // - The pending RVH tells CrossSiteRequestManager (a thread-safe singleton)
120 // that it has a pending cross-site request. We will check this on the IO
121 // thread when deciding how to handle the response.
122 // - The current RVH runs its beforeunload handler. If it returns false, we
123 // cancel all the pending logic. Otherwise we allow the pending RVH to send
124 // the navigation request to its renderer.
125 // - ResourceDispatcherHost receives a ResourceRequest on the IO thread for the
126 // main resource load on the pending RVH. It creates a
127 // CrossSiteResourceHandler to check whether a process swap is needed when
128 // the request is ready to commit.
129 // - When RDH receives a response, the BufferedResourceHandler determines
130 // whether it is a download. If so, it sends a message to the new renderer
131 // causing it to cancel the request, and the download proceeds. For now, the
132 // pending RVH remains until the next DidNavigate event for this
133 // WebContentsImpl. This isn't ideal, but it doesn't affect any functionality.
134 // - After RDH receives a response and determines that it is safe and not a
135 // download, the CrossSiteResourceHandler checks whether a process swap is
136 // needed (either because CrossSiteRequestManager has state for it or because
137 // a transfer was needed for a redirect).
138 // - If so, CrossSiteResourceHandler pauses the response to first run the old
139 // page's unload handler. It does this by asynchronously calling the
140 // OnCrossSiteResponse method of RenderFrameHostManager on the UI thread,
141 // which sends a SwapOut message to the current RVH.
142 // - Once the unload handler is finished, RVHM::SwappedOut checks if a transfer
143 // to a new process is needed, based on the stored pending_nav_params_. (This
144 // is independent of whether we started out with a cross-process navigation.)
145 // - If not, it just tells the ResourceDispatcherHost to resume the response
146 // to its current RenderViewHost.
147 // - If so, it cancels the current pending RenderViewHost and sets up a new
148 // navigation using RequestTransferURL. When the transferred request
149 // arrives in the ResourceDispatcherHost, we transfer the response and
150 // resume it.
151 // - The pending renderer sends a FrameNavigate message that invokes the
152 // DidNavigate method. This replaces the current RVH with the
153 // pending RVH.
154 // - The previous renderer is kept swapped out in RenderFrameHostManager in case
155 // the user goes back. The process only stays live if another tab is using
156 // it, but if so, the existing frame relationships will be maintained.
158 namespace content {
159 namespace {
161 const char kDotGoogleDotCom[] = ".google.com";
163 #if defined(OS_ANDROID)
164 const char kWebContentsAndroidKey[] = "web_contents_android";
165 #endif // OS_ANDROID
167 base::LazyInstance<std::vector<WebContentsImpl::CreatedCallback> >
168 g_created_callbacks = LAZY_INSTANCE_INITIALIZER;
170 static int StartDownload(content::RenderViewHost* rvh,
171 const GURL& url,
172 bool is_favicon,
173 uint32_t max_bitmap_size) {
174 static int g_next_image_download_id = 0;
175 rvh->Send(new ImageMsg_DownloadImage(rvh->GetRoutingID(),
176 ++g_next_image_download_id,
177 url,
178 is_favicon,
179 max_bitmap_size));
180 return g_next_image_download_id;
183 void NotifyCacheOnIO(
184 scoped_refptr<net::URLRequestContextGetter> request_context,
185 const GURL& url,
186 const std::string& http_method) {
187 request_context->GetURLRequestContext()->http_transaction_factory()->
188 GetCache()->OnExternalCacheHit(url, http_method);
191 // Helper function for retrieving all the sites in a frame tree.
192 bool CollectSites(BrowserContext* context,
193 std::set<GURL>* sites,
194 FrameTreeNode* node) {
195 sites->insert(SiteInstance::GetSiteForURL(context, node->current_url()));
196 return true;
199 bool ForEachFrameInternal(
200 const base::Callback<void(RenderFrameHost*)>& on_frame,
201 FrameTreeNode* node) {
202 on_frame.Run(node->current_frame_host());
203 return true;
206 void SendToAllFramesInternal(IPC::Message* message, RenderFrameHost* rfh) {
207 IPC::Message* message_copy = new IPC::Message(*message);
208 message_copy->set_routing_id(rfh->GetRoutingID());
209 rfh->Send(message_copy);
212 } // namespace
214 WebContents* WebContents::Create(const WebContents::CreateParams& params) {
215 return WebContentsImpl::CreateWithOpener(
216 params, static_cast<WebContentsImpl*>(params.opener));
219 WebContents* WebContents::CreateWithSessionStorage(
220 const WebContents::CreateParams& params,
221 const SessionStorageNamespaceMap& session_storage_namespace_map) {
222 WebContentsImpl* new_contents = new WebContentsImpl(
223 params.browser_context, NULL);
225 for (SessionStorageNamespaceMap::const_iterator it =
226 session_storage_namespace_map.begin();
227 it != session_storage_namespace_map.end();
228 ++it) {
229 new_contents->GetController()
230 .SetSessionStorageNamespace(it->first, it->second.get());
233 new_contents->Init(params);
234 return new_contents;
237 void WebContentsImpl::AddCreatedCallback(const CreatedCallback& callback) {
238 g_created_callbacks.Get().push_back(callback);
241 void WebContentsImpl::RemoveCreatedCallback(const CreatedCallback& callback) {
242 for (size_t i = 0; i < g_created_callbacks.Get().size(); ++i) {
243 if (g_created_callbacks.Get().at(i).Equals(callback)) {
244 g_created_callbacks.Get().erase(g_created_callbacks.Get().begin() + i);
245 return;
250 WebContents* WebContents::FromRenderViewHost(const RenderViewHost* rvh) {
251 return rvh->GetDelegate()->GetAsWebContents();
254 WebContents* WebContents::FromRenderFrameHost(RenderFrameHost* rfh) {
255 RenderFrameHostImpl* rfh_impl = static_cast<RenderFrameHostImpl*>(rfh);
256 if (!rfh_impl)
257 return NULL;
258 return rfh_impl->delegate()->GetAsWebContents();
261 // WebContentsImpl::DestructionObserver ----------------------------------------
263 class WebContentsImpl::DestructionObserver : public WebContentsObserver {
264 public:
265 DestructionObserver(WebContentsImpl* owner, WebContents* watched_contents)
266 : WebContentsObserver(watched_contents),
267 owner_(owner) {
270 // WebContentsObserver:
271 virtual void WebContentsDestroyed(WebContents* web_contents) OVERRIDE {
272 owner_->OnWebContentsDestroyed(static_cast<WebContentsImpl*>(web_contents));
275 private:
276 WebContentsImpl* owner_;
278 DISALLOW_COPY_AND_ASSIGN(DestructionObserver);
281 // WebContentsImpl -------------------------------------------------------------
283 WebContentsImpl::WebContentsImpl(
284 BrowserContext* browser_context,
285 WebContentsImpl* opener)
286 : delegate_(NULL),
287 controller_(this, browser_context),
288 render_view_host_delegate_view_(NULL),
289 opener_(opener),
290 #if defined(OS_WIN)
291 accessible_parent_(NULL),
292 #endif
293 frame_tree_(new NavigatorImpl(&controller_, this),
294 this, this, this, this),
295 is_loading_(false),
296 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING),
297 crashed_error_code_(0),
298 waiting_for_response_(false),
299 load_state_(net::LOAD_STATE_IDLE, base::string16()),
300 upload_size_(0),
301 upload_position_(0),
302 displayed_insecure_content_(false),
303 capturer_count_(0),
304 should_normally_be_visible_(true),
305 is_being_destroyed_(false),
306 notify_disconnection_(false),
307 dialog_manager_(NULL),
308 is_showing_before_unload_dialog_(false),
309 closed_by_user_gesture_(false),
310 minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)),
311 maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)),
312 temporary_zoom_settings_(false),
313 color_chooser_identifier_(0),
314 render_view_message_source_(NULL),
315 fullscreen_widget_routing_id_(MSG_ROUTING_NONE),
316 is_subframe_(false) {
317 for (size_t i = 0; i < g_created_callbacks.Get().size(); i++)
318 g_created_callbacks.Get().at(i).Run(this);
319 frame_tree_.SetFrameRemoveListener(
320 base::Bind(&WebContentsImpl::OnFrameRemoved,
321 base::Unretained(this)));
324 WebContentsImpl::~WebContentsImpl() {
325 is_being_destroyed_ = true;
327 ClearAllPowerSaveBlockers();
329 for (std::set<RenderWidgetHostImpl*>::iterator iter =
330 created_widgets_.begin(); iter != created_widgets_.end(); ++iter) {
331 (*iter)->DetachDelegate();
333 created_widgets_.clear();
335 // Clear out any JavaScript state.
336 if (dialog_manager_)
337 dialog_manager_->WebContentsDestroyed(this);
339 if (color_chooser_)
340 color_chooser_->End();
342 NotifyDisconnected();
344 // Notify any observer that have a reference on this WebContents.
345 NotificationService::current()->Notify(
346 NOTIFICATION_WEB_CONTENTS_DESTROYED,
347 Source<WebContents>(this),
348 NotificationService::NoDetails());
350 RenderViewHost* pending_rvh = GetRenderManager()->pending_render_view_host();
351 if (pending_rvh) {
352 FOR_EACH_OBSERVER(WebContentsObserver,
353 observers_,
354 RenderViewDeleted(pending_rvh));
357 FOR_EACH_OBSERVER(WebContentsObserver,
358 observers_,
359 RenderViewDeleted(GetRenderManager()->current_host()));
361 FOR_EACH_OBSERVER(WebContentsObserver,
362 observers_,
363 WebContentsImplDestroyed());
365 SetDelegate(NULL);
367 STLDeleteContainerPairSecondPointers(destruction_observers_.begin(),
368 destruction_observers_.end());
371 WebContentsImpl* WebContentsImpl::CreateWithOpener(
372 const WebContents::CreateParams& params,
373 WebContentsImpl* opener) {
374 TRACE_EVENT0("browser", "WebContentsImpl::CreateWithOpener");
375 WebContentsImpl* new_contents = new WebContentsImpl(
376 params.browser_context, opener);
378 new_contents->Init(params);
379 return new_contents;
382 // static
383 BrowserPluginGuest* WebContentsImpl::CreateGuest(
384 BrowserContext* browser_context,
385 SiteInstance* site_instance,
386 int guest_instance_id,
387 scoped_ptr<base::DictionaryValue> extra_params) {
388 WebContentsImpl* new_contents = new WebContentsImpl(browser_context, NULL);
390 // This makes |new_contents| act as a guest.
391 // For more info, see comment above class BrowserPluginGuest.
392 BrowserPluginGuest::Create(
393 guest_instance_id, site_instance, new_contents, extra_params.Pass());
395 WebContents::CreateParams create_params(browser_context, site_instance);
396 new_contents->Init(create_params);
398 // We are instantiating a WebContents for browser plugin. Set its subframe bit
399 // to true.
400 new_contents->is_subframe_ = true;
402 return new_contents->browser_plugin_guest_.get();
405 RenderFrameHostManager* WebContentsImpl::GetRenderManagerForTesting() {
406 return GetRenderManager();
409 bool WebContentsImpl::OnMessageReceived(RenderViewHost* render_view_host,
410 const IPC::Message& message) {
411 return OnMessageReceived(render_view_host, NULL, message);
414 bool WebContentsImpl::OnMessageReceived(RenderViewHost* render_view_host,
415 RenderFrameHost* render_frame_host,
416 const IPC::Message& message) {
417 DCHECK(render_view_host || render_frame_host);
418 if (GetWebUI() &&
419 static_cast<WebUIImpl*>(GetWebUI())->OnMessageReceived(message)) {
420 return true;
423 ObserverListBase<WebContentsObserver>::Iterator it(observers_);
424 WebContentsObserver* observer;
425 while ((observer = it.GetNext()) != NULL)
426 if (observer->OnMessageReceived(message))
427 return true;
429 // Message handlers should be aware of which RenderViewHost sent the
430 // message, which is temporarily stored in render_view_message_source_.
431 render_view_message_source_ = render_view_host;
432 bool handled = true;
433 bool message_is_ok = true;
434 IPC_BEGIN_MESSAGE_MAP_EX(WebContentsImpl, message, message_is_ok)
435 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung, OnPepperPluginHung)
436 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed, OnPluginCrashed)
437 IPC_MESSAGE_HANDLER(ViewHostMsg_DidLoadResourceFromMemoryCache,
438 OnDidLoadResourceFromMemoryCache)
439 IPC_MESSAGE_HANDLER(ViewHostMsg_DidDisplayInsecureContent,
440 OnDidDisplayInsecureContent)
441 IPC_MESSAGE_HANDLER(ViewHostMsg_DidRunInsecureContent,
442 OnDidRunInsecureContent)
443 IPC_MESSAGE_HANDLER(ViewHostMsg_DocumentLoadedInFrame,
444 OnDocumentLoadedInFrame)
445 IPC_MESSAGE_HANDLER(ViewHostMsg_DidFinishLoad, OnDidFinishLoad)
446 IPC_MESSAGE_HANDLER(ViewHostMsg_DidFailLoadWithError,
447 OnDidFailLoadWithError)
448 IPC_MESSAGE_HANDLER(ViewHostMsg_GoToEntryAtOffset, OnGoToEntryAtOffset)
449 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateZoomLimits, OnUpdateZoomLimits)
450 IPC_MESSAGE_HANDLER(ViewHostMsg_EnumerateDirectory, OnEnumerateDirectory)
451 IPC_MESSAGE_HANDLER(ViewHostMsg_JSOutOfMemory, OnJSOutOfMemory)
452 IPC_MESSAGE_HANDLER(ViewHostMsg_RegisterProtocolHandler,
453 OnRegisterProtocolHandler)
454 IPC_MESSAGE_HANDLER(ViewHostMsg_Find_Reply, OnFindReply)
455 IPC_MESSAGE_HANDLER(ViewHostMsg_AppCacheAccessed, OnAppCacheAccessed)
456 IPC_MESSAGE_HANDLER(ViewHostMsg_OpenColorChooser, OnOpenColorChooser)
457 IPC_MESSAGE_HANDLER(ViewHostMsg_EndColorChooser, OnEndColorChooser)
458 IPC_MESSAGE_HANDLER(ViewHostMsg_SetSelectedColorInColorChooser,
459 OnSetSelectedColorInColorChooser)
460 IPC_MESSAGE_HANDLER(ViewHostMsg_WebUISend, OnWebUISend)
461 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission,
462 OnRequestPpapiBrokerPermission)
463 IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_AllocateInstanceID,
464 OnBrowserPluginMessage(message))
465 IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_Attach,
466 OnBrowserPluginMessage(message))
467 IPC_MESSAGE_HANDLER(ImageHostMsg_DidDownloadImage, OnDidDownloadImage)
468 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateFaviconURL, OnUpdateFaviconURL)
469 #if defined(OS_ANDROID)
470 IPC_MESSAGE_HANDLER(ViewHostMsg_FindMatchRects_Reply,
471 OnFindMatchRectsReply)
472 IPC_MESSAGE_HANDLER(ViewHostMsg_OpenDateTimeDialog,
473 OnOpenDateTimeDialog)
474 IPC_MESSAGE_HANDLER_DELAY_REPLY(JavaBridgeHostMsg_GetChannelHandle,
475 OnJavaBridgeGetChannelHandle)
476 #endif
477 IPC_MESSAGE_HANDLER(ViewHostMsg_MediaNotification, OnMediaNotification)
478 IPC_MESSAGE_HANDLER(ViewHostMsg_DidFirstVisuallyNonEmptyPaint,
479 OnFirstVisuallyNonEmptyPaint)
480 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowValidationMessage,
481 OnShowValidationMessage)
482 IPC_MESSAGE_HANDLER(ViewHostMsg_HideValidationMessage,
483 OnHideValidationMessage)
484 IPC_MESSAGE_HANDLER(ViewHostMsg_MoveValidationMessage,
485 OnMoveValidationMessage)
486 IPC_MESSAGE_UNHANDLED(handled = false)
487 IPC_END_MESSAGE_MAP_EX()
488 render_view_message_source_ = NULL;
490 if (!message_is_ok) {
491 RecordAction(base::UserMetricsAction("BadMessageTerminate_RVD"));
492 GetRenderProcessHost()->ReceivedBadMessage();
495 return handled;
498 void WebContentsImpl::RunFileChooser(
499 RenderViewHost* render_view_host,
500 const FileChooserParams& params) {
501 if (delegate_)
502 delegate_->RunFileChooser(this, params);
505 NavigationControllerImpl& WebContentsImpl::GetController() {
506 return controller_;
509 const NavigationControllerImpl& WebContentsImpl::GetController() const {
510 return controller_;
513 BrowserContext* WebContentsImpl::GetBrowserContext() const {
514 return controller_.GetBrowserContext();
517 const GURL& WebContentsImpl::GetURL() const {
518 // We may not have a navigation entry yet.
519 NavigationEntry* entry = controller_.GetVisibleEntry();
520 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
523 const GURL& WebContentsImpl::GetVisibleURL() const {
524 // We may not have a navigation entry yet.
525 NavigationEntry* entry = controller_.GetVisibleEntry();
526 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
529 const GURL& WebContentsImpl::GetLastCommittedURL() const {
530 // We may not have a navigation entry yet.
531 NavigationEntry* entry = controller_.GetLastCommittedEntry();
532 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
535 WebContentsDelegate* WebContentsImpl::GetDelegate() {
536 return delegate_;
539 void WebContentsImpl::SetDelegate(WebContentsDelegate* delegate) {
540 // TODO(cbentzel): remove this debugging code?
541 if (delegate == delegate_)
542 return;
543 if (delegate_)
544 delegate_->Detach(this);
545 delegate_ = delegate;
546 if (delegate_) {
547 delegate_->Attach(this);
548 // Ensure the visible RVH reflects the new delegate's preferences.
549 if (view_)
550 view_->SetOverscrollControllerEnabled(delegate->CanOverscrollContent());
554 RenderProcessHost* WebContentsImpl::GetRenderProcessHost() const {
555 RenderViewHostImpl* host = GetRenderManager()->current_host();
556 return host ? host->GetProcess() : NULL;
559 RenderFrameHost* WebContentsImpl::GetMainFrame() {
560 return frame_tree_.root()->current_frame_host();
563 void WebContentsImpl::ForEachFrame(
564 const base::Callback<void(RenderFrameHost*)>& on_frame) {
565 frame_tree_.ForEach(base::Bind(&ForEachFrameInternal, on_frame));
568 void WebContentsImpl::SendToAllFrames(IPC::Message* message) {
569 ForEachFrame(base::Bind(&SendToAllFramesInternal, message));
570 delete message;
573 RenderViewHost* WebContentsImpl::GetRenderViewHost() const {
574 return GetRenderManager()->current_host();
577 void WebContentsImpl::GetRenderViewHostAtPosition(
578 int x,
579 int y,
580 const base::Callback<void(RenderViewHost*, int, int)>& callback) {
581 BrowserPluginEmbedder* embedder = GetBrowserPluginEmbedder();
582 if (embedder)
583 embedder->GetRenderViewHostAtPosition(x, y, callback);
584 else
585 callback.Run(GetRenderViewHost(), x, y);
588 WebContents* WebContentsImpl::GetEmbedderWebContents() const {
589 BrowserPluginGuest* guest = GetBrowserPluginGuest();
590 if (guest)
591 return guest->embedder_web_contents();
592 return NULL;
595 int WebContentsImpl::GetEmbeddedInstanceID() const {
596 BrowserPluginGuest* guest = GetBrowserPluginGuest();
597 if (guest)
598 return guest->instance_id();
599 return 0;
602 int WebContentsImpl::GetRoutingID() const {
603 if (!GetRenderViewHost())
604 return MSG_ROUTING_NONE;
606 return GetRenderViewHost()->GetRoutingID();
609 int WebContentsImpl::GetFullscreenWidgetRoutingID() const {
610 return fullscreen_widget_routing_id_;
613 RenderWidgetHostView* WebContentsImpl::GetRenderWidgetHostView() const {
614 return GetRenderManager()->GetRenderWidgetHostView();
617 RenderWidgetHostViewPort* WebContentsImpl::GetRenderWidgetHostViewPort() const {
618 BrowserPluginGuest* guest = GetBrowserPluginGuest();
619 if (guest && guest->embedder_web_contents()) {
620 return guest->embedder_web_contents()->GetRenderWidgetHostViewPort();
622 return RenderWidgetHostViewPort::FromRWHV(GetRenderWidgetHostView());
625 RenderWidgetHostView* WebContentsImpl::GetFullscreenRenderWidgetHostView()
626 const {
627 RenderWidgetHost* const widget_host =
628 RenderWidgetHostImpl::FromID(GetRenderProcessHost()->GetID(),
629 GetFullscreenWidgetRoutingID());
630 return widget_host ? widget_host->GetView() : NULL;
633 WebContentsView* WebContentsImpl::GetView() const {
634 return view_.get();
637 WebUI* WebContentsImpl::CreateWebUI(const GURL& url) {
638 WebUIImpl* web_ui = new WebUIImpl(this);
639 WebUIController* controller = WebUIControllerFactoryRegistry::GetInstance()->
640 CreateWebUIControllerForURL(web_ui, url);
641 if (controller) {
642 web_ui->AddMessageHandler(new GenericHandler());
643 web_ui->SetController(controller);
644 return web_ui;
647 delete web_ui;
648 return NULL;
651 WebUI* WebContentsImpl::GetWebUI() const {
652 return GetRenderManager()->web_ui() ? GetRenderManager()->web_ui()
653 : GetRenderManager()->pending_web_ui();
656 WebUI* WebContentsImpl::GetCommittedWebUI() const {
657 return GetRenderManager()->web_ui();
660 void WebContentsImpl::SetUserAgentOverride(const std::string& override) {
661 if (GetUserAgentOverride() == override)
662 return;
664 renderer_preferences_.user_agent_override = override;
666 // Send the new override string to the renderer.
667 RenderViewHost* host = GetRenderViewHost();
668 if (host)
669 host->SyncRendererPrefs();
671 // Reload the page if a load is currently in progress to avoid having
672 // different parts of the page loaded using different user agents.
673 NavigationEntry* entry = controller_.GetVisibleEntry();
674 if (is_loading_ && entry != NULL && entry->GetIsOverridingUserAgent())
675 controller_.ReloadIgnoringCache(true);
677 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
678 UserAgentOverrideSet(override));
681 const std::string& WebContentsImpl::GetUserAgentOverride() const {
682 return renderer_preferences_.user_agent_override;
685 #if defined(OS_WIN)
686 void WebContentsImpl::SetParentNativeViewAccessible(
687 gfx::NativeViewAccessible accessible_parent) {
688 accessible_parent_ = accessible_parent;
689 if (GetRenderViewHost())
690 GetRenderViewHostImpl()->SetParentNativeViewAccessible(accessible_parent);
692 #endif
694 const base::string16& WebContentsImpl::GetTitle() const {
695 // Transient entries take precedence. They are used for interstitial pages
696 // that are shown on top of existing pages.
697 NavigationEntry* entry = controller_.GetTransientEntry();
698 std::string accept_languages =
699 GetContentClient()->browser()->GetAcceptLangs(
700 GetBrowserContext());
701 if (entry) {
702 return entry->GetTitleForDisplay(accept_languages);
704 WebUI* our_web_ui = GetRenderManager()->pending_web_ui() ?
705 GetRenderManager()->pending_web_ui() : GetRenderManager()->web_ui();
706 if (our_web_ui) {
707 // Don't override the title in view source mode.
708 entry = controller_.GetVisibleEntry();
709 if (!(entry && entry->IsViewSourceMode())) {
710 // Give the Web UI the chance to override our title.
711 const base::string16& title = our_web_ui->GetOverriddenTitle();
712 if (!title.empty())
713 return title;
717 // We use the title for the last committed entry rather than a pending
718 // navigation entry. For example, when the user types in a URL, we want to
719 // keep the old page's title until the new load has committed and we get a new
720 // title.
721 entry = controller_.GetLastCommittedEntry();
723 // We make an exception for initial navigations.
724 if (controller_.IsInitialNavigation()) {
725 // We only want to use the title from the visible entry in one of two cases:
726 // 1. There's already a committed entry for an initial navigation, in which
727 // case we are doing a history navigation in a new tab (e.g., Ctrl+Back).
728 // 2. The pending entry has been explicitly assigned a title to display.
730 // If there's no last committed entry and no assigned title, we should fall
731 // back to |page_title_when_no_navigation_entry_| rather than showing the
732 // URL.
733 if (entry ||
734 (controller_.GetVisibleEntry() &&
735 !controller_.GetVisibleEntry()->GetTitle().empty())) {
736 entry = controller_.GetVisibleEntry();
740 if (entry) {
741 return entry->GetTitleForDisplay(accept_languages);
744 // |page_title_when_no_navigation_entry_| is finally used
745 // if no title cannot be retrieved.
746 return page_title_when_no_navigation_entry_;
749 int32 WebContentsImpl::GetMaxPageID() {
750 return GetMaxPageIDForSiteInstance(GetSiteInstance());
753 int32 WebContentsImpl::GetMaxPageIDForSiteInstance(
754 SiteInstance* site_instance) {
755 if (max_page_ids_.find(site_instance->GetId()) == max_page_ids_.end())
756 max_page_ids_[site_instance->GetId()] = -1;
758 return max_page_ids_[site_instance->GetId()];
761 void WebContentsImpl::UpdateMaxPageID(int32 page_id) {
762 UpdateMaxPageIDForSiteInstance(GetSiteInstance(), page_id);
765 void WebContentsImpl::UpdateMaxPageIDForSiteInstance(
766 SiteInstance* site_instance, int32 page_id) {
767 if (GetMaxPageIDForSiteInstance(site_instance) < page_id)
768 max_page_ids_[site_instance->GetId()] = page_id;
771 void WebContentsImpl::CopyMaxPageIDsFrom(WebContents* web_contents) {
772 WebContentsImpl* contents = static_cast<WebContentsImpl*>(web_contents);
773 max_page_ids_ = contents->max_page_ids_;
776 SiteInstance* WebContentsImpl::GetSiteInstance() const {
777 return GetRenderManager()->current_host()->GetSiteInstance();
780 SiteInstance* WebContentsImpl::GetPendingSiteInstance() const {
781 RenderViewHost* dest_rvh = GetRenderManager()->pending_render_view_host() ?
782 GetRenderManager()->pending_render_view_host() :
783 GetRenderManager()->current_host();
784 return dest_rvh->GetSiteInstance();
787 bool WebContentsImpl::IsLoading() const {
788 return is_loading_;
791 bool WebContentsImpl::IsWaitingForResponse() const {
792 return waiting_for_response_;
795 const net::LoadStateWithParam& WebContentsImpl::GetLoadState() const {
796 return load_state_;
799 const base::string16& WebContentsImpl::GetLoadStateHost() const {
800 return load_state_host_;
803 uint64 WebContentsImpl::GetUploadSize() const {
804 return upload_size_;
807 uint64 WebContentsImpl::GetUploadPosition() const {
808 return upload_position_;
811 std::set<GURL> WebContentsImpl::GetSitesInTab() const {
812 std::set<GURL> sites;
813 frame_tree_.ForEach(base::Bind(&CollectSites,
814 base::Unretained(GetBrowserContext()),
815 base::Unretained(&sites)));
816 return sites;
819 const std::string& WebContentsImpl::GetEncoding() const {
820 return encoding_;
823 bool WebContentsImpl::DisplayedInsecureContent() const {
824 return displayed_insecure_content_;
827 void WebContentsImpl::IncrementCapturerCount() {
828 DCHECK(!is_being_destroyed_);
829 ++capturer_count_;
830 DVLOG(1) << "There are now " << capturer_count_
831 << " capturing(s) of WebContentsImpl@" << this;
834 void WebContentsImpl::DecrementCapturerCount() {
835 --capturer_count_;
836 DVLOG(1) << "There are now " << capturer_count_
837 << " capturing(s) of WebContentsImpl@" << this;
838 DCHECK_LE(0, capturer_count_);
840 if (is_being_destroyed_)
841 return;
843 if (IsHidden()) {
844 DVLOG(1) << "Executing delayed WasHidden().";
845 WasHidden();
849 int WebContentsImpl::GetCapturerCount() const {
850 return capturer_count_;
853 bool WebContentsImpl::IsCrashed() const {
854 return (crashed_status_ == base::TERMINATION_STATUS_PROCESS_CRASHED ||
855 crashed_status_ == base::TERMINATION_STATUS_ABNORMAL_TERMINATION ||
856 crashed_status_ == base::TERMINATION_STATUS_PROCESS_WAS_KILLED);
859 void WebContentsImpl::SetIsCrashed(base::TerminationStatus status,
860 int error_code) {
861 if (status == crashed_status_)
862 return;
864 crashed_status_ = status;
865 crashed_error_code_ = error_code;
866 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
869 base::TerminationStatus WebContentsImpl::GetCrashedStatus() const {
870 return crashed_status_;
873 bool WebContentsImpl::IsBeingDestroyed() const {
874 return is_being_destroyed_;
877 void WebContentsImpl::NotifyNavigationStateChanged(unsigned changed_flags) {
878 if (delegate_)
879 delegate_->NavigationStateChanged(this, changed_flags);
882 base::TimeTicks WebContentsImpl::GetLastSelectedTime() const {
883 return last_selected_time_;
886 void WebContentsImpl::WasShown() {
887 controller_.SetActive(true);
888 RenderWidgetHostViewPort* rwhv =
889 RenderWidgetHostViewPort::FromRWHV(GetRenderWidgetHostView());
890 if (rwhv) {
891 rwhv->Show();
892 #if defined(OS_MACOSX)
893 rwhv->SetActive(true);
894 #endif
897 last_selected_time_ = base::TimeTicks::Now();
899 // The resize rect might have changed while this was inactive -- send the new
900 // one to make sure it's up to date.
901 RenderViewHostImpl* rvh =
902 static_cast<RenderViewHostImpl*>(GetRenderViewHost());
903 if (rvh) {
904 rvh->ResizeRectChanged(GetRootWindowResizerRect());
907 FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasShown());
909 should_normally_be_visible_ = true;
912 void WebContentsImpl::WasHidden() {
913 // If there are entities capturing screenshots or video (e.g., mirroring),
914 // don't activate the "disable rendering" optimization.
915 if (capturer_count_ == 0) {
916 // |GetRenderViewHost()| can be NULL if the user middle clicks a link to
917 // open a tab in the background, then closes the tab before selecting it.
918 // This is because closing the tab calls WebContentsImpl::Destroy(), which
919 // removes the |GetRenderViewHost()|; then when we actually destroy the
920 // window, OnWindowPosChanged() notices and calls WasHidden() (which
921 // calls us).
922 RenderWidgetHostViewPort* rwhv =
923 RenderWidgetHostViewPort::FromRWHV(GetRenderWidgetHostView());
924 if (rwhv)
925 rwhv->Hide();
928 FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasHidden());
930 should_normally_be_visible_ = false;
933 bool WebContentsImpl::NeedToFireBeforeUnload() {
934 // TODO(creis): Should we fire even for interstitial pages?
935 return WillNotifyDisconnection() &&
936 !ShowingInterstitialPage() &&
937 !static_cast<RenderViewHostImpl*>(
938 GetRenderViewHost())->SuddenTerminationAllowed();
941 void WebContentsImpl::Stop() {
942 GetRenderManager()->Stop();
943 FOR_EACH_OBSERVER(WebContentsObserver, observers_, NavigationStopped());
946 WebContents* WebContentsImpl::Clone() {
947 // We use our current SiteInstance since the cloned entry will use it anyway.
948 // We pass our own opener so that the cloned page can access it if it was
949 // before.
950 CreateParams create_params(GetBrowserContext(), GetSiteInstance());
951 create_params.initial_size = view_->GetContainerSize();
952 WebContentsImpl* tc = CreateWithOpener(create_params, opener_);
953 tc->GetController().CopyStateFrom(controller_);
954 FOR_EACH_OBSERVER(WebContentsObserver,
955 observers_,
956 DidCloneToNewWebContents(this, tc));
957 return tc;
960 void WebContentsImpl::Observe(int type,
961 const NotificationSource& source,
962 const NotificationDetails& details) {
963 switch (type) {
964 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: {
965 RenderWidgetHost* host = Source<RenderWidgetHost>(source).ptr();
966 for (PendingWidgetViews::iterator i = pending_widget_views_.begin();
967 i != pending_widget_views_.end(); ++i) {
968 if (host->GetView() == i->second) {
969 pending_widget_views_.erase(i);
970 break;
973 break;
975 default:
976 NOTREACHED();
980 WebContents* WebContentsImpl::GetWebContents() {
981 return this;
984 void WebContentsImpl::Init(const WebContents::CreateParams& params) {
985 // This is set before initializing the render manager since
986 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
987 // it should be hidden.
988 should_normally_be_visible_ = !params.initially_hidden;
990 GetRenderManager()->Init(
991 params.browser_context, params.site_instance, params.routing_id,
992 params.main_frame_routing_id);
994 view_.reset(GetContentClient()->browser()->
995 OverrideCreateWebContentsView(this, &render_view_host_delegate_view_));
996 if (view_) {
997 CHECK(render_view_host_delegate_view_);
998 } else {
999 WebContentsViewDelegate* delegate =
1000 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
1002 if (browser_plugin_guest_) {
1003 scoped_ptr<WebContentsViewPort> platform_view(CreateWebContentsView(
1004 this, delegate, &render_view_host_delegate_view_));
1006 WebContentsViewGuest* rv = new WebContentsViewGuest(
1007 this, browser_plugin_guest_.get(), platform_view.Pass(),
1008 render_view_host_delegate_view_);
1009 render_view_host_delegate_view_ = rv;
1010 view_.reset(rv);
1011 } else {
1012 // Regular WebContentsView.
1013 view_.reset(CreateWebContentsView(
1014 this, delegate, &render_view_host_delegate_view_));
1016 CHECK(render_view_host_delegate_view_);
1018 CHECK(view_.get());
1020 gfx::Size initial_size = params.initial_size;
1021 view_->CreateView(initial_size, params.context);
1023 // Listen for whether our opener gets destroyed.
1024 if (opener_)
1025 AddDestructionObserver(opener_);
1027 registrar_.Add(this,
1028 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1029 NotificationService::AllBrowserContextsAndSources());
1030 #if defined(OS_ANDROID)
1031 java_bridge_dispatcher_host_manager_.reset(
1032 new JavaBridgeDispatcherHostManager(this));
1033 date_time_chooser_.reset(new DateTimeChooserAndroid());
1034 #endif
1037 void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl* web_contents) {
1038 RemoveDestructionObserver(web_contents);
1040 // Clear the opener if it has been closed.
1041 if (web_contents == opener_) {
1042 opener_ = NULL;
1043 return;
1045 // Clear a pending contents that has been closed before being shown.
1046 for (PendingContents::iterator iter = pending_contents_.begin();
1047 iter != pending_contents_.end();
1048 ++iter) {
1049 if (iter->second != web_contents)
1050 continue;
1051 pending_contents_.erase(iter);
1052 return;
1054 NOTREACHED();
1057 void WebContentsImpl::AddDestructionObserver(WebContentsImpl* web_contents) {
1058 if (!ContainsKey(destruction_observers_, web_contents)) {
1059 destruction_observers_[web_contents] =
1060 new DestructionObserver(this, web_contents);
1064 void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl* web_contents) {
1065 DestructionObservers::iterator iter =
1066 destruction_observers_.find(web_contents);
1067 if (iter != destruction_observers_.end()) {
1068 delete destruction_observers_[web_contents];
1069 destruction_observers_.erase(iter);
1073 void WebContentsImpl::AddObserver(WebContentsObserver* observer) {
1074 observers_.AddObserver(observer);
1077 void WebContentsImpl::RemoveObserver(WebContentsObserver* observer) {
1078 observers_.RemoveObserver(observer);
1081 void WebContentsImpl::Activate() {
1082 if (delegate_)
1083 delegate_->ActivateContents(this);
1086 void WebContentsImpl::Deactivate() {
1087 if (delegate_)
1088 delegate_->DeactivateContents(this);
1091 void WebContentsImpl::LostCapture() {
1092 if (delegate_)
1093 delegate_->LostCapture();
1096 void WebContentsImpl::RenderWidgetDeleted(
1097 RenderWidgetHostImpl* render_widget_host) {
1098 if (is_being_destroyed_) {
1099 // |created_widgets_| might have been destroyed.
1100 return;
1103 std::set<RenderWidgetHostImpl*>::iterator iter =
1104 created_widgets_.find(render_widget_host);
1105 if (iter != created_widgets_.end())
1106 created_widgets_.erase(iter);
1108 if (render_widget_host &&
1109 render_widget_host->GetRoutingID() == fullscreen_widget_routing_id_) {
1110 if (delegate_ && delegate_->EmbedsFullscreenWidget())
1111 delegate_->ToggleFullscreenModeForTab(this, false);
1112 FOR_EACH_OBSERVER(WebContentsObserver,
1113 observers_,
1114 DidDestroyFullscreenWidget(
1115 fullscreen_widget_routing_id_));
1116 fullscreen_widget_routing_id_ = MSG_ROUTING_NONE;
1120 bool WebContentsImpl::PreHandleKeyboardEvent(
1121 const NativeWebKeyboardEvent& event,
1122 bool* is_keyboard_shortcut) {
1123 return delegate_ &&
1124 delegate_->PreHandleKeyboardEvent(this, event, is_keyboard_shortcut);
1127 void WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
1128 if (browser_plugin_embedder_ &&
1129 browser_plugin_embedder_->HandleKeyboardEvent(event)) {
1130 return;
1133 if (delegate_)
1134 delegate_->HandleKeyboardEvent(this, event);
1137 bool WebContentsImpl::PreHandleWheelEvent(
1138 const blink::WebMouseWheelEvent& event) {
1139 #if !defined(OS_MACOSX)
1140 // On platforms other than Mac, control+mousewheel changes zoom. On Mac, this
1141 // isn't done for two reasons:
1142 // -the OS already has a gesture to do this through pinch-zoom
1143 // -if a user starts an inertial scroll, let's go, and presses control
1144 // (i.e. control+tab) then the OS's buffered scroll events will come in
1145 // with control key set which isn't what the user wants
1146 if (delegate_ &&
1147 event.wheelTicksY &&
1148 (event.modifiers & blink::WebInputEvent::ControlKey)) {
1149 delegate_->ContentsZoomChange(event.wheelTicksY > 0);
1150 return true;
1152 #endif
1154 return false;
1157 #if defined(OS_WIN)
1158 gfx::NativeViewAccessible WebContentsImpl::GetParentNativeViewAccessible() {
1159 return accessible_parent_;
1161 #endif
1163 void WebContentsImpl::HandleMouseDown() {
1164 if (delegate_)
1165 delegate_->HandleMouseDown();
1168 void WebContentsImpl::HandleMouseUp() {
1169 if (delegate_)
1170 delegate_->HandleMouseUp();
1173 void WebContentsImpl::HandlePointerActivate() {
1174 if (delegate_)
1175 delegate_->HandlePointerActivate();
1178 void WebContentsImpl::HandleGestureBegin() {
1179 if (delegate_)
1180 delegate_->HandleGestureBegin();
1183 void WebContentsImpl::HandleGestureEnd() {
1184 if (delegate_)
1185 delegate_->HandleGestureEnd();
1188 void WebContentsImpl::ToggleFullscreenMode(bool enter_fullscreen) {
1189 // This method is being called to enter or leave renderer-initiated fullscreen
1190 // mode. Either way, make sure any existing fullscreen widget is shut down
1191 // first.
1192 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
1193 if (widget_view)
1194 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())->Shutdown();
1196 if (delegate_)
1197 delegate_->ToggleFullscreenModeForTab(this, enter_fullscreen);
1200 bool WebContentsImpl::IsFullscreenForCurrentTab() const {
1201 return delegate_ ? delegate_->IsFullscreenForTabOrPending(this) : false;
1204 void WebContentsImpl::RequestToLockMouse(bool user_gesture,
1205 bool last_unlocked_by_target) {
1206 if (delegate_) {
1207 delegate_->RequestToLockMouse(this, user_gesture, last_unlocked_by_target);
1208 } else {
1209 GotResponseToLockMouseRequest(false);
1213 void WebContentsImpl::LostMouseLock() {
1214 if (delegate_)
1215 delegate_->LostMouseLock();
1218 void WebContentsImpl::CreateNewWindow(
1219 int render_process_id,
1220 int route_id,
1221 int main_frame_route_id,
1222 const ViewHostMsg_CreateWindow_Params& params,
1223 SessionStorageNamespace* session_storage_namespace) {
1224 // We usually create the new window in the same BrowsingInstance (group of
1225 // script-related windows), by passing in the current SiteInstance. However,
1226 // if the opener is being suppressed (in a non-guest), we create a new
1227 // SiteInstance in its own BrowsingInstance.
1228 bool is_guest = GetRenderProcessHost()->IsGuest();
1230 // If the opener is to be suppressed, the new window can be in any process.
1231 // Since routing ids are process specific, we must not have one passed in
1232 // as argument here.
1233 DCHECK(!params.opener_suppressed || route_id == MSG_ROUTING_NONE);
1235 scoped_refptr<SiteInstance> site_instance =
1236 params.opener_suppressed && !is_guest ?
1237 SiteInstance::CreateForURL(GetBrowserContext(), params.target_url) :
1238 GetSiteInstance();
1240 // A message to create a new window can only come from the active process for
1241 // this WebContentsImpl instance. If any other process sends the request,
1242 // it is invalid and the process must be terminated.
1243 if (GetRenderProcessHost()->GetID() != render_process_id) {
1244 base::ProcessHandle process_handle =
1245 RenderProcessHost::FromID(render_process_id)->GetHandle();
1246 if (process_handle != base::kNullProcessHandle) {
1247 RecordAction(
1248 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWindow"));
1249 base::KillProcess(process_handle, content::RESULT_CODE_KILLED, false);
1251 return;
1254 // We must assign the SessionStorageNamespace before calling Init().
1256 // http://crbug.com/142685
1257 const std::string& partition_id =
1258 GetContentClient()->browser()->
1259 GetStoragePartitionIdForSite(GetBrowserContext(),
1260 site_instance->GetSiteURL());
1261 StoragePartition* partition = BrowserContext::GetStoragePartition(
1262 GetBrowserContext(), site_instance.get());
1263 DOMStorageContextWrapper* dom_storage_context =
1264 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
1265 SessionStorageNamespaceImpl* session_storage_namespace_impl =
1266 static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
1267 CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
1269 if (delegate_ &&
1270 !delegate_->ShouldCreateWebContents(this,
1271 route_id,
1272 params.window_container_type,
1273 params.frame_name,
1274 params.target_url,
1275 partition_id,
1276 session_storage_namespace)) {
1277 if (route_id != MSG_ROUTING_NONE &&
1278 !RenderViewHost::FromID(render_process_id, route_id)) {
1279 // If the embedder didn't create a WebContents for this route, we need to
1280 // delete the RenderView that had already been created.
1281 Send(new ViewMsg_Close(route_id));
1283 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(route_id);
1284 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(
1285 main_frame_route_id);
1286 return;
1289 // Create the new web contents. This will automatically create the new
1290 // WebContentsView. In the future, we may want to create the view separately.
1291 WebContentsImpl* new_contents =
1292 new WebContentsImpl(GetBrowserContext(),
1293 params.opener_suppressed ? NULL : this);
1295 new_contents->GetController().SetSessionStorageNamespace(
1296 partition_id,
1297 session_storage_namespace);
1298 CreateParams create_params(GetBrowserContext(), site_instance.get());
1299 create_params.routing_id = route_id;
1300 create_params.main_frame_routing_id = main_frame_route_id;
1301 if (!is_guest) {
1302 create_params.context = view_->GetNativeView();
1303 create_params.initial_size = view_->GetContainerSize();
1304 } else {
1305 // This makes |new_contents| act as a guest.
1306 // For more info, see comment above class BrowserPluginGuest.
1307 int instance_id = GetBrowserPluginGuestManager()->get_next_instance_id();
1308 WebContentsImpl* new_contents_impl =
1309 static_cast<WebContentsImpl*>(new_contents);
1310 BrowserPluginGuest::CreateWithOpener(instance_id,
1311 new_contents_impl->opener() != NULL,
1312 new_contents_impl,
1313 GetBrowserPluginGuest());
1315 if (params.disposition == NEW_BACKGROUND_TAB)
1316 create_params.initially_hidden = true;
1317 new_contents->Init(create_params);
1319 // Save the window for later if we're not suppressing the opener (since it
1320 // will be shown immediately).
1321 if (!params.opener_suppressed) {
1322 if (!is_guest) {
1323 WebContentsViewPort* new_view = new_contents->view_.get();
1325 // TODO(brettw): It seems bogus that we have to call this function on the
1326 // newly created object and give it one of its own member variables.
1327 new_view->CreateViewForWidget(new_contents->GetRenderViewHost());
1329 // Save the created window associated with the route so we can show it
1330 // later.
1331 DCHECK_NE(MSG_ROUTING_NONE, route_id);
1332 pending_contents_[route_id] = new_contents;
1333 AddDestructionObserver(new_contents);
1336 if (delegate_) {
1337 delegate_->WebContentsCreated(
1338 this, params.opener_frame_id, params.frame_name,
1339 params.target_url, new_contents);
1342 if (params.opener_suppressed) {
1343 // When the opener is suppressed, the original renderer cannot access the
1344 // new window. As a result, we need to show and navigate the window here.
1345 bool was_blocked = false;
1346 if (delegate_) {
1347 gfx::Rect initial_pos;
1348 delegate_->AddNewContents(
1349 this, new_contents, params.disposition, initial_pos,
1350 params.user_gesture, &was_blocked);
1352 if (!was_blocked) {
1353 OpenURLParams open_params(params.target_url,
1354 Referrer(),
1355 CURRENT_TAB,
1356 PAGE_TRANSITION_LINK,
1357 true /* is_renderer_initiated */);
1358 open_params.user_gesture = params.user_gesture;
1359 new_contents->OpenURL(open_params);
1364 void WebContentsImpl::CreateNewWidget(int render_process_id,
1365 int route_id,
1366 blink::WebPopupType popup_type) {
1367 CreateNewWidget(render_process_id, route_id, false, popup_type);
1370 void WebContentsImpl::CreateNewFullscreenWidget(int render_process_id,
1371 int route_id) {
1372 CreateNewWidget(render_process_id, route_id, true, blink::WebPopupTypeNone);
1375 void WebContentsImpl::CreateNewWidget(int render_process_id,
1376 int route_id,
1377 bool is_fullscreen,
1378 blink::WebPopupType popup_type) {
1379 RenderProcessHost* process = GetRenderProcessHost();
1380 // A message to create a new widget can only come from the active process for
1381 // this WebContentsImpl instance. If any other process sends the request,
1382 // it is invalid and the process must be terminated.
1383 if (process->GetID() != render_process_id) {
1384 base::ProcessHandle process_handle =
1385 RenderProcessHost::FromID(render_process_id)->GetHandle();
1386 if (process_handle != base::kNullProcessHandle) {
1387 RecordAction(
1388 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWidget"));
1389 base::KillProcess(process_handle, content::RESULT_CODE_KILLED, false);
1391 return;
1394 RenderWidgetHostImpl* widget_host =
1395 new RenderWidgetHostImpl(this, process, route_id, IsHidden());
1396 created_widgets_.insert(widget_host);
1398 RenderWidgetHostViewPort* widget_view = RenderWidgetHostViewPort::FromRWHV(
1399 view_->CreateViewForPopupWidget(widget_host));
1400 if (!widget_view)
1401 return;
1402 if (!is_fullscreen) {
1403 // Popups should not get activated.
1404 widget_view->SetPopupType(popup_type);
1406 // Save the created widget associated with the route so we can show it later.
1407 pending_widget_views_[route_id] = widget_view;
1409 #if defined(OS_MACOSX)
1410 // A RenderWidgetHostViewMac has lifetime scoped to the view. We'll retain it
1411 // to allow it to survive the trip without being hosted.
1412 base::mac::NSObjectRetain(widget_view->GetNativeView());
1413 #endif
1416 void WebContentsImpl::ShowCreatedWindow(int route_id,
1417 WindowOpenDisposition disposition,
1418 const gfx::Rect& initial_pos,
1419 bool user_gesture) {
1420 WebContentsImpl* contents = GetCreatedWindow(route_id);
1421 if (contents) {
1422 WebContentsDelegate* delegate = GetDelegate();
1423 if (delegate) {
1424 delegate->AddNewContents(
1425 this, contents, disposition, initial_pos, user_gesture, NULL);
1430 void WebContentsImpl::ShowCreatedWidget(int route_id,
1431 const gfx::Rect& initial_pos) {
1432 ShowCreatedWidget(route_id, false, initial_pos);
1435 void WebContentsImpl::ShowCreatedFullscreenWidget(int route_id) {
1436 ShowCreatedWidget(route_id, true, gfx::Rect());
1439 void WebContentsImpl::ShowCreatedWidget(int route_id,
1440 bool is_fullscreen,
1441 const gfx::Rect& initial_pos) {
1442 RenderWidgetHostViewPort* widget_host_view =
1443 RenderWidgetHostViewPort::FromRWHV(GetCreatedWidget(route_id));
1444 if (!widget_host_view)
1445 return;
1446 if (is_fullscreen) {
1447 DCHECK_EQ(MSG_ROUTING_NONE, fullscreen_widget_routing_id_);
1448 fullscreen_widget_routing_id_ = route_id;
1449 if (delegate_ && delegate_->EmbedsFullscreenWidget()) {
1450 widget_host_view->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
1451 delegate_->ToggleFullscreenModeForTab(this, true);
1452 } else {
1453 widget_host_view->InitAsFullscreen(GetRenderWidgetHostViewPort());
1455 FOR_EACH_OBSERVER(WebContentsObserver,
1456 observers_,
1457 DidShowFullscreenWidget(route_id));
1458 if (!widget_host_view->HasFocus())
1459 widget_host_view->Focus();
1460 } else {
1461 widget_host_view->InitAsPopup(GetRenderWidgetHostViewPort(), initial_pos);
1464 RenderWidgetHostImpl* render_widget_host_impl =
1465 RenderWidgetHostImpl::From(widget_host_view->GetRenderWidgetHost());
1466 render_widget_host_impl->Init();
1467 // Only allow privileged mouse lock for fullscreen render widget, which is
1468 // used to implement Pepper Flash fullscreen.
1469 render_widget_host_impl->set_allow_privileged_mouse_lock(is_fullscreen);
1471 #if defined(OS_MACOSX)
1472 // A RenderWidgetHostViewMac has lifetime scoped to the view. Now that it's
1473 // properly embedded (or purposefully ignored) we can release the retain we
1474 // took in CreateNewWidget().
1475 base::mac::NSObjectRelease(widget_host_view->GetNativeView());
1476 #endif
1479 WebContentsImpl* WebContentsImpl::GetCreatedWindow(int route_id) {
1480 PendingContents::iterator iter = pending_contents_.find(route_id);
1482 // Certain systems can block the creation of new windows. If we didn't succeed
1483 // in creating one, just return NULL.
1484 if (iter == pending_contents_.end()) {
1485 return NULL;
1488 WebContentsImpl* new_contents = iter->second;
1489 pending_contents_.erase(route_id);
1490 RemoveDestructionObserver(new_contents);
1492 // Don't initialize the guest WebContents immediately.
1493 if (new_contents->GetRenderProcessHost()->IsGuest())
1494 return new_contents;
1496 if (!new_contents->GetRenderProcessHost()->HasConnection() ||
1497 !new_contents->GetRenderViewHost()->GetView())
1498 return NULL;
1500 // TODO(brettw): It seems bogus to reach into here and initialize the host.
1501 static_cast<RenderViewHostImpl*>(new_contents->GetRenderViewHost())->Init();
1502 return new_contents;
1505 RenderWidgetHostView* WebContentsImpl::GetCreatedWidget(int route_id) {
1506 PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id);
1507 if (iter == pending_widget_views_.end()) {
1508 DCHECK(false);
1509 return NULL;
1512 RenderWidgetHostView* widget_host_view = iter->second;
1513 pending_widget_views_.erase(route_id);
1515 RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
1516 if (!widget_host->GetProcess()->HasConnection()) {
1517 // The view has gone away or the renderer crashed. Nothing to do.
1518 return NULL;
1521 return widget_host_view;
1524 void WebContentsImpl::ShowContextMenu(const ContextMenuParams& params) {
1525 // Allow WebContentsDelegates to handle the context menu operation first.
1526 if (delegate_ && delegate_->HandleContextMenu(params))
1527 return;
1529 render_view_host_delegate_view_->ShowContextMenu(params);
1532 void WebContentsImpl::RequestMediaAccessPermission(
1533 const MediaStreamRequest& request,
1534 const MediaResponseCallback& callback) {
1535 if (delegate_)
1536 delegate_->RequestMediaAccessPermission(this, request, callback);
1537 else
1538 callback.Run(MediaStreamDevices(), scoped_ptr<MediaStreamUI>());
1541 SessionStorageNamespace* WebContentsImpl::GetSessionStorageNamespace(
1542 SiteInstance* instance) {
1543 return controller_.GetSessionStorageNamespace(instance);
1546 FrameTree* WebContentsImpl::GetFrameTree() {
1547 return &frame_tree_;
1550 void WebContentsImpl::OnShowValidationMessage(
1551 const gfx::Rect& anchor_in_root_view,
1552 const base::string16& main_text,
1553 const base::string16& sub_text) {
1554 if (delegate_)
1555 delegate_->ShowValidationMessage(
1556 this, anchor_in_root_view, main_text, sub_text);
1559 void WebContentsImpl::OnHideValidationMessage() {
1560 if (delegate_)
1561 delegate_->HideValidationMessage(this);
1564 void WebContentsImpl::OnMoveValidationMessage(
1565 const gfx::Rect& anchor_in_root_view) {
1566 if (delegate_)
1567 delegate_->MoveValidationMessage(this, anchor_in_root_view);
1570 void WebContentsImpl::DidSendScreenRects(RenderWidgetHostImpl* rwh) {
1571 if (browser_plugin_embedder_)
1572 browser_plugin_embedder_->DidSendScreenRects();
1575 void WebContentsImpl::UpdatePreferredSize(const gfx::Size& pref_size) {
1576 preferred_size_ = pref_size;
1577 if (delegate_)
1578 delegate_->UpdatePreferredSize(this, pref_size);
1581 void WebContentsImpl::ResizeDueToAutoResize(const gfx::Size& new_size) {
1582 if (delegate_)
1583 delegate_->ResizeDueToAutoResize(this, new_size);
1586 WebContents* WebContentsImpl::OpenURL(const OpenURLParams& params) {
1587 if (!delegate_)
1588 return NULL;
1590 WebContents* new_contents = delegate_->OpenURLFromTab(this, params);
1591 return new_contents;
1594 bool WebContentsImpl::Send(IPC::Message* message) {
1595 if (!GetRenderViewHost()) {
1596 delete message;
1597 return false;
1600 return GetRenderViewHost()->Send(message);
1603 bool WebContentsImpl::NavigateToPendingEntry(
1604 NavigationController::ReloadType reload_type) {
1605 return frame_tree_.root()->navigator()->NavigateToPendingEntry(
1606 frame_tree_.GetMainFrame(), reload_type);
1609 void WebContentsImpl::RenderFrameForInterstitialPageCreated(
1610 RenderFrameHost* render_frame_host) {
1611 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1612 RenderFrameForInterstitialPageCreated(render_frame_host));
1615 void WebContentsImpl::AttachInterstitialPage(
1616 InterstitialPageImpl* interstitial_page) {
1617 DCHECK(interstitial_page);
1618 GetRenderManager()->set_interstitial_page(interstitial_page);
1620 // Cancel any visible dialogs so that they don't interfere with the
1621 // interstitial.
1622 if (dialog_manager_)
1623 dialog_manager_->CancelActiveAndPendingDialogs(this);
1625 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1626 DidAttachInterstitialPage());
1629 void WebContentsImpl::DetachInterstitialPage() {
1630 if (GetInterstitialPage())
1631 GetRenderManager()->remove_interstitial_page();
1632 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1633 DidDetachInterstitialPage());
1636 void WebContentsImpl::SetHistoryLengthAndPrune(
1637 const SiteInstance* site_instance,
1638 int history_length,
1639 int32 minimum_page_id) {
1640 // SetHistoryLengthAndPrune doesn't work when there are pending cross-site
1641 // navigations. Callers should ensure that this is the case.
1642 if (GetRenderManager()->pending_render_view_host()) {
1643 NOTREACHED();
1644 return;
1646 RenderViewHostImpl* rvh = GetRenderViewHostImpl();
1647 if (!rvh) {
1648 NOTREACHED();
1649 return;
1651 if (site_instance && rvh->GetSiteInstance() != site_instance) {
1652 NOTREACHED();
1653 return;
1655 Send(new ViewMsg_SetHistoryLengthAndPrune(GetRoutingID(),
1656 history_length,
1657 minimum_page_id));
1660 void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
1661 if (ShowingInterstitialPage()) {
1662 GetRenderManager()->interstitial_page()->FocusThroughTabTraversal(reverse);
1663 return;
1665 GetRenderViewHostImpl()->SetInitialFocus(reverse);
1668 bool WebContentsImpl::ShowingInterstitialPage() const {
1669 return GetRenderManager()->interstitial_page() != NULL;
1672 InterstitialPage* WebContentsImpl::GetInterstitialPage() const {
1673 return GetRenderManager()->interstitial_page();
1676 bool WebContentsImpl::IsSavable() {
1677 // WebKit creates Document object when MIME type is application/xhtml+xml,
1678 // so we also support this MIME type.
1679 return contents_mime_type_ == "text/html" ||
1680 contents_mime_type_ == "text/xml" ||
1681 contents_mime_type_ == "application/xhtml+xml" ||
1682 contents_mime_type_ == "text/plain" ||
1683 contents_mime_type_ == "text/css" ||
1684 net::IsSupportedJavascriptMimeType(contents_mime_type_.c_str());
1687 void WebContentsImpl::OnSavePage() {
1688 // If we can not save the page, try to download it.
1689 if (!IsSavable()) {
1690 RecordDownloadSource(INITIATED_BY_SAVE_PACKAGE_ON_NON_HTML);
1691 SaveFrame(GetURL(), Referrer());
1692 return;
1695 Stop();
1697 // Create the save package and possibly prompt the user for the name to save
1698 // the page as. The user prompt is an asynchronous operation that runs on
1699 // another thread.
1700 save_package_ = new SavePackage(this);
1701 save_package_->GetSaveInfo();
1704 // Used in automated testing to bypass prompting the user for file names.
1705 // Instead, the names and paths are hard coded rather than running them through
1706 // file name sanitation and extension / mime checking.
1707 bool WebContentsImpl::SavePage(const base::FilePath& main_file,
1708 const base::FilePath& dir_path,
1709 SavePageType save_type) {
1710 // Stop the page from navigating.
1711 Stop();
1713 save_package_ = new SavePackage(this, save_type, main_file, dir_path);
1714 return save_package_->Init(SavePackageDownloadCreatedCallback());
1717 void WebContentsImpl::SaveFrame(const GURL& url,
1718 const Referrer& referrer) {
1719 if (!GetURL().is_valid())
1720 return;
1721 bool is_main_frame = (url == GetURL());
1723 DownloadManager* dlm =
1724 BrowserContext::GetDownloadManager(GetBrowserContext());
1725 if (!dlm)
1726 return;
1727 int64 post_id = -1;
1728 if (is_main_frame) {
1729 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
1730 if (entry)
1731 post_id = entry->GetPostID();
1733 scoped_ptr<DownloadUrlParameters> params(
1734 DownloadUrlParameters::FromWebContents(this, url));
1735 params->set_referrer(referrer);
1736 params->set_post_id(post_id);
1737 params->set_prefer_cache(true);
1738 if (post_id >= 0)
1739 params->set_method("POST");
1740 params->set_prompt(true);
1741 dlm->DownloadUrl(params.Pass());
1744 void WebContentsImpl::GenerateMHTML(
1745 const base::FilePath& file,
1746 const base::Callback<void(int64)>& callback) {
1747 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, file, callback);
1750 // TODO(nasko): Rename this method to IsVisibleEntry.
1751 bool WebContentsImpl::IsActiveEntry(int32 page_id) {
1752 NavigationEntryImpl* visible_entry =
1753 NavigationEntryImpl::FromNavigationEntry(controller_.GetVisibleEntry());
1754 return (visible_entry != NULL &&
1755 visible_entry->site_instance() == GetSiteInstance() &&
1756 visible_entry->GetPageID() == page_id);
1759 const std::string& WebContentsImpl::GetContentsMimeType() const {
1760 return contents_mime_type_;
1763 bool WebContentsImpl::WillNotifyDisconnection() const {
1764 return notify_disconnection_;
1767 void WebContentsImpl::SetOverrideEncoding(const std::string& encoding) {
1768 SetEncoding(encoding);
1769 Send(new ViewMsg_SetPageEncoding(GetRoutingID(), encoding));
1772 void WebContentsImpl::ResetOverrideEncoding() {
1773 encoding_.clear();
1774 Send(new ViewMsg_ResetPageEncodingToDefault(GetRoutingID()));
1777 RendererPreferences* WebContentsImpl::GetMutableRendererPrefs() {
1778 return &renderer_preferences_;
1781 void WebContentsImpl::Close() {
1782 Close(GetRenderViewHost());
1785 void WebContentsImpl::DragSourceEndedAt(int client_x, int client_y,
1786 int screen_x, int screen_y, blink::WebDragOperation operation) {
1787 if (browser_plugin_embedder_.get())
1788 browser_plugin_embedder_->DragSourceEndedAt(client_x, client_y,
1789 screen_x, screen_y, operation);
1790 if (GetRenderViewHost())
1791 GetRenderViewHostImpl()->DragSourceEndedAt(client_x, client_y,
1792 screen_x, screen_y, operation);
1795 void WebContentsImpl::DragSourceMovedTo(int client_x, int client_y,
1796 int screen_x, int screen_y) {
1797 if (browser_plugin_embedder_.get())
1798 browser_plugin_embedder_->DragSourceMovedTo(client_x, client_y,
1799 screen_x, screen_y);
1800 if (GetRenderViewHost())
1801 GetRenderViewHostImpl()->DragSourceMovedTo(client_x, client_y,
1802 screen_x, screen_y);
1805 void WebContentsImpl::DidGetResourceResponseStart(
1806 const ResourceRequestDetails& details) {
1807 controller_.ssl_manager()->DidStartResourceResponse(details);
1809 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1810 DidGetResourceResponseStart(details));
1812 // TODO(avi): Remove. http://crbug.com/170921
1813 NotificationService::current()->Notify(
1814 NOTIFICATION_RESOURCE_RESPONSE_STARTED,
1815 Source<WebContents>(this),
1816 Details<const ResourceRequestDetails>(&details));
1819 void WebContentsImpl::DidGetRedirectForResourceRequest(
1820 RenderViewHost* render_view_host,
1821 const ResourceRedirectDetails& details) {
1822 controller_.ssl_manager()->DidReceiveResourceRedirect(details);
1824 FOR_EACH_OBSERVER(
1825 WebContentsObserver,
1826 observers_,
1827 DidGetRedirectForResourceRequest(render_view_host, details));
1829 // TODO(avi): Remove. http://crbug.com/170921
1830 NotificationService::current()->Notify(
1831 NOTIFICATION_RESOURCE_RECEIVED_REDIRECT,
1832 Source<WebContents>(this),
1833 Details<const ResourceRedirectDetails>(&details));
1836 void WebContentsImpl::SystemDragEnded() {
1837 if (GetRenderViewHost())
1838 GetRenderViewHostImpl()->DragSourceSystemDragEnded();
1839 if (delegate_)
1840 delegate_->DragEnded();
1841 if (browser_plugin_embedder_.get())
1842 browser_plugin_embedder_->SystemDragEnded();
1845 void WebContentsImpl::UserGestureDone() {
1846 OnUserGesture();
1849 void WebContentsImpl::SetClosedByUserGesture(bool value) {
1850 closed_by_user_gesture_ = value;
1853 bool WebContentsImpl::GetClosedByUserGesture() const {
1854 return closed_by_user_gesture_;
1857 double WebContentsImpl::GetZoomLevel() const {
1858 HostZoomMapImpl* zoom_map = static_cast<HostZoomMapImpl*>(
1859 HostZoomMap::GetForBrowserContext(GetBrowserContext()));
1860 if (!zoom_map)
1861 return 0;
1863 double zoom_level;
1864 if (temporary_zoom_settings_) {
1865 zoom_level = zoom_map->GetTemporaryZoomLevel(
1866 GetRenderProcessHost()->GetID(), GetRenderViewHost()->GetRoutingID());
1867 } else {
1868 GURL url;
1869 NavigationEntry* entry = GetController().GetLastCommittedEntry();
1870 // Since zoom map is updated using rewritten URL, use rewritten URL
1871 // to get the zoom level.
1872 url = entry ? entry->GetURL() : GURL::EmptyGURL();
1873 zoom_level = zoom_map->GetZoomLevelForHostAndScheme(url.scheme(),
1874 net::GetHostOrSpecFromURL(url));
1876 return zoom_level;
1879 int WebContentsImpl::GetZoomPercent(bool* enable_increment,
1880 bool* enable_decrement) const {
1881 *enable_decrement = *enable_increment = false;
1882 // Calculate the zoom percent from the factor. Round up to the nearest whole
1883 // number.
1884 int percent = static_cast<int>(
1885 ZoomLevelToZoomFactor(GetZoomLevel()) * 100 + 0.5);
1886 *enable_decrement = percent > minimum_zoom_percent_;
1887 *enable_increment = percent < maximum_zoom_percent_;
1888 return percent;
1891 void WebContentsImpl::ViewSource() {
1892 if (!delegate_)
1893 return;
1895 NavigationEntry* entry = GetController().GetLastCommittedEntry();
1896 if (!entry)
1897 return;
1899 delegate_->ViewSourceForTab(this, entry->GetURL());
1902 void WebContentsImpl::ViewFrameSource(const GURL& url,
1903 const PageState& page_state) {
1904 if (!delegate_)
1905 return;
1907 delegate_->ViewSourceForFrame(this, url, page_state);
1910 int WebContentsImpl::GetMinimumZoomPercent() const {
1911 return minimum_zoom_percent_;
1914 int WebContentsImpl::GetMaximumZoomPercent() const {
1915 return maximum_zoom_percent_;
1918 gfx::Size WebContentsImpl::GetPreferredSize() const {
1919 return preferred_size_;
1922 bool WebContentsImpl::GotResponseToLockMouseRequest(bool allowed) {
1923 return GetRenderViewHost() ?
1924 GetRenderViewHostImpl()->GotResponseToLockMouseRequest(allowed) : false;
1927 bool WebContentsImpl::HasOpener() const {
1928 return opener_ != NULL;
1931 void WebContentsImpl::DidChooseColorInColorChooser(SkColor color) {
1932 Send(new ViewMsg_DidChooseColorResponse(
1933 GetRoutingID(), color_chooser_identifier_, color));
1936 void WebContentsImpl::DidEndColorChooser() {
1937 Send(new ViewMsg_DidEndColorChooser(GetRoutingID(),
1938 color_chooser_identifier_));
1939 color_chooser_.reset();
1940 color_chooser_identifier_ = 0;
1943 int WebContentsImpl::DownloadImage(const GURL& url,
1944 bool is_favicon,
1945 uint32_t max_bitmap_size,
1946 const ImageDownloadCallback& callback) {
1947 RenderViewHost* host = GetRenderViewHost();
1948 int id = StartDownload(host, url, is_favicon, max_bitmap_size);
1949 image_download_map_[id] = callback;
1950 return id;
1953 bool WebContentsImpl::IsSubframe() const {
1954 return is_subframe_;
1957 void WebContentsImpl::SetZoomLevel(double level) {
1958 Send(new ViewMsg_SetZoomLevel(GetRoutingID(), level));
1959 BrowserPluginEmbedder* embedder = GetBrowserPluginEmbedder();
1960 if (embedder)
1961 embedder->SetZoomLevel(level);
1964 void WebContentsImpl::Find(int request_id,
1965 const base::string16& search_text,
1966 const blink::WebFindOptions& options) {
1967 Send(new ViewMsg_Find(GetRoutingID(), request_id, search_text, options));
1970 void WebContentsImpl::StopFinding(StopFindAction action) {
1971 Send(new ViewMsg_StopFinding(GetRoutingID(), action));
1974 bool WebContentsImpl::FocusLocationBarByDefault() {
1975 NavigationEntry* entry = controller_.GetVisibleEntry();
1976 if (entry && entry->GetURL() == GURL(kAboutBlankURL))
1977 return true;
1978 return delegate_ && delegate_->ShouldFocusLocationBarByDefault(this);
1981 void WebContentsImpl::SetFocusToLocationBar(bool select_all) {
1982 if (delegate_)
1983 delegate_->SetFocusToLocationBar(select_all);
1986 void WebContentsImpl::DidStartProvisionalLoad(
1987 RenderFrameHostImpl* render_frame_host,
1988 int64 frame_id,
1989 int64 parent_frame_id,
1990 bool is_main_frame,
1991 const GURL& validated_url,
1992 bool is_error_page,
1993 bool is_iframe_srcdoc) {
1994 if (is_main_frame)
1995 DidChangeLoadProgress(0);
1997 // Notify observers about the start of the provisional load.
1998 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1999 DidStartProvisionalLoadForFrame(frame_id, parent_frame_id,
2000 is_main_frame, validated_url, is_error_page,
2001 is_iframe_srcdoc, render_frame_host->render_view_host()));
2003 if (is_main_frame) {
2004 FOR_EACH_OBSERVER(
2005 WebContentsObserver,
2006 observers_,
2007 ProvisionalChangeToMainFrameUrl(validated_url,
2008 render_frame_host));
2012 void WebContentsImpl::DidFailProvisionalLoadWithError(
2013 RenderFrameHostImpl* render_frame_host,
2014 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
2015 GURL validated_url(params.url);
2016 FOR_EACH_OBSERVER(
2017 WebContentsObserver,
2018 observers_,
2019 DidFailProvisionalLoad(params.frame_id,
2020 params.frame_unique_name,
2021 params.is_main_frame,
2022 validated_url,
2023 params.error_code,
2024 params.error_description,
2025 render_frame_host->render_view_host()));
2028 void WebContentsImpl::NotifyChangedNavigationState(
2029 InvalidateTypes changed_flags) {
2030 NotifyNavigationStateChanged(changed_flags);
2033 void WebContentsImpl::AboutToNavigateRenderFrame(
2034 RenderFrameHostImpl* render_frame_host) {
2035 // Notify observers that we will navigate in this RenderView.
2036 FOR_EACH_OBSERVER(
2037 WebContentsObserver,
2038 observers_,
2039 AboutToNavigateRenderView(render_frame_host->render_view_host()));
2042 void WebContentsImpl::DidStartNavigationToPendingEntry(
2043 RenderFrameHostImpl* render_frame_host,
2044 const GURL& url,
2045 NavigationController::ReloadType reload_type) {
2046 // Notify observers about navigation.
2047 FOR_EACH_OBSERVER(
2048 WebContentsObserver,
2049 observers_,
2050 DidStartNavigationToPendingEntry(url, reload_type));
2053 void WebContentsImpl::DidRedirectProvisionalLoad(
2054 RenderFrameHostImpl* render_frame_host,
2055 const GURL& validated_target_url) {
2056 // Notify observers about the provisional change in the main frame URL.
2057 FOR_EACH_OBSERVER(
2058 WebContentsObserver,
2059 observers_,
2060 ProvisionalChangeToMainFrameUrl(validated_target_url,
2061 render_frame_host));
2064 void WebContentsImpl::OnDidLoadResourceFromMemoryCache(
2065 const GURL& url,
2066 const std::string& security_info,
2067 const std::string& http_method,
2068 const std::string& mime_type,
2069 ResourceType::Type resource_type) {
2070 base::StatsCounter cache("WebKit.CacheHit");
2071 cache.Increment();
2073 // Send out a notification that we loaded a resource from our memory cache.
2074 int cert_id = 0;
2075 net::CertStatus cert_status = 0;
2076 int security_bits = -1;
2077 int connection_status = 0;
2078 SignedCertificateTimestampIDStatusList signed_certificate_timestamp_ids;
2079 DeserializeSecurityInfo(security_info, &cert_id, &cert_status,
2080 &security_bits, &connection_status,
2081 &signed_certificate_timestamp_ids);
2082 // TODO(alcutter,eranm): Pass signed_certificate_timestamp_ids into details
2083 LoadFromMemoryCacheDetails details(
2084 url, GetRenderProcessHost()->GetID(), cert_id, cert_status, http_method,
2085 mime_type, resource_type);
2087 controller_.ssl_manager()->DidLoadFromMemoryCache(details);
2089 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2090 DidLoadResourceFromMemoryCache(details));
2092 if (url.is_valid() && url.SchemeIsHTTPOrHTTPS()) {
2093 scoped_refptr<net::URLRequestContextGetter> request_context(
2094 resource_type == ResourceType::MEDIA ?
2095 GetBrowserContext()->GetMediaRequestContextForRenderProcess(
2096 GetRenderProcessHost()->GetID()) :
2097 GetBrowserContext()->GetRequestContextForRenderProcess(
2098 GetRenderProcessHost()->GetID()));
2099 BrowserThread::PostTask(
2100 BrowserThread::IO,
2101 FROM_HERE,
2102 base::Bind(&NotifyCacheOnIO, request_context, url, http_method));
2106 void WebContentsImpl::OnDidDisplayInsecureContent() {
2107 RecordAction(base::UserMetricsAction("SSL.DisplayedInsecureContent"));
2108 displayed_insecure_content_ = true;
2109 SSLManager::NotifySSLInternalStateChanged(
2110 GetController().GetBrowserContext());
2113 void WebContentsImpl::OnDidRunInsecureContent(
2114 const std::string& security_origin, const GURL& target_url) {
2115 LOG(WARNING) << security_origin << " ran insecure content from "
2116 << target_url.possibly_invalid_spec();
2117 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
2118 if (EndsWith(security_origin, kDotGoogleDotCom, false))
2119 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
2120 controller_.ssl_manager()->DidRunInsecureContent(security_origin);
2121 displayed_insecure_content_ = true;
2122 SSLManager::NotifySSLInternalStateChanged(
2123 GetController().GetBrowserContext());
2126 void WebContentsImpl::OnDocumentLoadedInFrame(int64 frame_id) {
2127 FOR_EACH_OBSERVER(
2128 WebContentsObserver, observers_,
2129 DocumentLoadedInFrame(frame_id, render_view_message_source_));
2132 void WebContentsImpl::OnDidFinishLoad(
2133 int64 frame_id,
2134 const GURL& url,
2135 bool is_main_frame) {
2136 GURL validated_url(url);
2138 // --site-per-process mode has a short-term hack allowing cross-process
2139 // subframe pages to commit thinking they are top-level. Correct it here to
2140 // avoid confusing the observers.
2141 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess) &&
2142 render_view_message_source_ != GetRenderViewHost())
2143 is_main_frame = false;
2145 RenderProcessHost* render_process_host =
2146 render_view_message_source_->GetProcess();
2147 render_process_host->FilterURL(false, &validated_url);
2148 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2149 DidFinishLoad(frame_id, validated_url, is_main_frame,
2150 render_view_message_source_));
2153 void WebContentsImpl::OnDidFailLoadWithError(
2154 int64 frame_id,
2155 const GURL& url,
2156 bool is_main_frame,
2157 int error_code,
2158 const base::string16& error_description) {
2159 GURL validated_url(url);
2160 RenderProcessHost* render_process_host =
2161 render_view_message_source_->GetProcess();
2162 render_process_host->FilterURL(false, &validated_url);
2163 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2164 DidFailLoad(frame_id, validated_url, is_main_frame,
2165 error_code, error_description,
2166 render_view_message_source_));
2169 void WebContentsImpl::OnGoToEntryAtOffset(int offset) {
2170 if (!delegate_ || delegate_->OnGoToEntryOffset(offset)) {
2171 NavigationEntryImpl* entry = NavigationEntryImpl::FromNavigationEntry(
2172 controller_.GetEntryAtOffset(offset));
2173 if (!entry)
2174 return;
2175 // Note that we don't call NavigationController::GotToOffset() as we don't
2176 // want to create a pending navigation entry (it might end up lingering
2177 // http://crbug.com/51680).
2178 entry->SetTransitionType(
2179 PageTransitionFromInt(
2180 entry->GetTransitionType() |
2181 PAGE_TRANSITION_FORWARD_BACK));
2182 frame_tree_.root()->navigator()->NavigateToEntry(
2183 frame_tree_.GetMainFrame(),
2184 *entry,
2185 NavigationControllerImpl::NO_RELOAD);
2187 // If the entry is being restored and doesn't have a SiteInstance yet, fill
2188 // it in now that we know. This allows us to find the entry when it commits.
2189 if (!entry->site_instance() &&
2190 entry->restore_type() != NavigationEntryImpl::RESTORE_NONE) {
2191 entry->set_site_instance(
2192 static_cast<SiteInstanceImpl*>(GetPendingSiteInstance()));
2197 void WebContentsImpl::OnUpdateZoomLimits(int minimum_percent,
2198 int maximum_percent,
2199 bool remember) {
2200 minimum_zoom_percent_ = minimum_percent;
2201 maximum_zoom_percent_ = maximum_percent;
2202 temporary_zoom_settings_ = !remember;
2205 void WebContentsImpl::OnEnumerateDirectory(int request_id,
2206 const base::FilePath& path) {
2207 if (!delegate_)
2208 return;
2210 ChildProcessSecurityPolicyImpl* policy =
2211 ChildProcessSecurityPolicyImpl::GetInstance();
2212 if (policy->CanReadFile(GetRenderProcessHost()->GetID(), path))
2213 delegate_->EnumerateDirectory(this, request_id, path);
2216 void WebContentsImpl::OnJSOutOfMemory() {
2217 if (delegate_)
2218 delegate_->JSOutOfMemory(this);
2221 void WebContentsImpl::OnRegisterProtocolHandler(const std::string& protocol,
2222 const GURL& url,
2223 const base::string16& title,
2224 bool user_gesture) {
2225 if (!delegate_)
2226 return;
2228 ChildProcessSecurityPolicyImpl* policy =
2229 ChildProcessSecurityPolicyImpl::GetInstance();
2230 if (policy->IsPseudoScheme(protocol))
2231 return;
2233 delegate_->RegisterProtocolHandler(this, protocol, url, title, user_gesture);
2236 void WebContentsImpl::OnFindReply(int request_id,
2237 int number_of_matches,
2238 const gfx::Rect& selection_rect,
2239 int active_match_ordinal,
2240 bool final_update) {
2241 if (delegate_) {
2242 delegate_->FindReply(this, request_id, number_of_matches, selection_rect,
2243 active_match_ordinal, final_update);
2247 #if defined(OS_ANDROID)
2248 void WebContentsImpl::OnFindMatchRectsReply(
2249 int version,
2250 const std::vector<gfx::RectF>& rects,
2251 const gfx::RectF& active_rect) {
2252 if (delegate_)
2253 delegate_->FindMatchRectsReply(this, version, rects, active_rect);
2256 void WebContentsImpl::OnOpenDateTimeDialog(
2257 const ViewHostMsg_DateTimeDialogValue_Params& value) {
2258 date_time_chooser_->ShowDialog(ContentViewCore::FromWebContents(this),
2259 GetRenderViewHost(),
2260 value.dialog_type,
2261 value.dialog_value,
2262 value.minimum,
2263 value.maximum,
2264 value.step,
2265 value.suggestions);
2268 void WebContentsImpl::OnJavaBridgeGetChannelHandle(IPC::Message* reply_msg) {
2269 java_bridge_dispatcher_host_manager_->OnGetChannelHandle(
2270 render_view_message_source_, reply_msg);
2273 #endif
2275 void WebContentsImpl::OnPepperPluginHung(int plugin_child_id,
2276 const base::FilePath& path,
2277 bool is_hung) {
2278 UMA_HISTOGRAM_COUNTS("Pepper.PluginHung", 1);
2280 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2281 PluginHungStatusChanged(plugin_child_id, path, is_hung));
2284 void WebContentsImpl::OnPluginCrashed(const base::FilePath& plugin_path,
2285 base::ProcessId plugin_pid) {
2286 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2287 PluginCrashed(plugin_path, plugin_pid));
2290 void WebContentsImpl::OnAppCacheAccessed(const GURL& manifest_url,
2291 bool blocked_by_policy) {
2292 // Notify observers about navigation.
2293 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2294 AppCacheAccessed(manifest_url, blocked_by_policy));
2297 void WebContentsImpl::OnOpenColorChooser(
2298 int color_chooser_id,
2299 SkColor color,
2300 const std::vector<ColorSuggestion>& suggestions) {
2301 ColorChooser* new_color_chooser =
2302 delegate_->OpenColorChooser(this, color, suggestions);
2303 if (!new_color_chooser)
2304 return;
2305 if (color_chooser_)
2306 color_chooser_->End();
2307 color_chooser_.reset(new_color_chooser);
2308 color_chooser_identifier_ = color_chooser_id;
2311 void WebContentsImpl::OnEndColorChooser(int color_chooser_id) {
2312 if (color_chooser_ &&
2313 color_chooser_id == color_chooser_identifier_)
2314 color_chooser_->End();
2317 void WebContentsImpl::OnSetSelectedColorInColorChooser(int color_chooser_id,
2318 SkColor color) {
2319 if (color_chooser_ &&
2320 color_chooser_id == color_chooser_identifier_)
2321 color_chooser_->SetSelectedColor(color);
2324 // This exists for render views that don't have a WebUI, but do have WebUI
2325 // bindings enabled.
2326 void WebContentsImpl::OnWebUISend(const GURL& source_url,
2327 const std::string& name,
2328 const base::ListValue& args) {
2329 if (delegate_)
2330 delegate_->WebUISend(this, source_url, name, args);
2333 void WebContentsImpl::OnRequestPpapiBrokerPermission(
2334 int routing_id,
2335 const GURL& url,
2336 const base::FilePath& plugin_path) {
2337 if (!delegate_) {
2338 OnPpapiBrokerPermissionResult(routing_id, false);
2339 return;
2342 if (!delegate_->RequestPpapiBrokerPermission(
2343 this, url, plugin_path,
2344 base::Bind(&WebContentsImpl::OnPpapiBrokerPermissionResult,
2345 base::Unretained(this), routing_id))) {
2346 NOTIMPLEMENTED();
2347 OnPpapiBrokerPermissionResult(routing_id, false);
2351 void WebContentsImpl::OnPpapiBrokerPermissionResult(int routing_id,
2352 bool result) {
2353 Send(new ViewMsg_PpapiBrokerPermissionResult(routing_id, result));
2356 void WebContentsImpl::OnBrowserPluginMessage(const IPC::Message& message) {
2357 // This creates a BrowserPluginEmbedder, which handles all the BrowserPlugin
2358 // specific messages for this WebContents. This means that any message from
2359 // a BrowserPlugin prior to this will be ignored.
2360 // For more info, see comment above classes BrowserPluginEmbedder and
2361 // BrowserPluginGuest.
2362 CHECK(!browser_plugin_embedder_.get());
2363 browser_plugin_embedder_.reset(BrowserPluginEmbedder::Create(this));
2364 browser_plugin_embedder_->OnMessageReceived(message);
2367 void WebContentsImpl::OnDidDownloadImage(
2368 int id,
2369 int http_status_code,
2370 const GURL& image_url,
2371 const std::vector<SkBitmap>& bitmaps,
2372 const std::vector<gfx::Size>& original_bitmap_sizes) {
2373 if (bitmaps.size() != original_bitmap_sizes.size())
2374 return;
2376 ImageDownloadMap::iterator iter = image_download_map_.find(id);
2377 if (iter == image_download_map_.end()) {
2378 // Currently WebContents notifies us of ANY downloads so that it is
2379 // possible to get here.
2380 return;
2382 if (!iter->second.is_null()) {
2383 iter->second.Run(
2384 id, http_status_code, image_url, bitmaps, original_bitmap_sizes);
2386 image_download_map_.erase(id);
2389 void WebContentsImpl::OnUpdateFaviconURL(
2390 int32 page_id,
2391 const std::vector<FaviconURL>& candidates) {
2392 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2393 DidUpdateFaviconURL(page_id, candidates));
2396 void WebContentsImpl::OnMediaNotification(int64 player_cookie,
2397 bool has_video,
2398 bool has_audio,
2399 bool is_playing) {
2400 // Chrome OS does its own detection of audio and video.
2401 #if !defined(OS_CHROMEOS)
2402 if (is_playing) {
2403 scoped_ptr<PowerSaveBlocker> blocker;
2404 if (has_video) {
2405 blocker = PowerSaveBlocker::Create(
2406 PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep,
2407 "Playing video");
2408 #if defined(OS_ANDROID)
2409 static_cast<PowerSaveBlockerImpl*>(blocker.get())->
2410 InitDisplaySleepBlocker(GetView()->GetNativeView());
2411 #endif
2412 } else if (has_audio) {
2413 blocker = PowerSaveBlocker::Create(
2414 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension,
2415 "Playing audio");
2418 if (blocker) {
2419 power_save_blockers_[render_view_message_source_][player_cookie] =
2420 blocker.release();
2422 } else {
2423 delete power_save_blockers_[render_view_message_source_][player_cookie];
2424 power_save_blockers_[render_view_message_source_].erase(player_cookie);
2426 #endif // !defined(OS_CHROMEOS)
2429 void WebContentsImpl::OnFirstVisuallyNonEmptyPaint(int32 page_id) {
2430 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2431 DidFirstVisuallyNonEmptyPaint(page_id));
2434 void WebContentsImpl::DidChangeVisibleSSLState() {
2435 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2436 DidChangeVisibleSSLState());
2439 void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
2440 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2441 BeforeFormRepostWarningShow());
2445 void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
2446 Activate();
2447 if (delegate_)
2448 delegate_->ShowRepostFormWarningDialog(this);
2451 // Notifies the RenderWidgetHost instance about the fact that the page is
2452 // loading, or done loading.
2453 void WebContentsImpl::SetIsLoading(RenderViewHost* render_view_host,
2454 bool is_loading,
2455 LoadNotificationDetails* details) {
2456 if (is_loading == is_loading_)
2457 return;
2459 if (!is_loading) {
2460 load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
2461 base::string16());
2462 load_state_host_.clear();
2463 upload_size_ = 0;
2464 upload_position_ = 0;
2467 GetRenderManager()->SetIsLoading(is_loading);
2469 is_loading_ = is_loading;
2470 waiting_for_response_ = is_loading;
2472 if (delegate_)
2473 delegate_->LoadingStateChanged(this);
2474 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
2476 std::string url = (details ? details->url.possibly_invalid_spec() : "NULL");
2477 if (is_loading) {
2478 TRACE_EVENT_ASYNC_BEGIN1("browser", "WebContentsImpl Loading", this,
2479 "URL", url);
2480 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2481 DidStartLoading(render_view_host));
2482 } else {
2483 TRACE_EVENT_ASYNC_END1("browser", "WebContentsImpl Loading", this,
2484 "URL", url);
2485 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2486 DidStopLoading(render_view_host));
2489 // TODO(avi): Remove. http://crbug.com/170921
2490 int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
2491 NotificationDetails det = NotificationService::NoDetails();
2492 if (details)
2493 det = Details<LoadNotificationDetails>(details);
2494 NotificationService::current()->Notify(
2495 type, Source<NavigationController>(&controller_), det);
2498 void WebContentsImpl::DidNavigateMainFramePostCommit(
2499 const LoadCommittedDetails& details,
2500 const ViewHostMsg_FrameNavigate_Params& params) {
2501 if (details.is_navigation_to_different_page()) {
2502 // Clear the status bubble. This is a workaround for a bug where WebKit
2503 // doesn't let us know that the cursor left an element during a
2504 // transition (this is also why the mouse cursor remains as a hand after
2505 // clicking on a link); see bugs 1184641 and 980803. We don't want to
2506 // clear the bubble when a user navigates to a named anchor in the same
2507 // page.
2508 UpdateTargetURL(details.entry->GetPageID(), GURL());
2511 if (!details.is_in_page) {
2512 // Once the main frame is navigated, we're no longer considered to have
2513 // displayed insecure content.
2514 displayed_insecure_content_ = false;
2515 SSLManager::NotifySSLInternalStateChanged(
2516 GetController().GetBrowserContext());
2519 // Notify observers about navigation.
2520 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2521 DidNavigateMainFrame(details, params));
2524 void WebContentsImpl::DidNavigateAnyFramePostCommit(
2525 RenderViewHost* render_view_host,
2526 const LoadCommittedDetails& details,
2527 const ViewHostMsg_FrameNavigate_Params& params) {
2528 // If we navigate off the page, close all JavaScript dialogs.
2529 if (dialog_manager_ && !details.is_in_page)
2530 dialog_manager_->CancelActiveAndPendingDialogs(this);
2532 // Notify observers about navigation.
2533 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2534 DidNavigateAnyFrame(details, params));
2537 bool WebContentsImpl::ShouldAssignSiteForURL(const GURL& url) {
2538 // about:blank should not "use up" a new SiteInstance. The SiteInstance can
2539 // still be used for a normal web site.
2540 if (url == GURL(kAboutBlankURL))
2541 return false;
2543 // The embedder will then have the opportunity to determine if the URL
2544 // should "use up" the SiteInstance.
2545 return GetContentClient()->browser()->ShouldAssignSiteForURL(url);
2548 void WebContentsImpl::UpdateMaxPageIDIfNecessary(RenderViewHost* rvh) {
2549 // If we are creating a RVH for a restored controller, then we need to make
2550 // sure the RenderView starts with a next_page_id_ larger than the number
2551 // of restored entries. This must be called before the RenderView starts
2552 // navigating (to avoid a race between the browser updating max_page_id and
2553 // the renderer updating next_page_id_). Because of this, we only call this
2554 // from CreateRenderView and allow that to notify the RenderView for us.
2555 int max_restored_page_id = controller_.GetMaxRestoredPageID();
2556 if (max_restored_page_id >
2557 GetMaxPageIDForSiteInstance(rvh->GetSiteInstance()))
2558 UpdateMaxPageIDForSiteInstance(rvh->GetSiteInstance(),
2559 max_restored_page_id);
2562 bool WebContentsImpl::UpdateTitleForEntry(NavigationEntryImpl* entry,
2563 const base::string16& title) {
2564 // For file URLs without a title, use the pathname instead. In the case of a
2565 // synthesized title, we don't want the update to count toward the "one set
2566 // per page of the title to history."
2567 base::string16 final_title;
2568 bool explicit_set;
2569 if (entry && entry->GetURL().SchemeIsFile() && title.empty()) {
2570 final_title = base::UTF8ToUTF16(entry->GetURL().ExtractFileName());
2571 explicit_set = false; // Don't count synthetic titles toward the set limit.
2572 } else {
2573 TrimWhitespace(title, TRIM_ALL, &final_title);
2574 explicit_set = true;
2577 // If a page is created via window.open and never navigated,
2578 // there will be no navigation entry. In this situation,
2579 // |page_title_when_no_navigation_entry_| will be used for page title.
2580 if (entry) {
2581 if (final_title == entry->GetTitle())
2582 return false; // Nothing changed, don't bother.
2584 entry->SetTitle(final_title);
2585 } else {
2586 if (page_title_when_no_navigation_entry_ == final_title)
2587 return false; // Nothing changed, don't bother.
2589 page_title_when_no_navigation_entry_ = final_title;
2592 // Lastly, set the title for the view.
2593 view_->SetPageTitle(final_title);
2595 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2596 TitleWasSet(entry, explicit_set));
2598 // TODO(avi): Remove. http://crbug.com/170921
2599 std::pair<NavigationEntry*, bool> details =
2600 std::make_pair(entry, explicit_set);
2601 NotificationService::current()->Notify(
2602 NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED,
2603 Source<WebContents>(this),
2604 Details<std::pair<NavigationEntry*, bool> >(&details));
2606 return true;
2609 void WebContentsImpl::NotifySwapped(RenderViewHost* old_host,
2610 RenderViewHost* new_host) {
2611 // After sending out a swap notification, we need to send a disconnect
2612 // notification so that clients that pick up a pointer to |this| can NULL the
2613 // pointer. See Bug 1230284.
2614 notify_disconnection_ = true;
2615 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2616 RenderViewHostChanged(old_host, new_host));
2618 // TODO(avi): Remove. http://crbug.com/170921
2619 std::pair<RenderViewHost*, RenderViewHost*> details =
2620 std::make_pair(old_host, new_host);
2621 NotificationService::current()->Notify(
2622 NOTIFICATION_RENDER_VIEW_HOST_CHANGED,
2623 Source<WebContents>(this),
2624 Details<std::pair<RenderViewHost*, RenderViewHost*> >(&details));
2626 // Ensure that the associated embedder gets cleared after a RenderViewHost
2627 // gets swapped, so we don't reuse the same embedder next time a
2628 // RenderViewHost is attached to this WebContents.
2629 RemoveBrowserPluginEmbedder();
2632 // TODO(avi): Remove this entire function because this notification is already
2633 // covered by two observer functions. http://crbug.com/170921
2634 void WebContentsImpl::NotifyDisconnected() {
2635 if (!notify_disconnection_)
2636 return;
2638 notify_disconnection_ = false;
2639 NotificationService::current()->Notify(
2640 NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
2641 Source<WebContents>(this),
2642 NotificationService::NoDetails());
2645 void WebContentsImpl::NotifyNavigationEntryCommitted(
2646 const LoadCommittedDetails& load_details) {
2647 FOR_EACH_OBSERVER(
2648 WebContentsObserver, observers_, NavigationEntryCommitted(load_details));
2651 bool WebContentsImpl::OnMessageReceived(RenderFrameHost* render_frame_host,
2652 const IPC::Message& message) {
2653 return OnMessageReceived(NULL, render_frame_host, message);
2656 void WebContentsImpl::RenderFrameCreated(RenderFrameHost* render_frame_host) {
2657 // Note this is only for subframes, the notification for the main frame
2658 // happens in RenderViewCreated.
2659 FOR_EACH_OBSERVER(WebContentsObserver,
2660 observers_,
2661 RenderFrameCreated(render_frame_host));
2664 void WebContentsImpl::RenderFrameDeleted(RenderFrameHost* render_frame_host) {
2665 FOR_EACH_OBSERVER(WebContentsObserver,
2666 observers_,
2667 RenderFrameDeleted(render_frame_host));
2670 void WebContentsImpl::WorkerCrashed() {
2671 if (delegate_)
2672 delegate_->WorkerCrashed(this);
2675 WebContents* WebContentsImpl::GetAsWebContents() {
2676 return this;
2679 RenderViewHostDelegateView* WebContentsImpl::GetDelegateView() {
2680 return render_view_host_delegate_view_;
2683 RenderViewHostDelegate::RendererManagement*
2684 WebContentsImpl::GetRendererManagementDelegate() {
2685 return GetRenderManager();
2688 RendererPreferences WebContentsImpl::GetRendererPrefs(
2689 BrowserContext* browser_context) const {
2690 return renderer_preferences_;
2693 gfx::Rect WebContentsImpl::GetRootWindowResizerRect() const {
2694 if (delegate_)
2695 return delegate_->GetRootWindowResizerRect();
2696 return gfx::Rect();
2699 void WebContentsImpl::RemoveBrowserPluginEmbedder() {
2700 if (browser_plugin_embedder_)
2701 browser_plugin_embedder_.reset();
2704 void WebContentsImpl::RenderViewCreated(RenderViewHost* render_view_host) {
2705 // Don't send notifications if we are just creating a swapped-out RVH for
2706 // the opener chain. These won't be used for view-source or WebUI, so it's
2707 // ok to return early.
2708 if (static_cast<RenderViewHostImpl*>(render_view_host)->is_swapped_out())
2709 return;
2711 if (delegate_)
2712 view_->SetOverscrollControllerEnabled(delegate_->CanOverscrollContent());
2714 NotificationService::current()->Notify(
2715 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
2716 Source<WebContents>(this),
2717 Details<RenderViewHost>(render_view_host));
2719 // When we're creating views, we're still doing initial setup, so we always
2720 // use the pending Web UI rather than any possibly existing committed one.
2721 if (GetRenderManager()->pending_web_ui())
2722 GetRenderManager()->pending_web_ui()->RenderViewCreated(render_view_host);
2724 NavigationEntry* entry = controller_.GetPendingEntry();
2725 if (entry && entry->IsViewSourceMode()) {
2726 // Put the renderer in view source mode.
2727 render_view_host->Send(
2728 new ViewMsg_EnableViewSourceMode(render_view_host->GetRoutingID()));
2731 view_->RenderViewCreated(render_view_host);
2733 FOR_EACH_OBSERVER(
2734 WebContentsObserver, observers_, RenderViewCreated(render_view_host));
2736 // We tell the observers now instead of when the main RenderFrameHostImpl is
2737 // constructed because otherwise it would be too early (i.e. IPCs sent to the
2738 // frame would be dropped because it's not created yet).
2739 RenderFrameHost* main_frame = GetMainFrame();
2740 FOR_EACH_OBSERVER(
2741 WebContentsObserver, observers_, RenderFrameCreated(main_frame));
2744 void WebContentsImpl::RenderViewReady(RenderViewHost* rvh) {
2745 if (rvh != GetRenderViewHost()) {
2746 // Don't notify the world, since this came from a renderer in the
2747 // background.
2748 return;
2751 notify_disconnection_ = true;
2752 // TODO(avi): Remove. http://crbug.com/170921
2753 NotificationService::current()->Notify(
2754 NOTIFICATION_WEB_CONTENTS_CONNECTED,
2755 Source<WebContents>(this),
2756 NotificationService::NoDetails());
2758 bool was_crashed = IsCrashed();
2759 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
2761 // Restore the focus to the tab (otherwise the focus will be on the top
2762 // window).
2763 if (was_crashed && !FocusLocationBarByDefault() &&
2764 (!delegate_ || delegate_->ShouldFocusPageAfterCrash())) {
2765 view_->Focus();
2768 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewReady());
2771 void WebContentsImpl::RenderViewTerminated(RenderViewHost* rvh,
2772 base::TerminationStatus status,
2773 int error_code) {
2774 if (rvh != GetRenderViewHost()) {
2775 // The pending page's RenderViewHost is gone.
2776 return;
2779 ClearPowerSaveBlockers(rvh);
2780 SetIsLoading(rvh, false, NULL);
2781 NotifyDisconnected();
2782 SetIsCrashed(status, error_code);
2783 GetView()->OnTabCrashed(GetCrashedStatus(), crashed_error_code_);
2785 FOR_EACH_OBSERVER(WebContentsObserver,
2786 observers_,
2787 RenderProcessGone(GetCrashedStatus()));
2790 void WebContentsImpl::RenderViewDeleted(RenderViewHost* rvh) {
2791 ClearPowerSaveBlockers(rvh);
2792 GetRenderManager()->RenderViewDeleted(rvh);
2793 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewDeleted(rvh));
2796 void WebContentsImpl::DidNavigate(
2797 RenderViewHost* rvh,
2798 const ViewHostMsg_FrameNavigate_Params& orig_params) {
2799 ViewHostMsg_FrameNavigate_Params params(orig_params);
2800 bool use_site_per_process =
2801 CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess);
2802 if (frame_tree_.IsFirstNavigationAfterSwap()) {
2803 // First navigation should be a main frame navigation.
2804 // TODO(creis): This DCHECK is currently disabled for --site-per-process
2805 // because cross-process subframe navigations still have a main frame
2806 // PageTransition.
2807 if (!use_site_per_process)
2808 DCHECK(PageTransitionIsMainFrame(params.transition));
2809 frame_tree_.OnFirstNavigationAfterSwap(params.frame_id);
2812 // When using --site-per-process, look up the FrameTreeNode ID that the
2813 // renderer-specific frame ID corresponds to.
2814 int64 frame_tree_node_id = frame_tree_.root()->frame_tree_node_id();
2815 if (use_site_per_process) {
2816 FrameTreeNode* source_node = frame_tree_.FindByFrameID(params.frame_id);
2817 if (source_node)
2818 frame_tree_node_id = source_node->frame_tree_node_id();
2820 // TODO(creis): In the short term, cross-process subframe navigations are
2821 // happening in the pending RenderViewHost's top-level frame. (We need to
2822 // both mirror the frame tree and get the navigation to occur in the correct
2823 // subframe to fix this.) Until then, we should check whether we have a
2824 // pending NavigationEntry with a frame ID and if so, treat the
2825 // cross-process "main frame" navigation as a subframe navigation. This
2826 // limits us to a single cross-process subframe per RVH, and it affects
2827 // NavigateToEntry, NavigatorImpl::DidStartProvisionalLoad, and
2828 // OnDidFinishLoad.
2829 NavigationEntryImpl* pending_entry =
2830 NavigationEntryImpl::FromNavigationEntry(controller_.GetPendingEntry());
2831 int root_ftn_id = frame_tree_.root()->frame_tree_node_id();
2832 if (pending_entry &&
2833 pending_entry->frame_tree_node_id() != -1 &&
2834 pending_entry->frame_tree_node_id() != root_ftn_id) {
2835 params.transition = PAGE_TRANSITION_AUTO_SUBFRAME;
2836 frame_tree_node_id = pending_entry->frame_tree_node_id();
2840 if (PageTransitionIsMainFrame(params.transition)) {
2841 // When overscroll navigation gesture is enabled, a screenshot of the page
2842 // in its current state is taken so that it can be used during the
2843 // nav-gesture. It is necessary to take the screenshot here, before calling
2844 // RenderFrameHostManager::DidNavigateMainFrame, because that can change
2845 // WebContents::GetRenderViewHost to return the new host, instead of the one
2846 // that may have just been swapped out.
2847 if (delegate_ && delegate_->CanOverscrollContent())
2848 controller_.TakeScreenshot();
2850 if (!use_site_per_process)
2851 GetRenderManager()->DidNavigateMainFrame(rvh);
2854 // When using --site-per-process, we notify the RFHM for all navigations,
2855 // not just main frame navigations.
2856 if (use_site_per_process) {
2857 FrameTreeNode* frame = frame_tree_.FindByID(frame_tree_node_id);
2858 // TODO(creis): Rename to DidNavigateFrame.
2859 frame->render_manager()->DidNavigateMainFrame(rvh);
2862 // Update the site of the SiteInstance if it doesn't have one yet, unless
2863 // assigning a site is not necessary for this URL. In that case, the
2864 // SiteInstance can still be considered unused until a navigation to a real
2865 // page.
2866 if (!static_cast<SiteInstanceImpl*>(GetSiteInstance())->HasSite() &&
2867 ShouldAssignSiteForURL(params.url)) {
2868 static_cast<SiteInstanceImpl*>(GetSiteInstance())->SetSite(params.url);
2871 // Need to update MIME type here because it's referred to in
2872 // UpdateNavigationCommands() called by RendererDidNavigate() to
2873 // determine whether or not to enable the encoding menu.
2874 // It's updated only for the main frame. For a subframe,
2875 // RenderView::UpdateURL does not set params.contents_mime_type.
2876 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
2877 // TODO(jungshik): Add a test for the encoding menu to avoid
2878 // regressing it again.
2879 if (PageTransitionIsMainFrame(params.transition))
2880 contents_mime_type_ = params.contents_mime_type;
2882 LoadCommittedDetails details;
2883 bool did_navigate = controller_.RendererDidNavigate(rvh, params, &details);
2885 // For now, keep track of each frame's URL in its FrameTreeNode. This lets
2886 // us estimate our process count for implementing OOP iframes.
2887 // TODO(creis): Remove this when we track which pages commit in each frame.
2888 frame_tree_.SetFrameUrl(params.frame_id, params.url);
2890 // Send notification about committed provisional loads. This notification is
2891 // different from the NAV_ENTRY_COMMITTED notification which doesn't include
2892 // the actual URL navigated to and isn't sent for AUTO_SUBFRAME navigations.
2893 if (details.type != NAVIGATION_TYPE_NAV_IGNORE) {
2894 // For AUTO_SUBFRAME navigations, an event for the main frame is generated
2895 // that is not recorded in the navigation history. For the purpose of
2896 // tracking navigation events, we treat this event as a sub frame navigation
2897 // event.
2898 bool is_main_frame = did_navigate ? details.is_main_frame : false;
2899 PageTransition transition_type = params.transition;
2900 // Whether or not a page transition was triggered by going backward or
2901 // forward in the history is only stored in the navigation controller's
2902 // entry list.
2903 if (did_navigate &&
2904 (controller_.GetLastCommittedEntry()->GetTransitionType() &
2905 PAGE_TRANSITION_FORWARD_BACK)) {
2906 transition_type = PageTransitionFromInt(
2907 params.transition | PAGE_TRANSITION_FORWARD_BACK);
2909 // Notify observers about the commit of the provisional load.
2910 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2911 DidCommitProvisionalLoadForFrame(
2912 params.frame_id,
2913 params.frame_unique_name,
2914 is_main_frame,
2915 params.url,
2916 transition_type,
2917 rvh));
2920 if (!did_navigate)
2921 return; // No navigation happened.
2923 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
2924 // for the appropriate notification (best) or you can add it to
2925 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
2926 // necessary, please).
2928 // Run post-commit tasks.
2929 if (details.is_main_frame) {
2930 DidNavigateMainFramePostCommit(details, params);
2931 if (delegate_) {
2932 delegate_->DidNavigateMainFramePostCommit(this);
2933 view_->SetOverscrollControllerEnabled(delegate_->CanOverscrollContent());
2936 DidNavigateAnyFramePostCommit(rvh, details, params);
2939 void WebContentsImpl::UpdateState(RenderViewHost* rvh,
2940 int32 page_id,
2941 const PageState& page_state) {
2942 // Ensure that this state update comes from either the active RVH or one of
2943 // the swapped out RVHs. We don't expect to hear from any other RVHs.
2944 // TODO(nasko): This should go through RenderFrameHost.
2945 // TODO(creis): We can't update state for cross-process subframes until we
2946 // have FrameNavigationEntries. Once we do, this should be a DCHECK.
2947 if (rvh != GetRenderViewHost() &&
2948 !GetRenderManager()->IsRVHOnSwappedOutList(
2949 static_cast<RenderViewHostImpl*>(rvh)))
2950 return;
2952 // We must be prepared to handle state updates for any page, these occur
2953 // when the user is scrolling and entering form data, as well as when we're
2954 // leaving a page, in which case our state may have already been moved to
2955 // the next page. The navigation controller will look up the appropriate
2956 // NavigationEntry and update it when it is notified via the delegate.
2958 int entry_index = controller_.GetEntryIndexWithPageID(
2959 rvh->GetSiteInstance(), page_id);
2960 if (entry_index < 0)
2961 return;
2962 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
2964 if (page_state == entry->GetPageState())
2965 return; // Nothing to update.
2966 entry->SetPageState(page_state);
2967 controller_.NotifyEntryChanged(entry, entry_index);
2970 void WebContentsImpl::UpdateTitle(RenderViewHost* rvh,
2971 int32 page_id,
2972 const base::string16& title,
2973 base::i18n::TextDirection title_direction) {
2974 // If we have a title, that's a pretty good indication that we've started
2975 // getting useful data.
2976 SetNotWaitingForResponse();
2978 // Try to find the navigation entry, which might not be the current one.
2979 // For example, it might be from a pending RVH for the pending entry.
2980 NavigationEntryImpl* entry = controller_.GetEntryWithPageID(
2981 rvh->GetSiteInstance(), page_id);
2983 // We can handle title updates when we don't have an entry in
2984 // UpdateTitleForEntry, but only if the update is from the current RVH.
2985 if (!entry && rvh != GetRenderViewHost())
2986 return;
2988 // TODO(evan): make use of title_direction.
2989 // http://code.google.com/p/chromium/issues/detail?id=27094
2990 if (!UpdateTitleForEntry(entry, title))
2991 return;
2993 // Broadcast notifications when the UI should be updated.
2994 if (entry == controller_.GetEntryAtOffset(0))
2995 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
2998 void WebContentsImpl::UpdateEncoding(RenderViewHost* render_view_host,
2999 const std::string& encoding) {
3000 SetEncoding(encoding);
3003 void WebContentsImpl::UpdateTargetURL(int32 page_id, const GURL& url) {
3004 if (delegate_)
3005 delegate_->UpdateTargetURL(this, page_id, url);
3008 void WebContentsImpl::Close(RenderViewHost* rvh) {
3009 #if defined(OS_MACOSX)
3010 // The UI may be in an event-tracking loop, such as between the
3011 // mouse-down and mouse-up in text selection or a button click.
3012 // Defer the close until after tracking is complete, so that we
3013 // don't free objects out from under the UI.
3014 // TODO(shess): This could get more fine-grained. For instance,
3015 // closing a tab in another window while selecting text in the
3016 // current window's Omnibox should be just fine.
3017 if (view_->IsEventTracking()) {
3018 view_->CloseTabAfterEventTracking();
3019 return;
3021 #endif
3023 // Ignore this if it comes from a RenderViewHost that we aren't showing.
3024 if (delegate_ && rvh == GetRenderViewHost())
3025 delegate_->CloseContents(this);
3028 void WebContentsImpl::SwappedOut(RenderViewHost* rvh) {
3029 if (delegate_ && rvh == GetRenderViewHost())
3030 delegate_->SwappedOut(this);
3032 // Allow the navigation to proceed.
3033 GetRenderManager()->SwappedOut(rvh);
3036 void WebContentsImpl::RequestMove(const gfx::Rect& new_bounds) {
3037 if (delegate_ && delegate_->IsPopupOrPanel(this))
3038 delegate_->MoveContents(this, new_bounds);
3041 void WebContentsImpl::DidStartLoading(RenderViewHost* render_view_host) {
3042 SetIsLoading(render_view_host, true, NULL);
3045 void WebContentsImpl::DidStopLoading(RenderViewHost* render_view_host) {
3046 scoped_ptr<LoadNotificationDetails> details;
3048 // Use the last committed entry rather than the active one, in case a
3049 // pending entry has been created.
3050 NavigationEntry* entry = controller_.GetLastCommittedEntry();
3051 Navigator* navigator = frame_tree_.root()->navigator();
3053 // An entry may not exist for a stop when loading an initial blank page or
3054 // if an iframe injected by script into a blank page finishes loading.
3055 if (entry) {
3056 base::TimeDelta elapsed =
3057 base::TimeTicks::Now() - navigator->GetCurrentLoadStart();
3059 details.reset(new LoadNotificationDetails(
3060 entry->GetVirtualURL(),
3061 entry->GetTransitionType(),
3062 elapsed,
3063 &controller_,
3064 controller_.GetCurrentEntryIndex()));
3067 SetIsLoading(render_view_host, false, details.get());
3070 void WebContentsImpl::DidCancelLoading() {
3071 controller_.DiscardNonCommittedEntries();
3073 // Update the URL display.
3074 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
3077 void WebContentsImpl::DidChangeLoadProgress(double progress) {
3078 if (delegate_)
3079 delegate_->LoadProgressChanged(this, progress);
3082 void WebContentsImpl::DidDisownOpener(RenderViewHost* rvh) {
3083 if (opener_) {
3084 // Clear our opener so that future cross-process navigations don't have an
3085 // opener assigned.
3086 RemoveDestructionObserver(opener_);
3087 opener_ = NULL;
3090 // Notify all swapped out RenderViewHosts for this tab. This is important
3091 // in case we go back to them, or if another window in those processes tries
3092 // to access window.opener.
3093 GetRenderManager()->DidDisownOpener(rvh);
3096 void WebContentsImpl::DidAccessInitialDocument() {
3097 // Update the URL display.
3098 NotifyNavigationStateChanged(content::INVALIDATE_TYPE_URL);
3101 void WebContentsImpl::DocumentAvailableInMainFrame(
3102 RenderViewHost* render_view_host) {
3103 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3104 DocumentAvailableInMainFrame());
3107 void WebContentsImpl::DocumentOnLoadCompletedInMainFrame(
3108 RenderViewHost* render_view_host,
3109 int32 page_id) {
3110 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3111 DocumentOnLoadCompletedInMainFrame(page_id));
3113 // TODO(avi): Remove. http://crbug.com/170921
3114 NotificationService::current()->Notify(
3115 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
3116 Source<WebContents>(this),
3117 Details<int>(&page_id));
3120 void WebContentsImpl::RequestOpenURL(RenderViewHost* rvh,
3121 const GURL& url,
3122 const Referrer& referrer,
3123 WindowOpenDisposition disposition,
3124 int64 source_frame_id,
3125 bool should_replace_current_entry,
3126 bool user_gesture) {
3127 // If this came from a swapped out RenderViewHost, we only allow the request
3128 // if we are still in the same BrowsingInstance.
3129 if (static_cast<RenderViewHostImpl*>(rvh)->is_swapped_out() &&
3130 !rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance())) {
3131 return;
3134 // Delegate to RequestTransferURL because this is just the generic
3135 // case where |old_request_id| is empty.
3136 // TODO(creis): Pass the redirect_chain into this method to support client
3137 // redirects. http://crbug.com/311721.
3138 std::vector<GURL> redirect_chain;
3139 RequestTransferURL(url, redirect_chain, referrer, PAGE_TRANSITION_LINK,
3140 disposition, source_frame_id, GlobalRequestID(),
3141 should_replace_current_entry, user_gesture);
3144 void WebContentsImpl::RequestTransferURL(
3145 const GURL& url,
3146 const std::vector<GURL>& redirect_chain,
3147 const Referrer& referrer,
3148 PageTransition page_transition,
3149 WindowOpenDisposition disposition,
3150 int64 source_frame_id,
3151 const GlobalRequestID& old_request_id,
3152 bool should_replace_current_entry,
3153 bool user_gesture) {
3154 WebContents* new_contents = NULL;
3155 GURL dest_url(url);
3156 if (!GetContentClient()->browser()->ShouldAllowOpenURL(
3157 GetSiteInstance(), url))
3158 dest_url = GURL(kAboutBlankURL);
3160 // Look up the FrameTreeNode ID corresponding to source_frame_id.
3161 int64 frame_tree_node_id = -1;
3162 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess) &&
3163 source_frame_id != -1) {
3164 FrameTreeNode* source_node = frame_tree_.FindByFrameID(source_frame_id);
3165 if (source_node)
3166 frame_tree_node_id = source_node->frame_tree_node_id();
3168 OpenURLParams params(dest_url, referrer, source_frame_id,
3169 frame_tree_node_id, disposition,
3170 page_transition, true /* is_renderer_initiated */);
3171 if (redirect_chain.size() > 0)
3172 params.redirect_chain = redirect_chain;
3173 params.transferred_global_request_id = old_request_id;
3174 params.should_replace_current_entry = should_replace_current_entry;
3175 params.user_gesture = user_gesture;
3177 if (GetRenderManager()->web_ui()) {
3178 // Web UI pages sometimes want to override the page transition type for
3179 // link clicks (e.g., so the new tab page can specify AUTO_BOOKMARK for
3180 // automatically generated suggestions). We don't override other types
3181 // like TYPED because they have different implications (e.g., autocomplete).
3182 if (PageTransitionCoreTypeIs(params.transition, PAGE_TRANSITION_LINK))
3183 params.transition = GetRenderManager()->web_ui()->GetLinkTransitionType();
3185 // Note also that we hide the referrer for Web UI pages. We don't really
3186 // want web sites to see a referrer of "chrome://blah" (and some
3187 // chrome: URLs might have search terms or other stuff we don't want to
3188 // send to the site), so we send no referrer.
3189 params.referrer = Referrer();
3191 // Navigations in Web UI pages count as browser-initiated navigations.
3192 params.is_renderer_initiated = false;
3195 new_contents = OpenURL(params);
3197 if (new_contents) {
3198 // Notify observers.
3199 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3200 DidOpenRequestedURL(new_contents,
3201 dest_url,
3202 referrer,
3203 disposition,
3204 params.transition,
3205 source_frame_id));
3209 void WebContentsImpl::RouteCloseEvent(RenderViewHost* rvh) {
3210 // Tell the active RenderViewHost to run unload handlers and close, as long
3211 // as the request came from a RenderViewHost in the same BrowsingInstance.
3212 // In most cases, we receive this from a swapped out RenderViewHost.
3213 // It is possible to receive it from one that has just been swapped in,
3214 // in which case we might as well deliver the message anyway.
3215 if (rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()))
3216 GetRenderViewHost()->ClosePage();
3219 void WebContentsImpl::RouteMessageEvent(
3220 RenderViewHost* rvh,
3221 const ViewMsg_PostMessage_Params& params) {
3222 // Only deliver the message to the active RenderViewHost if the request
3223 // came from a RenderViewHost in the same BrowsingInstance or if this
3224 // WebContents is dedicated to a browser plugin guest.
3225 // Note: This check means that an embedder could theoretically receive a
3226 // postMessage from anyone (not just its own guests). However, this is
3227 // probably not a risk for apps since other pages won't have references
3228 // to App windows.
3229 if (!rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()) &&
3230 !GetBrowserPluginGuest() && !GetBrowserPluginEmbedder())
3231 return;
3233 ViewMsg_PostMessage_Params new_params(params);
3235 if (!params.message_port_ids.empty()) {
3236 MessagePortMessageFilter* message_port_message_filter =
3237 static_cast<RenderProcessHostImpl*>(GetRenderProcessHost())
3238 ->message_port_message_filter();
3239 std::vector<int> new_routing_ids(params.message_port_ids.size());
3240 for (size_t i = 0; i < params.message_port_ids.size(); ++i) {
3241 new_routing_ids[i] = message_port_message_filter->GetNextRoutingID();
3242 MessagePortService::GetInstance()->UpdateMessagePort(
3243 params.message_port_ids[i],
3244 message_port_message_filter,
3245 new_routing_ids[i]);
3247 new_params.new_routing_ids = new_routing_ids;
3250 // If there is a source_routing_id, translate it to the routing ID for
3251 // the equivalent swapped out RVH in the target process. If we need
3252 // to create a swapped out RVH for the source tab, we create its opener
3253 // chain as well, since those will also be accessible to the target page.
3254 if (new_params.source_routing_id != MSG_ROUTING_NONE) {
3255 // Try to look up the WebContents for the source page.
3256 WebContentsImpl* source_contents = NULL;
3257 RenderViewHostImpl* source_rvh = RenderViewHostImpl::FromID(
3258 rvh->GetProcess()->GetID(), params.source_routing_id);
3259 if (source_rvh) {
3260 source_contents = static_cast<WebContentsImpl*>(
3261 source_rvh->GetDelegate()->GetAsWebContents());
3264 if (source_contents) {
3265 if (GetBrowserPluginGuest()) {
3266 // We create a swapped out RenderView for the embedder in the guest's
3267 // render process but we intentionally do not expose the embedder's
3268 // opener chain to it.
3269 new_params.source_routing_id =
3270 source_contents->CreateSwappedOutRenderView(GetSiteInstance());
3271 } else {
3272 new_params.source_routing_id =
3273 source_contents->CreateOpenerRenderViews(GetSiteInstance());
3275 } else {
3276 // We couldn't find it, so don't pass a source frame.
3277 new_params.source_routing_id = MSG_ROUTING_NONE;
3281 // In most cases, we receive this from a swapped out RenderViewHost.
3282 // It is possible to receive it from one that has just been swapped in,
3283 // in which case we might as well deliver the message anyway.
3284 Send(new ViewMsg_PostMessageEvent(GetRoutingID(), new_params));
3287 void WebContentsImpl::RunJavaScriptMessage(
3288 RenderViewHost* rvh,
3289 const base::string16& message,
3290 const base::string16& default_prompt,
3291 const GURL& frame_url,
3292 JavaScriptMessageType javascript_message_type,
3293 IPC::Message* reply_msg,
3294 bool* did_suppress_message) {
3295 // Suppress JavaScript dialogs when requested. Also suppress messages when
3296 // showing an interstitial as it's shown over the previous page and we don't
3297 // want the hidden page's dialogs to interfere with the interstitial.
3298 bool suppress_this_message =
3299 static_cast<RenderViewHostImpl*>(rvh)->is_swapped_out() ||
3300 ShowingInterstitialPage() ||
3301 !delegate_ ||
3302 delegate_->ShouldSuppressDialogs() ||
3303 !delegate_->GetJavaScriptDialogManager();
3305 if (!suppress_this_message) {
3306 std::string accept_lang = GetContentClient()->browser()->
3307 GetAcceptLangs(GetBrowserContext());
3308 dialog_manager_ = delegate_->GetJavaScriptDialogManager();
3309 dialog_manager_->RunJavaScriptDialog(
3310 this,
3311 frame_url.GetOrigin(),
3312 accept_lang,
3313 javascript_message_type,
3314 message,
3315 default_prompt,
3316 base::Bind(&WebContentsImpl::OnDialogClosed,
3317 base::Unretained(this),
3318 rvh,
3319 reply_msg),
3320 &suppress_this_message);
3323 *did_suppress_message = suppress_this_message;
3325 if (suppress_this_message) {
3326 // If we are suppressing messages, just reply as if the user immediately
3327 // pressed "Cancel".
3328 OnDialogClosed(rvh, reply_msg, false, base::string16());
3331 // OnDialogClosed (two lines up) may have caused deletion of this object (see
3332 // http://crbug.com/288961 ). The only safe thing to do here is return.
3335 void WebContentsImpl::RunBeforeUnloadConfirm(RenderViewHost* rvh,
3336 const base::string16& message,
3337 bool is_reload,
3338 IPC::Message* reply_msg) {
3339 RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(rvh);
3340 if (delegate_)
3341 delegate_->WillRunBeforeUnloadConfirm();
3343 bool suppress_this_message =
3344 rvhi->is_swapped_out() ||
3345 !delegate_ ||
3346 delegate_->ShouldSuppressDialogs() ||
3347 !delegate_->GetJavaScriptDialogManager();
3348 if (suppress_this_message) {
3349 // The reply must be sent to the RVH that sent the request.
3350 rvhi->JavaScriptDialogClosed(reply_msg, true, base::string16());
3351 return;
3354 is_showing_before_unload_dialog_ = true;
3355 dialog_manager_ = delegate_->GetJavaScriptDialogManager();
3356 dialog_manager_->RunBeforeUnloadDialog(
3357 this, message, is_reload,
3358 base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this), rvh,
3359 reply_msg));
3362 bool WebContentsImpl::AddMessageToConsole(int32 level,
3363 const base::string16& message,
3364 int32 line_no,
3365 const base::string16& source_id) {
3366 if (!delegate_)
3367 return false;
3368 return delegate_->AddMessageToConsole(this, level, message, line_no,
3369 source_id);
3372 WebPreferences WebContentsImpl::GetWebkitPrefs() {
3373 // We want to base the page config off of the actual URL, rather than the
3374 // virtual URL.
3375 // TODO(nasko): Investigate how to remove the GetActiveEntry usage here,
3376 // as it is deprecated and can be out of sync with GetRenderViewHost().
3377 GURL url = controller_.GetActiveEntry()
3378 ? controller_.GetActiveEntry()->GetURL() : GURL::EmptyGURL();
3380 return GetRenderManager()->current_host()->GetWebkitPrefs(url);
3383 int WebContentsImpl::CreateSwappedOutRenderView(
3384 SiteInstance* instance) {
3385 return GetRenderManager()->CreateRenderFrame(instance, MSG_ROUTING_NONE,
3386 true, true);
3389 void WebContentsImpl::OnUserGesture() {
3390 // Notify observers.
3391 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetUserGesture());
3393 ResourceDispatcherHostImpl* rdh = ResourceDispatcherHostImpl::Get();
3394 if (rdh) // NULL in unittests.
3395 rdh->OnUserGesture(this);
3398 void WebContentsImpl::OnIgnoredUIEvent() {
3399 // Notify observers.
3400 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetIgnoredUIEvent());
3403 void WebContentsImpl::RendererUnresponsive(RenderViewHost* rvh,
3404 bool is_during_beforeunload,
3405 bool is_during_unload) {
3406 // Don't show hung renderer dialog for a swapped out RVH.
3407 if (rvh != GetRenderViewHost())
3408 return;
3410 RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(rvh);
3412 // Ignore renderer unresponsive event if debugger is attached to the tab
3413 // since the event may be a result of the renderer sitting on a breakpoint.
3414 // See http://crbug.com/65458
3415 if (DevToolsAgentHost::IsDebuggerAttached(this))
3416 return;
3418 if (is_during_beforeunload || is_during_unload) {
3419 // Hang occurred while firing the beforeunload/unload handler.
3420 // Pretend the handler fired so tab closing continues as if it had.
3421 rvhi->set_sudden_termination_allowed(true);
3423 if (!GetRenderManager()->ShouldCloseTabOnUnresponsiveRenderer())
3424 return;
3426 // If the tab hangs in the beforeunload/unload handler there's really
3427 // nothing we can do to recover. If the hang is in the beforeunload handler,
3428 // pretend the beforeunload listeners have all fired and allow the delegate
3429 // to continue closing; the user will not have the option of cancelling the
3430 // close. Otherwise, pretend the unload listeners have all fired and close
3431 // the tab.
3432 bool close = true;
3433 if (is_during_beforeunload) {
3434 delegate_->BeforeUnloadFired(this, true, &close);
3436 if (close)
3437 Close(rvh);
3438 return;
3441 if (!GetRenderViewHostImpl() || !GetRenderViewHostImpl()->IsRenderViewLive())
3442 return;
3444 if (delegate_)
3445 delegate_->RendererUnresponsive(this);
3448 void WebContentsImpl::RendererResponsive(RenderViewHost* render_view_host) {
3449 if (delegate_)
3450 delegate_->RendererResponsive(this);
3453 void WebContentsImpl::LoadStateChanged(
3454 const GURL& url,
3455 const net::LoadStateWithParam& load_state,
3456 uint64 upload_position,
3457 uint64 upload_size) {
3458 load_state_ = load_state;
3459 upload_position_ = upload_position;
3460 upload_size_ = upload_size;
3461 load_state_host_ = net::IDNToUnicode(url.host(),
3462 GetContentClient()->browser()->GetAcceptLangs(
3463 GetBrowserContext()));
3464 if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
3465 SetNotWaitingForResponse();
3466 if (IsLoading()) {
3467 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD | INVALIDATE_TYPE_TAB);
3471 void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
3472 bool proceed, const base::TimeTicks& proceed_time,
3473 bool* proceed_to_fire_unload) {
3474 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3475 BeforeUnloadFired(proceed_time));
3476 if (delegate_)
3477 delegate_->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
3478 // Note: |this| might be deleted at this point.
3481 void WebContentsImpl::RenderProcessGoneFromRenderManager(
3482 RenderViewHost* render_view_host) {
3483 DCHECK(crashed_status_ != base::TERMINATION_STATUS_STILL_RUNNING);
3484 RenderViewTerminated(render_view_host, crashed_status_, crashed_error_code_);
3487 void WebContentsImpl::UpdateRenderViewSizeForRenderManager() {
3488 // TODO(brettw) this is a hack. See WebContentsView::SizeContents.
3489 gfx::Size size = GetSizeForNewRenderView();
3490 // 0x0 isn't a valid window size (minimal window size is 1x1) but it may be
3491 // here during container initialization and normal window size will be set
3492 // later. In case of tab duplication this resizing to 0x0 prevents setting
3493 // normal size later so just ignore it.
3494 if (!size.IsEmpty())
3495 view_->SizeContents(size);
3498 void WebContentsImpl::CancelModalDialogsForRenderManager() {
3499 // We need to cancel modal dialogs when doing a process swap, since the load
3500 // deferrer would prevent us from swapping out.
3501 if (dialog_manager_)
3502 dialog_manager_->CancelActiveAndPendingDialogs(this);
3505 void WebContentsImpl::NotifySwappedFromRenderManager(RenderViewHost* old_host,
3506 RenderViewHost* new_host) {
3507 NotifySwapped(old_host, new_host);
3509 // Make sure the visible RVH reflects the new delegate's preferences.
3510 if (delegate_)
3511 view_->SetOverscrollControllerEnabled(delegate_->CanOverscrollContent());
3513 view_->RenderViewSwappedIn(new_host);
3516 int WebContentsImpl::CreateOpenerRenderViewsForRenderManager(
3517 SiteInstance* instance) {
3518 if (!opener_)
3519 return MSG_ROUTING_NONE;
3521 // Recursively create RenderViews for anything else in the opener chain.
3522 return opener_->CreateOpenerRenderViews(instance);
3525 int WebContentsImpl::CreateOpenerRenderViews(SiteInstance* instance) {
3526 int opener_route_id = MSG_ROUTING_NONE;
3528 // If this tab has an opener, ensure it has a RenderView in the given
3529 // SiteInstance as well.
3530 if (opener_)
3531 opener_route_id = opener_->CreateOpenerRenderViews(instance);
3533 // If any of the renderers (current, pending, or swapped out) for this
3534 // WebContents has the same SiteInstance, use it.
3535 if (GetRenderManager()->current_host()->GetSiteInstance() == instance)
3536 return GetRenderManager()->current_host()->GetRoutingID();
3538 if (GetRenderManager()->pending_render_view_host() &&
3539 GetRenderManager()->pending_render_view_host()->GetSiteInstance() ==
3540 instance)
3541 return GetRenderManager()->pending_render_view_host()->GetRoutingID();
3543 RenderViewHostImpl* rvh = GetRenderManager()->GetSwappedOutRenderViewHost(
3544 instance);
3545 if (rvh)
3546 return rvh->GetRoutingID();
3548 // Create a swapped out RenderView in the given SiteInstance if none exists,
3549 // setting its opener to the given route_id. Return the new view's route_id.
3550 return GetRenderManager()->CreateRenderFrame(instance, opener_route_id,
3551 true, true);
3554 NavigationControllerImpl& WebContentsImpl::GetControllerForRenderManager() {
3555 return GetController();
3558 WebUIImpl* WebContentsImpl::CreateWebUIForRenderManager(const GURL& url) {
3559 return static_cast<WebUIImpl*>(CreateWebUI(url));
3562 NavigationEntry*
3563 WebContentsImpl::GetLastCommittedNavigationEntryForRenderManager() {
3564 return controller_.GetLastCommittedEntry();
3567 bool WebContentsImpl::CreateRenderViewForRenderManager(
3568 RenderViewHost* render_view_host, int opener_route_id) {
3569 TRACE_EVENT0("browser", "WebContentsImpl::CreateRenderViewForRenderManager");
3570 // Can be NULL during tests.
3571 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
3573 // Now that the RenderView has been created, we need to tell it its size.
3574 if (rwh_view)
3575 rwh_view->SetSize(GetSizeForNewRenderView());
3577 // Make sure we use the correct starting page_id in the new RenderView.
3578 UpdateMaxPageIDIfNecessary(render_view_host);
3579 int32 max_page_id =
3580 GetMaxPageIDForSiteInstance(render_view_host->GetSiteInstance());
3582 if (!static_cast<RenderViewHostImpl*>(
3583 render_view_host)->CreateRenderView(base::string16(),
3584 opener_route_id,
3585 max_page_id)) {
3586 return false;
3589 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
3590 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
3591 // linux. See crbug.com/83941.
3592 if (rwh_view) {
3593 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
3594 render_widget_host->WasResized();
3596 #endif
3598 return true;
3601 #if defined(OS_ANDROID)
3602 base::android::ScopedJavaLocalRef<jobject>
3603 WebContentsImpl::GetJavaWebContents() {
3604 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
3606 WebContentsAndroid* web_contents_android =
3607 static_cast<WebContentsAndroid*>(GetUserData(kWebContentsAndroidKey));
3608 if (!web_contents_android) {
3609 web_contents_android = new WebContentsAndroid(this);
3610 SetUserData(kWebContentsAndroidKey, web_contents_android);
3612 return web_contents_android->GetJavaObject();
3615 bool WebContentsImpl::CreateRenderViewForInitialEmptyDocument() {
3616 return CreateRenderViewForRenderManager(GetRenderViewHost(),
3617 MSG_ROUTING_NONE);
3619 #endif
3621 void WebContentsImpl::OnDialogClosed(RenderViewHost* rvh,
3622 IPC::Message* reply_msg,
3623 bool success,
3624 const base::string16& user_input) {
3625 if (is_showing_before_unload_dialog_ && !success) {
3626 // If a beforeunload dialog is canceled, we need to stop the throbber from
3627 // spinning, since we forced it to start spinning in Navigate.
3628 DidStopLoading(rvh);
3629 controller_.DiscardNonCommittedEntries();
3631 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3632 BeforeUnloadDialogCancelled());
3634 is_showing_before_unload_dialog_ = false;
3635 static_cast<RenderViewHostImpl*>(
3636 rvh)->JavaScriptDialogClosed(reply_msg, success, user_input);
3639 void WebContentsImpl::SetEncoding(const std::string& encoding) {
3640 encoding_ = GetContentClient()->browser()->
3641 GetCanonicalEncodingNameByAliasName(encoding);
3644 void WebContentsImpl::CreateViewAndSetSizeForRVH(RenderViewHost* rvh) {
3645 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(rvh);
3646 // Can be NULL during tests.
3647 if (rwh_view)
3648 rwh_view->SetSize(GetView()->GetContainerSize());
3651 bool WebContentsImpl::IsHidden() {
3652 return capturer_count_ == 0 && !should_normally_be_visible_;
3655 RenderFrameHostManager* WebContentsImpl::GetRenderManager() const {
3656 return frame_tree_.root()->render_manager();
3659 RenderViewHostImpl* WebContentsImpl::GetRenderViewHostImpl() {
3660 return static_cast<RenderViewHostImpl*>(GetRenderViewHost());
3663 BrowserPluginGuest* WebContentsImpl::GetBrowserPluginGuest() const {
3664 return browser_plugin_guest_.get();
3667 void WebContentsImpl::SetBrowserPluginGuest(BrowserPluginGuest* guest) {
3668 CHECK(!browser_plugin_guest_);
3669 browser_plugin_guest_.reset(guest);
3672 BrowserPluginEmbedder* WebContentsImpl::GetBrowserPluginEmbedder() const {
3673 return browser_plugin_embedder_.get();
3676 BrowserPluginGuestManager*
3677 WebContentsImpl::GetBrowserPluginGuestManager() const {
3678 return static_cast<BrowserPluginGuestManager*>(
3679 GetBrowserContext()->GetUserData(
3680 browser_plugin::kBrowserPluginGuestManagerKeyName));
3683 void WebContentsImpl::ClearPowerSaveBlockers(
3684 RenderViewHost* render_view_host) {
3685 STLDeleteValues(&power_save_blockers_[render_view_host]);
3686 power_save_blockers_.erase(render_view_host);
3689 void WebContentsImpl::ClearAllPowerSaveBlockers() {
3690 for (PowerSaveBlockerMap::iterator i(power_save_blockers_.begin());
3691 i != power_save_blockers_.end(); ++i)
3692 STLDeleteValues(&power_save_blockers_[i->first]);
3693 power_save_blockers_.clear();
3696 gfx::Size WebContentsImpl::GetSizeForNewRenderView() const {
3697 gfx::Size size;
3698 if (delegate_)
3699 size = delegate_->GetSizeForNewRenderView(this);
3700 if (size.IsEmpty())
3701 size = view_->GetContainerSize();
3702 return size;
3705 void WebContentsImpl::OnFrameRemoved(
3706 RenderViewHostImpl* render_view_host,
3707 int64 frame_id) {
3708 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3709 FrameDetached(render_view_host, frame_id));
3712 } // namespace content