-
Notifications
You must be signed in to change notification settings - Fork 15
/
AppRootViewController.swift
417 lines (338 loc) · 16.1 KB
/
AppRootViewController.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
//
// Wire
// Copyright (C) 2017 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import UIKit
import Classy
@objc
class AppRootViewController : UIViewController {
public let mainWindow : UIWindow
public let overlayWindow : UIWindow
public fileprivate(set) var sessionManager : SessionManager?
public fileprivate(set) var visibleViewController : UIViewController?
fileprivate let appStateController : AppStateController
fileprivate let classyCache : ClassyCache
fileprivate let fileBackupExcluder : FileBackupExcluder
fileprivate let avsLogObserver : AVSLogObserver
fileprivate var authenticatedBlocks : [() -> Void] = []
fileprivate let transitionQueue : DispatchQueue = DispatchQueue(label: "transitionQueue")
fileprivate var isClassyInitialized = false
fileprivate weak var requestToOpenViewDelegate: ZMRequestsToOpenViewsDelegate? {
didSet {
if let delegate = requestToOpenViewDelegate {
performWhenRequestsToOpenViewsDelegateAvailable?(delegate)
performWhenRequestsToOpenViewsDelegateAvailable = nil
}
}
}
fileprivate var performWhenRequestsToOpenViewsDelegateAvailable: ((ZMRequestsToOpenViewsDelegate)->())?
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
appStateController = AppStateController()
classyCache = ClassyCache()
fileBackupExcluder = FileBackupExcluder()
avsLogObserver = AVSLogObserver()
MagicConfig.shared()
mainWindow = UIWindow()
mainWindow.frame = UIScreen.main.bounds
mainWindow.accessibilityIdentifier = "ZClientMainWindow"
overlayWindow = PassthroughWindow()
overlayWindow.backgroundColor = .clear
overlayWindow.frame = UIScreen.main.bounds
overlayWindow.windowLevel = UIWindowLevelStatusBar + 1
overlayWindow.accessibilityIdentifier = "ZClientNotificationWindow"
overlayWindow.rootViewController = NotificationWindowRootViewController()
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
AutomationHelper.sharedHelper.installDebugDataIfNeeded()
appStateController.delegate = self
// Notification window has to be on top, so must be made visible last. Changing the window level is
// not possible because it has to be below the status bar.
mainWindow.rootViewController = self
mainWindow.makeKeyAndVisible()
overlayWindow.makeKeyAndVisible()
mainWindow.makeKey()
configureMediaManager()
if let appGroupIdentifier = Bundle.main.appGroupIdentifier {
let sharedContainerURL = FileManager.sharedContainerDirectory(for: appGroupIdentifier)
fileBackupExcluder.excludeLibraryFolderInSharedContainer(sharedContainerURL: sharedContainerURL)
}
NotificationCenter.default.addObserver(self, selector: #selector(onContentSizeCategoryChange), name: Notification.Name.UIContentSizeCategoryDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: Notification.Name.UIApplicationDidEnterBackground, object: nil)
transition(to: .headless)
enqueueTransition(to: appStateController.appState)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.frame = mainWindow.bounds
}
public func launch(with launchOptions : LaunchOptions) {
let bundle = Bundle.main
let appVersion = bundle.infoDictionary?[kCFBundleVersionKey as String] as? String
let mediaManager = AVSMediaManager.sharedInstance()
let analytics = Analytics.shared()
SessionManager.create(
appVersion: appVersion!,
mediaManager: mediaManager!,
analytics: analytics,
delegate: appStateController,
application: UIApplication.shared,
launchOptions: launchOptions,
blacklistDownloadInterval: Settings.shared().blacklistDownloadInterval)
{ sessionManager in
self.sessionManager = sessionManager
self.sessionManager?.localMessageNotificationResponder = self
self.sessionManager?.requestToOpenViewDelegate = self
sessionManager.updateCallNotificationStyleFromSettings()
sessionManager.useConstantBitRateAudio = false // Settings.shared().callingConstantBitRate TODO re-enable
}
}
func enqueueTransition(to appState: AppState, completion: (() -> Void)? = nil) {
transitionQueue.async {
let transitionGroup = DispatchGroup()
transitionGroup.enter()
DispatchQueue.main.async {
self.prepare(for: appState, completionHandler: {
transitionGroup.leave()
})
}
transitionGroup.wait()
}
transitionQueue.async {
let transitionGroup = DispatchGroup()
transitionGroup.enter()
DispatchQueue.main.async {
self.transition(to: appState, completionHandler: {
transitionGroup.leave()
completion?()
})
}
transitionGroup.wait()
}
}
func transition(to appState: AppState, completionHandler: (() -> Void)? = nil) {
var viewController : UIViewController? = nil
requestToOpenViewDelegate = nil
switch appState {
case .blacklisted:
viewController = BlacklistViewController()
case .migrating:
let launchImageViewController = LaunchImageViewController()
launchImageViewController.showLoadingScreen()
viewController = launchImageViewController
case .unauthenticated(error: let error):
UIColor.setAccentOverride(ZMUser.pickRandomAccentColor())
mainWindow.tintColor = UIColor.accent()
let registrationViewController = RegistrationViewController()
registrationViewController.delegate = appStateController
registrationViewController.signInError = error
viewController = registrationViewController
case .authenticated(completedRegistration: let completedRegistration):
// TODO: CallKit only with 1 account
sessionManager?.updateCallNotificationStyleFromSettings()
UIColor.setAccentOverride(.undefined)
mainWindow.tintColor = UIColor.accent()
executeAuthenticatedBlocks()
let clientViewController = ZClientViewController()
clientViewController.isComingFromRegistration = completedRegistration
viewController = clientViewController
case .headless:
viewController = LaunchImageViewController()
case .loading(account: let toAccount, from: let fromAccount):
viewController = SkeletonViewController(from: fromAccount, to: toAccount)
}
if let viewController = viewController {
transition(to: viewController, animated: true) {
self.requestToOpenViewDelegate = viewController as? ZMRequestsToOpenViewsDelegate
completionHandler?()
}
} else {
completionHandler?()
}
}
private func dismissModalsFromAllChildren(of viewController: UIViewController?) {
guard let viewController = viewController else { return }
for child in viewController.childViewControllers {
if child.presentedViewController != nil {
child.dismiss(animated: false, completion: nil)
}
dismissModalsFromAllChildren(of: child)
}
}
func transition(to viewController : UIViewController, animated : Bool = true, completionHandler: (() -> Void)? = nil) {
// If we have some modal view controllers presented in any of the (grand)children
// of this controller they stay in memory and leak on iOS 10.
dismissModalsFromAllChildren(of: visibleViewController)
visibleViewController?.willMove(toParentViewController: nil)
if let previousViewController = visibleViewController, animated {
addChildViewController(viewController)
transition(from: previousViewController,
to: viewController,
duration: 0.5,
options: .transitionCrossDissolve,
animations: nil,
completion:
{ (finished) in
viewController.didMove(toParentViewController: self)
previousViewController.removeFromParentViewController()
self.visibleViewController = viewController
UIApplication.shared.wr_updateStatusBarForCurrentControllerAnimated(true)
completionHandler?()
})
} else {
UIView.performWithoutAnimation {
visibleViewController?.removeFromParentViewController()
addChildViewController(viewController)
viewController.view.frame = view.bounds
viewController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
view.addSubview(viewController.view)
viewController.didMove(toParentViewController: self)
visibleViewController = viewController
UIApplication.shared.wr_updateStatusBarForCurrentControllerAnimated(false)
}
completionHandler?()
}
}
func prepare(for appState: AppState, completionHandler: @escaping () -> Void) {
if appState == .authenticated(completedRegistration: false) {
(overlayWindow.rootViewController as? NotificationWindowRootViewController)?.transitionToLoggedInSession()
} else {
overlayWindow.rootViewController = NotificationWindowRootViewController()
}
if !isClassyInitialized && isClassyRequired(for: appState) {
isClassyInitialized = true
let windows = [mainWindow, overlayWindow]
DispatchQueue.main.async {
self.setupClassy(with: windows)
completionHandler()
}
} else {
completionHandler()
}
}
func isClassyRequired(for appState: AppState) -> Bool {
switch appState {
case .authenticated, .unauthenticated, .loading:
return true
default:
return false
}
}
func configureMediaManager() {
guard !Settings.shared().disableAVS else { return }
let mediaManager = AVSProvider.shared.mediaManager
mediaManager?.configureSounds()
mediaManager?.observeSoundConfigurationChanges()
mediaManager?.isMicrophoneMuted = false
mediaManager?.isSpeakerEnabled = false
}
func setupClassy(with windows: [UIWindow]) {
let colorScheme = ColorScheme.default()
colorScheme.accentColor = UIColor.accent()
colorScheme.variant = ColorSchemeVariant(rawValue: Settings.shared().colorScheme.rawValue) ?? .light
let fontScheme = FontScheme(contentSizeCategory: UIApplication.shared.preferredContentSizeCategory)
CASStyler.default().cache = classyCache
CASStyler.bootstrapClassy(withTargetWindows: windows)
CASStyler.default().apply(colorScheme)
CASStyler.default().apply(fontScheme: fontScheme)
}
func onContentSizeCategoryChange() {
Message.invalidateMarkdownStyle()
UIFont.wr_flushFontCache()
NSAttributedString.wr_flushCellParagraphStyleCache()
ConversationListCell.invalidateCachedCellSize()
let fontScheme = FontScheme(contentSizeCategory: UIApplication.shared.preferredContentSizeCategory)
CASStyler.default().apply(fontScheme: fontScheme)
}
public func performWhenAuthenticated(_ block : @escaping () -> Void) {
if appStateController.appState == .authenticated(completedRegistration: false) {
block()
} else {
authenticatedBlocks.append(block)
}
}
func executeAuthenticatedBlocks() {
while !authenticatedBlocks.isEmpty {
authenticatedBlocks.removeFirst()()
}
}
func reload() {
enqueueTransition(to: .headless)
enqueueTransition(to: self.appStateController.appState)
}
}
// MARK: - Status Bar / Supported Orientations
extension AppRootViewController {
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return UIViewController.wr_supportedInterfaceOrientations()
}
override var prefersStatusBarHidden: Bool {
return visibleViewController?.prefersStatusBarHidden ?? false
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return visibleViewController?.preferredStatusBarStyle ?? .default
}
}
extension AppRootViewController : AppStateControllerDelegate {
func appStateController(transitionedTo appState: AppState, transitionCompleted: @escaping () -> Void) {
enqueueTransition(to: appState, completion: transitionCompleted)
}
}
// MARK: - RequestToOpenViewsDelegate
extension AppRootViewController : ZMRequestsToOpenViewsDelegate {
public func showConversationList(for userSession: ZMUserSession!) {
whenRequestsToOpenViewsDelegateAvailable(do: { delegate in
delegate.showConversationList(for: userSession)
})
}
public func userSession(_ userSession: ZMUserSession!, show conversation: ZMConversation!) {
whenRequestsToOpenViewsDelegateAvailable(do: { delegate in
delegate.userSession(userSession, show: conversation)
})
}
public func userSession(_ userSession: ZMUserSession!, show message: ZMMessage!, in conversation: ZMConversation!) {
whenRequestsToOpenViewsDelegateAvailable(do: { delegate in
delegate.userSession(userSession, show: message, in: conversation)
})
}
internal func whenRequestsToOpenViewsDelegateAvailable(do closure: @escaping (ZMRequestsToOpenViewsDelegate)->()) {
if let delegate = self.requestToOpenViewDelegate {
closure(delegate)
}
else {
self.performWhenRequestsToOpenViewsDelegateAvailable = closure
}
}
}
// MARK: - Application Icon Badge Number
extension AppRootViewController : LocalMessageNotificationResponder {
func processLocalMessage(_ notification: UILocalNotification, forSession session: ZMUserSession) {
(self.overlayWindow.rootViewController as! NotificationWindowRootViewController).show(notification)
}
@objc fileprivate func applicationDidEnterBackground() {
let unreadConversations = sessionManager?.accountManager.totalUnreadCount ?? 0
UIApplication.shared.applicationIconBadgeNumber = unreadConversations
}
}