[Media Router] Add integration tests and e2e tests for media router and presentation...
[chromium-blink-merge.git] / chrome / browser / prerender / prerender_contents.cc
blobfb7daa97816557294ef6be57a1d4ed3e29eaf13e
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 "chrome/browser/prerender/prerender_contents.h"
7 #include <algorithm>
8 #include <functional>
9 #include <utility>
11 #include "base/bind.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "chrome/browser/chrome_notification_types.h"
14 #include "chrome/browser/history/history_tab_helper.h"
15 #include "chrome/browser/prerender/prerender_field_trial.h"
16 #include "chrome/browser/prerender/prerender_final_status.h"
17 #include "chrome/browser/prerender/prerender_handle.h"
18 #include "chrome/browser/prerender/prerender_manager.h"
19 #include "chrome/browser/prerender/prerender_manager_factory.h"
20 #include "chrome/browser/prerender/prerender_resource_throttle.h"
21 #include "chrome/browser/profiles/profile.h"
22 #include "chrome/browser/ui/browser.h"
23 #include "chrome/browser/ui/tab_helpers.h"
24 #include "chrome/browser/ui/web_contents_sizer.h"
25 #include "chrome/common/prerender_messages.h"
26 #include "chrome/common/render_messages.h"
27 #include "chrome/common/url_constants.h"
28 #include "components/history/core/browser/history_types.h"
29 #include "content/public/browser/browser_child_process_host.h"
30 #include "content/public/browser/browser_thread.h"
31 #include "content/public/browser/notification_service.h"
32 #include "content/public/browser/render_frame_host.h"
33 #include "content/public/browser/render_process_host.h"
34 #include "content/public/browser/render_view_host.h"
35 #include "content/public/browser/resource_request_details.h"
36 #include "content/public/browser/session_storage_namespace.h"
37 #include "content/public/browser/web_contents.h"
38 #include "content/public/browser/web_contents_delegate.h"
39 #include "content/public/common/frame_navigate_params.h"
40 #include "ui/base/page_transition_types.h"
41 #include "ui/gfx/geometry/rect.h"
43 using content::BrowserThread;
44 using content::DownloadItem;
45 using content::OpenURLParams;
46 using content::RenderViewHost;
47 using content::ResourceRedirectDetails;
48 using content::ResourceType;
49 using content::SessionStorageNamespace;
50 using content::WebContents;
52 namespace prerender {
54 namespace {
56 void ResumeThrottles(
57 std::vector<base::WeakPtr<PrerenderResourceThrottle> > throttles) {
58 for (size_t i = 0; i < throttles.size(); i++) {
59 if (throttles[i])
60 throttles[i]->Resume();
64 } // namespace
66 class PrerenderContentsFactoryImpl : public PrerenderContents::Factory {
67 public:
68 PrerenderContents* CreatePrerenderContents(
69 PrerenderManager* prerender_manager,
70 Profile* profile,
71 const GURL& url,
72 const content::Referrer& referrer,
73 Origin origin) override {
74 return new PrerenderContents(prerender_manager, profile, url, referrer,
75 origin);
79 // WebContentsDelegateImpl -----------------------------------------------------
81 class PrerenderContents::WebContentsDelegateImpl
82 : public content::WebContentsDelegate {
83 public:
84 explicit WebContentsDelegateImpl(PrerenderContents* prerender_contents)
85 : prerender_contents_(prerender_contents) {
88 // content::WebContentsDelegate implementation:
89 WebContents* OpenURLFromTab(WebContents* source,
90 const OpenURLParams& params) override {
91 // |OpenURLFromTab| is typically called when a frame performs a navigation
92 // that requires the browser to perform the transition instead of WebKit.
93 // Examples include prerendering a site that redirects to an app URL, or if
94 // --site-per-process is specified and the prerendered frame redirects to a
95 // different origin.
96 // TODO(cbentzel): Consider supporting this for CURRENT_TAB dispositions, if
97 // it is a common case during prerenders.
98 prerender_contents_->Destroy(FINAL_STATUS_OPEN_URL);
99 return NULL;
102 void CloseContents(content::WebContents* contents) override {
103 prerender_contents_->Destroy(FINAL_STATUS_CLOSED);
106 void CanDownload(const GURL& url,
107 const std::string& request_method,
108 const base::Callback<void(bool)>& callback) override {
109 prerender_contents_->Destroy(FINAL_STATUS_DOWNLOAD);
110 // Cancel the download.
111 callback.Run(false);
114 bool ShouldCreateWebContents(
115 WebContents* web_contents,
116 int route_id,
117 int main_frame_route_id,
118 WindowContainerType window_container_type,
119 const base::string16& frame_name,
120 const GURL& target_url,
121 const std::string& partition_id,
122 SessionStorageNamespace* session_storage_namespace) override {
123 // Since we don't want to permit child windows that would have a
124 // window.opener property, terminate prerendering.
125 prerender_contents_->Destroy(FINAL_STATUS_CREATE_NEW_WINDOW);
126 // Cancel the popup.
127 return false;
130 bool OnGoToEntryOffset(int offset) override {
131 // This isn't allowed because the history merge operation
132 // does not work if there are renderer issued challenges.
133 // TODO(cbentzel): Cancel in this case? May not need to do
134 // since render-issued offset navigations are not guaranteed,
135 // but indicates that the page cares about the history.
136 return false;
139 bool ShouldSuppressDialogs(WebContents* source) override {
140 // We still want to show the user the message when they navigate to this
141 // page, so cancel this prerender.
142 prerender_contents_->Destroy(FINAL_STATUS_JAVASCRIPT_ALERT);
143 // Always suppress JavaScript messages if they're triggered by a page being
144 // prerendered.
145 return true;
148 void RegisterProtocolHandler(WebContents* web_contents,
149 const std::string& protocol,
150 const GURL& url,
151 bool user_gesture) override {
152 // TODO(mmenke): Consider supporting this if it is a common case during
153 // prerenders.
154 prerender_contents_->Destroy(FINAL_STATUS_REGISTER_PROTOCOL_HANDLER);
157 gfx::Size GetSizeForNewRenderView(WebContents* web_contents) const override {
158 // Have to set the size of the RenderView on initialization to be sure it is
159 // set before the RenderView is hidden on all platforms (esp. Android).
160 return prerender_contents_->size_;
163 private:
164 PrerenderContents* prerender_contents_;
167 void PrerenderContents::Observer::OnPrerenderStopLoading(
168 PrerenderContents* contents) {
171 void PrerenderContents::Observer::OnPrerenderDomContentLoaded(
172 PrerenderContents* contents) {
175 void PrerenderContents::Observer::OnPrerenderCreatedMatchCompleteReplacement(
176 PrerenderContents* contents, PrerenderContents* replacement) {
179 PrerenderContents::Observer::Observer() {
182 PrerenderContents::Observer::~Observer() {
185 PrerenderContents::PrerenderContents(
186 PrerenderManager* prerender_manager,
187 Profile* profile,
188 const GURL& url,
189 const content::Referrer& referrer,
190 Origin origin)
191 : prerendering_has_started_(false),
192 session_storage_namespace_id_(-1),
193 prerender_manager_(prerender_manager),
194 prerender_url_(url),
195 referrer_(referrer),
196 profile_(profile),
197 page_id_(0),
198 has_stopped_loading_(false),
199 has_finished_loading_(false),
200 final_status_(FINAL_STATUS_MAX),
201 match_complete_status_(MATCH_COMPLETE_DEFAULT),
202 prerendering_has_been_cancelled_(false),
203 child_id_(-1),
204 route_id_(-1),
205 origin_(origin),
206 network_bytes_(0) {
207 DCHECK(prerender_manager != NULL);
210 PrerenderContents* PrerenderContents::CreateMatchCompleteReplacement() {
211 PrerenderContents* new_contents = prerender_manager_->CreatePrerenderContents(
212 prerender_url(), referrer(), origin());
214 new_contents->load_start_time_ = load_start_time_;
215 new_contents->session_storage_namespace_id_ = session_storage_namespace_id_;
216 new_contents->set_match_complete_status(
217 PrerenderContents::MATCH_COMPLETE_REPLACEMENT_PENDING);
219 const bool did_init = new_contents->Init();
220 DCHECK(did_init);
221 DCHECK_EQ(alias_urls_.front(), new_contents->alias_urls_.front());
222 DCHECK_EQ(1u, new_contents->alias_urls_.size());
223 new_contents->alias_urls_ = alias_urls_;
224 // Erase all but the first alias URL; the replacement has adopted the
225 // remainder without increasing the renderer-side reference count.
226 alias_urls_.resize(1);
227 new_contents->set_match_complete_status(
228 PrerenderContents::MATCH_COMPLETE_REPLACEMENT);
229 NotifyPrerenderCreatedMatchCompleteReplacement(new_contents);
230 return new_contents;
233 bool PrerenderContents::Init() {
234 return AddAliasURL(prerender_url_);
237 // static
238 PrerenderContents::Factory* PrerenderContents::CreateFactory() {
239 return new PrerenderContentsFactoryImpl();
242 // static
243 PrerenderContents* PrerenderContents::FromWebContents(
244 content::WebContents* web_contents) {
245 if (!web_contents)
246 return NULL;
247 PrerenderManager* prerender_manager = PrerenderManagerFactory::GetForProfile(
248 Profile::FromBrowserContext(web_contents->GetBrowserContext()));
249 if (!prerender_manager)
250 return NULL;
251 return prerender_manager->GetPrerenderContents(web_contents);
254 void PrerenderContents::StartPrerendering(
255 const gfx::Size& size,
256 SessionStorageNamespace* session_storage_namespace) {
257 DCHECK(profile_ != NULL);
258 DCHECK(!size.IsEmpty());
259 DCHECK(!prerendering_has_started_);
260 DCHECK(prerender_contents_.get() == NULL);
261 DCHECK(size_.IsEmpty());
262 DCHECK_EQ(1U, alias_urls_.size());
264 session_storage_namespace_id_ = session_storage_namespace->id();
265 size_ = size;
267 DCHECK(load_start_time_.is_null());
268 load_start_time_ = base::TimeTicks::Now();
270 // Everything after this point sets up the WebContents object and associated
271 // RenderView for the prerender page. Don't do this for members of the
272 // control group.
273 if (prerender_manager_->IsControlGroup())
274 return;
276 prerendering_has_started_ = true;
278 prerender_contents_.reset(CreateWebContents(session_storage_namespace));
279 TabHelpers::AttachTabHelpers(prerender_contents_.get());
280 content::WebContentsObserver::Observe(prerender_contents_.get());
282 web_contents_delegate_.reset(new WebContentsDelegateImpl(this));
283 prerender_contents_.get()->SetDelegate(web_contents_delegate_.get());
284 // Set the size of the prerender WebContents.
285 ResizeWebContents(prerender_contents_.get(), size_);
287 // TODO(davidben): This logic assumes each prerender has at most one
288 // route. https://crbug.com/440544
289 child_id_ = GetRenderViewHost()->GetProcess()->GetID();
290 route_id_ = GetRenderViewHost()->GetRoutingID();
292 // TODO(davidben): This logic assumes each prerender has at most one
293 // process. https://crbug.com/440544
294 prerender_manager()->AddPrerenderProcessHost(
295 GetRenderViewHost()->GetProcess());
297 NotifyPrerenderStart();
299 // Close ourselves when the application is shutting down.
300 notification_registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
301 content::NotificationService::AllSources());
303 // Register to inform new RenderViews that we're prerendering.
304 notification_registrar_.Add(
305 this, content::NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
306 content::Source<WebContents>(prerender_contents_.get()));
308 // Transfer over the user agent override.
309 prerender_contents_.get()->SetUserAgentOverride(
310 prerender_manager_->config().user_agent_override);
312 content::NavigationController::LoadURLParams load_url_params(
313 prerender_url_);
314 load_url_params.referrer = referrer_;
315 load_url_params.transition_type = ui::PAGE_TRANSITION_LINK;
316 if (origin_ == ORIGIN_OMNIBOX) {
317 load_url_params.transition_type = ui::PageTransitionFromInt(
318 ui::PAGE_TRANSITION_TYPED |
319 ui::PAGE_TRANSITION_FROM_ADDRESS_BAR);
320 } else if (origin_ == ORIGIN_INSTANT) {
321 load_url_params.transition_type = ui::PageTransitionFromInt(
322 ui::PAGE_TRANSITION_GENERATED |
323 ui::PAGE_TRANSITION_FROM_ADDRESS_BAR);
325 load_url_params.override_user_agent =
326 prerender_manager_->config().is_overriding_user_agent ?
327 content::NavigationController::UA_OVERRIDE_TRUE :
328 content::NavigationController::UA_OVERRIDE_FALSE;
329 prerender_contents_.get()->GetController().LoadURLWithParams(load_url_params);
332 bool PrerenderContents::GetChildId(int* child_id) const {
333 CHECK(child_id);
334 DCHECK_GE(child_id_, -1);
335 *child_id = child_id_;
336 return child_id_ != -1;
339 bool PrerenderContents::GetRouteId(int* route_id) const {
340 CHECK(route_id);
341 DCHECK_GE(route_id_, -1);
342 *route_id = route_id_;
343 return route_id_ != -1;
346 void PrerenderContents::SetFinalStatus(FinalStatus final_status) {
347 DCHECK_GE(final_status, FINAL_STATUS_USED);
348 DCHECK_LT(final_status, FINAL_STATUS_MAX);
350 DCHECK_EQ(FINAL_STATUS_MAX, final_status_);
352 final_status_ = final_status;
355 PrerenderContents::~PrerenderContents() {
356 DCHECK_NE(FINAL_STATUS_MAX, final_status());
357 DCHECK(
358 prerendering_has_been_cancelled() || final_status() == FINAL_STATUS_USED);
359 DCHECK_NE(ORIGIN_MAX, origin());
361 prerender_manager_->RecordFinalStatusWithMatchCompleteStatus(
362 origin(), match_complete_status(), final_status());
364 bool used = final_status() == FINAL_STATUS_USED ||
365 final_status() == FINAL_STATUS_WOULD_HAVE_BEEN_USED;
366 prerender_manager_->RecordNetworkBytes(origin(), used, network_bytes_);
368 // Broadcast the removal of aliases.
369 for (content::RenderProcessHost::iterator host_iterator =
370 content::RenderProcessHost::AllHostsIterator();
371 !host_iterator.IsAtEnd();
372 host_iterator.Advance()) {
373 content::RenderProcessHost* host = host_iterator.GetCurrentValue();
374 host->Send(new PrerenderMsg_OnPrerenderRemoveAliases(alias_urls_));
377 // If we still have a WebContents, clean up anything we need to and then
378 // destroy it.
379 if (prerender_contents_.get())
380 delete ReleasePrerenderContents();
383 void PrerenderContents::AddObserver(Observer* observer) {
384 DCHECK_EQ(FINAL_STATUS_MAX, final_status_);
385 observer_list_.AddObserver(observer);
388 void PrerenderContents::RemoveObserver(Observer* observer) {
389 observer_list_.RemoveObserver(observer);
392 void PrerenderContents::Observe(int type,
393 const content::NotificationSource& source,
394 const content::NotificationDetails& details) {
395 switch (type) {
396 // TODO(davidben): Try to remove this in favor of relying on
397 // FINAL_STATUS_PROFILE_DESTROYED.
398 case chrome::NOTIFICATION_APP_TERMINATING:
399 Destroy(FINAL_STATUS_APP_TERMINATING);
400 return;
402 case content::NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED: {
403 if (prerender_contents_.get()) {
404 DCHECK_EQ(content::Source<WebContents>(source).ptr(),
405 prerender_contents_.get());
407 content::Details<RenderViewHost> new_render_view_host(details);
408 OnRenderViewHostCreated(new_render_view_host.ptr());
410 // Make sure the size of the RenderViewHost has been passed to the new
411 // RenderView. Otherwise, the size may not be sent until the
412 // RenderViewReady event makes it from the render process to the UI
413 // thread of the browser process. When the RenderView receives its
414 // size, is also sets itself to be visible, which would then break the
415 // visibility API.
416 new_render_view_host->WasResized();
417 prerender_contents_->WasHidden();
419 break;
422 default:
423 NOTREACHED() << "Unexpected notification sent.";
424 break;
428 void PrerenderContents::OnRenderViewHostCreated(
429 RenderViewHost* new_render_view_host) {
432 WebContents* PrerenderContents::CreateWebContents(
433 SessionStorageNamespace* session_storage_namespace) {
434 // TODO(ajwong): Remove the temporary map once prerendering is aware of
435 // multiple session storage namespaces per tab.
436 content::SessionStorageNamespaceMap session_storage_namespace_map;
437 session_storage_namespace_map[std::string()] = session_storage_namespace;
438 return WebContents::CreateWithSessionStorage(
439 WebContents::CreateParams(profile_), session_storage_namespace_map);
442 void PrerenderContents::NotifyPrerenderStart() {
443 DCHECK_EQ(FINAL_STATUS_MAX, final_status_);
444 FOR_EACH_OBSERVER(Observer, observer_list_, OnPrerenderStart(this));
447 void PrerenderContents::NotifyPrerenderStopLoading() {
448 FOR_EACH_OBSERVER(Observer, observer_list_, OnPrerenderStopLoading(this));
451 void PrerenderContents::NotifyPrerenderDomContentLoaded() {
452 FOR_EACH_OBSERVER(Observer, observer_list_,
453 OnPrerenderDomContentLoaded(this));
456 void PrerenderContents::NotifyPrerenderStop() {
457 DCHECK_NE(FINAL_STATUS_MAX, final_status_);
458 FOR_EACH_OBSERVER(Observer, observer_list_, OnPrerenderStop(this));
459 observer_list_.Clear();
462 void PrerenderContents::NotifyPrerenderCreatedMatchCompleteReplacement(
463 PrerenderContents* replacement) {
464 FOR_EACH_OBSERVER(Observer, observer_list_,
465 OnPrerenderCreatedMatchCompleteReplacement(this,
466 replacement));
469 bool PrerenderContents::OnMessageReceived(const IPC::Message& message) {
470 bool handled = true;
471 // The following messages we do want to consume.
472 IPC_BEGIN_MESSAGE_MAP(PrerenderContents, message)
473 IPC_MESSAGE_HANDLER(ChromeViewHostMsg_CancelPrerenderForPrinting,
474 OnCancelPrerenderForPrinting)
475 IPC_MESSAGE_UNHANDLED(handled = false)
476 IPC_END_MESSAGE_MAP()
478 return handled;
481 bool PrerenderContents::CheckURL(const GURL& url) {
482 if (!url.SchemeIsHTTPOrHTTPS()) {
483 DCHECK_NE(MATCH_COMPLETE_REPLACEMENT_PENDING, match_complete_status_);
484 Destroy(FINAL_STATUS_UNSUPPORTED_SCHEME);
485 return false;
487 if (match_complete_status_ != MATCH_COMPLETE_REPLACEMENT_PENDING &&
488 prerender_manager_->HasRecentlyBeenNavigatedTo(origin(), url)) {
489 Destroy(FINAL_STATUS_RECENTLY_VISITED);
490 return false;
492 return true;
495 bool PrerenderContents::AddAliasURL(const GURL& url) {
496 if (!CheckURL(url))
497 return false;
499 alias_urls_.push_back(url);
501 for (content::RenderProcessHost::iterator host_iterator =
502 content::RenderProcessHost::AllHostsIterator();
503 !host_iterator.IsAtEnd();
504 host_iterator.Advance()) {
505 content::RenderProcessHost* host = host_iterator.GetCurrentValue();
506 host->Send(new PrerenderMsg_OnPrerenderAddAlias(url));
509 return true;
512 bool PrerenderContents::Matches(
513 const GURL& url,
514 const SessionStorageNamespace* session_storage_namespace) const {
515 // TODO(davidben): Remove any consumers that pass in a NULL
516 // session_storage_namespace and only test with matches.
517 if (session_storage_namespace &&
518 session_storage_namespace_id_ != session_storage_namespace->id()) {
519 return false;
521 return std::count_if(alias_urls_.begin(), alias_urls_.end(),
522 std::bind2nd(std::equal_to<GURL>(), url)) != 0;
525 void PrerenderContents::RenderProcessGone(base::TerminationStatus status) {
526 Destroy(FINAL_STATUS_RENDERER_CRASHED);
529 void PrerenderContents::RenderFrameCreated(
530 content::RenderFrameHost* render_frame_host) {
531 // When a new RenderFrame is created for a prerendering WebContents, tell the
532 // new RenderFrame it's being used for prerendering before any navigations
533 // occur. Note that this is always triggered before the first navigation, so
534 // there's no need to send the message just after the WebContents is created.
535 render_frame_host->Send(new PrerenderMsg_SetIsPrerendering(
536 render_frame_host->GetRoutingID(), true));
539 void PrerenderContents::DidStopLoading() {
540 has_stopped_loading_ = true;
541 NotifyPrerenderStopLoading();
544 void PrerenderContents::DocumentLoadedInFrame(
545 content::RenderFrameHost* render_frame_host) {
546 if (!render_frame_host->GetParent())
547 NotifyPrerenderDomContentLoaded();
550 void PrerenderContents::DidStartProvisionalLoadForFrame(
551 content::RenderFrameHost* render_frame_host,
552 const GURL& validated_url,
553 bool is_error_page,
554 bool is_iframe_srcdoc) {
555 if (!render_frame_host->GetParent()) {
556 if (!CheckURL(validated_url))
557 return;
559 // Usually, this event fires if the user clicks or enters a new URL.
560 // Neither of these can happen in the case of an invisible prerender.
561 // So the cause is: Some JavaScript caused a new URL to be loaded. In that
562 // case, the spinner would start again in the browser, so we must reset
563 // has_stopped_loading_ so that the spinner won't be stopped.
564 has_stopped_loading_ = false;
565 has_finished_loading_ = false;
569 void PrerenderContents::DidFinishLoad(
570 content::RenderFrameHost* render_frame_host,
571 const GURL& validated_url) {
572 if (!render_frame_host->GetParent())
573 has_finished_loading_ = true;
576 void PrerenderContents::DidNavigateMainFrame(
577 const content::LoadCommittedDetails& details,
578 const content::FrameNavigateParams& params) {
579 // If the prerender made a second navigation entry, abort the prerender. This
580 // avoids having to correctly implement a complex history merging case (this
581 // interacts with location.replace) and correctly synchronize with the
582 // renderer. The final status may be monitored to see we need to revisit this
583 // decision. This does not affect client redirects as those do not push new
584 // history entries. (Calls to location.replace, navigations before onload, and
585 // <meta http-equiv=refresh> with timeouts under 1 second do not create
586 // entries in Blink.)
587 if (prerender_contents_->GetController().GetEntryCount() > 1) {
588 Destroy(FINAL_STATUS_NEW_NAVIGATION_ENTRY);
589 return;
592 // Add each redirect as an alias. |params.url| is included in
593 // |params.redirects|.
595 // TODO(davidben): We do not correctly patch up history for renderer-initated
596 // navigations which add history entries. http://crbug.com/305660.
597 for (size_t i = 0; i < params.redirects.size(); i++) {
598 if (!AddAliasURL(params.redirects[i]))
599 return;
603 void PrerenderContents::DidGetRedirectForResourceRequest(
604 content::RenderFrameHost* render_frame_host,
605 const content::ResourceRedirectDetails& details) {
606 // DidGetRedirectForResourceRequest can come for any resource on a page. If
607 // it's a redirect on the top-level resource, the name needs to be remembered
608 // for future matching, and if it redirects to an https resource, it needs to
609 // be canceled. If a subresource is redirected, nothing changes.
610 if (details.resource_type != content::RESOURCE_TYPE_MAIN_FRAME)
611 return;
612 CheckURL(details.new_url);
615 void PrerenderContents::Destroy(FinalStatus final_status) {
616 DCHECK_NE(final_status, FINAL_STATUS_USED);
618 if (prerendering_has_been_cancelled_)
619 return;
621 SetFinalStatus(final_status);
623 prerendering_has_been_cancelled_ = true;
624 prerender_manager_->AddToHistory(this);
625 prerender_manager_->MoveEntryToPendingDelete(this, final_status);
627 // Note that if this PrerenderContents was made into a MatchComplete
628 // replacement by MoveEntryToPendingDelete, NotifyPrerenderStop will
629 // not reach the PrerenderHandle. Rather
630 // OnPrerenderCreatedMatchCompleteReplacement will propogate that
631 // information to the referer.
632 if (!prerender_manager_->IsControlGroup() &&
633 (prerendering_has_started() ||
634 match_complete_status() == MATCH_COMPLETE_REPLACEMENT)) {
635 NotifyPrerenderStop();
639 base::ProcessMetrics* PrerenderContents::MaybeGetProcessMetrics() {
640 if (process_metrics_.get() == NULL) {
641 // If a PrenderContents hasn't started prerending, don't be fully formed.
642 if (!GetRenderViewHost() || !GetRenderViewHost()->GetProcess())
643 return NULL;
644 base::ProcessHandle handle = GetRenderViewHost()->GetProcess()->GetHandle();
645 if (handle == base::kNullProcessHandle)
646 return NULL;
647 #if !defined(OS_MACOSX)
648 process_metrics_.reset(base::ProcessMetrics::CreateProcessMetrics(handle));
649 #else
650 process_metrics_.reset(base::ProcessMetrics::CreateProcessMetrics(
651 handle,
652 content::BrowserChildProcessHost::GetPortProvider()));
653 #endif
656 return process_metrics_.get();
659 void PrerenderContents::DestroyWhenUsingTooManyResources() {
660 base::ProcessMetrics* metrics = MaybeGetProcessMetrics();
661 if (metrics == NULL)
662 return;
664 size_t private_bytes, shared_bytes;
665 if (metrics->GetMemoryBytes(&private_bytes, &shared_bytes) &&
666 private_bytes > prerender_manager_->config().max_bytes) {
667 Destroy(FINAL_STATUS_MEMORY_LIMIT_EXCEEDED);
671 WebContents* PrerenderContents::ReleasePrerenderContents() {
672 prerender_contents_->SetDelegate(NULL);
673 content::WebContentsObserver::Observe(NULL);
674 return prerender_contents_.release();
677 RenderViewHost* PrerenderContents::GetRenderViewHostMutable() {
678 return const_cast<RenderViewHost*>(GetRenderViewHost());
681 const RenderViewHost* PrerenderContents::GetRenderViewHost() const {
682 if (!prerender_contents_.get())
683 return NULL;
684 return prerender_contents_->GetRenderViewHost();
687 void PrerenderContents::DidNavigate(
688 const history::HistoryAddPageArgs& add_page_args) {
689 add_page_vector_.push_back(add_page_args);
692 void PrerenderContents::CommitHistory(WebContents* tab) {
693 HistoryTabHelper* history_tab_helper = HistoryTabHelper::FromWebContents(tab);
694 for (size_t i = 0; i < add_page_vector_.size(); ++i)
695 history_tab_helper->UpdateHistoryForNavigation(add_page_vector_[i]);
698 base::Value* PrerenderContents::GetAsValue() const {
699 if (!prerender_contents_.get())
700 return NULL;
701 base::DictionaryValue* dict_value = new base::DictionaryValue();
702 dict_value->SetString("url", prerender_url_.spec());
703 base::TimeTicks current_time = base::TimeTicks::Now();
704 base::TimeDelta duration = current_time - load_start_time_;
705 dict_value->SetInteger("duration", duration.InSeconds());
706 dict_value->SetBoolean("is_loaded", prerender_contents_ &&
707 !prerender_contents_->IsLoading());
708 return dict_value;
711 bool PrerenderContents::IsCrossSiteNavigationPending() const {
712 if (!prerender_contents_)
713 return false;
714 return (prerender_contents_->GetSiteInstance() !=
715 prerender_contents_->GetPendingSiteInstance());
718 void PrerenderContents::PrepareForUse() {
719 SetFinalStatus(FINAL_STATUS_USED);
721 if (prerender_contents_.get()) {
722 prerender_contents_->SendToAllFrames(
723 new PrerenderMsg_SetIsPrerendering(MSG_ROUTING_NONE, false));
726 NotifyPrerenderStop();
728 BrowserThread::PostTask(
729 BrowserThread::IO,
730 FROM_HERE,
731 base::Bind(&ResumeThrottles, resource_throttles_));
732 resource_throttles_.clear();
735 void PrerenderContents::OnCancelPrerenderForPrinting() {
736 Destroy(FINAL_STATUS_WINDOW_PRINT);
739 void PrerenderContents::AddResourceThrottle(
740 const base::WeakPtr<PrerenderResourceThrottle>& throttle) {
741 resource_throttles_.push_back(throttle);
744 void PrerenderContents::AddNetworkBytes(int64 bytes) {
745 network_bytes_ += bytes;
748 } // namespace prerender