-
Notifications
You must be signed in to change notification settings - Fork 895
/
Copy pathApplicationContext.swift
908 lines (691 loc) · 36.6 KB
/
ApplicationContext.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
import Foundation
import WebKit
import UserNotifications
import TGUIKit
import SwiftSignalKit
import Postbox
import TelegramCore
import Localization
import InAppSettings
import IOKit
import CodeSyntax
import Dock
import PrivateCallScreen
private final class AuthModalController : ModalController {
override var background: NSColor {
return theme.colors.background
}
override var dynamicSize: Bool {
return true
}
override var closable: Bool {
return false
}
override func measure(size: NSSize) {
self.modal?.resize(with: NSMakeSize(size.width, size.height), animated: false)
}
}
final class UnauthorizedApplicationContext {
let account: UnauthorizedAccount
let rootController: MajorNavigationController
let window:Window
let modal: ModalController
let sharedContext: SharedAccountContext
private let updatesDisposable: DisposableSet = DisposableSet()
private let authController: AuthController
var rootView: NSView {
return rootController.view
}
init(window:Window, sharedContext: SharedAccountContext, account: UnauthorizedAccount, otherAccountPhoneNumbers: ((String, AccountRecordId, Bool)?, [(String, AccountRecordId, Bool)])) {
window.maxSize = NSMakeSize(.greatestFiniteMagnitude, .greatestFiniteMagnitude)
window.minSize = NSMakeSize(380, 550)
updatesDisposable.add(managedAppConfigurationUpdates(accountManager: sharedContext.accountManager, network: account.network).start())
if window.frame.height < window.minSize.height || window.frame.width < window.minSize.width {
window.setFrame(NSMakeRect(window.frame.minX, window.frame.minY, window.minSize.width, window.minSize.height), display: true)
window.center()
}
self.authController = AuthController(account, sharedContext: sharedContext, otherAccountPhoneNumbers: otherAccountPhoneNumbers)
self.account = account
self.window = window
self.sharedContext = sharedContext
self.rootController = MajorNavigationController(AuthController.self, self.authController, window)
rootController._frameRect = NSMakeRect(0, 0, window.frame.width, window.frame.height)
self.modal = AuthModalController(rootController)
rootController.alwaysAnimate = true
account.shouldBeServiceTaskMaster.set(.single(.now))
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(receiveWakeNote(_:)), name: NSWorkspace.screensDidWakeNotification, object: nil)
}
func applyExternalLoginCode(_ code: String) {
authController.applyExternalLoginCode(code)
}
deinit {
account.shouldBeServiceTaskMaster.set(.single(.never))
updatesDisposable.dispose()
NSWorkspace.shared.notificationCenter.removeObserver(self)
}
@objc func receiveWakeNote(_ notificaiton:Notification) {
account.shouldBeServiceTaskMaster.set(.single(.never) |> then(.single(.now)))
}
}
enum ApplicationContextLaunchAction {
case navigate(ViewController)
case preferences
}
let leftSidebarWidth: CGFloat = 72
private final class ApplicationContainerView: View {
fileprivate let splitView: SplitView
fileprivate private(set) var leftSideView: NSView?
required init(frame frameRect: NSRect) {
splitView = SplitView(frame: NSMakeRect(0, 0, frameRect.width, frameRect.height))
super.init(frame: frameRect)
addSubview(splitView)
autoresizingMask = [.width, .height]
}
required init?(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func updateLeftSideView(_ view: NSView?, animated: Bool) {
if let view = view {
addSubview(view)
} else {
self.leftSideView?.removeFromSuperview()
}
self.leftSideView = view
needsLayout = true
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
splitView.backgroundColor = theme.colors.background
}
override func layout() {
super.layout()
if let leftSideView = leftSideView {
leftSideView.frame = NSMakeRect(0, 0, leftSidebarWidth, frame.height)
splitView.frame = NSMakeRect(leftSideView.frame.maxX, 0, frame.width - leftSideView.frame.maxX, frame.height)
} else {
splitView.frame = bounds
}
}
}
final class AuthorizedApplicationContext: NSObject, SplitViewDelegate {
var rootView: View {
return view
}
let context: AccountContext
private let window:Window
private let view:ApplicationContainerView
private let leftController:MainViewController
private let rightController:MajorNavigationController
private let emptyController:EmptyChatViewController
private var entertainment: EntertainmentViewController?
private var leftSidebarController: LeftSidebarController?
private let loggedOutDisposable = MetaDisposable()
private let ringingStatesDisposable = MetaDisposable()
private let settingsDisposable = MetaDisposable()
private let suggestedLocalizationDisposable = MetaDisposable()
private let alertsDisposable = MetaDisposable()
private let audioDisposable = MetaDisposable()
private let termDisposable = MetaDisposable()
private let someActionsDisposable = DisposableSet()
private let clearReadNotifiesDisposable = MetaDisposable()
private let appUpdateDisposable = MetaDisposable()
private let updateFoldersDisposable = MetaDisposable()
private let _ready:Promise<Bool> = Promise()
var ready: Signal<Bool, NoError> {
return _ready.get() |> filter { $0 } |> take (1)
}
func applyNewTheme() {
rightController.backgroundColor = theme.colors.background
rightController.backgroundMode = theme.controllerBackgroundMode
view.updateLocalizationAndTheme(theme: theme)
}
private var launchAction: ApplicationContextLaunchAction?
init(window: Window, context: AccountContext, launchSettings: LaunchSettings, callSession: PCallSession?, groupCallContext: GroupCallContext?, inlinePlayerContext: InlineAudioPlayerView.ContextObject?, folders: ChatListFolders?) {
self.context = context
emptyController = EmptyChatViewController(context)
self.window = window
if !window.initFromSaver {
window.setFrame(NSMakeRect(0, 0, 800, 650), display: true)
window.center()
}
window.maxSize = NSMakeSize(.greatestFiniteMagnitude, .greatestFiniteMagnitude)
window.minSize = NSMakeSize(380, 550)
context.account.importableContacts.set(.single([:]))
self.view = ApplicationContainerView(frame: window.contentView!.bounds)
self.view.splitView.setProportion(proportion: SplitProportion(min:380, max:300+350), state: .single);
self.view.splitView.setProportion(proportion: SplitProportion(min:300+350, max:300+350+600), state: .dual)
rightController = ExMajorNavigationController(context, ChatController.self, emptyController);
rightController.set(header: NavigationHeader(44, initializer: { header, contextObject, view -> (NavigationHeaderView, CGFloat) in
let newView = view ?? InlineAudioPlayerView(header)
newView.update(with: contextObject)
return (newView, 44)
}))
rightController.set(callHeader: CallNavigationHeader(35, initializer: { header, contextObject, view -> (NavigationHeaderView, CGFloat) in
let newView: NavigationHeaderView
if contextObject is GroupCallContext {
if let view = view, view.className == GroupCallNavigationHeaderView.className() {
newView = view
} else {
newView = GroupCallNavigationHeaderView(header)
}
} else if contextObject is PCallSession {
if let view = view, view.className == CallNavigationHeaderView.className() {
newView = view
} else {
newView = CallNavigationHeaderView(header)
}
} else {
fatalError("not supported")
}
newView.update(with: contextObject)
return (newView, 35 + 18)
}))
window.rootViewController = rightController
leftController = MainViewController(context);
super.init()
context.bindings = AccountContextBindings(rootNavigation: { [weak self] () -> MajorNavigationController in
guard let `self` = self else {
return MajorNavigationController(ViewController.self, ViewController(), window)
}
return self.rightController
}, mainController: { [weak self] () -> MainViewController in
guard let `self` = self else {
fatalError("Cannot use bindings. Application context is not exists")
}
return self.leftController
}, showControllerToaster: { [weak self] toaster, animated in
guard let `self` = self else {
fatalError("Cannot use bindings. Application context is not exists")
}
self.rightController.controller.show(toaster: toaster, animated: animated)
}, globalSearch: { [weak self] search, peerId in
guard let `self` = self else {
fatalError("Cannot use bindings. Application context is not exists")
}
self.leftController.tabController.select(index: self.leftController.chatIndex)
self.leftController.globalSearch(search, peerId: peerId)
}, entertainment: { [weak self] () -> EntertainmentViewController in
guard let `self` = self else {
return EntertainmentViewController.init(size: NSZeroSize, context: context)
}
if self.entertainment == nil {
self.entertainment = EntertainmentViewController(size: NSMakeSize(350, 350), context: self.context)
}
return self.entertainment!
}, switchSplitLayout: { [weak self] state in
guard let `self` = self else {
fatalError("Cannot use bindings. Application context is not exists")
}
self.view.splitView.state = state
}, needFullsize: { [weak self] in
self?.view.splitView.needFullsize()
}, displayUpgradeProgress: { progress in
})
termDisposable.set((context.account.stateManager.termsOfServiceUpdate |> deliverOnMainQueue).start(next: { terms in
if let terms = terms {
showModal(with: TermsModalController(context, terms: terms), for: context.window)
} else {
closeModal(TermsModalController.self)
}
}))
closeAllPopovers(for: context.window)
closeAllModals(window: context.window)
AppMenu.closeAll()
// var forceNotice:Bool = false
if FastSettings.isMinimisize {
self.view.splitView.mustMinimisize = true
// forceNotice = true
} else {
self.view.splitView.mustMinimisize = false
}
self.view.splitView.delegate = self;
self.view.splitView.update(false)
let accountId = context.account.id
self.loggedOutDisposable.set(context.account.loggedOut.start(next: { value in
if value {
let _ = logoutFromAccount(id: accountId, accountManager: context.sharedContext.accountManager, alreadyLoggedOutRemotely: false).start()
FastSettings.clear_uuid(context.account.id.int64)
}
}))
alertsDisposable.set((context.account.stateManager.displayAlerts |> deliverOnMainQueue).start(next: { alerts in
for text in alerts {
let alert:NSAlert = NSAlert()
alert.window.appearance = theme.appearance
alert.alertStyle = .informational
alert.messageText = appName
alert.informativeText = text.text
if text.isDropAuth {
alert.addButton(withTitle: strings().editAccountLogout)
alert.addButton(withTitle: strings().modalCancel)
}
alert.beginSheetModal(for: window, completionHandler: { result in
if result.rawValue == 1000 && text.isDropAuth {
let _ = logoutFromAccount(id: context.account.id, accountManager: context.sharedContext.accountManager, alreadyLoggedOutRemotely: false).start()
}
})
}
}))
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.rightController.push(ChatController(context: context, chatLocation: .peer(context.peerId)))
return .invoked
}, with: self, for: .Zero, priority: .low, modifierFlags: [.command])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(0, false)
return .invoked
}, with: self, for: .One, priority: .low, modifierFlags: [.command])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(1, false)
return .invoked
}, with: self, for: .Two, priority: .low, modifierFlags: [.command])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(2, false)
return .invoked
}, with: self, for: .Three, priority: .low, modifierFlags: [.command])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(3, false)
return .invoked
}, with: self, for: .Four, priority: .low, modifierFlags: [.command])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(4, false)
return .invoked
}, with: self, for: .Five, priority: .low, modifierFlags: [.command])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(5, false)
return .invoked
}, with: self, for: .Six, priority: .low, modifierFlags: [.command])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(6, false)
return .invoked
}, with: self, for: .Seven, priority: .low, modifierFlags: [.command])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(7, false)
return .invoked
}, with: self, for: .Eight, priority: .low, modifierFlags: [.command])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(8, false)
return .invoked
}, with: self, for: .Nine, priority: .low, modifierFlags: [.command])
window.set(handler: { _ -> KeyHandlerResult in
appDelegate?.sharedApplicationContextValue?.notificationManager.updatePasslock(context.sharedContext.accountManager.transaction { transaction -> Bool in
switch transaction.getAccessChallengeData() {
case .none:
return false
default:
return true
}
})
let hasPasscode = context.sharedContext.accountManager.transaction { $0.getAccessChallengeData() != .none } |> deliverOnMainQueue
_ = hasPasscode.startStandalone(next: { value in
if !value {
context.bindings.rootNavigation().push(PasscodeSettingsViewController(context))
}
})
return .invoked
}, with: self, for: .L, priority: .supreme, modifierFlags: [.command])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(0, true)
return .invoked
}, with: self, for: .One, priority: .low, modifierFlags: [.command, .option])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(1, true)
return .invoked
}, with: self, for: .Two, priority: .low, modifierFlags: [.command, .option])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(2, true)
return .invoked
}, with: self, for: .Three, priority: .low, modifierFlags: [.command, .option])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(3, true)
return .invoked
}, with: self, for: .Four, priority: .low, modifierFlags: [.command, .option])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(4, true)
return .invoked
}, with: self, for: .Five, priority: .low, modifierFlags: [.command, .option])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(5, true)
return .invoked
}, with: self, for: .Six, priority: .low, modifierFlags: [.command, .option])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(6, true)
return .invoked
}, with: self, for: .Seven, priority: .low, modifierFlags: [.command, .option])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(7, true)
return .invoked
}, with: self, for: .Eight, priority: .low, modifierFlags: [.command, .option])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(8, true)
return .invoked
}, with: self, for: .Nine, priority: .low, modifierFlags: [.command, .option])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.openChat(9, true)
return .invoked
}, with: self, for: .Minus, priority: .low, modifierFlags: [.command, .option])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.switchAccount(1, true)
return .invoked
}, with: self, for: .One, priority: .low, modifierFlags: [.control])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.switchAccount(2, true)
return .invoked
}, with: self, for: .Two, priority: .low, modifierFlags: [.control])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.switchAccount(3, true)
return .invoked
}, with: self, for: .Three, priority: .low, modifierFlags: [.control])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.switchAccount(4, true)
return .invoked
}, with: self, for: .Four, priority: .low, modifierFlags: [.control])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.switchAccount(5, true)
return .invoked
}, with: self, for: .Five, priority: .low, modifierFlags: [.control])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.switchAccount(6, true)
return .invoked
}, with: self, for: .Six, priority: .low, modifierFlags: [.control])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.switchAccount(7, true)
return .invoked
}, with: self, for: .Seven, priority: .low, modifierFlags: [.control])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.switchAccount(8, true)
return .invoked
}, with: self, for: .Eight, priority: .low, modifierFlags: [.control])
window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.switchAccount(9, true)
return .invoked
}, with: self, for: .Nine, priority: .low, modifierFlags: [.control])
#if DEBUG
self.context.window.set(handler: { _ -> KeyHandlerResult in
//showModal(with: StoryFoundListController(context: context, source: .hashtag("#telegram"), presentation: theme), for: context.window)
showModal(with: Star_ReactionsController(context: context), for: context.window)
// showModal(with: Star_TransactionScreen(context: context, peer: .init(context.myPeer!), transaction: StarsContext.State.Transaction.init(id: "kqwjeflklqwkejflqwkejflqkwejflqkwejf", count: 1000, date: Int32(Date().timeIntervalSince1970), peer: StarsContext.State.Transaction.Peer.appStore)), for: context.window)
// showModal(with: FactCheckController(context: context), for: context.window)
// showModal(with: Star_PurschaseInApp(context: context, peerId: context.peerId), for: context.window)
return .invoked
}, with: self, for: .T, priority: .supreme, modifierFlags: [.command])
#endif
// window.set(handler: { [weak self] _ -> KeyHandlerResult in
// self?.leftController.focusSearch(animated: true)
// return .invoked
// }, with: self, for: .F, priority: .supreme, modifierFlags: [.command, .shift])
window.set(handler: { _ -> KeyHandlerResult in
context.bindings.rootNavigation().push(ShortcutListController(context: context))
return .invoked
}, with: self, for: .Slash, priority: .low, modifierFlags: [.command])
appUpdateDisposable.set((context.account.stateManager.appUpdateInfo |> deliverOnMainQueue).start(next: { info in
}))
suggestedLocalizationDisposable.set(( context.account.postbox.preferencesView(keys: [PreferencesKeys.suggestedLocalization]) |> mapToSignal { preferences -> Signal<SuggestedLocalizationInfo, NoError> in
let preferences = preferences.values[PreferencesKeys.suggestedLocalization]?.get(SuggestedLocalizationEntry.self)
if preferences == nil || !preferences!.isSeen, preferences?.languageCode != appCurrentLanguage.languageCode, preferences?.languageCode != "en" {
let current = Locale.preferredLanguages[0]
let split = current.split(separator: "-")
let lan: String = !split.isEmpty ? String(split[0]) : "en"
if lan != "en" {
return context.engine.localization.suggestedLocalizationInfo(languageCode: lan, extractKeys: ["Suggest.Localization.Header", "Suggest.Localization.Other"]) |> take(1)
}
}
return .complete()
} |> deliverOnMainQueue).start(next: { suggestionInfo in
if suggestionInfo.availableLocalizations.count >= 2 {
showModal(with: SuggestionLocalizationViewController(context, suggestionInfo: suggestionInfo), for: window)
}
}))
someActionsDisposable.add(context.engine.peers.managedUpdatedRecentPeers().start())
clearReadNotifiesDisposable.set(context.account.stateManager.appliedIncomingReadMessages.start(next: { msgIds in
UNUserNotifications.current?.clearNotifies(by: msgIds)
}))
someActionsDisposable.add(applyUpdateTextIfNeeded(context.account.postbox).start())
if let folders = folders {
self.updateLeftSidebar(with: folders, layout: context.layout, animated: false)
}
self.view.splitView.layout()
if let navigation = launchSettings.navigation {
switch navigation {
case .settings:
self.launchAction = .preferences
_ready.set(leftController.settings.ready.get())
leftController.tabController.select(index: leftController.settingsIndex)
case let .profile(peer, necessary):
_ready.set(leftController.chatList.ready.get())
self.leftController.tabController.select(index: self.leftController.chatIndex)
if (necessary || context.layout != .single) {
let controller = PeerInfoController(context: context, peer: peer._asPeer())
controller.navigationController = self.rightController
controller.loadViewIfNeeded(self.rightController.bounds)
self.launchAction = .navigate(controller)
self._ready.set(combineLatest(self.leftController.chatList.ready.get(), controller.ready.get()) |> map { $0 && $1 })
self.leftController.tabController.select(index: self.leftController.chatIndex)
} else {
_ready.set(leftController.chatList.ready.get())
self.leftController.tabController.select(index: self.leftController.chatIndex)
}
case let .chat(peerId, necessary):
_ready.set(leftController.chatList.ready.get())
self.leftController.tabController.select(index: self.leftController.chatIndex)
if (necessary || context.layout != .single) {
let controller = ChatController(context: context, chatLocation: .peer(peerId))
controller.navigationController = self.rightController
controller.loadViewIfNeeded(self.rightController.bounds)
self.launchAction = .navigate(controller)
self._ready.set(combineLatest(self.leftController.chatList.ready.get(), controller.ready.get()) |> map { $0 && $1 })
self.leftController.tabController.select(index: self.leftController.chatIndex)
} else {
// self._ready.set(.single(true))
_ready.set(leftController.chatList.ready.get())
self.leftController.tabController.select(index: self.leftController.chatIndex)
}
case let .thread(threadId, fromId, threadData, _):
self.leftController.tabController.select(index: self.leftController.chatIndex)
self._ready.set(self.leftController.chatList.ready.get())
if let fromId = fromId {
context.navigateToThread(threadId, fromId: fromId)
} else if let _ = threadData {
_ = ForumUI.openTopic(Int64(threadId.id), peerId: threadId.peerId, context: context).start()
}
}
} else {
// self._ready.set(.single(true))
_ready.set(leftController.chatList.ready.get())
leftController.tabController.select(index: leftController.chatIndex)
// _ready.set(leftController.ready.get())
}
if let session = callSession {
rightController.callHeader?.show(true, contextObject: session)
}
if let groupCallContext = groupCallContext {
rightController.callHeader?.show(true, contextObject: groupCallContext)
}
if let inlinePlayerContext = inlinePlayerContext {
rightController.header?.show(true, contextObject: inlinePlayerContext)
}
self.updateFoldersDisposable.set(combineLatest(queue: .mainQueue(), chatListFilterPreferences(engine: context.engine), context.layoutValue).start(next: { [weak self] value, layout in
self?.updateLeftSidebar(with: value, layout: layout, animated: true)
}))
// _ready.set(.single(true))
}
private var folders: ChatListFolders?
private var previousLayout: SplitViewState?
private let foldersReadyDisposable = MetaDisposable()
private func updateLeftSidebar(with folders: ChatListFolders, layout: SplitViewState, animated: Bool) -> Void {
if let window = self.window as? AppWindow {
if (folders.sidebar && !folders.isEmpty) || layout == .minimisize {
self.context.bindings.rootNavigation().navigationBarLeftPosition = 0
window.initialButtonPoint = .system
} else {
self.context.bindings.rootNavigation().navigationBarLeftPosition = layout == .single ? Window.controlsInset : 0
window.initialButtonPoint = .app
}
}
let currentSidebar = !folders.isEmpty && (folders.sidebar)
let previousSidebar = self.folders == nil ? nil : !self.folders!.isEmpty && (self.folders!.sidebar)
let readySignal: Signal<Bool, NoError>
if currentSidebar != previousSidebar {
if !currentSidebar {
leftSidebarController?.removeFromSuperview()
leftSidebarController = nil
readySignal = .single(true)
} else {
let controller = LeftSidebarController(context, filterData: leftController.chatList.filterSignal, updateFilter: leftController.chatList.updateFilter)
controller._frameRect = NSMakeRect(0, 0, leftSidebarWidth, window.frame.height)
controller.loadViewIfNeeded()
self.leftSidebarController = controller
readySignal = controller.ready.get() |> take(1)
}
let enlarge: CGFloat
if currentSidebar && previousSidebar != nil {
enlarge = leftSidebarWidth
} else {
if previousSidebar == true {
enlarge = -leftSidebarWidth
} else {
enlarge = 0
}
}
foldersReadyDisposable.set(readySignal.start(next: { [weak self] _ in
guard let `self` = self else {
return
}
self.view.updateLeftSideView(self.leftSidebarController?.genericView, animated: animated)
if !self.window.isFullScreen {
self.window.setFrame(NSMakeRect(max(0, self.window.frame.minX - enlarge), self.window.frame.minY, self.window.frame.width + enlarge, self.window.frame.height), display: true, animate: false)
}
self.updateMinMaxWindowSize(animated: animated)
}))
}
self.folders = folders
self.previousLayout = layout
}
private func updateMinMaxWindowSize(animated: Bool) {
var width: CGFloat = 380
if leftSidebarController != nil {
width += leftSidebarWidth
}
if context.layout == .minimisize {
width += 70
}
window.minSize = NSMakeSize(width, 550)
if window.frame.width < window.minSize.width {
window.setFrame(NSMakeRect(max(0, window.frame.minX - (window.minSize.width - window.frame.width)), window.frame.minY, window.minSize.width, window.frame.height), display: true, animate: false)
}
}
func runLaunchAction() {
if let launchAction = launchAction {
switch launchAction {
case let .navigate(controller):
leftController.tabController.select(index: leftController.chatIndex)
context.bindings.rootNavigation().push(controller, context.layout == .single)
case .preferences:
leftController.tabController.select(index: leftController.settingsIndex)
}
self.launchAction = nil
} else {
leftController.tabController.select(index: leftController.chatIndex)
}
Queue.mainQueue().justDispatch { [weak self] in
self?.leftController.prepareControllers()
}
}
private func openChat(_ index: Int, _ force: Bool = false) {
leftController.openChat(index, force: force)
}
private func switchAccount(_ index: Int, _ force: Bool = false) {
let accounts = context.sharedContext.activeAccounts |> take(1) |> deliverOnMainQueue
let context = self.context
_ = accounts.start(next: { accounts in
let account = accounts.accounts[min(index - 1, accounts.accounts.count - 1)]
context.sharedContext.switchToAccount(id: account.0, action: nil)
})
}
func splitResizeCursor(at point: NSPoint) -> NSCursor? {
if FastSettings.isMinimisize {
return NSCursor.resizeRight
} else {
if window.frame.width - point.x <= 380 {
return NSCursor.resizeLeft
}
return NSCursor.resizeLeftRight
}
}
func splitViewShouldResize(at point: NSPoint) {
if !FastSettings.isMinimisize {
let max_w = window.frame.width - 380
let result = round(min(max(point.x, 300), max_w))
FastSettings.updateLeftColumnWidth(result)
self.view.splitView.updateStartSize(size: NSMakeSize(result, result), controller: leftController)
}
}
func splitViewDidNeedSwapToLayout(state: SplitViewState) {
let previousState = self.view.splitView.state
self.view.splitView.removeAllControllers()
let w:CGFloat = FastSettings.leftColumnWidth
FastSettings.isMinimisize = false
self.view.splitView.mustMinimisize = false
switch state {
case .single:
rightController.empty = leftController
if rightController.modalAction != nil {
if rightController.controller is ChatController {
rightController.push(ForwardChatListController(context), false)
}
}
if rightController.stackCount == 1, previousState != .none {
leftController.viewWillAppear(false)
}
self.view.splitView.addController(controller: rightController, proportion: SplitProportion(min:380, max:CGFloat.greatestFiniteMagnitude))
if rightController.stackCount == 1, previousState != .none {
leftController.viewDidAppear(false)
}
case .dual:
rightController.empty = emptyController
if rightController.controller is ForwardChatListController {
rightController.back(animated:false)
}
self.view.splitView.addController(controller: leftController, proportion: SplitProportion(min:w, max:w))
self.view.splitView.addController(controller: rightController, proportion: SplitProportion(min:380, max:CGFloat.greatestFiniteMagnitude))
case .minimisize:
self.view.splitView.mustMinimisize = true
FastSettings.isMinimisize = true
self.view.splitView.addController(controller: leftController, proportion: SplitProportion(min:70, max:70))
self.view.splitView.addController(controller: rightController, proportion: SplitProportion(min:380, max:CGFloat.greatestFiniteMagnitude))
default:
break;
}
updateMinMaxWindowSize(animated: false)
DispatchQueue.main.async {
self.view.splitView.needsLayout = true
}
context.layout = state
}
func splitViewDidNeedMinimisize(controller: ViewController) {
}
func splitViewDidNeedFullsize(controller: ViewController) {
}
func splitViewIsCanMinimisize() -> Bool {
return self.leftController.isCanMinimisize();
}
func splitViewDrawBorder() -> Bool {
return false
}
deinit {
self.loggedOutDisposable.dispose()
window.removeAllHandlers(for: self)
settingsDisposable.dispose()
ringingStatesDisposable.dispose()
suggestedLocalizationDisposable.dispose()
audioDisposable.dispose()
alertsDisposable.dispose()
termDisposable.dispose()
viewer?.close()
someActionsDisposable.dispose()
clearReadNotifiesDisposable.dispose()
appUpdateDisposable.dispose()
updateFoldersDisposable.dispose()
foldersReadyDisposable.dispose()
context.cleanup()
NotificationCenter.default.removeObserver(self)
}
}