-
Notifications
You must be signed in to change notification settings - Fork 405
/
MainViewController.swift
2622 lines (2152 loc) · 93.5 KB
/
MainViewController.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
//
// MainViewController.swift
// DuckDuckGo
//
// Copyright © 2017 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import WebKit
import WidgetKit
import Combine
import Common
import Core
import DDGSync
import Kingfisher
import BrowserServicesKit
import Bookmarks
import Persistence
import PrivacyDashboard
import Networking
import Suggestions
import Subscription
import SwiftUI
#if NETWORK_PROTECTION
import NetworkProtection
#endif
// swiftlint:disable file_length
// swiftlint:disable type_body_length
class MainViewController: UIViewController {
// swiftlint:enable type_body_length
override var preferredStatusBarStyle: UIStatusBarStyle {
return ThemeManager.shared.currentTheme.statusBarStyle
}
override var preferredScreenEdgesDeferringSystemGestures: UIRectEdge {
let isIPad = UIDevice.current.userInterfaceIdiom == .pad
return isIPad ? [.left, .right] : []
}
weak var findInPageView: FindInPageView!
weak var findInPageHeightLayoutConstraint: NSLayoutConstraint!
weak var findInPageBottomLayoutConstraint: NSLayoutConstraint!
weak var notificationView: UIView?
var chromeManager: BrowserChromeManager!
var allowContentUnderflow = false {
didSet {
viewCoordinator.constraints.contentContainerTop.constant = allowContentUnderflow ? contentUnderflow : 0
}
}
var contentUnderflow: CGFloat {
return 3 + (allowContentUnderflow ? -viewCoordinator.navigationBarContainer.frame.size.height : 0)
}
var isShowingAutocompleteSuggestions: Bool {
suggestionTrayController?.isShowingAutocompleteSuggestions == true
}
lazy var emailManager: EmailManager = {
let emailManager = EmailManager()
emailManager.aliasPermissionDelegate = self
emailManager.requestDelegate = self
return emailManager
}()
var homeViewController: HomeViewController?
var newTabPageViewController: NewTabPageViewController?
var homeController: NewTabPage? {
homeViewController ?? newTabPageViewController
}
var tabsBarController: TabsBarViewController?
var suggestionTrayController: SuggestionTrayViewController?
let homeTabManager: NewTabPageManager
let tabManager: TabManager
let previewsSource: TabPreviewsSource
let appSettings: AppSettings
private var launchTabObserver: LaunchTabNotification.Observer?
var autoClearInProgress = false
var autoClearShouldRefreshUIAfterClear = true
let bookmarksDatabase: CoreDataDatabase
private weak var bookmarksDatabaseCleaner: BookmarkDatabaseCleaner?
private var favoritesViewModel: FavoritesListInteracting
let syncService: DDGSyncing
let syncDataProviders: SyncDataProviders
let syncPausedStateManager: any SyncPausedStateManaging
@UserDefaultsWrapper(key: .syncDidShowSyncPausedByFeatureFlagAlert, defaultValue: false)
private var syncDidShowSyncPausedByFeatureFlagAlert: Bool
private var localUpdatesCancellable: AnyCancellable?
private var syncUpdatesCancellable: AnyCancellable?
private var syncFeatureFlagsCancellable: AnyCancellable?
private var favoritesDisplayModeCancellable: AnyCancellable?
private var emailCancellables = Set<AnyCancellable>()
private var urlInterceptorCancellables = Set<AnyCancellable>()
#if NETWORK_PROTECTION
private let tunnelDefaults = UserDefaults.networkProtectionGroupDefaults
private var vpnCancellables = Set<AnyCancellable>()
#endif
private lazy var featureFlagger = AppDependencyProvider.shared.featureFlagger
lazy var menuBookmarksViewModel: MenuBookmarksInteracting = {
let viewModel = MenuBookmarksViewModel(bookmarksDatabase: bookmarksDatabase, syncService: syncService)
viewModel.favoritesDisplayMode = appSettings.favoritesDisplayMode
return viewModel
}()
weak var tabSwitcherController: TabSwitcherViewController?
let tabSwitcherButton = TabSwitcherButton()
/// Do not reference directly, use `presentedMenuButton`
let menuButton = MenuButton()
var presentedMenuButton: MenuButton {
AppWidthObserver.shared.isLargeWidth ? viewCoordinator.omniBar.menuButtonContent : menuButton
}
let gestureBookmarksButton = GestureToolbarButton()
private lazy var fireButtonAnimator: FireButtonAnimator = FireButtonAnimator(appSettings: appSettings)
let bookmarksCachingSearch: BookmarksCachingSearch
lazy var tabSwitcherTransition = TabSwitcherTransitionDelegate()
var currentTab: TabViewController? {
return tabManager.current(createIfNeeded: false)
}
var searchBarRect: CGRect {
let view = UIApplication.shared.windows.filter({ $0.isKeyWindow }).first?.rootViewController?.view
return viewCoordinator.omniBar.searchContainer.convert(viewCoordinator.omniBar.searchContainer.bounds, to: view)
}
var keyModifierFlags: UIKeyModifierFlags?
var showKeyboardAfterFireButton: DispatchWorkItem?
// Skip SERP flow (focusing on autocomplete logic) and prepare for new navigation when selecting search bar
private var skipSERPFlow = true
private var keyboardHeight: CGFloat = 0.0
var postClear: (() -> Void)?
var clearInProgress = false
var dataStoreWarmup: DataStoreWarmup? = DataStoreWarmup()
required init?(coder: NSCoder) {
fatalError("Use init?(code:")
}
var historyManager: HistoryManager
var viewCoordinator: MainViewCoordinator!
init(
bookmarksDatabase: CoreDataDatabase,
bookmarksDatabaseCleaner: BookmarkDatabaseCleaner,
historyManager: HistoryManager,
syncService: DDGSyncing,
syncDataProviders: SyncDataProviders,
appSettings: AppSettings,
previewsSource: TabPreviewsSource,
tabsModel: TabsModel,
syncPausedStateManager: any SyncPausedStateManaging
) {
self.bookmarksDatabase = bookmarksDatabase
self.bookmarksDatabaseCleaner = bookmarksDatabaseCleaner
self.historyManager = historyManager
self.syncService = syncService
self.syncDataProviders = syncDataProviders
self.favoritesViewModel = FavoritesListViewModel(bookmarksDatabase: bookmarksDatabase, favoritesDisplayMode: appSettings.favoritesDisplayMode)
self.bookmarksCachingSearch = BookmarksCachingSearch(bookmarksStore: CoreDataBookmarksSearchStore(bookmarksStore: bookmarksDatabase))
self.appSettings = appSettings
self.previewsSource = previewsSource
self.tabManager = TabManager(model: tabsModel,
previewsSource: previewsSource,
bookmarksDatabase: bookmarksDatabase,
historyManager: historyManager,
syncService: syncService)
self.syncPausedStateManager = syncPausedStateManager
self.homeTabManager = NewTabPageManager()
super.init(nibName: nil, bundle: nil)
tabManager.delegate = self
bindSyncService()
}
func loadFindInPage() {
let view = FindInPageView.loadFromXib()
self.view.addSubview(view)
// Avoids coercion swiftlint warnings
let superview = self.view!
let height = view.constrainAttribute(.height, to: view.frame.height)
let bottom = superview.constrainView(view, by: .bottom, to: .bottom)
NSLayoutConstraint.activate([
bottom,
superview.constrainView(view, by: .width, to: .width),
height,
superview.constrainView(view, by: .centerX, to: .centerX)
])
findInPageView = view
findInPageBottomLayoutConstraint = bottom
findInPageHeightLayoutConstraint = height
}
var swipeTabsCoordinator: SwipeTabsCoordinator?
override func viewDidLoad() {
super.viewDidLoad()
viewCoordinator = MainViewFactory.createViewHierarchy(self.view)
viewCoordinator.moveAddressBarToPosition(appSettings.currentAddressBarPosition)
viewCoordinator.toolbarBackButton.action = #selector(onBackPressed)
viewCoordinator.toolbarForwardButton.action = #selector(onForwardPressed)
viewCoordinator.toolbarFireButton.action = #selector(onFirePressed)
installSwipeTabs()
loadSuggestionTray()
loadTabsBarIfNeeded()
loadFindInPage()
attachOmniBar()
view.addInteraction(UIDropInteraction(delegate: self))
chromeManager = BrowserChromeManager()
chromeManager.delegate = self
initTabButton()
initMenuButton()
initBookmarksButton()
loadInitialView()
previewsSource.prepare()
addLaunchTabNotificationObserver()
subscribeToEmailProtectionStatusNotifications()
subscribeToURLInterceptorNotifications()
#if NETWORK_PROTECTION
subscribeToNetworkProtectionEvents()
#endif
findInPageView.delegate = self
findInPageBottomLayoutConstraint.constant = 0
registerForKeyboardNotifications()
registerForSyncFeatureFlagsUpdates()
decorate()
tabsBarController?.refresh(tabsModel: tabManager.model, scrollToSelected: true)
swipeTabsCoordinator?.refresh(tabsModel: tabManager.model, scrollToSelected: true)
_ = AppWidthObserver.shared.willResize(toWidth: view.frame.width)
applyWidth()
registerForApplicationEvents()
registerForCookiesManagedNotification()
registerForSettingsChangeNotifications()
tabManager.cleanupTabsFaviconCache()
// Needs to be called here to established correct view hierarchy
refreshViewsBasedOnAddressBarPosition(appSettings.currentAddressBarPosition)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Needs to be called here because sometimes the frames are not the expected size during didLoad
refreshViewsBasedOnAddressBarPosition(appSettings.currentAddressBarPosition)
startOnboardingFlowIfNotSeenBefore()
tabsBarController?.refresh(tabsModel: tabManager.model)
swipeTabsCoordinator?.refresh(tabsModel: tabManager.model, scrollToSelected: true)
_ = AppWidthObserver.shared.willResize(toWidth: view.frame.width)
applyWidth()
if DaxDialogs.shared.shouldShowFireButtonPulse {
showFireButtonPulse()
}
}
override func performSegue(withIdentifier identifier: String, sender: Any?) {
assertionFailure()
super.performSegue(withIdentifier: identifier, sender: sender)
}
private func installSwipeTabs() {
guard swipeTabsCoordinator == nil else { return }
swipeTabsCoordinator = SwipeTabsCoordinator(coordinator: viewCoordinator,
tabPreviewsSource: previewsSource,
appSettings: appSettings) { [weak self] in
guard $0 != self?.tabManager.model.currentIndex else { return }
DailyPixel.fire(pixel: .swipeTabsUsedDaily)
self?.select(tabAt: $0)
} newTab: { [weak self] in
Pixel.fire(pixel: .swipeToOpenNewTab)
self?.newTab()
} onSwipeStarted: { [weak self] in
self?.performCancel()
self?.hideKeyboard()
self?.updatePreviewForCurrentTab()
}
}
func updatePreviewForCurrentTab(completion: (() -> Void)? = nil) {
assert(Thread.isMainThread)
if !viewCoordinator.logoContainer.isHidden,
self.tabManager.current()?.link == nil,
let tab = self.tabManager.model.currentTab {
// Home screen with logo
if let image = viewCoordinator.logoContainer.createImageSnapshot(inBounds: viewCoordinator.contentContainer.frame) {
previewsSource.update(preview: image, forTab: tab)
completion?()
}
} else if let currentTab = self.tabManager.current(), currentTab.link != nil {
// Web view
currentTab.preparePreview(completion: { image in
guard let image else { return }
self.previewsSource.update(preview: image,
forTab: currentTab.tabModel)
completion?()
})
} else if let tab = self.tabManager.model.currentTab {
// Favorites, etc
if let image = viewCoordinator.contentContainer.createImageSnapshot() {
previewsSource.update(preview: image, forTab: tab)
completion?()
}
} else {
completion?()
}
}
func loadSuggestionTray() {
let storyboard = UIStoryboard(name: "SuggestionTray", bundle: nil)
guard let controller = storyboard.instantiateInitialViewController(creator: { coder in
SuggestionTrayViewController(coder: coder,
favoritesViewModel: self.favoritesViewModel,
bookmarksDatabase: self.bookmarksDatabase,
historyManager: self.historyManager)
}) else {
assertionFailure()
return
}
controller.view.frame = viewCoordinator.suggestionTrayContainer.bounds
viewCoordinator.suggestionTrayContainer.addSubview(controller.view)
controller.dismissHandler = dismissSuggestionTray
controller.autocompleteDelegate = self
controller.favoritesOverlayDelegate = self
suggestionTrayController = controller
}
func loadTabsBarIfNeeded() {
guard isPad else { return }
let storyboard = UIStoryboard(name: "TabSwitcher", bundle: nil)
let controller: TabsBarViewController = storyboard.instantiateViewController(identifier: "TabsBar")
controller.view.frame = viewCoordinator.tabBarContainer.bounds
controller.delegate = self
viewCoordinator.tabBarContainer.addSubview(controller.view)
tabsBarController = controller
}
func startAddFavoriteFlow() {
DaxDialogs.shared.enableAddFavoriteFlow()
if DefaultTutorialSettings().hasSeenOnboarding {
newTab()
}
}
func startOnboardingFlowIfNotSeenBefore() {
guard ProcessInfo.processInfo.environment["ONBOARDING"] != "false" else {
// explicitly skip onboarding, e.g. for integration tests
return
}
let settings = DefaultTutorialSettings()
let showOnboarding = !settings.hasSeenOnboarding ||
// explicitly show onboarding, can be set in the scheme > Run > Environment Variables
ProcessInfo.processInfo.environment["ONBOARDING"] == "true"
guard showOnboarding else { return }
segueToDaxOnboarding()
}
private func registerForKeyboardNotifications() {
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillChangeFrame),
name: UIResponder.keyboardWillChangeFrameNotification,
object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide),
name: UIResponder.keyboardWillHideNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow),
name: UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide),
name: UIResponder.keyboardDidHideNotification, object: nil)
}
var keyboardShowing = false
@objc
private func keyboardDidShow() {
keyboardShowing = true
}
@objc
private func keyboardWillHide() {
if homeController?.isDragging == true, keyboardShowing {
Pixel.fire(pixel: .addressBarGestureDismiss)
}
}
@objc
private func keyboardDidHide() {
keyboardShowing = false
}
private func registerForSyncFeatureFlagsUpdates() {
syncFeatureFlagsCancellable = syncService.featureFlagsPublisher
.dropFirst()
.map { $0.contains(.dataSyncing) }
.receive(on: DispatchQueue.main)
.sink { [weak self] isDataSyncingAvailable in
guard let self else {
return
}
if isDataSyncingAvailable {
self.syncDidShowSyncPausedByFeatureFlagAlert = false
} else if self.syncService.authState == .active, !self.syncDidShowSyncPausedByFeatureFlagAlert {
self.showSyncPausedByFeatureFlagAlert()
self.syncDidShowSyncPausedByFeatureFlagAlert = true
}
}
}
private func showSyncPausedByFeatureFlagAlert(upgradeRequired: Bool = false) {
let title = UserText.syncPausedTitle
let description = upgradeRequired ? UserText.syncUnavailableMessageUpgradeRequired : UserText.syncUnavailableMessage
if self.presentedViewController is SyncSettingsViewController {
return
}
self.presentedViewController?.dismiss(animated: true)
let alert = UIAlertController(title: title,
message: description,
preferredStyle: .alert)
if syncService.featureFlags.contains(.userInterface) {
let learnMoreAction = UIAlertAction(title: UserText.syncPausedAlertLearnMoreButton, style: .default) { _ in
self.segueToSettingsSync()
}
alert.addAction(learnMoreAction)
}
alert.addAction(UIAlertAction(title: UserText.syncPausedAlertOkButton, style: .cancel))
self.present(alert, animated: true)
}
func registerForSettingsChangeNotifications() {
NotificationCenter.default.addObserver(self, selector:
#selector(onAddressBarPositionChanged),
name: AppUserDefaults.Notifications.addressBarPositionChanged,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(onShowFullURLAddressChanged),
name: AppUserDefaults.Notifications.showsFullURLAddressSettingChanged,
object: nil)
}
@objc func onAddressBarPositionChanged() {
viewCoordinator.moveAddressBarToPosition(appSettings.currentAddressBarPosition)
refreshViewsBasedOnAddressBarPosition(appSettings.currentAddressBarPosition)
updateStatusBarBackgroundColor()
}
@objc private func onShowFullURLAddressChanged() {
refreshOmniBar()
}
func refreshViewsBasedOnAddressBarPosition(_ position: AddressBarPosition) {
switch position {
case .top:
swipeTabsCoordinator?.addressBarPositionChanged(isTop: true)
viewCoordinator.omniBar.moveSeparatorToBottom()
viewCoordinator.showToolbarSeparator()
viewCoordinator.constraints.navigationBarContainerBottom.isActive = false
case .bottom:
swipeTabsCoordinator?.addressBarPositionChanged(isTop: false)
viewCoordinator.omniBar.moveSeparatorToTop()
// If this is called before the toolbar has shown it will not re-add the separator when moving to the top position
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
self.viewCoordinator.hideToolbarSeparator()
}
}
}
@objc func onShowFullSiteAddressChanged() {
refreshOmniBar()
}
/// Based on https://stackoverflow.com/a/46117073/73479
/// Handles iPhone X devices properly.
@objc private func keyboardWillChangeFrame(_ notification: Notification) {
guard let userInfo = notification.userInfo,
let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
return
}
let duration: TimeInterval = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
let animationCurveRawNSN = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber
let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIView.AnimationOptions.curveEaseInOut.rawValue
let animationCurve = UIView.AnimationOptions(rawValue: animationCurveRaw)
var height = keyboardFrame.size.height
let keyboardFrameInView = view.convert(keyboardFrame, from: nil)
let safeAreaFrame = view.safeAreaLayoutGuide.layoutFrame.insetBy(dx: 0, dy: -additionalSafeAreaInsets.bottom)
let intersection = safeAreaFrame.intersection(keyboardFrameInView)
height = intersection.height
findInPageBottomLayoutConstraint.constant = height
keyboardHeight = height
if let suggestionsTray = suggestionTrayController {
let suggestionsFrameInView = suggestionsTray.view.convert(suggestionsTray.contentFrame, to: view)
let overflow = suggestionsFrameInView.intersection(keyboardFrameInView).height
if overflow > 0 && !appSettings.currentAddressBarPosition.isBottom {
suggestionsTray.applyContentInset(UIEdgeInsets(top: 0, left: 0, bottom: overflow, right: 0))
} else {
suggestionsTray.applyContentInset(.zero)
}
}
let y = self.view.frame.height - height
let frame = self.findInPageView.frame
UIView.animate(withDuration: duration, delay: 0, options: animationCurve, animations: {
self.findInPageView.frame = CGRect(x: 0, y: y - frame.height, width: frame.width, height: frame.height)
}, completion: nil)
if self.appSettings.currentAddressBarPosition.isBottom {
let navBarOffset = min(0, self.toolbarHeight - intersection.height)
self.viewCoordinator.constraints.navigationBarCollectionViewBottom.constant = navBarOffset
UIView.animate(withDuration: duration, delay: 0, options: animationCurve) {
self.viewCoordinator.navigationBarContainer.superview?.layoutIfNeeded()
}
}
}
private func initTabButton() {
tabSwitcherButton.delegate = self
viewCoordinator.toolbarTabSwitcherButton.customView = tabSwitcherButton
viewCoordinator.toolbarTabSwitcherButton.isAccessibilityElement = true
viewCoordinator.toolbarTabSwitcherButton.accessibilityTraits = .button
}
private func initMenuButton() {
viewCoordinator.lastToolbarButton.customView = menuButton
viewCoordinator.lastToolbarButton.isAccessibilityElement = true
viewCoordinator.lastToolbarButton.accessibilityTraits = .button
menuButton.delegate = self
}
private func initBookmarksButton() {
viewCoordinator.omniBar.bookmarksButton.addGestureRecognizer(UILongPressGestureRecognizer(target: self,
action: #selector(quickSaveBookmarkLongPress(gesture:))))
gestureBookmarksButton.delegate = self
gestureBookmarksButton.image = UIImage(named: "Bookmarks")
}
private func bindFavoritesDisplayMode() {
favoritesDisplayModeCancellable = NotificationCenter.default.publisher(for: AppUserDefaults.Notifications.favoritesDisplayModeChange)
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
guard let self else {
return
}
self.menuBookmarksViewModel.favoritesDisplayMode = self.appSettings.favoritesDisplayMode
self.favoritesViewModel.favoritesDisplayMode = self.appSettings.favoritesDisplayMode
self.homeController?.reloadFavorites()
WidgetCenter.shared.reloadAllTimelines()
}
}
private func bindSyncService() {
localUpdatesCancellable = favoritesViewModel.localUpdates
.sink { [weak self] in
self?.syncService.scheduler.notifyDataChanged()
}
syncUpdatesCancellable = syncDataProviders.bookmarksAdapter.syncDidCompletePublisher
.sink { [weak self] _ in
self?.favoritesViewModel.reloadData()
DispatchQueue.main.async {
self?.homeController?.reloadFavorites()
}
}
}
@objc func quickSaveBookmarkLongPress(gesture: UILongPressGestureRecognizer) {
if gesture.state == .began {
quickSaveBookmark()
}
}
@objc func quickSaveBookmark() {
UIImpactFeedbackGenerator(style: .heavy).impactOccurred()
guard currentTab != nil else {
ActionMessageView.present(message: UserText.webSaveBookmarkNone,
presentationLocation: .withBottomBar(andAddressBarBottom: appSettings.currentAddressBarPosition.isBottom))
return
}
Pixel.fire(pixel: .tabBarBookmarksLongPressed)
currentTab?.saveAsBookmark(favorite: true, viewModel: menuBookmarksViewModel)
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if let presentedViewController {
return presentedViewController.supportedInterfaceOrientations
}
return DefaultTutorialSettings().hasSeenOnboarding ? [.allButUpsideDown] : [.portrait]
}
override var shouldAutorotate: Bool {
return true
}
@objc func dismissSuggestionTray() {
omniBar.cancel()
dismissOmniBar()
}
private func addLaunchTabNotificationObserver() {
launchTabObserver = LaunchTabNotification.addObserver(handler: { [weak self] urlString in
guard let self = self else { return }
if let url = URL(string: urlString) {
self.loadUrlInNewTab(url, inheritedAttribution: nil)
} else {
self.loadQuery(urlString)
}
})
}
private func loadInitialView() {
// if let tab = currentTab, tab.link != nil {
// if let tab = tabManager.current(create: true), tab.link != nil {
if tabManager.model.currentTab?.link != nil {
guard let tab = tabManager.current(createIfNeeded: true) else {
fatalError("Unable to create tab")
}
attachTab(tab: tab)
refreshControls()
} else {
attachHomeScreen()
}
}
func handlePressEvent(event: UIPressesEvent?) {
keyModifierFlags = event?.modifierFlags
}
override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
super.pressesBegan(presses, with: event)
handlePressEvent(event: event)
}
override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
super.pressesEnded(presses, with: event)
handlePressEvent(event: event)
}
private func attachOmniBar() {
viewCoordinator.omniBar.omniDelegate = self
viewCoordinator.omniBar.menuButtonContent.delegate = self
}
fileprivate func attachHomeScreen() {
guard !autoClearInProgress else { return }
viewCoordinator.logoContainer.isHidden = false
findInPageView.isHidden = true
chromeManager.detach()
currentTab?.dismiss()
removeHomeScreen()
AppDependencyProvider.shared.homePageConfiguration.refresh()
// Access the tab model directly as we don't want to create a new tab controller here
guard let tabModel = tabManager.model.currentTab else {
fatalError("No tab model")
}
if homeTabManager.isNewTabPageSectionsEnabled {
let controller = NewTabPageViewController()
newTabPageViewController = controller
addToContentContainer(controller: controller)
viewCoordinator.logoContainer.isHidden = true
} else {
let controller = HomeViewController.loadFromStoryboard(model: tabModel,
favoritesViewModel: favoritesViewModel,
appSettings: appSettings,
syncService: syncService,
syncDataProviders: syncDataProviders)
controller.delegate = self
controller.chromeDelegate = self
homeViewController = controller
addToContentContainer(controller: controller)
}
refreshControls()
syncService.scheduler.requestSyncImmediately()
}
fileprivate func removeHomeScreen() {
homeController?.willMove(toParent: nil)
homeController?.dismiss()
homeViewController = nil
newTabPageViewController = nil
}
@IBAction func onFirePressed() {
Pixel.fire(pixel: .forgetAllPressedBrowsing)
wakeLazyFireButtonAnimator()
if let spec = DaxDialogs.shared.fireButtonEducationMessage() {
segueToActionSheetDaxDialogWithSpec(spec)
} else {
let alert = ForgetDataAlert.buildAlert(forgetTabsAndDataHandler: { [weak self] in
self?.forgetAllWithAnimation {}
})
self.present(controller: alert, fromView: self.viewCoordinator.toolbar)
}
performCancel()
}
func onQuickFirePressed() {
wakeLazyFireButtonAnimator()
forgetAllWithAnimation {}
dismiss(animated: true)
if KeyboardSettings().onAppLaunch {
enterSearch()
}
}
private func wakeLazyFireButtonAnimator() {
DispatchQueue.main.async {
_ = self.fireButtonAnimator
}
}
@IBAction func onBackPressed() {
Pixel.fire(pixel: .tabBarBackPressed)
performCancel()
hideSuggestionTray()
currentTab?.goBack()
}
@IBAction func onForwardPressed() {
Pixel.fire(pixel: .tabBarForwardPressed)
performCancel()
hideSuggestionTray()
currentTab?.goForward()
}
func didReturnFromBackground() {
skipSERPFlow = true
if DaxDialogs.shared.shouldShowFireButtonPulse {
showFireButtonPulse()
}
}
func loadQueryInNewTab(_ query: String, reuseExisting: Bool = false) {
dismissOmniBar()
guard let url = URL.makeSearchURL(query: query) else {
os_log("Couldn‘t form URL for query “%s”", log: .lifecycleLog, type: .error, query)
return
}
loadUrlInNewTab(url, reuseExisting: reuseExisting, inheritedAttribution: nil)
}
func loadUrlInNewTab(_ url: URL, reuseExisting: Bool = false, inheritedAttribution: AdClickAttributionLogic.State?, fromExternalLink: Bool = false) {
func worker() {
allowContentUnderflow = false
viewCoordinator.navigationBarContainer.alpha = 1
loadViewIfNeeded()
if reuseExisting, let existing = tabManager.first(withUrl: url) {
selectTab(existing)
return
} else if reuseExisting, let existing = tabManager.firstHomeTab() {
if autoClearInProgress {
autoClearShouldRefreshUIAfterClear = false
}
tabManager.selectTab(existing)
loadUrl(url, fromExternalLink: fromExternalLink)
} else {
addTab(url: url, inheritedAttribution: inheritedAttribution, fromExternalLink: fromExternalLink)
}
refreshOmniBar()
refreshTabIcon()
refreshControls()
tabsBarController?.refresh(tabsModel: tabManager.model)
swipeTabsCoordinator?.refresh(tabsModel: tabManager.model, scrollToSelected: true)
}
if clearInProgress {
postClear = worker
} else {
worker()
}
}
func enterSearch() {
if presentedViewController == nil {
showBars()
viewCoordinator.omniBar.becomeFirstResponder()
}
}
fileprivate func loadQuery(_ query: String) {
guard let url = URL.makeSearchURL(query: query, queryContext: currentTab?.url) else {
os_log("Couldn‘t form URL for query “%s” with context “%s”",
log: .lifecycleLog,
type: .error,
query,
currentTab?.url?.absoluteString ?? "<nil>")
return
}
loadUrl(url)
}
func loadUrl(_ url: URL, fromExternalLink: Bool = false) {
prepareTabForRequest {
self.currentTab?.load(url: url)
if fromExternalLink {
self.currentTab?.inferredOpenerContext = .external
}
}
}
func executeBookmarklet(_ url: URL) {
if url.isBookmarklet() {
currentTab?.executeBookmarklet(url: url)
}
}
private func loadBackForwardItem(_ item: WKBackForwardListItem) {
prepareTabForRequest {
currentTab?.load(backForwardListItem: item)
}
}
private func prepareTabForRequest(request: () -> Void) {
viewCoordinator.navigationBarContainer.alpha = 1
allowContentUnderflow = false
if currentTab == nil {
if tabManager.current(createIfNeeded: true) == nil {
fatalError("failed to create tab")
}
}
guard let tab = currentTab else { fatalError("no tab") }
request()
dismissOmniBar()
select(tab: tab)
}
private func addTab(url: URL?, inheritedAttribution: AdClickAttributionLogic.State?, fromExternalLink: Bool = false) {
let tab = tabManager.add(url: url, inheritedAttribution: inheritedAttribution)
tab.inferredOpenerContext = .external
dismissOmniBar()
attachTab(tab: tab)
}
func select(tabAt index: Int) {
viewCoordinator.navigationBarContainer.alpha = 1
allowContentUnderflow = false
if tabManager.model.tabs.indices.contains(index) {
let tab = tabManager.select(tabAt: index)
select(tab: tab)
} else {
assertionFailure("Invalid index selected")
}
}
fileprivate func select(tab: TabViewController) {
if tab.link == nil {
attachHomeScreen()
} else {
attachTab(tab: tab)
refreshControls()
}
tabsBarController?.refresh(tabsModel: tabManager.model, scrollToSelected: true)
swipeTabsCoordinator?.refresh(tabsModel: tabManager.model, scrollToSelected: true)
if DaxDialogs.shared.shouldShowFireButtonPulse {
showFireButtonPulse()
}
}
private func attachTab(tab: TabViewController) {
removeHomeScreen()
updateFindInPage()
currentTab?.progressWorker.progressBar = nil
currentTab?.chromeDelegate = nil
addToContentContainer(controller: tab)
viewCoordinator.logoContainer.isHidden = true
tab.progressWorker.progressBar = viewCoordinator.progress
chromeManager.attach(to: tab.webView.scrollView)
tab.chromeDelegate = self
}
private func addToContentContainer(controller: UIViewController) {
viewCoordinator.contentContainer.isHidden = false
addChild(controller)
viewCoordinator.contentContainer.subviews.forEach { $0.removeFromSuperview() }
viewCoordinator.contentContainer.addSubview(controller.view)
controller.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
controller.view.frame = viewCoordinator.contentContainer.bounds
controller.didMove(toParent: self)
}
fileprivate func updateCurrentTab() {
if let currentTab = currentTab {
select(tab: currentTab)
viewCoordinator.omniBar.resignFirstResponder()
} else {
attachHomeScreen()
}
}
fileprivate func refreshControls() {
refreshTabIcon()
refreshMenuButtonState()
refreshOmniBar()
refreshBackForwardButtons()
refreshBackForwardMenuItems()
}
private func refreshTabIcon() {
viewCoordinator.toolbarTabSwitcherButton.accessibilityHint = UserText.numberOfTabs(tabManager.count)
tabSwitcherButton.tabCount = tabManager.count
tabSwitcherButton.hasUnread = tabManager.hasUnread
}
private func refreshOmniBar() {
guard let tab = currentTab, tab.link != nil else {
viewCoordinator.omniBar.stopBrowsing()
return