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

Side by Side Diff: ios/web/web_state/ui/crw_web_controller.mm

Issue 2705673003: Removed CRWSessionEntry from CRWWebController. (Closed)
Patch Set: web_controller Created 3 years, 10 months 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
OLDNEW
1 // Copyright 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #import "ios/web/web_state/ui/crw_web_controller.h" 5 #import "ios/web/web_state/ui/crw_web_controller.h"
6 6
7 #import <WebKit/WebKit.h> 7 #import <WebKit/WebKit.h>
8 8
9 #import <objc/runtime.h> 9 #import <objc/runtime.h>
10 #include <stddef.h> 10 #include <stddef.h>
(...skipping 25 matching lines...) Expand all
36 #include "base/strings/sys_string_conversions.h" 36 #include "base/strings/sys_string_conversions.h"
37 #include "base/strings/utf_string_conversions.h" 37 #include "base/strings/utf_string_conversions.h"
38 #include "base/time/time.h" 38 #include "base/time/time.h"
39 #include "base/values.h" 39 #include "base/values.h"
40 #import "ios/net/http_response_headers_util.h" 40 #import "ios/net/http_response_headers_util.h"
41 #import "ios/net/nsurlrequest_util.h" 41 #import "ios/net/nsurlrequest_util.h"
42 #include "ios/web/history_state_util.h" 42 #include "ios/web/history_state_util.h"
43 #import "ios/web/interstitials/web_interstitial_impl.h" 43 #import "ios/web/interstitials/web_interstitial_impl.h"
44 #import "ios/web/navigation/crw_session_certificate_policy_manager.h" 44 #import "ios/web/navigation/crw_session_certificate_policy_manager.h"
45 #import "ios/web/navigation/crw_session_controller.h" 45 #import "ios/web/navigation/crw_session_controller.h"
46 #import "ios/web/navigation/crw_session_entry.h"
47 #import "ios/web/navigation/navigation_item_impl.h" 46 #import "ios/web/navigation/navigation_item_impl.h"
48 #import "ios/web/navigation/navigation_manager_impl.h" 47 #import "ios/web/navigation/navigation_manager_impl.h"
49 #include "ios/web/net/cert_host_pair.h" 48 #include "ios/web/net/cert_host_pair.h"
50 #import "ios/web/net/crw_cert_verification_controller.h" 49 #import "ios/web/net/crw_cert_verification_controller.h"
51 #import "ios/web/net/crw_ssl_status_updater.h" 50 #import "ios/web/net/crw_ssl_status_updater.h"
52 #include "ios/web/public/browser_state.h" 51 #include "ios/web/public/browser_state.h"
53 #include "ios/web/public/favicon_url.h" 52 #include "ios/web/public/favicon_url.h"
54 #import "ios/web/public/java_script_dialog_presenter.h" 53 #import "ios/web/public/java_script_dialog_presenter.h"
55 #import "ios/web/public/navigation_item.h" 54 #import "ios/web/public/navigation_item.h"
56 #import "ios/web/public/navigation_manager.h" 55 #import "ios/web/public/navigation_manager.h"
(...skipping 399 matching lines...) Expand 10 before | Expand all | Expand 10 after
456 455
457 // Returns YES if the user interacted with the page recently. 456 // Returns YES if the user interacted with the page recently.
458 @property(nonatomic, readonly) BOOL userClickedRecently; 457 @property(nonatomic, readonly) BOOL userClickedRecently;
459 // Returns whether the desktop user agent should be used when setting the user 458 // Returns whether the desktop user agent should be used when setting the user
460 // agent. 459 // agent.
461 @property(nonatomic, readonly) BOOL useDesktopUserAgent; 460 @property(nonatomic, readonly) BOOL useDesktopUserAgent;
462 461
463 // Facade for Mojo API. 462 // Facade for Mojo API.
464 @property(nonatomic, readonly) web::MojoFacade* mojoFacade; 463 @property(nonatomic, readonly) web::MojoFacade* mojoFacade;
465 464
466 // Updates Desktop User Agent and calls webWillFinishHistoryNavigationFromEntry: 465 // TODO(crbug.com/692871): Remove these functions and replace with more
466 // appropriate NavigationItem getters.
467 // Returns the navigation item for the current page.
468 @property(nonatomic, readonly) web::NavigationItemImpl* currentNavItem;
469 // Returns the current transition type.
470 @property(nonatomic, readonly) ui::PageTransition currentTransition;
471 // Returns the referrer for current navigation item. May be empty.
472 @property(nonatomic, readonly) web::Referrer currentNavItemReferrer;
473 // The HTTP headers associated with the current navigation item. These are nil
474 // unless the request was a POST.
475 @property(nonatomic, readonly) NSDictionary* currentHTTPHeaders;
476
477 // Updates Desktop User Agent and calls webWillFinishHistoryNavigation
467 // on CRWWebDelegate. TODO(crbug.com/684098): Remove this method and inline its 478 // on CRWWebDelegate. TODO(crbug.com/684098): Remove this method and inline its
468 // content. 479 // content.
469 - (void)webWillFinishHistoryNavigationFromEntry:(CRWSessionEntry*)fromEntry; 480 - (void)webWillFinishHistoryNavigationFromItem:(web::NavigationItem*)item;
470 // Recreates web view if |entry| and |fromEntry| have different value for
471 // IsOverridingUserAgent() flag.
472 - (void)updateDesktopUserAgentForEntry:(CRWSessionEntry*)entry
473 fromEntry:(CRWSessionEntry*)fromEntry;
474 // Removes the container view from the hierarchy and resets the ivar. 481 // Removes the container view from the hierarchy and resets the ivar.
475 - (void)resetContainerView; 482 - (void)resetContainerView;
476 // Called when the web page has changed document and/or URL, and so the page 483 // Called when the web page has changed document and/or URL, and so the page
477 // navigation should be reported to the delegate, and internal state updated to 484 // navigation should be reported to the delegate, and internal state updated to
478 // reflect the fact that the navigation has occurred. 485 // reflect the fact that the navigation has occurred.
479 // TODO(stuartmorgan): The code conflates URL changes and document object 486 // TODO(stuartmorgan): The code conflates URL changes and document object
480 // changes; the two need to be separated and handled differently. 487 // changes; the two need to be separated and handled differently.
481 - (void)webPageChanged; 488 - (void)webPageChanged;
482 // Resets any state that is associated with a specific document object (e.g., 489 // Resets any state that is associated with a specific document object (e.g.,
483 // page interaction tracking). 490 // page interaction tracking).
484 - (void)resetDocumentSpecificState; 491 - (void)resetDocumentSpecificState;
485 // Called when a page (native or web) has actually started loading (i.e., for 492 // Called when a page (native or web) has actually started loading (i.e., for
486 // a web page the document has actually changed), or after the load request has 493 // a web page the document has actually changed), or after the load request has
487 // been registered for a non-document-changing URL change. Updates internal 494 // been registered for a non-document-changing URL change. Updates internal
488 // state not specific to web pages, and informs the delegate. 495 // state not specific to web pages, and informs the delegate.
489 - (void)didStartLoadingURL:(const GURL&)URL updateHistory:(BOOL)updateHistory; 496 - (void)didStartLoadingURL:(const GURL&)URL updateHistory:(BOOL)updateHistory;
490 // Returns YES if the URL looks like it is one CRWWebController can show. 497 // Returns YES if the URL looks like it is one CRWWebController can show.
491 + (BOOL)webControllerCanShow:(const GURL&)url; 498 + (BOOL)webControllerCanShow:(const GURL&)url;
492 // Clears the currently-displayed transient content view. 499 // Clears the currently-displayed transient content view.
493 - (void)clearTransientContentView; 500 - (void)clearTransientContentView;
494 // Returns a lazily created CRWTouchTrackingRecognizer. 501 // Returns a lazily created CRWTouchTrackingRecognizer.
495 - (CRWTouchTrackingRecognizer*)touchTrackingRecognizer; 502 - (CRWTouchTrackingRecognizer*)touchTrackingRecognizer;
496 // Shows placeholder overlay. 503 // Shows placeholder overlay.
497 - (void)addPlaceholderOverlay; 504 - (void)addPlaceholderOverlay;
498 // Removes placeholder overlay. 505 // Removes placeholder overlay.
499 - (void)removePlaceholderOverlay; 506 - (void)removePlaceholderOverlay;
500 507
501 // Returns the current entry from the underlying session controller.
502 // TODO(stuartmorgan): Audit all calls to these methods; these are just wrappers
503 // around the same logic as GetActiveEntry, so should probably not be used for
504 // the same reason that GetActiveEntry is deprecated. (E.g., page operations
505 // should generally be dealing with the last commited entry, not a pending
506 // entry).
507 - (CRWSessionEntry*)currentSessionEntry;
508 // Returns the navigation item for the current page.
509 - (web::NavigationItem*)currentNavItem;
510 // Returns the current transition type.
511 - (ui::PageTransition)currentTransition;
512 // Returns the referrer for current navigation item. May be empty.
513 - (web::Referrer)currentSessionEntryReferrer;
514 // The HTTP headers associated with the current navigation item. These are nil
515 // unless the request was a POST.
516 - (NSDictionary*)currentHTTPHeaders;
517
518 // Creates a web view if it's not yet created. 508 // Creates a web view if it's not yet created.
519 - (void)ensureWebViewCreated; 509 - (void)ensureWebViewCreated;
520 // Creates a web view with given |config|. No-op if web view is already created. 510 // Creates a web view with given |config|. No-op if web view is already created.
521 - (void)ensureWebViewCreatedWithConfiguration:(WKWebViewConfiguration*)config; 511 - (void)ensureWebViewCreatedWithConfiguration:(WKWebViewConfiguration*)config;
522 // Returns a new autoreleased web view created with given configuration. 512 // Returns a new autoreleased web view created with given configuration.
523 - (WKWebView*)webViewWithConfiguration:(WKWebViewConfiguration*)config; 513 - (WKWebView*)webViewWithConfiguration:(WKWebViewConfiguration*)config;
524 // Sets the value of the webView property, and performs its basic setup. 514 // Sets the value of the webView property, and performs its basic setup.
525 - (void)setWebView:(WKWebView*)webView; 515 - (void)setWebView:(WKWebView*)webView;
526 // Removes webView, optionally tracking the URL of the evicted 516 // Removes webView, optionally tracking the URL of the evicted
527 // page for later cache-based reconstruction. 517 // page for later cache-based reconstruction.
(...skipping 71 matching lines...) Expand 10 before | Expand all | Expand 10 after
599 // Update the appropriate parts of the model and broadcast to the embedder. This 589 // Update the appropriate parts of the model and broadcast to the embedder. This
600 // may be called multiple times and thus must be idempotent. 590 // may be called multiple times and thus must be idempotent.
601 - (void)loadCompleteWithSuccess:(BOOL)loadSuccess; 591 - (void)loadCompleteWithSuccess:(BOOL)loadSuccess;
602 // Called after URL is finished loading and _loadPhase is set to PAGE_LOADED. 592 // Called after URL is finished loading and _loadPhase is set to PAGE_LOADED.
603 - (void)didFinishWithURL:(const GURL&)currentURL loadSuccess:(BOOL)loadSuccess; 593 - (void)didFinishWithURL:(const GURL&)currentURL loadSuccess:(BOOL)loadSuccess;
604 // Navigates forwards or backwards by |delta| pages. No-op if delta is out of 594 // Navigates forwards or backwards by |delta| pages. No-op if delta is out of
605 // bounds. Reloads if delta is 0. 595 // bounds. Reloads if delta is 0.
606 // TODO(crbug.com/661316): Move this method to NavigationManager. 596 // TODO(crbug.com/661316): Move this method to NavigationManager.
607 - (void)goDelta:(int)delta; 597 - (void)goDelta:(int)delta;
608 // Loads a new URL if the current entry is not from a pushState() navigation. 598 // Loads a new URL if the current entry is not from a pushState() navigation.
609 // |fromEntry| is the CRWSessionEntry that was the current entry prior to the 599 // |item| is the NavigationItem that was the current entry prior to the
610 // navigation. 600 // navigation.
611 - (void)finishHistoryNavigationFromEntry:(CRWSessionEntry*)fromEntry; 601 - (void)finishHistoryNavigationFromItem:(web::NavigationItem*)item;
612 // Informs the native controller if web usage is allowed or not. 602 // Informs the native controller if web usage is allowed or not.
613 - (void)setNativeControllerWebUsageEnabled:(BOOL)webUsageEnabled; 603 - (void)setNativeControllerWebUsageEnabled:(BOOL)webUsageEnabled;
614 // Called when web controller receives a new message from the web page. 604 // Called when web controller receives a new message from the web page.
615 - (void)didReceiveScriptMessage:(WKScriptMessage*)message; 605 - (void)didReceiveScriptMessage:(WKScriptMessage*)message;
616 // Returns a new script which wraps |script| with windowID check so |script| is 606 // Returns a new script which wraps |script| with windowID check so |script| is
617 // not evaluated on windowID mismatch. 607 // not evaluated on windowID mismatch.
618 - (NSString*)scriptByAddingWindowIDCheckForScript:(NSString*)script; 608 - (NSString*)scriptByAddingWindowIDCheckForScript:(NSString*)script;
619 // Attempts to handle a script message. Returns YES on success, NO otherwise. 609 // Attempts to handle a script message. Returns YES on success, NO otherwise.
620 - (BOOL)respondToWKScriptMessage:(WKScriptMessage*)scriptMessage; 610 - (BOOL)respondToWKScriptMessage:(WKScriptMessage*)scriptMessage;
621 // Registers load request with empty referrer and link or client redirect 611 // Registers load request with empty referrer and link or client redirect
(...skipping 663 matching lines...) Expand 10 before | Expand all | Expand 10 after
1285 } 1275 }
1286 // Any non-web URL source is trusted. 1276 // Any non-web URL source is trusted.
1287 *trustLevel = web::URLVerificationTrustLevel::kAbsolute; 1277 *trustLevel = web::URLVerificationTrustLevel::kAbsolute;
1288 if (self.nativeController) { 1278 if (self.nativeController) {
1289 if ([self.nativeController respondsToSelector:@selector(virtualURL)]) { 1279 if ([self.nativeController respondsToSelector:@selector(virtualURL)]) {
1290 return [self.nativeController virtualURL]; 1280 return [self.nativeController virtualURL];
1291 } else { 1281 } else {
1292 return [self.nativeController url]; 1282 return [self.nativeController url];
1293 } 1283 }
1294 } 1284 }
1295 web::NavigationItem* item = [self currentNavItem]; 1285 web::NavigationItem* item = self.currentNavItem;
1296 return item ? item->GetVirtualURL() : GURL::EmptyGURL(); 1286 return item ? item->GetVirtualURL() : GURL::EmptyGURL();
1297 } 1287 }
1298 1288
1299 - (WKWebView*)webView { 1289 - (WKWebView*)webView {
1300 return _webView.get(); 1290 return _webView.get();
1301 } 1291 }
1302 1292
1303 - (UIScrollView*)webScrollView { 1293 - (UIScrollView*)webScrollView {
1304 return [_webView scrollView]; 1294 return [_webView scrollView];
1305 } 1295 }
1306 1296
1307 - (GURL)currentURL { 1297 - (GURL)currentURL {
1308 web::URLVerificationTrustLevel trustLevel = 1298 web::URLVerificationTrustLevel trustLevel =
1309 web::URLVerificationTrustLevel::kNone; 1299 web::URLVerificationTrustLevel::kNone;
1310 return [self currentURLWithTrustLevel:&trustLevel]; 1300 return [self currentURLWithTrustLevel:&trustLevel];
1311 } 1301 }
1312 1302
1313 - (web::Referrer)currentReferrer { 1303 - (web::Referrer)currentReferrer {
1314 // Referrer string doesn't include the fragment, so in cases where the 1304 // Referrer string doesn't include the fragment, so in cases where the
1315 // previous URL is equal to the current referrer plus the fragment the 1305 // previous URL is equal to the current referrer plus the fragment the
1316 // previous URL is returned as current referrer. 1306 // previous URL is returned as current referrer.
1317 NSString* referrerString = _currentReferrerString; 1307 NSString* referrerString = _currentReferrerString;
1318 1308
1319 // In case of an error evaluating the JavaScript simply return empty string. 1309 // In case of an error evaluating the JavaScript simply return empty string.
1320 if ([referrerString length] == 0) 1310 if ([referrerString length] == 0)
1321 return web::Referrer(); 1311 return web::Referrer();
1322 1312
1323 web::NavigationItem* item = [self currentNavItem]; 1313 web::NavigationItem* item = self.currentNavItem;
1324 GURL navigationURL = item ? item->GetVirtualURL() : GURL::EmptyGURL(); 1314 GURL navigationURL = item ? item->GetVirtualURL() : GURL::EmptyGURL();
1325 NSString* previousURLString = base::SysUTF8ToNSString(navigationURL.spec()); 1315 NSString* previousURLString = base::SysUTF8ToNSString(navigationURL.spec());
1326 // Check if the referrer is equal to the previous URL minus the hash symbol. 1316 // Check if the referrer is equal to the previous URL minus the hash symbol.
1327 // L'#' is used to convert the char '#' to a unichar. 1317 // L'#' is used to convert the char '#' to a unichar.
1328 if ([previousURLString length] > [referrerString length] && 1318 if ([previousURLString length] > [referrerString length] &&
1329 [previousURLString hasPrefix:referrerString] && 1319 [previousURLString hasPrefix:referrerString] &&
1330 [previousURLString characterAtIndex:[referrerString length]] == L'#') { 1320 [previousURLString characterAtIndex:[referrerString length]] == L'#') {
1331 referrerString = previousURLString; 1321 referrerString = previousURLString;
1332 } 1322 }
1333 // Since referrer is being extracted from the destination page, the correct 1323 // Since referrer is being extracted from the destination page, the correct
(...skipping 66 matching lines...) Expand 10 before | Expand all | Expand 10 after
1400 // |_pendingNavigationInfo| will be nil if the decidePolicy* delegate methods 1390 // |_pendingNavigationInfo| will be nil if the decidePolicy* delegate methods
1401 // were not called. 1391 // were not called.
1402 NSString* HTTPMethod = 1392 NSString* HTTPMethod =
1403 _pendingNavigationInfo 1393 _pendingNavigationInfo
1404 ? [_pendingNavigationInfo HTTPMethod] 1394 ? [_pendingNavigationInfo HTTPMethod]
1405 : [self currentBackForwardListItemHolder]->http_method(); 1395 : [self currentBackForwardListItemHolder]->http_method();
1406 return [HTTPMethod isEqual:@"POST"]; 1396 return [HTTPMethod isEqual:@"POST"];
1407 } 1397 }
1408 1398
1409 - (BOOL)isCurrentNavigationBackForward { 1399 - (BOOL)isCurrentNavigationBackForward {
1410 if (![self currentNavItem]) 1400 if (!self.currentNavItem)
1411 return NO; 1401 return NO;
1412 WKNavigationType currentNavigationType = 1402 WKNavigationType currentNavigationType =
1413 [self currentBackForwardListItemHolder]->navigation_type(); 1403 [self currentBackForwardListItemHolder]->navigation_type();
1414 return currentNavigationType == WKNavigationTypeBackForward; 1404 return currentNavigationType == WKNavigationTypeBackForward;
1415 } 1405 }
1416 1406
1417 - (BOOL)isLinkNavigation:(WKNavigationType)navigationType { 1407 - (BOOL)isLinkNavigation:(WKNavigationType)navigationType {
1418 switch (navigationType) { 1408 switch (navigationType) {
1419 case WKNavigationTypeLinkActivated: 1409 case WKNavigationTypeLinkActivated:
1420 return YES; 1410 return YES;
(...skipping 160 matching lines...) Expand 10 before | Expand all | Expand 10 after
1581 [[self sessionController] addPendingItem:requestURL 1571 [[self sessionController] addPendingItem:requestURL
1582 referrer:referrer 1572 referrer:referrer
1583 transition:transition 1573 transition:transition
1584 rendererInitiated:YES]; 1574 rendererInitiated:YES];
1585 } 1575 }
1586 _webStateImpl->SetIsLoading(true); 1576 _webStateImpl->SetIsLoading(true);
1587 _webStateImpl->OnProvisionalNavigationStarted(requestURL); 1577 _webStateImpl->OnProvisionalNavigationStarted(requestURL);
1588 } 1578 }
1589 1579
1590 - (void)updateHTML5HistoryState { 1580 - (void)updateHTML5HistoryState {
1591 web::NavigationItemImpl* currentItem = 1581 web::NavigationItemImpl* currentItem = self.currentNavItem;
1592 static_cast<web::NavigationItemImpl*>([self currentNavItem]);
1593 if (!currentItem) 1582 if (!currentItem)
1594 return; 1583 return;
1595 1584
1596 // Same-document navigations must trigger a popState event. 1585 // Same-document navigations must trigger a popState event.
1597 CRWSessionController* sessionController = self.sessionController; 1586 CRWSessionController* sessionController = self.sessionController;
1598 BOOL sameDocumentNavigation = [sessionController 1587 BOOL sameDocumentNavigation = [sessionController
1599 isSameDocumentNavigationBetweenItem:sessionController.currentItem 1588 isSameDocumentNavigationBetweenItem:sessionController.currentItem
1600 andItem:sessionController.previousItem]; 1589 andItem:sessionController.previousItem];
1601 // WKWebView doesn't send hashchange events for same-document non-BFLI 1590 // WKWebView doesn't send hashchange events for same-document non-BFLI
1602 // navigations, so one must be dispatched manually for hash change same- 1591 // navigations, so one must be dispatched manually for hash change same-
1603 // document navigations. 1592 // document navigations.
1604 web::NavigationItem* previousItem =
1605 self.sessionController.previousEntry.navigationItem;
1606 const GURL URL = currentItem->GetURL(); 1593 const GURL URL = currentItem->GetURL();
1594 web::NavigationItem* previousItem = self.sessionController.previousItem;
1607 const GURL oldURL = previousItem ? previousItem->GetURL() : GURL(); 1595 const GURL oldURL = previousItem ? previousItem->GetURL() : GURL();
1608 BOOL shouldDispatchHashchange = sameDocumentNavigation && previousItem && 1596 BOOL shouldDispatchHashchange = sameDocumentNavigation && previousItem &&
1609 (web::GURLByRemovingRefFromGURL(URL) == 1597 (web::GURLByRemovingRefFromGURL(URL) ==
1610 web::GURLByRemovingRefFromGURL(oldURL)); 1598 web::GURLByRemovingRefFromGURL(oldURL));
1611 // The URL and state object must be set for same-document navigations and 1599 // The URL and state object must be set for same-document navigations and
1612 // NavigationItems that were created or updated by calls to pushState() or 1600 // NavigationItems that were created or updated by calls to pushState() or
1613 // replaceState(). 1601 // replaceState().
1614 BOOL shouldUpdateState = sameDocumentNavigation || 1602 BOOL shouldUpdateState = sameDocumentNavigation ||
1615 currentItem->IsCreatedFromPushState() || 1603 currentItem->IsCreatedFromPushState() ||
1616 currentItem->HasStateBeenReplaced(); 1604 currentItem->HasStateBeenReplaced();
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
1649 1637
1650 - (NSString*)javaScriptToDispatchHashChangeWithOldURL:(const GURL&)oldURL 1638 - (NSString*)javaScriptToDispatchHashChangeWithOldURL:(const GURL&)oldURL
1651 newURL:(const GURL&)newURL { 1639 newURL:(const GURL&)newURL {
1652 return [NSString 1640 return [NSString
1653 stringWithFormat:@"__gCrWeb.dispatchHashchangeEvent(\'%s\', \'%s\');", 1641 stringWithFormat:@"__gCrWeb.dispatchHashchangeEvent(\'%s\', \'%s\');",
1654 oldURL.spec().c_str(), newURL.spec().c_str()]; 1642 oldURL.spec().c_str(), newURL.spec().c_str()];
1655 } 1643 }
1656 1644
1657 - (void)injectHTML5HistoryScriptWithHashChange:(BOOL)dispatchHashChange 1645 - (void)injectHTML5HistoryScriptWithHashChange:(BOOL)dispatchHashChange
1658 sameDocumentNavigation:(BOOL)sameDocumentNavigation { 1646 sameDocumentNavigation:(BOOL)sameDocumentNavigation {
1659 web::NavigationItemImpl* currentItem = 1647 web::NavigationItemImpl* currentItem = self.currentNavItem;
1660 static_cast<web::NavigationItemImpl*>([self currentNavItem]);
1661 if (!currentItem) 1648 if (!currentItem)
1662 return; 1649 return;
1663 1650
1664 const GURL URL = currentItem->GetURL(); 1651 const GURL URL = currentItem->GetURL();
1665 NSString* stateObject = currentItem->GetSerializedStateObject(); 1652 NSString* stateObject = currentItem->GetSerializedStateObject();
1666 NSMutableString* script = [NSMutableString 1653 NSMutableString* script = [NSMutableString
1667 stringWithString:[self javaScriptToReplaceWebViewURL:URL 1654 stringWithString:[self javaScriptToReplaceWebViewURL:URL
1668 stateObjectJSON:stateObject]]; 1655 stateObjectJSON:stateObject]];
1669 if (sameDocumentNavigation) { 1656 if (sameDocumentNavigation) {
1670 [script 1657 [script
1671 appendString:[self javaScriptToDispatchPopStateWithObject:stateObject]]; 1658 appendString:[self javaScriptToDispatchPopStateWithObject:stateObject]];
1672 } 1659 }
1673 if (dispatchHashChange) { 1660 if (dispatchHashChange) {
1674 web::NavigationItemImpl* previousItem = 1661 web::NavigationItemImpl* previousItem =
1675 self.sessionController.previousEntry.navigationItemImpl; 1662 self.sessionController.previousItem;
1676 const GURL oldURL = previousItem ? previousItem->GetURL() : GURL(); 1663 const GURL oldURL = previousItem ? previousItem->GetURL() : GURL();
1677 [script appendString:[self javaScriptToDispatchHashChangeWithOldURL:oldURL 1664 [script appendString:[self javaScriptToDispatchHashChangeWithOldURL:oldURL
1678 newURL:URL]]; 1665 newURL:URL]];
1679 } 1666 }
1680 base::WeakNSObject<CRWWebController> weakSelf(self); 1667 base::WeakNSObject<CRWWebController> weakSelf(self);
1681 [self executeJavaScript:script 1668 [self executeJavaScript:script
1682 completionHandler:^(id, NSError*) { 1669 completionHandler:^(id, NSError*) {
1683 if (!weakSelf || weakSelf.get()->_isBeingDestroyed) 1670 if (!weakSelf || weakSelf.get()->_isBeingDestroyed)
1684 return; 1671 return;
1685 base::scoped_nsobject<CRWWebController> strongSelf([weakSelf retain]); 1672 base::scoped_nsobject<CRWWebController> strongSelf([weakSelf retain]);
1686 strongSelf.get()->_URLOnStartLoading = URL; 1673 strongSelf.get()->_URLOnStartLoading = URL;
1687 strongSelf.get()->_lastRegisteredRequestURL = URL; 1674 strongSelf.get()->_lastRegisteredRequestURL = URL;
1688 }]; 1675 }];
1689 } 1676 }
1690 1677
1691 // Load the current URL in a web view, first ensuring the web view is visible. 1678 // Load the current URL in a web view, first ensuring the web view is visible.
1692 - (void)loadCurrentURLInWebView { 1679 - (void)loadCurrentURLInWebView {
1693 // Clear the set of URLs opened in external applications. 1680 // Clear the set of URLs opened in external applications.
1694 _openedApplicationURL.reset([[NSMutableSet alloc] init]); 1681 _openedApplicationURL.reset([[NSMutableSet alloc] init]);
1695 1682
1696 web::NavigationItem* item = [self currentNavItem]; 1683 web::NavigationItem* item = self.currentNavItem;
1697 GURL targetURL = item ? item->GetVirtualURL() : GURL::EmptyGURL(); 1684 GURL targetURL = item ? item->GetVirtualURL() : GURL::EmptyGURL();
1698 // Load the url. The UIWebView delegate callbacks take care of updating the 1685 // Load the url. The UIWebView delegate callbacks take care of updating the
1699 // session history and UI. 1686 // session history and UI.
1700 if (!targetURL.is_valid()) { 1687 if (!targetURL.is_valid()) {
1701 [self didFinishWithURL:targetURL loadSuccess:NO]; 1688 [self didFinishWithURL:targetURL loadSuccess:NO];
1702 return; 1689 return;
1703 } 1690 }
1704 1691
1705 // JavaScript should never be evaluated here. User-entered JS should be 1692 // JavaScript should never be evaluated here. User-entered JS should be
1706 // evaluated via stringByEvaluatingUserJavaScriptFromString. 1693 // evaluated via stringByEvaluatingUserJavaScriptFromString.
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
1741 if ([_pendingNavigationInfo MIMEType]) { 1728 if ([_pendingNavigationInfo MIMEType]) {
1742 self.webStateImpl->SetContentsMimeType( 1729 self.webStateImpl->SetContentsMimeType(
1743 base::SysNSStringToUTF8([_pendingNavigationInfo MIMEType])); 1730 base::SysNSStringToUTF8([_pendingNavigationInfo MIMEType]));
1744 } 1731 }
1745 [self updateCurrentBackForwardListItemHolder]; 1732 [self updateCurrentBackForwardListItemHolder];
1746 1733
1747 _pendingNavigationInfo.reset(); 1734 _pendingNavigationInfo.reset();
1748 } 1735 }
1749 1736
1750 - (NSMutableURLRequest*)requestForCurrentNavigationItem { 1737 - (NSMutableURLRequest*)requestForCurrentNavigationItem {
1751 web::NavigationItem* item = [self currentNavItem]; 1738 web::NavigationItem* item = self.currentNavItem;
1752 const GURL currentNavigationURL = 1739 const GURL currentNavigationURL =
1753 item ? item->GetVirtualURL() : GURL::EmptyGURL(); 1740 item ? item->GetVirtualURL() : GURL::EmptyGURL();
1754 NSMutableURLRequest* request = [NSMutableURLRequest 1741 NSMutableURLRequest* request = [NSMutableURLRequest
1755 requestWithURL:net::NSURLWithGURL(currentNavigationURL)]; 1742 requestWithURL:net::NSURLWithGURL(currentNavigationURL)];
1756 const web::Referrer referrer([self currentSessionEntryReferrer]); 1743 const web::Referrer referrer(self.currentNavItemReferrer);
1757 if (referrer.url.is_valid()) { 1744 if (referrer.url.is_valid()) {
1758 std::string referrerValue = 1745 std::string referrerValue =
1759 web::ReferrerHeaderValueForNavigation(currentNavigationURL, referrer); 1746 web::ReferrerHeaderValueForNavigation(currentNavigationURL, referrer);
1760 if (!referrerValue.empty()) { 1747 if (!referrerValue.empty()) {
1761 [request setValue:base::SysUTF8ToNSString(referrerValue) 1748 [request setValue:base::SysUTF8ToNSString(referrerValue)
1762 forHTTPHeaderField:kReferrerHeaderName]; 1749 forHTTPHeaderField:kReferrerHeaderName];
1763 } 1750 }
1764 } 1751 }
1765 1752
1766 // If there are headers in the current session entry add them to |request|. 1753 // If there are headers in the current session entry add them to |request|.
1767 // Headers that would overwrite fields already present in |request| are 1754 // Headers that would overwrite fields already present in |request| are
1768 // skipped. 1755 // skipped.
1769 NSDictionary* headers = [self currentHTTPHeaders]; 1756 NSDictionary* headers = self.currentHTTPHeaders;
1770 for (NSString* headerName in headers) { 1757 for (NSString* headerName in headers) {
1771 if (![request valueForHTTPHeaderField:headerName]) { 1758 if (![request valueForHTTPHeaderField:headerName]) {
1772 [request setValue:[headers objectForKey:headerName] 1759 [request setValue:[headers objectForKey:headerName]
1773 forHTTPHeaderField:headerName]; 1760 forHTTPHeaderField:headerName];
1774 } 1761 }
1775 } 1762 }
1776 1763
1777 return request; 1764 return request;
1778 } 1765 }
1779 1766
1780 - (web::WKBackForwardListItemHolder*)currentBackForwardListItemHolder { 1767 - (web::WKBackForwardListItemHolder*)currentBackForwardListItemHolder {
1781 web::NavigationItem* item = [self currentSessionEntry].navigationItemImpl; 1768 web::NavigationItem* item = self.currentNavItem;
1782 DCHECK(item); 1769 DCHECK(item);
1783 web::WKBackForwardListItemHolder* holder = 1770 web::WKBackForwardListItemHolder* holder =
1784 web::WKBackForwardListItemHolder::FromNavigationItem(item); 1771 web::WKBackForwardListItemHolder::FromNavigationItem(item);
1785 DCHECK(holder); 1772 DCHECK(holder);
1786 return holder; 1773 return holder;
1787 } 1774 }
1788 1775
1789 - (void)updateCurrentBackForwardListItemHolder { 1776 - (void)updateCurrentBackForwardListItemHolder {
1790 // WebUI pages (which are loaded via loadHTMLString:baseURL:) have no entry 1777 // WebUI pages (which are loaded via loadHTMLString:baseURL:) have no entry
1791 // in the back/forward list, so the current item will still be the previous 1778 // in the back/forward list, so the current item will still be the previous
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
1827 // delegate. 1814 // delegate.
1828 if ([_delegate respondsToSelector:@selector(webController:titleDidChange:)]) { 1815 if ([_delegate respondsToSelector:@selector(webController:titleDidChange:)]) {
1829 if ([self.nativeController respondsToSelector:@selector(setDelegate:)]) { 1816 if ([self.nativeController respondsToSelector:@selector(setDelegate:)]) {
1830 [self.nativeController setDelegate:self]; 1817 [self.nativeController setDelegate:self];
1831 } 1818 }
1832 } 1819 }
1833 } 1820 }
1834 1821
1835 - (void)loadErrorInNativeView:(NSError*)error { 1822 - (void)loadErrorInNativeView:(NSError*)error {
1836 [self removeWebViewAllowingCachedReconstruction:NO]; 1823 [self removeWebViewAllowingCachedReconstruction:NO];
1837 web::NavigationItem* item = [self currentNavItem]; 1824 web::NavigationItem* item = self.currentNavItem;
1838 const GURL currentURL = item ? item->GetVirtualURL() : GURL::EmptyGURL(); 1825 const GURL currentURL = item ? item->GetVirtualURL() : GURL::EmptyGURL();
1839 1826
1840 if (web::IsWKWebViewSSLCertError(error)) { 1827 if (web::IsWKWebViewSSLCertError(error)) {
1841 // This could happen only if certificate is absent or could not be parsed. 1828 // This could happen only if certificate is absent or could not be parsed.
1842 error = web::NetErrorFromError(error, net::ERR_SSL_SERVER_CERT_BAD_FORMAT); 1829 error = web::NetErrorFromError(error, net::ERR_SSL_SERVER_CERT_BAD_FORMAT);
1843 #if defined(DEBUG) 1830 #if defined(DEBUG)
1844 net::SSLInfo info; 1831 net::SSLInfo info;
1845 web::GetSSLInfoFromWKWebViewSSLCertError(error, &info); 1832 web::GetSSLInfoFromWKWebViewSSLCertError(error, &info);
1846 CHECK(!error.cert); 1833 CHECK(!error.cert);
1847 #endif 1834 #endif
1848 } else { 1835 } else {
1849 error = web::NetErrorFromError(error); 1836 error = web::NetErrorFromError(error);
1850 } 1837 }
1851 1838
1852 BOOL isPost = [self isCurrentNavigationItemPOST]; 1839 BOOL isPost = [self isCurrentNavigationItemPOST];
1853 [self setNativeController:[_nativeProvider controllerForURL:currentURL 1840 [self setNativeController:[_nativeProvider controllerForURL:currentURL
1854 withError:error 1841 withError:error
1855 isPost:isPost]]; 1842 isPost:isPost]];
1856 [self loadNativeViewWithSuccess:NO]; 1843 [self loadNativeViewWithSuccess:NO];
1857 } 1844 }
1858 1845
1859 // Load the current URL in a native controller, retrieved from the native 1846 // Load the current URL in a native controller, retrieved from the native
1860 // provider. Call |loadNativeViewWithSuccess:YES| to load the native controller. 1847 // provider. Call |loadNativeViewWithSuccess:YES| to load the native controller.
1861 - (void)loadCurrentURLInNativeView { 1848 - (void)loadCurrentURLInNativeView {
1862 // Free the web view. 1849 // Free the web view.
1863 [self removeWebViewAllowingCachedReconstruction:NO]; 1850 [self removeWebViewAllowingCachedReconstruction:NO];
1864 1851
1865 web::NavigationItem* item = [self currentNavItem]; 1852 web::NavigationItem* item = self.currentNavItem;
1866 const GURL targetURL = item ? item->GetURL() : GURL::EmptyGURL(); 1853 const GURL targetURL = item ? item->GetURL() : GURL::EmptyGURL();
1867 const web::Referrer referrer; 1854 const web::Referrer referrer;
1868 id<CRWNativeContent> nativeContent = 1855 id<CRWNativeContent> nativeContent =
1869 [_nativeProvider controllerForURL:targetURL webState:self.webState]; 1856 [_nativeProvider controllerForURL:targetURL webState:self.webState];
1870 // Unlike the WebView case, always create a new controller and view. 1857 // Unlike the WebView case, always create a new controller and view.
1871 // TODO(pinkerton): What to do if this does return nil? 1858 // TODO(pinkerton): What to do if this does return nil?
1872 [self setNativeController:nativeContent]; 1859 [self setNativeController:nativeContent];
1873 if ([nativeContent respondsToSelector:@selector(virtualURL)]) { 1860 if ([nativeContent respondsToSelector:@selector(virtualURL)]) {
1874 item->SetVirtualURL([nativeContent virtualURL]); 1861 item->SetVirtualURL([nativeContent virtualURL]);
1875 } 1862 }
1876 1863
1877 [self registerLoadRequest:targetURL 1864 [self registerLoadRequest:targetURL
1878 referrer:referrer 1865 referrer:referrer
1879 transition:[self currentTransition]]; 1866 transition:self.currentTransition];
1880 [self loadNativeViewWithSuccess:YES]; 1867 [self loadNativeViewWithSuccess:YES];
1881 } 1868 }
1882 1869
1883 - (void)loadWithParams:(const NavigationManager::WebLoadParams&)originalParams { 1870 - (void)loadWithParams:(const NavigationManager::WebLoadParams&)originalParams {
1884 // Make a copy of |params|, as some of the delegate methods may modify it. 1871 // Make a copy of |params|, as some of the delegate methods may modify it.
1885 NavigationManager::WebLoadParams params(originalParams); 1872 NavigationManager::WebLoadParams params(originalParams);
1886 1873
1887 // Initiating a navigation from the UI, record the current page state before 1874 // Initiating a navigation from the UI, record the current page state before
1888 // the new page loads. Don't record for back/forward, as the current entry 1875 // the new page loads. Don't record for back/forward, as the current entry
1889 // has already been moved to the next entry in the history. Do, however, 1876 // has already been moved to the next entry in the history. Do, however,
(...skipping 20 matching lines...) Expand all
1910 // manager. TODO(stuartmorgan): Drive Transient Item clearing from 1897 // manager. TODO(stuartmorgan): Drive Transient Item clearing from
1911 // navigation system, rather than from WebController. 1898 // navigation system, rather than from WebController.
1912 [self clearTransientContentView]; 1899 [self clearTransientContentView];
1913 1900
1914 // TODO(stuartmorgan): Why doesn't recordStateInHistory get called for 1901 // TODO(stuartmorgan): Why doesn't recordStateInHistory get called for
1915 // forward/back transitions? 1902 // forward/back transitions?
1916 [self recordStateInHistory]; 1903 [self recordStateInHistory];
1917 1904
1918 CRWSessionController* history = 1905 CRWSessionController* history =
1919 _webStateImpl->GetNavigationManagerImpl().GetSessionController(); 1906 _webStateImpl->GetNavigationManagerImpl().GetSessionController();
1920 if (!self.currentSessionEntry) 1907 if (!history.currentItem)
1921 initialNavigation = YES; 1908 initialNavigation = YES;
1922 [history addPendingItem:navUrl 1909 [history addPendingItem:navUrl
1923 referrer:params.referrer 1910 referrer:params.referrer
1924 transition:transition 1911 transition:transition
1925 rendererInitiated:params.is_renderer_initiated]; 1912 rendererInitiated:params.is_renderer_initiated];
1926 web::NavigationItemImpl* addedItem = 1913 web::NavigationItemImpl* addedItem = history.currentItem;
1927 [self currentSessionEntry].navigationItemImpl;
1928 DCHECK(addedItem); 1914 DCHECK(addedItem);
1929 if (params.extra_headers) 1915 if (params.extra_headers)
1930 addedItem->AddHttpRequestHeaders(params.extra_headers); 1916 addedItem->AddHttpRequestHeaders(params.extra_headers);
1931 if (params.post_data) { 1917 if (params.post_data) {
1932 DCHECK([addedItem->GetHttpRequestHeaders() objectForKey:@"Content-Type"]) 1918 DCHECK([addedItem->GetHttpRequestHeaders() objectForKey:@"Content-Type"])
1933 << "Post data should have an associated content type"; 1919 << "Post data should have an associated content type";
1934 addedItem->SetPostData(params.post_data); 1920 addedItem->SetPostData(params.post_data);
1935 addedItem->SetShouldSkipRepostFormConfirmation(true); 1921 addedItem->SetShouldSkipRepostFormConfirmation(true);
1936 } 1922 }
1937 } 1923 }
(...skipping 15 matching lines...) Expand all
1953 1939
1954 // Abort any outstanding page load. This ensures the delegate gets informed 1940 // Abort any outstanding page load. This ensures the delegate gets informed
1955 // about the outgoing page, and further messages from the page are suppressed. 1941 // about the outgoing page, and further messages from the page are suppressed.
1956 if (_loadPhase != web::PAGE_LOADED) 1942 if (_loadPhase != web::PAGE_LOADED)
1957 [self abortLoad]; 1943 [self abortLoad];
1958 1944
1959 DCHECK(!_isHalted); 1945 DCHECK(!_isHalted);
1960 // Remove the transient content view. 1946 // Remove the transient content view.
1961 [self clearTransientContentView]; 1947 [self clearTransientContentView];
1962 1948
1963 web::NavigationItem* item = [self currentNavItem]; 1949 web::NavigationItem* item = self.currentNavItem;
1964 const GURL currentURL = item ? item->GetURL() : GURL::EmptyGURL(); 1950 const GURL currentURL = item ? item->GetURL() : GURL::EmptyGURL();
1965 // If it's a chrome URL, but not a native one, create the WebUI instance. 1951 // If it's a chrome URL, but not a native one, create the WebUI instance.
1966 if (web::GetWebClient()->IsAppSpecificURL(currentURL) && 1952 if (web::GetWebClient()->IsAppSpecificURL(currentURL) &&
1967 ![_nativeProvider hasControllerForURL:currentURL]) { 1953 ![_nativeProvider hasControllerForURL:currentURL]) {
1968 if (!(item->GetTransitionType() & ui::PAGE_TRANSITION_TYPED || 1954 if (!(item->GetTransitionType() & ui::PAGE_TRANSITION_TYPED ||
1969 item->GetTransitionType() & ui::PAGE_TRANSITION_AUTO_BOOKMARK) && 1955 item->GetTransitionType() & ui::PAGE_TRANSITION_AUTO_BOOKMARK) &&
1970 self.sessionController.openedByDOM) { 1956 self.sessionController.openedByDOM) {
1971 // WebUI URLs can not be opened by DOM to prevent cross-site scripting as 1957 // WebUI URLs can not be opened by DOM to prevent cross-site scripting as
1972 // they have increased power. WebUI URLs may only be opened when the user 1958 // they have increased power. WebUI URLs may only be opened when the user
1973 // types in the URL or use bookmarks. 1959 // types in the URL or use bookmarks.
(...skipping 47 matching lines...) Expand 10 before | Expand all | Expand 10 after
2021 CGFloat statusBarHeight = 2007 CGFloat statusBarHeight =
2022 [[UIApplication sharedApplication] statusBarFrame].size.height; 2008 [[UIApplication sharedApplication] statusBarFrame].size.height;
2023 CGRect containerViewFrame = [UIScreen mainScreen].bounds; 2009 CGRect containerViewFrame = [UIScreen mainScreen].bounds;
2024 containerViewFrame.origin.y += statusBarHeight; 2010 containerViewFrame.origin.y += statusBarHeight;
2025 containerViewFrame.size.height -= statusBarHeight; 2011 containerViewFrame.size.height -= statusBarHeight;
2026 _containerView.get().frame = containerViewFrame; 2012 _containerView.get().frame = containerViewFrame;
2027 DCHECK(!CGRectIsEmpty(_containerView.get().frame)); 2013 DCHECK(!CGRectIsEmpty(_containerView.get().frame));
2028 2014
2029 [_containerView addGestureRecognizer:[self touchTrackingRecognizer]]; 2015 [_containerView addGestureRecognizer:[self touchTrackingRecognizer]];
2030 // Is |currentUrl| a web scheme or native chrome scheme. 2016 // Is |currentUrl| a web scheme or native chrome scheme.
2031 web::NavigationItem* item = [self currentNavItem]; 2017 web::NavigationItem* item = self.currentNavItem;
2032 const GURL currentNavigationURL = 2018 const GURL currentNavigationURL =
2033 item ? item->GetVirtualURL() : GURL::EmptyGURL(); 2019 item ? item->GetVirtualURL() : GURL::EmptyGURL();
2034 BOOL isChromeScheme = 2020 BOOL isChromeScheme =
2035 web::GetWebClient()->IsAppSpecificURL(currentNavigationURL); 2021 web::GetWebClient()->IsAppSpecificURL(currentNavigationURL);
2036 2022
2037 // Don't immediately load the web page if in overlay mode. Always load if 2023 // Don't immediately load the web page if in overlay mode. Always load if
2038 // native. 2024 // native.
2039 if (isChromeScheme || !_overlayPreviewMode) { 2025 if (isChromeScheme || !_overlayPreviewMode) {
2040 // TODO(jimblackler): end the practice of calling |loadCurrentURL| when it 2026 // TODO(jimblackler): end the practice of calling |loadCurrentURL| when it
2041 // is possible there is no current URL. If the call performs necessary 2027 // is possible there is no current URL. If the call performs necessary
(...skipping 94 matching lines...) Expand 10 before | Expand all | Expand 10 after
2136 } 2122 }
2137 [_delegate webLoadCancelled:_URLOnStartLoading]; 2123 [_delegate webLoadCancelled:_URLOnStartLoading];
2138 break; 2124 break;
2139 case web::PAGE_LOADED: 2125 case web::PAGE_LOADED:
2140 break; 2126 break;
2141 } 2127 }
2142 } 2128 }
2143 2129
2144 - (void)goToItemAtIndex:(int)index { 2130 - (void)goToItemAtIndex:(int)index {
2145 CRWSessionController* sessionController = self.sessionController; 2131 CRWSessionController* sessionController = self.sessionController;
2146 NSArray* entries = sessionController.entries; 2132 web::NavigationItemList items = sessionController.items;
2147 if (index < 0 || index >= static_cast<int>(entries.count)) { 2133 if (index < 0 || index >= static_cast<int>(items.size())) {
2148 NOTREACHED(); 2134 NOTREACHED();
2149 return; 2135 return;
2150 } 2136 }
2151 2137
2152 if (!_webStateImpl->IsShowingWebInterstitial()) 2138 if (!_webStateImpl->IsShowingWebInterstitial())
2153 [self recordStateInHistory]; 2139 [self recordStateInHistory];
2154 CRWSessionEntry* fromEntry = sessionController.currentEntry; 2140 web::NavigationItem* fromItem = sessionController.currentItem;
2155 CRWSessionEntry* toEntry = entries[index]; 2141 web::NavigationItem* toItem = items[index];
2156 2142
2157 NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults]; 2143 NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
2158 if (![userDefaults boolForKey:@"PendingIndexNavigationDisabled"]) { 2144 if (![userDefaults boolForKey:@"PendingIndexNavigationDisabled"]) {
2159 [self clearTransientContentView]; 2145 [self clearTransientContentView];
2160 2146
2161 BOOL sameDocumentNavigation = [sessionController 2147 BOOL sameDocumentNavigation = [sessionController
2162 isSameDocumentNavigationBetweenItem:fromEntry.navigationItem 2148 isSameDocumentNavigationBetweenItem:fromItem
2163 andItem:toEntry.navigationItem]; 2149 andItem:toItem];
2164 if (sameDocumentNavigation) { 2150 if (sameDocumentNavigation) {
2165 [self.sessionController goToItemAtIndex:index]; 2151 [self.sessionController goToItemAtIndex:index];
2166 // TODO(crbug.com/684098): move this call out this block to avoid code 2152 // TODO(crbug.com/684098): move this call out this block to avoid code
2167 // duplication. 2153 // duplication.
2168 [self webWillFinishHistoryNavigationFromEntry:fromEntry]; 2154 [self webWillFinishHistoryNavigationFromItem:fromItem];
2169 [self updateHTML5HistoryState]; 2155 [self updateHTML5HistoryState];
2170 } else { 2156 } else {
2171 [sessionController discardNonCommittedItems]; 2157 [sessionController discardNonCommittedItems];
2172 [sessionController setPendingItemIndex:index]; 2158 [sessionController setPendingItemIndex:index];
2173 2159
2174 // TODO(crbug.com/684098): move this call out this block to avoid code 2160 // TODO(crbug.com/684098): move this call out this block to avoid code
2175 // duplication. 2161 // duplication.
2176 [self webWillFinishHistoryNavigationFromEntry:fromEntry]; 2162 [self webWillFinishHistoryNavigationFromItem:fromItem];
2177 2163
2178 web::NavigationItemImpl* pendingItem = 2164 web::NavigationItemImpl* pendingItem = sessionController.pendingItem;
2179 sessionController.pendingEntry.navigationItemImpl;
2180 pendingItem->SetTransitionType(ui::PageTransitionFromInt( 2165 pendingItem->SetTransitionType(ui::PageTransitionFromInt(
2181 pendingItem->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK)); 2166 pendingItem->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
2182 2167
2183 [self loadCurrentURL]; 2168 [self loadCurrentURL];
2184 } 2169 }
2185 } else { 2170 } else {
2186 [self.sessionController goToItemAtIndex:index]; 2171 [self.sessionController goToItemAtIndex:index];
2187 if (fromEntry) 2172 if (fromItem)
2188 [self finishHistoryNavigationFromEntry:fromEntry]; 2173 [self finishHistoryNavigationFromItem:fromItem];
2189 } 2174 }
2190 } 2175 }
2191 2176
2192 - (BOOL)isLoaded { 2177 - (BOOL)isLoaded {
2193 return _loadPhase == web::PAGE_LOADED; 2178 return _loadPhase == web::PAGE_LOADED;
2194 } 2179 }
2195 2180
2196 - (void)didFinishNavigation { 2181 - (void)didFinishNavigation {
2197 // This can be called at multiple times after the document has loaded. Do 2182 // This can be called at multiple times after the document has loaded. Do
2198 // nothing if the document has already loaded. 2183 // nothing if the document has already loaded.
(...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after
2242 // WKWebView will cache the WebUI HTML in the previous WKBackForwardListItem 2227 // WKWebView will cache the WebUI HTML in the previous WKBackForwardListItem
2243 // since it's loaded via |-loadHTML:forURL:| instead of an NSURLRequest. As a 2228 // since it's loaded via |-loadHTML:forURL:| instead of an NSURLRequest. As a
2244 // result, the WebUI's HTML and URL will be loaded when navigating to that 2229 // result, the WebUI's HTML and URL will be loaded when navigating to that
2245 // WKBackForwardListItem, causing a mismatch between the visible content and 2230 // WKBackForwardListItem, causing a mismatch between the visible content and
2246 // the visible URL (WebUI page will be visible, but URL will be the previous 2231 // the visible URL (WebUI page will be visible, but URL will be the previous
2247 // page's URL). To prevent this potential URL spoofing vulnerability, reset 2232 // page's URL). To prevent this potential URL spoofing vulnerability, reset
2248 // the previous NavigationItem's WKBackForwardListItem to force loading via 2233 // the previous NavigationItem's WKBackForwardListItem to force loading via
2249 // NSURLRequest. 2234 // NSURLRequest.
2250 if (_webUIManager) { 2235 if (_webUIManager) {
2251 web::NavigationItem* lastNavigationItem = 2236 web::NavigationItem* lastNavigationItem =
2252 self.sessionController.previousEntry.navigationItem; 2237 self.sessionController.previousItem;
2253 if (lastNavigationItem) { 2238 if (lastNavigationItem) {
2254 web::WKBackForwardListItemHolder* holder = 2239 web::WKBackForwardListItemHolder* holder =
2255 web::WKBackForwardListItemHolder::FromNavigationItem( 2240 web::WKBackForwardListItemHolder::FromNavigationItem(
2256 lastNavigationItem); 2241 lastNavigationItem);
2257 DCHECK(holder); 2242 DCHECK(holder);
2258 holder->set_back_forward_list_item(nil); 2243 holder->set_back_forward_list_item(nil);
2259 } 2244 }
2260 } 2245 }
2261 2246
2262 [self restoreStateFromHistory]; 2247 [self restoreStateFromHistory];
(...skipping 10 matching lines...) Expand all
2273 return; 2258 return;
2274 } 2259 }
2275 2260
2276 web::NavigationManagerImpl& navigationManager = 2261 web::NavigationManagerImpl& navigationManager =
2277 _webStateImpl->GetNavigationManagerImpl(); 2262 _webStateImpl->GetNavigationManagerImpl();
2278 if (navigationManager.CanGoToOffset(delta)) { 2263 if (navigationManager.CanGoToOffset(delta)) {
2279 [self goToItemAtIndex:navigationManager.GetIndexForOffset(delta)]; 2264 [self goToItemAtIndex:navigationManager.GetIndexForOffset(delta)];
2280 } 2265 }
2281 } 2266 }
2282 2267
2283 - (void)finishHistoryNavigationFromEntry:(CRWSessionEntry*)fromEntry { 2268 - (void)finishHistoryNavigationFromItem:(web::NavigationItem*)item {
2284 [self webWillFinishHistoryNavigationFromEntry:fromEntry]; 2269 [self webWillFinishHistoryNavigationFromItem:item];
2285 2270
2286 // Only load the new URL if it has a different document than |fromEntry| to 2271 // Only load the new URL if it has a different document than |fromEntry| to
2287 // prevent extra page loads from NavigationItems created by hash changes or 2272 // prevent extra page loads from NavigationItems created by hash changes or
2288 // calls to window.history.pushState(). 2273 // calls to window.history.pushState().
2289 BOOL shouldLoadURL = 2274 BOOL shouldLoadURL =
2290 ![_webStateImpl->GetNavigationManagerImpl().GetSessionController() 2275 ![_webStateImpl->GetNavigationManagerImpl().GetSessionController()
2291 isSameDocumentNavigationBetweenItem:fromEntry.navigationItem 2276 isSameDocumentNavigationBetweenItem:item
2292 andItem:self.currentNavItem]; 2277 andItem:self.currentNavItem];
2293 web::NavigationItemImpl* currentItem = 2278 web::NavigationItemImpl* currentItem = self.currentNavItem;
2294 self.currentSessionEntry.navigationItemImpl; 2279 GURL endURL = [self URLForHistoryNavigationFromItem:item
2295 GURL endURL = [self URLForHistoryNavigationFromItem:fromEntry.navigationItem
2296 toItem:currentItem]; 2280 toItem:currentItem];
2297 if (shouldLoadURL) { 2281 if (shouldLoadURL) {
2298 ui::PageTransition transition = ui::PageTransitionFromInt( 2282 ui::PageTransition transition = ui::PageTransitionFromInt(
2299 ui::PAGE_TRANSITION_RELOAD | ui::PAGE_TRANSITION_FORWARD_BACK); 2283 ui::PAGE_TRANSITION_RELOAD | ui::PAGE_TRANSITION_FORWARD_BACK);
2300 2284
2301 NavigationManager::WebLoadParams params(endURL); 2285 NavigationManager::WebLoadParams params(endURL);
2302 if (currentItem) { 2286 if (currentItem) {
2303 params.referrer = currentItem->GetReferrer(); 2287 params.referrer = currentItem->GetReferrer();
2304 } 2288 }
2305 params.transition_type = transition; 2289 params.transition_type = transition;
(...skipping 51 matching lines...) Expand 10 before | Expand all | Expand 10 after
2357 // the page has no navigation items, as occurs when an App Store link is 2341 // the page has no navigation items, as occurs when an App Store link is
2358 // opened from another application. 2342 // opened from another application.
2359 BOOL rendererInitiatedWithoutInteraction = 2343 BOOL rendererInitiatedWithoutInteraction =
2360 self.sessionController.openedByDOM && !_userInteractedWithWebController; 2344 self.sessionController.openedByDOM && !_userInteractedWithWebController;
2361 BOOL noNavigationItems = 2345 BOOL noNavigationItems =
2362 !_webStateImpl->GetNavigationManagerImpl().GetItemCount(); 2346 !_webStateImpl->GetNavigationManagerImpl().GetItemCount();
2363 return rendererInitiatedWithoutInteraction || noNavigationItems; 2347 return rendererInitiatedWithoutInteraction || noNavigationItems;
2364 } 2348 }
2365 2349
2366 - (BOOL)useDesktopUserAgent { 2350 - (BOOL)useDesktopUserAgent {
2367 web::NavigationItem* item = [self currentNavItem]; 2351 web::NavigationItem* item = self.currentNavItem;
2368 return item && item->IsOverridingUserAgent(); 2352 return item && item->IsOverridingUserAgent();
2369 } 2353 }
2370 2354
2371 - (web::MojoFacade*)mojoFacade { 2355 - (web::MojoFacade*)mojoFacade {
2372 if (!_mojoFacade) { 2356 if (!_mojoFacade) {
2373 service_manager::mojom::InterfaceProvider* interfaceProvider = 2357 service_manager::mojom::InterfaceProvider* interfaceProvider =
2374 _webStateImpl->GetMojoInterfaceRegistry(); 2358 _webStateImpl->GetMojoInterfaceRegistry();
2375 _mojoFacade.reset(new web::MojoFacade(interfaceProvider, self)); 2359 _mojoFacade.reset(new web::MojoFacade(interfaceProvider, self));
2376 } 2360 }
2377 return _mojoFacade.get(); 2361 return _mojoFacade.get();
(...skipping 19 matching lines...) Expand all
2397 [delegate webController:strongSelf didLoadPassKitObject:data]; 2381 [delegate webController:strongSelf didLoadPassKitObject:data];
2398 } 2382 }
2399 }; 2383 };
2400 web::BrowserState* browserState = self.webStateImpl->GetBrowserState(); 2384 web::BrowserState* browserState = self.webStateImpl->GetBrowserState();
2401 _passKitDownloader.reset([[CRWPassKitDownloader alloc] 2385 _passKitDownloader.reset([[CRWPassKitDownloader alloc]
2402 initWithContextGetter:browserState->GetRequestContext() 2386 initWithContextGetter:browserState->GetRequestContext()
2403 completionHandler:passKitCompletion]); 2387 completionHandler:passKitCompletion]);
2404 return _passKitDownloader.get(); 2388 return _passKitDownloader.get();
2405 } 2389 }
2406 2390
2407 - (void)webWillFinishHistoryNavigationFromEntry:(CRWSessionEntry*)fromEntry { 2391 - (void)webWillFinishHistoryNavigationFromItem:(web::NavigationItem*)item {
2408 DCHECK(fromEntry); 2392 DCHECK(item);
2409 [self updateDesktopUserAgentForEntry:self.currentSessionEntry 2393 // Require page reconstruction if the current NavigationItem and |item| have
2410 fromEntry:fromEntry]; 2394 // a different user agent.
2411 [_delegate webWillFinishHistoryNavigationFromEntry:fromEntry]; 2395 if (self.currentNavItem->IsOverridingUserAgent() !=
2412 } 2396 item->IsOverridingUserAgent()) {
2413
2414 - (void)updateDesktopUserAgentForEntry:(CRWSessionEntry*)entry
2415 fromEntry:(CRWSessionEntry*)fromEntry {
2416 web::NavigationItemImpl* item = entry.navigationItemImpl;
2417 web::NavigationItemImpl* fromItem = fromEntry.navigationItemImpl;
2418 if (!item || !fromItem)
2419 return;
2420 bool useDesktopUserAgent = item->IsOverridingUserAgent();
2421 if (useDesktopUserAgent != fromItem->IsOverridingUserAgent()) {
2422 [self requirePageReconstruction]; 2397 [self requirePageReconstruction];
2423 } 2398 }
2399 // Inform the delegate.
2400 [_delegate webWillFinishHistoryNavigation];
2424 } 2401 }
2425 2402
2426 #pragma mark - 2403 #pragma mark -
2427 #pragma mark CRWWebControllerContainerViewDelegate 2404 #pragma mark CRWWebControllerContainerViewDelegate
2428 2405
2429 - (CRWWebViewProxyImpl*)contentViewProxyForContainerView: 2406 - (CRWWebViewProxyImpl*)contentViewProxyForContainerView:
2430 (CRWWebControllerContainerView*)containerView { 2407 (CRWWebControllerContainerView*)containerView {
2431 return _webViewProxy.get(); 2408 return _webViewProxy.get();
2432 } 2409 }
2433 2410
(...skipping 430 matching lines...) Expand 10 before | Expand all | Expand 10 after
2864 [self executeJavaScript:@"__gCrWeb.sendFaviconsToHost();" 2841 [self executeJavaScript:@"__gCrWeb.sendFaviconsToHost();"
2865 completionHandler:nil]; 2842 completionHandler:nil];
2866 2843
2867 // Record that the current NavigationItem was created by a hash change, but 2844 // Record that the current NavigationItem was created by a hash change, but
2868 // ignore hashchange events that are manually dispatched for same-document 2845 // ignore hashchange events that are manually dispatched for same-document
2869 // navigations. 2846 // navigations.
2870 if (_dispatchingSameDocumentHashChangeEvent) { 2847 if (_dispatchingSameDocumentHashChangeEvent) {
2871 _dispatchingSameDocumentHashChangeEvent = NO; 2848 _dispatchingSameDocumentHashChangeEvent = NO;
2872 } else { 2849 } else {
2873 web::NavigationItemImpl* item = 2850 web::NavigationItemImpl* item =
2874 static_cast<web::NavigationItemImpl*>([self currentNavItem]); 2851 static_cast<web::NavigationItemImpl*>(self.currentNavItem);
Eugene But (OOO till 7-30) 2017/02/21 23:29:24 Do you need this cast? |currentNavItem| returns we
kkhorimoto 2017/03/02 22:01:11 Removed
2875 DCHECK(item); 2852 DCHECK(item);
2876 item->SetIsCreatedFromHashChange(true); 2853 item->SetIsCreatedFromHashChange(true);
2877 } 2854 }
2878 2855
2879 // Notify the observers. 2856 // Notify the observers.
2880 _webStateImpl->OnUrlHashChanged(); 2857 _webStateImpl->OnUrlHashChanged();
2881 return YES; 2858 return YES;
2882 } 2859 }
2883 2860
2884 - (BOOL)handleWindowHistoryBackMessage:(base::DictionaryValue*)message 2861 - (BOOL)handleWindowHistoryBackMessage:(base::DictionaryValue*)message
(...skipping 27 matching lines...) Expand all
2912 - (BOOL)handleWindowHistoryDidPushStateMessage:(base::DictionaryValue*)message 2889 - (BOOL)handleWindowHistoryDidPushStateMessage:(base::DictionaryValue*)message
2913 context:(NSDictionary*)context { 2890 context:(NSDictionary*)context {
2914 DCHECK(_changingHistoryState); 2891 DCHECK(_changingHistoryState);
2915 _changingHistoryState = NO; 2892 _changingHistoryState = NO;
2916 2893
2917 // If there is a pending entry, a new navigation has been registered but 2894 // If there is a pending entry, a new navigation has been registered but
2918 // hasn't begun loading. Since the pushState message is coming from the 2895 // hasn't begun loading. Since the pushState message is coming from the
2919 // previous page, ignore it and allow the previously registered navigation to 2896 // previous page, ignore it and allow the previously registered navigation to
2920 // continue. This can ocur if a pushState is issued from an anchor tag 2897 // continue. This can ocur if a pushState is issued from an anchor tag
2921 // onClick event, as the click would have already been registered. 2898 // onClick event, as the click would have already been registered.
2922 if ([self sessionController].pendingEntry) 2899 if ([self sessionController].pendingItem)
2923 return NO; 2900 return NO;
2924 2901
2925 std::string pageURL; 2902 std::string pageURL;
2926 std::string baseURL; 2903 std::string baseURL;
2927 if (!message->GetString("pageUrl", &pageURL) || 2904 if (!message->GetString("pageUrl", &pageURL) ||
2928 !message->GetString("baseUrl", &baseURL)) { 2905 !message->GetString("baseUrl", &baseURL)) {
2929 DLOG(WARNING) << "JS message parameter not found: pageUrl or baseUrl"; 2906 DLOG(WARNING) << "JS message parameter not found: pageUrl or baseUrl";
2930 return NO; 2907 return NO;
2931 } 2908 }
2932 GURL pushURL = web::history_state_util::GetHistoryStateChangeUrl( 2909 GURL pushURL = web::history_state_util::GetHistoryStateChangeUrl(
2933 [self currentURL], GURL(baseURL), pageURL); 2910 [self currentURL], GURL(baseURL), pageURL);
2934 // UIWebView seems to choke on unicode characters that haven't been 2911 // UIWebView seems to choke on unicode characters that haven't been
2935 // escaped; escape the URL now so the expected load URL is correct. 2912 // escaped; escape the URL now so the expected load URL is correct.
2936 pushURL = URLEscapedForHistory(pushURL); 2913 pushURL = URLEscapedForHistory(pushURL);
2937 if (!pushURL.is_valid()) 2914 if (!pushURL.is_valid())
2938 return YES; 2915 return YES;
2939 web::NavigationItem* navItem = [self currentNavItem]; 2916 web::NavigationItem* navItem = self.currentNavItem;
2940 // PushState happened before first navigation entry or called when the 2917 // PushState happened before first navigation entry or called when the
2941 // navigation entry does not contain a valid URL. 2918 // navigation entry does not contain a valid URL.
2942 if (!navItem || !navItem->GetURL().is_valid()) 2919 if (!navItem || !navItem->GetURL().is_valid())
2943 return YES; 2920 return YES;
2944 if (!web::history_state_util::IsHistoryStateChangeValid( 2921 if (!web::history_state_util::IsHistoryStateChangeValid(
2945 [self currentNavItem]->GetURL(), pushURL)) { 2922 self.currentNavItem->GetURL(), pushURL)) {
2946 // If the current session entry URL origin still doesn't match pushURL's 2923 // If the current session entry URL origin still doesn't match pushURL's
2947 // origin, ignore the pushState. This can happen if a new URL is loaded 2924 // origin, ignore the pushState. This can happen if a new URL is loaded
2948 // just before the pushState. 2925 // just before the pushState.
2949 return YES; 2926 return YES;
2950 } 2927 }
2951 std::string stateObjectJSON; 2928 std::string stateObjectJSON;
2952 if (!message->GetString("stateObject", &stateObjectJSON)) { 2929 if (!message->GetString("stateObject", &stateObjectJSON)) {
2953 DLOG(WARNING) << "JS message parameter not found: stateObject"; 2930 DLOG(WARNING) << "JS message parameter not found: stateObject";
2954 return NO; 2931 return NO;
2955 } 2932 }
(...skipping 42 matching lines...) Expand 10 before | Expand all | Expand 10 after
2998 } 2975 }
2999 GURL replaceURL = web::history_state_util::GetHistoryStateChangeUrl( 2976 GURL replaceURL = web::history_state_util::GetHistoryStateChangeUrl(
3000 [self currentURL], GURL(baseURL), pageURL); 2977 [self currentURL], GURL(baseURL), pageURL);
3001 // UIWebView seems to choke on unicode characters that haven't been 2978 // UIWebView seems to choke on unicode characters that haven't been
3002 // escaped; escape the URL now so the expected load URL is correct. 2979 // escaped; escape the URL now so the expected load URL is correct.
3003 replaceURL = URLEscapedForHistory(replaceURL); 2980 replaceURL = URLEscapedForHistory(replaceURL);
3004 if (!replaceURL.is_valid()) 2981 if (!replaceURL.is_valid())
3005 return YES; 2982 return YES;
3006 const NavigationManagerImpl& navigationManager = 2983 const NavigationManagerImpl& navigationManager =
3007 _webStateImpl->GetNavigationManagerImpl(); 2984 _webStateImpl->GetNavigationManagerImpl();
3008 web::NavigationItem* navItem = [self currentNavItem]; 2985 web::NavigationItem* navItem = self.currentNavItem;
3009 // ReplaceState happened before first navigation entry or called right 2986 // ReplaceState happened before first navigation entry or called right
3010 // after window.open when the url is empty/not valid. 2987 // after window.open when the url is empty/not valid.
3011 if (!navItem || 2988 if (!navItem ||
3012 (navigationManager.GetItemCount() <= 1 && navItem->GetURL().is_empty())) 2989 (navigationManager.GetItemCount() <= 1 && navItem->GetURL().is_empty()))
3013 return YES; 2990 return YES;
3014 if (!web::history_state_util::IsHistoryStateChangeValid( 2991 if (!web::history_state_util::IsHistoryStateChangeValid(
3015 [self currentNavItem]->GetURL(), replaceURL)) { 2992 self.currentNavItem->GetURL(), replaceURL)) {
3016 // If the current session entry URL origin still doesn't match 2993 // If the current session entry URL origin still doesn't match
3017 // replaceURL's origin, ignore the replaceState. This can happen if a 2994 // replaceURL's origin, ignore the replaceState. This can happen if a
3018 // new URL is loaded just before the replaceState. 2995 // new URL is loaded just before the replaceState.
3019 return YES; 2996 return YES;
3020 } 2997 }
3021 std::string stateObjectJSON; 2998 std::string stateObjectJSON;
3022 if (!message->GetString("stateObject", &stateObjectJSON)) { 2999 if (!message->GetString("stateObject", &stateObjectJSON)) {
3023 DLOG(WARNING) << "JS message parameter not found: stateObject"; 3000 DLOG(WARNING) << "JS message parameter not found: stateObject";
3024 return NO; 3001 return NO;
3025 } 3002 }
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
3061 // we should be distinguishing better, and be clear about the expected 3038 // we should be distinguishing better, and be clear about the expected
3062 // WebDelegate and WCO callbacks in each case. 3039 // WebDelegate and WCO callbacks in each case.
3063 - (void)webPageChanged { 3040 - (void)webPageChanged {
3064 DCHECK(_loadPhase == web::LOAD_REQUESTED); 3041 DCHECK(_loadPhase == web::LOAD_REQUESTED);
3065 3042
3066 const GURL currentURL([self currentURL]); 3043 const GURL currentURL([self currentURL]);
3067 web::Referrer referrer = [self currentReferrer]; 3044 web::Referrer referrer = [self currentReferrer];
3068 // If no referrer was known in advance, record it now. (If there was one, 3045 // If no referrer was known in advance, record it now. (If there was one,
3069 // keep it since it will have a more accurate URL and policy than what can 3046 // keep it since it will have a more accurate URL and policy than what can
3070 // be extracted from the landing page.) 3047 // be extracted from the landing page.)
3071 web::NavigationItem* currentItem = [self currentNavItem]; 3048 web::NavigationItem* currentItem = self.currentNavItem;
3072 if (!currentItem->GetReferrer().url.is_valid()) { 3049 if (!currentItem->GetReferrer().url.is_valid()) {
3073 currentItem->SetReferrer(referrer); 3050 currentItem->SetReferrer(referrer);
3074 } 3051 }
3075 3052
3076 // TODO(stuartmorgan): This shouldn't be called for hash state or 3053 // TODO(stuartmorgan): This shouldn't be called for hash state or
3077 // push/replaceState. 3054 // push/replaceState.
3078 [self resetDocumentSpecificState]; 3055 [self resetDocumentSpecificState];
3079 3056
3080 [self didStartLoadingURL:currentURL updateHistory:YES]; 3057 [self didStartLoadingURL:currentURL updateHistory:YES];
3081 } 3058 }
(...skipping 39 matching lines...) Expand 10 before | Expand all | Expand 10 after
3121 _userInteractionRegistered = flag; 3098 _userInteractionRegistered = flag;
3122 if (flag) 3099 if (flag)
3123 _interactionRegisteredSinceLastURLChange = YES; 3100 _interactionRegisteredSinceLastURLChange = YES;
3124 } 3101 }
3125 3102
3126 - (BOOL)userInteractionRegistered { 3103 - (BOOL)userInteractionRegistered {
3127 return _userInteractionRegistered; 3104 return _userInteractionRegistered;
3128 } 3105 }
3129 3106
3130 - (void)cachePOSTDataForRequest:(NSURLRequest*)request 3107 - (void)cachePOSTDataForRequest:(NSURLRequest*)request
3131 inSessionEntry:(CRWSessionEntry*)currentSessionEntry { 3108 inNavigationItem:(web::NavigationItemImpl*)item {
3132 NSUInteger maxPOSTDataSizeInBytes = 4096; 3109 NSUInteger maxPOSTDataSizeInBytes = 4096;
3133 NSString* cookieHeaderName = @"cookie"; 3110 NSString* cookieHeaderName = @"cookie";
3134 3111
3135 web::NavigationItemImpl* currentItem = currentSessionEntry.navigationItemImpl; 3112 DCHECK(item);
3136 DCHECK(currentItem);
3137 const bool shouldUpdateEntry = 3113 const bool shouldUpdateEntry =
3138 ui::PageTransitionCoreTypeIs(currentItem->GetTransitionType(), 3114 ui::PageTransitionCoreTypeIs(item->GetTransitionType(),
3139 ui::PAGE_TRANSITION_FORM_SUBMIT) && 3115 ui::PAGE_TRANSITION_FORM_SUBMIT) &&
3140 ![request HTTPBodyStream] && // Don't cache streams. 3116 ![request HTTPBodyStream] && // Don't cache streams.
3141 !currentItem->HasPostData() && 3117 !item->HasPostData() &&
3142 currentItem->GetURL() == net::GURLWithNSURL([request URL]); 3118 item->GetURL() == net::GURLWithNSURL([request URL]);
3143 const bool belowSizeCap = 3119 const bool belowSizeCap =
3144 [[request HTTPBody] length] < maxPOSTDataSizeInBytes; 3120 [[request HTTPBody] length] < maxPOSTDataSizeInBytes;
3145 DLOG_IF(WARNING, shouldUpdateEntry && !belowSizeCap) 3121 DLOG_IF(WARNING, shouldUpdateEntry && !belowSizeCap)
3146 << "Data in POST request exceeds the size cap (" << maxPOSTDataSizeInBytes 3122 << "Data in POST request exceeds the size cap (" << maxPOSTDataSizeInBytes
3147 << " bytes), and will not be cached."; 3123 << " bytes), and will not be cached.";
3148 3124
3149 if (shouldUpdateEntry && belowSizeCap) { 3125 if (shouldUpdateEntry && belowSizeCap) {
3150 currentItem->SetPostData([request HTTPBody]); 3126 item->SetPostData([request HTTPBody]);
3151 currentItem->ResetHttpRequestHeaders(); 3127 item->ResetHttpRequestHeaders();
3152 currentItem->AddHttpRequestHeaders([request allHTTPHeaderFields]); 3128 item->AddHttpRequestHeaders([request allHTTPHeaderFields]);
3153 // Don't cache the "Cookie" header. 3129 // Don't cache the "Cookie" header.
3154 // According to NSURLRequest documentation, |-valueForHTTPHeaderField:| is 3130 // According to NSURLRequest documentation, |-valueForHTTPHeaderField:| is
3155 // case insensitive, so it's enough to test the lower case only. 3131 // case insensitive, so it's enough to test the lower case only.
3156 if ([request valueForHTTPHeaderField:cookieHeaderName]) { 3132 if ([request valueForHTTPHeaderField:cookieHeaderName]) {
3157 // Case insensitive search in |headers|. 3133 // Case insensitive search in |headers|.
3158 NSSet* cookieKeys = [currentItem->GetHttpRequestHeaders() 3134 NSSet* cookieKeys = [item->GetHttpRequestHeaders()
3159 keysOfEntriesPassingTest:^(id key, id obj, BOOL* stop) { 3135 keysOfEntriesPassingTest:^(id key, id obj, BOOL* stop) {
3160 NSString* header = (NSString*)key; 3136 NSString* header = (NSString*)key;
3161 const BOOL found = 3137 const BOOL found =
3162 [header caseInsensitiveCompare:cookieHeaderName] == 3138 [header caseInsensitiveCompare:cookieHeaderName] ==
3163 NSOrderedSame; 3139 NSOrderedSame;
3164 *stop = found; 3140 *stop = found;
3165 return found; 3141 return found;
3166 }]; 3142 }];
3167 DCHECK_EQ(1u, [cookieKeys count]); 3143 DCHECK_EQ(1u, [cookieKeys count]);
3168 currentItem->RemoveHttpRequestHeaderForKey([cookieKeys anyObject]); 3144 item->RemoveHttpRequestHeaderForKey([cookieKeys anyObject]);
3169 } 3145 }
3170 } 3146 }
3171 } 3147 }
3172 3148
3173 // TODO(stuartmorgan): This is mostly logic from the original UIWebView delegate 3149 // TODO(stuartmorgan): This is mostly logic from the original UIWebView delegate
3174 // method, which provides less information than the WKWebView version. Audit 3150 // method, which provides less information than the WKWebView version. Audit
3175 // this for things that should be handled in the subclass instead. 3151 // this for things that should be handled in the subclass instead.
3176 - (BOOL)shouldAllowLoadWithNavigationAction:(WKNavigationAction*)action { 3152 - (BOOL)shouldAllowLoadWithNavigationAction:(WKNavigationAction*)action {
3177 NSURLRequest* request = action.request; 3153 NSURLRequest* request = action.request;
3178 GURL requestURL = net::GURLWithNSURL(request.URL); 3154 GURL requestURL = net::GURLWithNSURL(request.URL);
3179 3155
3180 // External application launcher needs |isNavigationTypeLinkActivated| to 3156 // External application launcher needs |isNavigationTypeLinkActivated| to
3181 // decide if the user intended to open the application by clicking on a link. 3157 // decide if the user intended to open the application by clicking on a link.
3182 BOOL isNavigationTypeLinkActivated = 3158 BOOL isNavigationTypeLinkActivated =
3183 action.navigationType == WKNavigationTypeLinkActivated; 3159 action.navigationType == WKNavigationTypeLinkActivated;
3184 3160
3185 // Check if the link navigation leads to a launch of an external app. 3161 // Check if the link navigation leads to a launch of an external app.
3186 // TODO(crbug.com/607780): Revise the logic of allowing external app launch 3162 // TODO(crbug.com/607780): Revise the logic of allowing external app launch
3187 // and move it to externalAppLauncher. 3163 // and move it to externalAppLauncher.
3188 BOOL isOpenInNewTabNavigation = 3164 BOOL isOpenInNewTabNavigation =
3189 !_webStateImpl->GetNavigationManager()->GetItemCount(); 3165 !_webStateImpl->GetNavigationManager()->GetItemCount();
3190 BOOL isPossibleLinkClick = [self isLinkNavigation:action.navigationType]; 3166 BOOL isPossibleLinkClick = [self isLinkNavigation:action.navigationType];
3191 if (isPossibleLinkClick || isOpenInNewTabNavigation || 3167 if (isPossibleLinkClick || isOpenInNewTabNavigation ||
3192 PageTransitionCoreTypeIs([self currentTransition], 3168 PageTransitionCoreTypeIs(self.currentTransition,
3193 ui::PAGE_TRANSITION_AUTO_BOOKMARK)) { 3169 ui::PAGE_TRANSITION_AUTO_BOOKMARK)) {
3194 web::NavigationItem* item = [self currentNavItem]; 3170 web::NavigationItem* item = self.currentNavItem;
3195 const GURL currentNavigationURL = 3171 const GURL currentNavigationURL =
3196 item ? item->GetVirtualURL() : GURL::EmptyGURL(); 3172 item ? item->GetVirtualURL() : GURL::EmptyGURL();
3197 // Check If the URL is handled by a native app. 3173 // Check If the URL is handled by a native app.
3198 if ([self urlTriggersNativeAppLaunch:requestURL 3174 if ([self urlTriggersNativeAppLaunch:requestURL
3199 sourceURL:currentNavigationURL 3175 sourceURL:currentNavigationURL
3200 linkActivatedNavigation:isNavigationTypeLinkActivated]) { 3176 linkActivatedNavigation:isNavigationTypeLinkActivated]) {
3201 // External app has been launched successfully. Stop the current page 3177 // External app has been launched successfully. Stop the current page
3202 // load operation (e.g. notifying all observers) and record the URL so 3178 // load operation (e.g. notifying all observers) and record the URL so
3203 // that errors reported following the 'NO' reply can be safely ignored. 3179 // that errors reported following the 'NO' reply can be safely ignored.
3204 if ([self shouldClosePageOnNativeApplicationLoad]) 3180 if ([self shouldClosePageOnNativeApplicationLoad])
(...skipping 47 matching lines...) Expand 10 before | Expand all | Expand 10 after
3252 // Record the URL so that errors reported following the 'NO' reply can be 3228 // Record the URL so that errors reported following the 'NO' reply can be
3253 // safely ignored. 3229 // safely ignored.
3254 [_openedApplicationURL addObject:request.URL]; 3230 [_openedApplicationURL addObject:request.URL];
3255 if ([self shouldClosePageOnNativeApplicationLoad]) 3231 if ([self shouldClosePageOnNativeApplicationLoad])
3256 [_delegate webPageOrderedClose]; 3232 [_delegate webPageOrderedClose];
3257 } 3233 }
3258 return NO; 3234 return NO;
3259 } 3235 }
3260 3236
3261 if ([[request HTTPMethod] isEqualToString:@"POST"]) { 3237 if ([[request HTTPMethod] isEqualToString:@"POST"]) {
3262 CRWSessionEntry* currentEntry = [self currentSessionEntry]; 3238 web::NavigationItemImpl* item = self.currentNavItem;
3263 // TODO(crbug.com/570699): Remove this check once it's no longer possible to 3239 // TODO(crbug.com/570699): Remove this check once it's no longer possible to
3264 // have no current entries. 3240 // have no current entries.
3265 if (currentEntry) 3241 if (item)
3266 [self cachePOSTDataForRequest:request inSessionEntry:currentEntry]; 3242 [self cachePOSTDataForRequest:request inNavigationItem:item];
3267 } 3243 }
3268 3244
3269 return YES; 3245 return YES;
3270 } 3246 }
3271 3247
3272 - (void)handleLoadError:(NSError*)error inMainFrame:(BOOL)inMainFrame { 3248 - (void)handleLoadError:(NSError*)error inMainFrame:(BOOL)inMainFrame {
3273 NSString* MIMEType = [_pendingNavigationInfo MIMEType]; 3249 NSString* MIMEType = [_pendingNavigationInfo MIMEType];
3274 if ([_passKitDownloader isMIMETypePassKitType:MIMEType]) 3250 if ([_passKitDownloader isMIMETypePassKitType:MIMEType])
3275 return; 3251 return;
3276 if ([error code] == NSURLErrorUnsupportedURL) 3252 if ([error code] == NSURLErrorUnsupportedURL)
(...skipping 378 matching lines...) Expand 10 before | Expand all | Expand 10 after
3655 3631
3656 #pragma mark - 3632 #pragma mark -
3657 #pragma mark Session Information 3633 #pragma mark Session Information
3658 3634
3659 - (CRWSessionController*)sessionController { 3635 - (CRWSessionController*)sessionController {
3660 return _webStateImpl 3636 return _webStateImpl
3661 ? _webStateImpl->GetNavigationManagerImpl().GetSessionController() 3637 ? _webStateImpl->GetNavigationManagerImpl().GetSessionController()
3662 : nil; 3638 : nil;
3663 } 3639 }
3664 3640
3665 - (CRWSessionEntry*)currentSessionEntry { 3641 - (web::NavigationItemImpl*)currentNavItem {
3666 return [[self sessionController] currentEntry];
3667 }
3668
3669 - (web::NavigationItem*)currentNavItem {
3670 // This goes through the legacy Session* interface rather than Navigation* 3642 // This goes through the legacy Session* interface rather than Navigation*
3671 // because it is itself a legacy method that should not exist, and this 3643 // because it is itself a legacy method that should not exist, and this
3672 // avoids needing to add a GetActiveItem to NavigationManager. If/when this 3644 // avoids needing to add a GetActiveItem to NavigationManager. If/when this
3673 // method chain becomes a blocker to eliminating SessionController, the logic 3645 // method chain becomes a blocker to eliminating SessionController, the logic
3674 // can be moved here, using public NavigationManager getters. That's not 3646 // can be moved here, using public NavigationManager getters. That's not
3675 // done now in order to avoid code duplication. 3647 // done now in order to avoid code duplication.
3676 return [[self currentSessionEntry] navigationItem]; 3648 return [[self sessionController] currentItem];
3677 } 3649 }
3678 3650
3679 - (ui::PageTransition)currentTransition { 3651 - (ui::PageTransition)currentTransition {
3680 if ([self currentNavItem]) 3652 if (self.currentNavItem)
3681 return [self currentNavItem]->GetTransitionType(); 3653 return self.currentNavItem->GetTransitionType();
3682 else 3654 else
3683 return ui::PageTransitionFromInt(0); 3655 return ui::PageTransitionFromInt(0);
3684 } 3656 }
3685 3657
3686 - (web::Referrer)currentSessionEntryReferrer { 3658 - (web::Referrer)currentNavItemReferrer {
3687 web::NavigationItem* currentItem = [self currentNavItem]; 3659 web::NavigationItem* currentItem = self.currentNavItem;
3688 return currentItem ? currentItem->GetReferrer() : web::Referrer(); 3660 return currentItem ? currentItem->GetReferrer() : web::Referrer();
3689 } 3661 }
3690 3662
3691 - (NSDictionary*)currentHTTPHeaders { 3663 - (NSDictionary*)currentHTTPHeaders {
3692 DCHECK([self currentSessionEntry]); 3664 web::NavigationItem* currentItem = self.currentNavItem;
3693 return [self currentSessionEntry].navigationItem->GetHttpRequestHeaders(); 3665 return currentItem ? currentItem->GetHttpRequestHeaders() : nil;
3694 } 3666 }
3695 3667
3696 #pragma mark - 3668 #pragma mark -
3697 #pragma mark CRWWebViewScrollViewProxyObserver 3669 #pragma mark CRWWebViewScrollViewProxyObserver
3698 3670
3699 - (void)webViewScrollViewDidZoom: 3671 - (void)webViewScrollViewDidZoom:
3700 (CRWWebViewScrollViewProxy*)webViewScrollViewProxy { 3672 (CRWWebViewScrollViewProxy*)webViewScrollViewProxy {
3701 _pageHasZoomed = YES; 3673 _pageHasZoomed = YES;
3702 3674
3703 base::WeakNSObject<UIScrollView> weakScrollView(self.webScrollView); 3675 base::WeakNSObject<UIScrollView> weakScrollView(self.webScrollView);
3704 [self extractViewportTagWithCompletion:^( 3676 [self extractViewportTagWithCompletion:^(
3705 const web::PageViewportState* viewportState) { 3677 const web::PageViewportState* viewportState) {
3706 if (!weakScrollView) 3678 if (!weakScrollView)
3707 return; 3679 return;
3708 base::scoped_nsobject<UIScrollView> scrollView([weakScrollView retain]); 3680 base::scoped_nsobject<UIScrollView> scrollView([weakScrollView retain]);
3709 if (viewportState && !viewportState->viewport_tag_present() && 3681 if (viewportState && !viewportState->viewport_tag_present() &&
3710 [scrollView minimumZoomScale] == [scrollView maximumZoomScale] && 3682 [scrollView minimumZoomScale] == [scrollView maximumZoomScale] &&
3711 [scrollView zoomScale] > 1.0) { 3683 [scrollView zoomScale] > 1.0) {
3712 UMA_HISTOGRAM_BOOLEAN(kUMAViewportZoomBugCount, true); 3684 UMA_HISTOGRAM_BOOLEAN(kUMAViewportZoomBugCount, true);
3713 } 3685 }
3714 }]; 3686 }];
3715 } 3687 }
3716 3688
3717 - (void)webViewScrollViewDidResetContentSize: 3689 - (void)webViewScrollViewDidResetContentSize:
3718 (CRWWebViewScrollViewProxy*)webViewScrollViewProxy { 3690 (CRWWebViewScrollViewProxy*)webViewScrollViewProxy {
3719 web::NavigationItem* currentItem = [self currentNavItem]; 3691 web::NavigationItem* currentItem = self.currentNavItem;
3720 if (webViewScrollViewProxy.isZooming || _applyingPageState || !currentItem) 3692 if (webViewScrollViewProxy.isZooming || _applyingPageState || !currentItem)
3721 return; 3693 return;
3722 CGSize contentSize = webViewScrollViewProxy.contentSize; 3694 CGSize contentSize = webViewScrollViewProxy.contentSize;
3723 if (contentSize.width < CGRectGetWidth(webViewScrollViewProxy.frame)) { 3695 if (contentSize.width < CGRectGetWidth(webViewScrollViewProxy.frame)) {
3724 // The renderer incorrectly resized the content area. Resetting the scroll 3696 // The renderer incorrectly resized the content area. Resetting the scroll
3725 // view's zoom scale will force a re-rendering. rdar://23963992 3697 // view's zoom scale will force a re-rendering. rdar://23963992
3726 _applyingPageState = YES; 3698 _applyingPageState = YES;
3727 web::PageZoomState zoomState = 3699 web::PageZoomState zoomState =
3728 currentItem->GetPageDisplayState().zoom_state(); 3700 currentItem->GetPageDisplayState().zoom_state();
3729 if (!zoomState.IsValid()) 3701 if (!zoomState.IsValid())
(...skipping 24 matching lines...) Expand all
3754 completionHandler:nil]; 3726 completionHandler:nil];
3755 } 3727 }
3756 3728
3757 #pragma mark - 3729 #pragma mark -
3758 #pragma mark Page State 3730 #pragma mark Page State
3759 3731
3760 - (void)recordStateInHistory { 3732 - (void)recordStateInHistory {
3761 // Only record the state if: 3733 // Only record the state if:
3762 // - the current NavigationItem's URL matches the current URL, and 3734 // - the current NavigationItem's URL matches the current URL, and
3763 // - the user has interacted with the page. 3735 // - the user has interacted with the page.
3764 CRWSessionEntry* current = [self currentSessionEntry]; 3736 web::NavigationItem* item = self.currentNavItem;
3765 if (current && [current navigationItem]->GetURL() == [self currentURL] && 3737 if (item && item->GetURL() == [self currentURL] &&
3766 self.userInteractionRegistered) { 3738 self.userInteractionRegistered) {
3767 [current navigationItem]->SetPageDisplayState(self.pageDisplayState); 3739 item->SetPageDisplayState(self.pageDisplayState);
3768 } 3740 }
3769 } 3741 }
3770 3742
3771 - (void)restoreStateFromHistory { 3743 - (void)restoreStateFromHistory {
3772 CRWSessionEntry* current = [self currentSessionEntry]; 3744 web::NavigationItem* item = self.currentNavItem;
3773 if ([current navigationItem]) 3745 if (item)
3774 self.pageDisplayState = [current navigationItem]->GetPageDisplayState(); 3746 self.pageDisplayState = item->GetPageDisplayState();
3775 } 3747 }
3776 3748
3777 - (web::PageDisplayState)pageDisplayState { 3749 - (web::PageDisplayState)pageDisplayState {
3778 web::PageDisplayState displayState; 3750 web::PageDisplayState displayState;
3779 if (_webView) { 3751 if (_webView) {
3780 CGPoint scrollOffset = [self scrollPosition]; 3752 CGPoint scrollOffset = [self scrollPosition];
3781 displayState.scroll_state().set_offset_x(std::floor(scrollOffset.x)); 3753 displayState.scroll_state().set_offset_x(std::floor(scrollOffset.x));
3782 displayState.scroll_state().set_offset_y(std::floor(scrollOffset.y)); 3754 displayState.scroll_state().set_offset_y(std::floor(scrollOffset.y));
3783 UIScrollView* scrollView = self.webScrollView; 3755 UIScrollView* scrollView = self.webScrollView;
3784 displayState.zoom_state().set_minimum_zoom_scale( 3756 displayState.zoom_state().set_minimum_zoom_scale(
(...skipping 20 matching lines...) Expand all
3805 currentPageDisplayState.scroll_state().offset_y() == 3777 currentPageDisplayState.scroll_state().offset_y() ==
3806 _displayStateOnStartLoading.scroll_state().offset_y() && 3778 _displayStateOnStartLoading.scroll_state().offset_y() &&
3807 !_pageHasZoomed) { 3779 !_pageHasZoomed) {
3808 [self applyPageDisplayState:displayState]; 3780 [self applyPageDisplayState:displayState];
3809 } 3781 }
3810 } 3782 }
3811 } 3783 }
3812 3784
3813 - (void)extractViewportTagWithCompletion:(ViewportStateCompletion)completion { 3785 - (void)extractViewportTagWithCompletion:(ViewportStateCompletion)completion {
3814 DCHECK(completion); 3786 DCHECK(completion);
3815 web::NavigationItem* currentItem = [self currentNavItem]; 3787 web::NavigationItem* currentItem = self.currentNavItem;
3816 if (!currentItem) { 3788 if (!currentItem) {
3817 completion(nullptr); 3789 completion(nullptr);
3818 return; 3790 return;
3819 } 3791 }
3820 NSString* const kViewportContentQuery = 3792 NSString* const kViewportContentQuery =
3821 @"var viewport = document.querySelector('meta[name=\"viewport\"]');" 3793 @"var viewport = document.querySelector('meta[name=\"viewport\"]');"
3822 "viewport ? viewport.content : '';"; 3794 "viewport ? viewport.content : '';";
3823 base::WeakNSObject<CRWWebController> weakSelf(self); 3795 base::WeakNSObject<CRWWebController> weakSelf(self);
3824 int itemID = currentItem->GetUniqueID(); 3796 int itemID = currentItem->GetUniqueID();
3825 [self executeJavaScript:kViewportContentQuery 3797 [self executeJavaScript:kViewportContentQuery
(...skipping 52 matching lines...) Expand 10 before | Expand all | Expand 10 after
3878 userScalable:viewportState->user_scalable()]; 3850 userScalable:viewportState->user_scalable()];
3879 } 3851 }
3880 }]; 3852 }];
3881 } 3853 }
3882 3854
3883 - (void)applyPageDisplayState:(const web::PageDisplayState&)displayState 3855 - (void)applyPageDisplayState:(const web::PageDisplayState&)displayState
3884 userScalable:(BOOL)isUserScalable { 3856 userScalable:(BOOL)isUserScalable {
3885 // Early return if |scrollState| doesn't match the current NavigationItem. 3857 // Early return if |scrollState| doesn't match the current NavigationItem.
3886 // This can sometimes occur in tests, as navigation occurs programmatically 3858 // This can sometimes occur in tests, as navigation occurs programmatically
3887 // and |-applyPageScrollState:| is asynchronous. 3859 // and |-applyPageScrollState:| is asynchronous.
3888 web::NavigationItem* currentItem = [self currentSessionEntry].navigationItem; 3860 web::NavigationItem* currentItem = self.currentNavItem;
3889 if (currentItem && currentItem->GetPageDisplayState() != displayState) 3861 if (currentItem && currentItem->GetPageDisplayState() != displayState)
3890 return; 3862 return;
3891 DCHECK(displayState.IsValid()); 3863 DCHECK(displayState.IsValid());
3892 _applyingPageState = YES; 3864 _applyingPageState = YES;
3893 if (isUserScalable) { 3865 if (isUserScalable) {
3894 [self prepareToApplyWebViewScrollZoomScale]; 3866 [self prepareToApplyWebViewScrollZoomScale];
3895 [self applyWebViewScrollZoomScaleFromZoomState:displayState.zoom_state()]; 3867 [self applyWebViewScrollZoomScaleFromZoomState:displayState.zoom_state()];
3896 [self finishApplyingWebViewScrollZoomScale]; 3868 [self finishApplyingWebViewScrollZoomScale];
3897 } 3869 }
3898 [self applyWebViewScrollOffsetFromScrollState:displayState.scroll_state()]; 3870 [self applyWebViewScrollOffsetFromScrollState:displayState.scroll_state()];
(...skipping 432 matching lines...) Expand 10 before | Expand all | Expand 10 after
4331 _injectedScriptManagers.reset([[NSMutableSet alloc] init]); 4303 _injectedScriptManagers.reset([[NSMutableSet alloc] init]);
4332 [self setDocumentURL:_defaultURL]; 4304 [self setDocumentURL:_defaultURL];
4333 } 4305 }
4334 4306
4335 - (void)removeWebViewAllowingCachedReconstruction:(BOOL)allowCache { 4307 - (void)removeWebViewAllowingCachedReconstruction:(BOOL)allowCache {
4336 if (!_webView) 4308 if (!_webView)
4337 return; 4309 return;
4338 4310
4339 _webStateImpl->CancelDialogs(); 4311 _webStateImpl->CancelDialogs();
4340 4312
4341 web::NavigationItem* item = [self currentNavItem]; 4313 web::NavigationItem* item = self.currentNavItem;
4342 if (allowCache && item) { 4314 if (allowCache && item) {
4343 _expectedReconstructionURL = item->GetVirtualURL(); 4315 _expectedReconstructionURL = item->GetVirtualURL();
4344 } else { 4316 } else {
4345 _expectedReconstructionURL = GURL::EmptyGURL(); 4317 _expectedReconstructionURL = GURL::EmptyGURL();
4346 } 4318 }
4347 4319
4348 [self abortLoad]; 4320 [self abortLoad];
4349 [_webView removeFromSuperview]; 4321 [_webView removeFromSuperview];
4350 [_containerView resetContent]; 4322 [_containerView resetContent];
4351 [self setWebView:nil]; 4323 [self setWebView:nil];
(...skipping 61 matching lines...) Expand 10 before | Expand all | Expand 10 after
4413 } 4385 }
4414 4386
4415 - (void)stopLoading { 4387 - (void)stopLoading {
4416 _stoppedWKNavigation.reset([_navigationStates lastAddedNavigation]); 4388 _stoppedWKNavigation.reset([_navigationStates lastAddedNavigation]);
4417 4389
4418 base::RecordAction(UserMetricsAction("Stop")); 4390 base::RecordAction(UserMetricsAction("Stop"));
4419 // Discard the pending and transient entried before notifying the tab model 4391 // Discard the pending and transient entried before notifying the tab model
4420 // observers of the change via |-abortLoad|. 4392 // observers of the change via |-abortLoad|.
4421 [[self sessionController] discardNonCommittedItems]; 4393 [[self sessionController] discardNonCommittedItems];
4422 [self abortLoad]; 4394 [self abortLoad];
4423 web::NavigationItem* item = [self currentNavItem]; 4395 web::NavigationItem* item = self.currentNavItem;
4424 GURL navigationURL = item ? item->GetVirtualURL() : GURL::EmptyGURL(); 4396 GURL navigationURL = item ? item->GetVirtualURL() : GURL::EmptyGURL();
4425 // If discarding the non-committed entries results in an app-specific URL, 4397 // If discarding the non-committed entries results in an app-specific URL,
4426 // reload it in its native view. 4398 // reload it in its native view.
4427 if (!self.nativeController && 4399 if (!self.nativeController &&
4428 [self shouldLoadURLInNativeView:navigationURL]) { 4400 [self shouldLoadURLInNativeView:navigationURL]) {
4429 [self loadCurrentURLInNativeView]; 4401 [self loadCurrentURLInNativeView];
4430 } 4402 }
4431 } 4403 }
4432 4404
4433 #pragma mark - 4405 #pragma mark -
(...skipping 232 matching lines...) Expand 10 before | Expand all | Expand 10 after
4666 [self abortLoad]; 4638 [self abortLoad];
4667 NavigationManager::WebLoadParams params(webViewURL); 4639 NavigationManager::WebLoadParams params(webViewURL);
4668 [self loadWithParams:params]; 4640 [self loadWithParams:params];
4669 } 4641 }
4670 return; 4642 return;
4671 } else { 4643 } else {
4672 [self registerLoadRequest:webViewURL]; 4644 [self registerLoadRequest:webViewURL];
4673 } 4645 }
4674 } 4646 }
4675 4647
4676 if (![self currentSessionEntry]) { 4648 if (!self.currentNavItem) {
4677 // In this state CRWWebController will crash in |didCommitNavigation:| 4649 // In this state CRWWebController will crash in |didCommitNavigation:|
4678 // (crbug.com/676458). It's unclear if web controller could get into this 4650 // (crbug.com/676458). It's unclear if web controller could get into this
4679 // state but it's one of the guesses for crbug.com/676458 root cause. Report 4651 // state but it's one of the guesses for crbug.com/676458 root cause. Report
4680 // UMA historgam if that happens. 4652 // UMA historgam if that happens.
4681 // TODO(crbug.com/677552): Remove this historgam. 4653 // TODO(crbug.com/677552): Remove this historgam.
4682 UMA_HISTOGRAM_BOOLEAN( 4654 UMA_HISTOGRAM_BOOLEAN(
4683 "WebController." 4655 "WebController."
4684 "StartProvisionalNavigationExitedWithEmptyNavigationManager", 4656 "StartProvisionalNavigationExitedWithEmptyNavigationManager",
4685 true); 4657 true);
4686 } 4658 }
(...skipping 457 matching lines...) Expand 10 before | Expand all | Expand 10 after
5144 if (self.loadPhase != web::LOAD_REQUESTED) 5116 if (self.loadPhase != web::LOAD_REQUESTED)
5145 return NO; 5117 return NO;
5146 5118
5147 web::NavigationItem* pendingItem = 5119 web::NavigationItem* pendingItem =
5148 self.webState->GetNavigationManager()->GetPendingItem(); 5120 self.webState->GetNavigationManager()->GetPendingItem();
5149 return pendingItem && pendingItem->GetURL() == targetURL; 5121 return pendingItem && pendingItem->GetURL() == targetURL;
5150 } 5122 }
5151 5123
5152 - (void)loadRequestForCurrentNavigationItem { 5124 - (void)loadRequestForCurrentNavigationItem {
5153 DCHECK(_webView && !self.nativeController); 5125 DCHECK(_webView && !self.nativeController);
5154 DCHECK([self currentSessionEntry]); 5126 DCHECK(self.currentNavItem);
5155 // If a load is kicked off on a WKWebView with a frame whose size is {0, 0} or 5127 // If a load is kicked off on a WKWebView with a frame whose size is {0, 0} or
5156 // that has a negative dimension for a size, rendering issues occur that 5128 // that has a negative dimension for a size, rendering issues occur that
5157 // manifest in erroneous scrolling and tap handling (crbug.com/574996, 5129 // manifest in erroneous scrolling and tap handling (crbug.com/574996,
5158 // crbug.com/577793). 5130 // crbug.com/577793).
5159 DCHECK_GT(CGRectGetWidth([_webView frame]), 0.0); 5131 DCHECK_GT(CGRectGetWidth([_webView frame]), 0.0);
5160 DCHECK_GT(CGRectGetHeight([_webView frame]), 0.0); 5132 DCHECK_GT(CGRectGetHeight([_webView frame]), 0.0);
5161 5133
5162 web::WKBackForwardListItemHolder* holder = 5134 web::WKBackForwardListItemHolder* holder =
5163 [self currentBackForwardListItemHolder]; 5135 [self currentBackForwardListItemHolder];
5164 BOOL repostedForm = 5136 BOOL repostedForm =
5165 [holder->http_method() isEqual:@"POST"] && 5137 [holder->http_method() isEqual:@"POST"] &&
5166 (holder->navigation_type() == WKNavigationTypeFormResubmitted || 5138 (holder->navigation_type() == WKNavigationTypeFormResubmitted ||
5167 holder->navigation_type() == WKNavigationTypeFormSubmitted); 5139 holder->navigation_type() == WKNavigationTypeFormSubmitted);
5168 web::NavigationItemImpl* currentItem = 5140 web::NavigationItemImpl* currentItem = self.currentNavItem;
5169 [self currentSessionEntry].navigationItemImpl;
5170 NSData* POSTData = currentItem->GetPostData(); 5141 NSData* POSTData = currentItem->GetPostData();
5171 NSMutableURLRequest* request = [self requestForCurrentNavigationItem]; 5142 NSMutableURLRequest* request = [self requestForCurrentNavigationItem];
5172 5143
5173 // If the request has POST data and is not a repost form, configure and 5144 // If the request has POST data and is not a repost form, configure and
5174 // run the POST request. 5145 // run the POST request.
5175 if (POSTData.length && !repostedForm) { 5146 if (POSTData.length && !repostedForm) {
5176 [request setHTTPMethod:@"POST"]; 5147 [request setHTTPMethod:@"POST"];
5177 [request setHTTPBody:POSTData]; 5148 [request setHTTPBody:POSTData];
5178 [request setAllHTTPHeaderFields:[self currentHTTPHeaders]]; 5149 [request setAllHTTPHeaderFields:self.currentHTTPHeaders];
5179 GURL navigationURL = 5150 GURL navigationURL =
5180 currentItem ? currentItem->GetURL() : GURL::EmptyGURL(); 5151 currentItem ? currentItem->GetURL() : GURL::EmptyGURL();
5181 [self registerLoadRequest:navigationURL 5152 [self registerLoadRequest:navigationURL
5182 referrer:[self currentSessionEntryReferrer] 5153 referrer:self.currentNavItemReferrer
5183 transition:[self currentTransition]]; 5154 transition:self.currentTransition];
5184 [self loadPOSTRequest:request]; 5155 [self loadPOSTRequest:request];
5185 return; 5156 return;
5186 } 5157 }
5187 5158
5188 ProceduralBlock defaultNavigationBlock = ^{ 5159 ProceduralBlock defaultNavigationBlock = ^{
5189 web::NavigationItem* item = [self currentNavItem]; 5160 web::NavigationItem* item = self.currentNavItem;
5190 GURL navigationURL = item ? item->GetURL() : GURL::EmptyGURL(); 5161 GURL navigationURL = item ? item->GetURL() : GURL::EmptyGURL();
5191 [self registerLoadRequest:navigationURL 5162 [self registerLoadRequest:navigationURL
5192 referrer:[self currentSessionEntryReferrer] 5163 referrer:self.currentNavItemReferrer
5193 transition:[self currentTransition]]; 5164 transition:self.currentTransition];
5194 [self loadRequest:request]; 5165 [self loadRequest:request];
5195 }; 5166 };
5196 5167
5197 // When navigating via WKBackForwardListItem to pages created or updated by 5168 // When navigating via WKBackForwardListItem to pages created or updated by
5198 // calls to pushState() and replaceState(), sometimes core.js is not injected 5169 // calls to pushState() and replaceState(), sometimes core.js is not injected
5199 // correctly. This means that calling window.history navigation functions 5170 // correctly. This means that calling window.history navigation functions
5200 // will invoke WKWebView's non-overridden implementations, causing a mismatch 5171 // will invoke WKWebView's non-overridden implementations, causing a mismatch
5201 // between the WKBackForwardList and NavigationManager. 5172 // between the WKBackForwardList and NavigationManager.
5202 // TODO(crbug.com/659816): Figure out how to prevent core.js injection flake. 5173 // TODO(crbug.com/659816): Figure out how to prevent core.js injection flake.
5203 if (currentItem->HasStateBeenReplaced() || 5174 if (currentItem->HasStateBeenReplaced() ||
(...skipping 10 matching lines...) Expand all
5214 ![self isBackForwardListItemValid:holder->back_forward_list_item()]) { 5185 ![self isBackForwardListItemValid:holder->back_forward_list_item()]) {
5215 defaultNavigationBlock(); 5186 defaultNavigationBlock();
5216 return; 5187 return;
5217 } 5188 }
5218 5189
5219 ProceduralBlock webViewNavigationBlock = ^{ 5190 ProceduralBlock webViewNavigationBlock = ^{
5220 // If the current navigation URL is the same as the URL of the visible 5191 // If the current navigation URL is the same as the URL of the visible
5221 // page, that means the user requested a reload. |goToBackForwardListItem| 5192 // page, that means the user requested a reload. |goToBackForwardListItem|
5222 // will be a no-op when it is passed the current back forward list item, 5193 // will be a no-op when it is passed the current back forward list item,
5223 // so |reload| must be explicitly called. 5194 // so |reload| must be explicitly called.
5224 web::NavigationItem* item = [self currentNavItem]; 5195 web::NavigationItem* item = self.currentNavItem;
5225 GURL navigationURL = item ? item->GetURL() : GURL::EmptyGURL(); 5196 GURL navigationURL = item ? item->GetURL() : GURL::EmptyGURL();
5226 [self registerLoadRequest:navigationURL 5197 [self registerLoadRequest:navigationURL
5227 referrer:[self currentSessionEntryReferrer] 5198 referrer:self.currentNavItemReferrer
5228 transition:[self currentTransition]]; 5199 transition:self.currentTransition];
5229 if (navigationURL == net::GURLWithNSURL([_webView URL])) { 5200 if (navigationURL == net::GURLWithNSURL([_webView URL])) {
5230 [_navigationStates setState:web::WKNavigationState::REQUESTED 5201 [_navigationStates setState:web::WKNavigationState::REQUESTED
5231 forNavigation:[_webView reload]]; 5202 forNavigation:[_webView reload]];
5232 } else { 5203 } else {
5233 // |didCommitNavigation:| may not be called for fast navigation, so update 5204 // |didCommitNavigation:| may not be called for fast navigation, so update
5234 // the navigation type now as it is already known. 5205 // the navigation type now as it is already known.
5235 holder->set_navigation_type(WKNavigationTypeBackForward); 5206 holder->set_navigation_type(WKNavigationTypeBackForward);
5236 WKNavigation* navigation = 5207 WKNavigation* navigation =
5237 [_webView goToBackForwardListItem:holder->back_forward_list_item()]; 5208 [_webView goToBackForwardListItem:holder->back_forward_list_item()];
5238 [_navigationStates setState:web::WKNavigationState::REQUESTED 5209 [_navigationStates setState:web::WKNavigationState::REQUESTED
(...skipping 79 matching lines...) Expand 10 before | Expand all | Expand 10 after
5318 - (void)simulateLoadRequestWithURL:(const GURL&)URL { 5289 - (void)simulateLoadRequestWithURL:(const GURL&)URL {
5319 _lastRegisteredRequestURL = URL; 5290 _lastRegisteredRequestURL = URL;
5320 _loadPhase = web::LOAD_REQUESTED; 5291 _loadPhase = web::LOAD_REQUESTED;
5321 } 5292 }
5322 5293
5323 - (NSString*)refererFromNavigationAction:(WKNavigationAction*)action { 5294 - (NSString*)refererFromNavigationAction:(WKNavigationAction*)action {
5324 return [action.request valueForHTTPHeaderField:@"Referer"]; 5295 return [action.request valueForHTTPHeaderField:@"Referer"];
5325 } 5296 }
5326 5297
5327 @end 5298 @end
OLDNEW
« no previous file with comments | « ios/web/web_state/ui/crw_web_controller.h ('k') | ios/web/web_state/ui/crw_web_controller_unittest.mm » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698