blob: 56201f350d1eb550c851d88f671000109d6df143 [file] [log] [blame]
[email protected]43032342011-03-21 14:10:311// Copyright (c) 2011 The Chromium Authors. All rights reserved.
[email protected]0dd3a0ab2011-02-18 08:17:442// 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_TAB_CONTENTS_NAVIGATION_CONTROLLER_H_
6#define CONTENT_BROWSER_TAB_CONTENTS_NAVIGATION_CONTROLLER_H_
7#pragma once
8
9#include "build/build_config.h"
10
11#include <string>
12#include <vector>
13
14#include "base/linked_ptr.h"
15#include "base/time.h"
16#include "googleurl/src/gurl.h"
17#include "chrome/browser/sessions/session_id.h"
18#include "chrome/browser/ssl/ssl_manager.h"
[email protected]4dd57932011-03-17 06:06:1219#include "content/common/navigation_types.h"
20#include "content/common/page_transition_types.h"
[email protected]0dd3a0ab2011-02-18 08:17:4421
22class NavigationEntry;
23class Profile;
24class SessionStorageNamespace;
25class SiteInstance;
26class TabContents;
27class TabNavigation;
28struct ViewHostMsg_FrameNavigate_Params;
29
30// A NavigationController maintains the back-forward list for a single tab and
31// manages all navigation within that list.
32//
33// The NavigationController also owns all TabContents for the tab. This is to
34// make sure that we have at most one TabContents instance per type.
35class NavigationController {
36 public:
37 // Notification details ------------------------------------------------------
38
39 // Provides the details for a NOTIFY_NAV_ENTRY_CHANGED notification.
40 struct EntryChangedDetails {
41 // The changed navigation entry after it has been updated.
42 const NavigationEntry* changed_entry;
43
44 // Indicates the current index in the back/forward list of the entry.
45 int index;
46 };
47
48 // Provides the details for a NOTIFY_NAV_ENTRY_COMMITTED notification.
49 // TODO(brettw) this mostly duplicates ProvisionalLoadDetails, it would be
50 // nice to unify these somehow.
51 struct LoadCommittedDetails {
52 // By default, the entry will be filled according to a new main frame
53 // navigation.
54 LoadCommittedDetails()
55 : entry(NULL),
56 type(NavigationType::UNKNOWN),
57 previous_entry_index(-1),
58 is_auto(false),
59 did_replace_entry(false),
60 is_in_page(false),
61 is_main_frame(true),
[email protected]0dd3a0ab2011-02-18 08:17:4462 http_status_code(0) {
63 }
64
65 // The committed entry. This will be the active entry in the controller.
66 NavigationEntry* entry;
67
68 // The type of navigation that just occurred. Note that not all types of
69 // navigations in the enum are valid here, since some of them don't actually
70 // cause a "commit" and won't generate this notification.
71 NavigationType::Type type;
72
73 // The index of the previously committed navigation entry. This will be -1
74 // if there are no previous entries.
75 int previous_entry_index;
76
77 // The previous URL that the user was on. This may be empty if none.
78 GURL previous_url;
79
80 // True when this load was non-user initated. This corresponds to a
81 // a NavigationGestureAuto call from WebKit (see webview_delegate.h).
82 // We also count reloads and meta-refreshes as "auto" to account for the
83 // fact that WebKit doesn't always set the user gesture properly in these
84 // cases (see bug 1051891).
85 bool is_auto;
86
87 // True if the committed entry has replaced the exisiting one.
88 // A non-user initiated redirect causes such replacement.
89 // This is somewhat similiar to is_auto, but not exactly the same.
90 bool did_replace_entry;
91
92 // True if the navigation was in-page. This means that the active entry's
93 // URL and the |previous_url| are the same except for reference fragments.
94 bool is_in_page;
95
96 // True when the main frame was navigated. False means the navigation was a
97 // sub-frame.
98 bool is_main_frame;
99
[email protected]0dd3a0ab2011-02-18 08:17:44100 // When the committed load is a web page from the renderer, this string
101 // specifies the security state if the page is secure.
102 // See ViewHostMsg_FrameNavigate_Params.security_info, where it comes from.
103 // Use SSLManager::DeserializeSecurityInfo to decode it.
104 std::string serialized_security_info;
105
106 // Returns whether the user probably felt like they navigated somewhere new.
107 // We often need this logic for showing or hiding something, and this
108 // returns true only for main frame loads that the user initiated, that go
109 // to a new page.
110 bool is_user_initiated_main_frame_load() const {
111 return !is_auto && !is_in_page && is_main_frame;
112 }
113
114 // The HTTP status code for this entry..
115 int http_status_code;
116 };
117
118 // Details sent for NOTIFY_NAV_LIST_PRUNED.
119 struct PrunedDetails {
120 // If true, count items were removed from the front of the list, otherwise
121 // count items were removed from the back of the list.
122 bool from_front;
123
124 // Number of items removed.
125 int count;
126 };
127
128 enum ReloadType {
129 NO_RELOAD, // Normal load.
130 RELOAD, // Normal (cache-validating) reload.
131 RELOAD_IGNORING_CACHE // Reload bypassing the cache, aka shift-reload.
132 };
133
134 // ---------------------------------------------------------------------------
135
136 NavigationController(TabContents* tab_contents,
137 Profile* profile,
138 SessionStorageNamespace* session_storage_namespace);
139 ~NavigationController();
140
141 // Returns the profile for this controller. It can never be NULL.
142 Profile* profile() const {
143 return profile_;
144 }
145
146 // Sets the profile for this controller.
147 void set_profile(Profile* profile) {
148 profile_ = profile;
149 }
150
151 // Initializes this NavigationController with the given saved navigations,
152 // using selected_navigation as the currently loaded entry. Before this call
153 // the controller should be unused (there should be no current entry). If
154 // from_last_session is true, navigations are from the previous session,
155 // otherwise they are from the current session (undo tab close).
156 // This is used for session restore.
157 void RestoreFromState(const std::vector<TabNavigation>& navigations,
158 int selected_navigation, bool from_last_session);
159
160 // Active entry --------------------------------------------------------------
161
162 // Returns the active entry, which is the transient entry if any, the pending
163 // entry if a navigation is in progress or the last committed entry otherwise.
164 // NOTE: This can be NULL!!
165 //
166 // If you are trying to get the current state of the NavigationController,
167 // this is the method you will typically want to call.
168 NavigationEntry* GetActiveEntry() const;
169
170 // Returns the index from which we would go back/forward or reload. This is
171 // the last_committed_entry_index_ if pending_entry_index_ is -1. Otherwise,
172 // it is the pending_entry_index_.
173 int GetCurrentEntryIndex() const;
174
175 // Returns the last committed entry, which may be null if there are no
176 // committed entries.
177 NavigationEntry* GetLastCommittedEntry() const;
178
179 // Returns true if the source for the current entry can be viewed.
180 bool CanViewSource() const;
181
182 // Returns the index of the last committed entry.
183 int last_committed_entry_index() const {
184 return last_committed_entry_index_;
185 }
186
187 // Navigation list -----------------------------------------------------------
188
189 // Returns the number of entries in the NavigationController, excluding
190 // the pending entry if there is one, but including the transient entry if
191 // any.
192 int entry_count() const {
193 return static_cast<int>(entries_.size());
194 }
195
196 NavigationEntry* GetEntryAtIndex(int index) const {
197 return entries_.at(index).get();
198 }
199
200 // Returns the entry at the specified offset from current. Returns NULL
201 // if out of bounds.
202 NavigationEntry* GetEntryAtOffset(int offset) const;
203
204 // Returns the index of the specified entry, or -1 if entry is not contained
205 // in this NavigationController.
206 int GetIndexOfEntry(const NavigationEntry* entry) const;
207
208 // Return the index of the entry with the corresponding instance and page_id,
209 // or -1 if not found.
210 int GetEntryIndexWithPageID(SiteInstance* instance,
211 int32 page_id) const;
212
213 // Return the entry with the corresponding instance and page_id, or NULL if
214 // not found.
215 NavigationEntry* GetEntryWithPageID(SiteInstance* instance,
216 int32 page_id) const;
217
218 // Pending entry -------------------------------------------------------------
219
220 // Commits the current pending entry and issues the NOTIFY_NAV_ENTRY_COMMIT
221 // notification. No changes are made to the entry during this process, it is
222 // just moved from pending to committed. This is an alternative to
223 // RendererDidNavigate for simple TabContents types.
224 //
225 // When the pending entry is a new navigation, it will have a page ID of -1.
226 // The caller should leave this as-is. CommitPendingEntry will generate a
227 // new page ID for you and update the TabContents with that ID.
228 void CommitPendingEntry();
229
230 // Discards the pending and transient entries if any.
231 void DiscardNonCommittedEntries();
232
233 // Returns the pending entry corresponding to the navigation that is
234 // currently in progress, or null if there is none.
235 NavigationEntry* pending_entry() const {
236 return pending_entry_;
237 }
238
239 // Returns the index of the pending entry or -1 if the pending entry
240 // corresponds to a new navigation (created via LoadURL).
241 int pending_entry_index() const {
242 return pending_entry_index_;
243 }
244
245 // Transient entry -----------------------------------------------------------
246
247 // Adds an entry that is returned by GetActiveEntry(). The entry is
248 // transient: any navigation causes it to be removed and discarded.
249 // The NavigationController becomes the owner of |entry| and deletes it when
250 // it discards it. This is useful with interstitial page that need to be
251 // represented as an entry, but should go away when the user navigates away
252 // from them.
253 // Note that adding a transient entry does not change the active contents.
254 void AddTransientEntry(NavigationEntry* entry);
255
256 // Returns the transient entry if any. Note that the returned entry is owned
257 // by the navigation controller and may be deleted at any time.
258 NavigationEntry* GetTransientEntry() const;
259
260 // New navigations -----------------------------------------------------------
261
262 // Loads the specified URL.
263 void LoadURL(const GURL& url, const GURL& referrer,
264 PageTransition::Type type);
265
266 // Loads the current page if this NavigationController was restored from
267 // history and the current page has not loaded yet.
268 void LoadIfNecessary();
269
270 // Renavigation --------------------------------------------------------------
271
272 // Navigation relative to the "current entry"
273 bool CanGoBack() const;
274 bool CanGoForward() const;
275 void GoBack();
276 void GoForward();
277
278 // Navigates to the specified absolute index.
279 void GoToIndex(int index);
280
281 // Navigates to the specified offset from the "current entry". Does nothing if
282 // the offset is out of bounds.
283 void GoToOffset(int offset);
284
285 // Reloads the current entry. If |check_for_repost| is true and the current
286 // entry has POST data the user is prompted to see if they really want to
287 // reload the page. In nearly all cases pass in true.
288 void Reload(bool check_for_repost);
289 // Like Reload(), but don't use caches (aka "shift-reload").
290 void ReloadIgnoringCache(bool check_for_repost);
291
292 // Removing of entries -------------------------------------------------------
293
294 // Removes the entry at the specified |index|. This call dicards any pending
295 // and transient entries. |default_url| is the URL that the navigation
296 // controller navigates to if there are no more entries after the removal.
297 // If |default_url| is empty, we default to "about:blank".
298 void RemoveEntryAtIndex(int index, const GURL& default_url);
299
300 // TabContents ---------------------------------------------------------------
301
302 // Returns the tab contents associated with this controller. Non-NULL except
303 // during set-up of the tab.
304 TabContents* tab_contents() const {
305 // This currently returns the active tab contents which should be renamed to
306 // tab_contents.
307 return tab_contents_;
308 }
309
310 // Called when a document has been loaded in a frame.
311 void DocumentLoadedInFrame();
312
313 // For use by TabContents ----------------------------------------------------
314
315 // Handles updating the navigation state after the renderer has navigated.
316 // This is used by the TabContents. Simpler tab contents types can use
317 // CommitPendingEntry below.
318 //
319 // If a new entry is created, it will return true and will have filled the
320 // given details structure and broadcast the NOTIFY_NAV_ENTRY_COMMITTED
321 // notification. The caller can then use the details without worrying about
322 // listening for the notification.
323 //
324 // In the case that nothing has changed, the details structure is undefined
325 // and it will return false.
326 //
327 // |extra_invalidate_flags| are an additional set of flags (InvalidateTypes)
328 // added to the flags sent to the delegate's NotifyNavigationStateChanged.
329 bool RendererDidNavigate(const ViewHostMsg_FrameNavigate_Params& params,
330 int extra_invalidate_flags,
331 LoadCommittedDetails* details);
332
333 // Notifies us that we just became active. This is used by the TabContents
334 // so that we know to load URLs that were pending as "lazy" loads.
335 void SetActive(bool is_active);
336
337 // Broadcasts the NOTIFY_NAV_ENTRY_CHANGED notification for the given entry
338 // (which must be at the given index). This will keep things in sync like
339 // the saved session.
340 void NotifyEntryChanged(const NavigationEntry* entry, int index);
341
342 // Returns true if the given URL would be an in-page navigation (i.e. only
343 // the reference fragment is different) from the "last committed entry". We do
344 // not compare it against the "active entry" since the active entry can be
345 // pending and in page navigations only happen on committed pages. If there
346 // is no last committed entry, then nothing will be in-page.
347 //
348 // Special note: if the URLs are the same, it does NOT count as an in-page
349 // navigation. Neither does an input URL that has no ref, even if the rest is
350 // the same. This may seem weird, but when we're considering whether a
351 // navigation happened without loading anything, the same URL would be a
352 // reload, while only a different ref would be in-page (pages can't clear
353 // refs without reload, only change to "#" which we don't count as empty).
354 bool IsURLInPageNavigation(const GURL& url) const;
355
356 // Copies the navigation state from the given controller to this one. This
357 // one should be empty (just created).
358 void CopyStateFrom(const NavigationController& source);
359
360 // A variant of CopyStateFrom. Removes all entries from this except the last
361 // entry, inserts all entries from |source| before and including the active
362 // entry. This method is intended for use when the last entry of |this| is the
363 // active entry. For example:
364 // source: A B *C* D
365 // this: E F *G* (last must be active or pending)
366 // result: A B *G*
367 // This ignores the transient index of the source and honors that of 'this'.
[email protected]43032342011-03-21 14:10:31368 //
369 // If |remove_first_entry| is true, the first NavigationEntry is removed
370 // from this before merging.
371 void CopyStateFromAndPrune(NavigationController* source,
372 bool remove_first_entry);
[email protected]0dd3a0ab2011-02-18 08:17:44373
374 // Removes all the entries except the active entry. If there is a new pending
375 // navigation it is preserved.
376 void PruneAllButActive();
377
378 // Random data ---------------------------------------------------------------
379
380 // Returns the identifier used by session restore.
381 const SessionID& session_id() const { return session_id_; }
382
383 // Identifier of the window we're in.
384 void SetWindowID(const SessionID& id);
385 const SessionID& window_id() const { return window_id_; }
386
387 SSLManager* ssl_manager() { return &ssl_manager_; }
388
389 // Returns true if a reload happens when activated (SetActive(true) is
390 // invoked). This is true for session/tab restore and cloned tabs.
391 bool needs_reload() const { return needs_reload_; }
392
393 // Sets the max restored page ID this NavigationController has seen, if it
394 // was restored from a previous session.
395 void set_max_restored_page_id(int32 max_id) {
396 max_restored_page_id_ = max_id;
397 }
398
399 // Returns the largest restored page ID seen in this navigation controller,
400 // if it was restored from a previous session. (-1 otherwise)
401 int32 max_restored_page_id() const { return max_restored_page_id_; }
402
403 // The session storage namespace that all child render views should use.
404 SessionStorageNamespace* session_storage_namespace() const {
405 return session_storage_namespace_;
406 }
407
408 // Disables checking for a repost and prompting the user. This is used during
409 // testing.
410 static void DisablePromptOnRepost();
411
412 // Maximum number of entries before we start removing entries from the front.
413#ifdef UNIT_TEST
414 static void set_max_entry_count(size_t max_entry_count) {
415 max_entry_count_ = max_entry_count;
416 }
417#endif
418 static size_t max_entry_count() { return max_entry_count_; }
419
420 // Cancels a repost that brought up a warning.
421 void CancelPendingReload();
422 // Continues a repost that brought up a warning.
423 void ContinuePendingReload();
424
425 // Returns true if we are navigating to the URL the tab is opened with.
426 bool IsInitialNavigation();
427
428 // Creates navigation entry and translates the virtual url to a real one.
429 // Used when restoring a tab from a TabNavigation object and when navigating
430 // to a new URL using LoadURL.
431 static NavigationEntry* CreateNavigationEntry(const GURL& url,
432 const GURL& referrer,
433 PageTransition::Type transition,
434 Profile* profile);
435
436 private:
437 class RestoreHelper;
438 friend class RestoreHelper;
439 friend class TabContents; // For invoking OnReservedPageIDRange.
440
441 // Classifies the given renderer navigation (see the NavigationType enum).
442 NavigationType::Type ClassifyNavigation(
443 const ViewHostMsg_FrameNavigate_Params& params) const;
444
445 // Causes the controller to load the specified entry. The function assumes
446 // ownership of the pointer since it is put in the navigation list.
447 // NOTE: Do not pass an entry that the controller already owns!
448 void LoadEntry(NavigationEntry* entry);
449
450 // Handlers for the different types of navigation types. They will actually
451 // handle the navigations corresponding to the different NavClasses above.
452 // They will NOT broadcast the commit notification, that should be handled by
453 // the caller.
454 //
455 // RendererDidNavigateAutoSubframe is special, it may not actually change
456 // anything if some random subframe is loaded. It will return true if anything
457 // changed, or false if not.
458 //
459 // The functions taking |did_replace_entry| will fill into the given variable
460 // whether the last entry has been replaced or not.
461 // See LoadCommittedDetails.did_replace_entry.
462 void RendererDidNavigateToNewPage(
463 const ViewHostMsg_FrameNavigate_Params& params, bool* did_replace_entry);
464 void RendererDidNavigateToExistingPage(
465 const ViewHostMsg_FrameNavigate_Params& params);
466 void RendererDidNavigateToSamePage(
467 const ViewHostMsg_FrameNavigate_Params& params);
468 void RendererDidNavigateInPage(
469 const ViewHostMsg_FrameNavigate_Params& params, bool* did_replace_entry);
470 void RendererDidNavigateNewSubframe(
471 const ViewHostMsg_FrameNavigate_Params& params);
472 bool RendererDidNavigateAutoSubframe(
473 const ViewHostMsg_FrameNavigate_Params& params);
474
475 // Helper function for code shared between Reload() and ReloadIgnoringCache().
476 void ReloadInternal(bool check_for_repost, ReloadType reload_type);
477
478 // Actually issues the navigation held in pending_entry.
479 void NavigateToPendingEntry(ReloadType reload_type);
480
481 // Allows the derived class to issue notifications that a load has been
482 // committed. This will fill in the active entry to the details structure.
483 //
484 // |extra_invalidate_flags| are an additional set of flags (InvalidateTypes)
485 // added to the flags sent to the delegate's NotifyNavigationStateChanged.
486 void NotifyNavigationEntryCommitted(LoadCommittedDetails* details,
487 int extra_invalidate_flags);
488
489 // Updates the virtual URL of an entry to match a new URL, for cases where
490 // the real renderer URL is derived from the virtual URL, like view-source:
491 void UpdateVirtualURLToURL(NavigationEntry* entry, const GURL& new_url);
492
493 // Invoked after session/tab restore or cloning a tab. Resets the transition
494 // type of the entries, updates the max page id and creates the active
495 // contents. See RestoreFromState for a description of from_last_session.
496 void FinishRestore(int selected_index, bool from_last_session);
497
498 // Inserts a new entry or replaces the current entry with a new one, removing
499 // all entries after it. The new entry will become the active one.
500 void InsertOrReplaceEntry(NavigationEntry* entry, bool replace);
501
[email protected]43032342011-03-21 14:10:31502 // Removes the entry at |index|.
503 void RemoveEntryAtIndexInternal(int index);
504
[email protected]0dd3a0ab2011-02-18 08:17:44505 // Discards the pending and transient entries.
506 void DiscardNonCommittedEntriesInternal();
507
508 // Discards the transient entry.
509 void DiscardTransientEntry();
510
511 // Returns true if the navigation is redirect.
512 bool IsRedirect(const ViewHostMsg_FrameNavigate_Params& params);
513
514 // Returns true if the navigation is likley to be automatic rather than
515 // user-initiated.
516 bool IsLikelyAutoNavigation(base::TimeTicks now);
517
518 // Creates a new NavigationEntry for each TabNavigation in navigations, adding
519 // the NavigationEntry to entries. This is used during session restore.
520 void CreateNavigationEntriesFromTabNavigations(
521 const std::vector<TabNavigation>& navigations,
522 std::vector<linked_ptr<NavigationEntry> >* entries);
523
524 // Inserts up to |max_index| entries from |source| into this. This does NOT
525 // adjust any of the members that reference entries_
526 // (last_committed_entry_index_, pending_entry_index_ or
527 // transient_entry_index_).
528 void InsertEntriesFrom(const NavigationController& source, int max_index);
529
530 // ---------------------------------------------------------------------------
531
532 // The user profile associated with this controller
533 Profile* profile_;
534
535 // List of NavigationEntry for this tab
536 typedef std::vector<linked_ptr<NavigationEntry> > NavigationEntries;
537 NavigationEntries entries_;
538
539 // An entry we haven't gotten a response for yet. This will be discarded
540 // when we navigate again. It's used only so we know what the currently
541 // displayed tab is.
542 //
543 // This may refer to an item in the entries_ list if the pending_entry_index_
544 // == -1, or it may be its own entry that should be deleted. Be careful with
545 // the memory management.
546 NavigationEntry* pending_entry_;
547
548 // currently visible entry
549 int last_committed_entry_index_;
550
551 // index of pending entry if it is in entries_, or -1 if pending_entry_ is a
552 // new entry (created by LoadURL).
553 int pending_entry_index_;
554
555 // The index for the entry that is shown until a navigation occurs. This is
556 // used for interstitial pages. -1 if there are no such entry.
557 // Note that this entry really appears in the list of entries, but only
558 // temporarily (until the next navigation). Any index pointing to an entry
559 // after the transient entry will become invalid if you navigate forward.
560 int transient_entry_index_;
561
562 // The tab contents associated with the controller. Possibly NULL during
563 // setup.
564 TabContents* tab_contents_;
565
566 // The max restored page ID in this controller, if it was restored. We must
567 // store this so that TabContents can tell any renderer in charge of one of
568 // the restored entries to update its max page ID.
569 int32 max_restored_page_id_;
570
571 // Manages the SSL security UI
572 SSLManager ssl_manager_;
573
574 // Whether we need to be reloaded when made active.
575 bool needs_reload_;
576
577 // Unique identifier of this controller for session restore. This id is only
578 // unique within the current session, and is not guaranteed to be unique
579 // across sessions.
580 SessionID session_id_;
581
582 // Unique identifier of the window we're in. Used by session restore.
583 SessionID window_id_;
584
585 // The time ticks at which the last document was loaded.
586 base::TimeTicks last_document_loaded_;
587
588 // The session storage id that any (indirectly) owned RenderView should use.
589 scoped_refptr<SessionStorageNamespace> session_storage_namespace_;
590
591 // Should Reload check for post data? The default is true, but is set to false
592 // when testing.
593 static bool check_for_repost_;
594
595 // The maximum number of entries that a navigation controller can store.
596 static size_t max_entry_count_;
597
598 // If a repost is pending, its type (RELOAD or RELOAD_IGNORING_CACHE),
599 // NO_RELOAD otherwise.
600 ReloadType pending_reload_;
601
602 DISALLOW_COPY_AND_ASSIGN(NavigationController);
603};
604
605#endif // CONTENT_BROWSER_TAB_CONTENTS_NAVIGATION_CONTROLLER_H_