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 struct FaviconURL;
     34 class RenderViewHost;
     35 class SessionStorageNamespace;
     36 class WebContents;
     37 }
     38 
     39 namespace history {
     40 struct HistoryAddPageArgs;
     41 }
     42 
     43 namespace prerender {
     44 
     45 class PrerenderHandle;
     46 class PrerenderManager;
     47 class PrerenderRenderViewHostObserver;
     48 
     49 class PrerenderContents : public content::NotificationObserver,
     50                           public content::WebContentsObserver {
     51  public:
     52   // PrerenderContents::Create uses the currently registered Factory to create
     53   // the PrerenderContents. Factory is intended for testing.
     54   class Factory {
     55    public:
     56     Factory() {}
     57     virtual ~Factory() {}
     58 
     59     // Ownership is not transfered through this interface as prerender_manager,
     60     // prerender_tracker, and profile are stored as weak pointers.
     61     virtual PrerenderContents* CreatePrerenderContents(
     62         PrerenderManager* prerender_manager,
     63         Profile* profile,
     64         const GURL& url,
     65         const content::Referrer& referrer,
     66         Origin origin,
     67         uint8 experiment_id) = 0;
     68 
     69    private:
     70     DISALLOW_COPY_AND_ASSIGN(Factory);
     71   };
     72 
     73   class Observer {
     74    public:
     75     // Signals that the prerender has started running.
     76     virtual void OnPrerenderStart(PrerenderContents* contents) = 0;
     77 
     78     // Signals that the prerender has had its load event.
     79     virtual void OnPrerenderStopLoading(PrerenderContents* contents);
     80 
     81     // Signals that the prerender has stopped running.
     82     virtual void OnPrerenderStop(PrerenderContents* contents) = 0;
     83 
     84     // Signals that this prerender has just become a MatchComplete replacement.
     85     virtual void OnPrerenderCreatedMatchCompleteReplacement(
     86         PrerenderContents* contents, PrerenderContents* replacement);
     87 
     88    protected:
     89     Observer();
     90     virtual ~Observer() = 0;
     91   };
     92 
     93   // A container for extra data on pending prerenders.
     94   struct PendingPrerenderInfo {
     95    public:
     96     PendingPrerenderInfo(
     97         base::WeakPtr<PrerenderHandle> weak_prerender_handle,
     98         Origin origin,
     99         const GURL& url,
    100         const content::Referrer& referrer,
    101         const gfx::Size& size);
    102 
    103     ~PendingPrerenderInfo();
    104 
    105     base::WeakPtr<PrerenderHandle> weak_prerender_handle;
    106     Origin origin;
    107     GURL url;
    108     content::Referrer referrer;
    109     gfx::Size size;
    110   };
    111 
    112   // Indicates how this PrerenderContents relates to MatchComplete. This is to
    113   // figure out which histograms to use to record the FinalStatus, Match (record
    114   // all prerenders and control group prerenders) or MatchComplete (record
    115   // running prerenders only in the way they would have been recorded in the
    116   // control group).
    117   enum MatchCompleteStatus {
    118     // A regular prerender which will be recorded both in Match and
    119     // MatchComplete.
    120     MATCH_COMPLETE_DEFAULT,
    121     // A prerender that used to be a regular prerender, but has since been
    122     // replaced by a MatchComplete dummy. Therefore, we will record this only
    123     // for Match, but not for MatchComplete.
    124     MATCH_COMPLETE_REPLACED,
    125     // A prerender that is a MatchComplete dummy replacing a regular prerender.
    126     // In the control group, our prerender never would have been canceled, so
    127     // we record in MatchComplete but not Match.
    128     MATCH_COMPLETE_REPLACEMENT,
    129     // A prerender that is a MatchComplete dummy, early in the process of being
    130     // created. This prerender should not fail. Record for MatchComplete, but
    131     // not Match.
    132     MATCH_COMPLETE_REPLACEMENT_PENDING,
    133   };
    134 
    135   virtual ~PrerenderContents();
    136 
    137   // All observers of a PrerenderContents are removed after the OnPrerenderStop
    138   // event is sent, so there is no need to call RemoveObserver() in the normal
    139   // use case.
    140   void AddObserver(Observer* observer);
    141   void RemoveObserver(Observer* observer);
    142 
    143   // For MatchComplete correctness, create a dummy replacement prerender
    144   // contents to stand in for this prerender contents that (which we are about
    145   // to destroy).
    146   PrerenderContents* CreateMatchCompleteReplacement();
    147 
    148   bool Init();
    149 
    150   static Factory* CreateFactory();
    151 
    152   // Start rendering the contents in the prerendered state. If
    153   // |is_control_group| is true, this will go through some of the mechanics of
    154   // starting a prerender, without actually creating the RenderView.
    155   // |creator_child_id| is the id of the child process that caused the prerender
    156   // to be created, and is needed so that the prerendered URLs can be sent to it
    157   // so render-initiated navigations will swap in the prerendered page. |size|
    158   // indicates the rectangular dimensions that the prerendered page should be.
    159   // |session_storage_namespace| indicates the namespace that the prerendered
    160   // page should be part of.
    161   virtual void StartPrerendering(
    162       int creator_child_id,
    163       const gfx::Size& size,
    164       content::SessionStorageNamespace* session_storage_namespace);
    165 
    166   // Verifies that the prerendering is not using too many resources, and kills
    167   // it if not.
    168   void DestroyWhenUsingTooManyResources();
    169 
    170   content::RenderViewHost* GetRenderViewHostMutable();
    171   const content::RenderViewHost* GetRenderViewHost() const;
    172 
    173   PrerenderManager* prerender_manager() { return prerender_manager_; }
    174 
    175   string16 title() const { return title_; }
    176   int32 page_id() const { return page_id_; }
    177   GURL icon_url() const { return icon_url_; }
    178   const GURL& prerender_url() const { return prerender_url_; }
    179   const content::Referrer& referrer() const { return referrer_; }
    180   bool has_stopped_loading() const { return has_stopped_loading_; }
    181   bool has_finished_loading() const { return has_finished_loading_; }
    182   bool prerendering_has_started() const { return prerendering_has_started_; }
    183   MatchCompleteStatus match_complete_status() const {
    184     return match_complete_status_;
    185   }
    186   void set_match_complete_status(MatchCompleteStatus status) {
    187     match_complete_status_ = status;
    188   }
    189 
    190   // Sets the parameter to the value of the associated RenderViewHost's child id
    191   // and returns a boolean indicating the validity of that id.
    192   virtual bool GetChildId(int* child_id) const;
    193 
    194   // Sets the parameter to the value of the associated RenderViewHost's route id
    195   // and returns a boolean indicating the validity of that id.
    196   virtual bool GetRouteId(int* route_id) const;
    197 
    198   // Set the final status for how the PrerenderContents was used. This
    199   // should only be called once, and should be called before the prerender
    200   // contents are destroyed.
    201   void SetFinalStatus(FinalStatus final_status);
    202   FinalStatus final_status() const { return final_status_; }
    203 
    204   Origin origin() const { return origin_; }
    205   uint8 experiment_id() const { return experiment_id_; }
    206 
    207   base::TimeTicks load_start_time() const { return load_start_time_; }
    208 
    209   // Indicates whether this prerendered page can be used for the provided
    210   // |url| and |session_storage_namespace|.
    211   bool Matches(
    212       const GURL& url,
    213       const content::SessionStorageNamespace* session_storage_namespace) const;
    214 
    215   // content::WebContentsObserver implementation.
    216   virtual void DidStopLoading(
    217       content::RenderViewHost* render_view_host) OVERRIDE;
    218   virtual void DidStartProvisionalLoadForFrame(
    219       int64 frame_id,
    220       int64 parent_frame_id,
    221       bool is_main_frame,
    222       const GURL& validated_url,
    223       bool is_error_page,
    224       bool is_iframe_srcdoc,
    225       content::RenderViewHost* render_view_host) OVERRIDE;
    226   virtual void DidFinishLoad(
    227       int64 frame_id,
    228       const GURL& validated_url,
    229       bool is_main_frame,
    230       content::RenderViewHost* render_view_host) OVERRIDE;
    231   virtual void DidUpdateFaviconURL(int32 page_id,
    232       const std::vector<content::FaviconURL>& urls) OVERRIDE;
    233 
    234   virtual void RenderProcessGone(base::TerminationStatus status) OVERRIDE;
    235 
    236   // content::NotificationObserver
    237   virtual void Observe(int type,
    238                        const content::NotificationSource& source,
    239                        const content::NotificationDetails& details) OVERRIDE;
    240 
    241   // Adds an alias URL, for one of the many redirections. If the URL can not
    242   // be prerendered - for example, it's an ftp URL - |this| will be destroyed
    243   // and false is returned. Otherwise, true is returned and the alias is
    244   // remembered.
    245   virtual bool AddAliasURL(const GURL& url);
    246 
    247   // The prerender WebContents (may be NULL).
    248   content::WebContents* prerender_contents() const {
    249     return prerender_contents_.get();
    250   }
    251 
    252   content::WebContents* ReleasePrerenderContents();
    253 
    254   // Sets the final status, calls OnDestroy and adds |this| to the
    255   // PrerenderManager's pending deletes list.
    256   void Destroy(FinalStatus reason);
    257 
    258   // Called by the history tab helper with the information that it woudl have
    259   // added to the history service had this web contents not been used for
    260   // prerendering.
    261   void DidNavigate(const history::HistoryAddPageArgs& add_page_args);
    262 
    263   // Applies all the URL history encountered during prerendering to the
    264   // new tab.
    265   void CommitHistory(content::WebContents* tab);
    266 
    267   base::Value* GetAsValue() const;
    268 
    269   // Returns whether a pending cross-site navigation is happening.
    270   // This could happen with renderer-issued navigations, such as a
    271   // MouseEvent being dispatched by a link to a website installed as an app.
    272   bool IsCrossSiteNavigationPending() const;
    273 
    274   // Adds a pending prerender to the list. If |weak_prerender_handle| still
    275   // exists when this page is made visible, it will be launched.
    276   virtual void AddPendingPrerender(
    277       scoped_ptr<PendingPrerenderInfo> pending_prerender_info);
    278 
    279   // Reissues any pending prerender requests from the prerendered page.  Also
    280   // clears the list of pending requests. Sends notifications.
    281   void PrepareForUse();
    282 
    283  protected:
    284   PrerenderContents(PrerenderManager* prerender_manager,
    285                     Profile* profile,
    286                     const GURL& url,
    287                     const content::Referrer& referrer,
    288                     Origin origin,
    289                     uint8 experiment_id);
    290 
    291   // These call out to methods on our Observers, using our observer_list_. Note
    292   // that NotifyPrerenderStop() also clears the observer list.
    293   void NotifyPrerenderStart();
    294   void NotifyPrerenderStopLoading();
    295   void NotifyPrerenderStop();
    296   void NotifyPrerenderCreatedMatchCompleteReplacement(
    297       PrerenderContents* replacement);
    298 
    299   // Called whenever a RenderViewHost is created for prerendering.  Only called
    300   // once the RenderViewHost has a RenderView and RenderWidgetHostView.
    301   virtual void OnRenderViewHostCreated(
    302       content::RenderViewHost* new_render_view_host);
    303 
    304   content::NotificationRegistrar& notification_registrar() {
    305     return notification_registrar_;
    306   }
    307 
    308   size_t pending_prerender_count() const;
    309 
    310   bool prerendering_has_been_cancelled() const {
    311     return prerendering_has_been_cancelled_;
    312   }
    313 
    314   virtual content::WebContents* CreateWebContents(
    315       content::SessionStorageNamespace* session_storage_namespace);
    316 
    317   bool prerendering_has_started_;
    318 
    319   // Time at which we started to load the URL.  This is used to compute
    320   // the time elapsed from initiating a prerender until the time the
    321   // (potentially only partially) prerendered page is shown to the user.
    322   base::TimeTicks load_start_time_;
    323 
    324  private:
    325   class WebContentsDelegateImpl;
    326 
    327   // Needs to be able to call the constructor.
    328   friend class PrerenderContentsFactoryImpl;
    329 
    330   friend class PrerenderRenderViewHostObserver;
    331 
    332   // Returns the ProcessMetrics for the render process, if it exists.
    333   base::ProcessMetrics* MaybeGetProcessMetrics();
    334 
    335   ObserverList<Observer> observer_list_;
    336 
    337   // The prerender manager owning this object.
    338   PrerenderManager* prerender_manager_;
    339 
    340   // The URL being prerendered.
    341   GURL prerender_url_;
    342 
    343   // The referrer.
    344   content::Referrer referrer_;
    345 
    346   // The profile being used
    347   Profile* profile_;
    348 
    349   // Information about the title and URL of the page that this class as a
    350   // RenderViewHostDelegate has received from the RenderView.
    351   // Used to apply to the new RenderViewHost delegate that might eventually
    352   // own the contained RenderViewHost when the prerendered page is shown
    353   // in a WebContents.
    354   string16 title_;
    355   int32 page_id_;
    356   GURL url_;
    357   GURL icon_url_;
    358   content::NotificationRegistrar notification_registrar_;
    359 
    360   // A vector of URLs that this prerendered page matches against.
    361   // This array can contain more than element as a result of redirects,
    362   // such as HTTP redirects or javascript redirects.
    363   std::vector<GURL> alias_urls_;
    364 
    365   // The session storage namespace id for use in matching. We must save it
    366   // rather than get it from the RenderViewHost since in the control group
    367   // we won't have a RenderViewHost.
    368   int64 session_storage_namespace_id_;
    369 
    370   bool has_stopped_loading_;
    371 
    372   // True when the main frame has finished loading.
    373   bool has_finished_loading_;
    374 
    375   // This must be the same value as the PrerenderTracker has recorded for
    376   // |this|, when |this| has a RenderView.
    377   FinalStatus final_status_;
    378 
    379   // The MatchComplete status of the prerender, indicating how it relates
    380   // to being a MatchComplete dummy (see definition of MatchCompleteStatus
    381   // above).
    382   MatchCompleteStatus match_complete_status_;
    383 
    384   // Tracks whether or not prerendering has been cancelled by calling Destroy.
    385   // Used solely to prevent double deletion.
    386   bool prerendering_has_been_cancelled_;
    387 
    388   // Process Metrics of the render process associated with the
    389   // RenderViewHost for this object.
    390   scoped_ptr<base::ProcessMetrics> process_metrics_;
    391 
    392   // The prerendered WebContents; may be null.
    393   scoped_ptr<content::WebContents> prerender_contents_;
    394 
    395   scoped_ptr<PrerenderRenderViewHostObserver> render_view_host_observer_;
    396 
    397   scoped_ptr<WebContentsDelegateImpl> web_contents_delegate_;
    398 
    399   // These are -1 before a RenderView is created.
    400   int child_id_;
    401   int route_id_;
    402 
    403   // Origin for this prerender.
    404   Origin origin_;
    405 
    406   // Experiment during which this prerender is performed.
    407   uint8 experiment_id_;
    408 
    409   // Prerenders that the prerendered page has tried to prerender. They remain
    410   // pending until this page is displayed.
    411   ScopedVector<PendingPrerenderInfo> pending_prerenders_;
    412 
    413   // The process that created the child id.
    414   int creator_child_id_;
    415 
    416   // The size of the WebView from the launching page.
    417   gfx::Size size_;
    418 
    419   typedef std::vector<history::HistoryAddPageArgs> AddPageVector;
    420 
    421   // Caches pages to be added to the history.
    422   AddPageVector add_page_vector_;
    423 
    424   DISALLOW_COPY_AND_ASSIGN(PrerenderContents);
    425 };
    426 
    427 }  // namespace prerender
    428 
    429 #endif  // CHROME_BROWSER_PRERENDER_PRERENDER_CONTENTS_H_
    430