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