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