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.
5 #include "content/browser/frame_host/navigation_controller_impl.h"
8 #include "base/debug/trace_event.h"
9 #include "base/logging.h"
10 #include "base/strings/string_number_conversions.h" // Temporary
11 #include "base/strings/string_util.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "base/time/time.h"
14 #include "content/browser/browser_url_handler_impl.h"
15 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
16 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
17 #include "content/browser/frame_host/debug_urls.h"
18 #include "content/browser/frame_host/interstitial_page_impl.h"
19 #include "content/browser/frame_host/navigation_entry_impl.h"
20 #include "content/browser/frame_host/web_contents_screenshot_manager.h"
21 #include "content/browser/renderer_host/render_view_host_impl.h" // Temporary
22 #include "content/browser/site_instance_impl.h"
23 #include "content/common/view_messages.h"
24 #include "content/public/browser/browser_context.h"
25 #include "content/public/browser/content_browser_client.h"
26 #include "content/public/browser/invalidate_type.h"
27 #include "content/public/browser/navigation_details.h"
28 #include "content/public/browser/notification_service.h"
29 #include "content/public/browser/notification_types.h"
30 #include "content/public/browser/render_widget_host.h"
31 #include "content/public/browser/render_widget_host_view.h"
32 #include "content/public/browser/storage_partition.h"
33 #include "content/public/browser/user_metrics.h"
34 #include "content/public/common/content_client.h"
35 #include "content/public/common/content_constants.h"
36 #include "content/public/common/url_constants.h"
37 #include "net/base/escape.h"
38 #include "net/base/mime_util.h"
39 #include "net/base/net_util.h"
40 #include "skia/ext/platform_canvas.h"
45 const int kInvalidateAll = 0xFFFFFFFF;
47 // Invoked when entries have been pruned, or removed. For example, if the
48 // current entries are [google, digg, yahoo], with the current entry google,
49 // and the user types in cnet, then digg and yahoo are pruned.
50 void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
53 PrunedDetails details;
54 details.from_front = from_front;
55 details.count = count;
56 NotificationService::current()->Notify(
57 NOTIFICATION_NAV_LIST_PRUNED,
58 Source<NavigationController>(nav_controller),
59 Details<PrunedDetails>(&details));
62 // Ensure the given NavigationEntry has a valid state, so that WebKit does not
63 // get confused if we navigate back to it.
65 // An empty state is treated as a new navigation by WebKit, which would mean
66 // losing the navigation entries and generating a new navigation entry after
67 // this one. We don't want that. To avoid this we create a valid state which
68 // WebKit will not treat as a new navigation.
69 void SetPageStateIfEmpty(NavigationEntryImpl* entry) {
70 if (!entry->GetPageState().IsValid())
71 entry->SetPageState(PageState::CreateFromURL(entry->GetURL()));
74 NavigationEntryImpl::RestoreType ControllerRestoreTypeToEntryType(
75 NavigationController::RestoreType type) {
77 case NavigationController::RESTORE_CURRENT_SESSION:
78 return NavigationEntryImpl::RESTORE_CURRENT_SESSION;
79 case NavigationController::RESTORE_LAST_SESSION_EXITED_CLEANLY:
80 return NavigationEntryImpl::RESTORE_LAST_SESSION_EXITED_CLEANLY;
81 case NavigationController::RESTORE_LAST_SESSION_CRASHED:
82 return NavigationEntryImpl::RESTORE_LAST_SESSION_CRASHED;
85 return NavigationEntryImpl::RESTORE_CURRENT_SESSION;
88 // Configure all the NavigationEntries in entries for restore. This resets
89 // the transition type to reload and makes sure the content state isn't empty.
90 void ConfigureEntriesForRestore(
91 std::vector<linked_ptr<NavigationEntryImpl> >* entries,
92 NavigationController::RestoreType type) {
93 for (size_t i = 0; i < entries->size(); ++i) {
94 // Use a transition type of reload so that we don't incorrectly increase
96 (*entries)[i]->SetTransitionType(PAGE_TRANSITION_RELOAD);
97 (*entries)[i]->set_restore_type(ControllerRestoreTypeToEntryType(type));
98 // NOTE(darin): This code is only needed for backwards compat.
99 SetPageStateIfEmpty((*entries)[i].get());
103 // See NavigationController::IsURLInPageNavigation for how this works and why.
104 bool AreURLsInPageNavigation(const GURL& existing_url,
106 bool renderer_says_in_page,
107 NavigationType navigation_type) {
108 if (existing_url == new_url)
109 return renderer_says_in_page;
111 if (!new_url.has_ref()) {
112 // When going back from the ref URL to the non ref one the navigation type
114 return navigation_type == NAVIGATION_TYPE_IN_PAGE;
117 url_canon::Replacements<char> replacements;
118 replacements.ClearRef();
119 return existing_url.ReplaceComponents(replacements) ==
120 new_url.ReplaceComponents(replacements);
123 // Determines whether or not we should be carrying over a user agent override
124 // between two NavigationEntries.
125 bool ShouldKeepOverride(const NavigationEntry* last_entry) {
126 return last_entry && last_entry->GetIsOverridingUserAgent();
131 // NavigationControllerImpl ----------------------------------------------------
133 const size_t kMaxEntryCountForTestingNotSet = -1;
136 size_t NavigationControllerImpl::max_entry_count_for_testing_ =
137 kMaxEntryCountForTestingNotSet;
139 // Should Reload check for post data? The default is true, but is set to false
141 static bool g_check_for_repost = true;
144 NavigationEntry* NavigationController::CreateNavigationEntry(
146 const Referrer& referrer,
147 PageTransition transition,
148 bool is_renderer_initiated,
149 const std::string& extra_headers,
150 BrowserContext* browser_context) {
151 // Allow the browser URL handler to rewrite the URL. This will, for example,
152 // remove "view-source:" from the beginning of the URL to get the URL that
153 // will actually be loaded. This real URL won't be shown to the user, just
155 GURL loaded_url(url);
156 bool reverse_on_redirect = false;
157 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
158 &loaded_url, browser_context, &reverse_on_redirect);
160 NavigationEntryImpl* entry = new NavigationEntryImpl(
161 NULL, // The site instance for tabs is sent on navigation
162 // (WebContents::GetSiteInstance).
168 is_renderer_initiated);
169 entry->SetVirtualURL(url);
170 entry->set_user_typed_url(url);
171 entry->set_update_virtual_url_with_url(reverse_on_redirect);
172 entry->set_extra_headers(extra_headers);
177 void NavigationController::DisablePromptOnRepost() {
178 g_check_for_repost = false;
181 base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
183 // If |t| is between the water marks, we're in a run of duplicates
184 // or just getting out of it, so increase the high-water mark to get
185 // a time that probably hasn't been used before and return it.
186 if (low_water_mark_ <= t && t <= high_water_mark_) {
187 high_water_mark_ += base::TimeDelta::FromMicroseconds(1);
188 return high_water_mark_;
191 // Otherwise, we're clear of the last duplicate run, so reset the
193 low_water_mark_ = high_water_mark_ = t;
197 NavigationControllerImpl::NavigationControllerImpl(
198 NavigationControllerDelegate* delegate,
199 BrowserContext* browser_context)
200 : browser_context_(browser_context),
201 pending_entry_(NULL),
202 last_committed_entry_index_(-1),
203 pending_entry_index_(-1),
204 transient_entry_index_(-1),
206 max_restored_page_id_(-1),
208 needs_reload_(false),
209 is_initial_navigation_(true),
210 pending_reload_(NO_RELOAD),
211 get_timestamp_callback_(base::Bind(&base::Time::Now)),
212 screenshot_manager_(new WebContentsScreenshotManager(this)) {
213 DCHECK(browser_context_);
216 NavigationControllerImpl::~NavigationControllerImpl() {
217 DiscardNonCommittedEntriesInternal();
220 WebContents* NavigationControllerImpl::GetWebContents() const {
221 return delegate_->GetWebContents();
224 BrowserContext* NavigationControllerImpl::GetBrowserContext() const {
225 return browser_context_;
228 void NavigationControllerImpl::SetBrowserContext(
229 BrowserContext* browser_context) {
230 browser_context_ = browser_context;
233 void NavigationControllerImpl::Restore(
234 int selected_navigation,
236 std::vector<NavigationEntry*>* entries) {
237 // Verify that this controller is unused and that the input is valid.
238 DCHECK(GetEntryCount() == 0 && !GetPendingEntry());
239 DCHECK(selected_navigation >= 0 &&
240 selected_navigation < static_cast<int>(entries->size()));
242 needs_reload_ = true;
243 for (size_t i = 0; i < entries->size(); ++i) {
244 NavigationEntryImpl* entry =
245 NavigationEntryImpl::FromNavigationEntry((*entries)[i]);
246 entries_.push_back(linked_ptr<NavigationEntryImpl>(entry));
250 // And finish the restore.
251 FinishRestore(selected_navigation, type);
254 void NavigationControllerImpl::Reload(bool check_for_repost) {
255 ReloadInternal(check_for_repost, RELOAD);
257 void NavigationControllerImpl::ReloadIgnoringCache(bool check_for_repost) {
258 ReloadInternal(check_for_repost, RELOAD_IGNORING_CACHE);
260 void NavigationControllerImpl::ReloadOriginalRequestURL(bool check_for_repost) {
261 ReloadInternal(check_for_repost, RELOAD_ORIGINAL_REQUEST_URL);
264 void NavigationControllerImpl::ReloadInternal(bool check_for_repost,
265 ReloadType reload_type) {
266 if (transient_entry_index_ != -1) {
267 // If an interstitial is showing, treat a reload as a navigation to the
268 // transient entry's URL.
269 NavigationEntryImpl* transient_entry =
270 NavigationEntryImpl::FromNavigationEntry(GetTransientEntry());
271 if (!transient_entry)
273 LoadURL(transient_entry->GetURL(),
275 PAGE_TRANSITION_RELOAD,
276 transient_entry->extra_headers());
280 NavigationEntryImpl* entry = NULL;
281 int current_index = -1;
283 // If we are reloading the initial navigation, just use the current
284 // pending entry. Otherwise look up the current entry.
285 if (IsInitialNavigation() && pending_entry_) {
286 entry = pending_entry_;
287 // The pending entry might be in entries_ (e.g., after a Clone), so we
288 // should also update the current_index.
289 current_index = pending_entry_index_;
291 DiscardNonCommittedEntriesInternal();
292 current_index = GetCurrentEntryIndex();
293 if (current_index != -1) {
294 entry = NavigationEntryImpl::FromNavigationEntry(
295 GetEntryAtIndex(current_index));
299 // If we are no where, then we can't reload. TODO(darin): We should add a
304 if (reload_type == NavigationControllerImpl::RELOAD_ORIGINAL_REQUEST_URL &&
305 entry->GetOriginalRequestURL().is_valid() && !entry->GetHasPostData()) {
306 // We may have been redirected when navigating to the current URL.
307 // Use the URL the user originally intended to visit, if it's valid and if a
308 // POST wasn't involved; the latter case avoids issues with sending data to
310 entry->SetURL(entry->GetOriginalRequestURL());
313 if (g_check_for_repost && check_for_repost &&
314 entry->GetHasPostData()) {
315 // The user is asking to reload a page with POST data. Prompt to make sure
316 // they really want to do this. If they do, the dialog will call us back
317 // with check_for_repost = false.
318 delegate_->NotifyBeforeFormRepostWarningShow();
320 pending_reload_ = reload_type;
321 delegate_->ActivateAndShowRepostFormWarningDialog();
323 if (!IsInitialNavigation())
324 DiscardNonCommittedEntriesInternal();
326 // If we are reloading an entry that no longer belongs to the current
327 // site instance (for example, refreshing a page for just installed app),
328 // the reload must happen in a new process.
329 // The new entry must have a new page_id and site instance, so it behaves
330 // as new navigation (which happens to clear forward history).
331 // Tabs that are discarded due to low memory conditions may not have a site
332 // instance, and should not be treated as a cross-site reload.
333 SiteInstanceImpl* site_instance = entry->site_instance();
335 site_instance->HasWrongProcessForURL(entry->GetURL())) {
336 // Create a navigation entry that resembles the current one, but do not
337 // copy page id, site instance, content state, or timestamp.
338 NavigationEntryImpl* nav_entry = NavigationEntryImpl::FromNavigationEntry(
339 CreateNavigationEntry(
340 entry->GetURL(), entry->GetReferrer(), entry->GetTransitionType(),
341 false, entry->extra_headers(), browser_context_));
343 // Mark the reload type as NO_RELOAD, so navigation will not be considered
344 // a reload in the renderer.
345 reload_type = NavigationController::NO_RELOAD;
347 nav_entry->set_should_replace_entry(true);
348 pending_entry_ = nav_entry;
350 pending_entry_ = entry;
351 pending_entry_index_ = current_index;
353 // The title of the page being reloaded might have been removed in the
354 // meanwhile, so we need to revert to the default title upon reload and
355 // invalidate the previously cached title (SetTitle will do both).
356 // See Chromium issue 96041.
357 pending_entry_->SetTitle(string16());
359 pending_entry_->SetTransitionType(PAGE_TRANSITION_RELOAD);
362 NavigateToPendingEntry(reload_type);
366 void NavigationControllerImpl::CancelPendingReload() {
367 DCHECK(pending_reload_ != NO_RELOAD);
368 pending_reload_ = NO_RELOAD;
371 void NavigationControllerImpl::ContinuePendingReload() {
372 if (pending_reload_ == NO_RELOAD) {
375 ReloadInternal(false, pending_reload_);
376 pending_reload_ = NO_RELOAD;
380 bool NavigationControllerImpl::IsInitialNavigation() const {
381 return is_initial_navigation_;
384 NavigationEntryImpl* NavigationControllerImpl::GetEntryWithPageID(
385 SiteInstance* instance, int32 page_id) const {
386 int index = GetEntryIndexWithPageID(instance, page_id);
387 return (index != -1) ? entries_[index].get() : NULL;
390 void NavigationControllerImpl::LoadEntry(NavigationEntryImpl* entry) {
391 // When navigating to a new page, we don't know for sure if we will actually
392 // end up leaving the current page. The new page load could for example
393 // result in a download or a 'no content' response (e.g., a mailto: URL).
394 SetPendingEntry(entry);
395 NavigateToPendingEntry(NO_RELOAD);
398 void NavigationControllerImpl::SetPendingEntry(NavigationEntryImpl* entry) {
399 DiscardNonCommittedEntriesInternal();
400 pending_entry_ = entry;
401 NotificationService::current()->Notify(
402 NOTIFICATION_NAV_ENTRY_PENDING,
403 Source<NavigationController>(this),
404 Details<NavigationEntry>(entry));
407 NavigationEntry* NavigationControllerImpl::GetActiveEntry() const {
408 if (transient_entry_index_ != -1)
409 return entries_[transient_entry_index_].get();
411 return pending_entry_;
412 return GetLastCommittedEntry();
415 NavigationEntry* NavigationControllerImpl::GetVisibleEntry() const {
416 if (transient_entry_index_ != -1)
417 return entries_[transient_entry_index_].get();
418 // The pending entry is safe to return for new (non-history), browser-
419 // initiated navigations. Most renderer-initiated navigations should not
420 // show the pending entry, to prevent URL spoof attacks.
422 // We make an exception for renderer-initiated navigations in new tabs, as
423 // long as no other page has tried to access the initial empty document in
424 // the new tab. If another page modifies this blank page, a URL spoof is
425 // possible, so we must stop showing the pending entry.
426 RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>(
427 delegate_->GetRenderViewHost());
428 bool safe_to_show_pending =
430 // Require a new navigation.
431 pending_entry_->GetPageID() == -1 &&
432 // Require either browser-initiated or an unmodified new tab.
433 (!pending_entry_->is_renderer_initiated() ||
434 (IsInitialNavigation() &&
435 !GetLastCommittedEntry() &&
436 !rvh->has_accessed_initial_document()));
438 // Also allow showing the pending entry for history navigations in a new tab,
439 // such as Ctrl+Back. In this case, no existing page is visible and no one
440 // can script the new tab before it commits.
441 if (!safe_to_show_pending &&
443 pending_entry_->GetPageID() != -1 &&
444 IsInitialNavigation() &&
445 !pending_entry_->is_renderer_initiated())
446 safe_to_show_pending = true;
448 if (safe_to_show_pending)
449 return pending_entry_;
450 return GetLastCommittedEntry();
453 int NavigationControllerImpl::GetCurrentEntryIndex() const {
454 if (transient_entry_index_ != -1)
455 return transient_entry_index_;
456 if (pending_entry_index_ != -1)
457 return pending_entry_index_;
458 return last_committed_entry_index_;
461 NavigationEntry* NavigationControllerImpl::GetLastCommittedEntry() const {
462 if (last_committed_entry_index_ == -1)
464 return entries_[last_committed_entry_index_].get();
467 bool NavigationControllerImpl::CanViewSource() const {
468 const std::string& mime_type = delegate_->GetContentsMimeType();
469 bool is_viewable_mime_type = net::IsSupportedNonImageMimeType(mime_type) &&
470 !net::IsSupportedMediaMimeType(mime_type);
471 NavigationEntry* visible_entry = GetVisibleEntry();
472 return visible_entry && !visible_entry->IsViewSourceMode() &&
473 is_viewable_mime_type && !delegate_->GetInterstitialPage();
476 int NavigationControllerImpl::GetLastCommittedEntryIndex() const {
477 return last_committed_entry_index_;
480 int NavigationControllerImpl::GetEntryCount() const {
481 DCHECK(entries_.size() <= max_entry_count());
482 return static_cast<int>(entries_.size());
485 NavigationEntry* NavigationControllerImpl::GetEntryAtIndex(
487 return entries_.at(index).get();
490 NavigationEntry* NavigationControllerImpl::GetEntryAtOffset(
492 int index = GetIndexForOffset(offset);
493 if (index < 0 || index >= GetEntryCount())
496 return entries_[index].get();
499 int NavigationControllerImpl::GetIndexForOffset(int offset) const {
500 return GetCurrentEntryIndex() + offset;
503 void NavigationControllerImpl::TakeScreenshot() {
504 screenshot_manager_->TakeScreenshot();
507 void NavigationControllerImpl::SetScreenshotManager(
508 WebContentsScreenshotManager* manager) {
509 screenshot_manager_.reset(manager ? manager :
510 new WebContentsScreenshotManager(this));
513 bool NavigationControllerImpl::CanGoBack() const {
514 return entries_.size() > 1 && GetCurrentEntryIndex() > 0;
517 bool NavigationControllerImpl::CanGoForward() const {
518 int index = GetCurrentEntryIndex();
519 return index >= 0 && index < (static_cast<int>(entries_.size()) - 1);
522 bool NavigationControllerImpl::CanGoToOffset(int offset) const {
523 int index = GetIndexForOffset(offset);
524 return index >= 0 && index < GetEntryCount();
527 void NavigationControllerImpl::GoBack() {
533 // Base the navigation on where we are now...
534 int current_index = GetCurrentEntryIndex();
536 DiscardNonCommittedEntries();
538 pending_entry_index_ = current_index - 1;
539 entries_[pending_entry_index_]->SetTransitionType(
540 PageTransitionFromInt(
541 entries_[pending_entry_index_]->GetTransitionType() |
542 PAGE_TRANSITION_FORWARD_BACK));
543 NavigateToPendingEntry(NO_RELOAD);
546 void NavigationControllerImpl::GoForward() {
547 if (!CanGoForward()) {
552 bool transient = (transient_entry_index_ != -1);
554 // Base the navigation on where we are now...
555 int current_index = GetCurrentEntryIndex();
557 DiscardNonCommittedEntries();
559 pending_entry_index_ = current_index;
560 // If there was a transient entry, we removed it making the current index
563 pending_entry_index_++;
565 entries_[pending_entry_index_]->SetTransitionType(
566 PageTransitionFromInt(
567 entries_[pending_entry_index_]->GetTransitionType() |
568 PAGE_TRANSITION_FORWARD_BACK));
569 NavigateToPendingEntry(NO_RELOAD);
572 void NavigationControllerImpl::GoToIndex(int index) {
573 if (index < 0 || index >= static_cast<int>(entries_.size())) {
578 if (transient_entry_index_ != -1) {
579 if (index == transient_entry_index_) {
580 // Nothing to do when navigating to the transient.
583 if (index > transient_entry_index_) {
584 // Removing the transient is goint to shift all entries by 1.
589 DiscardNonCommittedEntries();
591 pending_entry_index_ = index;
592 entries_[pending_entry_index_]->SetTransitionType(
593 PageTransitionFromInt(
594 entries_[pending_entry_index_]->GetTransitionType() |
595 PAGE_TRANSITION_FORWARD_BACK));
596 NavigateToPendingEntry(NO_RELOAD);
599 void NavigationControllerImpl::GoToOffset(int offset) {
600 if (!CanGoToOffset(offset))
603 GoToIndex(GetIndexForOffset(offset));
606 bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
607 if (index == last_committed_entry_index_ ||
608 index == pending_entry_index_)
611 RemoveEntryAtIndexInternal(index);
615 void NavigationControllerImpl::UpdateVirtualURLToURL(
616 NavigationEntryImpl* entry, const GURL& new_url) {
617 GURL new_virtual_url(new_url);
618 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
619 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
620 entry->SetVirtualURL(new_virtual_url);
624 void NavigationControllerImpl::LoadURL(
626 const Referrer& referrer,
627 PageTransition transition,
628 const std::string& extra_headers) {
629 LoadURLParams params(url);
630 params.referrer = referrer;
631 params.transition_type = transition;
632 params.extra_headers = extra_headers;
633 LoadURLWithParams(params);
636 void NavigationControllerImpl::LoadURLWithParams(const LoadURLParams& params) {
637 TRACE_EVENT0("browser", "NavigationControllerImpl::LoadURLWithParams");
638 if (HandleDebugURL(params.url, params.transition_type))
641 // Checks based on params.load_type.
642 switch (params.load_type) {
643 case LOAD_TYPE_DEFAULT:
645 case LOAD_TYPE_BROWSER_INITIATED_HTTP_POST:
646 if (!params.url.SchemeIs(kHttpScheme) &&
647 !params.url.SchemeIs(kHttpsScheme)) {
648 NOTREACHED() << "Http post load must use http(s) scheme.";
653 if (!params.url.SchemeIs(chrome::kDataScheme)) {
654 NOTREACHED() << "Data load must use data scheme.";
663 // The user initiated a load, we don't need to reload anymore.
664 needs_reload_ = false;
666 bool override = false;
667 switch (params.override_user_agent) {
668 case UA_OVERRIDE_INHERIT:
669 override = ShouldKeepOverride(GetLastCommittedEntry());
671 case UA_OVERRIDE_TRUE:
674 case UA_OVERRIDE_FALSE:
682 NavigationEntryImpl* entry = NavigationEntryImpl::FromNavigationEntry(
683 CreateNavigationEntry(
686 params.transition_type,
687 params.is_renderer_initiated,
688 params.extra_headers,
690 if (params.redirect_chain.size() > 0)
691 entry->set_redirect_chain(params.redirect_chain);
692 if (params.should_replace_current_entry)
693 entry->set_should_replace_entry(true);
694 entry->set_should_clear_history_list(params.should_clear_history_list);
695 entry->SetIsOverridingUserAgent(override);
696 entry->set_transferred_global_request_id(
697 params.transferred_global_request_id);
698 entry->SetFrameToNavigate(params.frame_name);
700 switch (params.load_type) {
701 case LOAD_TYPE_DEFAULT:
703 case LOAD_TYPE_BROWSER_INITIATED_HTTP_POST:
704 entry->SetHasPostData(true);
705 entry->SetBrowserInitiatedPostData(
706 params.browser_initiated_post_data.get());
709 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
710 entry->SetVirtualURL(params.virtual_url_for_data_url);
711 entry->SetCanLoadLocalResources(params.can_load_local_resources);
721 bool NavigationControllerImpl::RendererDidNavigate(
722 const ViewHostMsg_FrameNavigate_Params& params,
723 LoadCommittedDetails* details) {
724 is_initial_navigation_ = false;
726 // Save the previous state before we clobber it.
727 if (GetLastCommittedEntry()) {
728 details->previous_url = GetLastCommittedEntry()->GetURL();
729 details->previous_entry_index = GetLastCommittedEntryIndex();
731 details->previous_url = GURL();
732 details->previous_entry_index = -1;
735 // If we have a pending entry at this point, it should have a SiteInstance.
736 // Restored entries start out with a null SiteInstance, but we should have
737 // assigned one in NavigateToPendingEntry.
738 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance());
740 // If we are doing a cross-site reload, we need to replace the existing
741 // navigation entry, not add another entry to the history. This has the side
742 // effect of removing forward browsing history, if such existed.
743 // Or if we are doing a cross-site redirect navigation,
744 // we will do a similar thing.
745 details->did_replace_entry =
746 pending_entry_ && pending_entry_->should_replace_entry();
748 // Do navigation-type specific actions. These will make and commit an entry.
749 details->type = ClassifyNavigation(params);
751 // is_in_page must be computed before the entry gets committed.
752 details->is_in_page = IsURLInPageNavigation(
753 params.url, params.was_within_same_page, details->type);
755 switch (details->type) {
756 case NAVIGATION_TYPE_NEW_PAGE:
757 RendererDidNavigateToNewPage(params, details->did_replace_entry);
759 case NAVIGATION_TYPE_EXISTING_PAGE:
760 RendererDidNavigateToExistingPage(params);
762 case NAVIGATION_TYPE_SAME_PAGE:
763 RendererDidNavigateToSamePage(params);
765 case NAVIGATION_TYPE_IN_PAGE:
766 RendererDidNavigateInPage(params, &details->did_replace_entry);
768 case NAVIGATION_TYPE_NEW_SUBFRAME:
769 RendererDidNavigateNewSubframe(params);
771 case NAVIGATION_TYPE_AUTO_SUBFRAME:
772 if (!RendererDidNavigateAutoSubframe(params))
775 case NAVIGATION_TYPE_NAV_IGNORE:
776 // If a pending navigation was in progress, this canceled it. We should
777 // discard it and make sure it is removed from the URL bar. After that,
778 // there is nothing we can do with this navigation, so we just return to
779 // the caller that nothing has happened.
780 if (pending_entry_) {
781 DiscardNonCommittedEntries();
782 delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
789 // At this point, we know that the navigation has just completed, so
792 // TODO(akalin): Use "sane time" as described in
793 // http://www.chromium.org/developers/design-documents/sane-time .
794 base::Time timestamp =
795 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
796 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
797 << timestamp.ToInternalValue();
799 // We should not have a pending entry anymore. Clear it again in case any
800 // error cases above forgot to do so.
801 DiscardNonCommittedEntriesInternal();
803 // All committed entries should have nonempty content state so WebKit doesn't
804 // get confused when we go back to them (see the function for details).
805 DCHECK(params.page_state.IsValid());
806 NavigationEntryImpl* active_entry =
807 NavigationEntryImpl::FromNavigationEntry(GetLastCommittedEntry());
808 active_entry->SetTimestamp(timestamp);
809 active_entry->SetHttpStatusCode(params.http_status_code);
810 active_entry->SetPageState(params.page_state);
812 // Once it is committed, we no longer need to track several pieces of state on
814 active_entry->ResetForCommit();
816 // The active entry's SiteInstance should match our SiteInstance.
817 CHECK(active_entry->site_instance() == delegate_->GetSiteInstance());
819 // Remember the bindings the renderer process has at this point, so that
820 // we do not grant this entry additional bindings if we come back to it.
821 active_entry->SetBindings(
822 delegate_->GetRenderViewHost()->GetEnabledBindings());
824 // Now prep the rest of the details for the notification and broadcast.
825 details->entry = active_entry;
826 details->is_main_frame =
827 PageTransitionIsMainFrame(params.transition);
828 details->serialized_security_info = params.security_info;
829 details->http_status_code = params.http_status_code;
830 NotifyNavigationEntryCommitted(details);
835 NavigationType NavigationControllerImpl::ClassifyNavigation(
836 const ViewHostMsg_FrameNavigate_Params& params) const {
837 if (params.page_id == -1) {
838 // The renderer generates the page IDs, and so if it gives us the invalid
839 // page ID (-1) we know it didn't actually navigate. This happens in a few
842 // - If a page makes a popup navigated to about blank, and then writes
843 // stuff like a subframe navigated to a real page. We'll get the commit
844 // for the subframe, but there won't be any commit for the outer page.
846 // - We were also getting these for failed loads (for example, bug 21849).
847 // The guess is that we get a "load commit" for the alternate error page,
848 // but that doesn't affect the page ID, so we get the "old" one, which
849 // could be invalid. This can also happen for a cross-site transition
850 // that causes us to swap processes. Then the error page load will be in
851 // a new process with no page IDs ever assigned (and hence a -1 value),
852 // yet the navigation controller still might have previous pages in its
855 // In these cases, there's nothing we can do with them, so ignore.
856 return NAVIGATION_TYPE_NAV_IGNORE;
859 if (params.page_id > delegate_->GetMaxPageID()) {
860 // Greater page IDs than we've ever seen before are new pages. We may or may
861 // not have a pending entry for the page, and this may or may not be the
863 if (PageTransitionIsMainFrame(params.transition))
864 return NAVIGATION_TYPE_NEW_PAGE;
866 // When this is a new subframe navigation, we should have a committed page
867 // for which it's a suframe in. This may not be the case when an iframe is
868 // navigated on a popup navigated to about:blank (the iframe would be
869 // written into the popup by script on the main page). For these cases,
870 // there isn't any navigation stuff we can do, so just ignore it.
871 if (!GetLastCommittedEntry())
872 return NAVIGATION_TYPE_NAV_IGNORE;
874 // Valid subframe navigation.
875 return NAVIGATION_TYPE_NEW_SUBFRAME;
878 // We only clear the session history when navigating to a new page.
879 DCHECK(!params.history_list_was_cleared);
881 // Now we know that the notification is for an existing page. Find that entry.
882 int existing_entry_index = GetEntryIndexWithPageID(
883 delegate_->GetSiteInstance(),
885 if (existing_entry_index == -1) {
886 // The page was not found. It could have been pruned because of the limit on
887 // back/forward entries (not likely since we'll usually tell it to navigate
888 // to such entries). It could also mean that the renderer is smoking crack.
891 // Because the unknown entry has committed, we risk showing the wrong URL in
892 // release builds. Instead, we'll kill the renderer process to be safe.
893 LOG(ERROR) << "terminating renderer for bad navigation: " << params.url;
894 RecordAction(UserMetricsAction("BadMessageTerminate_NC"));
896 // Temporary code so we can get more information. Format:
897 // http://url/foo.html#page1#max3#frame1#ids:2_Nx,1_1x,3_2
898 std::string temp = params.url.spec();
899 temp.append("#page");
900 temp.append(base::IntToString(params.page_id));
902 temp.append(base::IntToString(delegate_->GetMaxPageID()));
903 temp.append("#frame");
904 temp.append(base::IntToString(params.frame_id));
906 for (int i = 0; i < static_cast<int>(entries_.size()); ++i) {
907 // Append entry metadata (e.g., 3_7x):
909 // 7: SiteInstance ID, or N for null
910 // x: appended if not from the current SiteInstance
911 temp.append(base::IntToString(entries_[i]->GetPageID()));
913 if (entries_[i]->site_instance())
914 temp.append(base::IntToString(entries_[i]->site_instance()->GetId()));
917 if (entries_[i]->site_instance() != delegate_->GetSiteInstance())
922 static_cast<RenderViewHostImpl*>(
923 delegate_->GetRenderViewHost())->Send(
924 new ViewMsg_TempCrashWithData(url));
925 return NAVIGATION_TYPE_NAV_IGNORE;
927 NavigationEntryImpl* existing_entry = entries_[existing_entry_index].get();
929 if (!PageTransitionIsMainFrame(params.transition)) {
930 // All manual subframes would get new IDs and were handled above, so we
931 // know this is auto. Since the current page was found in the navigation
932 // entry list, we're guaranteed to have a last committed entry.
933 DCHECK(GetLastCommittedEntry());
934 return NAVIGATION_TYPE_AUTO_SUBFRAME;
937 // Anything below here we know is a main frame navigation.
938 if (pending_entry_ &&
939 !pending_entry_->is_renderer_initiated() &&
940 existing_entry != pending_entry_ &&
941 pending_entry_->GetPageID() == -1 &&
942 existing_entry == GetLastCommittedEntry()) {
943 // In this case, we have a pending entry for a URL but WebCore didn't do a
944 // new navigation. This happens when you press enter in the URL bar to
945 // reload. We will create a pending entry, but WebKit will convert it to
946 // a reload since it's the same page and not create a new entry for it
947 // (the user doesn't want to have a new back/forward entry when they do
948 // this). If this matches the last committed entry, we want to just ignore
949 // the pending entry and go back to where we were (the "existing entry").
950 return NAVIGATION_TYPE_SAME_PAGE;
953 // Any toplevel navigations with the same base (minus the reference fragment)
954 // are in-page navigations. We weeded out subframe navigations above. Most of
955 // the time this doesn't matter since WebKit doesn't tell us about subframe
956 // navigations that don't actually navigate, but it can happen when there is
957 // an encoding override (it always sends a navigation request).
958 if (AreURLsInPageNavigation(existing_entry->GetURL(), params.url,
959 params.was_within_same_page,
960 NAVIGATION_TYPE_UNKNOWN)) {
961 return NAVIGATION_TYPE_IN_PAGE;
964 // Since we weeded out "new" navigations above, we know this is an existing
965 // (back/forward) navigation.
966 return NAVIGATION_TYPE_EXISTING_PAGE;
969 bool NavigationControllerImpl::IsRedirect(
970 const ViewHostMsg_FrameNavigate_Params& params) {
971 // For main frame transition, we judge by params.transition.
972 // Otherwise, by params.redirects.
973 if (PageTransitionIsMainFrame(params.transition)) {
974 return PageTransitionIsRedirect(params.transition);
976 return params.redirects.size() > 1;
979 void NavigationControllerImpl::RendererDidNavigateToNewPage(
980 const ViewHostMsg_FrameNavigate_Params& params, bool replace_entry) {
981 NavigationEntryImpl* new_entry;
982 bool update_virtual_url;
983 // Only make a copy of the pending entry if it is appropriate for the new page
984 // that was just loaded. We verify this at a coarse grain by checking that
985 // the SiteInstance hasn't been assigned to something else.
986 if (pending_entry_ &&
987 (!pending_entry_->site_instance() ||
988 pending_entry_->site_instance() == delegate_->GetSiteInstance())) {
989 new_entry = new NavigationEntryImpl(*pending_entry_);
991 // Don't use the page type from the pending entry. Some interstitial page
992 // may have set the type to interstitial. Once we commit, however, the page
993 // type must always be normal.
994 new_entry->set_page_type(PAGE_TYPE_NORMAL);
995 update_virtual_url = new_entry->update_virtual_url_with_url();
997 new_entry = new NavigationEntryImpl;
999 // Find out whether the new entry needs to update its virtual URL on URL
1000 // change and set up the entry accordingly. This is needed to correctly
1001 // update the virtual URL when replaceState is called after a pushState.
1002 GURL url = params.url;
1003 bool needs_update = false;
1004 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
1005 &url, browser_context_, &needs_update);
1006 new_entry->set_update_virtual_url_with_url(needs_update);
1008 // When navigating to a new page, give the browser URL handler a chance to
1009 // update the virtual URL based on the new URL. For example, this is needed
1010 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
1012 update_virtual_url = needs_update;
1015 new_entry->SetURL(params.url);
1016 if (update_virtual_url)
1017 UpdateVirtualURLToURL(new_entry, params.url);
1018 new_entry->SetReferrer(params.referrer);
1019 new_entry->SetPageID(params.page_id);
1020 new_entry->SetTransitionType(params.transition);
1021 new_entry->set_site_instance(
1022 static_cast<SiteInstanceImpl*>(delegate_->GetSiteInstance()));
1023 new_entry->SetHasPostData(params.is_post);
1024 new_entry->SetPostID(params.post_id);
1025 new_entry->SetOriginalRequestURL(params.original_request_url);
1026 new_entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1028 DCHECK(!params.history_list_was_cleared || !replace_entry);
1029 // The browser requested to clear the session history when it initiated the
1030 // navigation. Now we know that the renderer has updated its state accordingly
1031 // and it is safe to also clear the browser side history.
1032 if (params.history_list_was_cleared) {
1033 DiscardNonCommittedEntriesInternal();
1035 last_committed_entry_index_ = -1;
1038 InsertOrReplaceEntry(new_entry, replace_entry);
1041 void NavigationControllerImpl::RendererDidNavigateToExistingPage(
1042 const ViewHostMsg_FrameNavigate_Params& params) {
1043 // We should only get here for main frame navigations.
1044 DCHECK(PageTransitionIsMainFrame(params.transition));
1046 // This is a back/forward navigation. The existing page for the ID is
1047 // guaranteed to exist by ClassifyNavigation, and we just need to update it
1048 // with new information from the renderer.
1049 int entry_index = GetEntryIndexWithPageID(delegate_->GetSiteInstance(),
1051 DCHECK(entry_index >= 0 &&
1052 entry_index < static_cast<int>(entries_.size()));
1053 NavigationEntryImpl* entry = entries_[entry_index].get();
1055 // The URL may have changed due to redirects.
1056 entry->SetURL(params.url);
1057 if (entry->update_virtual_url_with_url())
1058 UpdateVirtualURLToURL(entry, params.url);
1060 // The redirected to page should not inherit the favicon from the previous
1062 if (PageTransitionIsRedirect(params.transition))
1063 entry->GetFavicon() = FaviconStatus();
1065 // The site instance will normally be the same except during session restore,
1066 // when no site instance will be assigned.
1067 DCHECK(entry->site_instance() == NULL ||
1068 entry->site_instance() == delegate_->GetSiteInstance());
1069 entry->set_site_instance(
1070 static_cast<SiteInstanceImpl*>(delegate_->GetSiteInstance()));
1072 entry->SetHasPostData(params.is_post);
1073 entry->SetPostID(params.post_id);
1075 // The entry we found in the list might be pending if the user hit
1076 // back/forward/reload. This load should commit it (since it's already in the
1077 // list, we can just discard the pending pointer). We should also discard the
1078 // pending entry if it corresponds to a different navigation, since that one
1079 // is now likely canceled. If it is not canceled, we will treat it as a new
1080 // navigation when it arrives, which is also ok.
1082 // Note that we need to use the "internal" version since we don't want to
1083 // actually change any other state, just kill the pointer.
1084 DiscardNonCommittedEntriesInternal();
1086 // If a transient entry was removed, the indices might have changed, so we
1087 // have to query the entry index again.
1088 last_committed_entry_index_ =
1089 GetEntryIndexWithPageID(delegate_->GetSiteInstance(), params.page_id);
1092 void NavigationControllerImpl::RendererDidNavigateToSamePage(
1093 const ViewHostMsg_FrameNavigate_Params& params) {
1094 // This mode implies we have a pending entry that's the same as an existing
1095 // entry for this page ID. This entry is guaranteed to exist by
1096 // ClassifyNavigation. All we need to do is update the existing entry.
1097 NavigationEntryImpl* existing_entry = GetEntryWithPageID(
1098 delegate_->GetSiteInstance(), params.page_id);
1100 // We assign the entry's unique ID to be that of the new one. Since this is
1101 // always the result of a user action, we want to dismiss infobars, etc. like
1102 // a regular user-initiated navigation.
1103 existing_entry->set_unique_id(pending_entry_->GetUniqueID());
1105 // The URL may have changed due to redirects.
1106 if (existing_entry->update_virtual_url_with_url())
1107 UpdateVirtualURLToURL(existing_entry, params.url);
1108 existing_entry->SetURL(params.url);
1110 DiscardNonCommittedEntries();
1113 void NavigationControllerImpl::RendererDidNavigateInPage(
1114 const ViewHostMsg_FrameNavigate_Params& params, bool* did_replace_entry) {
1115 DCHECK(PageTransitionIsMainFrame(params.transition)) <<
1116 "WebKit should only tell us about in-page navs for the main frame.";
1117 // We're guaranteed to have an entry for this one.
1118 NavigationEntryImpl* existing_entry = GetEntryWithPageID(
1119 delegate_->GetSiteInstance(), params.page_id);
1121 // Reference fragment navigation. We're guaranteed to have the last_committed
1122 // entry and it will be the same page as the new navigation (minus the
1123 // reference fragments, of course). We'll update the URL of the existing
1124 // entry without pruning the forward history.
1125 existing_entry->SetURL(params.url);
1126 if (existing_entry->update_virtual_url_with_url())
1127 UpdateVirtualURLToURL(existing_entry, params.url);
1129 // This replaces the existing entry since the page ID didn't change.
1130 *did_replace_entry = true;
1132 DiscardNonCommittedEntriesInternal();
1134 // If a transient entry was removed, the indices might have changed, so we
1135 // have to query the entry index again.
1136 last_committed_entry_index_ =
1137 GetEntryIndexWithPageID(delegate_->GetSiteInstance(), params.page_id);
1140 void NavigationControllerImpl::RendererDidNavigateNewSubframe(
1141 const ViewHostMsg_FrameNavigate_Params& params) {
1142 if (PageTransitionCoreTypeIs(params.transition,
1143 PAGE_TRANSITION_AUTO_SUBFRAME)) {
1144 // This is not user-initiated. Ignore.
1145 DiscardNonCommittedEntriesInternal();
1149 // Manual subframe navigations just get the current entry cloned so the user
1150 // can go back or forward to it. The actual subframe information will be
1151 // stored in the page state for each of those entries. This happens out of
1152 // band with the actual navigations.
1153 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
1154 << "that a last committed entry exists.";
1155 NavigationEntryImpl* new_entry = new NavigationEntryImpl(
1156 *NavigationEntryImpl::FromNavigationEntry(GetLastCommittedEntry()));
1157 new_entry->SetPageID(params.page_id);
1158 InsertOrReplaceEntry(new_entry, false);
1161 bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
1162 const ViewHostMsg_FrameNavigate_Params& params) {
1163 // We're guaranteed to have a previously committed entry, and we now need to
1164 // handle navigation inside of a subframe in it without creating a new entry.
1165 DCHECK(GetLastCommittedEntry());
1167 // Handle the case where we're navigating back/forward to a previous subframe
1168 // navigation entry. This is case "2." in NAV_AUTO_SUBFRAME comment in the
1169 // header file. In case "1." this will be a NOP.
1170 int entry_index = GetEntryIndexWithPageID(
1171 delegate_->GetSiteInstance(),
1173 if (entry_index < 0 ||
1174 entry_index >= static_cast<int>(entries_.size())) {
1179 // Update the current navigation entry in case we're going back/forward.
1180 if (entry_index != last_committed_entry_index_) {
1181 last_committed_entry_index_ = entry_index;
1182 DiscardNonCommittedEntriesInternal();
1186 // We do not need to discard the pending entry in this case, since we will
1187 // not generate commit notifications for this auto-subframe navigation.
1191 int NavigationControllerImpl::GetIndexOfEntry(
1192 const NavigationEntryImpl* entry) const {
1193 const NavigationEntries::const_iterator i(std::find(
1197 return (i == entries_.end()) ? -1 : static_cast<int>(i - entries_.begin());
1200 bool NavigationControllerImpl::IsURLInPageNavigation(
1202 bool renderer_says_in_page,
1203 NavigationType navigation_type) const {
1204 NavigationEntry* last_committed = GetLastCommittedEntry();
1205 return last_committed && AreURLsInPageNavigation(
1206 last_committed->GetURL(), url, renderer_says_in_page, navigation_type);
1209 void NavigationControllerImpl::CopyStateFrom(
1210 const NavigationController& temp) {
1211 const NavigationControllerImpl& source =
1212 static_cast<const NavigationControllerImpl&>(temp);
1213 // Verify that we look new.
1214 DCHECK(GetEntryCount() == 0 && !GetPendingEntry());
1216 if (source.GetEntryCount() == 0)
1217 return; // Nothing new to do.
1219 needs_reload_ = true;
1220 InsertEntriesFrom(source, source.GetEntryCount());
1222 for (SessionStorageNamespaceMap::const_iterator it =
1223 source.session_storage_namespace_map_.begin();
1224 it != source.session_storage_namespace_map_.end();
1226 SessionStorageNamespaceImpl* source_namespace =
1227 static_cast<SessionStorageNamespaceImpl*>(it->second.get());
1228 session_storage_namespace_map_[it->first] = source_namespace->Clone();
1231 FinishRestore(source.last_committed_entry_index_, RESTORE_CURRENT_SESSION);
1233 // Copy the max page id map from the old tab to the new tab. This ensures
1234 // that new and existing navigations in the tab's current SiteInstances
1235 // are identified properly.
1236 delegate_->CopyMaxPageIDsFrom(source.delegate()->GetWebContents());
1239 void NavigationControllerImpl::CopyStateFromAndPrune(
1240 NavigationController* temp) {
1241 // It is up to callers to check the invariants before calling this.
1242 CHECK(CanPruneAllButVisible());
1244 NavigationControllerImpl* source =
1245 static_cast<NavigationControllerImpl*>(temp);
1246 // The SiteInstance and page_id of the last committed entry needs to be
1247 // remembered at this point, in case there is only one committed entry
1248 // and it is pruned. We use a scoped_refptr to ensure the SiteInstance
1249 // can't be freed during this time period.
1250 NavigationEntryImpl* last_committed =
1251 NavigationEntryImpl::FromNavigationEntry(GetLastCommittedEntry());
1252 scoped_refptr<SiteInstance> site_instance(
1253 last_committed->site_instance());
1254 int32 minimum_page_id = last_committed->GetPageID();
1256 delegate_->GetMaxPageIDForSiteInstance(site_instance.get());
1258 // Remove all the entries leaving the active entry.
1259 PruneAllButVisibleInternal();
1261 // We now have one entry, possibly with a new pending entry. Ensure that
1262 // adding the entries from source won't put us over the limit.
1263 DCHECK_EQ(1, GetEntryCount());
1264 source->PruneOldestEntryIfFull();
1266 // Insert the entries from source. Don't use source->GetCurrentEntryIndex as
1267 // we don't want to copy over the transient entry. Ignore any pending entry,
1268 // since it has not committed in source.
1269 int max_source_index = source->last_committed_entry_index_;
1270 if (max_source_index == -1)
1271 max_source_index = source->GetEntryCount();
1274 InsertEntriesFrom(*source, max_source_index);
1276 // Adjust indices such that the last entry and pending are at the end now.
1277 last_committed_entry_index_ = GetEntryCount() - 1;
1279 delegate_->SetHistoryLengthAndPrune(site_instance.get(),
1283 // Copy the max page id map from the old tab to the new tab. This ensures
1284 // that new and existing navigations in the tab's current SiteInstances
1285 // are identified properly.
1286 delegate_->CopyMaxPageIDsFrom(source->delegate()->GetWebContents());
1288 // If there is a last committed entry, be sure to include it in the new
1290 if (max_page_id > -1) {
1291 delegate_->UpdateMaxPageIDForSiteInstance(site_instance.get(),
1296 bool NavigationControllerImpl::CanPruneAllButVisible() {
1297 // If there is no last committed entry, we cannot prune. Even if there is a
1298 // pending entry, it may not commit, leaving this WebContents blank, despite
1299 // possibly giving it new entries via CopyStateFromAndPrune.
1300 if (last_committed_entry_index_ == -1)
1303 // We cannot prune if there is a pending entry at an existing entry index.
1304 // It may not commit, so we have to keep the last committed entry, and thus
1305 // there is no sensible place to keep the pending entry. It is ok to have
1306 // a new pending entry, which can optionally commit as a new navigation.
1307 if (pending_entry_index_ != -1)
1310 // We should not prune if we are currently showing a transient entry.
1311 if (transient_entry_index_ != -1)
1317 void NavigationControllerImpl::PruneAllButVisible() {
1318 PruneAllButVisibleInternal();
1320 // We should still have a last committed entry.
1321 DCHECK_NE(-1, last_committed_entry_index_);
1323 // We pass 0 instead of GetEntryCount() for the history_length parameter of
1324 // SetHistoryLengthAndPrune, because it will create history_length additional
1326 // TODO(jochen): This API is confusing and we should clean it up.
1327 // http://crbug.com/178491
1328 NavigationEntryImpl* entry =
1329 NavigationEntryImpl::FromNavigationEntry(GetVisibleEntry());
1330 delegate_->SetHistoryLengthAndPrune(
1331 entry->site_instance(), 0, entry->GetPageID());
1334 void NavigationControllerImpl::PruneAllButVisibleInternal() {
1335 // It is up to callers to check the invariants before calling this.
1336 CHECK(CanPruneAllButVisible());
1338 // Erase all entries but the last committed entry. There may still be a
1339 // new pending entry after this.
1340 entries_.erase(entries_.begin(),
1341 entries_.begin() + last_committed_entry_index_);
1342 entries_.erase(entries_.begin() + 1, entries_.end());
1343 last_committed_entry_index_ = 0;
1346 void NavigationControllerImpl::ClearAllScreenshots() {
1347 screenshot_manager_->ClearAllScreenshots();
1350 void NavigationControllerImpl::SetSessionStorageNamespace(
1351 const std::string& partition_id,
1352 SessionStorageNamespace* session_storage_namespace) {
1353 if (!session_storage_namespace)
1356 // We can't overwrite an existing SessionStorage without violating spec.
1357 // Attempts to do so may give a tab access to another tab's session storage
1358 // so die hard on an error.
1359 bool successful_insert = session_storage_namespace_map_.insert(
1360 make_pair(partition_id,
1361 static_cast<SessionStorageNamespaceImpl*>(
1362 session_storage_namespace)))
1364 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
1367 void NavigationControllerImpl::SetMaxRestoredPageID(int32 max_id) {
1368 max_restored_page_id_ = max_id;
1371 int32 NavigationControllerImpl::GetMaxRestoredPageID() const {
1372 return max_restored_page_id_;
1375 SessionStorageNamespace*
1376 NavigationControllerImpl::GetSessionStorageNamespace(SiteInstance* instance) {
1377 std::string partition_id;
1379 // TODO(ajwong): When GetDefaultSessionStorageNamespace() goes away, remove
1380 // this if statement so |instance| must not be NULL.
1382 GetContentClient()->browser()->GetStoragePartitionIdForSite(
1383 browser_context_, instance->GetSiteURL());
1386 SessionStorageNamespaceMap::const_iterator it =
1387 session_storage_namespace_map_.find(partition_id);
1388 if (it != session_storage_namespace_map_.end())
1389 return it->second.get();
1391 // Create one if no one has accessed session storage for this partition yet.
1393 // TODO(ajwong): Should this use the |partition_id| directly rather than
1394 // re-lookup via |instance|? http://crbug.com/142685
1395 StoragePartition* partition =
1396 BrowserContext::GetStoragePartition(browser_context_, instance);
1397 SessionStorageNamespaceImpl* session_storage_namespace =
1398 new SessionStorageNamespaceImpl(
1399 static_cast<DOMStorageContextWrapper*>(
1400 partition->GetDOMStorageContext()));
1401 session_storage_namespace_map_[partition_id] = session_storage_namespace;
1403 return session_storage_namespace;
1406 SessionStorageNamespace*
1407 NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
1408 // TODO(ajwong): Remove if statement in GetSessionStorageNamespace().
1409 return GetSessionStorageNamespace(NULL);
1412 const SessionStorageNamespaceMap&
1413 NavigationControllerImpl::GetSessionStorageNamespaceMap() const {
1414 return session_storage_namespace_map_;
1417 bool NavigationControllerImpl::NeedsReload() const {
1418 return needs_reload_;
1421 void NavigationControllerImpl::SetNeedsReload() {
1422 needs_reload_ = true;
1425 void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
1426 DCHECK(index < GetEntryCount());
1427 DCHECK(index != last_committed_entry_index_);
1429 DiscardNonCommittedEntries();
1431 entries_.erase(entries_.begin() + index);
1432 if (last_committed_entry_index_ > index)
1433 last_committed_entry_index_--;
1436 void NavigationControllerImpl::DiscardNonCommittedEntries() {
1437 bool transient = transient_entry_index_ != -1;
1438 DiscardNonCommittedEntriesInternal();
1440 // If there was a transient entry, invalidate everything so the new active
1441 // entry state is shown.
1443 delegate_->NotifyNavigationStateChanged(kInvalidateAll);
1447 NavigationEntry* NavigationControllerImpl::GetPendingEntry() const {
1448 return pending_entry_;
1451 int NavigationControllerImpl::GetPendingEntryIndex() const {
1452 return pending_entry_index_;
1455 void NavigationControllerImpl::InsertOrReplaceEntry(NavigationEntryImpl* entry,
1457 DCHECK(entry->GetTransitionType() != PAGE_TRANSITION_AUTO_SUBFRAME);
1459 // Copy the pending entry's unique ID to the committed entry.
1460 // I don't know if pending_entry_index_ can be other than -1 here.
1461 const NavigationEntryImpl* const pending_entry =
1462 (pending_entry_index_ == -1) ?
1463 pending_entry_ : entries_[pending_entry_index_].get();
1465 entry->set_unique_id(pending_entry->GetUniqueID());
1467 DiscardNonCommittedEntriesInternal();
1469 int current_size = static_cast<int>(entries_.size());
1471 if (current_size > 0) {
1472 // Prune any entries which are in front of the current entry.
1473 // Also prune the current entry if we are to replace the current entry.
1474 // last_committed_entry_index_ must be updated here since calls to
1475 // NotifyPrunedEntries() below may re-enter and we must make sure
1476 // last_committed_entry_index_ is not left in an invalid state.
1478 --last_committed_entry_index_;
1481 while (last_committed_entry_index_ < (current_size - 1)) {
1483 entries_.pop_back();
1486 if (num_pruned > 0) // Only notify if we did prune something.
1487 NotifyPrunedEntries(this, false, num_pruned);
1490 PruneOldestEntryIfFull();
1492 entries_.push_back(linked_ptr<NavigationEntryImpl>(entry));
1493 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
1495 // This is a new page ID, so we need everybody to know about it.
1496 delegate_->UpdateMaxPageID(entry->GetPageID());
1499 void NavigationControllerImpl::PruneOldestEntryIfFull() {
1500 if (entries_.size() >= max_entry_count()) {
1501 DCHECK_EQ(max_entry_count(), entries_.size());
1502 DCHECK_GT(last_committed_entry_index_, 0);
1503 RemoveEntryAtIndex(0);
1504 NotifyPrunedEntries(this, true, 1);
1508 void NavigationControllerImpl::NavigateToPendingEntry(ReloadType reload_type) {
1509 needs_reload_ = false;
1511 // If we were navigating to a slow-to-commit page, and the user performs
1512 // a session history navigation to the last committed page, RenderViewHost
1513 // will force the throbber to start, but WebKit will essentially ignore the
1514 // navigation, and won't send a message to stop the throbber. To prevent this
1515 // from happening, we drop the navigation here and stop the slow-to-commit
1516 // page from loading (which would normally happen during the navigation).
1517 if (pending_entry_index_ != -1 &&
1518 pending_entry_index_ == last_committed_entry_index_ &&
1519 (entries_[pending_entry_index_]->restore_type() ==
1520 NavigationEntryImpl::RESTORE_NONE) &&
1521 (entries_[pending_entry_index_]->GetTransitionType() &
1522 PAGE_TRANSITION_FORWARD_BACK)) {
1525 // If an interstitial page is showing, we want to close it to get back
1526 // to what was showing before.
1527 if (delegate_->GetInterstitialPage())
1528 delegate_->GetInterstitialPage()->DontProceed();
1530 DiscardNonCommittedEntries();
1534 // If an interstitial page is showing, the previous renderer is blocked and
1535 // cannot make new requests. Unblock (and disable) it to allow this
1536 // navigation to succeed. The interstitial will stay visible until the
1537 // resulting DidNavigate.
1538 if (delegate_->GetInterstitialPage()) {
1539 static_cast<InterstitialPageImpl*>(delegate_->GetInterstitialPage())->
1540 CancelForNavigation();
1543 // For session history navigations only the pending_entry_index_ is set.
1544 if (!pending_entry_) {
1545 DCHECK_NE(pending_entry_index_, -1);
1546 pending_entry_ = entries_[pending_entry_index_].get();
1549 if (!delegate_->NavigateToPendingEntry(reload_type))
1550 DiscardNonCommittedEntries();
1552 // If the entry is being restored and doesn't have a SiteInstance yet, fill
1553 // it in now that we know. This allows us to find the entry when it commits.
1554 // This works for browser-initiated navigations. We handle renderer-initiated
1555 // navigations to restored entries in WebContentsImpl::OnGoToEntryAtOffset.
1556 if (pending_entry_ && !pending_entry_->site_instance() &&
1557 pending_entry_->restore_type() != NavigationEntryImpl::RESTORE_NONE) {
1558 pending_entry_->set_site_instance(static_cast<SiteInstanceImpl*>(
1559 delegate_->GetPendingSiteInstance()));
1560 pending_entry_->set_restore_type(NavigationEntryImpl::RESTORE_NONE);
1564 void NavigationControllerImpl::NotifyNavigationEntryCommitted(
1565 LoadCommittedDetails* details) {
1566 details->entry = GetLastCommittedEntry();
1568 // We need to notify the ssl_manager_ before the web_contents_ so the
1569 // location bar will have up-to-date information about the security style
1570 // when it wants to draw. See http://crbug.com/11157
1571 ssl_manager_.DidCommitProvisionalLoad(*details);
1573 delegate_->NotifyNavigationStateChanged(kInvalidateAll);
1574 delegate_->NotifyNavigationEntryCommitted(*details);
1576 // TODO(avi): Remove. http://crbug.com/170921
1577 NotificationDetails notification_details =
1578 Details<LoadCommittedDetails>(details);
1579 NotificationService::current()->Notify(
1580 NOTIFICATION_NAV_ENTRY_COMMITTED,
1581 Source<NavigationController>(this),
1582 notification_details);
1586 size_t NavigationControllerImpl::max_entry_count() {
1587 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
1588 return max_entry_count_for_testing_;
1589 return kMaxSessionHistoryEntries;
1592 void NavigationControllerImpl::SetActive(bool is_active) {
1593 if (is_active && needs_reload_)
1597 void NavigationControllerImpl::LoadIfNecessary() {
1601 // Calling Reload() results in ignoring state, and not loading.
1602 // Explicitly use NavigateToPendingEntry so that the renderer uses the
1604 pending_entry_index_ = last_committed_entry_index_;
1605 NavigateToPendingEntry(NO_RELOAD);
1608 void NavigationControllerImpl::NotifyEntryChanged(const NavigationEntry* entry,
1610 EntryChangedDetails det;
1611 det.changed_entry = entry;
1613 NotificationService::current()->Notify(
1614 NOTIFICATION_NAV_ENTRY_CHANGED,
1615 Source<NavigationController>(this),
1616 Details<EntryChangedDetails>(&det));
1619 void NavigationControllerImpl::FinishRestore(int selected_index,
1621 DCHECK(selected_index >= 0 && selected_index < GetEntryCount());
1622 ConfigureEntriesForRestore(&entries_, type);
1624 SetMaxRestoredPageID(static_cast<int32>(GetEntryCount()));
1626 last_committed_entry_index_ = selected_index;
1629 void NavigationControllerImpl::DiscardNonCommittedEntriesInternal() {
1630 DiscardPendingEntry();
1631 DiscardTransientEntry();
1634 void NavigationControllerImpl::DiscardPendingEntry() {
1635 if (pending_entry_index_ == -1)
1636 delete pending_entry_;
1637 pending_entry_ = NULL;
1638 pending_entry_index_ = -1;
1641 void NavigationControllerImpl::DiscardTransientEntry() {
1642 if (transient_entry_index_ == -1)
1644 entries_.erase(entries_.begin() + transient_entry_index_);
1645 if (last_committed_entry_index_ > transient_entry_index_)
1646 last_committed_entry_index_--;
1647 transient_entry_index_ = -1;
1650 int NavigationControllerImpl::GetEntryIndexWithPageID(
1651 SiteInstance* instance, int32 page_id) const {
1652 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
1653 if ((entries_[i]->site_instance() == instance) &&
1654 (entries_[i]->GetPageID() == page_id))
1660 NavigationEntry* NavigationControllerImpl::GetTransientEntry() const {
1661 if (transient_entry_index_ == -1)
1663 return entries_[transient_entry_index_].get();
1666 void NavigationControllerImpl::SetTransientEntry(NavigationEntry* entry) {
1667 // Discard any current transient entry, we can only have one at a time.
1669 if (last_committed_entry_index_ != -1)
1670 index = last_committed_entry_index_ + 1;
1671 DiscardTransientEntry();
1673 entries_.begin() + index, linked_ptr<NavigationEntryImpl>(
1674 NavigationEntryImpl::FromNavigationEntry(entry)));
1675 transient_entry_index_ = index;
1676 delegate_->NotifyNavigationStateChanged(kInvalidateAll);
1679 void NavigationControllerImpl::InsertEntriesFrom(
1680 const NavigationControllerImpl& source,
1682 DCHECK_LE(max_index, source.GetEntryCount());
1683 size_t insert_index = 0;
1684 for (int i = 0; i < max_index; i++) {
1685 // When cloning a tab, copy all entries except interstitial pages
1686 if (source.entries_[i].get()->GetPageType() !=
1687 PAGE_TYPE_INTERSTITIAL) {
1688 entries_.insert(entries_.begin() + insert_index++,
1689 linked_ptr<NavigationEntryImpl>(
1690 new NavigationEntryImpl(*source.entries_[i])));
1695 void NavigationControllerImpl::SetGetTimestampCallbackForTest(
1696 const base::Callback<base::Time()>& get_timestamp_callback) {
1697 get_timestamp_callback_ = get_timestamp_callback;
1700 } // namespace content