Home | History | Annotate | Download | only in prerender
      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:
     60     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 
    169   PrerenderManager* prerender_manager() { return prerender_manager_; }
    170 
    171   base::string16 title() const { return title_; }
    172   int32 page_id() const { return page_id_; }
    173   const GURL& prerender_url() const { return prerender_url_; }
    174   const content::Referrer& referrer() const { return referrer_; }
    175   bool has_stopped_loading() const { return has_stopped_loading_; }
    176   bool has_finished_loading() const { return has_finished_loading_; }
    177   bool prerendering_has_started() const { return prerendering_has_started_; }
    178   MatchCompleteStatus match_complete_status() const {
    179     return match_complete_status_;
    180   }
    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 
    193   FinalStatus final_status() const { return final_status_; }
    194 
    195   Origin origin() const { return origin_; }
    196   uint8 experiment_id() const { return experiment_id_; }
    197   int child_id() const { return child_id_; }
    198 
    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       int64 frame_id, content::RenderViewHost* render_view_host) OVERRIDE;
    214   virtual void DidStartProvisionalLoadForFrame(
    215       int64 frame_id,
    216       int64 parent_frame_id,
    217       bool is_main_frame,
    218       const GURL& validated_url,
    219       bool is_error_page,
    220       bool is_iframe_srcdoc,
    221       content::RenderViewHost* render_view_host) OVERRIDE;
    222   virtual void DidCommitProvisionalLoadForFrame(
    223       int64 frame_id,
    224       const base::string16& frame_unique_name,
    225       bool is_main_frame,
    226       const GURL& url,
    227       content::PageTransition transition_type,
    228       content::RenderViewHost* render_view_host) OVERRIDE;
    229   virtual void DidFinishLoad(
    230       int64 frame_id,
    231       const GURL& validated_url,
    232       bool is_main_frame,
    233       content::RenderViewHost* render_view_host) OVERRIDE;
    234   virtual void DidNavigateMainFrame(
    235       const content::LoadCommittedDetails& details,
    236       const content::FrameNavigateParams& params) OVERRIDE;
    237   virtual void DidGetRedirectForResourceRequest(
    238       content::RenderViewHost* render_view_host,
    239       const content::ResourceRedirectDetails& details) OVERRIDE;
    240   virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
    241 
    242   virtual void RenderProcessGone(base::TerminationStatus status) OVERRIDE;
    243 
    244   // content::NotificationObserver
    245   virtual void Observe(int type,
    246                        const content::NotificationSource& source,
    247                        const content::NotificationDetails& details) OVERRIDE;
    248 
    249   // Checks that a URL may be prerendered, for one of the many redirections. If
    250   // the URL can not be prerendered - for example, it's an ftp URL - |this| will
    251   // be destroyed and false is returned. Otherwise, true is returned.
    252   virtual bool CheckURL(const GURL& url);
    253 
    254   // Adds an alias URL. If the URL can not be prerendered, |this| will be
    255   // destroyed and false is returned.
    256   bool AddAliasURL(const GURL& url);
    257 
    258   // The prerender WebContents (may be NULL).
    259   content::WebContents* prerender_contents() const {
    260     return prerender_contents_.get();
    261   }
    262 
    263   content::WebContents* ReleasePrerenderContents();
    264 
    265   // Sets the final status, calls OnDestroy and adds |this| to the
    266   // PrerenderManager's pending deletes list.
    267   void Destroy(FinalStatus reason);
    268 
    269   // Called by the history tab helper with the information that it woudl have
    270   // added to the history service had this web contents not been used for
    271   // prerendering.
    272   void DidNavigate(const history::HistoryAddPageArgs& add_page_args);
    273 
    274   // Applies all the URL history encountered during prerendering to the
    275   // new tab.
    276   void CommitHistory(content::WebContents* tab);
    277 
    278   base::Value* GetAsValue() const;
    279 
    280   // Returns whether a pending cross-site navigation is happening.
    281   // This could happen with renderer-issued navigations, such as a
    282   // MouseEvent being dispatched by a link to a website installed as an app.
    283   bool IsCrossSiteNavigationPending() const;
    284 
    285   // Marks prerender as used and releases any throttled resource requests.
    286   void PrepareForUse();
    287 
    288   content::SessionStorageNamespace* GetSessionStorageNamespace() const;
    289 
    290   // Cookie events
    291   enum CookieEvent {
    292     COOKIE_EVENT_SEND = 0,
    293     COOKIE_EVENT_CHANGE = 1,
    294     COOKIE_EVENT_MAX
    295   };
    296 
    297   // Record a cookie transaction for this prerender contents.
    298   // In the event of cookies being sent, |earliest_create_date| contains
    299   // the time that the earliest of the cookies sent was created.
    300   void RecordCookieEvent(CookieEvent event,
    301                          bool is_main_frame_http_request,
    302                          bool is_third_party_cookie,
    303                          bool is_for_blocking_resource,
    304                          base::Time earliest_create_date);
    305 
    306   static const int kNumCookieStatuses;
    307   static const int kNumCookieSendTypes;
    308 
    309   // Called when a PrerenderResourceThrottle defers a request. If the prerender
    310   // is used it'll be resumed on the IO thread, otherwise they will get
    311   // cancelled automatically if prerendering is cancelled.
    312   void AddResourceThrottle(
    313       const base::WeakPtr<PrerenderResourceThrottle>& throttle);
    314 
    315   // Increments the number of bytes fetched over the network for this prerender.
    316   void AddNetworkBytes(int64 bytes);
    317 
    318  protected:
    319   PrerenderContents(PrerenderManager* prerender_manager,
    320                     Profile* profile,
    321                     const GURL& url,
    322                     const content::Referrer& referrer,
    323                     Origin origin,
    324                     uint8 experiment_id);
    325 
    326   // Set the final status for how the PrerenderContents was used. This
    327   // should only be called once, and should be called before the prerender
    328   // contents are destroyed.
    329   void SetFinalStatus(FinalStatus final_status);
    330 
    331   // These call out to methods on our Observers, using our observer_list_. Note
    332   // that NotifyPrerenderStop() also clears the observer list.
    333   void NotifyPrerenderStart();
    334   void NotifyPrerenderStopLoading();
    335   void NotifyPrerenderDomContentLoaded();
    336   void NotifyPrerenderStop();
    337   void NotifyPrerenderCreatedMatchCompleteReplacement(
    338       PrerenderContents* replacement);
    339 
    340   // Called whenever a RenderViewHost is created for prerendering.  Only called
    341   // once the RenderViewHost has a RenderView and RenderWidgetHostView.
    342   virtual void OnRenderViewHostCreated(
    343       content::RenderViewHost* new_render_view_host);
    344 
    345   content::NotificationRegistrar& notification_registrar() {
    346     return notification_registrar_;
    347   }
    348 
    349   bool prerendering_has_been_cancelled() const {
    350     return prerendering_has_been_cancelled_;
    351   }
    352 
    353   content::WebContents* CreateWebContents(
    354       content::SessionStorageNamespace* session_storage_namespace);
    355 
    356   bool prerendering_has_started_;
    357 
    358   // Time at which we started to load the URL.  This is used to compute
    359   // the time elapsed from initiating a prerender until the time the
    360   // (potentially only partially) prerendered page is shown to the user.
    361   base::TimeTicks load_start_time_;
    362 
    363   // The prerendered WebContents; may be null.
    364   scoped_ptr<content::WebContents> prerender_contents_;
    365 
    366   // The session storage namespace id for use in matching. We must save it
    367   // rather than get it from the RenderViewHost since in the control group
    368   // we won't have a RenderViewHost.
    369   int64 session_storage_namespace_id_;
    370 
    371   // The time at which we started prerendering, for the purpose of comparing
    372   // cookie creation times.
    373   base::Time start_time_;
    374 
    375  private:
    376   class WebContentsDelegateImpl;
    377 
    378   // Needs to be able to call the constructor.
    379   friend class PrerenderContentsFactoryImpl;
    380 
    381   // Returns the ProcessMetrics for the render process, if it exists.
    382   base::ProcessMetrics* MaybeGetProcessMetrics();
    383 
    384   // Message handlers.
    385   void OnCancelPrerenderForPrinting();
    386 
    387   ObserverList<Observer> observer_list_;
    388 
    389   // The prerender manager owning this object.
    390   PrerenderManager* prerender_manager_;
    391 
    392   // The URL being prerendered.
    393   GURL prerender_url_;
    394 
    395   // The referrer.
    396   content::Referrer referrer_;
    397 
    398   // The profile being used
    399   Profile* profile_;
    400 
    401   // Information about the title and URL of the page that this class as a
    402   // RenderViewHostDelegate has received from the RenderView.
    403   // Used to apply to the new RenderViewHost delegate that might eventually
    404   // own the contained RenderViewHost when the prerendered page is shown
    405   // in a WebContents.
    406   base::string16 title_;
    407   int32 page_id_;
    408   GURL url_;
    409   content::NotificationRegistrar notification_registrar_;
    410 
    411   // A vector of URLs that this prerendered page matches against.
    412   // This array can contain more than element as a result of redirects,
    413   // such as HTTP redirects or javascript redirects.
    414   std::vector<GURL> alias_urls_;
    415 
    416   bool has_stopped_loading_;
    417 
    418   // True when the main frame has finished loading.
    419   bool has_finished_loading_;
    420 
    421   // This must be the same value as the PrerenderTracker has recorded for
    422   // |this|, when |this| has a RenderView.
    423   FinalStatus final_status_;
    424 
    425   // The MatchComplete status of the prerender, indicating how it relates
    426   // to being a MatchComplete dummy (see definition of MatchCompleteStatus
    427   // above).
    428   MatchCompleteStatus match_complete_status_;
    429 
    430   // Tracks whether or not prerendering has been cancelled by calling Destroy.
    431   // Used solely to prevent double deletion.
    432   bool prerendering_has_been_cancelled_;
    433 
    434   // Process Metrics of the render process associated with the
    435   // RenderViewHost for this object.
    436   scoped_ptr<base::ProcessMetrics> process_metrics_;
    437 
    438   scoped_ptr<WebContentsDelegateImpl> web_contents_delegate_;
    439 
    440   // These are -1 before a RenderView is created.
    441   int child_id_;
    442   int route_id_;
    443 
    444   // Origin for this prerender.
    445   Origin origin_;
    446 
    447   // Experiment during which this prerender is performed.
    448   uint8 experiment_id_;
    449 
    450   // The process that created the child id.
    451   int creator_child_id_;
    452 
    453   // Main frame ID of last committed page.
    454   int64 main_frame_id_;
    455 
    456   // The size of the WebView from the launching page.
    457   gfx::Size size_;
    458 
    459   typedef std::vector<history::HistoryAddPageArgs> AddPageVector;
    460 
    461   // Caches pages to be added to the history.
    462   AddPageVector add_page_vector_;
    463 
    464   // The alias session storage namespace for this prerender.
    465   scoped_refptr<content::SessionStorageNamespace>
    466       alias_session_storage_namespace;
    467 
    468   // Indicates what internal cookie events (see prerender_contents.cc) have
    469   // occurred, using 1 bit for each possible InternalCookieEvent.
    470   int cookie_status_;
    471 
    472   // Indicates whether existing cookies were sent for this prerender, and
    473   // whether they were third-party cookies, and whether they were for blocking
    474   // resources. See the enum CookieSendType in prerender_contents.cc
    475   int cookie_send_type_;
    476 
    477   // Resources that are throttled, pending a prerender use. Can only access a
    478   // throttle on the IO thread.
    479   std::vector<base::WeakPtr<PrerenderResourceThrottle> > resource_throttles_;
    480 
    481   // A running tally of the number of bytes this prerender has caused to be
    482   // transferred over the network for resources.  Updated with AddNetworkBytes.
    483   int64 network_bytes_;
    484 
    485   DISALLOW_COPY_AND_ASSIGN(PrerenderContents);
    486 };
    487 
    488 }  // namespace prerender
    489 
    490 #endif  // CHROME_BROWSER_PRERENDER_PRERENDER_CONTENTS_H_
    491