Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(811)

Side by Side Diff: content/browser/web_contents/navigation_controller_impl.cc

Issue 49823002: Move navigation and frame tree classes to a new frame_host/ directory. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Fixing gyp and adding TODO. Created 7 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "content/browser/web_contents/navigation_controller_impl.h"
6
7 #include "base/bind.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/renderer_host/render_view_host_impl.h" // Temporary
18 #include "content/browser/site_instance_impl.h"
19 #include "content/browser/web_contents/debug_urls.h"
20 #include "content/browser/web_contents/interstitial_page_impl.h"
21 #include "content/browser/web_contents/navigation_entry_impl.h"
22 #include "content/browser/web_contents/web_contents_screenshot_manager.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/browser/web_contents_delegate.h"
35 #include "content/public/common/content_client.h"
36 #include "content/public/common/content_constants.h"
37 #include "content/public/common/url_constants.h"
38 #include "net/base/escape.h"
39 #include "net/base/mime_util.h"
40 #include "net/base/net_util.h"
41 #include "skia/ext/platform_canvas.h"
42
43 namespace content {
44 namespace {
45
46 const int kInvalidateAll = 0xFFFFFFFF;
47
48 // Invoked when entries have been pruned, or removed. For example, if the
49 // current entries are [google, digg, yahoo], with the current entry google,
50 // and the user types in cnet, then digg and yahoo are pruned.
51 void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
52 bool from_front,
53 int count) {
54 PrunedDetails details;
55 details.from_front = from_front;
56 details.count = count;
57 NotificationService::current()->Notify(
58 NOTIFICATION_NAV_LIST_PRUNED,
59 Source<NavigationController>(nav_controller),
60 Details<PrunedDetails>(&details));
61 }
62
63 // Ensure the given NavigationEntry has a valid state, so that WebKit does not
64 // get confused if we navigate back to it.
65 //
66 // An empty state is treated as a new navigation by WebKit, which would mean
67 // losing the navigation entries and generating a new navigation entry after
68 // this one. We don't want that. To avoid this we create a valid state which
69 // WebKit will not treat as a new navigation.
70 void SetPageStateIfEmpty(NavigationEntryImpl* entry) {
71 if (!entry->GetPageState().IsValid())
72 entry->SetPageState(PageState::CreateFromURL(entry->GetURL()));
73 }
74
75 NavigationEntryImpl::RestoreType ControllerRestoreTypeToEntryType(
76 NavigationController::RestoreType type) {
77 switch (type) {
78 case NavigationController::RESTORE_CURRENT_SESSION:
79 return NavigationEntryImpl::RESTORE_CURRENT_SESSION;
80 case NavigationController::RESTORE_LAST_SESSION_EXITED_CLEANLY:
81 return NavigationEntryImpl::RESTORE_LAST_SESSION_EXITED_CLEANLY;
82 case NavigationController::RESTORE_LAST_SESSION_CRASHED:
83 return NavigationEntryImpl::RESTORE_LAST_SESSION_CRASHED;
84 }
85 NOTREACHED();
86 return NavigationEntryImpl::RESTORE_CURRENT_SESSION;
87 }
88
89 // Configure all the NavigationEntries in entries for restore. This resets
90 // the transition type to reload and makes sure the content state isn't empty.
91 void ConfigureEntriesForRestore(
92 std::vector<linked_ptr<NavigationEntryImpl> >* entries,
93 NavigationController::RestoreType type) {
94 for (size_t i = 0; i < entries->size(); ++i) {
95 // Use a transition type of reload so that we don't incorrectly increase
96 // the typed count.
97 (*entries)[i]->SetTransitionType(PAGE_TRANSITION_RELOAD);
98 (*entries)[i]->set_restore_type(ControllerRestoreTypeToEntryType(type));
99 // NOTE(darin): This code is only needed for backwards compat.
100 SetPageStateIfEmpty((*entries)[i].get());
101 }
102 }
103
104 // See NavigationController::IsURLInPageNavigation for how this works and why.
105 bool AreURLsInPageNavigation(const GURL& existing_url,
106 const GURL& new_url,
107 bool renderer_says_in_page,
108 NavigationType navigation_type) {
109 if (existing_url == new_url)
110 return renderer_says_in_page;
111
112 if (!new_url.has_ref()) {
113 // When going back from the ref URL to the non ref one the navigation type
114 // is IN_PAGE.
115 return navigation_type == NAVIGATION_TYPE_IN_PAGE;
116 }
117
118 url_canon::Replacements<char> replacements;
119 replacements.ClearRef();
120 return existing_url.ReplaceComponents(replacements) ==
121 new_url.ReplaceComponents(replacements);
122 }
123
124 // Determines whether or not we should be carrying over a user agent override
125 // between two NavigationEntries.
126 bool ShouldKeepOverride(const NavigationEntry* last_entry) {
127 return last_entry && last_entry->GetIsOverridingUserAgent();
128 }
129
130 } // namespace
131
132 // NavigationControllerImpl ----------------------------------------------------
133
134 const size_t kMaxEntryCountForTestingNotSet = -1;
135
136 // static
137 size_t NavigationControllerImpl::max_entry_count_for_testing_ =
138 kMaxEntryCountForTestingNotSet;
139
140 // Should Reload check for post data? The default is true, but is set to false
141 // when testing.
142 static bool g_check_for_repost = true;
143
144 // static
145 NavigationEntry* NavigationController::CreateNavigationEntry(
146 const GURL& url,
147 const Referrer& referrer,
148 PageTransition transition,
149 bool is_renderer_initiated,
150 const std::string& extra_headers,
151 BrowserContext* browser_context) {
152 // Allow the browser URL handler to rewrite the URL. This will, for example,
153 // remove "view-source:" from the beginning of the URL to get the URL that
154 // will actually be loaded. This real URL won't be shown to the user, just
155 // used internally.
156 GURL loaded_url(url);
157 bool reverse_on_redirect = false;
158 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
159 &loaded_url, browser_context, &reverse_on_redirect);
160
161 NavigationEntryImpl* entry = new NavigationEntryImpl(
162 NULL, // The site instance for tabs is sent on navigation
163 // (WebContents::GetSiteInstance).
164 -1,
165 loaded_url,
166 referrer,
167 string16(),
168 transition,
169 is_renderer_initiated);
170 entry->SetVirtualURL(url);
171 entry->set_user_typed_url(url);
172 entry->set_update_virtual_url_with_url(reverse_on_redirect);
173 entry->set_extra_headers(extra_headers);
174 return entry;
175 }
176
177 // static
178 void NavigationController::DisablePromptOnRepost() {
179 g_check_for_repost = false;
180 }
181
182 base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
183 base::Time t) {
184 // If |t| is between the water marks, we're in a run of duplicates
185 // or just getting out of it, so increase the high-water mark to get
186 // a time that probably hasn't been used before and return it.
187 if (low_water_mark_ <= t && t <= high_water_mark_) {
188 high_water_mark_ += base::TimeDelta::FromMicroseconds(1);
189 return high_water_mark_;
190 }
191
192 // Otherwise, we're clear of the last duplicate run, so reset the
193 // water marks.
194 low_water_mark_ = high_water_mark_ = t;
195 return t;
196 }
197
198 NavigationControllerImpl::NavigationControllerImpl(
199 NavigationControllerDelegate* delegate,
200 BrowserContext* browser_context)
201 : browser_context_(browser_context),
202 pending_entry_(NULL),
203 last_committed_entry_index_(-1),
204 pending_entry_index_(-1),
205 transient_entry_index_(-1),
206 delegate_(delegate),
207 max_restored_page_id_(-1),
208 ssl_manager_(this),
209 needs_reload_(false),
210 is_initial_navigation_(true),
211 pending_reload_(NO_RELOAD),
212 get_timestamp_callback_(base::Bind(&base::Time::Now)),
213 screenshot_manager_(new WebContentsScreenshotManager(this)) {
214 DCHECK(browser_context_);
215 }
216
217 NavigationControllerImpl::~NavigationControllerImpl() {
218 DiscardNonCommittedEntriesInternal();
219 }
220
221 WebContents* NavigationControllerImpl::GetWebContents() const {
222 return delegate_->GetWebContents();
223 }
224
225 BrowserContext* NavigationControllerImpl::GetBrowserContext() const {
226 return browser_context_;
227 }
228
229 void NavigationControllerImpl::SetBrowserContext(
230 BrowserContext* browser_context) {
231 browser_context_ = browser_context;
232 }
233
234 void NavigationControllerImpl::Restore(
235 int selected_navigation,
236 RestoreType type,
237 std::vector<NavigationEntry*>* entries) {
238 // Verify that this controller is unused and that the input is valid.
239 DCHECK(GetEntryCount() == 0 && !GetPendingEntry());
240 DCHECK(selected_navigation >= 0 &&
241 selected_navigation < static_cast<int>(entries->size()));
242
243 needs_reload_ = true;
244 for (size_t i = 0; i < entries->size(); ++i) {
245 NavigationEntryImpl* entry =
246 NavigationEntryImpl::FromNavigationEntry((*entries)[i]);
247 entries_.push_back(linked_ptr<NavigationEntryImpl>(entry));
248 }
249 entries->clear();
250
251 // And finish the restore.
252 FinishRestore(selected_navigation, type);
253 }
254
255 void NavigationControllerImpl::Reload(bool check_for_repost) {
256 ReloadInternal(check_for_repost, RELOAD);
257 }
258 void NavigationControllerImpl::ReloadIgnoringCache(bool check_for_repost) {
259 ReloadInternal(check_for_repost, RELOAD_IGNORING_CACHE);
260 }
261 void NavigationControllerImpl::ReloadOriginalRequestURL(bool check_for_repost) {
262 ReloadInternal(check_for_repost, RELOAD_ORIGINAL_REQUEST_URL);
263 }
264
265 void NavigationControllerImpl::ReloadInternal(bool check_for_repost,
266 ReloadType reload_type) {
267 if (transient_entry_index_ != -1) {
268 // If an interstitial is showing, treat a reload as a navigation to the
269 // transient entry's URL.
270 NavigationEntryImpl* transient_entry =
271 NavigationEntryImpl::FromNavigationEntry(GetTransientEntry());
272 if (!transient_entry)
273 return;
274 LoadURL(transient_entry->GetURL(),
275 Referrer(),
276 PAGE_TRANSITION_RELOAD,
277 transient_entry->extra_headers());
278 return;
279 }
280
281 NavigationEntryImpl* entry = NULL;
282 int current_index = -1;
283
284 // If we are reloading the initial navigation, just use the current
285 // pending entry. Otherwise look up the current entry.
286 if (IsInitialNavigation() && pending_entry_) {
287 entry = pending_entry_;
288 // The pending entry might be in entries_ (e.g., after a Clone), so we
289 // should also update the current_index.
290 current_index = pending_entry_index_;
291 } else {
292 DiscardNonCommittedEntriesInternal();
293 current_index = GetCurrentEntryIndex();
294 if (current_index != -1) {
295 entry = NavigationEntryImpl::FromNavigationEntry(
296 GetEntryAtIndex(current_index));
297 }
298 }
299
300 // If we are no where, then we can't reload. TODO(darin): We should add a
301 // CanReload method.
302 if (!entry)
303 return;
304
305 if (reload_type == NavigationControllerImpl::RELOAD_ORIGINAL_REQUEST_URL &&
306 entry->GetOriginalRequestURL().is_valid() && !entry->GetHasPostData()) {
307 // We may have been redirected when navigating to the current URL.
308 // Use the URL the user originally intended to visit, if it's valid and if a
309 // POST wasn't involved; the latter case avoids issues with sending data to
310 // the wrong page.
311 entry->SetURL(entry->GetOriginalRequestURL());
312 }
313
314 if (g_check_for_repost && check_for_repost &&
315 entry->GetHasPostData()) {
316 // The user is asking to reload a page with POST data. Prompt to make sure
317 // they really want to do this. If they do, the dialog will call us back
318 // with check_for_repost = false.
319 delegate_->NotifyBeforeFormRepostWarningShow();
320
321 pending_reload_ = reload_type;
322 delegate_->ActivateAndShowRepostFormWarningDialog();
323 } else {
324 if (!IsInitialNavigation())
325 DiscardNonCommittedEntriesInternal();
326
327 // If we are reloading an entry that no longer belongs to the current
328 // site instance (for example, refreshing a page for just installed app),
329 // the reload must happen in a new process.
330 // The new entry must have a new page_id and site instance, so it behaves
331 // as new navigation (which happens to clear forward history).
332 // Tabs that are discarded due to low memory conditions may not have a site
333 // instance, and should not be treated as a cross-site reload.
334 SiteInstanceImpl* site_instance = entry->site_instance();
335 if (site_instance &&
336 site_instance->HasWrongProcessForURL(entry->GetURL())) {
337 // Create a navigation entry that resembles the current one, but do not
338 // copy page id, site instance, content state, or timestamp.
339 NavigationEntryImpl* nav_entry = NavigationEntryImpl::FromNavigationEntry(
340 CreateNavigationEntry(
341 entry->GetURL(), entry->GetReferrer(), entry->GetTransitionType(),
342 false, entry->extra_headers(), browser_context_));
343
344 // Mark the reload type as NO_RELOAD, so navigation will not be considered
345 // a reload in the renderer.
346 reload_type = NavigationController::NO_RELOAD;
347
348 nav_entry->set_should_replace_entry(true);
349 pending_entry_ = nav_entry;
350 } else {
351 pending_entry_ = entry;
352 pending_entry_index_ = current_index;
353
354 // The title of the page being reloaded might have been removed in the
355 // meanwhile, so we need to revert to the default title upon reload and
356 // invalidate the previously cached title (SetTitle will do both).
357 // See Chromium issue 96041.
358 pending_entry_->SetTitle(string16());
359
360 pending_entry_->SetTransitionType(PAGE_TRANSITION_RELOAD);
361 }
362
363 NavigateToPendingEntry(reload_type);
364 }
365 }
366
367 void NavigationControllerImpl::CancelPendingReload() {
368 DCHECK(pending_reload_ != NO_RELOAD);
369 pending_reload_ = NO_RELOAD;
370 }
371
372 void NavigationControllerImpl::ContinuePendingReload() {
373 if (pending_reload_ == NO_RELOAD) {
374 NOTREACHED();
375 } else {
376 ReloadInternal(false, pending_reload_);
377 pending_reload_ = NO_RELOAD;
378 }
379 }
380
381 bool NavigationControllerImpl::IsInitialNavigation() const {
382 return is_initial_navigation_;
383 }
384
385 NavigationEntryImpl* NavigationControllerImpl::GetEntryWithPageID(
386 SiteInstance* instance, int32 page_id) const {
387 int index = GetEntryIndexWithPageID(instance, page_id);
388 return (index != -1) ? entries_[index].get() : NULL;
389 }
390
391 void NavigationControllerImpl::LoadEntry(NavigationEntryImpl* entry) {
392 // When navigating to a new page, we don't know for sure if we will actually
393 // end up leaving the current page. The new page load could for example
394 // result in a download or a 'no content' response (e.g., a mailto: URL).
395 SetPendingEntry(entry);
396 NavigateToPendingEntry(NO_RELOAD);
397 }
398
399 void NavigationControllerImpl::SetPendingEntry(NavigationEntryImpl* entry) {
400 DiscardNonCommittedEntriesInternal();
401 pending_entry_ = entry;
402 NotificationService::current()->Notify(
403 NOTIFICATION_NAV_ENTRY_PENDING,
404 Source<NavigationController>(this),
405 Details<NavigationEntry>(entry));
406 }
407
408 NavigationEntry* NavigationControllerImpl::GetActiveEntry() const {
409 if (transient_entry_index_ != -1)
410 return entries_[transient_entry_index_].get();
411 if (pending_entry_)
412 return pending_entry_;
413 return GetLastCommittedEntry();
414 }
415
416 NavigationEntry* NavigationControllerImpl::GetVisibleEntry() const {
417 if (transient_entry_index_ != -1)
418 return entries_[transient_entry_index_].get();
419 // The pending entry is safe to return for new (non-history), browser-
420 // initiated navigations. Most renderer-initiated navigations should not
421 // show the pending entry, to prevent URL spoof attacks.
422 //
423 // We make an exception for renderer-initiated navigations in new tabs, as
424 // long as no other page has tried to access the initial empty document in
425 // the new tab. If another page modifies this blank page, a URL spoof is
426 // possible, so we must stop showing the pending entry.
427 RenderViewHostImpl* rvh = static_cast<RenderViewHostImpl*>(
428 delegate_->GetRenderViewHost());
429 bool safe_to_show_pending =
430 pending_entry_ &&
431 // Require a new navigation.
432 pending_entry_->GetPageID() == -1 &&
433 // Require either browser-initiated or an unmodified new tab.
434 (!pending_entry_->is_renderer_initiated() ||
435 (IsInitialNavigation() &&
436 !GetLastCommittedEntry() &&
437 !rvh->has_accessed_initial_document()));
438
439 // Also allow showing the pending entry for history navigations in a new tab,
440 // such as Ctrl+Back. In this case, no existing page is visible and no one
441 // can script the new tab before it commits.
442 if (!safe_to_show_pending &&
443 pending_entry_ &&
444 pending_entry_->GetPageID() != -1 &&
445 IsInitialNavigation() &&
446 !pending_entry_->is_renderer_initiated())
447 safe_to_show_pending = true;
448
449 if (safe_to_show_pending)
450 return pending_entry_;
451 return GetLastCommittedEntry();
452 }
453
454 int NavigationControllerImpl::GetCurrentEntryIndex() const {
455 if (transient_entry_index_ != -1)
456 return transient_entry_index_;
457 if (pending_entry_index_ != -1)
458 return pending_entry_index_;
459 return last_committed_entry_index_;
460 }
461
462 NavigationEntry* NavigationControllerImpl::GetLastCommittedEntry() const {
463 if (last_committed_entry_index_ == -1)
464 return NULL;
465 return entries_[last_committed_entry_index_].get();
466 }
467
468 bool NavigationControllerImpl::CanViewSource() const {
469 const std::string& mime_type = delegate_->GetContentsMimeType();
470 bool is_viewable_mime_type = net::IsSupportedNonImageMimeType(mime_type) &&
471 !net::IsSupportedMediaMimeType(mime_type);
472 NavigationEntry* visible_entry = GetVisibleEntry();
473 return visible_entry && !visible_entry->IsViewSourceMode() &&
474 is_viewable_mime_type && !delegate_->GetInterstitialPage();
475 }
476
477 int NavigationControllerImpl::GetLastCommittedEntryIndex() const {
478 return last_committed_entry_index_;
479 }
480
481 int NavigationControllerImpl::GetEntryCount() const {
482 DCHECK(entries_.size() <= max_entry_count());
483 return static_cast<int>(entries_.size());
484 }
485
486 NavigationEntry* NavigationControllerImpl::GetEntryAtIndex(
487 int index) const {
488 return entries_.at(index).get();
489 }
490
491 NavigationEntry* NavigationControllerImpl::GetEntryAtOffset(
492 int offset) const {
493 int index = GetIndexForOffset(offset);
494 if (index < 0 || index >= GetEntryCount())
495 return NULL;
496
497 return entries_[index].get();
498 }
499
500 int NavigationControllerImpl::GetIndexForOffset(int offset) const {
501 return GetCurrentEntryIndex() + offset;
502 }
503
504 void NavigationControllerImpl::TakeScreenshot() {
505 screenshot_manager_->TakeScreenshot();
506 }
507
508 void NavigationControllerImpl::SetScreenshotManager(
509 WebContentsScreenshotManager* manager) {
510 screenshot_manager_.reset(manager ? manager :
511 new WebContentsScreenshotManager(this));
512 }
513
514 bool NavigationControllerImpl::CanGoBack() const {
515 return entries_.size() > 1 && GetCurrentEntryIndex() > 0;
516 }
517
518 bool NavigationControllerImpl::CanGoForward() const {
519 int index = GetCurrentEntryIndex();
520 return index >= 0 && index < (static_cast<int>(entries_.size()) - 1);
521 }
522
523 bool NavigationControllerImpl::CanGoToOffset(int offset) const {
524 int index = GetIndexForOffset(offset);
525 return index >= 0 && index < GetEntryCount();
526 }
527
528 void NavigationControllerImpl::GoBack() {
529 if (!CanGoBack()) {
530 NOTREACHED();
531 return;
532 }
533
534 // Base the navigation on where we are now...
535 int current_index = GetCurrentEntryIndex();
536
537 DiscardNonCommittedEntries();
538
539 pending_entry_index_ = current_index - 1;
540 entries_[pending_entry_index_]->SetTransitionType(
541 PageTransitionFromInt(
542 entries_[pending_entry_index_]->GetTransitionType() |
543 PAGE_TRANSITION_FORWARD_BACK));
544 NavigateToPendingEntry(NO_RELOAD);
545 }
546
547 void NavigationControllerImpl::GoForward() {
548 if (!CanGoForward()) {
549 NOTREACHED();
550 return;
551 }
552
553 bool transient = (transient_entry_index_ != -1);
554
555 // Base the navigation on where we are now...
556 int current_index = GetCurrentEntryIndex();
557
558 DiscardNonCommittedEntries();
559
560 pending_entry_index_ = current_index;
561 // If there was a transient entry, we removed it making the current index
562 // the next page.
563 if (!transient)
564 pending_entry_index_++;
565
566 entries_[pending_entry_index_]->SetTransitionType(
567 PageTransitionFromInt(
568 entries_[pending_entry_index_]->GetTransitionType() |
569 PAGE_TRANSITION_FORWARD_BACK));
570 NavigateToPendingEntry(NO_RELOAD);
571 }
572
573 void NavigationControllerImpl::GoToIndex(int index) {
574 if (index < 0 || index >= static_cast<int>(entries_.size())) {
575 NOTREACHED();
576 return;
577 }
578
579 if (transient_entry_index_ != -1) {
580 if (index == transient_entry_index_) {
581 // Nothing to do when navigating to the transient.
582 return;
583 }
584 if (index > transient_entry_index_) {
585 // Removing the transient is goint to shift all entries by 1.
586 index--;
587 }
588 }
589
590 DiscardNonCommittedEntries();
591
592 pending_entry_index_ = index;
593 entries_[pending_entry_index_]->SetTransitionType(
594 PageTransitionFromInt(
595 entries_[pending_entry_index_]->GetTransitionType() |
596 PAGE_TRANSITION_FORWARD_BACK));
597 NavigateToPendingEntry(NO_RELOAD);
598 }
599
600 void NavigationControllerImpl::GoToOffset(int offset) {
601 if (!CanGoToOffset(offset))
602 return;
603
604 GoToIndex(GetIndexForOffset(offset));
605 }
606
607 bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
608 if (index == last_committed_entry_index_ ||
609 index == pending_entry_index_)
610 return false;
611
612 RemoveEntryAtIndexInternal(index);
613 return true;
614 }
615
616 void NavigationControllerImpl::UpdateVirtualURLToURL(
617 NavigationEntryImpl* entry, const GURL& new_url) {
618 GURL new_virtual_url(new_url);
619 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
620 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
621 entry->SetVirtualURL(new_virtual_url);
622 }
623 }
624
625 void NavigationControllerImpl::LoadURL(
626 const GURL& url,
627 const Referrer& referrer,
628 PageTransition transition,
629 const std::string& extra_headers) {
630 LoadURLParams params(url);
631 params.referrer = referrer;
632 params.transition_type = transition;
633 params.extra_headers = extra_headers;
634 LoadURLWithParams(params);
635 }
636
637 void NavigationControllerImpl::LoadURLWithParams(const LoadURLParams& params) {
638 TRACE_EVENT0("browser", "NavigationControllerImpl::LoadURLWithParams");
639 if (HandleDebugURL(params.url, params.transition_type))
640 return;
641
642 // Checks based on params.load_type.
643 switch (params.load_type) {
644 case LOAD_TYPE_DEFAULT:
645 break;
646 case LOAD_TYPE_BROWSER_INITIATED_HTTP_POST:
647 if (!params.url.SchemeIs(kHttpScheme) &&
648 !params.url.SchemeIs(kHttpsScheme)) {
649 NOTREACHED() << "Http post load must use http(s) scheme.";
650 return;
651 }
652 break;
653 case LOAD_TYPE_DATA:
654 if (!params.url.SchemeIs(chrome::kDataScheme)) {
655 NOTREACHED() << "Data load must use data scheme.";
656 return;
657 }
658 break;
659 default:
660 NOTREACHED();
661 break;
662 };
663
664 // The user initiated a load, we don't need to reload anymore.
665 needs_reload_ = false;
666
667 bool override = false;
668 switch (params.override_user_agent) {
669 case UA_OVERRIDE_INHERIT:
670 override = ShouldKeepOverride(GetLastCommittedEntry());
671 break;
672 case UA_OVERRIDE_TRUE:
673 override = true;
674 break;
675 case UA_OVERRIDE_FALSE:
676 override = false;
677 break;
678 default:
679 NOTREACHED();
680 break;
681 }
682
683 NavigationEntryImpl* entry = NavigationEntryImpl::FromNavigationEntry(
684 CreateNavigationEntry(
685 params.url,
686 params.referrer,
687 params.transition_type,
688 params.is_renderer_initiated,
689 params.extra_headers,
690 browser_context_));
691 if (params.should_replace_current_entry)
692 entry->set_should_replace_entry(true);
693 entry->set_should_clear_history_list(params.should_clear_history_list);
694 entry->SetIsOverridingUserAgent(override);
695 entry->set_transferred_global_request_id(
696 params.transferred_global_request_id);
697 entry->SetFrameToNavigate(params.frame_name);
698
699 switch (params.load_type) {
700 case LOAD_TYPE_DEFAULT:
701 break;
702 case LOAD_TYPE_BROWSER_INITIATED_HTTP_POST:
703 entry->SetHasPostData(true);
704 entry->SetBrowserInitiatedPostData(
705 params.browser_initiated_post_data.get());
706 break;
707 case LOAD_TYPE_DATA:
708 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
709 entry->SetVirtualURL(params.virtual_url_for_data_url);
710 entry->SetCanLoadLocalResources(params.can_load_local_resources);
711 break;
712 default:
713 NOTREACHED();
714 break;
715 };
716
717 LoadEntry(entry);
718 }
719
720 bool NavigationControllerImpl::RendererDidNavigate(
721 const ViewHostMsg_FrameNavigate_Params& params,
722 LoadCommittedDetails* details) {
723 is_initial_navigation_ = false;
724
725 // Save the previous state before we clobber it.
726 if (GetLastCommittedEntry()) {
727 details->previous_url = GetLastCommittedEntry()->GetURL();
728 details->previous_entry_index = GetLastCommittedEntryIndex();
729 } else {
730 details->previous_url = GURL();
731 details->previous_entry_index = -1;
732 }
733
734 // If we have a pending entry at this point, it should have a SiteInstance.
735 // Restored entries start out with a null SiteInstance, but we should have
736 // assigned one in NavigateToPendingEntry.
737 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance());
738
739 // If we are doing a cross-site reload, we need to replace the existing
740 // navigation entry, not add another entry to the history. This has the side
741 // effect of removing forward browsing history, if such existed.
742 // Or if we are doing a cross-site redirect navigation,
743 // we will do a similar thing.
744 details->did_replace_entry =
745 pending_entry_ && pending_entry_->should_replace_entry();
746
747 // Do navigation-type specific actions. These will make and commit an entry.
748 details->type = ClassifyNavigation(params);
749
750 // is_in_page must be computed before the entry gets committed.
751 details->is_in_page = IsURLInPageNavigation(
752 params.url, params.was_within_same_page, details->type);
753
754 switch (details->type) {
755 case NAVIGATION_TYPE_NEW_PAGE:
756 RendererDidNavigateToNewPage(params, details->did_replace_entry);
757 break;
758 case NAVIGATION_TYPE_EXISTING_PAGE:
759 RendererDidNavigateToExistingPage(params);
760 break;
761 case NAVIGATION_TYPE_SAME_PAGE:
762 RendererDidNavigateToSamePage(params);
763 break;
764 case NAVIGATION_TYPE_IN_PAGE:
765 RendererDidNavigateInPage(params, &details->did_replace_entry);
766 break;
767 case NAVIGATION_TYPE_NEW_SUBFRAME:
768 RendererDidNavigateNewSubframe(params);
769 break;
770 case NAVIGATION_TYPE_AUTO_SUBFRAME:
771 if (!RendererDidNavigateAutoSubframe(params))
772 return false;
773 break;
774 case NAVIGATION_TYPE_NAV_IGNORE:
775 // If a pending navigation was in progress, this canceled it. We should
776 // discard it and make sure it is removed from the URL bar. After that,
777 // there is nothing we can do with this navigation, so we just return to
778 // the caller that nothing has happened.
779 if (pending_entry_) {
780 DiscardNonCommittedEntries();
781 delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
782 }
783 return false;
784 default:
785 NOTREACHED();
786 }
787
788 // At this point, we know that the navigation has just completed, so
789 // record the time.
790 //
791 // TODO(akalin): Use "sane time" as described in
792 // http://www.chromium.org/developers/design-documents/sane-time .
793 base::Time timestamp =
794 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
795 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
796 << timestamp.ToInternalValue();
797
798 // We should not have a pending entry anymore. Clear it again in case any
799 // error cases above forgot to do so.
800 DiscardNonCommittedEntriesInternal();
801
802 // All committed entries should have nonempty content state so WebKit doesn't
803 // get confused when we go back to them (see the function for details).
804 DCHECK(params.page_state.IsValid());
805 NavigationEntryImpl* active_entry =
806 NavigationEntryImpl::FromNavigationEntry(GetLastCommittedEntry());
807 active_entry->SetTimestamp(timestamp);
808 active_entry->SetHttpStatusCode(params.http_status_code);
809 active_entry->SetPageState(params.page_state);
810 // No longer needed since content state will hold the post data if any.
811 active_entry->SetBrowserInitiatedPostData(NULL);
812
813 // Once committed, we do not need to track if the entry was initiated by
814 // the renderer.
815 active_entry->set_is_renderer_initiated(false);
816
817 // Once committed, we no longer need to track whether the session history was
818 // cleared. Navigating to this entry again shouldn't clear it again.
819 active_entry->set_should_clear_history_list(false);
820
821 // The active entry's SiteInstance should match our SiteInstance.
822 CHECK(active_entry->site_instance() == delegate_->GetSiteInstance());
823
824 // Remember the bindings the renderer process has at this point, so that
825 // we do not grant this entry additional bindings if we come back to it.
826 active_entry->SetBindings(
827 delegate_->GetRenderViewHost()->GetEnabledBindings());
828
829 // Now prep the rest of the details for the notification and broadcast.
830 details->entry = active_entry;
831 details->is_main_frame =
832 PageTransitionIsMainFrame(params.transition);
833 details->serialized_security_info = params.security_info;
834 details->http_status_code = params.http_status_code;
835 NotifyNavigationEntryCommitted(details);
836
837 return true;
838 }
839
840 NavigationType NavigationControllerImpl::ClassifyNavigation(
841 const ViewHostMsg_FrameNavigate_Params& params) const {
842 if (params.page_id == -1) {
843 // The renderer generates the page IDs, and so if it gives us the invalid
844 // page ID (-1) we know it didn't actually navigate. This happens in a few
845 // cases:
846 //
847 // - If a page makes a popup navigated to about blank, and then writes
848 // stuff like a subframe navigated to a real page. We'll get the commit
849 // for the subframe, but there won't be any commit for the outer page.
850 //
851 // - We were also getting these for failed loads (for example, bug 21849).
852 // The guess is that we get a "load commit" for the alternate error page,
853 // but that doesn't affect the page ID, so we get the "old" one, which
854 // could be invalid. This can also happen for a cross-site transition
855 // that causes us to swap processes. Then the error page load will be in
856 // a new process with no page IDs ever assigned (and hence a -1 value),
857 // yet the navigation controller still might have previous pages in its
858 // list.
859 //
860 // In these cases, there's nothing we can do with them, so ignore.
861 return NAVIGATION_TYPE_NAV_IGNORE;
862 }
863
864 if (params.page_id > delegate_->GetMaxPageID()) {
865 // Greater page IDs than we've ever seen before are new pages. We may or may
866 // not have a pending entry for the page, and this may or may not be the
867 // main frame.
868 if (PageTransitionIsMainFrame(params.transition))
869 return NAVIGATION_TYPE_NEW_PAGE;
870
871 // When this is a new subframe navigation, we should have a committed page
872 // for which it's a suframe in. This may not be the case when an iframe is
873 // navigated on a popup navigated to about:blank (the iframe would be
874 // written into the popup by script on the main page). For these cases,
875 // there isn't any navigation stuff we can do, so just ignore it.
876 if (!GetLastCommittedEntry())
877 return NAVIGATION_TYPE_NAV_IGNORE;
878
879 // Valid subframe navigation.
880 return NAVIGATION_TYPE_NEW_SUBFRAME;
881 }
882
883 // We only clear the session history when navigating to a new page.
884 DCHECK(!params.history_list_was_cleared);
885
886 // Now we know that the notification is for an existing page. Find that entry.
887 int existing_entry_index = GetEntryIndexWithPageID(
888 delegate_->GetSiteInstance(),
889 params.page_id);
890 if (existing_entry_index == -1) {
891 // The page was not found. It could have been pruned because of the limit on
892 // back/forward entries (not likely since we'll usually tell it to navigate
893 // to such entries). It could also mean that the renderer is smoking crack.
894 NOTREACHED();
895
896 // Because the unknown entry has committed, we risk showing the wrong URL in
897 // release builds. Instead, we'll kill the renderer process to be safe.
898 LOG(ERROR) << "terminating renderer for bad navigation: " << params.url;
899 RecordAction(UserMetricsAction("BadMessageTerminate_NC"));
900
901 // Temporary code so we can get more information. Format:
902 // http://url/foo.html#page1#max3#frame1#ids:2_Nx,1_1x,3_2
903 std::string temp = params.url.spec();
904 temp.append("#page");
905 temp.append(base::IntToString(params.page_id));
906 temp.append("#max");
907 temp.append(base::IntToString(delegate_->GetMaxPageID()));
908 temp.append("#frame");
909 temp.append(base::IntToString(params.frame_id));
910 temp.append("#ids");
911 for (int i = 0; i < static_cast<int>(entries_.size()); ++i) {
912 // Append entry metadata (e.g., 3_7x):
913 // 3: page_id
914 // 7: SiteInstance ID, or N for null
915 // x: appended if not from the current SiteInstance
916 temp.append(base::IntToString(entries_[i]->GetPageID()));
917 temp.append("_");
918 if (entries_[i]->site_instance())
919 temp.append(base::IntToString(entries_[i]->site_instance()->GetId()));
920 else
921 temp.append("N");
922 if (entries_[i]->site_instance() != delegate_->GetSiteInstance())
923 temp.append("x");
924 temp.append(",");
925 }
926 GURL url(temp);
927 static_cast<RenderViewHostImpl*>(
928 delegate_->GetRenderViewHost())->Send(
929 new ViewMsg_TempCrashWithData(url));
930 return NAVIGATION_TYPE_NAV_IGNORE;
931 }
932 NavigationEntryImpl* existing_entry = entries_[existing_entry_index].get();
933
934 if (!PageTransitionIsMainFrame(params.transition)) {
935 // All manual subframes would get new IDs and were handled above, so we
936 // know this is auto. Since the current page was found in the navigation
937 // entry list, we're guaranteed to have a last committed entry.
938 DCHECK(GetLastCommittedEntry());
939 return NAVIGATION_TYPE_AUTO_SUBFRAME;
940 }
941
942 // Anything below here we know is a main frame navigation.
943 if (pending_entry_ &&
944 !pending_entry_->is_renderer_initiated() &&
945 existing_entry != pending_entry_ &&
946 pending_entry_->GetPageID() == -1 &&
947 existing_entry == GetLastCommittedEntry()) {
948 // In this case, we have a pending entry for a URL but WebCore didn't do a
949 // new navigation. This happens when you press enter in the URL bar to
950 // reload. We will create a pending entry, but WebKit will convert it to
951 // a reload since it's the same page and not create a new entry for it
952 // (the user doesn't want to have a new back/forward entry when they do
953 // this). If this matches the last committed entry, we want to just ignore
954 // the pending entry and go back to where we were (the "existing entry").
955 return NAVIGATION_TYPE_SAME_PAGE;
956 }
957
958 // Any toplevel navigations with the same base (minus the reference fragment)
959 // are in-page navigations. We weeded out subframe navigations above. Most of
960 // the time this doesn't matter since WebKit doesn't tell us about subframe
961 // navigations that don't actually navigate, but it can happen when there is
962 // an encoding override (it always sends a navigation request).
963 if (AreURLsInPageNavigation(existing_entry->GetURL(), params.url,
964 params.was_within_same_page,
965 NAVIGATION_TYPE_UNKNOWN)) {
966 return NAVIGATION_TYPE_IN_PAGE;
967 }
968
969 // Since we weeded out "new" navigations above, we know this is an existing
970 // (back/forward) navigation.
971 return NAVIGATION_TYPE_EXISTING_PAGE;
972 }
973
974 bool NavigationControllerImpl::IsRedirect(
975 const ViewHostMsg_FrameNavigate_Params& params) {
976 // For main frame transition, we judge by params.transition.
977 // Otherwise, by params.redirects.
978 if (PageTransitionIsMainFrame(params.transition)) {
979 return PageTransitionIsRedirect(params.transition);
980 }
981 return params.redirects.size() > 1;
982 }
983
984 void NavigationControllerImpl::RendererDidNavigateToNewPage(
985 const ViewHostMsg_FrameNavigate_Params& params, bool replace_entry) {
986 NavigationEntryImpl* new_entry;
987 bool update_virtual_url;
988 // Only make a copy of the pending entry if it is appropriate for the new page
989 // that was just loaded. We verify this at a coarse grain by checking that
990 // the SiteInstance hasn't been assigned to something else.
991 if (pending_entry_ &&
992 (!pending_entry_->site_instance() ||
993 pending_entry_->site_instance() == delegate_->GetSiteInstance())) {
994 new_entry = new NavigationEntryImpl(*pending_entry_);
995
996 // Don't use the page type from the pending entry. Some interstitial page
997 // may have set the type to interstitial. Once we commit, however, the page
998 // type must always be normal.
999 new_entry->set_page_type(PAGE_TYPE_NORMAL);
1000 update_virtual_url = new_entry->update_virtual_url_with_url();
1001 } else {
1002 new_entry = new NavigationEntryImpl;
1003
1004 // Find out whether the new entry needs to update its virtual URL on URL
1005 // change and set up the entry accordingly. This is needed to correctly
1006 // update the virtual URL when replaceState is called after a pushState.
1007 GURL url = params.url;
1008 bool needs_update = false;
1009 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
1010 &url, browser_context_, &needs_update);
1011 new_entry->set_update_virtual_url_with_url(needs_update);
1012
1013 // When navigating to a new page, give the browser URL handler a chance to
1014 // update the virtual URL based on the new URL. For example, this is needed
1015 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
1016 // the URL.
1017 update_virtual_url = needs_update;
1018 }
1019
1020 new_entry->SetURL(params.url);
1021 if (update_virtual_url)
1022 UpdateVirtualURLToURL(new_entry, params.url);
1023 new_entry->SetReferrer(params.referrer);
1024 new_entry->SetPageID(params.page_id);
1025 new_entry->SetTransitionType(params.transition);
1026 new_entry->set_site_instance(
1027 static_cast<SiteInstanceImpl*>(delegate_->GetSiteInstance()));
1028 new_entry->SetHasPostData(params.is_post);
1029 new_entry->SetPostID(params.post_id);
1030 new_entry->SetOriginalRequestURL(params.original_request_url);
1031 new_entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1032
1033 DCHECK(!params.history_list_was_cleared || !replace_entry);
1034 // The browser requested to clear the session history when it initiated the
1035 // navigation. Now we know that the renderer has updated its state accordingly
1036 // and it is safe to also clear the browser side history.
1037 if (params.history_list_was_cleared) {
1038 DiscardNonCommittedEntriesInternal();
1039 entries_.clear();
1040 last_committed_entry_index_ = -1;
1041 }
1042
1043 InsertOrReplaceEntry(new_entry, replace_entry);
1044 }
1045
1046 void NavigationControllerImpl::RendererDidNavigateToExistingPage(
1047 const ViewHostMsg_FrameNavigate_Params& params) {
1048 // We should only get here for main frame navigations.
1049 DCHECK(PageTransitionIsMainFrame(params.transition));
1050
1051 // This is a back/forward navigation. The existing page for the ID is
1052 // guaranteed to exist by ClassifyNavigation, and we just need to update it
1053 // with new information from the renderer.
1054 int entry_index = GetEntryIndexWithPageID(delegate_->GetSiteInstance(),
1055 params.page_id);
1056 DCHECK(entry_index >= 0 &&
1057 entry_index < static_cast<int>(entries_.size()));
1058 NavigationEntryImpl* entry = entries_[entry_index].get();
1059
1060 // The URL may have changed due to redirects.
1061 entry->SetURL(params.url);
1062 if (entry->update_virtual_url_with_url())
1063 UpdateVirtualURLToURL(entry, params.url);
1064
1065 // The redirected to page should not inherit the favicon from the previous
1066 // page.
1067 if (PageTransitionIsRedirect(params.transition))
1068 entry->GetFavicon() = FaviconStatus();
1069
1070 // The site instance will normally be the same except during session restore,
1071 // when no site instance will be assigned.
1072 DCHECK(entry->site_instance() == NULL ||
1073 entry->site_instance() == delegate_->GetSiteInstance());
1074 entry->set_site_instance(
1075 static_cast<SiteInstanceImpl*>(delegate_->GetSiteInstance()));
1076
1077 entry->SetHasPostData(params.is_post);
1078 entry->SetPostID(params.post_id);
1079
1080 // The entry we found in the list might be pending if the user hit
1081 // back/forward/reload. This load should commit it (since it's already in the
1082 // list, we can just discard the pending pointer). We should also discard the
1083 // pending entry if it corresponds to a different navigation, since that one
1084 // is now likely canceled. If it is not canceled, we will treat it as a new
1085 // navigation when it arrives, which is also ok.
1086 //
1087 // Note that we need to use the "internal" version since we don't want to
1088 // actually change any other state, just kill the pointer.
1089 DiscardNonCommittedEntriesInternal();
1090
1091 // If a transient entry was removed, the indices might have changed, so we
1092 // have to query the entry index again.
1093 last_committed_entry_index_ =
1094 GetEntryIndexWithPageID(delegate_->GetSiteInstance(), params.page_id);
1095 }
1096
1097 void NavigationControllerImpl::RendererDidNavigateToSamePage(
1098 const ViewHostMsg_FrameNavigate_Params& params) {
1099 // This mode implies we have a pending entry that's the same as an existing
1100 // entry for this page ID. This entry is guaranteed to exist by
1101 // ClassifyNavigation. All we need to do is update the existing entry.
1102 NavigationEntryImpl* existing_entry = GetEntryWithPageID(
1103 delegate_->GetSiteInstance(), params.page_id);
1104
1105 // We assign the entry's unique ID to be that of the new one. Since this is
1106 // always the result of a user action, we want to dismiss infobars, etc. like
1107 // a regular user-initiated navigation.
1108 existing_entry->set_unique_id(pending_entry_->GetUniqueID());
1109
1110 // The URL may have changed due to redirects.
1111 if (existing_entry->update_virtual_url_with_url())
1112 UpdateVirtualURLToURL(existing_entry, params.url);
1113 existing_entry->SetURL(params.url);
1114
1115 DiscardNonCommittedEntries();
1116 }
1117
1118 void NavigationControllerImpl::RendererDidNavigateInPage(
1119 const ViewHostMsg_FrameNavigate_Params& params, bool* did_replace_entry) {
1120 DCHECK(PageTransitionIsMainFrame(params.transition)) <<
1121 "WebKit should only tell us about in-page navs for the main frame.";
1122 // We're guaranteed to have an entry for this one.
1123 NavigationEntryImpl* existing_entry = GetEntryWithPageID(
1124 delegate_->GetSiteInstance(), params.page_id);
1125
1126 // Reference fragment navigation. We're guaranteed to have the last_committed
1127 // entry and it will be the same page as the new navigation (minus the
1128 // reference fragments, of course). We'll update the URL of the existing
1129 // entry without pruning the forward history.
1130 existing_entry->SetURL(params.url);
1131 if (existing_entry->update_virtual_url_with_url())
1132 UpdateVirtualURLToURL(existing_entry, params.url);
1133
1134 // This replaces the existing entry since the page ID didn't change.
1135 *did_replace_entry = true;
1136
1137 DiscardNonCommittedEntriesInternal();
1138
1139 // If a transient entry was removed, the indices might have changed, so we
1140 // have to query the entry index again.
1141 last_committed_entry_index_ =
1142 GetEntryIndexWithPageID(delegate_->GetSiteInstance(), params.page_id);
1143 }
1144
1145 void NavigationControllerImpl::RendererDidNavigateNewSubframe(
1146 const ViewHostMsg_FrameNavigate_Params& params) {
1147 if (PageTransitionCoreTypeIs(params.transition,
1148 PAGE_TRANSITION_AUTO_SUBFRAME)) {
1149 // This is not user-initiated. Ignore.
1150 DiscardNonCommittedEntriesInternal();
1151 return;
1152 }
1153
1154 // Manual subframe navigations just get the current entry cloned so the user
1155 // can go back or forward to it. The actual subframe information will be
1156 // stored in the page state for each of those entries. This happens out of
1157 // band with the actual navigations.
1158 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
1159 << "that a last committed entry exists.";
1160 NavigationEntryImpl* new_entry = new NavigationEntryImpl(
1161 *NavigationEntryImpl::FromNavigationEntry(GetLastCommittedEntry()));
1162 new_entry->SetPageID(params.page_id);
1163 InsertOrReplaceEntry(new_entry, false);
1164 }
1165
1166 bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
1167 const ViewHostMsg_FrameNavigate_Params& params) {
1168 // We're guaranteed to have a previously committed entry, and we now need to
1169 // handle navigation inside of a subframe in it without creating a new entry.
1170 DCHECK(GetLastCommittedEntry());
1171
1172 // Handle the case where we're navigating back/forward to a previous subframe
1173 // navigation entry. This is case "2." in NAV_AUTO_SUBFRAME comment in the
1174 // header file. In case "1." this will be a NOP.
1175 int entry_index = GetEntryIndexWithPageID(
1176 delegate_->GetSiteInstance(),
1177 params.page_id);
1178 if (entry_index < 0 ||
1179 entry_index >= static_cast<int>(entries_.size())) {
1180 NOTREACHED();
1181 return false;
1182 }
1183
1184 // Update the current navigation entry in case we're going back/forward.
1185 if (entry_index != last_committed_entry_index_) {
1186 last_committed_entry_index_ = entry_index;
1187 DiscardNonCommittedEntriesInternal();
1188 return true;
1189 }
1190
1191 // We do not need to discard the pending entry in this case, since we will
1192 // not generate commit notifications for this auto-subframe navigation.
1193 return false;
1194 }
1195
1196 int NavigationControllerImpl::GetIndexOfEntry(
1197 const NavigationEntryImpl* entry) const {
1198 const NavigationEntries::const_iterator i(std::find(
1199 entries_.begin(),
1200 entries_.end(),
1201 entry));
1202 return (i == entries_.end()) ? -1 : static_cast<int>(i - entries_.begin());
1203 }
1204
1205 bool NavigationControllerImpl::IsURLInPageNavigation(
1206 const GURL& url,
1207 bool renderer_says_in_page,
1208 NavigationType navigation_type) const {
1209 NavigationEntry* last_committed = GetLastCommittedEntry();
1210 return last_committed && AreURLsInPageNavigation(
1211 last_committed->GetURL(), url, renderer_says_in_page, navigation_type);
1212 }
1213
1214 void NavigationControllerImpl::CopyStateFrom(
1215 const NavigationController& temp) {
1216 const NavigationControllerImpl& source =
1217 static_cast<const NavigationControllerImpl&>(temp);
1218 // Verify that we look new.
1219 DCHECK(GetEntryCount() == 0 && !GetPendingEntry());
1220
1221 if (source.GetEntryCount() == 0)
1222 return; // Nothing new to do.
1223
1224 needs_reload_ = true;
1225 InsertEntriesFrom(source, source.GetEntryCount());
1226
1227 for (SessionStorageNamespaceMap::const_iterator it =
1228 source.session_storage_namespace_map_.begin();
1229 it != source.session_storage_namespace_map_.end();
1230 ++it) {
1231 SessionStorageNamespaceImpl* source_namespace =
1232 static_cast<SessionStorageNamespaceImpl*>(it->second.get());
1233 session_storage_namespace_map_[it->first] = source_namespace->Clone();
1234 }
1235
1236 FinishRestore(source.last_committed_entry_index_, RESTORE_CURRENT_SESSION);
1237
1238 // Copy the max page id map from the old tab to the new tab. This ensures
1239 // that new and existing navigations in the tab's current SiteInstances
1240 // are identified properly.
1241 delegate_->CopyMaxPageIDsFrom(source.delegate()->GetWebContents());
1242 }
1243
1244 void NavigationControllerImpl::CopyStateFromAndPrune(
1245 NavigationController* temp) {
1246 // It is up to callers to check the invariants before calling this.
1247 CHECK(CanPruneAllButVisible());
1248
1249 NavigationControllerImpl* source =
1250 static_cast<NavigationControllerImpl*>(temp);
1251 // The SiteInstance and page_id of the last committed entry needs to be
1252 // remembered at this point, in case there is only one committed entry
1253 // and it is pruned. We use a scoped_refptr to ensure the SiteInstance
1254 // can't be freed during this time period.
1255 NavigationEntryImpl* last_committed =
1256 NavigationEntryImpl::FromNavigationEntry(GetLastCommittedEntry());
1257 scoped_refptr<SiteInstance> site_instance(
1258 last_committed->site_instance());
1259 int32 minimum_page_id = last_committed->GetPageID();
1260 int32 max_page_id =
1261 delegate_->GetMaxPageIDForSiteInstance(site_instance.get());
1262
1263 // Remove all the entries leaving the active entry.
1264 PruneAllButVisibleInternal();
1265
1266 // We now have one entry, possibly with a new pending entry. Ensure that
1267 // adding the entries from source won't put us over the limit.
1268 DCHECK_EQ(1, GetEntryCount());
1269 source->PruneOldestEntryIfFull();
1270
1271 // Insert the entries from source. Don't use source->GetCurrentEntryIndex as
1272 // we don't want to copy over the transient entry. Ignore any pending entry,
1273 // since it has not committed in source.
1274 int max_source_index = source->last_committed_entry_index_;
1275 if (max_source_index == -1)
1276 max_source_index = source->GetEntryCount();
1277 else
1278 max_source_index++;
1279 InsertEntriesFrom(*source, max_source_index);
1280
1281 // Adjust indices such that the last entry and pending are at the end now.
1282 last_committed_entry_index_ = GetEntryCount() - 1;
1283
1284 delegate_->SetHistoryLengthAndPrune(site_instance.get(),
1285 max_source_index,
1286 minimum_page_id);
1287
1288 // Copy the max page id map from the old tab to the new tab. This ensures
1289 // that new and existing navigations in the tab's current SiteInstances
1290 // are identified properly.
1291 delegate_->CopyMaxPageIDsFrom(source->delegate()->GetWebContents());
1292
1293 // If there is a last committed entry, be sure to include it in the new
1294 // max page ID map.
1295 if (max_page_id > -1) {
1296 delegate_->UpdateMaxPageIDForSiteInstance(site_instance.get(),
1297 max_page_id);
1298 }
1299 }
1300
1301 bool NavigationControllerImpl::CanPruneAllButVisible() {
1302 // If there is no last committed entry, we cannot prune. Even if there is a
1303 // pending entry, it may not commit, leaving this WebContents blank, despite
1304 // possibly giving it new entries via CopyStateFromAndPrune.
1305 if (last_committed_entry_index_ == -1)
1306 return false;
1307
1308 // We cannot prune if there is a pending entry at an existing entry index.
1309 // It may not commit, so we have to keep the last committed entry, and thus
1310 // there is no sensible place to keep the pending entry. It is ok to have
1311 // a new pending entry, which can optionally commit as a new navigation.
1312 if (pending_entry_index_ != -1)
1313 return false;
1314
1315 // We should not prune if we are currently showing a transient entry.
1316 if (transient_entry_index_ != -1)
1317 return false;
1318
1319 return true;
1320 }
1321
1322 void NavigationControllerImpl::PruneAllButVisible() {
1323 PruneAllButVisibleInternal();
1324
1325 // We should still have a last committed entry.
1326 DCHECK_NE(-1, last_committed_entry_index_);
1327
1328 // We pass 0 instead of GetEntryCount() for the history_length parameter of
1329 // SetHistoryLengthAndPrune, because it will create history_length additional
1330 // history entries.
1331 // TODO(jochen): This API is confusing and we should clean it up.
1332 // http://crbug.com/178491
1333 NavigationEntryImpl* entry =
1334 NavigationEntryImpl::FromNavigationEntry(GetVisibleEntry());
1335 delegate_->SetHistoryLengthAndPrune(
1336 entry->site_instance(), 0, entry->GetPageID());
1337 }
1338
1339 void NavigationControllerImpl::PruneAllButVisibleInternal() {
1340 // It is up to callers to check the invariants before calling this.
1341 CHECK(CanPruneAllButVisible());
1342
1343 // Erase all entries but the last committed entry. There may still be a
1344 // new pending entry after this.
1345 entries_.erase(entries_.begin(),
1346 entries_.begin() + last_committed_entry_index_);
1347 entries_.erase(entries_.begin() + 1, entries_.end());
1348 last_committed_entry_index_ = 0;
1349 }
1350
1351 void NavigationControllerImpl::ClearAllScreenshots() {
1352 screenshot_manager_->ClearAllScreenshots();
1353 }
1354
1355 void NavigationControllerImpl::SetSessionStorageNamespace(
1356 const std::string& partition_id,
1357 SessionStorageNamespace* session_storage_namespace) {
1358 if (!session_storage_namespace)
1359 return;
1360
1361 // We can't overwrite an existing SessionStorage without violating spec.
1362 // Attempts to do so may give a tab access to another tab's session storage
1363 // so die hard on an error.
1364 bool successful_insert = session_storage_namespace_map_.insert(
1365 make_pair(partition_id,
1366 static_cast<SessionStorageNamespaceImpl*>(
1367 session_storage_namespace)))
1368 .second;
1369 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
1370 }
1371
1372 void NavigationControllerImpl::SetMaxRestoredPageID(int32 max_id) {
1373 max_restored_page_id_ = max_id;
1374 }
1375
1376 int32 NavigationControllerImpl::GetMaxRestoredPageID() const {
1377 return max_restored_page_id_;
1378 }
1379
1380 SessionStorageNamespace*
1381 NavigationControllerImpl::GetSessionStorageNamespace(SiteInstance* instance) {
1382 std::string partition_id;
1383 if (instance) {
1384 // TODO(ajwong): When GetDefaultSessionStorageNamespace() goes away, remove
1385 // this if statement so |instance| must not be NULL.
1386 partition_id =
1387 GetContentClient()->browser()->GetStoragePartitionIdForSite(
1388 browser_context_, instance->GetSiteURL());
1389 }
1390
1391 SessionStorageNamespaceMap::const_iterator it =
1392 session_storage_namespace_map_.find(partition_id);
1393 if (it != session_storage_namespace_map_.end())
1394 return it->second.get();
1395
1396 // Create one if no one has accessed session storage for this partition yet.
1397 //
1398 // TODO(ajwong): Should this use the |partition_id| directly rather than
1399 // re-lookup via |instance|? http://crbug.com/142685
1400 StoragePartition* partition =
1401 BrowserContext::GetStoragePartition(browser_context_, instance);
1402 SessionStorageNamespaceImpl* session_storage_namespace =
1403 new SessionStorageNamespaceImpl(
1404 static_cast<DOMStorageContextWrapper*>(
1405 partition->GetDOMStorageContext()));
1406 session_storage_namespace_map_[partition_id] = session_storage_namespace;
1407
1408 return session_storage_namespace;
1409 }
1410
1411 SessionStorageNamespace*
1412 NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
1413 // TODO(ajwong): Remove if statement in GetSessionStorageNamespace().
1414 return GetSessionStorageNamespace(NULL);
1415 }
1416
1417 const SessionStorageNamespaceMap&
1418 NavigationControllerImpl::GetSessionStorageNamespaceMap() const {
1419 return session_storage_namespace_map_;
1420 }
1421
1422 bool NavigationControllerImpl::NeedsReload() const {
1423 return needs_reload_;
1424 }
1425
1426 void NavigationControllerImpl::SetNeedsReload() {
1427 needs_reload_ = true;
1428 }
1429
1430 void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
1431 DCHECK(index < GetEntryCount());
1432 DCHECK(index != last_committed_entry_index_);
1433
1434 DiscardNonCommittedEntries();
1435
1436 entries_.erase(entries_.begin() + index);
1437 if (last_committed_entry_index_ > index)
1438 last_committed_entry_index_--;
1439 }
1440
1441 void NavigationControllerImpl::DiscardNonCommittedEntries() {
1442 bool transient = transient_entry_index_ != -1;
1443 DiscardNonCommittedEntriesInternal();
1444
1445 // If there was a transient entry, invalidate everything so the new active
1446 // entry state is shown.
1447 if (transient) {
1448 delegate_->NotifyNavigationStateChanged(kInvalidateAll);
1449 }
1450 }
1451
1452 NavigationEntry* NavigationControllerImpl::GetPendingEntry() const {
1453 return pending_entry_;
1454 }
1455
1456 int NavigationControllerImpl::GetPendingEntryIndex() const {
1457 return pending_entry_index_;
1458 }
1459
1460 void NavigationControllerImpl::InsertOrReplaceEntry(NavigationEntryImpl* entry,
1461 bool replace) {
1462 DCHECK(entry->GetTransitionType() != PAGE_TRANSITION_AUTO_SUBFRAME);
1463
1464 // Copy the pending entry's unique ID to the committed entry.
1465 // I don't know if pending_entry_index_ can be other than -1 here.
1466 const NavigationEntryImpl* const pending_entry =
1467 (pending_entry_index_ == -1) ?
1468 pending_entry_ : entries_[pending_entry_index_].get();
1469 if (pending_entry)
1470 entry->set_unique_id(pending_entry->GetUniqueID());
1471
1472 DiscardNonCommittedEntriesInternal();
1473
1474 int current_size = static_cast<int>(entries_.size());
1475
1476 if (current_size > 0) {
1477 // Prune any entries which are in front of the current entry.
1478 // Also prune the current entry if we are to replace the current entry.
1479 // last_committed_entry_index_ must be updated here since calls to
1480 // NotifyPrunedEntries() below may re-enter and we must make sure
1481 // last_committed_entry_index_ is not left in an invalid state.
1482 if (replace)
1483 --last_committed_entry_index_;
1484
1485 int num_pruned = 0;
1486 while (last_committed_entry_index_ < (current_size - 1)) {
1487 num_pruned++;
1488 entries_.pop_back();
1489 current_size--;
1490 }
1491 if (num_pruned > 0) // Only notify if we did prune something.
1492 NotifyPrunedEntries(this, false, num_pruned);
1493 }
1494
1495 PruneOldestEntryIfFull();
1496
1497 entries_.push_back(linked_ptr<NavigationEntryImpl>(entry));
1498 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
1499
1500 // This is a new page ID, so we need everybody to know about it.
1501 delegate_->UpdateMaxPageID(entry->GetPageID());
1502 }
1503
1504 void NavigationControllerImpl::PruneOldestEntryIfFull() {
1505 if (entries_.size() >= max_entry_count()) {
1506 DCHECK_EQ(max_entry_count(), entries_.size());
1507 DCHECK_GT(last_committed_entry_index_, 0);
1508 RemoveEntryAtIndex(0);
1509 NotifyPrunedEntries(this, true, 1);
1510 }
1511 }
1512
1513 void NavigationControllerImpl::NavigateToPendingEntry(ReloadType reload_type) {
1514 needs_reload_ = false;
1515
1516 // If we were navigating to a slow-to-commit page, and the user performs
1517 // a session history navigation to the last committed page, RenderViewHost
1518 // will force the throbber to start, but WebKit will essentially ignore the
1519 // navigation, and won't send a message to stop the throbber. To prevent this
1520 // from happening, we drop the navigation here and stop the slow-to-commit
1521 // page from loading (which would normally happen during the navigation).
1522 if (pending_entry_index_ != -1 &&
1523 pending_entry_index_ == last_committed_entry_index_ &&
1524 (entries_[pending_entry_index_]->restore_type() ==
1525 NavigationEntryImpl::RESTORE_NONE) &&
1526 (entries_[pending_entry_index_]->GetTransitionType() &
1527 PAGE_TRANSITION_FORWARD_BACK)) {
1528 delegate_->Stop();
1529
1530 // If an interstitial page is showing, we want to close it to get back
1531 // to what was showing before.
1532 if (delegate_->GetInterstitialPage())
1533 delegate_->GetInterstitialPage()->DontProceed();
1534
1535 DiscardNonCommittedEntries();
1536 return;
1537 }
1538
1539 // If an interstitial page is showing, the previous renderer is blocked and
1540 // cannot make new requests. Unblock (and disable) it to allow this
1541 // navigation to succeed. The interstitial will stay visible until the
1542 // resulting DidNavigate.
1543 if (delegate_->GetInterstitialPage()) {
1544 static_cast<InterstitialPageImpl*>(delegate_->GetInterstitialPage())->
1545 CancelForNavigation();
1546 }
1547
1548 // For session history navigations only the pending_entry_index_ is set.
1549 if (!pending_entry_) {
1550 DCHECK_NE(pending_entry_index_, -1);
1551 pending_entry_ = entries_[pending_entry_index_].get();
1552 }
1553
1554 if (!delegate_->NavigateToPendingEntry(reload_type))
1555 DiscardNonCommittedEntries();
1556
1557 // If the entry is being restored and doesn't have a SiteInstance yet, fill
1558 // it in now that we know. This allows us to find the entry when it commits.
1559 // This works for browser-initiated navigations. We handle renderer-initiated
1560 // navigations to restored entries in WebContentsImpl::OnGoToEntryAtOffset.
1561 if (pending_entry_ && !pending_entry_->site_instance() &&
1562 pending_entry_->restore_type() != NavigationEntryImpl::RESTORE_NONE) {
1563 pending_entry_->set_site_instance(static_cast<SiteInstanceImpl*>(
1564 delegate_->GetPendingSiteInstance()));
1565 pending_entry_->set_restore_type(NavigationEntryImpl::RESTORE_NONE);
1566 }
1567 }
1568
1569 void NavigationControllerImpl::NotifyNavigationEntryCommitted(
1570 LoadCommittedDetails* details) {
1571 details->entry = GetLastCommittedEntry();
1572
1573 // We need to notify the ssl_manager_ before the web_contents_ so the
1574 // location bar will have up-to-date information about the security style
1575 // when it wants to draw. See http://crbug.com/11157
1576 ssl_manager_.DidCommitProvisionalLoad(*details);
1577
1578 delegate_->NotifyNavigationStateChanged(kInvalidateAll);
1579 delegate_->NotifyNavigationEntryCommitted(*details);
1580
1581 // TODO(avi): Remove. http://crbug.com/170921
1582 NotificationDetails notification_details =
1583 Details<LoadCommittedDetails>(details);
1584 NotificationService::current()->Notify(
1585 NOTIFICATION_NAV_ENTRY_COMMITTED,
1586 Source<NavigationController>(this),
1587 notification_details);
1588 }
1589
1590 // static
1591 size_t NavigationControllerImpl::max_entry_count() {
1592 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
1593 return max_entry_count_for_testing_;
1594 return kMaxSessionHistoryEntries;
1595 }
1596
1597 void NavigationControllerImpl::SetActive(bool is_active) {
1598 if (is_active && needs_reload_)
1599 LoadIfNecessary();
1600 }
1601
1602 void NavigationControllerImpl::LoadIfNecessary() {
1603 if (!needs_reload_)
1604 return;
1605
1606 // Calling Reload() results in ignoring state, and not loading.
1607 // Explicitly use NavigateToPendingEntry so that the renderer uses the
1608 // cached state.
1609 pending_entry_index_ = last_committed_entry_index_;
1610 NavigateToPendingEntry(NO_RELOAD);
1611 }
1612
1613 void NavigationControllerImpl::NotifyEntryChanged(const NavigationEntry* entry,
1614 int index) {
1615 EntryChangedDetails det;
1616 det.changed_entry = entry;
1617 det.index = index;
1618 NotificationService::current()->Notify(
1619 NOTIFICATION_NAV_ENTRY_CHANGED,
1620 Source<NavigationController>(this),
1621 Details<EntryChangedDetails>(&det));
1622 }
1623
1624 void NavigationControllerImpl::FinishRestore(int selected_index,
1625 RestoreType type) {
1626 DCHECK(selected_index >= 0 && selected_index < GetEntryCount());
1627 ConfigureEntriesForRestore(&entries_, type);
1628
1629 SetMaxRestoredPageID(static_cast<int32>(GetEntryCount()));
1630
1631 last_committed_entry_index_ = selected_index;
1632 }
1633
1634 void NavigationControllerImpl::DiscardNonCommittedEntriesInternal() {
1635 DiscardPendingEntry();
1636 DiscardTransientEntry();
1637 }
1638
1639 void NavigationControllerImpl::DiscardPendingEntry() {
1640 if (pending_entry_index_ == -1)
1641 delete pending_entry_;
1642 pending_entry_ = NULL;
1643 pending_entry_index_ = -1;
1644 }
1645
1646 void NavigationControllerImpl::DiscardTransientEntry() {
1647 if (transient_entry_index_ == -1)
1648 return;
1649 entries_.erase(entries_.begin() + transient_entry_index_);
1650 if (last_committed_entry_index_ > transient_entry_index_)
1651 last_committed_entry_index_--;
1652 transient_entry_index_ = -1;
1653 }
1654
1655 int NavigationControllerImpl::GetEntryIndexWithPageID(
1656 SiteInstance* instance, int32 page_id) const {
1657 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
1658 if ((entries_[i]->site_instance() == instance) &&
1659 (entries_[i]->GetPageID() == page_id))
1660 return i;
1661 }
1662 return -1;
1663 }
1664
1665 NavigationEntry* NavigationControllerImpl::GetTransientEntry() const {
1666 if (transient_entry_index_ == -1)
1667 return NULL;
1668 return entries_[transient_entry_index_].get();
1669 }
1670
1671 void NavigationControllerImpl::SetTransientEntry(NavigationEntry* entry) {
1672 // Discard any current transient entry, we can only have one at a time.
1673 int index = 0;
1674 if (last_committed_entry_index_ != -1)
1675 index = last_committed_entry_index_ + 1;
1676 DiscardTransientEntry();
1677 entries_.insert(
1678 entries_.begin() + index, linked_ptr<NavigationEntryImpl>(
1679 NavigationEntryImpl::FromNavigationEntry(entry)));
1680 transient_entry_index_ = index;
1681 delegate_->NotifyNavigationStateChanged(kInvalidateAll);
1682 }
1683
1684 void NavigationControllerImpl::InsertEntriesFrom(
1685 const NavigationControllerImpl& source,
1686 int max_index) {
1687 DCHECK_LE(max_index, source.GetEntryCount());
1688 size_t insert_index = 0;
1689 for (int i = 0; i < max_index; i++) {
1690 // When cloning a tab, copy all entries except interstitial pages
1691 if (source.entries_[i].get()->GetPageType() !=
1692 PAGE_TYPE_INTERSTITIAL) {
1693 entries_.insert(entries_.begin() + insert_index++,
1694 linked_ptr<NavigationEntryImpl>(
1695 new NavigationEntryImpl(*source.entries_[i])));
1696 }
1697 }
1698 }
1699
1700 void NavigationControllerImpl::SetGetTimestampCallbackForTest(
1701 const base::Callback<base::Time()>& get_timestamp_callback) {
1702 get_timestamp_callback_ = get_timestamp_callback;
1703 }
1704
1705 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698