Home | History | Annotate | Download | only in web_contents
      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 CONTENT_BROWSER_WEB_CONTENTS_NAVIGATION_CONTROLLER_IMPL_H_
      6 #define CONTENT_BROWSER_WEB_CONTENTS_NAVIGATION_CONTROLLER_IMPL_H_
      7 
      8 #include "base/callback.h"
      9 #include "base/compiler_specific.h"
     10 #include "base/gtest_prod_util.h"
     11 #include "base/memory/linked_ptr.h"
     12 #include "base/time/time.h"
     13 #include "build/build_config.h"
     14 #include "content/browser/ssl/ssl_manager.h"
     15 #include "content/public/browser/navigation_controller.h"
     16 #include "content/public/browser/navigation_type.h"
     17 
     18 struct ViewHostMsg_FrameNavigate_Params;
     19 
     20 namespace content {
     21 class NavigationEntryImpl;
     22 class RenderViewHost;
     23 class WebContentsImpl;
     24 class WebContentsScreenshotManager;
     25 class SiteInstance;
     26 struct LoadCommittedDetails;
     27 
     28 class CONTENT_EXPORT NavigationControllerImpl
     29     : public NON_EXPORTED_BASE(NavigationController) {
     30  public:
     31   NavigationControllerImpl(
     32       WebContentsImpl* web_contents,
     33       BrowserContext* browser_context);
     34   virtual ~NavigationControllerImpl();
     35 
     36   // NavigationController implementation:
     37   virtual WebContents* GetWebContents() const OVERRIDE;
     38   virtual BrowserContext* GetBrowserContext() const OVERRIDE;
     39   virtual void SetBrowserContext(
     40       BrowserContext* browser_context) OVERRIDE;
     41   virtual void Restore(
     42       int selected_navigation,
     43       RestoreType type,
     44       std::vector<NavigationEntry*>* entries) OVERRIDE;
     45   virtual NavigationEntry* GetActiveEntry() const OVERRIDE;
     46   virtual NavigationEntry* GetVisibleEntry() const OVERRIDE;
     47   virtual int GetCurrentEntryIndex() const OVERRIDE;
     48   virtual NavigationEntry* GetLastCommittedEntry() const OVERRIDE;
     49   virtual int GetLastCommittedEntryIndex() const OVERRIDE;
     50   virtual bool CanViewSource() const OVERRIDE;
     51   virtual int GetEntryCount() const OVERRIDE;
     52   virtual NavigationEntry* GetEntryAtIndex(int index) const OVERRIDE;
     53   virtual NavigationEntry* GetEntryAtOffset(int offset) const OVERRIDE;
     54   virtual void DiscardNonCommittedEntries() OVERRIDE;
     55   virtual NavigationEntry* GetPendingEntry() const OVERRIDE;
     56   virtual int GetPendingEntryIndex() const OVERRIDE;
     57   virtual NavigationEntry* GetTransientEntry() const OVERRIDE;
     58   virtual void SetTransientEntry(NavigationEntry* entry) OVERRIDE;
     59   virtual void LoadURL(const GURL& url,
     60                        const Referrer& referrer,
     61                        PageTransition type,
     62                        const std::string& extra_headers) OVERRIDE;
     63   virtual void LoadURLWithParams(const LoadURLParams& params) OVERRIDE;
     64   virtual void LoadIfNecessary() OVERRIDE;
     65   virtual bool CanGoBack() const OVERRIDE;
     66   virtual bool CanGoForward() const OVERRIDE;
     67   virtual bool CanGoToOffset(int offset) const OVERRIDE;
     68   virtual void GoBack() OVERRIDE;
     69   virtual void GoForward() OVERRIDE;
     70   virtual void GoToIndex(int index) OVERRIDE;
     71   virtual void GoToOffset(int offset) OVERRIDE;
     72   virtual bool RemoveEntryAtIndex(int index) OVERRIDE;
     73   virtual const SessionStorageNamespaceMap&
     74       GetSessionStorageNamespaceMap() const OVERRIDE;
     75   virtual SessionStorageNamespace*
     76       GetDefaultSessionStorageNamespace() OVERRIDE;
     77   virtual void SetMaxRestoredPageID(int32 max_id) OVERRIDE;
     78   virtual int32 GetMaxRestoredPageID() const OVERRIDE;
     79   virtual bool NeedsReload() const OVERRIDE;
     80   virtual void CancelPendingReload() OVERRIDE;
     81   virtual void ContinuePendingReload() OVERRIDE;
     82   virtual bool IsInitialNavigation() const OVERRIDE;
     83   virtual void Reload(bool check_for_repost) OVERRIDE;
     84   virtual void ReloadIgnoringCache(bool check_for_repost) OVERRIDE;
     85   virtual void ReloadOriginalRequestURL(bool check_for_repost) OVERRIDE;
     86   virtual void NotifyEntryChanged(const NavigationEntry* entry,
     87                                  int index) OVERRIDE;
     88   virtual void CopyStateFrom(
     89       const NavigationController& source) OVERRIDE;
     90   virtual void CopyStateFromAndPrune(
     91       NavigationController* source) OVERRIDE;
     92   virtual bool CanPruneAllButVisible() OVERRIDE;
     93   virtual void PruneAllButVisible() OVERRIDE;
     94   virtual void ClearAllScreenshots() OVERRIDE;
     95 
     96   // The session storage namespace that all child RenderViews belonging to
     97   // |instance| should use.
     98   SessionStorageNamespace* GetSessionStorageNamespace(
     99       SiteInstance* instance);
    100 
    101   // Returns the index of the specified entry, or -1 if entry is not contained
    102   // in this NavigationController.
    103   int GetIndexOfEntry(const NavigationEntryImpl* entry) const;
    104 
    105   // Return the index of the entry with the corresponding instance and page_id,
    106   // or -1 if not found.
    107   int GetEntryIndexWithPageID(SiteInstance* instance,
    108                               int32 page_id) const;
    109 
    110   // Return the entry with the corresponding instance and page_id, or NULL if
    111   // not found.
    112   NavigationEntryImpl* GetEntryWithPageID(
    113       SiteInstance* instance,
    114       int32 page_id) const;
    115 
    116   // WebContentsImpl -----------------------------------------------------------
    117 
    118   WebContentsImpl* web_contents() const {
    119     return web_contents_;
    120   }
    121 
    122   // For use by WebContentsImpl ------------------------------------------------
    123 
    124   // Allow renderer-initiated navigations to create a pending entry when the
    125   // provisional load starts.
    126   void SetPendingEntry(content::NavigationEntryImpl* entry);
    127 
    128   // Handles updating the navigation state after the renderer has navigated.
    129   // This is used by the WebContentsImpl.
    130   //
    131   // If a new entry is created, it will return true and will have filled the
    132   // given details structure and broadcast the NOTIFY_NAV_ENTRY_COMMITTED
    133   // notification. The caller can then use the details without worrying about
    134   // listening for the notification.
    135   //
    136   // In the case that nothing has changed, the details structure is undefined
    137   // and it will return false.
    138   bool RendererDidNavigate(const ViewHostMsg_FrameNavigate_Params& params,
    139                            LoadCommittedDetails* details);
    140 
    141   // Notifies us that we just became active. This is used by the WebContentsImpl
    142   // so that we know to load URLs that were pending as "lazy" loads.
    143   void SetActive(bool is_active);
    144 
    145   // Returns true if the given URL would be an in-page navigation (i.e. only
    146   // the reference fragment is different) from the "last committed entry". We do
    147   // not compare it against the "active entry" since the active entry can be
    148   // pending and in page navigations only happen on committed pages. If there
    149   // is no last committed entry, then nothing will be in-page.
    150   //
    151   // Special note: if the URLs are the same, it does NOT automatically count as
    152   // an in-page navigation. Neither does an input URL that has no ref, even if
    153   // the rest is the same. This may seem weird, but when we're considering
    154   // whether a navigation happened without loading anything, the same URL could
    155   // be a reload, while only a different ref would be in-page (pages can't clear
    156   // refs without reload, only change to "#" which we don't count as empty).
    157   bool IsURLInPageNavigation(const GURL& url) const {
    158     return IsURLInPageNavigation(url, false, NAVIGATION_TYPE_UNKNOWN);
    159   }
    160 
    161   // The situation is made murkier by history.replaceState(), which could
    162   // provide the same URL as part of an in-page navigation, not a reload. So
    163   // we need this form which lets the (untrustworthy) renderer resolve the
    164   // ambiguity, but only when the URLs are equal. This should be safe since the
    165   // origin isn't changing.
    166   bool IsURLInPageNavigation(
    167       const GURL& url,
    168       bool renderer_says_in_page,
    169       NavigationType navigation_type) const;
    170 
    171   // Sets the SessionStorageNamespace for the given |partition_id|. This is
    172   // used during initialization of a new NavigationController to allow
    173   // pre-population of the SessionStorageNamespace objects. Session restore,
    174   // prerendering, and the implementaion of window.open() are the primary users
    175   // of this API.
    176   //
    177   // Calling this function when a SessionStorageNamespace has already been
    178   // associated with a |partition_id| will CHECK() fail.
    179   void SetSessionStorageNamespace(
    180       const std::string& partition_id,
    181       SessionStorageNamespace* session_storage_namespace);
    182 
    183   // Random data ---------------------------------------------------------------
    184 
    185   SSLManager* ssl_manager() { return &ssl_manager_; }
    186 
    187   // Maximum number of entries before we start removing entries from the front.
    188   static void set_max_entry_count_for_testing(size_t max_entry_count) {
    189     max_entry_count_for_testing_ = max_entry_count;
    190   }
    191   static size_t max_entry_count();
    192 
    193   void SetGetTimestampCallbackForTest(
    194       const base::Callback<base::Time()>& get_timestamp_callback);
    195 
    196   // Takes a screenshot of the page at the current state.
    197   void TakeScreenshot();
    198 
    199   // Sets the screenshot manager for this NavigationControllerImpl. The
    200   // controller takes ownership of the screenshot manager and destroys it when
    201   // a new screenshot-manager is set, or when the controller is destroyed.
    202   // Setting a NULL manager recreates the default screenshot manager and uses
    203   // that.
    204   void SetScreenshotManager(WebContentsScreenshotManager* manager);
    205 
    206  private:
    207   friend class RestoreHelper;
    208   friend class WebContentsImpl;  // For invoking OnReservedPageIDRange.
    209 
    210   FRIEND_TEST_ALL_PREFIXES(NavigationControllerTest,
    211                            PurgeScreenshot);
    212   FRIEND_TEST_ALL_PREFIXES(TimeSmoother, Basic);
    213   FRIEND_TEST_ALL_PREFIXES(TimeSmoother, SingleDuplicate);
    214   FRIEND_TEST_ALL_PREFIXES(TimeSmoother, ManyDuplicates);
    215   FRIEND_TEST_ALL_PREFIXES(TimeSmoother, ClockBackwardsJump);
    216 
    217   // Helper class to smooth out runs of duplicate timestamps while still
    218   // allowing time to jump backwards.
    219   class CONTENT_EXPORT TimeSmoother {
    220    public:
    221     // Returns |t| with possibly some time added on.
    222     base::Time GetSmoothedTime(base::Time t);
    223 
    224    private:
    225     // |low_water_mark_| is the first time in a sequence of adjusted
    226     // times and |high_water_mark_| is the last.
    227     base::Time low_water_mark_;
    228     base::Time high_water_mark_;
    229   };
    230 
    231   // Classifies the given renderer navigation (see the NavigationType enum).
    232   NavigationType ClassifyNavigation(
    233       const ViewHostMsg_FrameNavigate_Params& params) const;
    234 
    235   // Causes the controller to load the specified entry. The function assumes
    236   // ownership of the pointer since it is put in the navigation list.
    237   // NOTE: Do not pass an entry that the controller already owns!
    238   void LoadEntry(NavigationEntryImpl* entry);
    239 
    240   // Handlers for the different types of navigation types. They will actually
    241   // handle the navigations corresponding to the different NavClasses above.
    242   // They will NOT broadcast the commit notification, that should be handled by
    243   // the caller.
    244   //
    245   // RendererDidNavigateAutoSubframe is special, it may not actually change
    246   // anything if some random subframe is loaded. It will return true if anything
    247   // changed, or false if not.
    248   //
    249   // The functions taking |did_replace_entry| will fill into the given variable
    250   // whether the last entry has been replaced or not.
    251   // See LoadCommittedDetails.did_replace_entry.
    252   void RendererDidNavigateToNewPage(
    253       const ViewHostMsg_FrameNavigate_Params& params, bool replace_entry);
    254   void RendererDidNavigateToExistingPage(
    255       const ViewHostMsg_FrameNavigate_Params& params);
    256   void RendererDidNavigateToSamePage(
    257       const ViewHostMsg_FrameNavigate_Params& params);
    258   void RendererDidNavigateInPage(
    259       const ViewHostMsg_FrameNavigate_Params& params, bool* did_replace_entry);
    260   void RendererDidNavigateNewSubframe(
    261       const ViewHostMsg_FrameNavigate_Params& params);
    262   bool RendererDidNavigateAutoSubframe(
    263       const ViewHostMsg_FrameNavigate_Params& params);
    264 
    265   // Helper function for code shared between Reload() and ReloadIgnoringCache().
    266   void ReloadInternal(bool check_for_repost, ReloadType reload_type);
    267 
    268   // Actually issues the navigation held in pending_entry.
    269   void NavigateToPendingEntry(ReloadType reload_type);
    270 
    271   // Allows the derived class to issue notifications that a load has been
    272   // committed. This will fill in the active entry to the details structure.
    273   void NotifyNavigationEntryCommitted(LoadCommittedDetails* details);
    274 
    275   // Updates the virtual URL of an entry to match a new URL, for cases where
    276   // the real renderer URL is derived from the virtual URL, like view-source:
    277   void UpdateVirtualURLToURL(NavigationEntryImpl* entry,
    278                              const GURL& new_url);
    279 
    280   // Invoked after session/tab restore or cloning a tab. Resets the transition
    281   // type of the entries, updates the max page id and creates the active
    282   // contents.
    283   void FinishRestore(int selected_index, RestoreType type);
    284 
    285   // Inserts a new entry or replaces the current entry with a new one, removing
    286   // all entries after it. The new entry will become the active one.
    287   void InsertOrReplaceEntry(NavigationEntryImpl* entry, bool replace);
    288 
    289   // Removes the entry at |index|, as long as it is not the current entry.
    290   void RemoveEntryAtIndexInternal(int index);
    291 
    292   // Discards both the pending and transient entries.
    293   void DiscardNonCommittedEntriesInternal();
    294 
    295   // Discards only the pending entry.
    296   void DiscardPendingEntry();
    297 
    298   // Discards only the transient entry.
    299   void DiscardTransientEntry();
    300 
    301   // If we have the maximum number of entries, remove the oldest one in
    302   // preparation to add another.
    303   void PruneOldestEntryIfFull();
    304 
    305   // Removes all entries except the last committed entry.  If there is a new
    306   // pending navigation it is preserved. In contrast to PruneAllButVisible()
    307   // this does not update the session history of the RenderView.  Callers
    308   // must ensure that |CanPruneAllButVisible| returns true before calling this.
    309   void PruneAllButVisibleInternal();
    310 
    311   // Returns true if the navigation is redirect.
    312   bool IsRedirect(const ViewHostMsg_FrameNavigate_Params& params);
    313 
    314   // Returns true if the navigation is likley to be automatic rather than
    315   // user-initiated.
    316   bool IsLikelyAutoNavigation(base::TimeTicks now);
    317 
    318   // Inserts up to |max_index| entries from |source| into this. This does NOT
    319   // adjust any of the members that reference entries_
    320   // (last_committed_entry_index_, pending_entry_index_ or
    321   // transient_entry_index_).
    322   void InsertEntriesFrom(const NavigationControllerImpl& source, int max_index);
    323 
    324   // Returns the navigation index that differs from the current entry by the
    325   // specified |offset|.  The index returned is not guaranteed to be valid.
    326   int GetIndexForOffset(int offset) const;
    327 
    328   // ---------------------------------------------------------------------------
    329 
    330   // The user browser context associated with this controller.
    331   BrowserContext* browser_context_;
    332 
    333   // List of NavigationEntry for this tab
    334   typedef std::vector<linked_ptr<NavigationEntryImpl> > NavigationEntries;
    335   NavigationEntries entries_;
    336 
    337   // An entry we haven't gotten a response for yet.  This will be discarded
    338   // when we navigate again.  It's used only so we know what the currently
    339   // displayed tab is.
    340   //
    341   // This may refer to an item in the entries_ list if the pending_entry_index_
    342   // == -1, or it may be its own entry that should be deleted. Be careful with
    343   // the memory management.
    344   NavigationEntryImpl* pending_entry_;
    345 
    346   // currently visible entry
    347   int last_committed_entry_index_;
    348 
    349   // index of pending entry if it is in entries_, or -1 if pending_entry_ is a
    350   // new entry (created by LoadURL).
    351   int pending_entry_index_;
    352 
    353   // The index for the entry that is shown until a navigation occurs.  This is
    354   // used for interstitial pages. -1 if there are no such entry.
    355   // Note that this entry really appears in the list of entries, but only
    356   // temporarily (until the next navigation).  Any index pointing to an entry
    357   // after the transient entry will become invalid if you navigate forward.
    358   int transient_entry_index_;
    359 
    360   // The WebContents associated with the controller. Possibly NULL during
    361   // setup.
    362   WebContentsImpl* web_contents_;
    363 
    364   // The max restored page ID in this controller, if it was restored.  We must
    365   // store this so that WebContentsImpl can tell any renderer in charge of one
    366   // of the restored entries to update its max page ID.
    367   int32 max_restored_page_id_;
    368 
    369   // Manages the SSL security UI
    370   SSLManager ssl_manager_;
    371 
    372   // Whether we need to be reloaded when made active.
    373   bool needs_reload_;
    374 
    375   // Whether this is the initial navigation.
    376   // Becomes false when initial navigation commits.
    377   bool is_initial_navigation_;
    378 
    379   // Used to find the appropriate SessionStorageNamespace for the storage
    380   // partition of a NavigationEntry.
    381   //
    382   // A NavigationController may contain NavigationEntries that correspond to
    383   // different StoragePartitions. Even though they are part of the same
    384   // NavigationController, only entries in the same StoragePartition may
    385   // share session storage state with one another.
    386   SessionStorageNamespaceMap session_storage_namespace_map_;
    387 
    388   // The maximum number of entries that a navigation controller can store.
    389   static size_t max_entry_count_for_testing_;
    390 
    391   // If a repost is pending, its type (RELOAD or RELOAD_IGNORING_CACHE),
    392   // NO_RELOAD otherwise.
    393   ReloadType pending_reload_;
    394 
    395   // Used to get timestamps for newly-created navigation entries.
    396   base::Callback<base::Time()> get_timestamp_callback_;
    397 
    398   // Used to smooth out timestamps from |get_timestamp_callback_|.
    399   // Without this, whenever there is a run of redirects or
    400   // code-generated navigations, those navigations may occur within
    401   // the timer resolution, leading to things sometimes showing up in
    402   // the wrong order in the history view.
    403   TimeSmoother time_smoother_;
    404 
    405   scoped_ptr<WebContentsScreenshotManager> screenshot_manager_;
    406 
    407   DISALLOW_COPY_AND_ASSIGN(NavigationControllerImpl);
    408 };
    409 
    410 }  // namespace content
    411 
    412 #endif  // CONTENT_BROWSER_WEB_CONTENTS_NAVIGATION_CONTROLLER_IMPL_H_
    413