-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathMainViewController.swift
More file actions
5734 lines (4832 loc) · 228 KB
/
MainViewController.swift
File metadata and controls
5734 lines (4832 loc) · 228 KB
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 UIKitExtensions
import WebKit
import WidgetKit
import Combine
import Common
import Core
import DDGSync
import Kingfisher
import BrowserServicesKit
import Bookmarks
import Persistence
import RemoteMessaging
import PrivacyDashboard
import Networking
import Suggestions
import Subscription
import SwiftUI
import VPN
import Onboarding
import os.log
import PageRefreshMonitor
import BrokenSitePrompt
import AIChat
import NetworkExtension
import DesignResourcesKit
import DesignResourcesKitIcons
import Configuration
import PixelKit
import SystemSettingsPiPTutorial
import DataBrokerProtection_iOS
import UserScript
import PrivacyConfig
import WebExtensions
struct StartupOnboardingDecision {
let shouldShowOnboarding: Bool
init(onboardingStatus: LaunchOptionsHandler.OnboardingStatus, tutorialSettings: TutorialSettings) {
switch onboardingStatus {
case .notOverridden:
shouldShowOnboarding = !tutorialSettings.hasSeenOnboarding
case let .overridden(.developer(completed: isOnboardingCompleted)):
shouldShowOnboarding = !isOnboardingCompleted
case let .overridden(.uiTests(completed: isOnboardingCompleted)):
tutorialSettings.hasSeenOnboarding = isOnboardingCompleted
shouldShowOnboarding = !tutorialSettings.hasSeenOnboarding
}
}
}
class MainViewController: UIViewController {
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 notificationView: UIView?
var chromeManager: BrowserChromeManager!
#if DEBUG || ALPHA
var automationServer: AutomationServer?
#endif
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
}
var isUnifiedURLPredictionEnabled: Bool {
featureFlagger.isFeatureOn(.unifiedURLPredictor)
}
lazy var emailManager: EmailManager = {
let emailManager = EmailManager()
emailManager.aliasPermissionDelegate = self
emailManager.requestDelegate = self
return emailManager
}()
var newTabPageViewController: NewTabPageViewController?
var tabsBarController: TabsBarViewController?
var suggestionTrayController: SuggestionTrayViewController?
let homePageConfiguration: HomePageConfiguration
let remoteMessagingActionHandler: RemoteMessagingActionHandling
let remoteMessagingImageLoader: RemoteMessagingImageLoading
let remoteMessagingPixelReporter: RemoteMessagingPixelReporting?
let whatsNewRepository: WhatsNewMessageRepository
let tabManager: TabManager
let previewsSource: TabPreviewsSource
let appSettings: AppSettings
let toggleModeStorage: ToggleModeStoring
var fireExecutor: FireExecuting
private var launchTabObserver: LaunchTabNotification.Observer?
var isNewTabPageVisible: Bool {
newTabPageViewController != nil
}
var autoClearInProgress = false
var autoClearShouldRefreshUIAfterClear = true
private var hasLoadedInitialView = false
private weak var burningOverlayView: UIView?
private var isStartupOnboardingPending = false
private var hasPresentedStartupOnboarding = false
private lazy var startupOnboardingCover = StartupOnboardingCover(
parentViewController: self,
fallbackBackgroundColor: themeManager.currentTheme.onboardingBackgroundColor
)
let privacyConfigurationManager: PrivacyConfigurationManaging
let bookmarksDatabase: CoreDataDatabase
private var favoritesViewModel: FavoritesListInteracting
let syncService: DDGSyncing
let syncDataProviders: SyncDataProviders
let syncPausedStateManager: any SyncPausedStateManaging
let userScriptsDependencies: DefaultScriptSourceProvider.Dependencies
let contentBlockingAssetsPublisher: AnyPublisher<ContentBlockingUpdating.NewContent, Never>
let duckAiNativeStorageHandler: DuckAiNativeStorageHandling?
private let tutorialSettings: TutorialSettings
private let contextualOnboardingLogic: ContextualOnboardingLogic
let contextualOnboardingPixelReporter: OnboardingPixelReporting
private let statisticsStore: StatisticsStore
let voiceSearchHelper: VoiceSearchHelperProtocol
let featureFlagger: FeatureFlagger
let idleReturnEligibilityManager: IdleReturnEligibilityManaging
let ntpAfterIdleInstrumentation: NTPAfterIdleInstrumentation
let syncAutoRestoreHandler: SyncAutoRestoreHandling
private let lastActiveTabStore: LastActiveTabStoring
private let fireModeCapability: FireModeCapable
@UserDefaultsWrapper(key: .syncDidShowSyncPausedByFeatureFlagAlert, defaultValue: false)
private var syncDidShowSyncPausedByFeatureFlagAlert: Bool
@UserDefaultsWrapper(key: .hadVPNEntitlements, defaultValue: false)
private var hadVPNEntitlements: 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>()
private var settingsDeepLinkcancellables = Set<AnyCancellable>()
private let tunnelDefaults = UserDefaults.networkProtectionGroupDefaults
private var vpnCancellables = Set<AnyCancellable>()
private var feedbackCancellable: AnyCancellable?
private var aiChatCancellables = Set<AnyCancellable>()
private var settingsCancellables = Set<AnyCancellable>()
private var syncRecoveryPromptService: SyncRecoveryPromptService?
private var currentNTPEscapeHatch: EscapeHatchModel?
private var hasCompletedInitialLoad = false
let subscriptionFeatureAvailability: SubscriptionFeatureAvailability
let subscriptionDataReporter: SubscriptionDataReporting
let contentScopeExperimentsManager: ContentScopeExperimentsManaging
private lazy var faviconLoader: FavoritesFaviconLoading = FavoritesFaviconLoader()
private lazy var faviconsFetcherOnboarding = FaviconsFetcherOnboarding(syncService: syncService, syncBookmarksAdapter: syncDataProviders.bookmarksAdapter)
private lazy var browsingMenuHeaderDataSource = BrowsingMenuHeaderDataSource()
private lazy var browsingMenuHeaderStateProvider = BrowsingMenuHeaderStateProvider()
lazy var menuBookmarksViewModel: MenuBookmarksInteracting = {
let viewModel = MenuBookmarksViewModel(bookmarksDatabase: bookmarksDatabase, syncService: syncService)
viewModel.favoritesDisplayMode = appSettings.favoritesDisplayMode
return viewModel
}()
weak var tabSwitcherController: TabSwitcherViewController?
var tabSwitcherButton: TabSwitcherButton?
var omniBarTabSwitcherButton: TabSwitcherButton?
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.firstKeyWindow?.rootViewController?.view
return viewCoordinator.omniBar.barView.searchContainer.convert(viewCoordinator.omniBar.barView.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
var postClear: (() -> Void)?
var clearInProgress = false
required init?(coder: NSCoder) {
fatalError("Use init?(code:")
}
let featureDiscovery: FeatureDiscovery
let fireproofing: Fireproofing
let favicons: FaviconManaging
let websiteDataManager: WebsiteDataManaging
let textZoomCoordinatorProvider: TextZoomCoordinatorProviding
var historyManager: HistoryManaging
var viewCoordinator: MainViewCoordinator!
let aiChatSettings: AIChatSettingsProvider
let aiChatAddressBarExperience: AIChatAddressBarExperienceProviding
let privacyStats: PrivacyStatsProviding
let customConfigurationURLProvider: CustomConfigurationURLProviding
let experimentalAIChatManager: ExperimentalAIChatManager
let daxDialogsManager: DaxDialogsManaging
let dbpIOSPublicInterface: DBPIOSInterface.PublicInterface?
let remoteMessagingDebugHandler: RemoteMessagingDebugHandling
var appDidFinishLaunchingStartTime: CFAbsoluteTime?
let maliciousSiteProtectionPreferencesManager: MaliciousSiteProtectionPreferencesManaging
private lazy var themeColorManager: SiteThemeColorManager = {
SiteThemeColorManager(viewCoordinator: viewCoordinator,
currentTabViewController: { [weak self] in self?.currentTab }(),
appSettings: appSettings,
themeManager: themeManager)
}()
private lazy var aiChatViewControllerManager: AIChatViewControllerManager = {
let manager = AIChatViewControllerManager(privacyConfigurationManager: privacyConfigurationManager,
contentBlockingAssetsPublisher: contentBlockingAssetsPublisher,
experimentalAIChatManager: .init(featureFlagger: featureFlagger),
featureFlagger: featureFlagger,
featureDiscovery: featureDiscovery,
aiChatSettings: aiChatSettings,
productSurfaceTelemetry: productSurfaceTelemetry)
manager.delegate = self
manager.isFireModeProvider = { [weak self] in self?.tabManager.currentBrowsingMode == .fire }
return manager
}()
private lazy var browsingMenuSheetCapability = BrowsingMenuSheetCapability.create()
let themeManager: ThemeManaging
let keyValueStore: ThrowingKeyValueStoring
let systemSettingsPiPTutorialManager: SystemSettingsPiPTutorialManaging
private var duckPlayerEntryPointVisible = false
private var subscriptionManager = AppDependencyProvider.shared.subscriptionManager
private let daxEasterEggPresenter: DaxEasterEggPresenting
private let daxEasterEggLogoStore: DaxEasterEggLogoStoring
private let internalUserCommands: URLBasedDebugCommands = InternalUserCommands()
private let launchSourceManager: LaunchSourceManaging
let winBackOfferVisibilityManager: WinBackOfferVisibilityManaging
let mobileCustomization: MobileCustomization
let productSurfaceTelemetry: ProductSurfaceTelemetry
private let aichatFullModeFeature: AIChatFullModeFeatureProviding
private let aichatIPadTabFeature: AIChatIPadTabFeatureProviding
private let aiChatContextualModeFeature: AIChatContextualModeFeatureProviding
let voiceShortcutFeature: DuckAIVoiceShortcutFeatureProviding
lazy var unifiedToggleInputFeature: UnifiedToggleInputFeatureProviding = UnifiedToggleInputFeature()
lazy var minimalChromeSettings: MinimalChromeSettingsProviding = MinimalChromeSettings()
var unifiedToggleInputCoordinator: UnifiedToggleInputCoordinator?
var unifiedToggleInputCancellables = Set<AnyCancellable>()
var aiChatTabChatHeaderView: AIChatTabChatHeaderView?
// MARK: - iPad Tab Mode Chat History
private lazy var iPadTabChatHistoryCoordinator = IPadTabChatHistoryCoordinator(
featureFlagger: featureFlagger,
privacyConfigurationManager: privacyConfigurationManager,
aiChatSettings: aiChatSettings,
iPadTabFeature: aichatIPadTabFeature
)
private var iPadAIChatQuery = ""
private var allowIPadAIAutocompleteShow = false
private var isAwaitingIPadHistoryRefreshAfterModeSwitch = false
private(set) var webExtensionEventsCoordinator: WebExtensionEventsCoordinator?
func setWebExtensionEventsCoordinator(_ coordinator: WebExtensionEventsCoordinator?) {
self.webExtensionEventsCoordinator = coordinator
}
private(set) var webExtensionManager: WebExtensionManaging?
func setWebExtensionManager(_ manager: WebExtensionManaging?) {
self.webExtensionManager = manager
}
private(set) var darkReaderFeatureSettings: DarkReaderFeatureSettings
private let fireModePromotionEligibility: FireModePromotionCoordinating?
init(
privacyConfigurationManager: PrivacyConfigurationManaging,
bookmarksDatabase: CoreDataDatabase,
historyManager: HistoryManaging,
homePageConfiguration: HomePageConfiguration,
syncService: DDGSyncing,
syncDataProviders: SyncDataProviders,
userScriptsDependencies: DefaultScriptSourceProvider.Dependencies,
contentBlockingAssetsPublisher: AnyPublisher<ContentBlockingUpdating.NewContent, Never>,
duckAiNativeStorageHandler: DuckAiNativeStorageHandling? = nil,
appSettings: AppSettings,
previewsSource: TabPreviewsSource,
tabManager: TabManager,
syncPausedStateManager: any SyncPausedStateManaging,
subscriptionDataReporter: SubscriptionDataReporting,
contextualOnboardingLogic: ContextualOnboardingLogic,
contextualOnboardingPixelReporter: OnboardingPixelReporting,
tutorialSettings: TutorialSettings = DefaultTutorialSettings(),
statisticsStore: StatisticsStore = StatisticsUserDefaults(),
subscriptionFeatureAvailability: SubscriptionFeatureAvailability,
voiceSearchHelper: VoiceSearchHelperProtocol,
featureFlagger: FeatureFlagger,
idleReturnEligibilityManager: IdleReturnEligibilityManaging,
lastActiveTabStore: LastActiveTabStoring = LastActiveTabStore(),
syncAutoRestoreHandler: SyncAutoRestoreHandling,
contentScopeExperimentsManager: ContentScopeExperimentsManaging,
fireproofing: Fireproofing,
favicons: FaviconManaging,
textZoomCoordinatorProvider: TextZoomCoordinatorProviding,
websiteDataManager: WebsiteDataManaging,
appDidFinishLaunchingStartTime: CFAbsoluteTime?,
maliciousSiteProtectionPreferencesManager: MaliciousSiteProtectionPreferencesManaging,
aiChatSettings: AIChatSettingsProvider,
aiChatAddressBarExperience: AIChatAddressBarExperienceProviding,
experimentalAIChatManager: ExperimentalAIChatManager = ExperimentalAIChatManager(),
featureDiscovery: FeatureDiscovery = DefaultFeatureDiscovery(wasUsedBeforeStorage: UserDefaults.standard),
themeManager: ThemeManaging,
keyValueStore: ThrowingKeyValueStoring,
customConfigurationURLProvider: CustomConfigurationURLProviding,
systemSettingsPiPTutorialManager: SystemSettingsPiPTutorialManaging,
daxDialogsManager: DaxDialogsManaging,
daxEasterEggPresenter: DaxEasterEggPresenting? = nil,
daxEasterEggLogoStore: DaxEasterEggLogoStoring = DaxEasterEggLogoStore(),
dbpIOSPublicInterface: DBPIOSInterface.PublicInterface?,
launchSourceManager: LaunchSourceManaging,
winBackOfferVisibilityManager: WinBackOfferVisibilityManaging,
aichatFullModeFeature: AIChatFullModeFeatureProviding = AIChatFullModeFeature(),
aichatIPadTabFeature: AIChatIPadTabFeatureProviding = AIChatIPadTabFeature(),
mobileCustomization: MobileCustomization,
remoteMessagingActionHandler: RemoteMessagingActionHandling,
remoteMessagingImageLoader: RemoteMessagingImageLoading,
remoteMessagingPixelReporter: RemoteMessagingPixelReporting?,
productSurfaceTelemetry: ProductSurfaceTelemetry,
fireExecutor: FireExecuting,
remoteMessagingDebugHandler: RemoteMessagingDebugHandling,
privacyStats: PrivacyStatsProviding,
aiChatContextualModeFeature: AIChatContextualModeFeatureProviding = AIChatContextualModeFeature(),
whatsNewRepository: WhatsNewMessageRepository,
darkReaderFeatureSettings: DarkReaderFeatureSettings,
voiceShortcutFeature: DuckAIVoiceShortcutFeatureProviding = DuckAIVoiceShortcutFeature(),
toggleModeStorage: ToggleModeStoring = ToggleModeStorage(),
fireModePromotionEligibility: FireModePromotionCoordinating? = nil
) {
self.remoteMessagingActionHandler = remoteMessagingActionHandler
self.remoteMessagingImageLoader = remoteMessagingImageLoader
self.remoteMessagingPixelReporter = remoteMessagingPixelReporter
self.privacyConfigurationManager = privacyConfigurationManager
self.bookmarksDatabase = bookmarksDatabase
self.historyManager = historyManager
self.homePageConfiguration = homePageConfiguration
self.syncService = syncService
self.syncDataProviders = syncDataProviders
self.userScriptsDependencies = userScriptsDependencies
self.contentBlockingAssetsPublisher = contentBlockingAssetsPublisher
self.duckAiNativeStorageHandler = duckAiNativeStorageHandler
self.favoritesViewModel = FavoritesListViewModel(bookmarksDatabase: bookmarksDatabase, favoritesDisplayMode: appSettings.favoritesDisplayMode)
self.bookmarksCachingSearch = BookmarksCachingSearch(bookmarksStore: CoreDataBookmarksSearchStore(bookmarksStore: bookmarksDatabase))
self.appSettings = appSettings
self.aiChatSettings = aiChatSettings
self.aiChatAddressBarExperience = aiChatAddressBarExperience
self.experimentalAIChatManager = experimentalAIChatManager
self.previewsSource = previewsSource
self.tabManager = tabManager
self.featureDiscovery = featureDiscovery
self.themeManager = themeManager
self.syncPausedStateManager = syncPausedStateManager
self.subscriptionDataReporter = subscriptionDataReporter
self.tutorialSettings = tutorialSettings
self.contextualOnboardingLogic = contextualOnboardingLogic
self.contextualOnboardingPixelReporter = contextualOnboardingPixelReporter
self.statisticsStore = statisticsStore
self.subscriptionFeatureAvailability = subscriptionFeatureAvailability
self.voiceSearchHelper = voiceSearchHelper
self.featureFlagger = featureFlagger
self.idleReturnEligibilityManager = idleReturnEligibilityManager
self.lastActiveTabStore = lastActiveTabStore
self.ntpAfterIdleInstrumentation = DefaultNTPAfterIdleInstrumentation(eligibilityManager: idleReturnEligibilityManager)
self.syncAutoRestoreHandler = syncAutoRestoreHandler
self.fireproofing = fireproofing
self.favicons = favicons
self.textZoomCoordinatorProvider = textZoomCoordinatorProvider
self.websiteDataManager = websiteDataManager
self.appDidFinishLaunchingStartTime = appDidFinishLaunchingStartTime
self.maliciousSiteProtectionPreferencesManager = maliciousSiteProtectionPreferencesManager
self.contentScopeExperimentsManager = contentScopeExperimentsManager
self.keyValueStore = keyValueStore
self.customConfigurationURLProvider = customConfigurationURLProvider
self.systemSettingsPiPTutorialManager = systemSettingsPiPTutorialManager
self.daxDialogsManager = daxDialogsManager
self.daxEasterEggLogoStore = daxEasterEggLogoStore
self.daxEasterEggPresenter = daxEasterEggPresenter ?? DaxEasterEggPresenter(logoStore: daxEasterEggLogoStore, featureFlagger: featureFlagger)
self.dbpIOSPublicInterface = dbpIOSPublicInterface
self.launchSourceManager = launchSourceManager
self.winBackOfferVisibilityManager = winBackOfferVisibilityManager
self.mobileCustomization = mobileCustomization
self.aichatFullModeFeature = aichatFullModeFeature
self.aichatIPadTabFeature = aichatIPadTabFeature
self.remoteMessagingDebugHandler = remoteMessagingDebugHandler
self.productSurfaceTelemetry = productSurfaceTelemetry
self.privacyStats = privacyStats
self.fireExecutor = fireExecutor
self.aiChatContextualModeFeature = aiChatContextualModeFeature
self.whatsNewRepository = whatsNewRepository
self.darkReaderFeatureSettings = darkReaderFeatureSettings
self.voiceShortcutFeature = voiceShortcutFeature
self.toggleModeStorage = toggleModeStorage
self.fireModeCapability = FireModeCapability.create()
self.fireModePromotionEligibility = fireModePromotionEligibility
super.init(nibName: nil, bundle: nil)
tabManager.delegate = self
tabManager.aiChatContentDelegate = self
tabManager.fireModeDelegate = self
self.fireExecutor.delegate = self
bindSyncService()
}
func loadFindInPage() {
let view = FindInPageView.loadFromXib()
self.view.addSubview(view)
let container = view.container!
// Avoids coercion swiftlint warnings
let superview = self.view!
NSLayoutConstraint.activate([
container.bottomAnchor.constraint(equalTo: superview.keyboardLayoutGuide.topAnchor),
view.bottomAnchor.constraint(equalTo: superview.bottomAnchor),
view.heightAnchor.constraint(greaterThanOrEqualToConstant: 0),
view.trailingAnchor.constraint(equalTo: superview.trailingAnchor),
view.leadingAnchor.constraint(equalTo: superview.leadingAnchor),
])
findInPageView = view
findInPageView?.delegate = self
updateFindInPage()
}
var swipeTabsCoordinator: SwipeTabsCoordinator?
private var expandedOmniBarDismissTapGesture: UITapGestureRecognizer?
lazy var newTabDaxDialogFactory: NewTabDaxDialogsProvider = {
NewTabDaxDialogsProvider(
featureFlagger: featureFlagger,
delegate: self,
daxDialogsFlowCoordinator: daxDialogsManager,
onboardingPixelReporter: contextualOnboardingPixelReporter)
}()
lazy var newTabPageDependencies: SuggestionTrayViewController.NewTabPageDependencies = {
SuggestionTrayViewController.NewTabPageDependencies(
favoritesModel: favoritesViewModel,
homePageMessagesConfiguration: homePageConfiguration,
subscriptionDataReporting: subscriptionDataReporter,
newTabDialogFactory: newTabDaxDialogFactory,
newTabDaxDialogManager: daxDialogsManager,
faviconLoader: faviconLoader,
faviconsCache: favicons,
remoteMessagingActionHandler: remoteMessagingActionHandler,
remoteMessagingImageLoader: remoteMessagingImageLoader,
remoteMessagingPixelReporter: remoteMessagingPixelReporter,
fireModePromotionEligibility: fireModePromotionEligibility,
appSettings: appSettings,
subscriptionManager: subscriptionManager,
internalUserCommands: internalUserCommands)
}()
lazy var suggestionTrayDependencies: SuggestionTrayDependencies = {
SuggestionTrayDependencies(
favoritesViewModel: favoritesViewModel,
bookmarksDatabase: bookmarksDatabase,
historyManager: historyManager,
tabsModelProvider: { self.tabManager.currentTabsModel },
featureFlagger: featureFlagger,
appSettings: appSettings,
aiChatSettings: aiChatSettings,
featureDiscovery: featureDiscovery,
newTabPageDependencies: newTabPageDependencies,
productSurfaceTelemetry: productSurfaceTelemetry)
}()
override func viewDidLoad() {
super.viewDidLoad()
viewCoordinator = MainViewFactory.createViewHierarchy(self,
aiChatSettings: aiChatSettings,
aiChatAddressBarExperience: aiChatAddressBarExperience,
voiceSearchHelper: voiceSearchHelper,
featureFlagger: featureFlagger,
suggestionTrayDependencies: suggestionTrayDependencies,
appSettings: appSettings,
mobileCustomization: mobileCustomization)
if featureFlagger.isFeatureOn(.iPadAIToggle) {
viewCoordinator.navigationBarContainer.allowsOverflowHitTesting = true
viewCoordinator.navigationBarCollectionView.allowsOverflowHitTesting = true
}
viewCoordinator.moveAddressBarToPosition(appSettings.currentAddressBarPosition)
setUpToolbarButtonsActions()
installSwipeTabs()
loadSuggestionTray()
loadTabsBarIfNeeded()
attachOmniBar()
view.addInteraction(UIDropInteraction(delegate: self))
chromeManager = BrowserChromeManager()
chromeManager.delegate = self
initTabButton()
initBookmarksButton()
setUpUnifiedToggleInputIfNeeded()
configureStartupPresentation()
previewsSource.prepare()
addLaunchTabNotificationObserver()
subscribeToEmailProtectionStatusNotifications()
subscribeToURLInterceptorNotifications()
subscribeToSettingsDeeplinkNotifications()
subscribeToNetworkProtectionEvents()
subscribeToUnifiedFeedbackNotifications()
subscribeToAIChatSettingsEvents()
subscribeToRefreshButtonSettingsEvents()
subscribeToCustomizationSettingsEvents()
subscribeToDaxEasterEggLogoChanges()
checkSubscriptionEntitlements()
registerForKeyboardNotifications()
registerForPageRefreshPatterns()
registerForSyncFeatureFlagsUpdates()
registerForWebExtensionNotifications()
registerForAppBackgroundNotification()
decorate()
swipeTabsCoordinator?.refresh(tabsModel: tabManager.currentTabsModel, 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)
applyCustomizationState()
mobileCustomization.delegate = self
installContextualSheetDismissGesture()
}
private func configureStartupPresentation() {
let startupOnboardingDecision = StartupOnboardingDecision(
onboardingStatus: LaunchOptionsHandler().onboardingStatus,
tutorialSettings: tutorialSettings
)
isStartupOnboardingPending = startupOnboardingDecision.shouldShowOnboarding
if isStartupOnboardingPending {
startupOnboardingCover.attach()
}
loadInitialViewIfNeeded()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
loadFindInPage()
productSurfaceTelemetry.dailyActiveUser()
productSurfaceTelemetry.iPadUsed(isPad: isPad)
defer {
if let appDidFinishLaunchingStartTime {
let launchTime = CFAbsoluteTimeGetCurrent() - appDidFinishLaunchingStartTime
Pixel.fire(pixel: .appDidShowUITime(time: Pixel.Event.BucketAggregation(number: launchTime)),
withAdditionalParameters: [PixelParameters.time: String(launchTime)])
self.appDidFinishLaunchingStartTime = nil /// We only want this pixel to be fired once
}
}
// Always hide this, we use StyledTopBottomBorderView where needed instead
viewCoordinator.hideToolbarSeparator()
// Needs to be called here because sometimes the frames are not the expected size during didLoad
refreshViewsBasedOnAddressBarPosition(appSettings.currentAddressBarPosition)
startOnboardingFlowIfNotSeenBefore()
tabsBarController?.refresh(tabsModel: tabManager.currentTabsModel, scrollToSelected: true)
swipeTabsCoordinator?.refresh(tabsModel: tabManager.currentTabsModel, scrollToSelected: true)
_ = AppWidthObserver.shared.willResize(toWidth: view.frame.width)
applyWidth()
if daxDialogsManager.shouldShowFireButtonPulse {
showFireButtonPulse()
}
presentSyncRecoveryPromptIfNeeded()
// Should be safe to call anyway but only really need for this specific scenario
if #available(iOS 26, *), isPad {
view.setNeedsUpdateConstraints()
}
}
override func performSegue(withIdentifier identifier: String, sender: Any?) {
assertionFailure()
super.performSegue(withIdentifier: identifier, sender: sender)
}
private func fireExperimentalAddressBarPixel() {
let isEnabledParam = "is_enabled"
let isEnableValue = "\(aiChatSettings.isAIChatSearchInputUserSettingsEnabled)"
DailyPixel.fireDaily(.aiChatExperimentalAddressBarIsEnabledDaily,
withAdditionalParameters: [isEnabledParam: isEnableValue])
}
private func fireIPadToggleStateOnAppOpenPixel() {
guard aiChatAddressBarExperience.isIPadAIToggleExperienceEnabled else { return }
let pixel: Pixel.Event = aiChatAddressBarExperience.shouldShowModeToggle ? .aiChatIPadToggleEnabledOnAppOpen : .aiChatIPadToggleDisabledOnAppOpen
DailyPixel.fireDailyAndCount(pixel: pixel)
}
private func fireContextualAutoAttachPixel() {
let isEnabled = "\(aiChatSettings.isAutomaticContextAttachmentEnabled)"
DailyPixel.fireDaily(.aiChatContextualAutoAttachDAU,
withAdditionalParameters: ["is_enabled": isEnabled])
}
private func fireAIChatIsEnabledPixel() {
let isEnabled = "\(aiChatSettings.isAIChatEnabled)"
DailyPixel.fireDaily(.aiChatIsEnabledDaily,
withAdditionalParameters: ["is_enabled": isEnabled])
}
private func fireKeyboardSettingsPixels() {
let keyboardSettings = KeyboardSettings()
let isEnabledParam = "is_enabled"
let onNewTabValue = "\(keyboardSettings.onNewTab)"
DailyPixel.fireDaily(.keyboardSettingsOnNewTabEnabledDaily,
withAdditionalParameters: [isEnabledParam: onNewTabValue])
let onAppLaunchValue = "\(keyboardSettings.onAppLaunch)"
DailyPixel.fireDaily(.keyboardSettingsOnAppLaunchEnabledDaily,
withAdditionalParameters: [isEnabledParam: onAppLaunchValue])
}
private func installSwipeTabs() {
guard swipeTabsCoordinator == nil else { return }
let omnibarDependencies = OmnibarDependencies(voiceSearchHelper: voiceSearchHelper,
featureFlagger: featureFlagger,
aichatIPadTabFeature: aichatIPadTabFeature,
aiChatSettings: aiChatSettings,
aiChatAddressBarExperience: aiChatAddressBarExperience,
appSettings: appSettings,
daxEasterEggPresenter: daxEasterEggPresenter,
mobileCustomization: mobileCustomization)
swipeTabsCoordinator = SwipeTabsCoordinator(coordinator: viewCoordinator,
tabPreviewsSource: previewsSource,
appSettings: appSettings,
omnibarDependencies: omnibarDependencies) { [weak self] in
guard $0 !== self?.tabManager.currentTabsModel.currentTab else { return }
DailyPixel.fire(pixel: .swipeTabsUsedDaily)
self?.currentTab?.aiChatContextualSheetCoordinator.dismissSheet()
self?.selectTab($0)
} newTab: { [weak self] in
Pixel.fire(pixel: .swipeToOpenNewTab)
self?.currentTab?.aiChatContextualSheetCoordinator.dismissSheet()
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.currentTabsModel.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.currentTabsModel.currentTab {
// Favorites, etc
if let image = viewCoordinator.contentContainer.createImageSnapshot() {
previewsSource.update(preview: image, forTab: tab)
completion?()
}
} else {
completion?()
}
}
func loadSuggestionTray() {
let controller = SuggestionTrayViewController(favoritesViewModel: self.favoritesViewModel,
bookmarksDatabase: self.bookmarksDatabase,
historyManager: self.historyManager,
tabsModelProvider: { self.tabManager.currentTabsModel },
featureFlagger: self.featureFlagger,
appSettings: self.appSettings,
aiChatSettings: self.aiChatSettings,
featureDiscovery: self.featureDiscovery,
newTabPageDependencies: self.newTabPageDependencies,
productSurfaceTelemetry: self.productSurfaceTelemetry,
hideBorder: false)
controller.view.frame = viewCoordinator.suggestionTrayContainer.bounds
controller.newTabPageControllerDelegate = self
viewCoordinator.suggestionTrayContainer.addSubview(controller.view)
controller.dismissHandler = dismissSuggestionTray
controller.autocompleteDelegate = self
suggestionTrayController = controller
}
func loadTabsBarIfNeeded() {
guard isPad else { return }
let controller = TabsBarViewController.createFromXib()
addChild(controller)
controller.view.frame = viewCoordinator.tabBarContainer.bounds
controller.delegate = self
controller.historyManager = historyManager
controller.fireproofing = fireproofing
controller.aiChatSettings = aiChatSettings
controller.keyValueStore = keyValueStore
controller.tabManager = tabManager
controller.daxDialogsManager = daxDialogsManager
controller.fireModeCapability = fireModeCapability
viewCoordinator.tabBarContainer.addSubview(controller.view)
tabsBarController = controller
controller.didMove(toParent: self)
}
func startAddFavoriteFlow() {
contextualOnboardingLogic.enableAddFavoriteFlow()
if tutorialSettings.hasSeenOnboarding {
newTab()
}
}
func startOnboardingFlowIfNotSeenBefore() {
guard isStartupOnboardingPending, !hasPresentedStartupOnboarding else { return }
hasPresentedStartupOnboarding = true
startupOnboardingCover.bringToFront()
segueToDaxOnboarding { [weak self] in
self?.startupOnboardingCover.detach()
}
}
func presentSyncRecoveryPromptIfNeeded() {
syncRecoveryPromptService = SyncRecoveryPromptService(
featureFlagger: featureFlagger,
syncService: syncService,
keyValueStore: keyValueStore,
isOnboardingComplete: !needsToShowOnboardingIntro()
)
guard let syncRecoveryPromptService = syncRecoveryPromptService else { return }
syncRecoveryPromptService.tryPresentSyncRecoveryPrompt(
from: self,
onSyncFlowSelected: { [weak self] source in
self?.segueToSettingsSync(with: source)
}
)
}
func presentNetworkProtectionStatusSettingsModal() {
Task {
if let canShowVPNInUI = try? await subscriptionManager.isFeatureIncludedInSubscription(.networkProtection),
canShowVPNInUI {
segueToVPN()
} else {
segueToDuckDuckGoSubscription()
}
}
}
func presentDataBrokerProtectionDashboard() {
segueToDataBrokerProtection()
}
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
private var didSendGestureDismissPixel: Bool = false
var latestKeyboardFrame: CGRect = .zero
@objc
private func keyboardDidShow() {
keyboardShowing = true
productSurfaceTelemetry.keyboardActive()
dismissContextualSheetIfKeyboardIsForBackgroundContent()
}
private func dismissContextualSheetIfKeyboardIsForBackgroundContent() {
guard let currentTab,
currentTab.aiChatContextualSheetCoordinator.isSheetPresented,
let sheetVC = currentTab.aiChatContextualSheetCoordinator.sheetViewController else {
return
}
// Check if first responder is within the sheet's view hierarchy
if let firstResponder = UIResponder.currentFirstResponder(),
firstResponder.isInViewHierarchy(of: sheetVC.view) {
// Keyboard is for the sheet, don't dismiss
return
}
// Keyboard is for background content (web view), dismiss the sheet
currentTab.aiChatContextualSheetCoordinator.dismissSheet()
}
@objc
private func keyboardWillHide() {
if !didSendGestureDismissPixel, newTabPageViewController?.isDragging == true, keyboardShowing {
Pixel.fire(pixel: .addressBarGestureDismiss)
didSendGestureDismissPixel = true
}
collapseExpandedUTIOnKeyboardDismiss()
}
private func collapseExpandedUTIOnKeyboardDismiss() {
guard unifiedToggleInputFeature.isAvailable,
currentTab?.isAITab == true,
let coordinator = unifiedToggleInputCoordinator,
coordinator.shouldCollapseOnKeyboardDismiss,
currentTab?.aiChatContextualSheetCoordinator.isSheetPresented != true else { return }
coordinator.showCollapsed()
}
@objc
private func keyboardDidHide() {
keyboardShowing = false
didSendGestureDismissPixel = false
if #available(iOS 26, *) {
latestKeyboardFrame = .zero
adjustUI(withKeyboardFrame: .zero)
}
}
private var isAnyAITabUTIState: Bool {
guard unifiedToggleInputFeature.isAvailable,
currentTab?.isAITab == true else { return false }
return unifiedToggleInputCoordinator?.isAITabState == true
}
var isNavigationBarEffectivelyAtBottom: Bool {
if appSettings.currentAddressBarPosition.isBottom {
return true
}
return isAnyAITabUTIState
}
private func setUpToolbarButtonsActions() {
viewCoordinator.toolbarBackButton.setCustomItemAction(on: self, action: #selector(onBackPressed))
viewCoordinator.toolbarForwardButton.setCustomItemAction(on: self, action: #selector(onForwardPressed))
viewCoordinator.toolbarPasswordsButton.setCustomItemAction(on: self, action: #selector(onPasswordsPressed))
viewCoordinator.toolbarBookmarksButton.setCustomItemAction(on: self, action: #selector(onToolbarBookmarksPressed))
viewCoordinator.menuToolbarButton.setCustomItemAction(on: self, action: #selector(onMenuPressed))
viewCoordinator.toolbarFireBarButtonItem.setCustomItemAction(on: self, action: #selector(performCustomizationActionForToolbar))
viewCoordinator.menuToolbarButton.customView?
.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(onMenuLongPressed)))
}
private func registerForPageRefreshPatterns() {
NotificationCenter.default.addObserver(
self,
selector: #selector(attemptToShowBrokenSitePrompt(_:)),
name: .pageRefreshMonitorDidDetectRefreshPattern,
object: nil)
}
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()