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

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

Issue 2705673003: Removed CRWSessionEntry from CRWWebController. (Closed)
Patch Set: reintroduced delegate callback Created 3 years, 9 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 401 matching lines...) Expand 10 before | Expand all | Expand 10 after
458 457
459 // Returns YES if the user interacted with the page recently. 458 // Returns YES if the user interacted with the page recently.
460 @property(nonatomic, readonly) BOOL userClickedRecently; 459 @property(nonatomic, readonly) BOOL userClickedRecently;
461 460
462 // Whether or not desktop user agent is used for the currentItem. 461 // Whether or not desktop user agent is used for the currentItem.
463 @property(nonatomic, readonly) BOOL usesDesktopUserAgent; 462 @property(nonatomic, readonly) BOOL usesDesktopUserAgent;
464 463
465 // Facade for Mojo API. 464 // Facade for Mojo API.
466 @property(nonatomic, readonly) web::MojoFacade* mojoFacade; 465 @property(nonatomic, readonly) web::MojoFacade* mojoFacade;
467 466
468 // Updates Desktop User Agent and calls webWillFinishHistoryNavigationFromEntry: 467 // TODO(crbug.com/692871): Remove these functions and replace with more
469 // on CRWWebDelegate. TODO(crbug.com/684098): Remove this method and inline its 468 // appropriate NavigationItem getters.
470 // content. 469 // Returns the navigation item for the current page.
471 - (void)webWillFinishHistoryNavigationFromEntry:(CRWSessionEntry*)fromEntry; 470 @property(nonatomic, readonly) web::NavigationItemImpl* currentNavItem;
472 // Recreates web view if |entry| and |fromEntry| have different value for 471 // Returns the current transition type.
473 // IsOverridingUserAgent() flag. 472 @property(nonatomic, readonly) ui::PageTransition currentTransition;
474 - (void)updateDesktopUserAgentForEntry:(CRWSessionEntry*)entry 473 // Returns the referrer for current navigation item. May be empty.
475 fromEntry:(CRWSessionEntry*)fromEntry; 474 @property(nonatomic, readonly) web::Referrer currentNavItemReferrer;
475 // The HTTP headers associated with the current navigation item. These are nil
476 // unless the request was a POST.
477 @property(nonatomic, readonly) NSDictionary* currentHTTPHeaders;
478
479 // TODO(crbug.com/684098): Remove these methods and inline their content.
480 // Called before finishing a history navigation from |item|.
481 - (void)webWillFinishHistoryNavigationFromItem:(web::NavigationItem*)item;
482 // Requires page reconstruction if |item| has a non-NONE UserAgentType and it
483 // differs from that of |fromItem|.
484 - (void)updateDesktopUserAgentForItem:(web::NavigationItem*)item
485 fromItem:(web::NavigationItem*)fromItem;
486
476 // Removes the container view from the hierarchy and resets the ivar. 487 // Removes the container view from the hierarchy and resets the ivar.
477 - (void)resetContainerView; 488 - (void)resetContainerView;
478 // Called when the web page has changed document and/or URL, and so the page 489 // Called when the web page has changed document and/or URL, and so the page
479 // navigation should be reported to the delegate, and internal state updated to 490 // navigation should be reported to the delegate, and internal state updated to
480 // reflect the fact that the navigation has occurred. 491 // reflect the fact that the navigation has occurred.
481 // TODO(stuartmorgan): The code conflates URL changes and document object 492 // TODO(stuartmorgan): The code conflates URL changes and document object
482 // changes; the two need to be separated and handled differently. 493 // changes; the two need to be separated and handled differently.
483 - (void)webPageChanged; 494 - (void)webPageChanged;
484 // Resets any state that is associated with a specific document object (e.g., 495 // Resets any state that is associated with a specific document object (e.g.,
485 // page interaction tracking). 496 // page interaction tracking).
486 - (void)resetDocumentSpecificState; 497 - (void)resetDocumentSpecificState;
487 // Called when a page (native or web) has actually started loading (i.e., for 498 // Called when a page (native or web) has actually started loading (i.e., for
488 // a web page the document has actually changed), or after the load request has 499 // a web page the document has actually changed), or after the load request has
489 // been registered for a non-document-changing URL change. Updates internal 500 // been registered for a non-document-changing URL change. Updates internal
490 // state not specific to web pages. 501 // state not specific to web pages.
491 - (void)didStartLoadingURL:(const GURL&)URL; 502 - (void)didStartLoadingURL:(const GURL&)URL;
492 // Returns YES if the URL looks like it is one CRWWebController can show. 503 // Returns YES if the URL looks like it is one CRWWebController can show.
493 + (BOOL)webControllerCanShow:(const GURL&)url; 504 + (BOOL)webControllerCanShow:(const GURL&)url;
494 // Clears the currently-displayed transient content view. 505 // Clears the currently-displayed transient content view.
495 - (void)clearTransientContentView; 506 - (void)clearTransientContentView;
496 // Returns a lazily created CRWTouchTrackingRecognizer. 507 // Returns a lazily created CRWTouchTrackingRecognizer.
497 - (CRWTouchTrackingRecognizer*)touchTrackingRecognizer; 508 - (CRWTouchTrackingRecognizer*)touchTrackingRecognizer;
498 // Shows placeholder overlay. 509 // Shows placeholder overlay.
499 - (void)addPlaceholderOverlay; 510 - (void)addPlaceholderOverlay;
500 // Removes placeholder overlay. 511 // Removes placeholder overlay.
501 - (void)removePlaceholderOverlay; 512 - (void)removePlaceholderOverlay;
502 513
503 // Returns the current entry from the underlying session controller.
504 // TODO(stuartmorgan): Audit all calls to these methods; these are just wrappers
505 // around the same logic as GetActiveEntry, so should probably not be used for
506 // the same reason that GetActiveEntry is deprecated. (E.g., page operations
507 // should generally be dealing with the last commited entry, not a pending
508 // entry).
509 - (CRWSessionEntry*)currentSessionEntry;
510 // Returns the navigation item for the current page.
511 - (web::NavigationItem*)currentNavItem;
512 // Returns the current transition type.
513 - (ui::PageTransition)currentTransition;
514 // Returns the referrer for current navigation item. May be empty.
515 - (web::Referrer)currentSessionEntryReferrer;
516 // The HTTP headers associated with the current navigation item. These are nil
517 // unless the request was a POST.
518 - (NSDictionary*)currentHTTPHeaders;
519
520 // Creates a web view if it's not yet created. 514 // Creates a web view if it's not yet created.
521 - (void)ensureWebViewCreated; 515 - (void)ensureWebViewCreated;
522 // Creates a web view with given |config|. No-op if web view is already created. 516 // Creates a web view with given |config|. No-op if web view is already created.
523 - (void)ensureWebViewCreatedWithConfiguration:(WKWebViewConfiguration*)config; 517 - (void)ensureWebViewCreatedWithConfiguration:(WKWebViewConfiguration*)config;
524 // Returns a new autoreleased web view created with given configuration. 518 // Returns a new autoreleased web view created with given configuration.
525 - (WKWebView*)webViewWithConfiguration:(WKWebViewConfiguration*)config; 519 - (WKWebView*)webViewWithConfiguration:(WKWebViewConfiguration*)config;
526 // Sets the value of the webView property, and performs its basic setup. 520 // Sets the value of the webView property, and performs its basic setup.
527 - (void)setWebView:(WKWebView*)webView; 521 - (void)setWebView:(WKWebView*)webView;
528 // Removes webView, optionally tracking the URL of the evicted 522 // Removes webView, optionally tracking the URL of the evicted
529 // page for later cache-based reconstruction. 523 // page for later cache-based reconstruction.
(...skipping 71 matching lines...) Expand 10 before | Expand all | Expand 10 after
601 // Update the appropriate parts of the model and broadcast to the embedder. This 595 // Update the appropriate parts of the model and broadcast to the embedder. This
602 // may be called multiple times and thus must be idempotent. 596 // may be called multiple times and thus must be idempotent.
603 - (void)loadCompleteWithSuccess:(BOOL)loadSuccess; 597 - (void)loadCompleteWithSuccess:(BOOL)loadSuccess;
604 // Called after URL is finished loading and _loadPhase is set to PAGE_LOADED. 598 // Called after URL is finished loading and _loadPhase is set to PAGE_LOADED.
605 - (void)didFinishWithURL:(const GURL&)currentURL loadSuccess:(BOOL)loadSuccess; 599 - (void)didFinishWithURL:(const GURL&)currentURL loadSuccess:(BOOL)loadSuccess;
606 // Navigates forwards or backwards by |delta| pages. No-op if delta is out of 600 // Navigates forwards or backwards by |delta| pages. No-op if delta is out of
607 // bounds. Reloads if delta is 0. 601 // bounds. Reloads if delta is 0.
608 // TODO(crbug.com/661316): Move this method to NavigationManager. 602 // TODO(crbug.com/661316): Move this method to NavigationManager.
609 - (void)goDelta:(int)delta; 603 - (void)goDelta:(int)delta;
610 // Loads a new URL if the current entry is not from a pushState() navigation. 604 // Loads a new URL if the current entry is not from a pushState() navigation.
611 // |fromEntry| is the CRWSessionEntry that was the current entry prior to the 605 // |item| is the NavigationItem that was the current entry prior to the
612 // navigation. 606 // navigation.
613 - (void)finishHistoryNavigationFromEntry:(CRWSessionEntry*)fromEntry; 607 - (void)finishHistoryNavigationFromItem:(web::NavigationItem*)item;
614 // Informs the native controller if web usage is allowed or not. 608 // Informs the native controller if web usage is allowed or not.
615 - (void)setNativeControllerWebUsageEnabled:(BOOL)webUsageEnabled; 609 - (void)setNativeControllerWebUsageEnabled:(BOOL)webUsageEnabled;
616 // Called when web controller receives a new message from the web page. 610 // Called when web controller receives a new message from the web page.
617 - (void)didReceiveScriptMessage:(WKScriptMessage*)message; 611 - (void)didReceiveScriptMessage:(WKScriptMessage*)message;
618 // Returns a new script which wraps |script| with windowID check so |script| is 612 // Returns a new script which wraps |script| with windowID check so |script| is
619 // not evaluated on windowID mismatch. 613 // not evaluated on windowID mismatch.
620 - (NSString*)scriptByAddingWindowIDCheckForScript:(NSString*)script; 614 - (NSString*)scriptByAddingWindowIDCheckForScript:(NSString*)script;
621 // Attempts to handle a script message. Returns YES on success, NO otherwise. 615 // Attempts to handle a script message. Returns YES on success, NO otherwise.
622 - (BOOL)respondToWKScriptMessage:(WKScriptMessage*)scriptMessage; 616 - (BOOL)respondToWKScriptMessage:(WKScriptMessage*)scriptMessage;
623 // Registers load request with empty referrer and link or client redirect 617 // Registers load request with empty referrer and link or client redirect
(...skipping 648 matching lines...) Expand 10 before | Expand all | Expand 10 after
1272 } 1266 }
1273 // Any non-web URL source is trusted. 1267 // Any non-web URL source is trusted.
1274 *trustLevel = web::URLVerificationTrustLevel::kAbsolute; 1268 *trustLevel = web::URLVerificationTrustLevel::kAbsolute;
1275 if (self.nativeController) { 1269 if (self.nativeController) {
1276 if ([self.nativeController respondsToSelector:@selector(virtualURL)]) { 1270 if ([self.nativeController respondsToSelector:@selector(virtualURL)]) {
1277 return [self.nativeController virtualURL]; 1271 return [self.nativeController virtualURL];
1278 } else { 1272 } else {
1279 return [self.nativeController url]; 1273 return [self.nativeController url];
1280 } 1274 }
1281 } 1275 }
1282 web::NavigationItem* item = [self currentNavItem]; 1276 web::NavigationItem* item = self.currentNavItem;
1283 return item ? item->GetVirtualURL() : GURL::EmptyGURL(); 1277 return item ? item->GetVirtualURL() : GURL::EmptyGURL();
1284 } 1278 }
1285 1279
1286 - (WKWebView*)webView { 1280 - (WKWebView*)webView {
1287 return _webView.get(); 1281 return _webView.get();
1288 } 1282 }
1289 1283
1290 - (UIScrollView*)webScrollView { 1284 - (UIScrollView*)webScrollView {
1291 return [_webView scrollView]; 1285 return [_webView scrollView];
1292 } 1286 }
1293 1287
1294 - (GURL)currentURL { 1288 - (GURL)currentURL {
1295 web::URLVerificationTrustLevel trustLevel = 1289 web::URLVerificationTrustLevel trustLevel =
1296 web::URLVerificationTrustLevel::kNone; 1290 web::URLVerificationTrustLevel::kNone;
1297 return [self currentURLWithTrustLevel:&trustLevel]; 1291 return [self currentURLWithTrustLevel:&trustLevel];
1298 } 1292 }
1299 1293
1300 - (web::Referrer)currentReferrer { 1294 - (web::Referrer)currentReferrer {
1301 // Referrer string doesn't include the fragment, so in cases where the 1295 // Referrer string doesn't include the fragment, so in cases where the
1302 // previous URL is equal to the current referrer plus the fragment the 1296 // previous URL is equal to the current referrer plus the fragment the
1303 // previous URL is returned as current referrer. 1297 // previous URL is returned as current referrer.
1304 NSString* referrerString = _currentReferrerString; 1298 NSString* referrerString = _currentReferrerString;
1305 1299
1306 // In case of an error evaluating the JavaScript simply return empty string. 1300 // In case of an error evaluating the JavaScript simply return empty string.
1307 if ([referrerString length] == 0) 1301 if ([referrerString length] == 0)
1308 return web::Referrer(); 1302 return web::Referrer();
1309 1303
1310 web::NavigationItem* item = [self currentNavItem]; 1304 web::NavigationItem* item = self.currentNavItem;
1311 GURL navigationURL = item ? item->GetVirtualURL() : GURL::EmptyGURL(); 1305 GURL navigationURL = item ? item->GetVirtualURL() : GURL::EmptyGURL();
1312 NSString* previousURLString = base::SysUTF8ToNSString(navigationURL.spec()); 1306 NSString* previousURLString = base::SysUTF8ToNSString(navigationURL.spec());
1313 // Check if the referrer is equal to the previous URL minus the hash symbol. 1307 // Check if the referrer is equal to the previous URL minus the hash symbol.
1314 // L'#' is used to convert the char '#' to a unichar. 1308 // L'#' is used to convert the char '#' to a unichar.
1315 if ([previousURLString length] > [referrerString length] && 1309 if ([previousURLString length] > [referrerString length] &&
1316 [previousURLString hasPrefix:referrerString] && 1310 [previousURLString hasPrefix:referrerString] &&
1317 [previousURLString characterAtIndex:[referrerString length]] == L'#') { 1311 [previousURLString characterAtIndex:[referrerString length]] == L'#') {
1318 referrerString = previousURLString; 1312 referrerString = previousURLString;
1319 } 1313 }
1320 // Since referrer is being extracted from the destination page, the correct 1314 // Since referrer is being extracted from the destination page, the correct
(...skipping 54 matching lines...) Expand 10 before | Expand all | Expand 10 after
1375 // |_pendingNavigationInfo| will be nil if the decidePolicy* delegate methods 1369 // |_pendingNavigationInfo| will be nil if the decidePolicy* delegate methods
1376 // were not called. 1370 // were not called.
1377 NSString* HTTPMethod = 1371 NSString* HTTPMethod =
1378 _pendingNavigationInfo 1372 _pendingNavigationInfo
1379 ? [_pendingNavigationInfo HTTPMethod] 1373 ? [_pendingNavigationInfo HTTPMethod]
1380 : [self currentBackForwardListItemHolder]->http_method(); 1374 : [self currentBackForwardListItemHolder]->http_method();
1381 return [HTTPMethod isEqual:@"POST"]; 1375 return [HTTPMethod isEqual:@"POST"];
1382 } 1376 }
1383 1377
1384 - (BOOL)isCurrentNavigationBackForward { 1378 - (BOOL)isCurrentNavigationBackForward {
1385 if (![self currentNavItem]) 1379 if (!self.currentNavItem)
1386 return NO; 1380 return NO;
1387 WKNavigationType currentNavigationType = 1381 WKNavigationType currentNavigationType =
1388 [self currentBackForwardListItemHolder]->navigation_type(); 1382 [self currentBackForwardListItemHolder]->navigation_type();
1389 return currentNavigationType == WKNavigationTypeBackForward; 1383 return currentNavigationType == WKNavigationTypeBackForward;
1390 } 1384 }
1391 1385
1392 - (BOOL)isLinkNavigation:(WKNavigationType)navigationType { 1386 - (BOOL)isLinkNavigation:(WKNavigationType)navigationType {
1393 switch (navigationType) { 1387 switch (navigationType) {
1394 case WKNavigationTypeLinkActivated: 1388 case WKNavigationTypeLinkActivated:
1395 return YES; 1389 return YES;
(...skipping 153 matching lines...) Expand 10 before | Expand all | Expand 10 after
1549 // A new session history entry needs to be created. 1543 // A new session history entry needs to be created.
1550 self.navigationManagerImpl->AddPendingItem( 1544 self.navigationManagerImpl->AddPendingItem(
1551 requestURL, referrer, transition, 1545 requestURL, referrer, transition,
1552 web::NavigationInitiationType::RENDERER_INITIATED); 1546 web::NavigationInitiationType::RENDERER_INITIATED);
1553 } 1547 }
1554 _webStateImpl->SetIsLoading(true); 1548 _webStateImpl->SetIsLoading(true);
1555 _webStateImpl->OnProvisionalNavigationStarted(requestURL); 1549 _webStateImpl->OnProvisionalNavigationStarted(requestURL);
1556 } 1550 }
1557 1551
1558 - (void)updateHTML5HistoryState { 1552 - (void)updateHTML5HistoryState {
1559 web::NavigationItemImpl* currentItem = 1553 web::NavigationItemImpl* currentItem = self.currentNavItem;
1560 static_cast<web::NavigationItemImpl*>([self currentNavItem]);
1561 if (!currentItem) 1554 if (!currentItem)
1562 return; 1555 return;
1563 1556
1564 // Same-document navigations must trigger a popState event. 1557 // Same-document navigations must trigger a popState event.
1565 CRWSessionController* sessionController = self.sessionController; 1558 CRWSessionController* sessionController = self.sessionController;
1566 BOOL sameDocumentNavigation = [sessionController 1559 BOOL sameDocumentNavigation = [sessionController
1567 isSameDocumentNavigationBetweenItem:sessionController.currentItem 1560 isSameDocumentNavigationBetweenItem:sessionController.currentItem
1568 andItem:sessionController.previousItem]; 1561 andItem:sessionController.previousItem];
1569 // WKWebView doesn't send hashchange events for same-document non-BFLI 1562 // WKWebView doesn't send hashchange events for same-document non-BFLI
1570 // navigations, so one must be dispatched manually for hash change same- 1563 // navigations, so one must be dispatched manually for hash change same-
1571 // document navigations. 1564 // document navigations.
1572 web::NavigationItem* previousItem =
1573 self.sessionController.previousEntry.navigationItem;
1574 const GURL URL = currentItem->GetURL(); 1565 const GURL URL = currentItem->GetURL();
1566 web::NavigationItem* previousItem = self.sessionController.previousItem;
1575 const GURL oldURL = previousItem ? previousItem->GetURL() : GURL(); 1567 const GURL oldURL = previousItem ? previousItem->GetURL() : GURL();
1576 BOOL shouldDispatchHashchange = sameDocumentNavigation && previousItem && 1568 BOOL shouldDispatchHashchange = sameDocumentNavigation && previousItem &&
1577 (web::GURLByRemovingRefFromGURL(URL) == 1569 (web::GURLByRemovingRefFromGURL(URL) ==
1578 web::GURLByRemovingRefFromGURL(oldURL)); 1570 web::GURLByRemovingRefFromGURL(oldURL));
1579 // The URL and state object must be set for same-document navigations and 1571 // The URL and state object must be set for same-document navigations and
1580 // NavigationItems that were created or updated by calls to pushState() or 1572 // NavigationItems that were created or updated by calls to pushState() or
1581 // replaceState(). 1573 // replaceState().
1582 BOOL shouldUpdateState = sameDocumentNavigation || 1574 BOOL shouldUpdateState = sameDocumentNavigation ||
1583 currentItem->IsCreatedFromPushState() || 1575 currentItem->IsCreatedFromPushState() ||
1584 currentItem->HasStateBeenReplaced(); 1576 currentItem->HasStateBeenReplaced();
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
1617 1609
1618 - (NSString*)javaScriptToDispatchHashChangeWithOldURL:(const GURL&)oldURL 1610 - (NSString*)javaScriptToDispatchHashChangeWithOldURL:(const GURL&)oldURL
1619 newURL:(const GURL&)newURL { 1611 newURL:(const GURL&)newURL {
1620 return [NSString 1612 return [NSString
1621 stringWithFormat:@"__gCrWeb.dispatchHashchangeEvent(\'%s\', \'%s\');", 1613 stringWithFormat:@"__gCrWeb.dispatchHashchangeEvent(\'%s\', \'%s\');",
1622 oldURL.spec().c_str(), newURL.spec().c_str()]; 1614 oldURL.spec().c_str(), newURL.spec().c_str()];
1623 } 1615 }
1624 1616
1625 - (void)injectHTML5HistoryScriptWithHashChange:(BOOL)dispatchHashChange 1617 - (void)injectHTML5HistoryScriptWithHashChange:(BOOL)dispatchHashChange
1626 sameDocumentNavigation:(BOOL)sameDocumentNavigation { 1618 sameDocumentNavigation:(BOOL)sameDocumentNavigation {
1627 web::NavigationItemImpl* currentItem = 1619 web::NavigationItemImpl* currentItem = self.currentNavItem;
1628 static_cast<web::NavigationItemImpl*>([self currentNavItem]);
1629 if (!currentItem) 1620 if (!currentItem)
1630 return; 1621 return;
1631 1622
1632 const GURL URL = currentItem->GetURL(); 1623 const GURL URL = currentItem->GetURL();
1633 NSString* stateObject = currentItem->GetSerializedStateObject(); 1624 NSString* stateObject = currentItem->GetSerializedStateObject();
1634 NSMutableString* script = [NSMutableString 1625 NSMutableString* script = [NSMutableString
1635 stringWithString:[self javaScriptToReplaceWebViewURL:URL 1626 stringWithString:[self javaScriptToReplaceWebViewURL:URL
1636 stateObjectJSON:stateObject]]; 1627 stateObjectJSON:stateObject]];
1637 if (sameDocumentNavigation) { 1628 if (sameDocumentNavigation) {
1638 [script 1629 [script
1639 appendString:[self javaScriptToDispatchPopStateWithObject:stateObject]]; 1630 appendString:[self javaScriptToDispatchPopStateWithObject:stateObject]];
1640 } 1631 }
1641 if (dispatchHashChange) { 1632 if (dispatchHashChange) {
1642 web::NavigationItemImpl* previousItem = 1633 web::NavigationItemImpl* previousItem = self.sessionController.previousItem;
1643 self.sessionController.previousEntry.navigationItemImpl;
1644 const GURL oldURL = previousItem ? previousItem->GetURL() : GURL(); 1634 const GURL oldURL = previousItem ? previousItem->GetURL() : GURL();
1645 [script appendString:[self javaScriptToDispatchHashChangeWithOldURL:oldURL 1635 [script appendString:[self javaScriptToDispatchHashChangeWithOldURL:oldURL
1646 newURL:URL]]; 1636 newURL:URL]];
1647 } 1637 }
1648 base::WeakNSObject<CRWWebController> weakSelf(self); 1638 base::WeakNSObject<CRWWebController> weakSelf(self);
1649 [self executeJavaScript:script 1639 [self executeJavaScript:script
1650 completionHandler:^(id, NSError*) { 1640 completionHandler:^(id, NSError*) {
1651 if (!weakSelf || weakSelf.get()->_isBeingDestroyed) 1641 if (!weakSelf || weakSelf.get()->_isBeingDestroyed)
1652 return; 1642 return;
1653 base::scoped_nsobject<CRWWebController> strongSelf([weakSelf retain]); 1643 base::scoped_nsobject<CRWWebController> strongSelf([weakSelf retain]);
1654 strongSelf.get()->_URLOnStartLoading = URL; 1644 strongSelf.get()->_URLOnStartLoading = URL;
1655 strongSelf.get()->_lastRegisteredRequestURL = URL; 1645 strongSelf.get()->_lastRegisteredRequestURL = URL;
1656 }]; 1646 }];
1657 } 1647 }
1658 1648
1659 // Load the current URL in a web view, first ensuring the web view is visible. 1649 // Load the current URL in a web view, first ensuring the web view is visible.
1660 - (void)loadCurrentURLInWebView { 1650 - (void)loadCurrentURLInWebView {
1661 // Clear the set of URLs opened in external applications. 1651 // Clear the set of URLs opened in external applications.
1662 _openedApplicationURL.reset([[NSMutableSet alloc] init]); 1652 _openedApplicationURL.reset([[NSMutableSet alloc] init]);
1663 1653
1664 web::NavigationItem* item = [self currentNavItem]; 1654 web::NavigationItem* item = self.currentNavItem;
1665 GURL targetURL = item ? item->GetVirtualURL() : GURL::EmptyGURL(); 1655 GURL targetURL = item ? item->GetVirtualURL() : GURL::EmptyGURL();
1666 // Load the url. The UIWebView delegate callbacks take care of updating the 1656 // Load the url. The UIWebView delegate callbacks take care of updating the
1667 // session history and UI. 1657 // session history and UI.
1668 if (!targetURL.is_valid()) { 1658 if (!targetURL.is_valid()) {
1669 [self didFinishWithURL:targetURL loadSuccess:NO]; 1659 [self didFinishWithURL:targetURL loadSuccess:NO];
1670 return; 1660 return;
1671 } 1661 }
1672 1662
1673 // JavaScript should never be evaluated here. User-entered JS should be 1663 // JavaScript should never be evaluated here. User-entered JS should be
1674 // evaluated via stringByEvaluatingUserJavaScriptFromString. 1664 // evaluated via stringByEvaluatingUserJavaScriptFromString.
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
1709 if ([_pendingNavigationInfo MIMEType]) { 1699 if ([_pendingNavigationInfo MIMEType]) {
1710 self.webStateImpl->SetContentsMimeType( 1700 self.webStateImpl->SetContentsMimeType(
1711 base::SysNSStringToUTF8([_pendingNavigationInfo MIMEType])); 1701 base::SysNSStringToUTF8([_pendingNavigationInfo MIMEType]));
1712 } 1702 }
1713 [self updateCurrentBackForwardListItemHolder]; 1703 [self updateCurrentBackForwardListItemHolder];
1714 1704
1715 _pendingNavigationInfo.reset(); 1705 _pendingNavigationInfo.reset();
1716 } 1706 }
1717 1707
1718 - (NSMutableURLRequest*)requestForCurrentNavigationItem { 1708 - (NSMutableURLRequest*)requestForCurrentNavigationItem {
1719 web::NavigationItem* item = [self currentNavItem]; 1709 web::NavigationItem* item = self.currentNavItem;
1720 const GURL currentNavigationURL = 1710 const GURL currentNavigationURL =
1721 item ? item->GetVirtualURL() : GURL::EmptyGURL(); 1711 item ? item->GetVirtualURL() : GURL::EmptyGURL();
1722 NSMutableURLRequest* request = [NSMutableURLRequest 1712 NSMutableURLRequest* request = [NSMutableURLRequest
1723 requestWithURL:net::NSURLWithGURL(currentNavigationURL)]; 1713 requestWithURL:net::NSURLWithGURL(currentNavigationURL)];
1724 const web::Referrer referrer([self currentSessionEntryReferrer]); 1714 const web::Referrer referrer(self.currentNavItemReferrer);
1725 if (referrer.url.is_valid()) { 1715 if (referrer.url.is_valid()) {
1726 std::string referrerValue = 1716 std::string referrerValue =
1727 web::ReferrerHeaderValueForNavigation(currentNavigationURL, referrer); 1717 web::ReferrerHeaderValueForNavigation(currentNavigationURL, referrer);
1728 if (!referrerValue.empty()) { 1718 if (!referrerValue.empty()) {
1729 [request setValue:base::SysUTF8ToNSString(referrerValue) 1719 [request setValue:base::SysUTF8ToNSString(referrerValue)
1730 forHTTPHeaderField:kReferrerHeaderName]; 1720 forHTTPHeaderField:kReferrerHeaderName];
1731 } 1721 }
1732 } 1722 }
1733 1723
1734 // If there are headers in the current session entry add them to |request|. 1724 // If there are headers in the current session entry add them to |request|.
1735 // Headers that would overwrite fields already present in |request| are 1725 // Headers that would overwrite fields already present in |request| are
1736 // skipped. 1726 // skipped.
1737 NSDictionary* headers = [self currentHTTPHeaders]; 1727 NSDictionary* headers = self.currentHTTPHeaders;
1738 for (NSString* headerName in headers) { 1728 for (NSString* headerName in headers) {
1739 if (![request valueForHTTPHeaderField:headerName]) { 1729 if (![request valueForHTTPHeaderField:headerName]) {
1740 [request setValue:[headers objectForKey:headerName] 1730 [request setValue:[headers objectForKey:headerName]
1741 forHTTPHeaderField:headerName]; 1731 forHTTPHeaderField:headerName];
1742 } 1732 }
1743 } 1733 }
1744 1734
1745 return request; 1735 return request;
1746 } 1736 }
1747 1737
1748 - (web::WKBackForwardListItemHolder*)currentBackForwardListItemHolder { 1738 - (web::WKBackForwardListItemHolder*)currentBackForwardListItemHolder {
1749 web::NavigationItem* item = [self currentSessionEntry].navigationItemImpl; 1739 web::NavigationItem* item = self.currentNavItem;
1750 DCHECK(item); 1740 DCHECK(item);
1751 web::WKBackForwardListItemHolder* holder = 1741 web::WKBackForwardListItemHolder* holder =
1752 web::WKBackForwardListItemHolder::FromNavigationItem(item); 1742 web::WKBackForwardListItemHolder::FromNavigationItem(item);
1753 DCHECK(holder); 1743 DCHECK(holder);
1754 return holder; 1744 return holder;
1755 } 1745 }
1756 1746
1757 - (void)updateCurrentBackForwardListItemHolder { 1747 - (void)updateCurrentBackForwardListItemHolder {
1758 // WebUI pages (which are loaded via loadHTMLString:baseURL:) have no entry 1748 // WebUI pages (which are loaded via loadHTMLString:baseURL:) have no entry
1759 // in the back/forward list, so the current item will still be the previous 1749 // in the back/forward list, so the current item will still be the previous
(...skipping 37 matching lines...) Expand 10 before | Expand all | Expand 10 after
1797 [self setNavigationItemTitle:title]; 1787 [self setNavigationItemTitle:title];
1798 } 1788 }
1799 1789
1800 if ([self.nativeController respondsToSelector:@selector(setDelegate:)]) { 1790 if ([self.nativeController respondsToSelector:@selector(setDelegate:)]) {
1801 [self.nativeController setDelegate:self]; 1791 [self.nativeController setDelegate:self];
1802 } 1792 }
1803 } 1793 }
1804 1794
1805 - (void)loadErrorInNativeView:(NSError*)error { 1795 - (void)loadErrorInNativeView:(NSError*)error {
1806 [self removeWebViewAllowingCachedReconstruction:NO]; 1796 [self removeWebViewAllowingCachedReconstruction:NO];
1807 web::NavigationItem* item = [self currentNavItem]; 1797 web::NavigationItem* item = self.currentNavItem;
1808 const GURL currentURL = item ? item->GetVirtualURL() : GURL::EmptyGURL(); 1798 const GURL currentURL = item ? item->GetVirtualURL() : GURL::EmptyGURL();
1809 1799
1810 if (web::IsWKWebViewSSLCertError(error)) { 1800 if (web::IsWKWebViewSSLCertError(error)) {
1811 // This could happen only if certificate is absent or could not be parsed. 1801 // This could happen only if certificate is absent or could not be parsed.
1812 error = web::NetErrorFromError(error, net::ERR_SSL_SERVER_CERT_BAD_FORMAT); 1802 error = web::NetErrorFromError(error, net::ERR_SSL_SERVER_CERT_BAD_FORMAT);
1813 #if defined(DEBUG) 1803 #if defined(DEBUG)
1814 net::SSLInfo info; 1804 net::SSLInfo info;
1815 web::GetSSLInfoFromWKWebViewSSLCertError(error, &info); 1805 web::GetSSLInfoFromWKWebViewSSLCertError(error, &info);
1816 CHECK(!error.cert); 1806 CHECK(!error.cert);
1817 #endif 1807 #endif
1818 } else { 1808 } else {
1819 error = web::NetErrorFromError(error); 1809 error = web::NetErrorFromError(error);
1820 } 1810 }
1821 1811
1822 BOOL isPost = [self isCurrentNavigationItemPOST]; 1812 BOOL isPost = [self isCurrentNavigationItemPOST];
1823 [self setNativeController:[_nativeProvider controllerForURL:currentURL 1813 [self setNativeController:[_nativeProvider controllerForURL:currentURL
1824 withError:error 1814 withError:error
1825 isPost:isPost]]; 1815 isPost:isPost]];
1826 [self loadNativeViewWithSuccess:NO]; 1816 [self loadNativeViewWithSuccess:NO];
1827 } 1817 }
1828 1818
1829 // Load the current URL in a native controller, retrieved from the native 1819 // Load the current URL in a native controller, retrieved from the native
1830 // provider. Call |loadNativeViewWithSuccess:YES| to load the native controller. 1820 // provider. Call |loadNativeViewWithSuccess:YES| to load the native controller.
1831 - (void)loadCurrentURLInNativeView { 1821 - (void)loadCurrentURLInNativeView {
1832 // Free the web view. 1822 // Free the web view.
1833 [self removeWebViewAllowingCachedReconstruction:NO]; 1823 [self removeWebViewAllowingCachedReconstruction:NO];
1834 1824
1835 web::NavigationItem* item = [self currentNavItem]; 1825 web::NavigationItem* item = self.currentNavItem;
1836 const GURL targetURL = item ? item->GetURL() : GURL::EmptyGURL(); 1826 const GURL targetURL = item ? item->GetURL() : GURL::EmptyGURL();
1837 const web::Referrer referrer; 1827 const web::Referrer referrer;
1838 id<CRWNativeContent> nativeContent = 1828 id<CRWNativeContent> nativeContent =
1839 [_nativeProvider controllerForURL:targetURL webState:self.webState]; 1829 [_nativeProvider controllerForURL:targetURL webState:self.webState];
1840 // Unlike the WebView case, always create a new controller and view. 1830 // Unlike the WebView case, always create a new controller and view.
1841 // TODO(pinkerton): What to do if this does return nil? 1831 // TODO(pinkerton): What to do if this does return nil?
1842 [self setNativeController:nativeContent]; 1832 [self setNativeController:nativeContent];
1843 if ([nativeContent respondsToSelector:@selector(virtualURL)]) { 1833 if ([nativeContent respondsToSelector:@selector(virtualURL)]) {
1844 item->SetVirtualURL([nativeContent virtualURL]); 1834 item->SetVirtualURL([nativeContent virtualURL]);
1845 } 1835 }
1846 1836
1847 [self registerLoadRequest:targetURL 1837 [self registerLoadRequest:targetURL
1848 referrer:referrer 1838 referrer:referrer
1849 transition:[self currentTransition]]; 1839 transition:self.currentTransition];
1850 [self loadNativeViewWithSuccess:YES]; 1840 [self loadNativeViewWithSuccess:YES];
1851 } 1841 }
1852 1842
1853 - (void)loadWithParams:(const NavigationManager::WebLoadParams&)originalParams { 1843 - (void)loadWithParams:(const NavigationManager::WebLoadParams&)originalParams {
1854 // Make a copy of |params|, as some of the delegate methods may modify it. 1844 // Make a copy of |params|, as some of the delegate methods may modify it.
1855 NavigationManager::WebLoadParams params(originalParams); 1845 NavigationManager::WebLoadParams params(originalParams);
1856 1846
1857 // Initiating a navigation from the UI, record the current page state before 1847 // Initiating a navigation from the UI, record the current page state before
1858 // the new page loads. Don't record for back/forward, as the current entry 1848 // the new page loads. Don't record for back/forward, as the current entry
1859 // has already been moved to the next entry in the history. Do, however, 1849 // has already been moved to the next entry in the history. Do, however,
(...skipping 18 matching lines...) Expand all
1878 } else { 1868 } else {
1879 // Clear transient view before making any changes to history and navigation 1869 // Clear transient view before making any changes to history and navigation
1880 // manager. TODO(stuartmorgan): Drive Transient Item clearing from 1870 // manager. TODO(stuartmorgan): Drive Transient Item clearing from
1881 // navigation system, rather than from WebController. 1871 // navigation system, rather than from WebController.
1882 [self clearTransientContentView]; 1872 [self clearTransientContentView];
1883 1873
1884 // TODO(stuartmorgan): Why doesn't recordStateInHistory get called for 1874 // TODO(stuartmorgan): Why doesn't recordStateInHistory get called for
1885 // forward/back transitions? 1875 // forward/back transitions?
1886 [self recordStateInHistory]; 1876 [self recordStateInHistory];
1887 1877
1888 if (!self.currentSessionEntry) 1878 if (!self.currentNavItem)
1889 initialNavigation = YES; 1879 initialNavigation = YES;
1890 1880
1891 web::NavigationInitiationType navigationInitiationType = 1881 web::NavigationInitiationType navigationInitiationType =
1892 params.is_renderer_initiated 1882 params.is_renderer_initiated
1893 ? web::NavigationInitiationType::RENDERER_INITIATED 1883 ? web::NavigationInitiationType::RENDERER_INITIATED
1894 : web::NavigationInitiationType::USER_INITIATED; 1884 : web::NavigationInitiationType::USER_INITIATED;
1895 self.navigationManagerImpl->AddPendingItem( 1885 self.navigationManagerImpl->AddPendingItem(
1896 navUrl, params.referrer, transition, navigationInitiationType); 1886 navUrl, params.referrer, transition, navigationInitiationType);
1897 1887
1898 web::NavigationItemImpl* addedItem = 1888 web::NavigationItemImpl* addedItem = self.currentNavItem;
1899 [self currentSessionEntry].navigationItemImpl;
1900 DCHECK(addedItem); 1889 DCHECK(addedItem);
1901 if (params.extra_headers) 1890 if (params.extra_headers)
1902 addedItem->AddHttpRequestHeaders(params.extra_headers); 1891 addedItem->AddHttpRequestHeaders(params.extra_headers);
1903 if (params.post_data) { 1892 if (params.post_data) {
1904 DCHECK([addedItem->GetHttpRequestHeaders() objectForKey:@"Content-Type"]) 1893 DCHECK([addedItem->GetHttpRequestHeaders() objectForKey:@"Content-Type"])
1905 << "Post data should have an associated content type"; 1894 << "Post data should have an associated content type";
1906 addedItem->SetPostData(params.post_data); 1895 addedItem->SetPostData(params.post_data);
1907 addedItem->SetShouldSkipRepostFormConfirmation(true); 1896 addedItem->SetShouldSkipRepostFormConfirmation(true);
1908 } 1897 }
1909 } 1898 }
(...skipping 15 matching lines...) Expand all
1925 1914
1926 // Abort any outstanding page load. This ensures the delegate gets informed 1915 // Abort any outstanding page load. This ensures the delegate gets informed
1927 // about the outgoing page, and further messages from the page are suppressed. 1916 // about the outgoing page, and further messages from the page are suppressed.
1928 if (_loadPhase != web::PAGE_LOADED) 1917 if (_loadPhase != web::PAGE_LOADED)
1929 [self abortLoad]; 1918 [self abortLoad];
1930 1919
1931 DCHECK(!_isHalted); 1920 DCHECK(!_isHalted);
1932 // Remove the transient content view. 1921 // Remove the transient content view.
1933 [self clearTransientContentView]; 1922 [self clearTransientContentView];
1934 1923
1935 web::NavigationItem* item = [self currentNavItem]; 1924 web::NavigationItem* item = self.currentNavItem;
1936 const GURL currentURL = item ? item->GetURL() : GURL::EmptyGURL(); 1925 const GURL currentURL = item ? item->GetURL() : GURL::EmptyGURL();
1937 // If it's a chrome URL, but not a native one, create the WebUI instance. 1926 // If it's a chrome URL, but not a native one, create the WebUI instance.
1938 if (web::GetWebClient()->IsAppSpecificURL(currentURL) && 1927 if (web::GetWebClient()->IsAppSpecificURL(currentURL) &&
1939 ![_nativeProvider hasControllerForURL:currentURL]) { 1928 ![_nativeProvider hasControllerForURL:currentURL]) {
1940 if (!(item->GetTransitionType() & ui::PAGE_TRANSITION_TYPED || 1929 if (!(item->GetTransitionType() & ui::PAGE_TRANSITION_TYPED ||
1941 item->GetTransitionType() & ui::PAGE_TRANSITION_AUTO_BOOKMARK) && 1930 item->GetTransitionType() & ui::PAGE_TRANSITION_AUTO_BOOKMARK) &&
1942 self.sessionController.openedByDOM) { 1931 self.sessionController.openedByDOM) {
1943 // WebUI URLs can not be opened by DOM to prevent cross-site scripting as 1932 // WebUI URLs can not be opened by DOM to prevent cross-site scripting as
1944 // they have increased power. WebUI URLs may only be opened when the user 1933 // they have increased power. WebUI URLs may only be opened when the user
1945 // types in the URL or use bookmarks. 1934 // types in the URL or use bookmarks.
(...skipping 52 matching lines...) Expand 10 before | Expand all | Expand 10 after
1998 _containerView.get().frame = containerViewFrame; 1987 _containerView.get().frame = containerViewFrame;
1999 DCHECK(!CGRectIsEmpty(_containerView.get().frame)); 1988 DCHECK(!CGRectIsEmpty(_containerView.get().frame));
2000 1989
2001 // TODO(crbug.com/691116): Remove this workaround once tests are no longer 1990 // TODO(crbug.com/691116): Remove this workaround once tests are no longer
2002 // dependent upon this accessibility ID. 1991 // dependent upon this accessibility ID.
2003 if (!base::ios::IsRunningOnIOS10OrLater()) 1992 if (!base::ios::IsRunningOnIOS10OrLater())
2004 [_containerView setAccessibilityIdentifier:@"Container View"]; 1993 [_containerView setAccessibilityIdentifier:@"Container View"];
2005 1994
2006 [_containerView addGestureRecognizer:[self touchTrackingRecognizer]]; 1995 [_containerView addGestureRecognizer:[self touchTrackingRecognizer]];
2007 // Is |currentUrl| a web scheme or native chrome scheme. 1996 // Is |currentUrl| a web scheme or native chrome scheme.
2008 web::NavigationItem* item = [self currentNavItem]; 1997 web::NavigationItem* item = self.currentNavItem;
2009 const GURL currentNavigationURL = 1998 const GURL currentNavigationURL =
2010 item ? item->GetVirtualURL() : GURL::EmptyGURL(); 1999 item ? item->GetVirtualURL() : GURL::EmptyGURL();
2011 BOOL isChromeScheme = 2000 BOOL isChromeScheme =
2012 web::GetWebClient()->IsAppSpecificURL(currentNavigationURL); 2001 web::GetWebClient()->IsAppSpecificURL(currentNavigationURL);
2013 2002
2014 // Don't immediately load the web page if in overlay mode. Always load if 2003 // Don't immediately load the web page if in overlay mode. Always load if
2015 // native. 2004 // native.
2016 if (isChromeScheme || !_overlayPreviewMode) { 2005 if (isChromeScheme || !_overlayPreviewMode) {
2017 // TODO(jimblackler): end the practice of calling |loadCurrentURL| when it 2006 // TODO(jimblackler): end the practice of calling |loadCurrentURL| when it
2018 // is possible there is no current URL. If the call performs necessary 2007 // is possible there is no current URL. If the call performs necessary
(...skipping 93 matching lines...) Expand 10 before | Expand all | Expand 10 after
2112 } 2101 }
2113 [_delegate webLoadCancelled:_URLOnStartLoading]; 2102 [_delegate webLoadCancelled:_URLOnStartLoading];
2114 break; 2103 break;
2115 case web::PAGE_LOADED: 2104 case web::PAGE_LOADED:
2116 break; 2105 break;
2117 } 2106 }
2118 } 2107 }
2119 2108
2120 - (void)goToItemAtIndex:(int)index { 2109 - (void)goToItemAtIndex:(int)index {
2121 CRWSessionController* sessionController = self.sessionController; 2110 CRWSessionController* sessionController = self.sessionController;
2122 NSArray* entries = sessionController.entries; 2111 web::NavigationItemList items = sessionController.items;
2123 if (index < 0 || index >= static_cast<int>(entries.count)) { 2112 if (index < 0 || index >= static_cast<int>(items.size())) {
2124 NOTREACHED(); 2113 NOTREACHED();
2125 return; 2114 return;
2126 } 2115 }
2127 2116
2128 if (!_webStateImpl->IsShowingWebInterstitial()) 2117 if (!_webStateImpl->IsShowingWebInterstitial())
2129 [self recordStateInHistory]; 2118 [self recordStateInHistory];
2130 CRWSessionEntry* fromEntry = sessionController.currentEntry; 2119 web::NavigationItem* fromItem = sessionController.currentItem;
2131 CRWSessionEntry* toEntry = entries[index]; 2120 web::NavigationItem* toItem = items[index];
2132 2121
2133 NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults]; 2122 NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
2134 if (![userDefaults boolForKey:@"PendingIndexNavigationDisabled"]) { 2123 if (![userDefaults boolForKey:@"PendingIndexNavigationDisabled"]) {
2135 [self clearTransientContentView]; 2124 [self clearTransientContentView];
2136 [self updateDesktopUserAgentForEntry:toEntry fromEntry:fromEntry];
2137 2125
2138 BOOL sameDocumentNavigation = [sessionController 2126 // Update the user agent before attempting the navigation.
2139 isSameDocumentNavigationBetweenItem:fromEntry.navigationItem 2127 [self updateDesktopUserAgentForItem:toItem fromItem:fromItem];
2140 andItem:toEntry.navigationItem]; 2128
2129 BOOL sameDocumentNavigation =
2130 [sessionController isSameDocumentNavigationBetweenItem:fromItem
2131 andItem:toItem];
2141 if (sameDocumentNavigation) { 2132 if (sameDocumentNavigation) {
2142 [sessionController goToItemAtIndex:index]; 2133 [sessionController goToItemAtIndex:index];
2143 [self updateHTML5HistoryState]; 2134 [self updateHTML5HistoryState];
2144 } else { 2135 } else {
2145 [sessionController discardNonCommittedItems]; 2136 [sessionController discardNonCommittedItems];
2146 [sessionController setPendingItemIndex:index]; 2137 [sessionController setPendingItemIndex:index];
2147 2138
2148 web::NavigationItemImpl* pendingItem = 2139 web::NavigationItemImpl* pendingItem = sessionController.pendingItem;
2149 sessionController.pendingEntry.navigationItemImpl;
2150 pendingItem->SetTransitionType(ui::PageTransitionFromInt( 2140 pendingItem->SetTransitionType(ui::PageTransitionFromInt(
2151 pendingItem->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK)); 2141 pendingItem->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
2152 2142
2153 [self loadCurrentURL]; 2143 [self loadCurrentURL];
2154 } 2144 }
2155 } else { 2145 } else {
2156 [sessionController goToItemAtIndex:index]; 2146 [sessionController goToItemAtIndex:index];
2157 if (fromEntry) 2147 if (fromItem)
2158 [self finishHistoryNavigationFromEntry:fromEntry]; 2148 [self finishHistoryNavigationFromItem:fromItem];
2159 } 2149 }
2160 } 2150 }
2161 2151
2162 - (BOOL)isLoaded { 2152 - (BOOL)isLoaded {
2163 return _loadPhase == web::PAGE_LOADED; 2153 return _loadPhase == web::PAGE_LOADED;
2164 } 2154 }
2165 2155
2166 - (void)didFinishNavigation { 2156 - (void)didFinishNavigation {
2167 // This can be called at multiple times after the document has loaded. Do 2157 // This can be called at multiple times after the document has loaded. Do
2168 // nothing if the document has already loaded. 2158 // nothing if the document has already loaded.
(...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after
2212 // WKWebView will cache the WebUI HTML in the previous WKBackForwardListItem 2202 // WKWebView will cache the WebUI HTML in the previous WKBackForwardListItem
2213 // since it's loaded via |-loadHTML:forURL:| instead of an NSURLRequest. As a 2203 // since it's loaded via |-loadHTML:forURL:| instead of an NSURLRequest. As a
2214 // result, the WebUI's HTML and URL will be loaded when navigating to that 2204 // result, the WebUI's HTML and URL will be loaded when navigating to that
2215 // WKBackForwardListItem, causing a mismatch between the visible content and 2205 // WKBackForwardListItem, causing a mismatch between the visible content and
2216 // the visible URL (WebUI page will be visible, but URL will be the previous 2206 // the visible URL (WebUI page will be visible, but URL will be the previous
2217 // page's URL). To prevent this potential URL spoofing vulnerability, reset 2207 // page's URL). To prevent this potential URL spoofing vulnerability, reset
2218 // the previous NavigationItem's WKBackForwardListItem to force loading via 2208 // the previous NavigationItem's WKBackForwardListItem to force loading via
2219 // NSURLRequest. 2209 // NSURLRequest.
2220 if (_webUIManager) { 2210 if (_webUIManager) {
2221 web::NavigationItem* lastNavigationItem = 2211 web::NavigationItem* lastNavigationItem =
2222 self.sessionController.previousEntry.navigationItem; 2212 self.sessionController.previousItem;
2223 if (lastNavigationItem) { 2213 if (lastNavigationItem) {
2224 web::WKBackForwardListItemHolder* holder = 2214 web::WKBackForwardListItemHolder* holder =
2225 web::WKBackForwardListItemHolder::FromNavigationItem( 2215 web::WKBackForwardListItemHolder::FromNavigationItem(
2226 lastNavigationItem); 2216 lastNavigationItem);
2227 DCHECK(holder); 2217 DCHECK(holder);
2228 holder->set_back_forward_list_item(nil); 2218 holder->set_back_forward_list_item(nil);
2229 } 2219 }
2230 } 2220 }
2231 2221
2232 [self restoreStateFromHistory]; 2222 [self restoreStateFromHistory];
2233 _webStateImpl->SetIsLoading(false); 2223 _webStateImpl->SetIsLoading(false);
2234 _webStateImpl->OnPageLoaded(currentURL, loadSuccess); 2224 _webStateImpl->OnPageLoaded(currentURL, loadSuccess);
2235 } 2225 }
2236 2226
2237 - (void)goDelta:(int)delta { 2227 - (void)goDelta:(int)delta {
2238 if (_isBeingDestroyed) 2228 if (_isBeingDestroyed)
2239 return; 2229 return;
2240 2230
2241 if (delta == 0) { 2231 if (delta == 0) {
2242 [self reload]; 2232 [self reload];
2243 return; 2233 return;
2244 } 2234 }
2245 2235
2246 if (self.navigationManagerImpl->CanGoToOffset(delta)) { 2236 if (self.navigationManagerImpl->CanGoToOffset(delta)) {
2247 NSInteger index = self.navigationManagerImpl->GetIndexForOffset(delta); 2237 NSInteger index = self.navigationManagerImpl->GetIndexForOffset(delta);
2248 [self goToItemAtIndex:index]; 2238 [self goToItemAtIndex:index];
2249 } 2239 }
2250 } 2240 }
2251 2241
2252 - (void)finishHistoryNavigationFromEntry:(CRWSessionEntry*)fromEntry { 2242 - (void)finishHistoryNavigationFromItem:(web::NavigationItem*)item {
2253 [self webWillFinishHistoryNavigationFromEntry:fromEntry]; 2243 [self webWillFinishHistoryNavigationFromItem:item];
2254 2244
2255 // Only load the new URL if it has a different document than |fromEntry| to 2245 // Only load the new URL if it has a different document than |fromEntry| to
2256 // prevent extra page loads from NavigationItems created by hash changes or 2246 // prevent extra page loads from NavigationItems created by hash changes or
2257 // calls to window.history.pushState(). 2247 // calls to window.history.pushState().
2258 BOOL shouldLoadURL = ![self.sessionController 2248 BOOL shouldLoadURL = ![self.sessionController
2259 isSameDocumentNavigationBetweenItem:fromEntry.navigationItem 2249 isSameDocumentNavigationBetweenItem:item
2260 andItem:self.currentNavItem]; 2250 andItem:self.currentNavItem];
2261 web::NavigationItemImpl* currentItem = 2251 web::NavigationItem* currentItem = self.currentNavItem;
2262 self.currentSessionEntry.navigationItemImpl; 2252 GURL endURL = [self URLForHistoryNavigationFromItem:item toItem:currentItem];
2263 GURL endURL = [self URLForHistoryNavigationFromItem:fromEntry.navigationItem
2264 toItem:currentItem];
2265 if (shouldLoadURL) { 2253 if (shouldLoadURL) {
2266 ui::PageTransition transition = ui::PageTransitionFromInt( 2254 ui::PageTransition transition = ui::PageTransitionFromInt(
2267 ui::PAGE_TRANSITION_RELOAD | ui::PAGE_TRANSITION_FORWARD_BACK); 2255 ui::PAGE_TRANSITION_RELOAD | ui::PAGE_TRANSITION_FORWARD_BACK);
2268 2256
2269 NavigationManager::WebLoadParams params(endURL); 2257 NavigationManager::WebLoadParams params(endURL);
2270 if (currentItem) { 2258 if (currentItem) {
2271 params.referrer = currentItem->GetReferrer(); 2259 params.referrer = currentItem->GetReferrer();
2272 } 2260 }
2273 params.transition_type = transition; 2261 params.transition_type = transition;
2274 [self loadWithParams:params]; 2262 [self loadWithParams:params];
(...skipping 49 matching lines...) Expand 10 before | Expand all | Expand 10 after
2324 // no user interaction with the page since the web view was created, or if 2312 // no user interaction with the page since the web view was created, or if
2325 // the page has no navigation items, as occurs when an App Store link is 2313 // the page has no navigation items, as occurs when an App Store link is
2326 // opened from another application. 2314 // opened from another application.
2327 BOOL rendererInitiatedWithoutInteraction = 2315 BOOL rendererInitiatedWithoutInteraction =
2328 self.sessionController.openedByDOM && !_userInteractedWithWebController; 2316 self.sessionController.openedByDOM && !_userInteractedWithWebController;
2329 BOOL noNavigationItems = !(self.navigationManagerImpl->GetItemCount()); 2317 BOOL noNavigationItems = !(self.navigationManagerImpl->GetItemCount());
2330 return rendererInitiatedWithoutInteraction || noNavigationItems; 2318 return rendererInitiatedWithoutInteraction || noNavigationItems;
2331 } 2319 }
2332 2320
2333 - (BOOL)usesDesktopUserAgent { 2321 - (BOOL)usesDesktopUserAgent {
2334 web::NavigationItem* item = [self currentNavItem]; 2322 web::NavigationItem* item = self.currentNavItem;
2335 return item && item->GetUserAgentType() == web::UserAgentType::DESKTOP; 2323 return item && item->GetUserAgentType() == web::UserAgentType::DESKTOP;
2336 } 2324 }
2337 2325
2338 - (web::MojoFacade*)mojoFacade { 2326 - (web::MojoFacade*)mojoFacade {
2339 if (!_mojoFacade) { 2327 if (!_mojoFacade) {
2340 service_manager::mojom::InterfaceProvider* interfaceProvider = 2328 service_manager::mojom::InterfaceProvider* interfaceProvider =
2341 _webStateImpl->GetMojoInterfaceRegistry(); 2329 _webStateImpl->GetMojoInterfaceRegistry();
2342 _mojoFacade.reset(new web::MojoFacade(interfaceProvider, self)); 2330 _mojoFacade.reset(new web::MojoFacade(interfaceProvider, self));
2343 } 2331 }
2344 return _mojoFacade.get(); 2332 return _mojoFacade.get();
(...skipping 19 matching lines...) Expand all
2364 [delegate webController:strongSelf didLoadPassKitObject:data]; 2352 [delegate webController:strongSelf didLoadPassKitObject:data];
2365 } 2353 }
2366 }; 2354 };
2367 web::BrowserState* browserState = self.webStateImpl->GetBrowserState(); 2355 web::BrowserState* browserState = self.webStateImpl->GetBrowserState();
2368 _passKitDownloader.reset([[CRWPassKitDownloader alloc] 2356 _passKitDownloader.reset([[CRWPassKitDownloader alloc]
2369 initWithContextGetter:browserState->GetRequestContext() 2357 initWithContextGetter:browserState->GetRequestContext()
2370 completionHandler:passKitCompletion]); 2358 completionHandler:passKitCompletion]);
2371 return _passKitDownloader.get(); 2359 return _passKitDownloader.get();
2372 } 2360 }
2373 2361
2374 - (void)webWillFinishHistoryNavigationFromEntry:(CRWSessionEntry*)fromEntry { 2362 - (void)webWillFinishHistoryNavigationFromItem:(web::NavigationItem*)item {
2375 DCHECK(fromEntry); 2363 DCHECK(item);
2376 [self updateDesktopUserAgentForEntry:self.currentSessionEntry 2364 [self updateDesktopUserAgentForItem:self.currentNavItem fromItem:item];
2377 fromEntry:fromEntry]; 2365 [_delegate webWillFinishHistoryNavigation];
2378 [_delegate webWillFinishHistoryNavigationFromEntry:fromEntry];
2379 } 2366 }
2380 2367
2381 - (void)updateDesktopUserAgentForEntry:(CRWSessionEntry*)entry 2368 - (void)updateDesktopUserAgentForItem:(web::NavigationItem*)item
2382 fromEntry:(CRWSessionEntry*)fromEntry { 2369 fromItem:(web::NavigationItem*)fromItem {
2383 web::NavigationItemImpl* item = entry.navigationItemImpl; 2370 if (!item || !fromItem)
2384 web::NavigationItemImpl* fromItem = fromEntry.navigationItemImpl; 2371 return;
2385 web::UserAgentType itemUserAgentType = item->GetUserAgentType(); 2372 web::UserAgentType itemUserAgentType = item->GetUserAgentType();
2386 if (!item || !fromItem || itemUserAgentType == web::UserAgentType::NONE) 2373 if (itemUserAgentType == web::UserAgentType::NONE)
2387 return; 2374 return;
2388 if (itemUserAgentType != fromItem->GetUserAgentType()) 2375 if (itemUserAgentType != fromItem->GetUserAgentType())
2389 [self requirePageReconstruction]; 2376 [self requirePageReconstruction];
2390 } 2377 }
2391 2378
2392 #pragma mark - 2379 #pragma mark -
2393 #pragma mark CRWWebControllerContainerViewDelegate 2380 #pragma mark CRWWebControllerContainerViewDelegate
2394 2381
2395 - (CRWWebViewProxyImpl*)contentViewProxyForContainerView: 2382 - (CRWWebViewProxyImpl*)contentViewProxyForContainerView:
2396 (CRWWebControllerContainerView*)containerView { 2383 (CRWWebControllerContainerView*)containerView {
(...skipping 432 matching lines...) Expand 10 before | Expand all | Expand 10 after
2829 // for the new page manually. 2816 // for the new page manually.
2830 [self executeJavaScript:@"__gCrWeb.sendFaviconsToHost();" 2817 [self executeJavaScript:@"__gCrWeb.sendFaviconsToHost();"
2831 completionHandler:nil]; 2818 completionHandler:nil];
2832 2819
2833 // Record that the current NavigationItem was created by a hash change, but 2820 // Record that the current NavigationItem was created by a hash change, but
2834 // ignore hashchange events that are manually dispatched for same-document 2821 // ignore hashchange events that are manually dispatched for same-document
2835 // navigations. 2822 // navigations.
2836 if (_dispatchingSameDocumentHashChangeEvent) { 2823 if (_dispatchingSameDocumentHashChangeEvent) {
2837 _dispatchingSameDocumentHashChangeEvent = NO; 2824 _dispatchingSameDocumentHashChangeEvent = NO;
2838 } else { 2825 } else {
2839 web::NavigationItemImpl* item = 2826 web::NavigationItemImpl* item = self.currentNavItem;
2840 static_cast<web::NavigationItemImpl*>([self currentNavItem]);
2841 DCHECK(item); 2827 DCHECK(item);
2842 item->SetIsCreatedFromHashChange(true); 2828 item->SetIsCreatedFromHashChange(true);
2843 } 2829 }
2844 2830
2845 return YES; 2831 return YES;
2846 } 2832 }
2847 2833
2848 - (BOOL)handleWindowHistoryBackMessage:(base::DictionaryValue*)message 2834 - (BOOL)handleWindowHistoryBackMessage:(base::DictionaryValue*)message
2849 context:(NSDictionary*)context { 2835 context:(NSDictionary*)context {
2850 [self goDelta:-1]; 2836 [self goDelta:-1];
(...skipping 25 matching lines...) Expand all
2876 - (BOOL)handleWindowHistoryDidPushStateMessage:(base::DictionaryValue*)message 2862 - (BOOL)handleWindowHistoryDidPushStateMessage:(base::DictionaryValue*)message
2877 context:(NSDictionary*)context { 2863 context:(NSDictionary*)context {
2878 DCHECK(_changingHistoryState); 2864 DCHECK(_changingHistoryState);
2879 _changingHistoryState = NO; 2865 _changingHistoryState = NO;
2880 2866
2881 // If there is a pending entry, a new navigation has been registered but 2867 // If there is a pending entry, a new navigation has been registered but
2882 // hasn't begun loading. Since the pushState message is coming from the 2868 // hasn't begun loading. Since the pushState message is coming from the
2883 // previous page, ignore it and allow the previously registered navigation to 2869 // previous page, ignore it and allow the previously registered navigation to
2884 // continue. This can ocur if a pushState is issued from an anchor tag 2870 // continue. This can ocur if a pushState is issued from an anchor tag
2885 // onClick event, as the click would have already been registered. 2871 // onClick event, as the click would have already been registered.
2886 if ([self sessionController].pendingEntry) 2872 if ([self sessionController].pendingItem)
2887 return NO; 2873 return NO;
2888 2874
2889 std::string pageURL; 2875 std::string pageURL;
2890 std::string baseURL; 2876 std::string baseURL;
2891 if (!message->GetString("pageUrl", &pageURL) || 2877 if (!message->GetString("pageUrl", &pageURL) ||
2892 !message->GetString("baseUrl", &baseURL)) { 2878 !message->GetString("baseUrl", &baseURL)) {
2893 DLOG(WARNING) << "JS message parameter not found: pageUrl or baseUrl"; 2879 DLOG(WARNING) << "JS message parameter not found: pageUrl or baseUrl";
2894 return NO; 2880 return NO;
2895 } 2881 }
2896 GURL pushURL = web::history_state_util::GetHistoryStateChangeUrl( 2882 GURL pushURL = web::history_state_util::GetHistoryStateChangeUrl(
2897 [self currentURL], GURL(baseURL), pageURL); 2883 [self currentURL], GURL(baseURL), pageURL);
2898 // UIWebView seems to choke on unicode characters that haven't been 2884 // UIWebView seems to choke on unicode characters that haven't been
2899 // escaped; escape the URL now so the expected load URL is correct. 2885 // escaped; escape the URL now so the expected load URL is correct.
2900 pushURL = URLEscapedForHistory(pushURL); 2886 pushURL = URLEscapedForHistory(pushURL);
2901 if (!pushURL.is_valid()) 2887 if (!pushURL.is_valid())
2902 return YES; 2888 return YES;
2903 web::NavigationItem* navItem = [self currentNavItem]; 2889 web::NavigationItem* navItem = self.currentNavItem;
2904 // PushState happened before first navigation entry or called when the 2890 // PushState happened before first navigation entry or called when the
2905 // navigation entry does not contain a valid URL. 2891 // navigation entry does not contain a valid URL.
2906 if (!navItem || !navItem->GetURL().is_valid()) 2892 if (!navItem || !navItem->GetURL().is_valid())
2907 return YES; 2893 return YES;
2908 if (!web::history_state_util::IsHistoryStateChangeValid( 2894 if (!web::history_state_util::IsHistoryStateChangeValid(
2909 [self currentNavItem]->GetURL(), pushURL)) { 2895 self.currentNavItem->GetURL(), pushURL)) {
2910 // If the current session entry URL origin still doesn't match pushURL's 2896 // If the current session entry URL origin still doesn't match pushURL's
2911 // origin, ignore the pushState. This can happen if a new URL is loaded 2897 // origin, ignore the pushState. This can happen if a new URL is loaded
2912 // just before the pushState. 2898 // just before the pushState.
2913 return YES; 2899 return YES;
2914 } 2900 }
2915 std::string stateObjectJSON; 2901 std::string stateObjectJSON;
2916 if (!message->GetString("stateObject", &stateObjectJSON)) { 2902 if (!message->GetString("stateObject", &stateObjectJSON)) {
2917 DLOG(WARNING) << "JS message parameter not found: stateObject"; 2903 DLOG(WARNING) << "JS message parameter not found: stateObject";
2918 return NO; 2904 return NO;
2919 } 2905 }
(...skipping 39 matching lines...) Expand 10 before | Expand all | Expand 10 after
2959 return NO; 2945 return NO;
2960 } 2946 }
2961 GURL replaceURL = web::history_state_util::GetHistoryStateChangeUrl( 2947 GURL replaceURL = web::history_state_util::GetHistoryStateChangeUrl(
2962 [self currentURL], GURL(baseURL), pageURL); 2948 [self currentURL], GURL(baseURL), pageURL);
2963 // UIWebView seems to choke on unicode characters that haven't been 2949 // UIWebView seems to choke on unicode characters that haven't been
2964 // escaped; escape the URL now so the expected load URL is correct. 2950 // escaped; escape the URL now so the expected load URL is correct.
2965 replaceURL = URLEscapedForHistory(replaceURL); 2951 replaceURL = URLEscapedForHistory(replaceURL);
2966 if (!replaceURL.is_valid()) 2952 if (!replaceURL.is_valid())
2967 return YES; 2953 return YES;
2968 2954
2969 web::NavigationItem* navItem = [self currentNavItem]; 2955 web::NavigationItem* navItem = self.currentNavItem;
2970 // ReplaceState happened before first navigation entry or called right 2956 // ReplaceState happened before first navigation entry or called right
2971 // after window.open when the url is empty/not valid. 2957 // after window.open when the url is empty/not valid.
2972 if (!navItem || (self.navigationManagerImpl->GetItemCount() <= 1 && 2958 if (!navItem || (self.navigationManagerImpl->GetItemCount() <= 1 &&
2973 navItem->GetURL().is_empty())) 2959 navItem->GetURL().is_empty()))
2974 return YES; 2960 return YES;
2975 if (!web::history_state_util::IsHistoryStateChangeValid( 2961 if (!web::history_state_util::IsHistoryStateChangeValid(
2976 [self currentNavItem]->GetURL(), replaceURL)) { 2962 self.currentNavItem->GetURL(), replaceURL)) {
2977 // If the current session entry URL origin still doesn't match 2963 // If the current session entry URL origin still doesn't match
2978 // replaceURL's origin, ignore the replaceState. This can happen if a 2964 // replaceURL's origin, ignore the replaceState. This can happen if a
2979 // new URL is loaded just before the replaceState. 2965 // new URL is loaded just before the replaceState.
2980 return YES; 2966 return YES;
2981 } 2967 }
2982 std::string stateObjectJSON; 2968 std::string stateObjectJSON;
2983 if (!message->GetString("stateObject", &stateObjectJSON)) { 2969 if (!message->GetString("stateObject", &stateObjectJSON)) {
2984 DLOG(WARNING) << "JS message parameter not found: stateObject"; 2970 DLOG(WARNING) << "JS message parameter not found: stateObject";
2985 return NO; 2971 return NO;
2986 } 2972 }
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
3022 // we should be distinguishing better, and be clear about the expected 3008 // we should be distinguishing better, and be clear about the expected
3023 // WebDelegate and WCO callbacks in each case. 3009 // WebDelegate and WCO callbacks in each case.
3024 - (void)webPageChanged { 3010 - (void)webPageChanged {
3025 DCHECK(_loadPhase == web::LOAD_REQUESTED); 3011 DCHECK(_loadPhase == web::LOAD_REQUESTED);
3026 3012
3027 const GURL currentURL([self currentURL]); 3013 const GURL currentURL([self currentURL]);
3028 web::Referrer referrer = [self currentReferrer]; 3014 web::Referrer referrer = [self currentReferrer];
3029 // If no referrer was known in advance, record it now. (If there was one, 3015 // If no referrer was known in advance, record it now. (If there was one,
3030 // keep it since it will have a more accurate URL and policy than what can 3016 // keep it since it will have a more accurate URL and policy than what can
3031 // be extracted from the landing page.) 3017 // be extracted from the landing page.)
3032 web::NavigationItem* currentItem = [self currentNavItem]; 3018 web::NavigationItem* currentItem = self.currentNavItem;
3033 if (!currentItem->GetReferrer().url.is_valid()) { 3019 if (!currentItem->GetReferrer().url.is_valid()) {
3034 currentItem->SetReferrer(referrer); 3020 currentItem->SetReferrer(referrer);
3035 } 3021 }
3036 3022
3037 // TODO(stuartmorgan): This shouldn't be called for hash state or 3023 // TODO(stuartmorgan): This shouldn't be called for hash state or
3038 // push/replaceState. 3024 // push/replaceState.
3039 [self resetDocumentSpecificState]; 3025 [self resetDocumentSpecificState];
3040 3026
3041 [self didStartLoadingURL:currentURL]; 3027 [self didStartLoadingURL:currentURL];
3042 } 3028 }
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
3081 _userInteractionRegistered = flag; 3067 _userInteractionRegistered = flag;
3082 if (flag) 3068 if (flag)
3083 _interactionRegisteredSinceLastURLChange = YES; 3069 _interactionRegisteredSinceLastURLChange = YES;
3084 } 3070 }
3085 3071
3086 - (BOOL)userInteractionRegistered { 3072 - (BOOL)userInteractionRegistered {
3087 return _userInteractionRegistered; 3073 return _userInteractionRegistered;
3088 } 3074 }
3089 3075
3090 - (void)cachePOSTDataForRequest:(NSURLRequest*)request 3076 - (void)cachePOSTDataForRequest:(NSURLRequest*)request
3091 inSessionEntry:(CRWSessionEntry*)currentSessionEntry { 3077 inNavigationItem:(web::NavigationItemImpl*)item {
3092 NSUInteger maxPOSTDataSizeInBytes = 4096; 3078 NSUInteger maxPOSTDataSizeInBytes = 4096;
3093 NSString* cookieHeaderName = @"cookie"; 3079 NSString* cookieHeaderName = @"cookie";
3094 3080
3095 web::NavigationItemImpl* currentItem = currentSessionEntry.navigationItemImpl; 3081 DCHECK(item);
3096 DCHECK(currentItem);
3097 const bool shouldUpdateEntry = 3082 const bool shouldUpdateEntry =
3098 ui::PageTransitionCoreTypeIs(currentItem->GetTransitionType(), 3083 ui::PageTransitionCoreTypeIs(item->GetTransitionType(),
3099 ui::PAGE_TRANSITION_FORM_SUBMIT) && 3084 ui::PAGE_TRANSITION_FORM_SUBMIT) &&
3100 ![request HTTPBodyStream] && // Don't cache streams. 3085 ![request HTTPBodyStream] && // Don't cache streams.
3101 !currentItem->HasPostData() && 3086 !item->HasPostData() &&
3102 currentItem->GetURL() == net::GURLWithNSURL([request URL]); 3087 item->GetURL() == net::GURLWithNSURL([request URL]);
3103 const bool belowSizeCap = 3088 const bool belowSizeCap =
3104 [[request HTTPBody] length] < maxPOSTDataSizeInBytes; 3089 [[request HTTPBody] length] < maxPOSTDataSizeInBytes;
3105 DLOG_IF(WARNING, shouldUpdateEntry && !belowSizeCap) 3090 DLOG_IF(WARNING, shouldUpdateEntry && !belowSizeCap)
3106 << "Data in POST request exceeds the size cap (" << maxPOSTDataSizeInBytes 3091 << "Data in POST request exceeds the size cap (" << maxPOSTDataSizeInBytes
3107 << " bytes), and will not be cached."; 3092 << " bytes), and will not be cached.";
3108 3093
3109 if (shouldUpdateEntry && belowSizeCap) { 3094 if (shouldUpdateEntry && belowSizeCap) {
3110 currentItem->SetPostData([request HTTPBody]); 3095 item->SetPostData([request HTTPBody]);
3111 currentItem->ResetHttpRequestHeaders(); 3096 item->ResetHttpRequestHeaders();
3112 currentItem->AddHttpRequestHeaders([request allHTTPHeaderFields]); 3097 item->AddHttpRequestHeaders([request allHTTPHeaderFields]);
3113 // Don't cache the "Cookie" header. 3098 // Don't cache the "Cookie" header.
3114 // According to NSURLRequest documentation, |-valueForHTTPHeaderField:| is 3099 // According to NSURLRequest documentation, |-valueForHTTPHeaderField:| is
3115 // case insensitive, so it's enough to test the lower case only. 3100 // case insensitive, so it's enough to test the lower case only.
3116 if ([request valueForHTTPHeaderField:cookieHeaderName]) { 3101 if ([request valueForHTTPHeaderField:cookieHeaderName]) {
3117 // Case insensitive search in |headers|. 3102 // Case insensitive search in |headers|.
3118 NSSet* cookieKeys = [currentItem->GetHttpRequestHeaders() 3103 NSSet* cookieKeys = [item->GetHttpRequestHeaders()
3119 keysOfEntriesPassingTest:^(id key, id obj, BOOL* stop) { 3104 keysOfEntriesPassingTest:^(id key, id obj, BOOL* stop) {
3120 NSString* header = (NSString*)key; 3105 NSString* header = (NSString*)key;
3121 const BOOL found = 3106 const BOOL found =
3122 [header caseInsensitiveCompare:cookieHeaderName] == 3107 [header caseInsensitiveCompare:cookieHeaderName] ==
3123 NSOrderedSame; 3108 NSOrderedSame;
3124 *stop = found; 3109 *stop = found;
3125 return found; 3110 return found;
3126 }]; 3111 }];
3127 DCHECK_EQ(1u, [cookieKeys count]); 3112 DCHECK_EQ(1u, [cookieKeys count]);
3128 currentItem->RemoveHttpRequestHeaderForKey([cookieKeys anyObject]); 3113 item->RemoveHttpRequestHeaderForKey([cookieKeys anyObject]);
3129 } 3114 }
3130 } 3115 }
3131 } 3116 }
3132 3117
3133 // TODO(stuartmorgan): This is mostly logic from the original UIWebView delegate 3118 // TODO(stuartmorgan): This is mostly logic from the original UIWebView delegate
3134 // method, which provides less information than the WKWebView version. Audit 3119 // method, which provides less information than the WKWebView version. Audit
3135 // this for things that should be handled in the subclass instead. 3120 // this for things that should be handled in the subclass instead.
3136 - (BOOL)shouldAllowLoadWithNavigationAction:(WKNavigationAction*)action { 3121 - (BOOL)shouldAllowLoadWithNavigationAction:(WKNavigationAction*)action {
3137 NSURLRequest* request = action.request; 3122 NSURLRequest* request = action.request;
3138 GURL requestURL = net::GURLWithNSURL(request.URL); 3123 GURL requestURL = net::GURLWithNSURL(request.URL);
3139 3124
3140 // External application launcher needs |isNavigationTypeLinkActivated| to 3125 // External application launcher needs |isNavigationTypeLinkActivated| to
3141 // decide if the user intended to open the application by clicking on a link. 3126 // decide if the user intended to open the application by clicking on a link.
3142 BOOL isNavigationTypeLinkActivated = 3127 BOOL isNavigationTypeLinkActivated =
3143 action.navigationType == WKNavigationTypeLinkActivated; 3128 action.navigationType == WKNavigationTypeLinkActivated;
3144 3129
3145 // Check if the link navigation leads to a launch of an external app. 3130 // Check if the link navigation leads to a launch of an external app.
3146 // TODO(crbug.com/607780): Revise the logic of allowing external app launch 3131 // TODO(crbug.com/607780): Revise the logic of allowing external app launch
3147 // and move it to externalAppLauncher. 3132 // and move it to externalAppLauncher.
3148 BOOL isOpenInNewTabNavigation = !(self.navigationManagerImpl->GetItemCount()); 3133 BOOL isOpenInNewTabNavigation = !(self.navigationManagerImpl->GetItemCount());
3149 BOOL isPossibleLinkClick = [self isLinkNavigation:action.navigationType]; 3134 BOOL isPossibleLinkClick = [self isLinkNavigation:action.navigationType];
3150 if (isPossibleLinkClick || isOpenInNewTabNavigation || 3135 if (isPossibleLinkClick || isOpenInNewTabNavigation ||
3151 PageTransitionCoreTypeIs([self currentTransition], 3136 PageTransitionCoreTypeIs(self.currentTransition,
3152 ui::PAGE_TRANSITION_AUTO_BOOKMARK)) { 3137 ui::PAGE_TRANSITION_AUTO_BOOKMARK)) {
3153 web::NavigationItem* item = [self currentNavItem]; 3138 web::NavigationItem* item = self.currentNavItem;
3154 const GURL currentNavigationURL = 3139 const GURL currentNavigationURL =
3155 item ? item->GetVirtualURL() : GURL::EmptyGURL(); 3140 item ? item->GetVirtualURL() : GURL::EmptyGURL();
3156 // Check If the URL is handled by a native app. 3141 // Check If the URL is handled by a native app.
3157 if ([self urlTriggersNativeAppLaunch:requestURL 3142 if ([self urlTriggersNativeAppLaunch:requestURL
3158 sourceURL:currentNavigationURL 3143 sourceURL:currentNavigationURL
3159 linkActivatedNavigation:isNavigationTypeLinkActivated]) { 3144 linkActivatedNavigation:isNavigationTypeLinkActivated]) {
3160 // External app has been launched successfully. Stop the current page 3145 // External app has been launched successfully. Stop the current page
3161 // load operation (e.g. notifying all observers) and record the URL so 3146 // load operation (e.g. notifying all observers) and record the URL so
3162 // that errors reported following the 'NO' reply can be safely ignored. 3147 // that errors reported following the 'NO' reply can be safely ignored.
3163 if ([self shouldClosePageOnNativeApplicationLoad]) 3148 if ([self shouldClosePageOnNativeApplicationLoad])
(...skipping 47 matching lines...) Expand 10 before | Expand all | Expand 10 after
3211 // Record the URL so that errors reported following the 'NO' reply can be 3196 // Record the URL so that errors reported following the 'NO' reply can be
3212 // safely ignored. 3197 // safely ignored.
3213 [_openedApplicationURL addObject:request.URL]; 3198 [_openedApplicationURL addObject:request.URL];
3214 if ([self shouldClosePageOnNativeApplicationLoad]) 3199 if ([self shouldClosePageOnNativeApplicationLoad])
3215 [_delegate webPageOrderedClose]; 3200 [_delegate webPageOrderedClose];
3216 } 3201 }
3217 return NO; 3202 return NO;
3218 } 3203 }
3219 3204
3220 if ([[request HTTPMethod] isEqualToString:@"POST"]) { 3205 if ([[request HTTPMethod] isEqualToString:@"POST"]) {
3221 CRWSessionEntry* currentEntry = [self currentSessionEntry]; 3206 web::NavigationItemImpl* item = self.currentNavItem;
3222 // TODO(crbug.com/570699): Remove this check once it's no longer possible to 3207 // TODO(crbug.com/570699): Remove this check once it's no longer possible to
3223 // have no current entries. 3208 // have no current entries.
3224 if (currentEntry) 3209 if (item)
3225 [self cachePOSTDataForRequest:request inSessionEntry:currentEntry]; 3210 [self cachePOSTDataForRequest:request inNavigationItem:item];
3226 } 3211 }
3227 3212
3228 return YES; 3213 return YES;
3229 } 3214 }
3230 3215
3231 - (void)handleLoadError:(NSError*)error inMainFrame:(BOOL)inMainFrame { 3216 - (void)handleLoadError:(NSError*)error inMainFrame:(BOOL)inMainFrame {
3232 NSString* MIMEType = [_pendingNavigationInfo MIMEType]; 3217 NSString* MIMEType = [_pendingNavigationInfo MIMEType];
3233 if ([_passKitDownloader isMIMETypePassKitType:MIMEType]) 3218 if ([_passKitDownloader isMIMETypePassKitType:MIMEType])
3234 return; 3219 return;
3235 if ([error code] == NSURLErrorUnsupportedURL) 3220 if ([error code] == NSURLErrorUnsupportedURL)
(...skipping 366 matching lines...) Expand 10 before | Expand all | Expand 10 after
3602 3587
3603 - (CRWSessionController*)sessionController { 3588 - (CRWSessionController*)sessionController {
3604 NavigationManagerImpl* navigationManager = self.navigationManagerImpl; 3589 NavigationManagerImpl* navigationManager = self.navigationManagerImpl;
3605 return navigationManager ? navigationManager->GetSessionController() : nil; 3590 return navigationManager ? navigationManager->GetSessionController() : nil;
3606 } 3591 }
3607 3592
3608 - (NavigationManagerImpl*)navigationManagerImpl { 3593 - (NavigationManagerImpl*)navigationManagerImpl {
3609 return _webStateImpl ? &(_webStateImpl->GetNavigationManagerImpl()) : nil; 3594 return _webStateImpl ? &(_webStateImpl->GetNavigationManagerImpl()) : nil;
3610 } 3595 }
3611 3596
3612 - (CRWSessionEntry*)currentSessionEntry { 3597 - (web::NavigationItemImpl*)currentNavItem {
3613 return [[self sessionController] currentEntry];
3614 }
3615
3616 - (web::NavigationItem*)currentNavItem {
3617 // This goes through the legacy Session* interface rather than Navigation* 3598 // This goes through the legacy Session* interface rather than Navigation*
3618 // because it is itself a legacy method that should not exist, and this 3599 // because it is itself a legacy method that should not exist, and this
3619 // avoids needing to add a GetActiveItem to NavigationManager. If/when this 3600 // avoids needing to add a GetActiveItem to NavigationManager. If/when this
3620 // method chain becomes a blocker to eliminating SessionController, the logic 3601 // method chain becomes a blocker to eliminating SessionController, the logic
3621 // can be moved here, using public NavigationManager getters. That's not 3602 // can be moved here, using public NavigationManager getters. That's not
3622 // done now in order to avoid code duplication. 3603 // done now in order to avoid code duplication.
3623 return [[self currentSessionEntry] navigationItem]; 3604 return [[self sessionController] currentItem];
3624 } 3605 }
3625 3606
3626 - (ui::PageTransition)currentTransition { 3607 - (ui::PageTransition)currentTransition {
3627 if ([self currentNavItem]) 3608 if (self.currentNavItem)
3628 return [self currentNavItem]->GetTransitionType(); 3609 return self.currentNavItem->GetTransitionType();
3629 else 3610 else
3630 return ui::PageTransitionFromInt(0); 3611 return ui::PageTransitionFromInt(0);
3631 } 3612 }
3632 3613
3633 - (web::Referrer)currentSessionEntryReferrer { 3614 - (web::Referrer)currentNavItemReferrer {
3634 web::NavigationItem* currentItem = [self currentNavItem]; 3615 web::NavigationItem* currentItem = self.currentNavItem;
3635 return currentItem ? currentItem->GetReferrer() : web::Referrer(); 3616 return currentItem ? currentItem->GetReferrer() : web::Referrer();
3636 } 3617 }
3637 3618
3638 - (NSDictionary*)currentHTTPHeaders { 3619 - (NSDictionary*)currentHTTPHeaders {
3639 DCHECK([self currentSessionEntry]); 3620 web::NavigationItem* currentItem = self.currentNavItem;
3640 return [self currentSessionEntry].navigationItem->GetHttpRequestHeaders(); 3621 return currentItem ? currentItem->GetHttpRequestHeaders() : nil;
3641 } 3622 }
3642 3623
3643 #pragma mark - 3624 #pragma mark -
3644 #pragma mark CRWWebViewScrollViewProxyObserver 3625 #pragma mark CRWWebViewScrollViewProxyObserver
3645 3626
3646 - (void)webViewScrollViewDidZoom: 3627 - (void)webViewScrollViewDidZoom:
3647 (CRWWebViewScrollViewProxy*)webViewScrollViewProxy { 3628 (CRWWebViewScrollViewProxy*)webViewScrollViewProxy {
3648 _pageHasZoomed = YES; 3629 _pageHasZoomed = YES;
3649 3630
3650 base::WeakNSObject<UIScrollView> weakScrollView(self.webScrollView); 3631 base::WeakNSObject<UIScrollView> weakScrollView(self.webScrollView);
3651 [self extractViewportTagWithCompletion:^( 3632 [self extractViewportTagWithCompletion:^(
3652 const web::PageViewportState* viewportState) { 3633 const web::PageViewportState* viewportState) {
3653 if (!weakScrollView) 3634 if (!weakScrollView)
3654 return; 3635 return;
3655 base::scoped_nsobject<UIScrollView> scrollView([weakScrollView retain]); 3636 base::scoped_nsobject<UIScrollView> scrollView([weakScrollView retain]);
3656 if (viewportState && !viewportState->viewport_tag_present() && 3637 if (viewportState && !viewportState->viewport_tag_present() &&
3657 [scrollView minimumZoomScale] == [scrollView maximumZoomScale] && 3638 [scrollView minimumZoomScale] == [scrollView maximumZoomScale] &&
3658 [scrollView zoomScale] > 1.0) { 3639 [scrollView zoomScale] > 1.0) {
3659 UMA_HISTOGRAM_BOOLEAN(kUMAViewportZoomBugCount, true); 3640 UMA_HISTOGRAM_BOOLEAN(kUMAViewportZoomBugCount, true);
3660 } 3641 }
3661 }]; 3642 }];
3662 } 3643 }
3663 3644
3664 - (void)webViewScrollViewDidResetContentSize: 3645 - (void)webViewScrollViewDidResetContentSize:
3665 (CRWWebViewScrollViewProxy*)webViewScrollViewProxy { 3646 (CRWWebViewScrollViewProxy*)webViewScrollViewProxy {
3666 web::NavigationItem* currentItem = [self currentNavItem]; 3647 web::NavigationItem* currentItem = self.currentNavItem;
3667 if (webViewScrollViewProxy.isZooming || _applyingPageState || !currentItem) 3648 if (webViewScrollViewProxy.isZooming || _applyingPageState || !currentItem)
3668 return; 3649 return;
3669 CGSize contentSize = webViewScrollViewProxy.contentSize; 3650 CGSize contentSize = webViewScrollViewProxy.contentSize;
3670 if (contentSize.width < CGRectGetWidth(webViewScrollViewProxy.frame)) { 3651 if (contentSize.width < CGRectGetWidth(webViewScrollViewProxy.frame)) {
3671 // The renderer incorrectly resized the content area. Resetting the scroll 3652 // The renderer incorrectly resized the content area. Resetting the scroll
3672 // view's zoom scale will force a re-rendering. rdar://23963992 3653 // view's zoom scale will force a re-rendering. rdar://23963992
3673 _applyingPageState = YES; 3654 _applyingPageState = YES;
3674 web::PageZoomState zoomState = 3655 web::PageZoomState zoomState =
3675 currentItem->GetPageDisplayState().zoom_state(); 3656 currentItem->GetPageDisplayState().zoom_state();
3676 if (!zoomState.IsValid()) 3657 if (!zoomState.IsValid())
(...skipping 24 matching lines...) Expand all
3701 completionHandler:nil]; 3682 completionHandler:nil];
3702 } 3683 }
3703 3684
3704 #pragma mark - 3685 #pragma mark -
3705 #pragma mark Page State 3686 #pragma mark Page State
3706 3687
3707 - (void)recordStateInHistory { 3688 - (void)recordStateInHistory {
3708 // Only record the state if: 3689 // Only record the state if:
3709 // - the current NavigationItem's URL matches the current URL, and 3690 // - the current NavigationItem's URL matches the current URL, and
3710 // - the user has interacted with the page. 3691 // - the user has interacted with the page.
3711 CRWSessionEntry* current = [self currentSessionEntry]; 3692 web::NavigationItem* item = self.currentNavItem;
3712 if (current && [current navigationItem]->GetURL() == [self currentURL] && 3693 if (item && item->GetURL() == [self currentURL] &&
3713 self.userInteractionRegistered) { 3694 self.userInteractionRegistered) {
3714 [current navigationItem]->SetPageDisplayState(self.pageDisplayState); 3695 item->SetPageDisplayState(self.pageDisplayState);
3715 } 3696 }
3716 } 3697 }
3717 3698
3718 - (void)restoreStateFromHistory { 3699 - (void)restoreStateFromHistory {
3719 CRWSessionEntry* current = [self currentSessionEntry]; 3700 web::NavigationItem* item = self.currentNavItem;
3720 if ([current navigationItem]) 3701 if (item)
3721 self.pageDisplayState = [current navigationItem]->GetPageDisplayState(); 3702 self.pageDisplayState = item->GetPageDisplayState();
3722 } 3703 }
3723 3704
3724 - (web::PageDisplayState)pageDisplayState { 3705 - (web::PageDisplayState)pageDisplayState {
3725 web::PageDisplayState displayState; 3706 web::PageDisplayState displayState;
3726 if (_webView) { 3707 if (_webView) {
3727 CGPoint scrollOffset = [self scrollPosition]; 3708 CGPoint scrollOffset = [self scrollPosition];
3728 displayState.scroll_state().set_offset_x(std::floor(scrollOffset.x)); 3709 displayState.scroll_state().set_offset_x(std::floor(scrollOffset.x));
3729 displayState.scroll_state().set_offset_y(std::floor(scrollOffset.y)); 3710 displayState.scroll_state().set_offset_y(std::floor(scrollOffset.y));
3730 UIScrollView* scrollView = self.webScrollView; 3711 UIScrollView* scrollView = self.webScrollView;
3731 displayState.zoom_state().set_minimum_zoom_scale( 3712 displayState.zoom_state().set_minimum_zoom_scale(
(...skipping 20 matching lines...) Expand all
3752 currentPageDisplayState.scroll_state().offset_y() == 3733 currentPageDisplayState.scroll_state().offset_y() ==
3753 _displayStateOnStartLoading.scroll_state().offset_y() && 3734 _displayStateOnStartLoading.scroll_state().offset_y() &&
3754 !_pageHasZoomed) { 3735 !_pageHasZoomed) {
3755 [self applyPageDisplayState:displayState]; 3736 [self applyPageDisplayState:displayState];
3756 } 3737 }
3757 } 3738 }
3758 } 3739 }
3759 3740
3760 - (void)extractViewportTagWithCompletion:(ViewportStateCompletion)completion { 3741 - (void)extractViewportTagWithCompletion:(ViewportStateCompletion)completion {
3761 DCHECK(completion); 3742 DCHECK(completion);
3762 web::NavigationItem* currentItem = [self currentNavItem]; 3743 web::NavigationItem* currentItem = self.currentNavItem;
3763 if (!currentItem) { 3744 if (!currentItem) {
3764 completion(nullptr); 3745 completion(nullptr);
3765 return; 3746 return;
3766 } 3747 }
3767 NSString* const kViewportContentQuery = 3748 NSString* const kViewportContentQuery =
3768 @"var viewport = document.querySelector('meta[name=\"viewport\"]');" 3749 @"var viewport = document.querySelector('meta[name=\"viewport\"]');"
3769 "viewport ? viewport.content : '';"; 3750 "viewport ? viewport.content : '';";
3770 base::WeakNSObject<CRWWebController> weakSelf(self); 3751 base::WeakNSObject<CRWWebController> weakSelf(self);
3771 int itemID = currentItem->GetUniqueID(); 3752 int itemID = currentItem->GetUniqueID();
3772 [self executeJavaScript:kViewportContentQuery 3753 [self executeJavaScript:kViewportContentQuery
(...skipping 52 matching lines...) Expand 10 before | Expand all | Expand 10 after
3825 userScalable:viewportState->user_scalable()]; 3806 userScalable:viewportState->user_scalable()];
3826 } 3807 }
3827 }]; 3808 }];
3828 } 3809 }
3829 3810
3830 - (void)applyPageDisplayState:(const web::PageDisplayState&)displayState 3811 - (void)applyPageDisplayState:(const web::PageDisplayState&)displayState
3831 userScalable:(BOOL)isUserScalable { 3812 userScalable:(BOOL)isUserScalable {
3832 // Early return if |scrollState| doesn't match the current NavigationItem. 3813 // Early return if |scrollState| doesn't match the current NavigationItem.
3833 // This can sometimes occur in tests, as navigation occurs programmatically 3814 // This can sometimes occur in tests, as navigation occurs programmatically
3834 // and |-applyPageScrollState:| is asynchronous. 3815 // and |-applyPageScrollState:| is asynchronous.
3835 web::NavigationItem* currentItem = [self currentSessionEntry].navigationItem; 3816 web::NavigationItem* currentItem = self.currentNavItem;
3836 if (currentItem && currentItem->GetPageDisplayState() != displayState) 3817 if (currentItem && currentItem->GetPageDisplayState() != displayState)
3837 return; 3818 return;
3838 DCHECK(displayState.IsValid()); 3819 DCHECK(displayState.IsValid());
3839 _applyingPageState = YES; 3820 _applyingPageState = YES;
3840 if (isUserScalable) { 3821 if (isUserScalable) {
3841 [self prepareToApplyWebViewScrollZoomScale]; 3822 [self prepareToApplyWebViewScrollZoomScale];
3842 [self applyWebViewScrollZoomScaleFromZoomState:displayState.zoom_state()]; 3823 [self applyWebViewScrollZoomScaleFromZoomState:displayState.zoom_state()];
3843 [self finishApplyingWebViewScrollZoomScale]; 3824 [self finishApplyingWebViewScrollZoomScale];
3844 } 3825 }
3845 [self applyWebViewScrollOffsetFromScrollState:displayState.scroll_state()]; 3826 [self applyWebViewScrollOffsetFromScrollState:displayState.scroll_state()];
(...skipping 392 matching lines...) Expand 10 before | Expand all | Expand 10 after
4238 _injectedScriptManagers.reset([[NSMutableSet alloc] init]); 4219 _injectedScriptManagers.reset([[NSMutableSet alloc] init]);
4239 [self setDocumentURL:_defaultURL]; 4220 [self setDocumentURL:_defaultURL];
4240 } 4221 }
4241 4222
4242 - (void)removeWebViewAllowingCachedReconstruction:(BOOL)allowCache { 4223 - (void)removeWebViewAllowingCachedReconstruction:(BOOL)allowCache {
4243 if (!_webView) 4224 if (!_webView)
4244 return; 4225 return;
4245 4226
4246 _webStateImpl->CancelDialogs(); 4227 _webStateImpl->CancelDialogs();
4247 4228
4248 web::NavigationItem* item = [self currentNavItem]; 4229 web::NavigationItem* item = self.currentNavItem;
4249 if (allowCache && item) { 4230 if (allowCache && item) {
4250 _expectedReconstructionURL = item->GetVirtualURL(); 4231 _expectedReconstructionURL = item->GetVirtualURL();
4251 } else { 4232 } else {
4252 _expectedReconstructionURL = GURL::EmptyGURL(); 4233 _expectedReconstructionURL = GURL::EmptyGURL();
4253 } 4234 }
4254 4235
4255 [self abortLoad]; 4236 [self abortLoad];
4256 [_webView removeFromSuperview]; 4237 [_webView removeFromSuperview];
4257 [_containerView resetContent]; 4238 [_containerView resetContent];
4258 [self setWebView:nil]; 4239 [self setWebView:nil];
(...skipping 61 matching lines...) Expand 10 before | Expand all | Expand 10 after
4320 } 4301 }
4321 4302
4322 - (void)stopLoading { 4303 - (void)stopLoading {
4323 _stoppedWKNavigation.reset([_navigationStates lastAddedNavigation]); 4304 _stoppedWKNavigation.reset([_navigationStates lastAddedNavigation]);
4324 4305
4325 base::RecordAction(UserMetricsAction("Stop")); 4306 base::RecordAction(UserMetricsAction("Stop"));
4326 // Discard the pending and transient entried before notifying the tab model 4307 // Discard the pending and transient entried before notifying the tab model
4327 // observers of the change via |-abortLoad|. 4308 // observers of the change via |-abortLoad|.
4328 [[self sessionController] discardNonCommittedItems]; 4309 [[self sessionController] discardNonCommittedItems];
4329 [self abortLoad]; 4310 [self abortLoad];
4330 web::NavigationItem* item = [self currentNavItem]; 4311 web::NavigationItem* item = self.currentNavItem;
4331 GURL navigationURL = item ? item->GetVirtualURL() : GURL::EmptyGURL(); 4312 GURL navigationURL = item ? item->GetVirtualURL() : GURL::EmptyGURL();
4332 // If discarding the non-committed entries results in an app-specific URL, 4313 // If discarding the non-committed entries results in an app-specific URL,
4333 // reload it in its native view. 4314 // reload it in its native view.
4334 if (!self.nativeController && 4315 if (!self.nativeController &&
4335 [self shouldLoadURLInNativeView:navigationURL]) { 4316 [self shouldLoadURLInNativeView:navigationURL]) {
4336 [self loadCurrentURLInNativeView]; 4317 [self loadCurrentURLInNativeView];
4337 } 4318 }
4338 } 4319 }
4339 4320
4340 #pragma mark - 4321 #pragma mark -
(...skipping 704 matching lines...) Expand 10 before | Expand all | Expand 10 after
5045 if (self.loadPhase != web::LOAD_REQUESTED) 5026 if (self.loadPhase != web::LOAD_REQUESTED)
5046 return NO; 5027 return NO;
5047 5028
5048 web::NavigationItem* pendingItem = 5029 web::NavigationItem* pendingItem =
5049 self.webState->GetNavigationManager()->GetPendingItem(); 5030 self.webState->GetNavigationManager()->GetPendingItem();
5050 return pendingItem && pendingItem->GetURL() == targetURL; 5031 return pendingItem && pendingItem->GetURL() == targetURL;
5051 } 5032 }
5052 5033
5053 - (void)loadRequestForCurrentNavigationItem { 5034 - (void)loadRequestForCurrentNavigationItem {
5054 DCHECK(_webView && !self.nativeController); 5035 DCHECK(_webView && !self.nativeController);
5055 DCHECK([self currentSessionEntry]); 5036 DCHECK(self.currentNavItem);
5056 // If a load is kicked off on a WKWebView with a frame whose size is {0, 0} or 5037 // If a load is kicked off on a WKWebView with a frame whose size is {0, 0} or
5057 // that has a negative dimension for a size, rendering issues occur that 5038 // that has a negative dimension for a size, rendering issues occur that
5058 // manifest in erroneous scrolling and tap handling (crbug.com/574996, 5039 // manifest in erroneous scrolling and tap handling (crbug.com/574996,
5059 // crbug.com/577793). 5040 // crbug.com/577793).
5060 DCHECK_GT(CGRectGetWidth([_webView frame]), 0.0); 5041 DCHECK_GT(CGRectGetWidth([_webView frame]), 0.0);
5061 DCHECK_GT(CGRectGetHeight([_webView frame]), 0.0); 5042 DCHECK_GT(CGRectGetHeight([_webView frame]), 0.0);
5062 5043
5063 web::WKBackForwardListItemHolder* holder = 5044 web::WKBackForwardListItemHolder* holder =
5064 [self currentBackForwardListItemHolder]; 5045 [self currentBackForwardListItemHolder];
5065 BOOL repostedForm = 5046 BOOL repostedForm =
5066 [holder->http_method() isEqual:@"POST"] && 5047 [holder->http_method() isEqual:@"POST"] &&
5067 (holder->navigation_type() == WKNavigationTypeFormResubmitted || 5048 (holder->navigation_type() == WKNavigationTypeFormResubmitted ||
5068 holder->navigation_type() == WKNavigationTypeFormSubmitted); 5049 holder->navigation_type() == WKNavigationTypeFormSubmitted);
5069 web::NavigationItemImpl* currentItem = 5050 web::NavigationItemImpl* currentItem = self.currentNavItem;
5070 [self currentSessionEntry].navigationItemImpl;
5071 NSData* POSTData = currentItem->GetPostData(); 5051 NSData* POSTData = currentItem->GetPostData();
5072 NSMutableURLRequest* request = [self requestForCurrentNavigationItem]; 5052 NSMutableURLRequest* request = [self requestForCurrentNavigationItem];
5073 5053
5074 // If the request has POST data and is not a repost form, configure and 5054 // If the request has POST data and is not a repost form, configure and
5075 // run the POST request. 5055 // run the POST request.
5076 if (POSTData.length && !repostedForm) { 5056 if (POSTData.length && !repostedForm) {
5077 [request setHTTPMethod:@"POST"]; 5057 [request setHTTPMethod:@"POST"];
5078 [request setHTTPBody:POSTData]; 5058 [request setHTTPBody:POSTData];
5079 [request setAllHTTPHeaderFields:[self currentHTTPHeaders]]; 5059 [request setAllHTTPHeaderFields:self.currentHTTPHeaders];
5080 GURL navigationURL = 5060 GURL navigationURL =
5081 currentItem ? currentItem->GetURL() : GURL::EmptyGURL(); 5061 currentItem ? currentItem->GetURL() : GURL::EmptyGURL();
5082 [self registerLoadRequest:navigationURL 5062 [self registerLoadRequest:navigationURL
5083 referrer:[self currentSessionEntryReferrer] 5063 referrer:self.currentNavItemReferrer
5084 transition:[self currentTransition]]; 5064 transition:self.currentTransition];
5085 [self loadPOSTRequest:request]; 5065 [self loadPOSTRequest:request];
5086 return; 5066 return;
5087 } 5067 }
5088 5068
5089 ProceduralBlock defaultNavigationBlock = ^{ 5069 ProceduralBlock defaultNavigationBlock = ^{
5090 web::NavigationItem* item = [self currentNavItem]; 5070 web::NavigationItem* item = self.currentNavItem;
5091 GURL navigationURL = item ? item->GetURL() : GURL::EmptyGURL(); 5071 GURL navigationURL = item ? item->GetURL() : GURL::EmptyGURL();
5092 [self registerLoadRequest:navigationURL 5072 [self registerLoadRequest:navigationURL
5093 referrer:[self currentSessionEntryReferrer] 5073 referrer:self.currentNavItemReferrer
5094 transition:[self currentTransition]]; 5074 transition:self.currentTransition];
5095 [self loadRequest:request]; 5075 [self loadRequest:request];
5096 }; 5076 };
5097 5077
5098 // When navigating via WKBackForwardListItem to pages created or updated by 5078 // When navigating via WKBackForwardListItem to pages created or updated by
5099 // calls to pushState() and replaceState(), sometimes core.js is not injected 5079 // calls to pushState() and replaceState(), sometimes core.js is not injected
5100 // correctly. This means that calling window.history navigation functions 5080 // correctly. This means that calling window.history navigation functions
5101 // will invoke WKWebView's non-overridden implementations, causing a mismatch 5081 // will invoke WKWebView's non-overridden implementations, causing a mismatch
5102 // between the WKBackForwardList and NavigationManager. 5082 // between the WKBackForwardList and NavigationManager.
5103 // TODO(crbug.com/659816): Figure out how to prevent core.js injection flake. 5083 // TODO(crbug.com/659816): Figure out how to prevent core.js injection flake.
5104 if (currentItem->HasStateBeenReplaced() || 5084 if (currentItem->HasStateBeenReplaced() ||
(...skipping 10 matching lines...) Expand all
5115 ![self isBackForwardListItemValid:holder->back_forward_list_item()]) { 5095 ![self isBackForwardListItemValid:holder->back_forward_list_item()]) {
5116 defaultNavigationBlock(); 5096 defaultNavigationBlock();
5117 return; 5097 return;
5118 } 5098 }
5119 5099
5120 ProceduralBlock webViewNavigationBlock = ^{ 5100 ProceduralBlock webViewNavigationBlock = ^{
5121 // If the current navigation URL is the same as the URL of the visible 5101 // If the current navigation URL is the same as the URL of the visible
5122 // page, that means the user requested a reload. |goToBackForwardListItem| 5102 // page, that means the user requested a reload. |goToBackForwardListItem|
5123 // will be a no-op when it is passed the current back forward list item, 5103 // will be a no-op when it is passed the current back forward list item,
5124 // so |reload| must be explicitly called. 5104 // so |reload| must be explicitly called.
5125 web::NavigationItem* item = [self currentNavItem]; 5105 web::NavigationItem* item = self.currentNavItem;
5126 GURL navigationURL = item ? item->GetURL() : GURL::EmptyGURL(); 5106 GURL navigationURL = item ? item->GetURL() : GURL::EmptyGURL();
5127 [self registerLoadRequest:navigationURL 5107 [self registerLoadRequest:navigationURL
5128 referrer:[self currentSessionEntryReferrer] 5108 referrer:self.currentNavItemReferrer
5129 transition:[self currentTransition]]; 5109 transition:self.currentTransition];
5130 if (navigationURL == net::GURLWithNSURL([_webView URL])) { 5110 if (navigationURL == net::GURLWithNSURL([_webView URL])) {
5131 [_navigationStates setState:web::WKNavigationState::REQUESTED 5111 [_navigationStates setState:web::WKNavigationState::REQUESTED
5132 forNavigation:[_webView reload]]; 5112 forNavigation:[_webView reload]];
5133 } else { 5113 } else {
5134 // |didCommitNavigation:| may not be called for fast navigation, so update 5114 // |didCommitNavigation:| may not be called for fast navigation, so update
5135 // the navigation type now as it is already known. 5115 // the navigation type now as it is already known.
5136 holder->set_navigation_type(WKNavigationTypeBackForward); 5116 holder->set_navigation_type(WKNavigationTypeBackForward);
5137 WKNavigation* navigation = 5117 WKNavigation* navigation =
5138 [_webView goToBackForwardListItem:holder->back_forward_list_item()]; 5118 [_webView goToBackForwardListItem:holder->back_forward_list_item()];
5139 [_navigationStates setState:web::WKNavigationState::REQUESTED 5119 [_navigationStates setState:web::WKNavigationState::REQUESTED
(...skipping 79 matching lines...) Expand 10 before | Expand all | Expand 10 after
5219 - (void)simulateLoadRequestWithURL:(const GURL&)URL { 5199 - (void)simulateLoadRequestWithURL:(const GURL&)URL {
5220 _lastRegisteredRequestURL = URL; 5200 _lastRegisteredRequestURL = URL;
5221 _loadPhase = web::LOAD_REQUESTED; 5201 _loadPhase = web::LOAD_REQUESTED;
5222 } 5202 }
5223 5203
5224 - (NSString*)referrerFromNavigationAction:(WKNavigationAction*)action { 5204 - (NSString*)referrerFromNavigationAction:(WKNavigationAction*)action {
5225 return [action.request valueForHTTPHeaderField:kReferrerHeaderName]; 5205 return [action.request valueForHTTPHeaderField:kReferrerHeaderName];
5226 } 5206 }
5227 5207
5228 @end 5208 @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