• 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 <set>
9 #include <string>
10 #include <utility>
11 #include <vector>
12 
13 #include "base/memory/scoped_ptr.h"
14 #include "base/memory/scoped_vector.h"
15 #include "base/memory/weak_ptr.h"
16 #include "base/observer_list.h"
17 #include "base/time/time.h"
18 #include "base/values.h"
19 #include "chrome/browser/prerender/prerender_final_status.h"
20 #include "chrome/browser/prerender/prerender_origin.h"
21 #include "content/public/browser/notification_observer.h"
22 #include "content/public/browser/notification_registrar.h"
23 #include "content/public/browser/web_contents_observer.h"
24 #include "content/public/common/referrer.h"
25 #include "ui/gfx/size.h"
26 
27 class Profile;
28 
29 namespace base {
30 class ProcessMetrics;
31 }
32 
33 namespace content {
34 struct FaviconURL;
35 class RenderViewHost;
36 class SessionStorageNamespace;
37 class WebContents;
38 }
39 
40 namespace history {
41 struct HistoryAddPageArgs;
42 }
43 
44 namespace prerender {
45 
46 class PrerenderHandle;
47 class PrerenderManager;
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:
Factory()56     Factory() {}
~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 
prerender_manager()173   PrerenderManager* prerender_manager() { return prerender_manager_; }
174 
title()175   base::string16 title() const { return title_; }
page_id()176   int32 page_id() const { return page_id_; }
icon_url()177   GURL icon_url() const { return icon_url_; }
prerender_url()178   const GURL& prerender_url() const { return prerender_url_; }
referrer()179   const content::Referrer& referrer() const { return referrer_; }
has_stopped_loading()180   bool has_stopped_loading() const { return has_stopped_loading_; }
has_finished_loading()181   bool has_finished_loading() const { return has_finished_loading_; }
prerendering_has_started()182   bool prerendering_has_started() const { return prerendering_has_started_; }
match_complete_status()183   MatchCompleteStatus match_complete_status() const {
184     return match_complete_status_;
185   }
set_match_complete_status(MatchCompleteStatus status)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);
final_status()202   FinalStatus final_status() const { return final_status_; }
203 
origin()204   Origin origin() const { return origin_; }
experiment_id()205   uint8 experiment_id() const { return experiment_id_; }
child_id()206   int child_id() const { return child_id_; }
207 
load_start_time()208   base::TimeTicks load_start_time() const { return load_start_time_; }
209 
210   // Indicates whether this prerendered page can be used for the provided
211   // |url| and |session_storage_namespace|.
212   bool Matches(
213       const GURL& url,
214       const content::SessionStorageNamespace* session_storage_namespace) const;
215 
216   // content::WebContentsObserver implementation.
217   virtual void RenderFrameCreated(
218       content::RenderFrameHost* render_frame_host) OVERRIDE;
219   virtual void RenderFrameDeleted(
220       content::RenderFrameHost* render_frame_host) OVERRIDE;
221   virtual void DidStopLoading(
222       content::RenderViewHost* render_view_host) OVERRIDE;
223   virtual void DidStartProvisionalLoadForFrame(
224       int64 frame_id,
225       int64 parent_frame_id,
226       bool is_main_frame,
227       const GURL& validated_url,
228       bool is_error_page,
229       bool is_iframe_srcdoc,
230       content::RenderViewHost* render_view_host) OVERRIDE;
231   virtual void DidFinishLoad(
232       int64 frame_id,
233       const GURL& validated_url,
234       bool is_main_frame,
235       content::RenderViewHost* render_view_host) OVERRIDE;
236   virtual void DidNavigateMainFrame(
237       const content::LoadCommittedDetails& details,
238       const content::FrameNavigateParams& params) OVERRIDE;
239   virtual void DidGetRedirectForResourceRequest(
240       const content::ResourceRedirectDetails& details) OVERRIDE;
241   virtual void DidUpdateFaviconURL(int32 page_id,
242       const std::vector<content::FaviconURL>& urls) OVERRIDE;
243   virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
244 
245   virtual void RenderProcessGone(base::TerminationStatus status) OVERRIDE;
246 
247   // content::NotificationObserver
248   virtual void Observe(int type,
249                        const content::NotificationSource& source,
250                        const content::NotificationDetails& details) OVERRIDE;
251 
252   // Checks that a URL may be prerendered, for one of the many redirections. If
253   // the URL can not be prerendered - for example, it's an ftp URL - |this| will
254   // be destroyed and false is returned. Otherwise, true is returned.
255   virtual bool CheckURL(const GURL& url);
256 
257   // Adds an alias URL. If the URL can not be prerendered, |this| will be
258   // destroyed and false is returned.
259   bool AddAliasURL(const GURL& url);
260 
261   // The prerender WebContents (may be NULL).
prerender_contents()262   content::WebContents* prerender_contents() const {
263     return prerender_contents_.get();
264   }
265 
266   content::WebContents* ReleasePrerenderContents();
267 
268   // Sets the final status, calls OnDestroy and adds |this| to the
269   // PrerenderManager's pending deletes list.
270   void Destroy(FinalStatus reason);
271 
272   // Called by the history tab helper with the information that it woudl have
273   // added to the history service had this web contents not been used for
274   // prerendering.
275   void DidNavigate(const history::HistoryAddPageArgs& add_page_args);
276 
277   // Applies all the URL history encountered during prerendering to the
278   // new tab.
279   void CommitHistory(content::WebContents* tab);
280 
281   base::Value* GetAsValue() const;
282 
283   // Returns whether a pending cross-site navigation is happening.
284   // This could happen with renderer-issued navigations, such as a
285   // MouseEvent being dispatched by a link to a website installed as an app.
286   bool IsCrossSiteNavigationPending() const;
287 
288   // Adds a pending prerender to the list. If |weak_prerender_handle| still
289   // exists when this page is made visible, it will be launched.
290   virtual void AddPendingPrerender(
291       scoped_ptr<PendingPrerenderInfo> pending_prerender_info);
292 
293   // Reissues any pending prerender requests from the prerendered page.  Also
294   // clears the list of pending requests. Sends notifications.
295   void PrepareForUse();
296 
297   content::SessionStorageNamespace* GetSessionStorageNamespace() const;
298 
299   // Cookie events
300   enum CookieEvent {
301     COOKIE_EVENT_SEND = 0,
302     COOKIE_EVENT_CHANGE = 1,
303     COOKIE_EVENT_MAX
304   };
305 
306   // Record a cookie transaction for this prerender contents.
307   // In the event of cookies being sent, |earliest_create_date| contains
308   // the time that the earliest of the cookies sent was created.
309   void RecordCookieEvent(CookieEvent event,
310                          bool main_frame_http_request,
311                          base::Time earliest_create_date);
312 
313   static const int kNumCookieStatuses;
314 
315  protected:
316   PrerenderContents(PrerenderManager* prerender_manager,
317                     Profile* profile,
318                     const GURL& url,
319                     const content::Referrer& referrer,
320                     Origin origin,
321                     uint8 experiment_id);
322 
323   // These call out to methods on our Observers, using our observer_list_. Note
324   // that NotifyPrerenderStop() also clears the observer list.
325   void NotifyPrerenderStart();
326   void NotifyPrerenderStopLoading();
327   void NotifyPrerenderStop();
328   void NotifyPrerenderCreatedMatchCompleteReplacement(
329       PrerenderContents* replacement);
330 
331   // Called whenever a RenderViewHost is created for prerendering.  Only called
332   // once the RenderViewHost has a RenderView and RenderWidgetHostView.
333   virtual void OnRenderViewHostCreated(
334       content::RenderViewHost* new_render_view_host);
335 
notification_registrar()336   content::NotificationRegistrar& notification_registrar() {
337     return notification_registrar_;
338   }
339 
340   size_t pending_prerender_count() const;
341 
prerendering_has_been_cancelled()342   bool prerendering_has_been_cancelled() const {
343     return prerendering_has_been_cancelled_;
344   }
345 
346   virtual content::WebContents* CreateWebContents(
347       content::SessionStorageNamespace* session_storage_namespace);
348 
349   bool prerendering_has_started_;
350 
351   // Time at which we started to load the URL.  This is used to compute
352   // the time elapsed from initiating a prerender until the time the
353   // (potentially only partially) prerendered page is shown to the user.
354   base::TimeTicks load_start_time_;
355 
356   // The prerendered WebContents; may be null.
357   scoped_ptr<content::WebContents> prerender_contents_;
358 
359   // The session storage namespace id for use in matching. We must save it
360   // rather than get it from the RenderViewHost since in the control group
361   // we won't have a RenderViewHost.
362   int64 session_storage_namespace_id_;
363 
364   // The time at which we started prerendering, for the purpose of comparing
365   // cookie creation times.
366   base::Time start_time_;
367 
368  private:
369   class WebContentsDelegateImpl;
370 
371   // Needs to be able to call the constructor.
372   friend class PrerenderContentsFactoryImpl;
373 
374   // Returns the ProcessMetrics for the render process, if it exists.
375   base::ProcessMetrics* MaybeGetProcessMetrics();
376 
377   // Message handlers.
378   void OnCancelPrerenderForPrinting();
379 
380   ObserverList<Observer> observer_list_;
381 
382   // The prerender manager owning this object.
383   PrerenderManager* prerender_manager_;
384 
385   // The URL being prerendered.
386   GURL prerender_url_;
387 
388   // The referrer.
389   content::Referrer referrer_;
390 
391   // The profile being used
392   Profile* profile_;
393 
394   // Information about the title and URL of the page that this class as a
395   // RenderViewHostDelegate has received from the RenderView.
396   // Used to apply to the new RenderViewHost delegate that might eventually
397   // own the contained RenderViewHost when the prerendered page is shown
398   // in a WebContents.
399   base::string16 title_;
400   int32 page_id_;
401   GURL url_;
402   GURL icon_url_;
403   content::NotificationRegistrar notification_registrar_;
404 
405   // A vector of URLs that this prerendered page matches against.
406   // This array can contain more than element as a result of redirects,
407   // such as HTTP redirects or javascript redirects.
408   std::vector<GURL> alias_urls_;
409 
410   bool has_stopped_loading_;
411 
412   // True when the main frame has finished loading.
413   bool has_finished_loading_;
414 
415   // This must be the same value as the PrerenderTracker has recorded for
416   // |this|, when |this| has a RenderView.
417   FinalStatus final_status_;
418 
419   // The MatchComplete status of the prerender, indicating how it relates
420   // to being a MatchComplete dummy (see definition of MatchCompleteStatus
421   // above).
422   MatchCompleteStatus match_complete_status_;
423 
424   // Tracks whether or not prerendering has been cancelled by calling Destroy.
425   // Used solely to prevent double deletion.
426   bool prerendering_has_been_cancelled_;
427 
428   // Process Metrics of the render process associated with the
429   // RenderViewHost for this object.
430   scoped_ptr<base::ProcessMetrics> process_metrics_;
431 
432   scoped_ptr<WebContentsDelegateImpl> web_contents_delegate_;
433 
434   // These are -1 before a RenderView is created.
435   int child_id_;
436   int route_id_;
437 
438   // Origin for this prerender.
439   Origin origin_;
440 
441   // Experiment during which this prerender is performed.
442   uint8 experiment_id_;
443 
444   // Prerenders that the prerendered page has tried to prerender. They remain
445   // pending until this page is displayed.
446   ScopedVector<PendingPrerenderInfo> pending_prerenders_;
447 
448   // The process that created the child id.
449   int creator_child_id_;
450 
451   // The size of the WebView from the launching page.
452   gfx::Size size_;
453 
454   typedef std::vector<history::HistoryAddPageArgs> AddPageVector;
455 
456   // Caches pages to be added to the history.
457   AddPageVector add_page_vector_;
458 
459   // The alias session storage namespace for this prerender.
460   scoped_refptr<content::SessionStorageNamespace>
461       alias_session_storage_namespace;
462 
463   // The RenderFrameHosts for prerender_contents_.
464   std::set<content::RenderFrameHost*> render_frame_hosts_;
465 
466   // Indicates what internal cookie events (see prerender_contents.cc) have
467   // occurred, using 1 bit for each possible InternalCookieEvent.
468   int cookie_status_;
469 
470   DISALLOW_COPY_AND_ASSIGN(PrerenderContents);
471 };
472 
473 }  // namespace prerender
474 
475 #endif  // CHROME_BROWSER_PRERENDER_PRERENDER_CONTENTS_H_
476