-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathBrowserViewController.swift
2837 lines (2397 loc) · 122 KB
/
BrowserViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Photos
import UIKit
import WebKit
import Shared
import Storage
import SnapKit
import XCGLogger
import Alamofire
import Account
import MobileCoreServices
import SDWebImage
import SwiftyJSON
import Telemetry
import Sentry
private let KVOs: [KVOConstants] = [
.estimatedProgress,
.loading,
.canGoBack,
.canGoForward,
.URL,
.title,
]
private let ActionSheetTitleMaxLength = 120
private struct BrowserViewControllerUX {
fileprivate static let BackgroundColor = UIConstants.AppBackgroundColor
fileprivate static let ShowHeaderTapAreaHeight: CGFloat = 32
fileprivate static let BookmarkStarAnimationDuration: Double = 0.5
fileprivate static let BookmarkStarAnimationOffset: CGFloat = 80
}
class BrowserViewController: UIViewController {
var homePanelController: HomePanelViewController?
var webViewContainer: UIView!
var urlBar: URLBarView!
var clipboardBarDisplayHandler: ClipboardBarDisplayHandler?
var readerModeBar: ReaderModeBarView?
var readerModeCache: ReaderModeCache
let webViewContainerToolbar = UIView()
var statusBarOverlay: UIView!
fileprivate(set) var toolbar: TabToolbar?
var searchController: SearchViewController?
fileprivate var screenshotHelper: ScreenshotHelper!
fileprivate var homePanelIsInline = false
fileprivate var searchLoader: SearchLoader?
fileprivate let alertStackView = UIStackView() // All content that appears above the footer should be added to this view. (Find In Page/SnackBars)
fileprivate var findInPageBar: FindInPageBar?
lazy var mailtoLinkHandler: MailtoLinkHandler = MailtoLinkHandler()
lazy fileprivate var customSearchEngineButton: UIButton = {
let searchButton = UIButton()
searchButton.setImage(UIImage(named: "AddSearch")?.withRenderingMode(.alwaysTemplate), for: [])
searchButton.addTarget(self, action: #selector(addCustomSearchEngineForFocusedElement), for: .touchUpInside)
searchButton.accessibilityIdentifier = "BrowserViewController.customSearchEngineButton"
return searchButton
}()
fileprivate var customSearchBarButton: UIBarButtonItem?
// popover rotation handling
fileprivate var displayedPopoverController: UIViewController?
fileprivate var updateDisplayedPopoverProperties: (() -> Void)?
var openInHelper: OpenInHelper?
// location label actions
fileprivate var pasteGoAction: AccessibleAction!
fileprivate var pasteAction: AccessibleAction!
fileprivate var copyAddressAction: AccessibleAction!
fileprivate weak var tabTrayController: TabTrayController!
let profile: Profile
let tabManager: TabManager
// These views wrap the urlbar and toolbar to provide background effects on them
var header: UIView!
var footer: UIView!
fileprivate var topTouchArea: UIButton!
let urlBarTopTabsContainer = UIView(frame: CGRect.zero)
var topTabsVisible: Bool {
return topTabsViewController != nil
}
// Backdrop used for displaying greyed background for private tabs
var webViewContainerBackdrop: UIView!
var scrollController = TabScrollingController()
fileprivate var keyboardState: KeyboardState?
var pendingToast: ButtonToast? // A toast that might be waiting for BVC to appear before displaying
// Tracking navigation items to record history types.
// TODO: weak references?
var ignoredNavigation = Set<WKNavigation>()
var typedNavigation = [WKNavigation: VisitType]()
var navigationToolbar: TabToolbarProtocol {
return toolbar ?? urlBar
}
var topTabsViewController: TopTabsViewController?
let topTabsContainer = UIView()
init(profile: Profile, tabManager: TabManager) {
self.profile = profile
self.tabManager = tabManager
self.readerModeCache = DiskReaderModeCache.sharedInstance
super.init(nibName: nil, bundle: nil)
didInit()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
dismissVisibleMenus()
coordinator.animate(alongsideTransition: { context in
self.scrollController.updateMinimumZoom()
self.topTabsViewController?.scrollToCurrentTab(false, centerCell: false)
if let popover = self.displayedPopoverController {
self.updateDisplayedPopoverProperties?()
self.present(popover, animated: true, completion: nil)
}
}, completion: { _ in
self.scrollController.setMinimumZoom()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
fileprivate func didInit() {
screenshotHelper = ScreenshotHelper(controller: self)
tabManager.addDelegate(self)
tabManager.addNavigationDelegate(self)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
let isPrivate = tabManager.selectedTab?.isPrivate ?? false
let isIpad = shouldShowTopTabsForTraitCollection(traitCollection)
return (isPrivate || isIpad) ? .lightContent : .default
}
func shouldShowFooterForTraitCollection(_ previousTraitCollection: UITraitCollection) -> Bool {
return previousTraitCollection.verticalSizeClass != .compact && previousTraitCollection.horizontalSizeClass != .regular
}
func shouldShowTopTabsForTraitCollection(_ newTraitCollection: UITraitCollection) -> Bool {
return newTraitCollection.verticalSizeClass == .regular && newTraitCollection.horizontalSizeClass == .regular
}
func toggleSnackBarVisibility(show: Bool) {
if show {
UIView.animate(withDuration: 0.1, animations: { self.alertStackView.isHidden = false })
} else {
alertStackView.isHidden = true
}
}
fileprivate func updateToolbarStateForTraitCollection(_ newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator? = nil) {
let showToolbar = shouldShowFooterForTraitCollection(newCollection)
let showTopTabs = shouldShowTopTabsForTraitCollection(newCollection)
urlBar.topTabsIsShowing = showTopTabs
urlBar.setShowToolbar(!showToolbar)
toolbar?.removeFromSuperview()
toolbar?.tabToolbarDelegate = nil
toolbar = nil
if showToolbar {
toolbar = TabToolbar()
footer.addSubview(toolbar!)
toolbar?.tabToolbarDelegate = self
let theme = (tabManager.selectedTab?.isPrivate ?? false) ? Theme.Private : Theme.Normal
toolbar?.applyTheme(theme)
updateTabCountUsingTabManager(self.tabManager)
}
if showTopTabs {
if topTabsViewController == nil {
let topTabsViewController = TopTabsViewController(tabManager: tabManager)
topTabsViewController.delegate = self
addChildViewController(topTabsViewController)
topTabsViewController.view.frame = topTabsContainer.frame
topTabsContainer.addSubview(topTabsViewController.view)
topTabsViewController.view.snp.makeConstraints { make in
make.edges.equalTo(topTabsContainer)
make.height.equalTo(TopTabsUX.TopTabsViewHeight)
}
self.topTabsViewController = topTabsViewController
}
topTabsContainer.snp.updateConstraints { make in
make.height.equalTo(TopTabsUX.TopTabsViewHeight)
}
} else {
topTabsContainer.snp.updateConstraints { make in
make.height.equalTo(0)
}
topTabsViewController?.view.removeFromSuperview()
topTabsViewController?.removeFromParentViewController()
topTabsViewController = nil
}
view.setNeedsUpdateConstraints()
if let home = homePanelController {
home.view.setNeedsUpdateConstraints()
}
if let tab = tabManager.selectedTab,
let webView = tab.webView {
updateURLBarDisplayURL(tab)
navigationToolbar.updateBackStatus(webView.canGoBack)
navigationToolbar.updateForwardStatus(webView.canGoForward)
navigationToolbar.updateReloadStatus(tab.loading)
}
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
// During split screen launching on iPad, this callback gets fired before viewDidLoad gets a chance to
// set things up. Make sure to only update the toolbar state if the view is ready for it.
if isViewLoaded {
updateToolbarStateForTraitCollection(newCollection, withTransitionCoordinator: coordinator)
}
displayedPopoverController?.dismiss(animated: true, completion: nil)
coordinator.animate(alongsideTransition: { context in
self.scrollController.showToolbars(animated: false)
if self.isViewLoaded {
self.statusBarOverlay.backgroundColor = self.shouldShowTopTabsForTraitCollection(self.traitCollection) ? UIColor.Photon.Grey80 : self.urlBar.backgroundColor
self.setNeedsStatusBarAppearanceUpdate()
}
}, completion: nil)
}
func dismissVisibleMenus() {
displayedPopoverController?.dismiss(animated: true)
if let _ = self.presentedViewController as? PhotonActionSheet {
self.presentedViewController?.dismiss(animated: true, completion: nil)
}
}
@objc func appDidEnterBackgroundNotification() {
displayedPopoverController?.dismiss(animated: false) {
self.displayedPopoverController = nil
}
}
@objc func tappedTopArea() {
scrollController.showToolbars(animated: true)
}
@objc func appWillResignActiveNotification() {
// Dismiss any popovers that might be visible
displayedPopoverController?.dismiss(animated: false) {
self.displayedPopoverController = nil
}
// If we are displying a private tab, hide any elements in the tab that we wouldn't want shown
// when the app is in the home switcher
guard let privateTab = tabManager.selectedTab, privateTab.isPrivate else {
return
}
webViewContainerBackdrop.alpha = 1
webViewContainer.alpha = 0
urlBar.locationContainer.alpha = 0
topTabsViewController?.switchForegroundStatus(isInForeground: false)
presentedViewController?.popoverPresentationController?.containerView?.alpha = 0
presentedViewController?.view.alpha = 0
}
@objc func appDidBecomeActiveNotification() {
// Re-show any components that might have been hidden because they were being displayed
// as part of a private mode tab
UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions(), animations: {
self.webViewContainer.alpha = 1
self.urlBar.locationContainer.alpha = 1
self.topTabsViewController?.switchForegroundStatus(isInForeground: true)
self.presentedViewController?.popoverPresentationController?.containerView?.alpha = 1
self.presentedViewController?.view.alpha = 1
self.view.backgroundColor = UIColor.clear
}, completion: { _ in
self.webViewContainerBackdrop.alpha = 0
})
// Re-show toolbar which might have been hidden during scrolling (prior to app moving into the background)
scrollController.showToolbars(animated: false)
}
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActiveNotification), name: .UIApplicationWillResignActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActiveNotification), name: .UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(appDidEnterBackgroundNotification), name: .UIApplicationDidEnterBackground, object: nil)
KeyboardHelper.defaultHelper.addDelegate(self)
webViewContainerBackdrop = UIView()
webViewContainerBackdrop.backgroundColor = UIColor.gray
webViewContainerBackdrop.alpha = 0
view.addSubview(webViewContainerBackdrop)
webViewContainer = UIView()
webViewContainer.addSubview(webViewContainerToolbar)
view.addSubview(webViewContainer)
// Temporary work around for covering the non-clipped web view content
statusBarOverlay = UIView()
view.addSubview(statusBarOverlay)
topTouchArea = UIButton()
topTouchArea.isAccessibilityElement = false
topTouchArea.addTarget(self, action: #selector(tappedTopArea), for: .touchUpInside)
view.addSubview(topTouchArea)
// Setup the URL bar, wrapped in a view to get transparency effect
urlBar = URLBarView()
urlBar.translatesAutoresizingMaskIntoConstraints = false
urlBar.delegate = self
urlBar.tabToolbarDelegate = self
header = urlBarTopTabsContainer
urlBarTopTabsContainer.addSubview(urlBar)
urlBarTopTabsContainer.addSubview(topTabsContainer)
view.addSubview(header)
// UIAccessibilityCustomAction subclass holding an AccessibleAction instance does not work, thus unable to generate AccessibleActions and UIAccessibilityCustomActions "on-demand" and need to make them "persistent" e.g. by being stored in BVC
pasteGoAction = AccessibleAction(name: Strings.PasteAndGoTitle, handler: { () -> Bool in
if let pasteboardContents = UIPasteboard.general.string {
self.urlBar(self.urlBar, didSubmitText: pasteboardContents)
return true
}
return false
})
pasteAction = AccessibleAction(name: Strings.PasteTitle, handler: { () -> Bool in
if let pasteboardContents = UIPasteboard.general.string {
// Enter overlay mode and make the search controller appear.
self.urlBar.enterOverlayMode(pasteboardContents, pasted: true, search: true)
return true
}
return false
})
copyAddressAction = AccessibleAction(name: Strings.CopyAddressTitle, handler: { () -> Bool in
if let url = self.urlBar.currentURL {
UIPasteboard.general.url = url as URL
}
return true
})
view.addSubview(alertStackView)
footer = UIView()
view.addSubview(footer)
alertStackView.axis = .vertical
alertStackView.alignment = .center
if AppConstants.MOZ_CLIPBOARD_BAR {
clipboardBarDisplayHandler = ClipboardBarDisplayHandler(prefs: profile.prefs, tabManager: tabManager)
clipboardBarDisplayHandler?.delegate = self
}
scrollController.urlBar = urlBar
scrollController.header = header
scrollController.footer = footer
scrollController.snackBars = alertStackView
scrollController.webViewContainerToolbar = webViewContainerToolbar
self.updateToolbarStateForTraitCollection(self.traitCollection)
setupConstraints()
// Setup UIDropInteraction to handle dragging and dropping
// links into the view from other apps.
if #available(iOS 11, *) {
let dropInteraction = UIDropInteraction(delegate: self)
view.addInteraction(dropInteraction)
}
}
fileprivate func setupConstraints() {
topTabsContainer.snp.makeConstraints { make in
make.leading.trailing.equalTo(self.header)
make.top.equalTo(urlBarTopTabsContainer)
}
urlBar.snp.makeConstraints { make in
make.leading.trailing.bottom.equalTo(urlBarTopTabsContainer)
make.height.equalTo(UIConstants.TopToolbarHeight)
make.top.equalTo(topTabsContainer.snp.bottom)
}
header.snp.makeConstraints { make in
scrollController.headerTopConstraint = make.top.equalTo(self.topLayoutGuide.snp.bottom).constraint
make.left.right.equalTo(self.view)
}
webViewContainerBackdrop.snp.makeConstraints { make in
make.edges.equalTo(webViewContainer)
}
webViewContainerToolbar.snp.makeConstraints { make in
make.left.right.top.equalTo(webViewContainer)
make.height.equalTo(0)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
statusBarOverlay.snp.remakeConstraints { make in
make.top.left.right.equalTo(self.view)
make.height.equalTo(self.topLayoutGuide.length)
}
}
override var canBecomeFirstResponder: Bool {
return true
}
override func becomeFirstResponder() -> Bool {
// Make the web view the first responder so that it can show the selection menu.
return tabManager.selectedTab?.webView?.becomeFirstResponder() ?? false
}
func loadQueuedTabs(receivedURLs: [URL]? = nil) {
// Chain off of a trivial deferred in order to run on the background queue.
succeed().upon() { res in
self.dequeueQueuedTabs(receivedURLs: receivedURLs ?? [])
}
}
fileprivate func dequeueQueuedTabs(receivedURLs: [URL]) {
assert(!Thread.current.isMainThread, "This must be called in the background.")
self.profile.queue.getQueuedTabs() >>== { cursor in
// This assumes that the DB returns rows in some kind of sane order.
// It does in practice, so WFM.
if cursor.count > 0 {
// Filter out any tabs received by a push notification to prevent dupes.
let urls = cursor.compactMap { $0?.url.asURL }.filter { !receivedURLs.contains($0) }
if !urls.isEmpty {
DispatchQueue.main.async {
self.tabManager.addTabsForURLs(urls, zombie: false)
}
}
// Clear *after* making an attempt to open. We're making a bet that
// it's better to run the risk of perhaps opening twice on a crash,
// rather than losing data.
self.profile.queue.clearQueuedTabs()
}
// Then, open any received URLs from push notifications.
if !receivedURLs.isEmpty {
DispatchQueue.main.async {
let unopenedReceivedURLs = receivedURLs.filter { self.tabManager.getTabForURL($0) == nil }
self.tabManager.addTabsForURLs(unopenedReceivedURLs, zombie: false)
if let lastURL = receivedURLs.last, let tab = self.tabManager.getTabForURL(lastURL) {
self.tabManager.selectTab(tab)
}
}
}
}
}
// Because crashedLastLaunch is sticky, it does not get reset, we need to remember its
// value so that we do not keep asking the user to restore their tabs.
var displayedRestoreTabsAlert = false
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// On iPhone, if we are about to show the On-Boarding, blank out the tab so that it does
// not flash before we present. This change of alpha also participates in the animation when
// the intro view is dismissed.
if UIDevice.current.userInterfaceIdiom == .phone {
self.view.alpha = (profile.prefs.intForKey(PrefsKeys.IntroSeen) != nil) ? 1.0 : 0.0
}
if !displayedRestoreTabsAlert && !cleanlyBackgrounded() && crashedLastLaunch() {
displayedRestoreTabsAlert = true
showRestoreTabsAlert()
} else {
tabManager.restoreTabs()
}
updateTabCountUsingTabManager(tabManager, animated: false)
clipboardBarDisplayHandler?.checkIfShouldDisplayBar()
}
fileprivate func crashedLastLaunch() -> Bool {
return Sentry.crashedLastLaunch
}
fileprivate func cleanlyBackgrounded() -> Bool {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return false
}
return appDelegate.applicationCleanlyBackgrounded
}
fileprivate func showRestoreTabsAlert() {
guard canRestoreTabs() else {
self.tabManager.addTabAndSelect()
return
}
let alert = UIAlertController.restoreTabsAlert(
okayCallback: { _ in
self.tabManager.restoreTabs()
},
noCallback: { _ in
self.tabManager.addTabAndSelect()
}
)
self.present(alert, animated: true, completion: nil)
}
fileprivate func canRestoreTabs() -> Bool {
guard let tabsToRestore = TabManager.tabsToRestore() else { return false }
return !tabsToRestore.isEmpty
}
override func viewDidAppear(_ animated: Bool) {
presentIntroViewController()
self.webViewContainerToolbar.isHidden = false
screenshotHelper.viewIsVisible = true
screenshotHelper.takePendingScreenshots(tabManager.tabs)
super.viewDidAppear(animated)
if shouldShowWhatsNewTab() {
// Only display if the SUMO topic has been configured in the Info.plist (present and not empty)
if let whatsNewTopic = AppInfo.whatsNewTopic, whatsNewTopic != "" {
if let whatsNewURL = SupportUtils.URLForTopic(whatsNewTopic) {
self.openURLInNewTab(whatsNewURL, isPrivileged: false)
profile.prefs.setString(AppInfo.appVersion, forKey: LatestAppVersionProfileKey)
}
}
}
if let toast = self.pendingToast {
self.pendingToast = nil
show(buttonToast: toast, afterWaiting: ButtonToastUX.ToastDelay)
}
showQueuedAlertIfAvailable()
}
// THe logic for shouldShowWhatsNewTab is as follows: If we do not have the LatestAppVersionProfileKey in
// the profile, that means that this is a fresh install and we do not show the What's New. If we do have
// that value, we compare it to the major version of the running app. If it is different then this is an
// upgrade, downgrades are not possible, so we can show the What's New page.
fileprivate func shouldShowWhatsNewTab() -> Bool {
guard let latestMajorAppVersion = profile.prefs.stringForKey(LatestAppVersionProfileKey)?.components(separatedBy: ".").first else {
return false // Clean install, never show What's New
}
return latestMajorAppVersion != AppInfo.majorAppVersion && DeviceInfo.hasConnectivity()
}
fileprivate func showQueuedAlertIfAvailable() {
if let queuedAlertInfo = tabManager.selectedTab?.dequeueJavascriptAlertPrompt() {
let alertController = queuedAlertInfo.alertController()
alertController.delegate = self
present(alertController, animated: true, completion: nil)
}
}
override func viewWillDisappear(_ animated: Bool) {
screenshotHelper.viewIsVisible = false
super.viewWillDisappear(animated)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
}
func resetBrowserChrome() {
// animate and reset transform for tab chrome
urlBar.updateAlphaForSubviews(1)
footer.alpha = 1
[header, footer, readerModeBar].forEach { view in
view?.transform = .identity
}
statusBarOverlay.isHidden = false
}
override func updateViewConstraints() {
super.updateViewConstraints()
topTouchArea.snp.remakeConstraints { make in
make.top.left.right.equalTo(self.view)
make.height.equalTo(BrowserViewControllerUX.ShowHeaderTapAreaHeight)
}
readerModeBar?.snp.remakeConstraints { make in
make.top.equalTo(self.header.snp.bottom)
make.height.equalTo(UIConstants.ToolbarHeight)
make.leading.trailing.equalTo(self.view)
}
webViewContainer.snp.remakeConstraints { make in
make.left.right.equalTo(self.view)
if let readerModeBarBottom = readerModeBar?.snp.bottom {
make.top.equalTo(readerModeBarBottom)
} else {
make.top.equalTo(self.header.snp.bottom)
}
let findInPageHeight = (findInPageBar == nil) ? 0 : UIConstants.ToolbarHeight
if let toolbar = self.toolbar {
make.bottom.equalTo(toolbar.snp.top).offset(-findInPageHeight)
} else {
make.bottom.equalTo(self.view).offset(-findInPageHeight)
}
}
// Setup the bottom toolbar
toolbar?.snp.remakeConstraints { make in
make.edges.equalTo(self.footer)
make.height.equalTo(UIConstants.BottomToolbarHeight)
}
footer.snp.remakeConstraints { make in
scrollController.footerBottomConstraint = make.bottom.equalTo(self.view.snp.bottom).constraint
make.leading.trailing.equalTo(self.view)
}
urlBar.setNeedsUpdateConstraints()
// Remake constraints even if we're already showing the home controller.
// The home controller may change sizes if we tap the URL bar while on about:home.
homePanelController?.view.snp.remakeConstraints { make in
make.top.equalTo(self.urlBar.snp.bottom)
make.left.right.equalTo(self.view)
if self.homePanelIsInline {
make.bottom.equalTo(self.toolbar?.snp.top ?? self.view.snp.bottom)
} else {
make.bottom.equalTo(self.view.snp.bottom)
}
}
alertStackView.snp.remakeConstraints { make in
make.centerX.equalTo(self.view)
make.width.equalTo(self.view.snp.width)
if let keyboardHeight = keyboardState?.intersectionHeightForView(self.view), keyboardHeight > 0 {
make.bottom.equalTo(self.view).offset(-keyboardHeight)
} else if let toolbar = self.toolbar {
make.bottom.equalTo(toolbar.snp.top)
} else {
make.bottom.equalTo(self.view)
}
}
}
fileprivate func showHomePanelController(inline: Bool) {
homePanelIsInline = inline
if homePanelController == nil {
let homePanelController = HomePanelViewController()
homePanelController.profile = profile
homePanelController.delegate = self
homePanelController.url = tabManager.selectedTab?.url?.displayURL
homePanelController.view.alpha = 0
self.homePanelController = homePanelController
addChildViewController(homePanelController)
view.addSubview(homePanelController.view)
homePanelController.didMove(toParentViewController: self)
}
guard let homePanelController = self.homePanelController else {
assertionFailure("homePanelController is still nil after assignment.")
return
}
let isPrivate = tabManager.selectedTab?.isPrivate ?? false
homePanelController.applyTheme(isPrivate ? Theme.Private : Theme.Normal)
let panelNumber = tabManager.selectedTab?.url?.fragment
// splitting this out to see if we can get better crash reports when this has a problem
var newSelectedButtonIndex = 0
if let numberArray = panelNumber?.components(separatedBy: "=") {
if let last = numberArray.last, let lastInt = Int(last) {
newSelectedButtonIndex = lastInt
}
}
homePanelController.selectedPanel = HomePanelType(rawValue: newSelectedButtonIndex)
// We have to run this animation, even if the view is already showing because there may be a hide animation running
// and we want to be sure to override its results.
UIView.animate(withDuration: 0.2, animations: { () -> Void in
homePanelController.view.alpha = 1
}, completion: { finished in
if finished {
self.webViewContainer.accessibilityElementsHidden = true
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
}
})
view.setNeedsUpdateConstraints()
}
fileprivate func hideHomePanelController() {
if let controller = homePanelController {
self.homePanelController = nil
UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: { () -> Void in
controller.view.alpha = 0
}, completion: { _ in
controller.willMove(toParentViewController: nil)
controller.view.removeFromSuperview()
controller.removeFromParentViewController()
self.webViewContainer.accessibilityElementsHidden = false
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
// Refresh the reading view toolbar since the article record may have changed
if let readerMode = self.tabManager.selectedTab?.getContentScript(name: ReaderMode.name()) as? ReaderMode, readerMode.state == .active {
self.showReaderModeBar(animated: false)
}
})
}
}
fileprivate func updateInContentHomePanel(_ url: URL?) {
if !urlBar.inOverlayMode {
guard let url = url else {
hideHomePanelController()
return
}
if url.isAboutHomeURL {
showHomePanelController(inline: true)
} else if !url.isLocalUtility || url.isReaderModeURL {
hideHomePanelController()
}
}
}
fileprivate func showSearchController() {
if searchController != nil {
return
}
let isPrivate = tabManager.selectedTab?.isPrivate ?? false
searchController = SearchViewController(isPrivate: isPrivate)
searchController!.searchEngines = profile.searchEngines
searchController!.searchDelegate = self
searchController!.profile = self.profile
searchLoader = SearchLoader(profile: profile, urlBar: urlBar)
searchLoader?.addListener(searchController!)
addChildViewController(searchController!)
view.addSubview(searchController!.view)
searchController!.view.snp.makeConstraints { make in
make.top.equalTo(self.urlBar.snp.bottom)
make.left.right.bottom.equalTo(self.view)
return
}
homePanelController?.view?.isHidden = true
searchController!.didMove(toParentViewController: self)
}
fileprivate func hideSearchController() {
if let searchController = searchController {
searchController.willMove(toParentViewController: nil)
searchController.view.removeFromSuperview()
searchController.removeFromParentViewController()
self.searchController = nil
homePanelController?.view?.isHidden = false
searchLoader = nil
}
}
func finishEditingAndSubmit(_ url: URL, visitType: VisitType) {
urlBar.currentURL = url
urlBar.leaveOverlayMode()
guard let tab = tabManager.selectedTab else {
return
}
if let webView = tab.webView {
resetSpoofedUserAgentIfRequired(webView, newURL: url)
}
if let nav = tab.loadRequest(PrivilegedRequest(url: url) as URLRequest) {
self.recordNavigationInTab(tab, navigation: nav, visitType: visitType)
}
}
func addBookmark(_ tabState: TabState) {
guard let url = tabState.url else { return }
let absoluteString = url.absoluteString
let shareItem = ShareItem(url: absoluteString, title: tabState.title, favicon: tabState.favicon)
_ = profile.bookmarks.shareItem(shareItem)
var userData = [QuickActions.TabURLKey: shareItem.url]
if let title = shareItem.title {
userData[QuickActions.TabTitleKey] = title
}
QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(.openLastBookmark,
withUserData: userData,
toApplication: UIApplication.shared)
}
override func accessibilityPerformEscape() -> Bool {
if urlBar.inOverlayMode {
urlBar.didClickCancel()
return true
} else if let selectedTab = tabManager.selectedTab, selectedTab.canGoBack {
selectedTab.goBack()
return true
}
return false
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
let webView = object as! WKWebView
guard let kp = keyPath, let path = KVOConstants(rawValue: kp) else {
assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")")
return
}
switch path {
case .estimatedProgress:
guard webView == tabManager.selectedTab?.webView,
let progress = change?[.newKey] as? Float else { break }
if !(webView.url?.isLocalUtility ?? false) {
urlBar.updateProgressBar(progress)
} else {
urlBar.hideProgressBar()
}
case .loading:
guard let loading = change?[.newKey] as? Bool else { break }
if webView == tabManager.selectedTab?.webView {
navigationToolbar.updateReloadStatus(loading)
}
if !loading {
runScriptsOnWebView(webView)
}
case .URL:
guard let tab = tabManager[webView] else { break }
// To prevent spoofing, only change the URL immediately if the new URL is on
// the same origin as the current URL. Otherwise, do nothing and wait for
// didCommitNavigation to confirm the page load.
if tab.url?.origin == webView.url?.origin {
tab.url = webView.url
if tab === tabManager.selectedTab && !tab.restoring {
updateUIForReaderHomeStateForTab(tab)
}
}
case .title:
guard let tab = tabManager[webView] else { break }
// Ensure that the tab title *actually* changed to prevent repeated calls
// to navigateInTab(tab:).
guard let title = tab.title else { break }
if !title.isEmpty && title != tab.lastTitle {
navigateInTab(tab: tab)
}
case .canGoBack:
guard webView == tabManager.selectedTab?.webView,
let canGoBack = change?[.newKey] as? Bool else { break }
navigationToolbar.updateBackStatus(canGoBack)
case .canGoForward:
guard webView == tabManager.selectedTab?.webView,
let canGoForward = change?[.newKey] as? Bool else { break }
navigationToolbar.updateForwardStatus(canGoForward)
default:
assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")")
}
}
fileprivate func runScriptsOnWebView(_ webView: WKWebView) {
guard let url = webView.url, url.isWebPage(), !url.isLocal else {
return
}
if #available(iOS 11, *) {
if NoImageModeHelper.isActivated(profile.prefs) {
webView.evaluateJavaScript("__firefox__.NoImageMode.setEnabled(true)", completionHandler: nil)
}
}
}
func updateUIForReaderHomeStateForTab(_ tab: Tab) {
updateURLBarDisplayURL(tab)
scrollController.showToolbars(animated: false)
if let url = tab.url {
if url.isReaderModeURL {
showReaderModeBar(animated: false)
NotificationCenter.default.addObserver(self, selector: #selector(dynamicFontChanged), name: .DynamicFontChanged, object: nil)
} else {
hideReaderModeBar(animated: false)
NotificationCenter.default.removeObserver(self, name: .DynamicFontChanged, object: nil)
}
updateInContentHomePanel(url as URL)
}
}
/// Updates the URL bar text and button states.
/// Call this whenever the page URL changes.
fileprivate func updateURLBarDisplayURL(_ tab: Tab) {
urlBar.currentURL = tab.url?.displayURL
let isPage = tab.url?.displayURL?.isWebPage() ?? false
navigationToolbar.updatePageStatus(isPage)
}
// MARK: Opening New Tabs
func switchToPrivacyMode(isPrivate: Bool ) {
// applyTheme(isPrivate ? Theme.PrivateMode : Theme.NormalMode)
let tabTrayController = self.tabTrayController ?? TabTrayController(tabManager: tabManager, profile: profile, tabTrayDelegate: self)
if tabTrayController.privateMode != isPrivate {
tabTrayController.changePrivacyMode(isPrivate)
}
self.tabTrayController = tabTrayController
}
func switchToTabForURLOrOpen(_ url: URL, isPrivate: Bool = false, isPrivileged: Bool) {
popToBVC()
if let tab = tabManager.getTabForURL(url) {
tabManager.selectTab(tab)
} else {
openURLInNewTab(url, isPrivate: isPrivate, isPrivileged: isPrivileged)
}
}
func openURLInNewTab(_ url: URL?, isPrivate: Bool = false, isPrivileged: Bool) {
if let selectedTab = tabManager.selectedTab {
screenshotHelper.takeScreenshot(selectedTab)
}
let request: URLRequest?
if let url = url {
request = isPrivileged ? PrivilegedRequest(url: url) as URLRequest : URLRequest(url: url)
} else {
request = nil
}
switchToPrivacyMode(isPrivate: isPrivate)
_ = tabManager.addTabAndSelect(request, isPrivate: isPrivate)
if url == nil && NewTabAccessors.getNewTabPage(profile.prefs) == .blankPage {
urlBar.tabLocationViewDidTapLocation(urlBar.locationView)
}
}
func openBlankNewTab(focusLocationField: Bool, isPrivate: Bool = false) {
popToBVC()
openURLInNewTab(nil, isPrivate: isPrivate, isPrivileged: true)
let freshTab = tabManager.selectedTab
if focusLocationField {
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(300)) {
// Without a delay, the text field fails to become first responder
// Check that the newly created tab is still selected.
// This let's the user spam the Cmd+T button without lots of responder changes.
if freshTab == self.tabManager.selectedTab {
self.urlBar.tabLocationViewDidTapLocation(self.urlBar.locationView)
}
}
}
}
fileprivate func popToBVC() {
guard let currentViewController = navigationController?.topViewController else {
return
}
currentViewController.dismiss(animated: true, completion: nil)