• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
4 
5 #ifndef CHROME_BROWSER_PRERENDER_PRERENDER_CONTENTS_H_
6 #define CHROME_BROWSER_PRERENDER_PRERENDER_CONTENTS_H_
7 
8 #include <string>
9 #include <utility>
10 #include <vector>
11 
12 #include "base/memory/scoped_ptr.h"
13 #include "base/memory/scoped_vector.h"
14 #include "base/memory/weak_ptr.h"
15 #include "base/observer_list.h"
16 #include "base/time/time.h"
17 #include "base/values.h"
18 #include "chrome/browser/prerender/prerender_final_status.h"
19 #include "chrome/browser/prerender/prerender_origin.h"
20 #include "content/public/browser/notification_observer.h"
21 #include "content/public/browser/notification_registrar.h"
22 #include "content/public/browser/web_contents_observer.h"
23 #include "content/public/common/referrer.h"
24 #include "ui/gfx/size.h"
25 
26 class Profile;
27 
28 namespace base {
29 class ProcessMetrics;
30 }
31 
32 namespace content {
33 class RenderViewHost;
34 class SessionStorageNamespace;
35 class WebContents;
36 }
37 
38 namespace history {
39 struct HistoryAddPageArgs;
40 }
41 
42 namespace net {
43 class URLRequestContextGetter;
44 }
45 
46 namespace prerender {
47 
48 class PrerenderHandle;
49 class PrerenderManager;
50 class PrerenderResourceThrottle;
51 
52 class PrerenderContents : public content::NotificationObserver,
53                           public content::WebContentsObserver,
54                           public base::SupportsWeakPtr<PrerenderContents> {
55  public:
56   // PrerenderContents::Create uses the currently registered Factory to create
57   // the PrerenderContents. Factory is intended for testing.
58   class Factory {
59    public:
Factory()60     Factory() {}
~Factory()61     virtual ~Factory() {}
62 
63     // Ownership is not transfered through this interface as prerender_manager,
64     // prerender_tracker, and profile are stored as weak pointers.
65     virtual PrerenderContents* CreatePrerenderContents(
66         PrerenderManager* prerender_manager,
67         Profile* profile,
68         const GURL& url,
69         const content::Referrer& referrer,
70         Origin origin,
71         uint8 experiment_id) = 0;
72 
73    private:
74     DISALLOW_COPY_AND_ASSIGN(Factory);
75   };
76 
77   class Observer {
78    public:
79     // Signals that the prerender has started running.
80     virtual void OnPrerenderStart(PrerenderContents* contents) = 0;
81 
82     // Signals that the prerender has had its load event.
83     virtual void OnPrerenderStopLoading(PrerenderContents* contents);
84 
85     // Signals that the prerender has had its 'DOMContentLoaded' event.
86     virtual void OnPrerenderDomContentLoaded(PrerenderContents* contents);
87 
88     // Signals that the prerender has stopped running. A PrerenderContents with
89     // an unset final status will always call OnPrerenderStop before being
90     // destroyed.
91     virtual void OnPrerenderStop(PrerenderContents* contents) = 0;
92 
93     // Signals that this prerender has just become a MatchComplete replacement.
94     virtual void OnPrerenderCreatedMatchCompleteReplacement(
95         PrerenderContents* contents, PrerenderContents* replacement);
96 
97    protected:
98     Observer();
99     virtual ~Observer() = 0;
100   };
101 
102   // Indicates how this PrerenderContents relates to MatchComplete. This is to
103   // figure out which histograms to use to record the FinalStatus, Match (record
104   // all prerenders and control group prerenders) or MatchComplete (record
105   // running prerenders only in the way they would have been recorded in the
106   // control group).
107   enum MatchCompleteStatus {
108     // A regular prerender which will be recorded both in Match and
109     // MatchComplete.
110     MATCH_COMPLETE_DEFAULT,
111     // A prerender that used to be a regular prerender, but has since been
112     // replaced by a MatchComplete dummy. Therefore, we will record this only
113     // for Match, but not for MatchComplete.
114     MATCH_COMPLETE_REPLACED,
115     // A prerender that is a MatchComplete dummy replacing a regular prerender.
116     // In the control group, our prerender never would have been canceled, so
117     // we record in MatchComplete but not Match.
118     MATCH_COMPLETE_REPLACEMENT,
119     // A prerender that is a MatchComplete dummy, early in the process of being
120     // created. This prerender should not fail. Record for MatchComplete, but
121     // not Match.
122     MATCH_COMPLETE_REPLACEMENT_PENDING,
123   };
124 
125   virtual ~PrerenderContents();
126 
127   // All observers of a PrerenderContents are removed after the OnPrerenderStop
128   // event is sent, so there is no need to call RemoveObserver() in the normal
129   // use case.
130   void AddObserver(Observer* observer);
131   void RemoveObserver(Observer* observer);
132 
133   // For MatchComplete correctness, create a dummy replacement prerender
134   // contents to stand in for this prerender contents that (which we are about
135   // to destroy).
136   PrerenderContents* CreateMatchCompleteReplacement();
137 
138   bool Init();
139 
140   static Factory* CreateFactory();
141 
142   // Returns a PrerenderContents from the given web_contents, if it's used for
143   // prerendering. Otherwise returns NULL. Handles a NULL input for
144   // convenience.
145   static PrerenderContents* FromWebContents(content::WebContents* web_contents);
146 
147   // Start rendering the contents in the prerendered state. If
148   // |is_control_group| is true, this will go through some of the mechanics of
149   // starting a prerender, without actually creating the RenderView.
150   // |creator_child_id| is the id of the child process that caused the prerender
151   // to be created, and is needed so that the prerendered URLs can be sent to it
152   // so render-initiated navigations will swap in the prerendered page. |size|
153   // indicates the rectangular dimensions that the prerendered page should be.
154   // |session_storage_namespace| indicates the namespace that the prerendered
155   // page should be part of.
156   virtual void StartPrerendering(
157       int creator_child_id,
158       const gfx::Size& size,
159       content::SessionStorageNamespace* session_storage_namespace,
160       net::URLRequestContextGetter* request_context);
161 
162   // Verifies that the prerendering is not using too many resources, and kills
163   // it if not.
164   void DestroyWhenUsingTooManyResources();
165 
166   content::RenderViewHost* GetRenderViewHostMutable();
167   const content::RenderViewHost* GetRenderViewHost() const;
168 
prerender_manager()169   PrerenderManager* prerender_manager() { return prerender_manager_; }
170 
title()171   base::string16 title() const { return title_; }
page_id()172   int32 page_id() const { return page_id_; }
prerender_url()173   const GURL& prerender_url() const { return prerender_url_; }
referrer()174   const content::Referrer& referrer() const { return referrer_; }
has_stopped_loading()175   bool has_stopped_loading() const { return has_stopped_loading_; }
has_finished_loading()176   bool has_finished_loading() const { return has_finished_loading_; }
prerendering_has_started()177   bool prerendering_has_started() const { return prerendering_has_started_; }
match_complete_status()178   MatchCompleteStatus match_complete_status() const {
179     return match_complete_status_;
180   }
set_match_complete_status(MatchCompleteStatus status)181   void set_match_complete_status(MatchCompleteStatus status) {
182     match_complete_status_ = status;
183   }
184 
185   // Sets the parameter to the value of the associated RenderViewHost's child id
186   // and returns a boolean indicating the validity of that id.
187   virtual bool GetChildId(int* child_id) const;
188 
189   // Sets the parameter to the value of the associated RenderViewHost's route id
190   // and returns a boolean indicating the validity of that id.
191   virtual bool GetRouteId(int* route_id) const;
192 
final_status()193   FinalStatus final_status() const { return final_status_; }
194 
origin()195   Origin origin() const { return origin_; }
experiment_id()196   uint8 experiment_id() const { return experiment_id_; }
child_id()197   int child_id() const { return child_id_; }
198 
load_start_time()199   base::TimeTicks load_start_time() const { return load_start_time_; }
200 
201   // Indicates whether this prerendered page can be used for the provided
202   // |url| and |session_storage_namespace|.
203   bool Matches(
204       const GURL& url,
205       const content::SessionStorageNamespace* session_storage_namespace) const;
206 
207   // content::WebContentsObserver implementation.
208   virtual void RenderFrameCreated(
209       content::RenderFrameHost* render_frame_host) OVERRIDE;
210   virtual void DidStopLoading(
211       content::RenderViewHost* render_view_host) OVERRIDE;
212   virtual void DocumentLoadedInFrame(
213       content::RenderFrameHost* render_frame_host) OVERRIDE;
214   virtual void DidStartProvisionalLoadForFrame(
215       content::RenderFrameHost* render_frame_host,
216       const GURL& validated_url,
217       bool is_error_page,
218       bool is_iframe_srcdoc) OVERRIDE;
219   virtual void DidFinishLoad(content::RenderFrameHost* render_frame_host,
220                              const GURL& validated_url) OVERRIDE;
221   virtual void DidNavigateMainFrame(
222       const content::LoadCommittedDetails& details,
223       const content::FrameNavigateParams& params) OVERRIDE;
224   virtual void DidGetRedirectForResourceRequest(
225       content::RenderViewHost* render_view_host,
226       const content::ResourceRedirectDetails& details) OVERRIDE;
227   virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
228 
229   virtual void RenderProcessGone(base::TerminationStatus status) OVERRIDE;
230 
231   // content::NotificationObserver
232   virtual void Observe(int type,
233                        const content::NotificationSource& source,
234                        const content::NotificationDetails& details) OVERRIDE;
235 
236   // Checks that a URL may be prerendered, for one of the many redirections. If
237   // the URL can not be prerendered - for example, it's an ftp URL - |this| will
238   // be destroyed and false is returned. Otherwise, true is returned.
239   virtual bool CheckURL(const GURL& url);
240 
241   // Adds an alias URL. If the URL can not be prerendered, |this| will be
242   // destroyed and false is returned.
243   bool AddAliasURL(const GURL& url);
244 
245   // The prerender WebContents (may be NULL).
prerender_contents()246   content::WebContents* prerender_contents() const {
247     return prerender_contents_.get();
248   }
249 
250   content::WebContents* ReleasePrerenderContents();
251 
252   // Sets the final status, calls OnDestroy and adds |this| to the
253   // PrerenderManager's pending deletes list.
254   void Destroy(FinalStatus reason);
255 
256   // Called by the history tab helper with the information that it woudl have
257   // added to the history service had this web contents not been used for
258   // prerendering.
259   void DidNavigate(const history::HistoryAddPageArgs& add_page_args);
260 
261   // Applies all the URL history encountered during prerendering to the
262   // new tab.
263   void CommitHistory(content::WebContents* tab);
264 
265   base::Value* GetAsValue() const;
266 
267   // Returns whether a pending cross-site navigation is happening.
268   // This could happen with renderer-issued navigations, such as a
269   // MouseEvent being dispatched by a link to a website installed as an app.
270   bool IsCrossSiteNavigationPending() const;
271 
272   // Marks prerender as used and releases any throttled resource requests.
273   void PrepareForUse();
274 
275   content::SessionStorageNamespace* GetSessionStorageNamespace() const;
276 
277   // Cookie events
278   enum CookieEvent {
279     COOKIE_EVENT_SEND = 0,
280     COOKIE_EVENT_CHANGE = 1,
281     COOKIE_EVENT_MAX
282   };
283 
284   // Record a cookie transaction for this prerender contents.
285   // In the event of cookies being sent, |earliest_create_date| contains
286   // the time that the earliest of the cookies sent was created.
287   void RecordCookieEvent(CookieEvent event,
288                          bool is_main_frame_http_request,
289                          bool is_third_party_cookie,
290                          bool is_for_blocking_resource,
291                          base::Time earliest_create_date);
292 
293   static const int kNumCookieStatuses;
294   static const int kNumCookieSendTypes;
295 
296   // Called when a PrerenderResourceThrottle defers a request. If the prerender
297   // is used it'll be resumed on the IO thread, otherwise they will get
298   // cancelled automatically if prerendering is cancelled.
299   void AddResourceThrottle(
300       const base::WeakPtr<PrerenderResourceThrottle>& throttle);
301 
302   // Increments the number of bytes fetched over the network for this prerender.
303   void AddNetworkBytes(int64 bytes);
304 
305  protected:
306   PrerenderContents(PrerenderManager* prerender_manager,
307                     Profile* profile,
308                     const GURL& url,
309                     const content::Referrer& referrer,
310                     Origin origin,
311                     uint8 experiment_id);
312 
313   // Set the final status for how the PrerenderContents was used. This
314   // should only be called once, and should be called before the prerender
315   // contents are destroyed.
316   void SetFinalStatus(FinalStatus final_status);
317 
318   // These call out to methods on our Observers, using our observer_list_. Note
319   // that NotifyPrerenderStop() also clears the observer list.
320   void NotifyPrerenderStart();
321   void NotifyPrerenderStopLoading();
322   void NotifyPrerenderDomContentLoaded();
323   void NotifyPrerenderStop();
324   void NotifyPrerenderCreatedMatchCompleteReplacement(
325       PrerenderContents* replacement);
326 
327   // Called whenever a RenderViewHost is created for prerendering.  Only called
328   // once the RenderViewHost has a RenderView and RenderWidgetHostView.
329   virtual void OnRenderViewHostCreated(
330       content::RenderViewHost* new_render_view_host);
331 
notification_registrar()332   content::NotificationRegistrar& notification_registrar() {
333     return notification_registrar_;
334   }
335 
prerendering_has_been_cancelled()336   bool prerendering_has_been_cancelled() const {
337     return prerendering_has_been_cancelled_;
338   }
339 
340   content::WebContents* CreateWebContents(
341       content::SessionStorageNamespace* session_storage_namespace);
342 
343   bool prerendering_has_started_;
344 
345   // Time at which we started to load the URL.  This is used to compute
346   // the time elapsed from initiating a prerender until the time the
347   // (potentially only partially) prerendered page is shown to the user.
348   base::TimeTicks load_start_time_;
349 
350   // The prerendered WebContents; may be null.
351   scoped_ptr<content::WebContents> prerender_contents_;
352 
353   // The session storage namespace id for use in matching. We must save it
354   // rather than get it from the RenderViewHost since in the control group
355   // we won't have a RenderViewHost.
356   int64 session_storage_namespace_id_;
357 
358   // The time at which we started prerendering, for the purpose of comparing
359   // cookie creation times.
360   base::Time start_time_;
361 
362  private:
363   class WebContentsDelegateImpl;
364 
365   // Needs to be able to call the constructor.
366   friend class PrerenderContentsFactoryImpl;
367 
368   // Returns the ProcessMetrics for the render process, if it exists.
369   base::ProcessMetrics* MaybeGetProcessMetrics();
370 
371   // Message handlers.
372   void OnCancelPrerenderForPrinting();
373 
374   ObserverList<Observer> observer_list_;
375 
376   // The prerender manager owning this object.
377   PrerenderManager* prerender_manager_;
378 
379   // The URL being prerendered.
380   GURL prerender_url_;
381 
382   // The referrer.
383   content::Referrer referrer_;
384 
385   // The profile being used
386   Profile* profile_;
387 
388   // Information about the title and URL of the page that this class as a
389   // RenderViewHostDelegate has received from the RenderView.
390   // Used to apply to the new RenderViewHost delegate that might eventually
391   // own the contained RenderViewHost when the prerendered page is shown
392   // in a WebContents.
393   base::string16 title_;
394   int32 page_id_;
395   GURL url_;
396   content::NotificationRegistrar notification_registrar_;
397 
398   // A vector of URLs that this prerendered page matches against.
399   // This array can contain more than element as a result of redirects,
400   // such as HTTP redirects or javascript redirects.
401   std::vector<GURL> alias_urls_;
402 
403   bool has_stopped_loading_;
404 
405   // True when the main frame has finished loading.
406   bool has_finished_loading_;
407 
408   // This must be the same value as the PrerenderTracker has recorded for
409   // |this|, when |this| has a RenderView.
410   FinalStatus final_status_;
411 
412   // The MatchComplete status of the prerender, indicating how it relates
413   // to being a MatchComplete dummy (see definition of MatchCompleteStatus
414   // above).
415   MatchCompleteStatus match_complete_status_;
416 
417   // Tracks whether or not prerendering has been cancelled by calling Destroy.
418   // Used solely to prevent double deletion.
419   bool prerendering_has_been_cancelled_;
420 
421   // Process Metrics of the render process associated with the
422   // RenderViewHost for this object.
423   scoped_ptr<base::ProcessMetrics> process_metrics_;
424 
425   scoped_ptr<WebContentsDelegateImpl> web_contents_delegate_;
426 
427   // These are -1 before a RenderView is created.
428   int child_id_;
429   int route_id_;
430 
431   // Origin for this prerender.
432   Origin origin_;
433 
434   // Experiment during which this prerender is performed.
435   uint8 experiment_id_;
436 
437   // The process that created the child id.
438   int creator_child_id_;
439 
440   // The size of the WebView from the launching page.
441   gfx::Size size_;
442 
443   typedef std::vector<history::HistoryAddPageArgs> AddPageVector;
444 
445   // Caches pages to be added to the history.
446   AddPageVector add_page_vector_;
447 
448   // The alias session storage namespace for this prerender.
449   scoped_refptr<content::SessionStorageNamespace>
450       alias_session_storage_namespace;
451 
452   // Indicates what internal cookie events (see prerender_contents.cc) have
453   // occurred, using 1 bit for each possible InternalCookieEvent.
454   int cookie_status_;
455 
456   // Indicates whether existing cookies were sent for this prerender, and
457   // whether they were third-party cookies, and whether they were for blocking
458   // resources. See the enum CookieSendType in prerender_contents.cc
459   int cookie_send_type_;
460 
461   // Resources that are throttled, pending a prerender use. Can only access a
462   // throttle on the IO thread.
463   std::vector<base::WeakPtr<PrerenderResourceThrottle> > resource_throttles_;
464 
465   // A running tally of the number of bytes this prerender has caused to be
466   // transferred over the network for resources.  Updated with AddNetworkBytes.
467   int64 network_bytes_;
468 
469   DISALLOW_COPY_AND_ASSIGN(PrerenderContents);
470 };
471 
472 }  // namespace prerender
473 
474 #endif  // CHROME_BROWSER_PRERENDER_PRERENDER_CONTENTS_H_
475