Broke ContentSettingBubbleModelTest.Plugins on Android.
[chromium-blink-merge.git] / content / browser / web_contents / navigation_controller_impl.cc
bloba4ec35fb626b3b13b14125f0b7c86edc4d305d79
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/web_contents/navigation_controller_impl.h"
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/file_util.h"
10 #include "base/logging.h"
11 #include "base/string_number_conversions.h" // Temporary
12 #include "base/string_util.h"
13 #include "base/time.h"
14 #include "base/utf_string_conversions.h"
15 #include "content/browser/browser_url_handler_impl.h"
16 #include "content/browser/child_process_security_policy_impl.h"
17 #include "content/browser/dom_storage/dom_storage_context_impl.h"
18 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
19 #include "content/browser/renderer_host/render_view_host_impl.h" // Temporary
20 #include "content/browser/site_instance_impl.h"
21 #include "content/browser/web_contents/debug_urls.h"
22 #include "content/browser/web_contents/interstitial_page_impl.h"
23 #include "content/browser/web_contents/navigation_entry_impl.h"
24 #include "content/browser/web_contents/web_contents_impl.h"
25 #include "content/common/view_messages.h"
26 #include "content/public/browser/browser_context.h"
27 #include "content/public/browser/content_browser_client.h"
28 #include "content/public/browser/invalidate_type.h"
29 #include "content/public/browser/navigation_details.h"
30 #include "content/public/browser/notification_service.h"
31 #include "content/public/browser/notification_types.h"
32 #include "content/public/browser/render_widget_host.h"
33 #include "content/public/browser/render_widget_host_view.h"
34 #include "content/public/browser/storage_partition.h"
35 #include "content/public/browser/user_metrics.h"
36 #include "content/public/browser/web_contents_delegate.h"
37 #include "content/public/common/content_client.h"
38 #include "content/public/common/content_constants.h"
39 #include "content/public/common/content_switches.h"
40 #include "content/public/common/url_constants.h"
41 #include "net/base/escape.h"
42 #include "net/base/mime_util.h"
43 #include "net/base/net_util.h"
44 #include "skia/ext/platform_canvas.h"
45 #include "ui/gfx/codec/png_codec.h"
46 #include "webkit/glue/glue_serialize.h"
48 namespace content {
49 namespace {
51 const int kInvalidateAll = 0xFFFFFFFF;
53 // Invoked when entries have been pruned, or removed. For example, if the
54 // current entries are [google, digg, yahoo], with the current entry google,
55 // and the user types in cnet, then digg and yahoo are pruned.
56 void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
57 bool from_front,
58 int count) {
59 PrunedDetails details;
60 details.from_front = from_front;
61 details.count = count;
62 NotificationService::current()->Notify(
63 NOTIFICATION_NAV_LIST_PRUNED,
64 Source<NavigationController>(nav_controller),
65 Details<PrunedDetails>(&details));
68 // Ensure the given NavigationEntry has a valid state, so that WebKit does not
69 // get confused if we navigate back to it.
71 // An empty state is treated as a new navigation by WebKit, which would mean
72 // losing the navigation entries and generating a new navigation entry after
73 // this one. We don't want that. To avoid this we create a valid state which
74 // WebKit will not treat as a new navigation.
75 void SetContentStateIfEmpty(NavigationEntryImpl* entry) {
76 if (entry->GetContentState().empty()) {
77 entry->SetContentState(
78 webkit_glue::CreateHistoryStateForURL(entry->GetURL()));
82 NavigationEntryImpl::RestoreType ControllerRestoreTypeToEntryType(
83 NavigationController::RestoreType type) {
84 switch (type) {
85 case NavigationController::RESTORE_CURRENT_SESSION:
86 return NavigationEntryImpl::RESTORE_CURRENT_SESSION;
87 case NavigationController::RESTORE_LAST_SESSION_EXITED_CLEANLY:
88 return NavigationEntryImpl::RESTORE_LAST_SESSION_EXITED_CLEANLY;
89 case NavigationController::RESTORE_LAST_SESSION_CRASHED:
90 return NavigationEntryImpl::RESTORE_LAST_SESSION_CRASHED;
92 NOTREACHED();
93 return NavigationEntryImpl::RESTORE_CURRENT_SESSION;
96 // Configure all the NavigationEntries in entries for restore. This resets
97 // the transition type to reload and makes sure the content state isn't empty.
98 void ConfigureEntriesForRestore(
99 std::vector<linked_ptr<NavigationEntryImpl> >* entries,
100 NavigationController::RestoreType type) {
101 for (size_t i = 0; i < entries->size(); ++i) {
102 // Use a transition type of reload so that we don't incorrectly increase
103 // the typed count.
104 (*entries)[i]->SetTransitionType(PAGE_TRANSITION_RELOAD);
105 (*entries)[i]->set_restore_type(ControllerRestoreTypeToEntryType(type));
106 // NOTE(darin): This code is only needed for backwards compat.
107 SetContentStateIfEmpty((*entries)[i].get());
111 // See NavigationController::IsURLInPageNavigation for how this works and why.
112 bool AreURLsInPageNavigation(const GURL& existing_url,
113 const GURL& new_url,
114 bool renderer_says_in_page) {
115 if (existing_url == new_url)
116 return renderer_says_in_page;
118 if (!new_url.has_ref()) {
119 // TODO(jcampan): what about when navigating back from a ref URL to the top
120 // non ref URL? Nothing is loaded in that case but we return false here.
121 // The user could also navigate from the ref URL to the non ref URL by
122 // entering the non ref URL in the location bar or through a bookmark, in
123 // which case there would be a load. I am not sure if the non-load/load
124 // scenarios can be differentiated with the TransitionType.
125 return false;
128 url_canon::Replacements<char> replacements;
129 replacements.ClearRef();
130 return existing_url.ReplaceComponents(replacements) ==
131 new_url.ReplaceComponents(replacements);
134 // Determines whether or not we should be carrying over a user agent override
135 // between two NavigationEntries.
136 bool ShouldKeepOverride(const NavigationEntry* last_entry) {
137 return last_entry && last_entry->GetIsOverridingUserAgent();
140 } // namespace
142 // NavigationControllerImpl ----------------------------------------------------
144 const size_t kMaxEntryCountForTestingNotSet = -1;
146 // static
147 size_t NavigationControllerImpl::max_entry_count_for_testing_ =
148 kMaxEntryCountForTestingNotSet;
150 // Should Reload check for post data? The default is true, but is set to false
151 // when testing.
152 static bool g_check_for_repost = true;
154 // static
155 NavigationEntry* NavigationController::CreateNavigationEntry(
156 const GURL& url,
157 const Referrer& referrer,
158 PageTransition transition,
159 bool is_renderer_initiated,
160 const std::string& extra_headers,
161 BrowserContext* browser_context) {
162 // Allow the browser URL handler to rewrite the URL. This will, for example,
163 // remove "view-source:" from the beginning of the URL to get the URL that
164 // will actually be loaded. This real URL won't be shown to the user, just
165 // used internally.
166 GURL loaded_url(url);
167 bool reverse_on_redirect = false;
168 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
169 &loaded_url, browser_context, &reverse_on_redirect);
171 NavigationEntryImpl* entry = new NavigationEntryImpl(
172 NULL, // The site instance for tabs is sent on navigation
173 // (WebContents::GetSiteInstance).
175 loaded_url,
176 referrer,
177 string16(),
178 transition,
179 is_renderer_initiated);
180 entry->SetVirtualURL(url);
181 entry->set_user_typed_url(url);
182 entry->set_update_virtual_url_with_url(reverse_on_redirect);
183 entry->set_extra_headers(extra_headers);
184 return entry;
187 // static
188 void NavigationController::DisablePromptOnRepost() {
189 g_check_for_repost = false;
192 base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
193 base::Time t) {
194 // If |t| is between the water marks, we're in a run of duplicates
195 // or just getting out of it, so increase the high-water mark to get
196 // a time that probably hasn't been used before and return it.
197 if (low_water_mark_ <= t && t <= high_water_mark_) {
198 high_water_mark_ += base::TimeDelta::FromMicroseconds(1);
199 return high_water_mark_;
202 // Otherwise, we're clear of the last duplicate run, so reset the
203 // water marks.
204 low_water_mark_ = high_water_mark_ = t;
205 return t;
208 NavigationControllerImpl::NavigationControllerImpl(
209 WebContentsImpl* web_contents,
210 BrowserContext* browser_context)
211 : browser_context_(browser_context),
212 pending_entry_(NULL),
213 last_committed_entry_index_(-1),
214 pending_entry_index_(-1),
215 transient_entry_index_(-1),
216 web_contents_(web_contents),
217 max_restored_page_id_(-1),
218 ALLOW_THIS_IN_INITIALIZER_LIST(ssl_manager_(this)),
219 needs_reload_(false),
220 is_initial_navigation_(true),
221 pending_reload_(NO_RELOAD),
222 get_timestamp_callback_(base::Bind(&base::Time::Now)),
223 screenshot_count_(0) {
224 DCHECK(browser_context_);
227 NavigationControllerImpl::~NavigationControllerImpl() {
228 DiscardNonCommittedEntriesInternal();
231 WebContents* NavigationControllerImpl::GetWebContents() const {
232 return web_contents_;
235 BrowserContext* NavigationControllerImpl::GetBrowserContext() const {
236 return browser_context_;
239 void NavigationControllerImpl::SetBrowserContext(
240 BrowserContext* browser_context) {
241 browser_context_ = browser_context;
244 void NavigationControllerImpl::Restore(
245 int selected_navigation,
246 RestoreType type,
247 std::vector<NavigationEntry*>* entries) {
248 // Verify that this controller is unused and that the input is valid.
249 DCHECK(GetEntryCount() == 0 && !GetPendingEntry());
250 DCHECK(selected_navigation >= 0 &&
251 selected_navigation < static_cast<int>(entries->size()));
253 needs_reload_ = true;
254 for (size_t i = 0; i < entries->size(); ++i) {
255 NavigationEntryImpl* entry =
256 NavigationEntryImpl::FromNavigationEntry((*entries)[i]);
257 entries_.push_back(linked_ptr<NavigationEntryImpl>(entry));
259 entries->clear();
261 // And finish the restore.
262 FinishRestore(selected_navigation, type);
265 void NavigationControllerImpl::Reload(bool check_for_repost) {
266 ReloadInternal(check_for_repost, RELOAD);
268 void NavigationControllerImpl::ReloadIgnoringCache(bool check_for_repost) {
269 ReloadInternal(check_for_repost, RELOAD_IGNORING_CACHE);
271 void NavigationControllerImpl::ReloadOriginalRequestURL(bool check_for_repost) {
272 ReloadInternal(check_for_repost, RELOAD_ORIGINAL_REQUEST_URL);
275 void NavigationControllerImpl::ReloadInternal(bool check_for_repost,
276 ReloadType reload_type) {
277 if (transient_entry_index_ != -1) {
278 // If an interstitial is showing, treat a reload as a navigation to the
279 // transient entry's URL.
280 NavigationEntryImpl* active_entry =
281 NavigationEntryImpl::FromNavigationEntry(GetActiveEntry());
282 if (!active_entry)
283 return;
284 LoadURL(active_entry->GetURL(),
285 Referrer(),
286 PAGE_TRANSITION_RELOAD,
287 active_entry->extra_headers());
288 return;
291 DiscardNonCommittedEntriesInternal();
292 int current_index = GetCurrentEntryIndex();
293 // If we are no where, then we can't reload. TODO(darin): We should add a
294 // CanReload method.
295 if (current_index == -1) {
296 return;
299 if (g_check_for_repost && check_for_repost &&
300 GetEntryAtIndex(current_index)->GetHasPostData()) {
301 // The user is asking to reload a page with POST data. Prompt to make sure
302 // they really want to do this. If they do, the dialog will call us back
303 // with check_for_repost = false.
304 NotificationService::current()->Notify(
305 NOTIFICATION_REPOST_WARNING_SHOWN,
306 Source<NavigationController>(this),
307 NotificationService::NoDetails());
309 pending_reload_ = reload_type;
310 web_contents_->Activate();
311 web_contents_->GetDelegate()->ShowRepostFormWarningDialog(web_contents_);
312 } else {
313 DiscardNonCommittedEntriesInternal();
315 NavigationEntryImpl* entry = entries_[current_index].get();
316 SiteInstanceImpl* site_instance = entry->site_instance();
317 DCHECK(site_instance);
319 // If we are reloading an entry that no longer belongs to the current
320 // site instance (for example, refreshing a page for just installed app),
321 // the reload must happen in a new process.
322 // The new entry must have a new page_id and site instance, so it behaves
323 // as new navigation (which happens to clear forward history).
324 // Tabs that are discarded due to low memory conditions may not have a site
325 // instance, and should not be treated as a cross-site reload.
326 if (site_instance &&
327 site_instance->HasWrongProcessForURL(entry->GetURL())) {
328 // Create a navigation entry that resembles the current one, but do not
329 // copy page id, site instance, content state, or timestamp.
330 NavigationEntryImpl* nav_entry = NavigationEntryImpl::FromNavigationEntry(
331 CreateNavigationEntry(
332 entry->GetURL(), entry->GetReferrer(), entry->GetTransitionType(),
333 false, entry->extra_headers(), browser_context_));
335 // Mark the reload type as NO_RELOAD, so navigation will not be considered
336 // a reload in the renderer.
337 reload_type = NavigationController::NO_RELOAD;
339 nav_entry->set_should_replace_entry(true);
340 pending_entry_ = nav_entry;
341 } else {
342 pending_entry_index_ = current_index;
344 // The title of the page being reloaded might have been removed in the
345 // meanwhile, so we need to revert to the default title upon reload and
346 // invalidate the previously cached title (SetTitle will do both).
347 // See Chromium issue 96041.
348 entries_[pending_entry_index_]->SetTitle(string16());
350 entries_[pending_entry_index_]->SetTransitionType(PAGE_TRANSITION_RELOAD);
353 NavigateToPendingEntry(reload_type);
357 void NavigationControllerImpl::CancelPendingReload() {
358 DCHECK(pending_reload_ != NO_RELOAD);
359 pending_reload_ = NO_RELOAD;
362 void NavigationControllerImpl::ContinuePendingReload() {
363 if (pending_reload_ == NO_RELOAD) {
364 NOTREACHED();
365 } else {
366 ReloadInternal(false, pending_reload_);
367 pending_reload_ = NO_RELOAD;
371 bool NavigationControllerImpl::IsInitialNavigation() {
372 return is_initial_navigation_;
375 NavigationEntryImpl* NavigationControllerImpl::GetEntryWithPageID(
376 SiteInstance* instance, int32 page_id) const {
377 int index = GetEntryIndexWithPageID(instance, page_id);
378 return (index != -1) ? entries_[index].get() : NULL;
381 void NavigationControllerImpl::LoadEntry(NavigationEntryImpl* entry) {
382 // Don't navigate to URLs disabled by policy. This prevents showing the URL
383 // on the Omnibar when it is also going to be blocked by
384 // ChildProcessSecurityPolicy::CanRequestURL.
385 ChildProcessSecurityPolicyImpl* policy =
386 ChildProcessSecurityPolicyImpl::GetInstance();
387 if (policy->IsDisabledScheme(entry->GetURL().scheme()) ||
388 policy->IsDisabledScheme(entry->GetVirtualURL().scheme())) {
389 VLOG(1) << "URL not loaded because the scheme is blocked by policy: "
390 << entry->GetURL();
391 delete entry;
392 return;
395 // When navigating to a new page, we don't know for sure if we will actually
396 // end up leaving the current page. The new page load could for example
397 // result in a download or a 'no content' response (e.g., a mailto: URL).
398 DiscardNonCommittedEntriesInternal();
399 pending_entry_ = entry;
400 NotificationService::current()->Notify(
401 NOTIFICATION_NAV_ENTRY_PENDING,
402 Source<NavigationController>(this),
403 Details<NavigationEntry>(entry));
404 NavigateToPendingEntry(NO_RELOAD);
407 NavigationEntry* NavigationControllerImpl::GetActiveEntry() const {
408 if (transient_entry_index_ != -1)
409 return entries_[transient_entry_index_].get();
410 if (pending_entry_)
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 // Only return the pending_entry for new (non-history), browser-initiated
419 // navigations, in order to prevent URL spoof attacks.
420 // Ideally we would also show the pending entry's URL for new renderer-
421 // initiated navigations with no last committed entry (e.g., a link opening
422 // in a new tab), but an attacker can insert content into the about:blank
423 // page while the pending URL loads in that case.
424 if (pending_entry_ &&
425 pending_entry_->GetPageID() == -1 &&
426 !pending_entry_->is_renderer_initiated())
427 return pending_entry_;
428 return GetLastCommittedEntry();
431 int NavigationControllerImpl::GetCurrentEntryIndex() const {
432 if (transient_entry_index_ != -1)
433 return transient_entry_index_;
434 if (pending_entry_index_ != -1)
435 return pending_entry_index_;
436 return last_committed_entry_index_;
439 NavigationEntry* NavigationControllerImpl::GetLastCommittedEntry() const {
440 if (last_committed_entry_index_ == -1)
441 return NULL;
442 return entries_[last_committed_entry_index_].get();
445 bool NavigationControllerImpl::CanViewSource() const {
446 const std::string& mime_type = web_contents_->GetContentsMimeType();
447 bool is_viewable_mime_type = net::IsSupportedNonImageMimeType(mime_type) &&
448 !net::IsSupportedMediaMimeType(mime_type);
449 NavigationEntry* active_entry = GetActiveEntry();
450 return active_entry && !active_entry->IsViewSourceMode() &&
451 is_viewable_mime_type && !web_contents_->GetInterstitialPage();
454 int NavigationControllerImpl::GetLastCommittedEntryIndex() const {
455 return last_committed_entry_index_;
458 int NavigationControllerImpl::GetEntryCount() const {
459 DCHECK(entries_.size() <= max_entry_count());
460 return static_cast<int>(entries_.size());
463 NavigationEntry* NavigationControllerImpl::GetEntryAtIndex(
464 int index) const {
465 return entries_.at(index).get();
468 NavigationEntry* NavigationControllerImpl::GetEntryAtOffset(
469 int offset) const {
470 int index = GetIndexForOffset(offset);
471 if (index < 0 || index >= GetEntryCount())
472 return NULL;
474 return entries_[index].get();
477 int NavigationControllerImpl::GetIndexForOffset(int offset) const {
478 return GetCurrentEntryIndex() + offset;
481 void NavigationControllerImpl::TakeScreenshot() {
482 static bool overscroll_enabled = !CommandLine::ForCurrentProcess()->
483 HasSwitch(switches::kDisableOverscrollHistoryNavigation);
484 if (!overscroll_enabled)
485 return;
487 NavigationEntryImpl* entry =
488 NavigationEntryImpl::FromNavigationEntry(GetLastCommittedEntry());
489 if (!entry)
490 return;
492 RenderViewHost* render_view_host = web_contents_->GetRenderViewHost();
493 if (!static_cast<RenderViewHostImpl*>
494 (render_view_host)->overscroll_controller()) {
495 return;
497 content::RenderWidgetHostView* view = render_view_host->GetView();
498 if (!view)
499 return;
501 if (!take_screenshot_callback_.is_null())
502 take_screenshot_callback_.Run(render_view_host);
504 skia::PlatformBitmap* temp_bitmap = new skia::PlatformBitmap;
505 render_view_host->CopyFromBackingStore(gfx::Rect(),
506 view->GetViewBounds().size(),
507 base::Bind(&NavigationControllerImpl::OnScreenshotTaken,
508 base::Unretained(this),
509 entry->GetUniqueID(),
510 base::Owned(temp_bitmap)),
511 temp_bitmap);
514 void NavigationControllerImpl::OnScreenshotTaken(
515 int unique_id,
516 skia::PlatformBitmap* bitmap,
517 bool success) {
518 NavigationEntryImpl* entry = NULL;
519 for (NavigationEntries::iterator i = entries_.begin();
520 i != entries_.end();
521 ++i) {
522 if ((*i)->GetUniqueID() == unique_id) {
523 entry = (*i).get();
524 break;
528 if (!entry) {
529 LOG(ERROR) << "Invalid entry with unique id: " << unique_id;
530 return;
533 if (!success) {
534 ClearScreenshot(entry);
535 return;
538 std::vector<unsigned char> data;
539 if (gfx::PNGCodec::EncodeBGRASkBitmap(bitmap->GetBitmap(), true, &data)) {
540 if (!entry->screenshot())
541 ++screenshot_count_;
542 entry->SetScreenshotPNGData(data);
543 PurgeScreenshotsIfNecessary();
544 } else {
545 ClearScreenshot(entry);
547 CHECK_GE(screenshot_count_, 0);
550 void NavigationControllerImpl::ClearScreenshot(NavigationEntryImpl* entry) {
551 if (entry->screenshot()) {
552 --screenshot_count_;
553 entry->SetScreenshotPNGData(std::vector<unsigned char>());
557 void NavigationControllerImpl::PurgeScreenshotsIfNecessary() {
558 // Allow only a certain number of entries to keep screenshots.
559 const int kMaxScreenshots = 10;
560 if (screenshot_count_ < kMaxScreenshots)
561 return;
563 const int current = GetCurrentEntryIndex();
564 const int num_entries = GetEntryCount();
565 int available_slots = kMaxScreenshots;
566 if (NavigationEntryImpl::FromNavigationEntry(
567 GetEntryAtIndex(current))->screenshot())
568 --available_slots;
570 // Keep screenshots closer to the current navigation entry, and purge the ones
571 // that are farther away from it. So in each step, look at the entries at
572 // each offset on both the back and forward history, and start counting them
573 // to make sure that the correct number of screenshots are kept in memory.
574 // Note that it is possible for some entries to be missing screenshots (e.g.
575 // when taking the screenshot failed for some reason). So there may be a state
576 // where there are a lot of entries in the back history, but none of them has
577 // any screenshot. In such cases, keep the screenshots for |kMaxScreenshots|
578 // entries in the forward history list.
579 int back = current - 1;
580 int forward = current + 1;
581 while (available_slots > 0 && (back >= 0 || forward < num_entries)) {
582 if (back >= 0) {
583 NavigationEntryImpl* entry = NavigationEntryImpl::FromNavigationEntry(
584 GetEntryAtIndex(back));
585 if (entry->screenshot())
586 --available_slots;
587 --back;
590 if (available_slots > 0 && forward < num_entries) {
591 NavigationEntryImpl* entry = NavigationEntryImpl::FromNavigationEntry(
592 GetEntryAtIndex(forward));
593 if (entry->screenshot())
594 --available_slots;
595 ++forward;
599 // Purge any screenshot at |back| or lower indices, and |forward| or higher
600 // indices.
602 while (screenshot_count_ > kMaxScreenshots && back >= 0) {
603 NavigationEntryImpl* entry = NavigationEntryImpl::FromNavigationEntry(
604 GetEntryAtIndex(back));
605 ClearScreenshot(entry);
606 --back;
609 while (screenshot_count_ > kMaxScreenshots && forward < num_entries) {
610 NavigationEntryImpl* entry = NavigationEntryImpl::FromNavigationEntry(
611 GetEntryAtIndex(forward));
612 ClearScreenshot(entry);
613 ++forward;
615 CHECK_GE(screenshot_count_, 0);
616 CHECK_LE(screenshot_count_, kMaxScreenshots);
619 bool NavigationControllerImpl::CanGoBack() const {
620 return entries_.size() > 1 && GetCurrentEntryIndex() > 0;
623 bool NavigationControllerImpl::CanGoForward() const {
624 int index = GetCurrentEntryIndex();
625 return index >= 0 && index < (static_cast<int>(entries_.size()) - 1);
628 bool NavigationControllerImpl::CanGoToOffset(int offset) const {
629 int index = GetIndexForOffset(offset);
630 return index >= 0 && index < GetEntryCount();
633 void NavigationControllerImpl::GoBack() {
634 if (!CanGoBack()) {
635 NOTREACHED();
636 return;
639 // Base the navigation on where we are now...
640 int current_index = GetCurrentEntryIndex();
642 DiscardNonCommittedEntries();
644 pending_entry_index_ = current_index - 1;
645 entries_[pending_entry_index_]->SetTransitionType(
646 PageTransitionFromInt(
647 entries_[pending_entry_index_]->GetTransitionType() |
648 PAGE_TRANSITION_FORWARD_BACK));
649 NavigateToPendingEntry(NO_RELOAD);
652 void NavigationControllerImpl::GoForward() {
653 if (!CanGoForward()) {
654 NOTREACHED();
655 return;
658 bool transient = (transient_entry_index_ != -1);
660 // Base the navigation on where we are now...
661 int current_index = GetCurrentEntryIndex();
663 DiscardNonCommittedEntries();
665 pending_entry_index_ = current_index;
666 // If there was a transient entry, we removed it making the current index
667 // the next page.
668 if (!transient)
669 pending_entry_index_++;
671 entries_[pending_entry_index_]->SetTransitionType(
672 PageTransitionFromInt(
673 entries_[pending_entry_index_]->GetTransitionType() |
674 PAGE_TRANSITION_FORWARD_BACK));
675 NavigateToPendingEntry(NO_RELOAD);
678 void NavigationControllerImpl::GoToIndex(int index) {
679 if (index < 0 || index >= static_cast<int>(entries_.size())) {
680 NOTREACHED();
681 return;
684 if (transient_entry_index_ != -1) {
685 if (index == transient_entry_index_) {
686 // Nothing to do when navigating to the transient.
687 return;
689 if (index > transient_entry_index_) {
690 // Removing the transient is goint to shift all entries by 1.
691 index--;
695 DiscardNonCommittedEntries();
697 pending_entry_index_ = index;
698 entries_[pending_entry_index_]->SetTransitionType(
699 PageTransitionFromInt(
700 entries_[pending_entry_index_]->GetTransitionType() |
701 PAGE_TRANSITION_FORWARD_BACK));
702 NavigateToPendingEntry(NO_RELOAD);
705 void NavigationControllerImpl::GoToOffset(int offset) {
706 if (!CanGoToOffset(offset))
707 return;
709 GoToIndex(GetIndexForOffset(offset));
712 void NavigationControllerImpl::RemoveEntryAtIndex(int index) {
713 if (index == last_committed_entry_index_)
714 return;
716 RemoveEntryAtIndexInternal(index);
719 void NavigationControllerImpl::UpdateVirtualURLToURL(
720 NavigationEntryImpl* entry, const GURL& new_url) {
721 GURL new_virtual_url(new_url);
722 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
723 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
724 entry->SetVirtualURL(new_virtual_url);
728 void NavigationControllerImpl::AddTransientEntry(NavigationEntryImpl* entry) {
729 // Discard any current transient entry, we can only have one at a time.
730 int index = 0;
731 if (last_committed_entry_index_ != -1)
732 index = last_committed_entry_index_ + 1;
733 DiscardTransientEntry();
734 entries_.insert(
735 entries_.begin() + index, linked_ptr<NavigationEntryImpl>(entry));
736 transient_entry_index_ = index;
737 web_contents_->NotifyNavigationStateChanged(kInvalidateAll);
740 void NavigationControllerImpl::LoadURL(
741 const GURL& url,
742 const Referrer& referrer,
743 PageTransition transition,
744 const std::string& extra_headers) {
745 LoadURLParams params(url);
746 params.referrer = referrer;
747 params.transition_type = transition;
748 params.extra_headers = extra_headers;
749 LoadURLWithParams(params);
752 void NavigationControllerImpl::LoadURLWithParams(const LoadURLParams& params) {
753 if (HandleDebugURL(params.url, params.transition_type))
754 return;
756 // Checks based on params.load_type.
757 switch (params.load_type) {
758 case LOAD_TYPE_DEFAULT:
759 break;
760 case LOAD_TYPE_BROWSER_INITIATED_HTTP_POST:
761 if (!params.url.SchemeIs(chrome::kHttpScheme) &&
762 !params.url.SchemeIs(chrome::kHttpsScheme)) {
763 NOTREACHED() << "Http post load must use http(s) scheme.";
764 return;
766 break;
767 case LOAD_TYPE_DATA:
768 if (!params.url.SchemeIs(chrome::kDataScheme)) {
769 NOTREACHED() << "Data load must use data scheme.";
770 return;
772 break;
773 default:
774 NOTREACHED();
775 break;
778 // The user initiated a load, we don't need to reload anymore.
779 needs_reload_ = false;
781 bool override = false;
782 switch (params.override_user_agent) {
783 case UA_OVERRIDE_INHERIT:
784 override = ShouldKeepOverride(GetLastCommittedEntry());
785 break;
786 case UA_OVERRIDE_TRUE:
787 override = true;
788 break;
789 case UA_OVERRIDE_FALSE:
790 override = false;
791 break;
792 default:
793 NOTREACHED();
794 break;
797 NavigationEntryImpl* entry = NavigationEntryImpl::FromNavigationEntry(
798 CreateNavigationEntry(
799 params.url,
800 params.referrer,
801 params.transition_type,
802 params.is_renderer_initiated,
803 params.extra_headers,
804 browser_context_));
805 if (params.is_cross_site_redirect)
806 entry->set_should_replace_entry(true);
807 entry->SetIsOverridingUserAgent(override);
808 entry->set_transferred_global_request_id(
809 params.transferred_global_request_id);
811 switch (params.load_type) {
812 case LOAD_TYPE_DEFAULT:
813 break;
814 case LOAD_TYPE_BROWSER_INITIATED_HTTP_POST:
815 entry->SetHasPostData(true);
816 entry->SetBrowserInitiatedPostData(
817 params.browser_initiated_post_data);
818 break;
819 case LOAD_TYPE_DATA:
820 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
821 entry->SetVirtualURL(params.virtual_url_for_data_url);
822 entry->SetCanLoadLocalResources(params.can_load_local_resources);
823 break;
824 default:
825 NOTREACHED();
826 break;
829 LoadEntry(entry);
832 void NavigationControllerImpl::DocumentLoadedInFrame() {
833 is_initial_navigation_ = false;
836 bool NavigationControllerImpl::RendererDidNavigate(
837 const ViewHostMsg_FrameNavigate_Params& params,
838 LoadCommittedDetails* details) {
839 // Save the previous state before we clobber it.
840 if (GetLastCommittedEntry()) {
841 details->previous_url = GetLastCommittedEntry()->GetURL();
842 details->previous_entry_index = GetLastCommittedEntryIndex();
843 } else {
844 details->previous_url = GURL();
845 details->previous_entry_index = -1;
848 // If we have a pending entry at this point, it should have a SiteInstance.
849 // Restored entries start out with a null SiteInstance, but we should have
850 // assigned one in NavigateToPendingEntry.
851 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance());
853 // If we are doing a cross-site reload, we need to replace the existing
854 // navigation entry, not add another entry to the history. This has the side
855 // effect of removing forward browsing history, if such existed.
856 // Or if we are doing a cross-site redirect navigation,
857 // we will do a similar thing.
858 details->did_replace_entry =
859 pending_entry_ && pending_entry_->should_replace_entry();
861 // is_in_page must be computed before the entry gets committed.
862 details->is_in_page = IsURLInPageNavigation(
863 params.url, params.was_within_same_page);
865 // Do navigation-type specific actions. These will make and commit an entry.
866 details->type = ClassifyNavigation(params);
868 switch (details->type) {
869 case NAVIGATION_TYPE_NEW_PAGE:
870 RendererDidNavigateToNewPage(params, details->did_replace_entry);
871 break;
872 case NAVIGATION_TYPE_EXISTING_PAGE:
873 RendererDidNavigateToExistingPage(params);
874 break;
875 case NAVIGATION_TYPE_SAME_PAGE:
876 RendererDidNavigateToSamePage(params);
877 break;
878 case NAVIGATION_TYPE_IN_PAGE:
879 RendererDidNavigateInPage(params, &details->did_replace_entry);
880 break;
881 case NAVIGATION_TYPE_NEW_SUBFRAME:
882 RendererDidNavigateNewSubframe(params);
883 break;
884 case NAVIGATION_TYPE_AUTO_SUBFRAME:
885 if (!RendererDidNavigateAutoSubframe(params))
886 return false;
887 break;
888 case NAVIGATION_TYPE_NAV_IGNORE:
889 // If a pending navigation was in progress, this canceled it. We should
890 // discard it and make sure it is removed from the URL bar. After that,
891 // there is nothing we can do with this navigation, so we just return to
892 // the caller that nothing has happened.
893 if (pending_entry_) {
894 DiscardNonCommittedEntries();
895 web_contents_->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
897 return false;
898 default:
899 NOTREACHED();
902 // At this point, we know that the navigation has just completed, so
903 // record the time.
905 // TODO(akalin): Use "sane time" as described in
906 // http://www.chromium.org/developers/design-documents/sane-time .
907 base::Time timestamp =
908 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
909 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
910 << timestamp.ToInternalValue();
912 // All committed entries should have nonempty content state so WebKit doesn't
913 // get confused when we go back to them (see the function for details).
914 DCHECK(!params.content_state.empty());
915 NavigationEntryImpl* active_entry =
916 NavigationEntryImpl::FromNavigationEntry(GetActiveEntry());
917 active_entry->SetTimestamp(timestamp);
918 active_entry->SetContentState(params.content_state);
919 // No longer needed since content state will hold the post data if any.
920 active_entry->SetBrowserInitiatedPostData(NULL);
922 // Once committed, we do not need to track if the entry was initiated by
923 // the renderer.
924 active_entry->set_is_renderer_initiated(false);
926 // The active entry's SiteInstance should match our SiteInstance.
927 DCHECK(active_entry->site_instance() == web_contents_->GetSiteInstance());
929 // Now prep the rest of the details for the notification and broadcast.
930 details->entry = active_entry;
931 details->is_main_frame =
932 PageTransitionIsMainFrame(params.transition);
933 details->serialized_security_info = params.security_info;
934 details->http_status_code = params.http_status_code;
935 NotifyNavigationEntryCommitted(details);
937 return true;
940 NavigationType NavigationControllerImpl::ClassifyNavigation(
941 const ViewHostMsg_FrameNavigate_Params& params) const {
942 if (params.page_id == -1) {
943 // The renderer generates the page IDs, and so if it gives us the invalid
944 // page ID (-1) we know it didn't actually navigate. This happens in a few
945 // cases:
947 // - If a page makes a popup navigated to about blank, and then writes
948 // stuff like a subframe navigated to a real page. We'll get the commit
949 // for the subframe, but there won't be any commit for the outer page.
951 // - We were also getting these for failed loads (for example, bug 21849).
952 // The guess is that we get a "load commit" for the alternate error page,
953 // but that doesn't affect the page ID, so we get the "old" one, which
954 // could be invalid. This can also happen for a cross-site transition
955 // that causes us to swap processes. Then the error page load will be in
956 // a new process with no page IDs ever assigned (and hence a -1 value),
957 // yet the navigation controller still might have previous pages in its
958 // list.
960 // In these cases, there's nothing we can do with them, so ignore.
961 return NAVIGATION_TYPE_NAV_IGNORE;
964 if (params.page_id > web_contents_->GetMaxPageID()) {
965 // Greater page IDs than we've ever seen before are new pages. We may or may
966 // not have a pending entry for the page, and this may or may not be the
967 // main frame.
968 if (PageTransitionIsMainFrame(params.transition))
969 return NAVIGATION_TYPE_NEW_PAGE;
971 // When this is a new subframe navigation, we should have a committed page
972 // for which it's a suframe in. This may not be the case when an iframe is
973 // navigated on a popup navigated to about:blank (the iframe would be
974 // written into the popup by script on the main page). For these cases,
975 // there isn't any navigation stuff we can do, so just ignore it.
976 if (!GetLastCommittedEntry())
977 return NAVIGATION_TYPE_NAV_IGNORE;
979 // Valid subframe navigation.
980 return NAVIGATION_TYPE_NEW_SUBFRAME;
983 // Now we know that the notification is for an existing page. Find that entry.
984 int existing_entry_index = GetEntryIndexWithPageID(
985 web_contents_->GetSiteInstance(),
986 params.page_id);
987 if (existing_entry_index == -1) {
988 // The page was not found. It could have been pruned because of the limit on
989 // back/forward entries (not likely since we'll usually tell it to navigate
990 // to such entries). It could also mean that the renderer is smoking crack.
991 NOTREACHED();
993 // Because the unknown entry has committed, we risk showing the wrong URL in
994 // release builds. Instead, we'll kill the renderer process to be safe.
995 LOG(ERROR) << "terminating renderer for bad navigation: " << params.url;
996 RecordAction(UserMetricsAction("BadMessageTerminate_NC"));
998 // Temporary code so we can get more information. Format:
999 // http://url/foo.html#page1#max3#frame1#ids:2_Nx,1_1x,3_2
1000 std::string temp = params.url.spec();
1001 temp.append("#page");
1002 temp.append(base::IntToString(params.page_id));
1003 temp.append("#max");
1004 temp.append(base::IntToString(web_contents_->GetMaxPageID()));
1005 temp.append("#frame");
1006 temp.append(base::IntToString(params.frame_id));
1007 temp.append("#ids");
1008 for (int i = 0; i < static_cast<int>(entries_.size()); ++i) {
1009 // Append entry metadata (e.g., 3_7x):
1010 // 3: page_id
1011 // 7: SiteInstance ID, or N for null
1012 // x: appended if not from the current SiteInstance
1013 temp.append(base::IntToString(entries_[i]->GetPageID()));
1014 temp.append("_");
1015 if (entries_[i]->site_instance())
1016 temp.append(base::IntToString(entries_[i]->site_instance()->GetId()));
1017 else
1018 temp.append("N");
1019 if (entries_[i]->site_instance() != web_contents_->GetSiteInstance())
1020 temp.append("x");
1021 temp.append(",");
1023 GURL url(temp);
1024 static_cast<RenderViewHostImpl*>(
1025 web_contents_->GetRenderViewHost())->Send(
1026 new ViewMsg_TempCrashWithData(url));
1027 return NAVIGATION_TYPE_NAV_IGNORE;
1029 NavigationEntryImpl* existing_entry = entries_[existing_entry_index].get();
1031 if (!PageTransitionIsMainFrame(params.transition)) {
1032 // All manual subframes would get new IDs and were handled above, so we
1033 // know this is auto. Since the current page was found in the navigation
1034 // entry list, we're guaranteed to have a last committed entry.
1035 DCHECK(GetLastCommittedEntry());
1036 return NAVIGATION_TYPE_AUTO_SUBFRAME;
1039 // Anything below here we know is a main frame navigation.
1040 if (pending_entry_ &&
1041 existing_entry != pending_entry_ &&
1042 pending_entry_->GetPageID() == -1 &&
1043 existing_entry == GetLastCommittedEntry()) {
1044 // In this case, we have a pending entry for a URL but WebCore didn't do a
1045 // new navigation. This happens when you press enter in the URL bar to
1046 // reload. We will create a pending entry, but WebKit will convert it to
1047 // a reload since it's the same page and not create a new entry for it
1048 // (the user doesn't want to have a new back/forward entry when they do
1049 // this). If this matches the last committed entry, we want to just ignore
1050 // the pending entry and go back to where we were (the "existing entry").
1051 return NAVIGATION_TYPE_SAME_PAGE;
1054 // Any toplevel navigations with the same base (minus the reference fragment)
1055 // are in-page navigations. We weeded out subframe navigations above. Most of
1056 // the time this doesn't matter since WebKit doesn't tell us about subframe
1057 // navigations that don't actually navigate, but it can happen when there is
1058 // an encoding override (it always sends a navigation request).
1059 if (AreURLsInPageNavigation(existing_entry->GetURL(), params.url,
1060 params.was_within_same_page)) {
1061 return NAVIGATION_TYPE_IN_PAGE;
1064 // Since we weeded out "new" navigations above, we know this is an existing
1065 // (back/forward) navigation.
1066 return NAVIGATION_TYPE_EXISTING_PAGE;
1069 bool NavigationControllerImpl::IsRedirect(
1070 const ViewHostMsg_FrameNavigate_Params& params) {
1071 // For main frame transition, we judge by params.transition.
1072 // Otherwise, by params.redirects.
1073 if (PageTransitionIsMainFrame(params.transition)) {
1074 return PageTransitionIsRedirect(params.transition);
1076 return params.redirects.size() > 1;
1079 void NavigationControllerImpl::RendererDidNavigateToNewPage(
1080 const ViewHostMsg_FrameNavigate_Params& params, bool replace_entry) {
1081 NavigationEntryImpl* new_entry;
1082 bool update_virtual_url;
1083 if (pending_entry_) {
1084 // TODO(brettw) this assumes that the pending entry is appropriate for the
1085 // new page that was just loaded. I don't think this is necessarily the
1086 // case! We should have some more tracking to know for sure.
1087 new_entry = new NavigationEntryImpl(*pending_entry_);
1089 // Don't use the page type from the pending entry. Some interstitial page
1090 // may have set the type to interstitial. Once we commit, however, the page
1091 // type must always be normal.
1092 new_entry->set_page_type(PAGE_TYPE_NORMAL);
1093 update_virtual_url = new_entry->update_virtual_url_with_url();
1094 } else {
1095 new_entry = new NavigationEntryImpl;
1097 // Find out whether the new entry needs to update its virtual URL on URL
1098 // change and set up the entry accordingly. This is needed to correctly
1099 // update the virtual URL when replaceState is called after a pushState.
1100 GURL url = params.url;
1101 bool needs_update = false;
1102 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
1103 &url, browser_context_, &needs_update);
1104 new_entry->set_update_virtual_url_with_url(needs_update);
1106 // When navigating to a new page, give the browser URL handler a chance to
1107 // update the virtual URL based on the new URL. For example, this is needed
1108 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
1109 // the URL.
1110 update_virtual_url = needs_update;
1113 new_entry->SetURL(params.url);
1114 if (update_virtual_url)
1115 UpdateVirtualURLToURL(new_entry, params.url);
1116 new_entry->SetReferrer(params.referrer);
1117 new_entry->SetPageID(params.page_id);
1118 new_entry->SetTransitionType(params.transition);
1119 new_entry->set_site_instance(
1120 static_cast<SiteInstanceImpl*>(web_contents_->GetSiteInstance()));
1121 new_entry->SetHasPostData(params.is_post);
1122 new_entry->SetPostID(params.post_id);
1123 new_entry->SetOriginalRequestURL(params.original_request_url);
1124 new_entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1126 InsertOrReplaceEntry(new_entry, replace_entry);
1129 void NavigationControllerImpl::RendererDidNavigateToExistingPage(
1130 const ViewHostMsg_FrameNavigate_Params& params) {
1131 // We should only get here for main frame navigations.
1132 DCHECK(PageTransitionIsMainFrame(params.transition));
1134 // This is a back/forward navigation. The existing page for the ID is
1135 // guaranteed to exist by ClassifyNavigation, and we just need to update it
1136 // with new information from the renderer.
1137 int entry_index = GetEntryIndexWithPageID(web_contents_->GetSiteInstance(),
1138 params.page_id);
1139 DCHECK(entry_index >= 0 &&
1140 entry_index < static_cast<int>(entries_.size()));
1141 NavigationEntryImpl* entry = entries_[entry_index].get();
1143 // The URL may have changed due to redirects.
1144 entry->SetURL(params.url);
1145 if (entry->update_virtual_url_with_url())
1146 UpdateVirtualURLToURL(entry, params.url);
1148 // The redirected to page should not inherit the favicon from the previous
1149 // page.
1150 if (PageTransitionIsRedirect(params.transition))
1151 entry->GetFavicon() = FaviconStatus();
1153 // The site instance will normally be the same except during session restore,
1154 // when no site instance will be assigned.
1155 DCHECK(entry->site_instance() == NULL ||
1156 entry->site_instance() == web_contents_->GetSiteInstance());
1157 entry->set_site_instance(
1158 static_cast<SiteInstanceImpl*>(web_contents_->GetSiteInstance()));
1160 entry->SetHasPostData(params.is_post);
1161 entry->SetPostID(params.post_id);
1163 // The entry we found in the list might be pending if the user hit
1164 // back/forward/reload. This load should commit it (since it's already in the
1165 // list, we can just discard the pending pointer). We should also discard the
1166 // pending entry if it corresponds to a different navigation, since that one
1167 // is now likely canceled. If it is not canceled, we will treat it as a new
1168 // navigation when it arrives, which is also ok.
1170 // Note that we need to use the "internal" version since we don't want to
1171 // actually change any other state, just kill the pointer.
1172 DiscardNonCommittedEntriesInternal();
1174 // If a transient entry was removed, the indices might have changed, so we
1175 // have to query the entry index again.
1176 last_committed_entry_index_ =
1177 GetEntryIndexWithPageID(web_contents_->GetSiteInstance(), params.page_id);
1180 void NavigationControllerImpl::RendererDidNavigateToSamePage(
1181 const ViewHostMsg_FrameNavigate_Params& params) {
1182 // This mode implies we have a pending entry that's the same as an existing
1183 // entry for this page ID. This entry is guaranteed to exist by
1184 // ClassifyNavigation. All we need to do is update the existing entry.
1185 NavigationEntryImpl* existing_entry = GetEntryWithPageID(
1186 web_contents_->GetSiteInstance(), params.page_id);
1188 // We assign the entry's unique ID to be that of the new one. Since this is
1189 // always the result of a user action, we want to dismiss infobars, etc. like
1190 // a regular user-initiated navigation.
1191 existing_entry->set_unique_id(pending_entry_->GetUniqueID());
1193 // The URL may have changed due to redirects.
1194 if (existing_entry->update_virtual_url_with_url())
1195 UpdateVirtualURLToURL(existing_entry, params.url);
1196 existing_entry->SetURL(params.url);
1198 DiscardNonCommittedEntries();
1201 void NavigationControllerImpl::RendererDidNavigateInPage(
1202 const ViewHostMsg_FrameNavigate_Params& params, bool* did_replace_entry) {
1203 DCHECK(PageTransitionIsMainFrame(params.transition)) <<
1204 "WebKit should only tell us about in-page navs for the main frame.";
1205 // We're guaranteed to have an entry for this one.
1206 NavigationEntryImpl* existing_entry = GetEntryWithPageID(
1207 web_contents_->GetSiteInstance(), params.page_id);
1209 // Reference fragment navigation. We're guaranteed to have the last_committed
1210 // entry and it will be the same page as the new navigation (minus the
1211 // reference fragments, of course). We'll update the URL of the existing
1212 // entry without pruning the forward history.
1213 existing_entry->SetURL(params.url);
1214 if (existing_entry->update_virtual_url_with_url())
1215 UpdateVirtualURLToURL(existing_entry, params.url);
1217 // This replaces the existing entry since the page ID didn't change.
1218 *did_replace_entry = true;
1220 DiscardNonCommittedEntriesInternal();
1222 // If a transient entry was removed, the indices might have changed, so we
1223 // have to query the entry index again.
1224 last_committed_entry_index_ =
1225 GetEntryIndexWithPageID(web_contents_->GetSiteInstance(), params.page_id);
1228 void NavigationControllerImpl::RendererDidNavigateNewSubframe(
1229 const ViewHostMsg_FrameNavigate_Params& params) {
1230 if (PageTransitionStripQualifier(params.transition) ==
1231 PAGE_TRANSITION_AUTO_SUBFRAME) {
1232 // This is not user-initiated. Ignore.
1233 return;
1236 // Manual subframe navigations just get the current entry cloned so the user
1237 // can go back or forward to it. The actual subframe information will be
1238 // stored in the page state for each of those entries. This happens out of
1239 // band with the actual navigations.
1240 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
1241 << "that a last committed entry exists.";
1242 NavigationEntryImpl* new_entry = new NavigationEntryImpl(
1243 *NavigationEntryImpl::FromNavigationEntry(GetLastCommittedEntry()));
1244 new_entry->SetPageID(params.page_id);
1245 InsertOrReplaceEntry(new_entry, false);
1248 bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
1249 const ViewHostMsg_FrameNavigate_Params& params) {
1250 // We're guaranteed to have a previously committed entry, and we now need to
1251 // handle navigation inside of a subframe in it without creating a new entry.
1252 DCHECK(GetLastCommittedEntry());
1254 // Handle the case where we're navigating back/forward to a previous subframe
1255 // navigation entry. This is case "2." in NAV_AUTO_SUBFRAME comment in the
1256 // header file. In case "1." this will be a NOP.
1257 int entry_index = GetEntryIndexWithPageID(
1258 web_contents_->GetSiteInstance(),
1259 params.page_id);
1260 if (entry_index < 0 ||
1261 entry_index >= static_cast<int>(entries_.size())) {
1262 NOTREACHED();
1263 return false;
1266 // Update the current navigation entry in case we're going back/forward.
1267 if (entry_index != last_committed_entry_index_) {
1268 last_committed_entry_index_ = entry_index;
1269 return true;
1271 return false;
1274 int NavigationControllerImpl::GetIndexOfEntry(
1275 const NavigationEntryImpl* entry) const {
1276 const NavigationEntries::const_iterator i(std::find(
1277 entries_.begin(),
1278 entries_.end(),
1279 entry));
1280 return (i == entries_.end()) ? -1 : static_cast<int>(i - entries_.begin());
1283 bool NavigationControllerImpl::IsURLInPageNavigation(
1284 const GURL& url, bool renderer_says_in_page) const {
1285 NavigationEntry* last_committed = GetLastCommittedEntry();
1286 return last_committed && AreURLsInPageNavigation(
1287 last_committed->GetURL(), url, renderer_says_in_page);
1290 void NavigationControllerImpl::CopyStateFrom(
1291 const NavigationController& temp) {
1292 const NavigationControllerImpl& source =
1293 static_cast<const NavigationControllerImpl&>(temp);
1294 // Verify that we look new.
1295 DCHECK(GetEntryCount() == 0 && !GetPendingEntry());
1297 if (source.GetEntryCount() == 0)
1298 return; // Nothing new to do.
1300 needs_reload_ = true;
1301 InsertEntriesFrom(source, source.GetEntryCount());
1303 for (SessionStorageNamespaceMap::const_iterator it =
1304 source.session_storage_namespace_map_.begin();
1305 it != source.session_storage_namespace_map_.end();
1306 ++it) {
1307 SessionStorageNamespaceImpl* source_namespace =
1308 static_cast<SessionStorageNamespaceImpl*>(it->second.get());
1309 session_storage_namespace_map_.insert(
1310 make_pair(it->first, source_namespace->Clone()));
1313 FinishRestore(source.last_committed_entry_index_, RESTORE_CURRENT_SESSION);
1315 // Copy the max page id map from the old tab to the new tab. This ensures
1316 // that new and existing navigations in the tab's current SiteInstances
1317 // are identified properly.
1318 web_contents_->CopyMaxPageIDsFrom(source.web_contents());
1321 void NavigationControllerImpl::CopyStateFromAndPrune(
1322 NavigationController* temp) {
1323 NavigationControllerImpl* source =
1324 static_cast<NavigationControllerImpl*>(temp);
1325 // The SiteInstance and page_id of the last committed entry needs to be
1326 // remembered at this point, in case there is only one committed entry
1327 // and it is pruned. We use a scoped_refptr to ensure the SiteInstance
1328 // can't be freed during this time period.
1329 NavigationEntryImpl* last_committed =
1330 NavigationEntryImpl::FromNavigationEntry(GetLastCommittedEntry());
1331 scoped_refptr<SiteInstance> site_instance(
1332 last_committed ? last_committed->site_instance() : NULL);
1333 int32 minimum_page_id = last_committed ? last_committed->GetPageID() : -1;
1334 int32 max_page_id = last_committed ?
1335 web_contents_->GetMaxPageIDForSiteInstance(site_instance.get()) : -1;
1337 // This code is intended for use when the last entry is the active entry.
1338 DCHECK(
1339 (transient_entry_index_ != -1 &&
1340 transient_entry_index_ == GetEntryCount() - 1) ||
1341 (pending_entry_ && (pending_entry_index_ == -1 ||
1342 pending_entry_index_ == GetEntryCount() - 1)) ||
1343 (!pending_entry_ && last_committed_entry_index_ == GetEntryCount() - 1));
1345 // Remove all the entries leaving the active entry.
1346 PruneAllButActive();
1348 // We now have zero or one entries. Ensure that adding the entries from
1349 // source won't put us over the limit.
1350 DCHECK(GetEntryCount() == 0 || GetEntryCount() == 1);
1351 if (GetEntryCount() > 0)
1352 source->PruneOldestEntryIfFull();
1354 // Insert the entries from source. Don't use source->GetCurrentEntryIndex as
1355 // we don't want to copy over the transient entry.
1356 int max_source_index = source->pending_entry_index_ != -1 ?
1357 source->pending_entry_index_ : source->last_committed_entry_index_;
1358 if (max_source_index == -1)
1359 max_source_index = source->GetEntryCount();
1360 else
1361 max_source_index++;
1362 InsertEntriesFrom(*source, max_source_index);
1364 // Adjust indices such that the last entry and pending are at the end now.
1365 last_committed_entry_index_ = GetEntryCount() - 1;
1366 if (pending_entry_index_ != -1)
1367 pending_entry_index_ = GetEntryCount() - 1;
1368 if (transient_entry_index_ != -1) {
1369 // There's a transient entry. In this case we want the last committed to
1370 // point to the previous entry.
1371 transient_entry_index_ = GetEntryCount() - 1;
1372 if (last_committed_entry_index_ != -1)
1373 last_committed_entry_index_--;
1376 web_contents_->SetHistoryLengthAndPrune(site_instance.get(),
1377 max_source_index,
1378 minimum_page_id);
1380 // Copy the max page id map from the old tab to the new tab. This ensures
1381 // that new and existing navigations in the tab's current SiteInstances
1382 // are identified properly.
1383 web_contents_->CopyMaxPageIDsFrom(source->web_contents());
1385 // If there is a last committed entry, be sure to include it in the new
1386 // max page ID map.
1387 if (max_page_id > -1) {
1388 web_contents_->UpdateMaxPageIDForSiteInstance(site_instance.get(),
1389 max_page_id);
1393 void NavigationControllerImpl::PruneAllButActive() {
1394 if (transient_entry_index_ != -1) {
1395 // There is a transient entry. Prune up to it.
1396 DCHECK_EQ(GetEntryCount() - 1, transient_entry_index_);
1397 entries_.erase(entries_.begin(), entries_.begin() + transient_entry_index_);
1398 transient_entry_index_ = 0;
1399 last_committed_entry_index_ = -1;
1400 pending_entry_index_ = -1;
1401 } else if (!pending_entry_) {
1402 // There's no pending entry. Leave the last entry (if there is one).
1403 if (!GetEntryCount())
1404 return;
1406 DCHECK(last_committed_entry_index_ >= 0);
1407 entries_.erase(entries_.begin(),
1408 entries_.begin() + last_committed_entry_index_);
1409 entries_.erase(entries_.begin() + 1, entries_.end());
1410 last_committed_entry_index_ = 0;
1411 } else if (pending_entry_index_ != -1) {
1412 entries_.erase(entries_.begin(), entries_.begin() + pending_entry_index_);
1413 entries_.erase(entries_.begin() + 1, entries_.end());
1414 pending_entry_index_ = 0;
1415 last_committed_entry_index_ = 0;
1416 } else {
1417 // There is a pending_entry, but it's not in entries_.
1418 pending_entry_index_ = -1;
1419 last_committed_entry_index_ = -1;
1420 entries_.clear();
1423 if (web_contents_->GetInterstitialPage()) {
1424 // Normally the interstitial page hides itself if the user doesn't proceeed.
1425 // This would result in showing a NavigationEntry we just removed. Set this
1426 // so the interstitial triggers a reload if the user doesn't proceed.
1427 static_cast<InterstitialPageImpl*>(web_contents_->GetInterstitialPage())->
1428 set_reload_on_dont_proceed(true);
1432 // Implemented here and not in NavigationEntry because this controller caches
1433 // the total number of screen shots across all entries.
1434 void NavigationControllerImpl::ClearAllScreenshots() {
1435 for (NavigationEntries::iterator it = entries_.begin();
1436 it != entries_.end();
1437 ++it)
1438 ClearScreenshot(it->get());
1439 DCHECK_EQ(screenshot_count_, 0);
1442 void NavigationControllerImpl::SetSessionStorageNamespace(
1443 const std::string& partition_id,
1444 SessionStorageNamespace* session_storage_namespace) {
1445 if (!session_storage_namespace)
1446 return;
1448 // We can't overwrite an existing SessionStorage without violating spec.
1449 // Attempts to do so may give a tab access to another tab's session storage
1450 // so die hard on an error.
1451 bool successful_insert = session_storage_namespace_map_.insert(
1452 make_pair(partition_id,
1453 static_cast<SessionStorageNamespaceImpl*>(
1454 session_storage_namespace)))
1455 .second;
1456 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
1459 void NavigationControllerImpl::SetMaxRestoredPageID(int32 max_id) {
1460 max_restored_page_id_ = max_id;
1463 int32 NavigationControllerImpl::GetMaxRestoredPageID() const {
1464 return max_restored_page_id_;
1467 SessionStorageNamespace*
1468 NavigationControllerImpl::GetSessionStorageNamespace(SiteInstance* instance) {
1469 std::string partition_id;
1470 if (instance) {
1471 // TODO(ajwong): When GetDefaultSessionStorageNamespace() goes away, remove
1472 // this if statement so |instance| must not be NULL.
1473 partition_id =
1474 GetContentClient()->browser()->GetStoragePartitionIdForSite(
1475 browser_context_, instance->GetSiteURL());
1478 SessionStorageNamespaceMap::const_iterator it =
1479 session_storage_namespace_map_.find(partition_id);
1480 if (it != session_storage_namespace_map_.end())
1481 return it->second.get();
1483 // Create one if no one has accessed session storage for this partition yet.
1485 // TODO(ajwong): Should this use the |partition_id| directly rather than
1486 // re-lookup via |instance|? http://crbug.com/142685
1487 StoragePartition* partition =
1488 BrowserContext::GetStoragePartition(browser_context_, instance);
1489 SessionStorageNamespaceImpl* session_storage_namespace =
1490 new SessionStorageNamespaceImpl(
1491 static_cast<DOMStorageContextImpl*>(
1492 partition->GetDOMStorageContext()));
1493 session_storage_namespace_map_[partition_id] = session_storage_namespace;
1495 return session_storage_namespace;
1498 SessionStorageNamespace*
1499 NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
1500 // TODO(ajwong): Remove if statement in GetSessionStorageNamespace().
1501 return GetSessionStorageNamespace(NULL);
1504 const SessionStorageNamespaceMap&
1505 NavigationControllerImpl::GetSessionStorageNamespaceMap() const {
1506 return session_storage_namespace_map_;
1509 bool NavigationControllerImpl::NeedsReload() const {
1510 return needs_reload_;
1513 void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
1514 DCHECK(index < GetEntryCount());
1515 DCHECK(index != last_committed_entry_index_);
1517 DiscardNonCommittedEntries();
1519 entries_.erase(entries_.begin() + index);
1520 if (last_committed_entry_index_ > index)
1521 last_committed_entry_index_--;
1524 void NavigationControllerImpl::DiscardNonCommittedEntries() {
1525 bool transient = transient_entry_index_ != -1;
1526 DiscardNonCommittedEntriesInternal();
1528 // If there was a transient entry, invalidate everything so the new active
1529 // entry state is shown.
1530 if (transient) {
1531 web_contents_->NotifyNavigationStateChanged(kInvalidateAll);
1535 NavigationEntry* NavigationControllerImpl::GetPendingEntry() const {
1536 return pending_entry_;
1539 int NavigationControllerImpl::GetPendingEntryIndex() const {
1540 return pending_entry_index_;
1543 void NavigationControllerImpl::InsertOrReplaceEntry(NavigationEntryImpl* entry,
1544 bool replace) {
1545 DCHECK(entry->GetTransitionType() != PAGE_TRANSITION_AUTO_SUBFRAME);
1547 // Copy the pending entry's unique ID to the committed entry.
1548 // I don't know if pending_entry_index_ can be other than -1 here.
1549 const NavigationEntryImpl* const pending_entry =
1550 (pending_entry_index_ == -1) ?
1551 pending_entry_ : entries_[pending_entry_index_].get();
1552 if (pending_entry)
1553 entry->set_unique_id(pending_entry->GetUniqueID());
1555 DiscardNonCommittedEntriesInternal();
1557 int current_size = static_cast<int>(entries_.size());
1559 if (current_size > 0) {
1560 // Prune any entries which are in front of the current entry.
1561 // Also prune the current entry if we are to replace the current entry.
1562 // last_committed_entry_index_ must be updated here since calls to
1563 // NotifyPrunedEntries() below may re-enter and we must make sure
1564 // last_committed_entry_index_ is not left in an invalid state.
1565 if (replace)
1566 --last_committed_entry_index_;
1568 int num_pruned = 0;
1569 while (last_committed_entry_index_ < (current_size - 1)) {
1570 num_pruned++;
1571 entries_.pop_back();
1572 current_size--;
1574 if (num_pruned > 0) // Only notify if we did prune something.
1575 NotifyPrunedEntries(this, false, num_pruned);
1578 PruneOldestEntryIfFull();
1580 entries_.push_back(linked_ptr<NavigationEntryImpl>(entry));
1581 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
1583 // This is a new page ID, so we need everybody to know about it.
1584 web_contents_->UpdateMaxPageID(entry->GetPageID());
1587 void NavigationControllerImpl::PruneOldestEntryIfFull() {
1588 if (entries_.size() >= max_entry_count()) {
1589 DCHECK_EQ(max_entry_count(), entries_.size());
1590 DCHECK(last_committed_entry_index_ > 0);
1591 RemoveEntryAtIndex(0);
1592 NotifyPrunedEntries(this, true, 1);
1596 void NavigationControllerImpl::NavigateToPendingEntry(ReloadType reload_type) {
1597 needs_reload_ = false;
1599 // If we were navigating to a slow-to-commit page, and the user performs
1600 // a session history navigation to the last committed page, RenderViewHost
1601 // will force the throbber to start, but WebKit will essentially ignore the
1602 // navigation, and won't send a message to stop the throbber. To prevent this
1603 // from happening, we drop the navigation here and stop the slow-to-commit
1604 // page from loading (which would normally happen during the navigation).
1605 if (pending_entry_index_ != -1 &&
1606 pending_entry_index_ == last_committed_entry_index_ &&
1607 (entries_[pending_entry_index_]->restore_type() ==
1608 NavigationEntryImpl::RESTORE_NONE) &&
1609 (entries_[pending_entry_index_]->GetTransitionType() &
1610 PAGE_TRANSITION_FORWARD_BACK)) {
1611 web_contents_->Stop();
1613 // If an interstitial page is showing, we want to close it to get back
1614 // to what was showing before.
1615 if (web_contents_->GetInterstitialPage())
1616 web_contents_->GetInterstitialPage()->DontProceed();
1618 DiscardNonCommittedEntries();
1619 return;
1622 // If an interstitial page is showing, the previous renderer is blocked and
1623 // cannot make new requests. Unblock (and disable) it to allow this
1624 // navigation to succeed. The interstitial will stay visible until the
1625 // resulting DidNavigate.
1626 if (web_contents_->GetInterstitialPage()) {
1627 static_cast<InterstitialPageImpl*>(web_contents_->GetInterstitialPage())->
1628 CancelForNavigation();
1631 // For session history navigations only the pending_entry_index_ is set.
1632 if (!pending_entry_) {
1633 DCHECK_NE(pending_entry_index_, -1);
1634 pending_entry_ = entries_[pending_entry_index_].get();
1637 if (!web_contents_->NavigateToPendingEntry(reload_type))
1638 DiscardNonCommittedEntries();
1640 // If the entry is being restored and doesn't have a SiteInstance yet, fill
1641 // it in now that we know. This allows us to find the entry when it commits.
1642 // This works for browser-initiated navigations. We handle renderer-initiated
1643 // navigations to restored entries in WebContentsImpl::OnGoToEntryAtOffset.
1644 if (pending_entry_ && !pending_entry_->site_instance() &&
1645 pending_entry_->restore_type() != NavigationEntryImpl::RESTORE_NONE) {
1646 pending_entry_->set_site_instance(static_cast<SiteInstanceImpl*>(
1647 web_contents_->GetPendingSiteInstance()));
1648 pending_entry_->set_restore_type(NavigationEntryImpl::RESTORE_NONE);
1652 void NavigationControllerImpl::NotifyNavigationEntryCommitted(
1653 LoadCommittedDetails* details) {
1654 details->entry = GetActiveEntry();
1655 NotificationDetails notification_details =
1656 Details<LoadCommittedDetails>(details);
1658 // We need to notify the ssl_manager_ before the web_contents_ so the
1659 // location bar will have up-to-date information about the security style
1660 // when it wants to draw. See http://crbug.com/11157
1661 ssl_manager_.DidCommitProvisionalLoad(notification_details);
1663 // TODO(pkasting): http://b/1113079 Probably these explicit notification paths
1664 // should be removed, and interested parties should just listen for the
1665 // notification below instead.
1666 web_contents_->NotifyNavigationStateChanged(kInvalidateAll);
1668 NotificationService::current()->Notify(
1669 NOTIFICATION_NAV_ENTRY_COMMITTED,
1670 Source<NavigationController>(this),
1671 notification_details);
1674 // static
1675 size_t NavigationControllerImpl::max_entry_count() {
1676 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
1677 return max_entry_count_for_testing_;
1678 return kMaxSessionHistoryEntries;
1681 void NavigationControllerImpl::SetActive(bool is_active) {
1682 if (is_active && needs_reload_)
1683 LoadIfNecessary();
1686 void NavigationControllerImpl::LoadIfNecessary() {
1687 if (!needs_reload_)
1688 return;
1690 // Calling Reload() results in ignoring state, and not loading.
1691 // Explicitly use NavigateToPendingEntry so that the renderer uses the
1692 // cached state.
1693 pending_entry_index_ = last_committed_entry_index_;
1694 NavigateToPendingEntry(NO_RELOAD);
1697 void NavigationControllerImpl::NotifyEntryChanged(const NavigationEntry* entry,
1698 int index) {
1699 EntryChangedDetails det;
1700 det.changed_entry = entry;
1701 det.index = index;
1702 NotificationService::current()->Notify(
1703 NOTIFICATION_NAV_ENTRY_CHANGED,
1704 Source<NavigationController>(this),
1705 Details<EntryChangedDetails>(&det));
1708 void NavigationControllerImpl::FinishRestore(int selected_index,
1709 RestoreType type) {
1710 DCHECK(selected_index >= 0 && selected_index < GetEntryCount());
1711 ConfigureEntriesForRestore(&entries_, type);
1713 SetMaxRestoredPageID(static_cast<int32>(GetEntryCount()));
1715 last_committed_entry_index_ = selected_index;
1718 void NavigationControllerImpl::DiscardNonCommittedEntriesInternal() {
1719 if (pending_entry_index_ == -1)
1720 delete pending_entry_;
1721 pending_entry_ = NULL;
1722 pending_entry_index_ = -1;
1724 DiscardTransientEntry();
1727 void NavigationControllerImpl::DiscardTransientEntry() {
1728 if (transient_entry_index_ == -1)
1729 return;
1730 entries_.erase(entries_.begin() + transient_entry_index_);
1731 if (last_committed_entry_index_ > transient_entry_index_)
1732 last_committed_entry_index_--;
1733 transient_entry_index_ = -1;
1736 int NavigationControllerImpl::GetEntryIndexWithPageID(
1737 SiteInstance* instance, int32 page_id) const {
1738 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
1739 if ((entries_[i]->site_instance() == instance) &&
1740 (entries_[i]->GetPageID() == page_id))
1741 return i;
1743 return -1;
1746 NavigationEntry* NavigationControllerImpl::GetTransientEntry() const {
1747 if (transient_entry_index_ == -1)
1748 return NULL;
1749 return entries_[transient_entry_index_].get();
1752 void NavigationControllerImpl::InsertEntriesFrom(
1753 const NavigationControllerImpl& source,
1754 int max_index) {
1755 DCHECK_LE(max_index, source.GetEntryCount());
1756 size_t insert_index = 0;
1757 for (int i = 0; i < max_index; i++) {
1758 // When cloning a tab, copy all entries except interstitial pages
1759 if (source.entries_[i].get()->GetPageType() !=
1760 PAGE_TYPE_INTERSTITIAL) {
1761 entries_.insert(entries_.begin() + insert_index++,
1762 linked_ptr<NavigationEntryImpl>(
1763 new NavigationEntryImpl(*source.entries_[i])));
1768 void NavigationControllerImpl::SetGetTimestampCallbackForTest(
1769 const base::Callback<base::Time()>& get_timestamp_callback) {
1770 get_timestamp_callback_ = get_timestamp_callback;
1773 void NavigationControllerImpl::SetTakeScreenshotCallbackForTest(
1774 const base::Callback<void(RenderViewHost*)>& take_screenshot_callback) {
1775 take_screenshot_callback_ = take_screenshot_callback;
1778 } // namespace content