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