Update V8 to version 4.6.61.
[chromium-blink-merge.git] / ios / web / navigation / crw_session_controller.mm
blobc1bfb15018252ff8b0157f44380ba37959a4d469
1 // Copyright 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 #import "ios/web/navigation/crw_session_controller.h"
7 #include <algorithm>
8 #include <vector>
10 #include "base/format_macros.h"
11 #include "base/logging.h"
12 #include "base/mac/objc_property_releaser.h"
13 #import "base/mac/scoped_nsobject.h"
14 #include "base/metrics/user_metrics_action.h"
15 #include "base/strings/sys_string_conversions.h"
16 #import "ios/web/history_state_util.h"
17 #import "ios/web/navigation/crw_session_certificate_policy_manager.h"
18 #import "ios/web/navigation/crw_session_controller+private_constructors.h"
19 #import "ios/web/navigation/crw_session_entry.h"
20 #include "ios/web/navigation/navigation_item_impl.h"
21 #import "ios/web/navigation/navigation_manager_facade_delegate.h"
22 #import "ios/web/navigation/navigation_manager_impl.h"
23 #include "ios/web/navigation/time_smoother.h"
24 #include "ios/web/public/browser_state.h"
25 #include "ios/web/public/browser_url_rewriter.h"
26 #include "ios/web/public/referrer.h"
27 #include "ios/web/public/ssl_status.h"
28 #include "ios/web/public/user_metrics.h"
30 using base::UserMetricsAction;
32 namespace {
33 NSString* const kCertificatePolicyManagerKey = @"certificatePolicyManager";
34 NSString* const kCurrentNavigationIndexKey = @"currentNavigationIndex";
35 NSString* const kEntriesKey = @"entries";
36 NSString* const kLastVisitedTimestampKey = @"lastVisitedTimestamp";
37 NSString* const kOpenerIdKey = @"openerId";
38 NSString* const kOpenedByDOMKey = @"openedByDOM";
39 NSString* const kOpenerNavigationIndexKey = @"openerNavigationIndex";
40 NSString* const kPreviousNavigationIndexKey = @"previousNavigationIndex";
41 NSString* const kTabIdKey = @"tabId";
42 NSString* const kWindowNameKey = @"windowName";
43 NSString* const kXCallbackParametersKey = @"xCallbackParameters";
44 }  // anonymous namespace
46 @interface CRWSessionController () {
47   // Weak pointer back to the owning NavigationManager. This is to facilitate
48   // the incremental merging of the two classes.
49   web::NavigationManagerImpl* _navigationManager;
51   NSString* _tabId;  // Unique id of the tab.
52   NSString* _openerId;  // Id of tab who opened this tab, empty/nil if none.
53   // Navigation index of the tab which opened this tab. Do not rely on the
54   // value of this member variable to indicate whether or not this tab has
55   // an opener, as both 0 and -1 are used as navigationIndex values.
56   NSInteger _openerNavigationIndex;
57   // Identifies the index of the current navigation in the CRWSessionEntry
58   // array.
59   NSInteger _currentNavigationIndex;
60   // Identifies the index of the previous navigation in the CRWSessionEntry
61   // array.
62   NSInteger _previousNavigationIndex;
63   // Ordered array of |CRWSessionEntry| objects, one for each site in session
64   // history. End of the list is the most recent load.
65   NSMutableArray* _entries;
67   // An entry we haven't gotten a response for yet. This will be discarded
68   // when we navigate again. It's used only so we know what the currently
69   // displayed tab is.  It backs the property of the same name and should only
70   // be set through its setter.
71   base::scoped_nsobject<CRWSessionEntry> _pendingEntry;
73   // The transient entry, if any. A transient entry is discarded on any
74   // navigation, and is used for representing interstitials that need to be
75   // represented in the session.  It backs the property of the same name and
76   // should only be set through its setter.
77   base::scoped_nsobject<CRWSessionEntry> _transientEntry;
79   // The window name associated with the session.
80   NSString* _windowName;
82    // Stores the certificate policies decided by the user.
83   CRWSessionCertificatePolicyManager* _sessionCertificatePolicyManager;
85   // The timestamp of the last time this tab is visited, represented in time
86   // interval since 1970.
87   NSTimeInterval _lastVisitedTimestamp;
89   // If |YES|, override |currentEntry.useDesktopUserAgent| and create the
90   // pending entry using the desktop user agent.
91   BOOL _useDesktopUserAgentForNextPendingEntry;
93   // The browser state associated with this CRWSessionController;
94   __weak web::BrowserState* _browserState;
96   // Time smoother for navigation entry timestamps; see comment in
97   // navigation_controller_impl.h
98   web::TimeSmoother _timeSmoother;
100   // XCallback parameters used to create (or clobber) the tab. Can be nil.
101   XCallbackParameters* _xCallbackParameters;
103   base::mac::ObjCPropertyReleaser _propertyReleaser_CRWSessionController;
106 // Redefine as readwrite.
107 @property(nonatomic, readwrite, assign) NSInteger currentNavigationIndex;
109 // TODO(rohitrao): These properties must be redefined readwrite to work around a
110 // clang bug. crbug.com/228650
111 @property(nonatomic, readwrite, retain) NSString* tabId;
112 @property(nonatomic, readwrite, retain) NSArray* entries;
113 @property(nonatomic, readwrite, retain)
114     CRWSessionCertificatePolicyManager* sessionCertificatePolicyManager;
116 - (NSString*)uniqueID;
117 // Removes all entries after currentNavigationIndex_.
118 - (void)clearForwardEntries;
119 // Discards the transient entry, if any.
120 - (void)discardTransientEntry;
121 // Create a new autoreleased session entry.
122 - (CRWSessionEntry*)sessionEntryWithURL:(const GURL&)url
123                                referrer:(const web::Referrer&)referrer
124                              transition:(ui::PageTransition)transition
125                     useDesktopUserAgent:(BOOL)useDesktopUserAgent
126                       rendererInitiated:(BOOL)rendererInitiated;
127 // Return the PageTransition for the underlying navigationItem at |index| in
128 // |entries_|
129 - (ui::PageTransition)transitionForIndex:(NSUInteger)index;
130 @end
132 @implementation CRWSessionController
134 @synthesize tabId = _tabId;
135 @synthesize currentNavigationIndex = _currentNavigationIndex;
136 @synthesize previousNavigationIndex = _previousNavigationIndex;
137 @synthesize entries = _entries;
138 @synthesize windowName = _windowName;
139 @synthesize lastVisitedTimestamp = _lastVisitedTimestamp;
140 @synthesize openerId = _openerId;
141 @synthesize openedByDOM = _openedByDOM;
142 @synthesize openerNavigationIndex = _openerNavigationIndex;
143 @synthesize sessionCertificatePolicyManager = _sessionCertificatePolicyManager;
144 @synthesize xCallbackParameters = _xCallbackParameters;
146 - (id)initWithWindowName:(NSString*)windowName
147                 openerId:(NSString*)openerId
148              openedByDOM:(BOOL)openedByDOM
149    openerNavigationIndex:(NSInteger)openerIndex
150             browserState:(web::BrowserState*)browserState {
151   self = [super init];
152   if (self) {
153     _propertyReleaser_CRWSessionController.Init(self,
154                                                 [CRWSessionController class]);
155     self.windowName = windowName;
156     _tabId = [[self uniqueID] retain];
157     _openerId = [openerId copy];
158     _openedByDOM = openedByDOM;
159     _openerNavigationIndex = openerIndex;
160     _browserState = browserState;
161     _entries = [[NSMutableArray array] retain];
162     _lastVisitedTimestamp = [[NSDate date] timeIntervalSince1970];
163     _currentNavigationIndex = -1;
164     _previousNavigationIndex = -1;
165     _sessionCertificatePolicyManager =
166         [[CRWSessionCertificatePolicyManager alloc] init];
167   }
168   return self;
171 - (id)initWithNavigationItems:(ScopedVector<web::NavigationItem>)scoped_items
172                  currentIndex:(NSUInteger)currentIndex
173                  browserState:(web::BrowserState*)browserState {
174   self = [super init];
175   if (self) {
176     _propertyReleaser_CRWSessionController.Init(self,
177                                                 [CRWSessionController class]);
178     _tabId = [[self uniqueID] retain];
179     _openerId = nil;
180     _browserState = browserState;
182     // Create entries array from list of navigations.
183     _entries = [[NSMutableArray alloc] initWithCapacity:scoped_items.size()];
184     std::vector<web::NavigationItem*> items;
185     scoped_items.release(&items);
187     for (size_t i = 0; i < items.size(); ++i) {
188       scoped_ptr<web::NavigationItem> item(items[i]);
189       base::scoped_nsobject<CRWSessionEntry> entry(
190           [[CRWSessionEntry alloc] initWithNavigationItem:item.Pass()]);
191       [_entries addObject:entry];
192     }
193     self.currentNavigationIndex = currentIndex;
194     // Prior to M34, 0 was used as "no index" instead of -1; adjust for that.
195     if (![_entries count])
196       self.currentNavigationIndex = -1;
197     if (_currentNavigationIndex >= static_cast<NSInteger>(items.size())) {
198       self.currentNavigationIndex = static_cast<NSInteger>(items.size()) - 1;
199     }
200     _previousNavigationIndex = -1;
201     _lastVisitedTimestamp = [[NSDate date] timeIntervalSince1970];
202     _sessionCertificatePolicyManager =
203         [[CRWSessionCertificatePolicyManager alloc] init];
204   }
205   return self;
208 - (id)initWithCoder:(NSCoder*)aDecoder {
209   self = [super init];
210   if (self) {
211     _propertyReleaser_CRWSessionController.Init(self,
212                                                 [CRWSessionController class]);
213     NSString* uuid = [aDecoder decodeObjectForKey:kTabIdKey];
214     if (!uuid)
215       uuid = [self uniqueID];
217     self.windowName = [aDecoder decodeObjectForKey:kWindowNameKey];
218     _tabId = [uuid retain];
219     _openerId = [[aDecoder decodeObjectForKey:kOpenerIdKey] copy];
220     _openedByDOM = [aDecoder decodeBoolForKey:kOpenedByDOMKey];
221     _openerNavigationIndex =
222         [aDecoder decodeIntForKey:kOpenerNavigationIndexKey];
223     _currentNavigationIndex =
224         [aDecoder decodeIntForKey:kCurrentNavigationIndexKey];
225     _previousNavigationIndex =
226         [aDecoder decodeIntForKey:kPreviousNavigationIndexKey];
227     _lastVisitedTimestamp =
228        [aDecoder decodeDoubleForKey:kLastVisitedTimestampKey];
229     NSMutableArray* temp =
230         [NSMutableArray arrayWithArray:
231             [aDecoder decodeObjectForKey:kEntriesKey]];
232     _entries = [temp retain];
233     // Prior to M34, 0 was used as "no index" instead of -1; adjust for that.
234     if (![_entries count])
235       _currentNavigationIndex = -1;
236     _sessionCertificatePolicyManager =
237        [[aDecoder decodeObjectForKey:kCertificatePolicyManagerKey] retain];
238     if (!_sessionCertificatePolicyManager) {
239       _sessionCertificatePolicyManager =
240           [[CRWSessionCertificatePolicyManager alloc] init];
241     }
243     _xCallbackParameters =
244         [[aDecoder decodeObjectForKey:kXCallbackParametersKey] retain];
245   }
246   return self;
249 - (void)encodeWithCoder:(NSCoder*)aCoder {
250   [aCoder encodeObject:_tabId forKey:kTabIdKey];
251   [aCoder encodeObject:_openerId forKey:kOpenerIdKey];
252   [aCoder encodeBool:_openedByDOM forKey:kOpenedByDOMKey];
253   [aCoder encodeInt:_openerNavigationIndex forKey:kOpenerNavigationIndexKey];
254   [aCoder encodeObject:_windowName forKey:kWindowNameKey];
255   [aCoder encodeInt:_currentNavigationIndex forKey:kCurrentNavigationIndexKey];
256   [aCoder encodeInt:_previousNavigationIndex
257              forKey:kPreviousNavigationIndexKey];
258   [aCoder encodeDouble:_lastVisitedTimestamp forKey:kLastVisitedTimestampKey];
259   [aCoder encodeObject:_entries forKey:kEntriesKey];
260   [aCoder encodeObject:_sessionCertificatePolicyManager
261                 forKey:kCertificatePolicyManagerKey];
262   [aCoder encodeObject:_xCallbackParameters forKey:kXCallbackParametersKey];
263   // rendererInitiated is deliberately not preserved, as upstream.
266 - (id)copyWithZone:(NSZone*)zone {
267   CRWSessionController* copy = [[[self class] alloc] init];
268   copy->_propertyReleaser_CRWSessionController.Init(
269       copy, [CRWSessionController class]);
270   copy->_tabId = [_tabId copy];
271   copy->_openerId = [_openerId copy];
272   copy->_openedByDOM = _openedByDOM;
273   copy->_openerNavigationIndex = _openerNavigationIndex;
274   copy.windowName = self.windowName;
275   copy->_currentNavigationIndex = _currentNavigationIndex;
276   copy->_previousNavigationIndex = _previousNavigationIndex;
277   copy->_lastVisitedTimestamp = _lastVisitedTimestamp;
278   copy->_entries = [_entries copy];
279   copy->_sessionCertificatePolicyManager =
280       [_sessionCertificatePolicyManager copy];
281   copy->_xCallbackParameters = [_xCallbackParameters copy];
282   return copy;
285 - (void)setCurrentNavigationIndex:(NSInteger)currentNavigationIndex {
286   if (_currentNavigationIndex != currentNavigationIndex) {
287     _currentNavigationIndex = currentNavigationIndex;
288     if (_navigationManager)
289       _navigationManager->RemoveTransientURLRewriters();
290   }
293 - (void)setNavigationManager:(web::NavigationManagerImpl*)navigationManager {
294   _navigationManager = navigationManager;
295   if (_navigationManager) {
296     // _browserState will be nullptr if CRWSessionController has been
297     // initialized with -initWithCoder: method. Take _browserState from
298     // NavigationManagerImpl if that's the case.
299     if (!_browserState) {
300       _browserState = _navigationManager->GetBrowserState();
301     }
302     DCHECK_EQ(_browserState, _navigationManager->GetBrowserState());
303   }
306 - (NSString*)description {
307   return [NSString
308       stringWithFormat:
309           @"id: %@\nname: %@\nlast visit: %f\ncurrent index: %" PRIdNS
310           @"\nprevious index: %" PRIdNS "\n%@\npending: %@\nxCallback:\n%@\n",
311           _tabId,
312           self.windowName,
313           _lastVisitedTimestamp,
314           _currentNavigationIndex,
315           _previousNavigationIndex,
316           _entries,
317           _pendingEntry.get(),
318           _xCallbackParameters];
321 // Returns the current entry in the session list, or the pending entry if there
322 // is a navigation in progress.
323 - (CRWSessionEntry*)currentEntry {
324   if (_transientEntry)
325     return _transientEntry.get();
326   if (_pendingEntry)
327     return _pendingEntry.get();
328   return [self lastCommittedEntry];
331 // See NavigationController::GetVisibleEntry for the motivation for this
332 // distinction.
333 - (CRWSessionEntry*)visibleEntry {
334   if (_transientEntry)
335     return _transientEntry.get();
336   // Only return the pending_entry for:
337   //   (a) new (non-history), browser-initiated navigations, and
338   //   (b) pending unsafe navigations (while showing the interstitial)
339   // in order to prevent URL spoof attacks.
340   web::NavigationItemImpl* pendingItem = [_pendingEntry navigationItemImpl];
341   if (pendingItem &&
342       (!pendingItem->is_renderer_initiated() || pendingItem->IsUnsafe())) {
343     return _pendingEntry.get();
344   }
345   return [self lastCommittedEntry];
348 - (CRWSessionEntry*)pendingEntry {
349   return _pendingEntry.get();
352 - (CRWSessionEntry*)transientEntry {
353   return _transientEntry.get();
356 - (CRWSessionEntry*)lastCommittedEntry {
357   if (_currentNavigationIndex == -1)
358     return nil;
359   return [_entries objectAtIndex:_currentNavigationIndex];
362 // Returns the previous entry in the session list, or nil if there isn't any.
363 - (CRWSessionEntry*)previousEntry {
364   if ((_previousNavigationIndex < 0) || (![_entries count]))
365     return nil;
366   return [_entries objectAtIndex:_previousNavigationIndex];
369 - (void)addPendingEntry:(const GURL&)url
370                referrer:(const web::Referrer&)ref
371              transition:(ui::PageTransition)trans
372       rendererInitiated:(BOOL)rendererInitiated {
373   [self discardTransientEntry];
375   // Don't create a new entry if it's already the same as the current entry,
376   // allowing this routine to be called multiple times in a row without issue.
377   // Note: CRWSessionController currently has the responsibility to distinguish
378   // between new navigations and history stack navigation, hence the inclusion
379   // of specific transiton type logic here, in order to make it reliable with
380   // real-world observed behavior.
381   // TODO(stuartmorgan): Fix the way changes are detected/reported elsewhere
382   // in the web layer so that this hack can be removed.
383   // Remove the workaround code from -presentSafeBrowsingWarningForResource:.
384   CRWSessionEntry* currentEntry = self.currentEntry;
385   if (currentEntry) {
386     // If the current entry is known-unsafe (and thus not visible and likely to
387     // be removed), ignore any renderer-initated updates and don't worry about
388     // sending a notification.
389     web::NavigationItem* item = [currentEntry navigationItem];
390     if (item->IsUnsafe() && rendererInitiated) {
391       return;
392     }
393     if (item->GetURL() == url &&
394         (!PageTransitionCoreTypeIs(trans, ui::PAGE_TRANSITION_FORM_SUBMIT) ||
395          PageTransitionCoreTypeIs(item->GetTransitionType(),
396                                   ui::PAGE_TRANSITION_FORM_SUBMIT) ||
397          item->IsUnsafe())) {
398       // Send the notification anyway, to preserve old behavior. It's unknown
399       // whether anything currently relies on this, but since both this whole
400       // hack and the content facade will both be going away, it's not worth
401       // trying to unwind.
402       if (_navigationManager && _navigationManager->GetFacadeDelegate()) {
403         _navigationManager->GetFacadeDelegate()->OnNavigationItemPending();
404       }
405       return;
406     }
407   }
409   BOOL useDesktopUserAgent =
410       _useDesktopUserAgentForNextPendingEntry ||
411       (self.currentEntry.navigationItem &&
412        self.currentEntry.navigationItem->IsOverridingUserAgent());
413   _useDesktopUserAgentForNextPendingEntry = NO;
414   _pendingEntry.reset([[self sessionEntryWithURL:url
415                                         referrer:ref
416                                       transition:trans
417                              useDesktopUserAgent:useDesktopUserAgent
418                                rendererInitiated:rendererInitiated] retain]);
420   if (_navigationManager && _navigationManager->GetFacadeDelegate()) {
421     _navigationManager->GetFacadeDelegate()->OnNavigationItemPending();
422   }
425 - (void)updatePendingEntry:(const GURL&)url {
426   [self discardTransientEntry];
428   // If there is no pending entry, navigation is probably happening within the
429   // session history. Don't modify the entry list.
430   if (!_pendingEntry)
431     return;
433   web::NavigationItemImpl* item = [_pendingEntry navigationItemImpl];
434   if (url != item->GetURL()) {
435     item->SetURL(url);
436     item->SetVirtualURL(url);
437     // Redirects (3xx response code), or client side navigation must change
438     // POST requests to GETs.
439     item->SetPostData(nil);
440     item->ResetHttpRequestHeaders();
441   }
443   // This should probably not be sent if the URLs matched, but that's what was
444   // done before, so preserve behavior in case something relies on it.
445   if (_navigationManager && _navigationManager->GetFacadeDelegate()) {
446     _navigationManager->GetFacadeDelegate()->OnNavigationItemPending();
447   }
450 - (void)clearForwardEntries {
451   [self discardTransientEntry];
453   NSInteger forwardEntryStartIndex = _currentNavigationIndex + 1;
454   DCHECK(forwardEntryStartIndex >= 0);
456   if (forwardEntryStartIndex >= static_cast<NSInteger>([_entries count]))
457     return;
459   NSRange remove = NSMakeRange(forwardEntryStartIndex,
460                                [_entries count] - forwardEntryStartIndex);
461   // Store removed items in temporary NSArray so they can be deallocated after
462   // their facades.
463   base::scoped_nsobject<NSArray> removedItems(
464       [[_entries subarrayWithRange:remove] retain]);
465   [_entries removeObjectsInRange:remove];
466   if (_previousNavigationIndex >= forwardEntryStartIndex)
467     _previousNavigationIndex = -1;
468   if (_navigationManager && _navigationManager->GetFacadeDelegate()) {
469     _navigationManager->GetFacadeDelegate()->OnNavigationItemsPruned(
470         remove.length);
471   }
474 - (void)commitPendingEntry {
475   if (_pendingEntry) {
476     [self clearForwardEntries];
477     // Add the new entry at the end.
478     [_entries addObject:_pendingEntry];
479     _previousNavigationIndex = _currentNavigationIndex;
480     self.currentNavigationIndex = [_entries count] - 1;
481     // Once an entry is committed it's not renderer-initiated any more. (Matches
482     // the implementation in NavigationController.)
483     [_pendingEntry navigationItemImpl]->ResetForCommit();
484     _pendingEntry.reset();
485   }
487   CRWSessionEntry* currentEntry = self.currentEntry;
488   web::NavigationItem* item = currentEntry.navigationItem;
489   // Update the navigation timestamp now that it's actually happened.
490   if (item)
491     item->SetTimestamp(_timeSmoother.GetSmoothedTime(base::Time::Now()));
493   if (_navigationManager && item)
494     _navigationManager->OnNavigationItemCommitted();
497 - (void)addTransientEntry:(const GURL&)url
498                     title:(const base::string16&)title
499                 sslStatus:(const web::SSLStatus*)status {
500   // TODO(stuartmorgan): Don't do this; this is here only to preserve the old
501   // behavior from when transient entries were faked with pending entries, so
502   // any actual pending entry had to be committed. This shouldn't be necessary
503   // now, but things may rely on the old behavior and need to be fixed.
504   [self commitPendingEntry];
506   _transientEntry.reset(
507       [[self sessionEntryWithURL:url
508                         referrer:web::Referrer()
509                       transition:ui::PAGE_TRANSITION_CLIENT_REDIRECT
510              useDesktopUserAgent:NO
511                rendererInitiated:NO] retain]);
513   web::NavigationItem* navigationItem = [_transientEntry navigationItem];
514   DCHECK(navigationItem);
515   if (status)
516     navigationItem->GetSSL() = *status;
517   navigationItem->SetTitle(title);
518   navigationItem->SetTimestamp(
519       _timeSmoother.GetSmoothedTime(base::Time::Now()));
521   // This doesn't match upstream, but matches what we've traditionally done and
522   // will hopefully continue to be good enough for as long as we need the
523   // facade.
524   if (_navigationManager)
525     _navigationManager->OnNavigationItemChanged();
528 - (void)pushNewEntryWithURL:(const GURL&)URL
529                 stateObject:(NSString*)stateObject
530                  transition:(ui::PageTransition)transition {
531   DCHECK([self currentEntry]);
532   web::NavigationItem* item = [self currentEntry].navigationItem;
533   CHECK(
534       web::history_state_util::IsHistoryStateChangeValid(item->GetURL(), URL));
535   web::Referrer referrer(item->GetURL(), web::ReferrerPolicyDefault);
536   bool overrideUserAgent =
537       self.currentEntry.navigationItem->IsOverridingUserAgent();
538   base::scoped_nsobject<CRWSessionEntry> pushedEntry(
539       [[self sessionEntryWithURL:URL
540                         referrer:referrer
541                       transition:transition
542              useDesktopUserAgent:overrideUserAgent
543                rendererInitiated:NO] retain]);
544   web::NavigationItemImpl* pushedItem = [pushedEntry navigationItemImpl];
545   pushedItem->SetSerializedStateObject(stateObject);
546   pushedItem->SetIsCreatedFromPushState(true);
547   web::SSLStatus& sslStatus = [self currentEntry].navigationItem->GetSSL();
548   pushedEntry.get().navigationItem->GetSSL() = sslStatus;
550   [self clearForwardEntries];
551   // Add the new entry at the end.
552   [_entries addObject:pushedEntry];
553   _previousNavigationIndex = _currentNavigationIndex;
554   self.currentNavigationIndex = [_entries count] - 1;
556   if (_navigationManager)
557     _navigationManager->OnNavigationItemCommitted();
560 - (void)updateCurrentEntryWithURL:(const GURL&)url
561                       stateObject:(NSString*)stateObject {
562   DCHECK(!_transientEntry);
563   CRWSessionEntry* currentEntry = self.currentEntry;
564   web::NavigationItemImpl* currentItem = self.currentEntry.navigationItemImpl;
565   currentItem->SetURL(url);
566   currentItem->SetSerializedStateObject(stateObject);
567   currentEntry.navigationItem->SetURL(url);
568   // If the change is to a committed entry, notify interested parties.
569   if (currentEntry != self.pendingEntry && _navigationManager)
570     _navigationManager->OnNavigationItemChanged();
573 - (void)discardNonCommittedEntries {
574   [self discardTransientEntry];
575   _pendingEntry.reset();
578 - (void)discardTransientEntry {
579   // Keep the entry alive temporarily. There are flows that get the current
580   // entry, do some navigation operation, and then try to use that old current
581   // entry; since navigations clear the transient entry, these flows might
582   // crash. (This should be removable once more session management is handled
583   // within this class and/or NavigationManager).
584   [[_transientEntry retain] autorelease];
585   _transientEntry.reset();
588 - (BOOL)hasPendingEntry {
589   return _pendingEntry != nil;
592 - (void)copyStateFromAndPrune:(CRWSessionController*)otherSession
593                  replaceState:(BOOL)replaceState {
594   DCHECK(otherSession);
595   if (replaceState) {
596     [_entries removeAllObjects];
597     self.currentNavigationIndex = -1;
598     _previousNavigationIndex = -1;
599   }
600   self.xCallbackParameters =
601       [[otherSession.xCallbackParameters copy] autorelease];
602   self.windowName = otherSession.windowName;
603   NSInteger numInitialEntries = [_entries count];
605   // Cycle through the entries from the other session and insert them before any
606   // entries from this session.  Do not copy anything that comes after the other
607   // session's current entry unless replaceState is true.
608   NSArray* otherEntries = [otherSession entries];
610   // The other session may not have any entries, in which case there is nothing
611   // to copy or prune.  The other session's currentNavigationEntry will be bogus
612   // in such cases, so ignore it and return early.
613   // TODO(rohitrao): Do we need to copy over any pending entries?  We might not
614   // add the prerendered page into the back/forward history if we don't copy
615   // pending entries.
616   if (![otherEntries count])
617     return;
619   NSInteger maxCopyIndex = replaceState ? [otherEntries count] - 1 :
620                                           [otherSession currentNavigationIndex];
621   for (NSInteger i = 0; i <= maxCopyIndex; ++i) {
622     [_entries insertObject:[otherEntries objectAtIndex:i] atIndex:i];
623     ++_currentNavigationIndex;
624     _previousNavigationIndex = -1;
625   }
627   // If this CRWSessionController has no entries initially, reset
628   // |currentNavigationIndex_| to be in bounds.
629   if (!numInitialEntries) {
630     if (replaceState) {
631       self.currentNavigationIndex = [otherSession currentNavigationIndex];
632       _previousNavigationIndex = [otherSession previousNavigationIndex];
633     } else {
634       self.currentNavigationIndex = maxCopyIndex;
635     }
636   }
637   DCHECK_LT((NSUInteger)_currentNavigationIndex, [_entries count]);
640 - (ui::PageTransition)transitionForIndex:(NSUInteger)index {
641   return [[_entries objectAtIndex:index] navigationItem]->GetTransitionType();
644 - (BOOL)canGoBack {
645   if ([_entries count] == 0)
646     return NO;
648   NSInteger lastNonRedirectedIndex = _currentNavigationIndex;
649   while (lastNonRedirectedIndex >= 0 &&
650          ui::PageTransitionIsRedirect(
651             [self transitionForIndex:lastNonRedirectedIndex])) {
652     --lastNonRedirectedIndex;
653   }
655   return lastNonRedirectedIndex > 0;
658 - (BOOL)canGoForward {
659   // In case there are pending entries return no since when the entry will be
660   // committed the history will be cleared from that point forward.
661   if (_pendingEntry)
662     return NO;
663   // If the current index is less than the last element, there are entries to
664   // go forward to.
665   const NSInteger count = [_entries count];
666   return count && _currentNavigationIndex < (count - 1);
669 - (void)goBack {
670   if (![self canGoBack])
671     return;
673   [self discardTransientEntry];
675   web::RecordAction(UserMetricsAction("Back"));
676   _previousNavigationIndex = _currentNavigationIndex;
677   // To stop the user getting 'stuck' on redirecting pages they weren't even
678   // aware existed, it is necessary to pass over pages that would immediately
679   // result in a redirect (the entry *before* the redirected page).
680   while (_currentNavigationIndex &&
681          [self transitionForIndex:_currentNavigationIndex] &
682              ui::PAGE_TRANSITION_IS_REDIRECT_MASK) {
683     --_currentNavigationIndex;
684   }
686   if (_currentNavigationIndex)
687     --_currentNavigationIndex;
690 - (void)goForward {
691   [self discardTransientEntry];
693   web::RecordAction(UserMetricsAction("Forward"));
694   if (_currentNavigationIndex + 1 < static_cast<NSInteger>([_entries count])) {
695     _previousNavigationIndex = _currentNavigationIndex;
696     ++_currentNavigationIndex;
697   }
698   // To reduce the chance of a redirect kicking in (truncating the history
699   // stack) we skip over any pages that might do this; we detect this by
700   // looking for when the *next* page had rediection transition type (was
701   // auto redirected to).
702   while (_currentNavigationIndex + 1 <
703          (static_cast<NSInteger>([_entries count])) &&
704          ([self transitionForIndex:_currentNavigationIndex + 1] &
705           ui::PAGE_TRANSITION_IS_REDIRECT_MASK)) {
706     ++_currentNavigationIndex;
707   }
710 - (void)goDelta:(int)delta {
711   if (delta < 0) {
712     while ([self canGoBack] && delta < 0) {
713       [self goBack];
714       ++delta;
715     }
716   } else {
717     while ([self canGoForward] && delta > 0) {
718       [self goForward];
719       --delta;
720     }
721   }
724 - (void)goToEntry:(CRWSessionEntry*)entry {
725   DCHECK(entry);
727   [self discardTransientEntry];
729   // Check that |entries_| still contains |entry|. |entry| could have been
730   // removed by -clearForwardEntries.
731   if ([_entries containsObject:entry])
732     self.currentNavigationIndex = [_entries indexOfObject:entry];
735 - (void)removeEntryAtIndex:(NSInteger)index {
736   DCHECK(index < static_cast<NSInteger>([_entries count]));
737   DCHECK(index != _currentNavigationIndex);
738   DCHECK(index >= 0);
740   [self discardNonCommittedEntries];
742   [_entries removeObjectAtIndex:index];
743   if (_currentNavigationIndex > index)
744     _currentNavigationIndex--;
745   if (_previousNavigationIndex >= index)
746     _previousNavigationIndex--;
749 - (NSArray*)backwardEntries {
750   NSMutableArray* entries = [NSMutableArray array];
751   NSInteger lastNonRedirectedIndex = _currentNavigationIndex;
752   while (lastNonRedirectedIndex >= 0) {
753     CRWSessionEntry* entry = [_entries objectAtIndex:lastNonRedirectedIndex];
754     if (!ui::PageTransitionIsRedirect(
755             entry.navigationItem->GetTransitionType())) {
756       [entries addObject:entry];
757     }
758     --lastNonRedirectedIndex;
759   }
760   // Remove the currently displayed entry.
761   [entries removeObjectAtIndex:0];
762   return entries;
765 - (NSArray*)forwardEntries {
766   NSMutableArray* entries = [NSMutableArray array];
767   NSUInteger lastNonRedirectedIndex = _currentNavigationIndex + 1;
768   while (lastNonRedirectedIndex < [_entries count]) {
769     CRWSessionEntry* entry = [_entries objectAtIndex:lastNonRedirectedIndex];
770     if (!ui::PageTransitionIsRedirect(
771             entry.navigationItem->GetTransitionType())) {
772       [entries addObject:entry];
773     }
774     ++lastNonRedirectedIndex;
775   }
776   return entries;
779 - (std::vector<GURL>)currentRedirectedUrls {
780   std::vector<GURL> results;
781   if (_pendingEntry) {
782     web::NavigationItem* item = [_pendingEntry navigationItem];
783     results.push_back(item->GetURL());
785     if (!ui::PageTransitionIsRedirect(item->GetTransitionType()))
786       return results;
787   }
789   if (![_entries count])
790     return results;
792   NSInteger index = _currentNavigationIndex;
793   // Add urls in the redirected entries.
794   while (index >= 0) {
795     web::NavigationItem* item = [[_entries objectAtIndex:index] navigationItem];
796     if (!ui::PageTransitionIsRedirect(item->GetTransitionType()))
797       break;
798     results.push_back(item->GetURL());
799     --index;
800   }
801   // Add the last non-redirected entry.
802   if (index >= 0) {
803     web::NavigationItem* item = [[_entries objectAtIndex:index] navigationItem];
804     results.push_back(item->GetURL());
805   }
806   return results;
809 - (BOOL)isPushStateNavigationBetweenEntry:(CRWSessionEntry*)firstEntry
810                                  andEntry:(CRWSessionEntry*)secondEntry {
811   DCHECK(firstEntry);
812   DCHECK(secondEntry);
813   if (firstEntry == secondEntry)
814     return NO;
815   NSUInteger firstIndex = [_entries indexOfObject:firstEntry];
816   NSUInteger secondIndex = [_entries indexOfObject:secondEntry];
817   if (firstIndex == NSNotFound || secondIndex == NSNotFound)
818     return NO;
819   NSUInteger startIndex = firstIndex < secondIndex ? firstIndex : secondIndex;
820   NSUInteger endIndex = firstIndex < secondIndex ? secondIndex : firstIndex;
822   for (NSUInteger i = startIndex + 1; i <= endIndex; i++) {
823     web::NavigationItemImpl* item = [_entries[i] navigationItemImpl];
824     // Every entry in the sequence has to be created from a pushState() call.
825     if (!item->IsCreatedFromPushState())
826       return NO;
827     // Every entry in the sequence has to have a URL that could have been
828     // created from a pushState() call.
829     if (!web::history_state_util::IsHistoryStateChangeValid(
830             firstEntry.navigationItem->GetURL(), item->GetURL()))
831       return NO;
832   }
833   return YES;
836 - (CRWSessionEntry*)lastUserEntry {
837   if (![_entries count])
838     return nil;
840   NSInteger index = _currentNavigationIndex;
841   // This will return the first session entry if all other entries are
842   // redirects, regardless of the transition state of the first entry.
843   while (index > 0 &&
844          [self transitionForIndex:index] &
845          ui::PAGE_TRANSITION_IS_REDIRECT_MASK) {
846     --index;
847   }
848   return [_entries objectAtIndex:index];
851 - (void)useDesktopUserAgentForNextPendingEntry {
852   if (_pendingEntry)
853     [_pendingEntry navigationItem]->SetIsOverridingUserAgent(true);
854   else
855     _useDesktopUserAgentForNextPendingEntry = YES;
858 #pragma mark -
859 #pragma mark Private methods
861 - (NSString*)uniqueID {
862   CFUUIDRef uuidRef = CFUUIDCreate(NULL);
863   CFStringRef uuidStringRef = CFUUIDCreateString(NULL, uuidRef);
864   CFRelease(uuidRef);
865   NSString* uuid = [NSString stringWithString:(NSString*)uuidStringRef];
866   CFRelease(uuidStringRef);
867   return uuid;
870 - (CRWSessionEntry*)sessionEntryWithURL:(const GURL&)url
871                                referrer:(const web::Referrer&)referrer
872                              transition:(ui::PageTransition)transition
873                     useDesktopUserAgent:(BOOL)useDesktopUserAgent
874                       rendererInitiated:(BOOL)rendererInitiated {
875   GURL loaded_url(url);
876   BOOL urlWasRewritten = NO;
877   if (_navigationManager) {
878     scoped_ptr<std::vector<web::BrowserURLRewriter::URLRewriter>>
879         transientRewriters = _navigationManager->GetTransientURLRewriters();
880     if (transientRewriters) {
881       urlWasRewritten = web::BrowserURLRewriter::RewriteURLWithWriters(
882           &loaded_url, _browserState, *transientRewriters.get());
883     }
884   }
885   if (!urlWasRewritten) {
886     web::BrowserURLRewriter::GetInstance()->RewriteURLIfNecessary(
887         &loaded_url, _browserState);
888   }
889   scoped_ptr<web::NavigationItemImpl> item(new web::NavigationItemImpl());
890   item->SetURL(loaded_url);
891   item->SetReferrer(referrer);
892   item->SetTransitionType(transition);
893   item->SetIsOverridingUserAgent(useDesktopUserAgent);
894   item->set_is_renderer_initiated(rendererInitiated);
895   return [
896       [[CRWSessionEntry alloc] initWithNavigationItem:item.Pass()] autorelease];
899 @end