-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathMainViewController.swift
More file actions
1591 lines (1316 loc) · 62 KB
/
MainViewController.swift
File metadata and controls
1591 lines (1316 loc) · 62 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
// LoopFollow
// MainViewController.swift
import AVFAudio
import Charts
import Combine
import CoreBluetooth
import EventKit
import ShareClient
import SwiftUI
import UIKit
import UserNotifications
func IsNightscoutEnabled() -> Bool {
return !Storage.shared.url.value.isEmpty
}
class MainViewController: UIViewController, UITableViewDataSource, ChartViewDelegate, UNUserNotificationCenterDelegate, UIScrollViewDelegate {
var isPresentedAsModal: Bool = false
@IBOutlet var BGText: UILabel!
@IBOutlet var DeltaText: UILabel!
@IBOutlet var DirectionText: UILabel!
@IBOutlet var BGChart: LineChartView!
@IBOutlet var BGChartFull: LineChartView!
@IBOutlet var MinAgoText: UILabel!
@IBOutlet var infoTable: UITableView!
@IBOutlet var Console: UITableViewCell!
@IBOutlet var DragBar: UIImageView!
@IBOutlet var PredictionLabel: UILabel!
@IBOutlet var LoopStatusLabel: UILabel!
@IBOutlet var statsPieChart: PieChartView!
@IBOutlet var statsLowPercent: UILabel!
@IBOutlet var statsInRangePercent: UILabel!
@IBOutlet var statsHighPercent: UILabel!
@IBOutlet var statsAvgBG: UILabel!
@IBOutlet var statsEstA1C: UILabel!
@IBOutlet var statsStdDev: UILabel!
@IBOutlet var serverText: UILabel!
@IBOutlet var statsView: UIView!
@IBOutlet var smallGraphHeightConstraint: NSLayoutConstraint!
var refreshScrollView: UIScrollView!
var refreshControl: UIRefreshControl!
// Setup buttons for first-time configuration
private var setupNightscoutButton: UIButton!
private var setupDexcomButton: UIButton!
let speechSynthesizer = AVSpeechSynthesizer()
// Variables for BG Charts
var firstGraphLoad: Bool = true
var currentOverride = 1.0
var currentSage: sageData?
var currentCage: cageData?
var currentIage: iageData?
var backgroundTask = BackgroundTask()
var graphNowTimer = Timer()
var lastCalendarWriteAttemptTime: TimeInterval = 0
// Info Table Setup
var infoManager: InfoManager!
var profileManager = ProfileManager.shared
var bgData: [ShareGlucoseData] = []
var basalProfile: [basalProfileStruct] = []
var basalData: [basalGraphStruct] = []
var basalScheduleData: [basalGraphStruct] = []
var bolusData: [bolusGraphStruct] = []
var smbData: [bolusGraphStruct] = []
var carbData: [carbGraphStruct] = []
// Stats-specific data storage (can hold up to 30 days)
var statsBGData: [ShareGlucoseData] = []
var statsBolusData: [bolusGraphStruct] = []
var statsSMBData: [bolusGraphStruct] = []
var statsCarbData: [carbGraphStruct] = []
var statsBasalData: [basalGraphStruct] = []
var overrideGraphData: [DataStructs.overrideStruct] = []
var tempTargetGraphData: [DataStructs.tempTargetStruct] = []
var predictionData: [ShareGlucoseData] = []
var bgCheckData: [ShareGlucoseData] = []
var suspendGraphData: [DataStructs.timestampOnlyStruct] = []
var resumeGraphData: [DataStructs.timestampOnlyStruct] = []
var sensorStartGraphData: [DataStructs.timestampOnlyStruct] = []
var noteGraphData: [DataStructs.noteStruct] = []
var chartData = LineChartData()
var deviceBatteryData: [DataStructs.batteryStruct] = []
var lastCalDate: Double = 0
var latestLoopStatusString = ""
var latestCOB: CarbMetric?
var latestBasal = ""
var latestPumpVolume: Double = 50.0
var latestIOB: InsulinMetric?
var lastOverrideStartTime: TimeInterval = 0
var lastOverrideEndTime: TimeInterval = 0
var topBG: Double = Storage.shared.minBGScale.value
var topPredictionBG: Double = Storage.shared.minBGScale.value
var lastOverrideAlarm: TimeInterval = 0
var lastTempTargetAlarm: TimeInterval = 0
var lastTempTargetStartTime: TimeInterval = 0
var lastTempTargetEndTime: TimeInterval = 0
// share
var bgDataShare: [ShareGlucoseData] = []
var dexShare: ShareClient?
// calendar setup
let store = EKEventStore()
// Stores the timestamp of the last BG value that was spoken.
var lastSpokenBGDate: TimeInterval = 0
var autoScrollPauseUntil: Date?
var IsNotLooping = false
let contactImageUpdater = ContactImageUpdater()
private var cancellables = Set<AnyCancellable>()
private var isViewHierarchyReady = false
// Loading state management
private var loadingOverlay: UIView?
private var isInitialLoad = true
private var loadingStates: [String: Bool] = [
"bg": false,
"profile": false,
"deviceStatus": false,
]
private var loadingTimeoutTimer: Timer?
override func viewDidLoad() {
super.viewDidLoad()
loadDebugData()
// Capture before migrations run: true for existing users, false for fresh installs.
let isExistingUser = Storage.shared.migrationStep.exists
if Storage.shared.migrationStep.value < 1 {
Storage.shared.migrateStep1()
Storage.shared.migrationStep.value = 1
}
if Storage.shared.migrationStep.value < 2 {
Storage.shared.migrateStep2()
Storage.shared.migrationStep.value = 2
}
if Storage.shared.migrationStep.value < 3 {
Storage.shared.migrateStep3()
Storage.shared.migrationStep.value = 3
}
// TODO: This migration step can be deleted in March 2027. Check the commit for other places to cleanup.
if Storage.shared.migrationStep.value < 4 {
// Existing users need to see the fat/protein order change banner.
// New users never saw the old order, so mark it as already seen.
Storage.shared.hasSeenFatProteinOrderChange.value = !isExistingUser
Storage.shared.migrationStep.value = 4
}
if Storage.shared.migrationStep.value < 5 {
Storage.shared.migrateStep5()
Storage.shared.migrationStep.value = 5
}
// Synchronize info types to ensure arrays are the correct size
synchronizeInfoTypes()
infoTable.rowHeight = 21
infoTable.dataSource = self
infoTable.tableFooterView = UIView(frame: .zero)
infoTable.bounces = false
infoTable.addBorder(toSide: .Left, withColor: UIColor.darkGray.cgColor, andThickness: 2)
infoManager = InfoManager(tableView: infoTable)
smallGraphHeightConstraint.constant = CGFloat(Storage.shared.smallGraphHeight.value)
view.layoutIfNeeded()
let shareUserName = Storage.shared.shareUserName.value
let sharePassword = Storage.shared.sharePassword.value
let shareServer = Storage.shared.shareServer.value == "US" ?KnownShareServers.US.rawValue : KnownShareServers.NON_US.rawValue
dexShare = ShareClient(username: shareUserName, password: sharePassword, shareServer: shareServer)
// setup show/hide small graph and stats
updateGraphVisibility()
statsView.isHidden = !Storage.shared.showStats.value
BGChart.delegate = self
BGChartFull.delegate = self
// Apply initial appearance mode
updateAppearance(Storage.shared.appearanceMode.value)
// Trigger foreground and background functions
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(appCameToForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
// Setup the Graph
if firstGraphLoad {
createGraph()
createSmallBGGraph()
}
// setup display for NS vs Dex
showHideNSDetails()
scheduleAllTasks()
// Set up refreshScrollView for BGText
refreshScrollView = UIScrollView()
refreshScrollView.translatesAutoresizingMaskIntoConstraints = false
refreshScrollView.alwaysBounceVertical = true
view.addSubview(refreshScrollView)
NSLayoutConstraint.activate([
refreshScrollView.leadingAnchor.constraint(equalTo: BGText.leadingAnchor),
refreshScrollView.trailingAnchor.constraint(equalTo: BGText.trailingAnchor),
refreshScrollView.topAnchor.constraint(equalTo: BGText.topAnchor),
refreshScrollView.bottomAnchor.constraint(equalTo: BGText.bottomAnchor),
])
refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
refreshScrollView.addSubview(refreshControl)
refreshScrollView.alwaysBounceVertical = true
refreshScrollView.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(refresh), name: NSNotification.Name("refresh"), object: nil)
Observable.shared.bgText.$value
.receive(on: DispatchQueue.main)
.sink { [weak self] newValue in
self?.BGText.text = newValue
}
.store(in: &cancellables)
Observable.shared.directionText.$value
.receive(on: DispatchQueue.main)
.sink { [weak self] newValue in
self?.DirectionText.text = newValue
}
.store(in: &cancellables)
Observable.shared.deltaText.$value
.receive(on: DispatchQueue.main)
.sink { [weak self] newValue in
self?.DeltaText.text = newValue
}
.store(in: &cancellables)
/// When an alarm is triggered, go to the snoozer tab
Observable.shared.currentAlarm.$value
.receive(on: DispatchQueue.main)
.compactMap { $0 }
.sink { [weak self] _ in
guard let self = self,
let tabBarController = self.tabBarController,
let vcs = tabBarController.viewControllers, !vcs.isEmpty,
let snoozerIndex = self.getSnoozerTabIndex(),
snoozerIndex < vcs.count else { return }
tabBarController.selectedIndex = snoozerIndex
}
.store(in: &cancellables)
Storage.shared.colorBGText.$value
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.updateBGTextAppearance()
}
.store(in: &cancellables)
// Update appearance when setting changes
Storage.shared.appearanceMode.$value
.receive(on: DispatchQueue.main)
.sink { [weak self] mode in
self?.updateAppearance(mode)
}
.store(in: &cancellables)
Storage.shared.showStats.$value
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.statsView.isHidden = !Storage.shared.showStats.value
}
.store(in: &cancellables)
Storage.shared.useIFCC.$value
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.updateStats()
}
.store(in: &cancellables)
Storage.shared.showSmallGraph.$value
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.updateGraphVisibility()
}
.store(in: &cancellables)
Storage.shared.screenlockSwitchState.$value
.receive(on: DispatchQueue.main)
.sink { newValue in
UIApplication.shared.isIdleTimerDisabled = newValue
}
.store(in: &cancellables)
Storage.shared.showDisplayName.$value
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.updateServerText()
}
.store(in: &cancellables)
Storage.shared.graphTimeZoneEnabled.$value
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.infoTable.reloadData()
}
.store(in: &cancellables)
Storage.shared.graphTimeZoneIdentifier.$value
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.infoTable.reloadData()
}
.store(in: &cancellables)
Storage.shared.speakBG.$value
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.updateQuickActions()
}
.store(in: &cancellables)
// Observe all tab position changes with debouncing to handle batch updates
Publishers.MergeMany(
Storage.shared.homePosition.$value.map { _ in () }.eraseToAnyPublisher(),
Storage.shared.alarmsPosition.$value.map { _ in () }.eraseToAnyPublisher(),
Storage.shared.remotePosition.$value.map { _ in () }.eraseToAnyPublisher(),
Storage.shared.nightscoutPosition.$value.map { _ in () }.eraseToAnyPublisher(),
Storage.shared.snoozerPosition.$value.map { _ in () }.eraseToAnyPublisher(),
Storage.shared.statisticsPosition.$value.map { _ in () }.eraseToAnyPublisher(),
Storage.shared.treatmentsPosition.$value.map { _ in () }.eraseToAnyPublisher()
)
.debounce(for: .milliseconds(100), scheduler: DispatchQueue.main)
.sink { [weak self] _ in
self?.setupTabBar()
}
.store(in: &cancellables)
Storage.shared.url.$value
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.updateNightscoutTabState()
self?.checkAndShowImportButtonIfNeeded()
}
.store(in: &cancellables)
Storage.shared.token.$value
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.checkAndShowImportButtonIfNeeded()
}
.store(in: &cancellables)
Storage.shared.shareUserName.$value
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.checkAndShowImportButtonIfNeeded()
}
.store(in: &cancellables)
Storage.shared.sharePassword.$value
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.checkAndShowImportButtonIfNeeded()
}
.store(in: &cancellables)
Storage.shared.apnsKey.$value
.receive(on: DispatchQueue.main)
.removeDuplicates()
.sink { _ in
JWTManager.shared.invalidateCache()
}
.store(in: &cancellables)
Storage.shared.teamId.$value
.receive(on: DispatchQueue.main)
.removeDuplicates()
.sink { _ in
JWTManager.shared.invalidateCache()
}
.store(in: &cancellables)
Storage.shared.keyId.$value
.receive(on: DispatchQueue.main)
.removeDuplicates()
.sink { _ in
JWTManager.shared.invalidateCache()
}
.store(in: &cancellables)
Storage.shared.device.$value
.receive(on: DispatchQueue.main)
.removeDuplicates()
.sink { [weak self] _ in
guard let self = self else { return }
let isTrioDevice = (Storage.shared.device.value == "Trio")
let isLoopDevice = (Storage.shared.device.value == "Loop")
let currentRemoteType = Storage.shared.remoteType.value
// Check if current remote type is invalid for the device
let shouldReset = (currentRemoteType == .loopAPNS && !isLoopDevice) ||
(currentRemoteType == .trc && !isTrioDevice) ||
(currentRemoteType == .nightscout && !isTrioDevice)
if shouldReset {
Storage.shared.remoteType.value = .none
}
}
.store(in: &cancellables)
updateQuickActions()
// Delay initial tab setup to ensure view hierarchy is ready
// This prevents crashes when trying to modify tabs during viewWillAppear
DispatchQueue.main.async { [weak self] in
self?.isViewHierarchyReady = true
self?.setupTabBar()
}
speechSynthesizer.delegate = self
// Check configuration and show appropriate UI
if isDataSourceConfigured() {
// Data source configured - show loading overlay
setupLoadingState()
showLoadingOverlay()
} else {
// No data source - hide all data UI and show setup buttons
hideAllDataUI()
isInitialLoad = false
}
checkAndShowImportButtonIfNeeded()
}
// MARK: - Loading Overlay
private func isDataSourceConfigured() -> Bool {
let isNightscoutConfigured = !Storage.shared.url.value.isEmpty
let isDexcomConfigured = !Storage.shared.shareUserName.value.isEmpty && !Storage.shared.sharePassword.value.isEmpty
return isNightscoutConfigured || isDexcomConfigured
}
private func setupLoadingState() {
// If Nightscout is not enabled, mark profile and deviceStatus as loaded
// since we only need BG data from Dexcom Share
if !IsNightscoutEnabled() {
loadingStates["profile"] = true
loadingStates["deviceStatus"] = true
}
}
private func showLoadingOverlay() {
guard loadingOverlay == nil else { return }
// Hide all data UI while loading
hideAllDataUI()
let overlay = UIView(frame: view.bounds)
overlay.backgroundColor = UIColor.systemBackground
overlay.autoresizingMask = [.flexibleWidth, .flexibleHeight]
let activityIndicator = UIActivityIndicatorView(style: .large)
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
activityIndicator.startAnimating()
let loadingLabel = UILabel()
loadingLabel.translatesAutoresizingMaskIntoConstraints = false
loadingLabel.text = "Loading..."
loadingLabel.textAlignment = .center
loadingLabel.font = UIFont.systemFont(ofSize: 17, weight: .medium)
loadingLabel.textColor = UIColor.secondaryLabel
overlay.addSubview(activityIndicator)
overlay.addSubview(loadingLabel)
NSLayoutConstraint.activate([
activityIndicator.centerXAnchor.constraint(equalTo: overlay.centerXAnchor),
activityIndicator.centerYAnchor.constraint(equalTo: overlay.centerYAnchor, constant: -20),
loadingLabel.centerXAnchor.constraint(equalTo: overlay.centerXAnchor),
loadingLabel.topAnchor.constraint(equalTo: activityIndicator.bottomAnchor, constant: 16),
])
view.addSubview(overlay)
loadingOverlay = overlay
// Set a timeout to hide the loading overlay if data takes too long
loadingTimeoutTimer = Timer.scheduledTimer(withTimeInterval: 15.0, repeats: false) { [weak self] _ in
guard let self = self else { return }
if self.isInitialLoad {
LogManager.shared.log(category: .general, message: "Loading timeout reached, hiding overlay")
self.isInitialLoad = false
self.hideLoadingOverlay()
}
}
}
private func hideLoadingOverlay() {
guard let overlay = loadingOverlay else { return }
// Cancel the timeout timer
loadingTimeoutTimer?.invalidate()
loadingTimeoutTimer = nil
// Show all data UI now that loading is complete
showAllDataUI()
UIView.animate(withDuration: 0.3, animations: {
overlay.alpha = 0
}, completion: { _ in
overlay.removeFromSuperview()
self.loadingOverlay = nil
})
}
func markDataLoaded(_ key: String) {
guard isInitialLoad else { return }
loadingStates[key] = true
// Check if all critical data is loaded
let allLoaded = loadingStates.values.allSatisfy { $0 }
if allLoaded {
isInitialLoad = false
DispatchQueue.main.async {
self.hideLoadingOverlay()
}
}
}
private func setupTabBar() {
guard isViewHierarchyReady else { return }
guard !isPresentedAsModal else { return }
var tbc = tabBarController
if tbc == nil {
if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
let window = windowScene.windows.first,
let rootVC = window.rootViewController as? UITabBarController
{
tbc = rootVC
}
}
guard let tabBarController = tbc else { return }
// If settings modal is presented, skip rebuild - it will happen when settings is dismissed
if tabBarController.presentedViewController != nil {
return
}
rebuildTabs(tabBarController: tabBarController)
}
/// Static method to rebuild tabs from anywhere in the app
/// This is useful when the MainViewController instance may not be in the tab bar
static func rebuildTabsIfNeeded() {
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
let window = windowScene.windows.first,
let tabBarController = window.rootViewController as? UITabBarController
else { return }
let previousSelectedIndex = tabBarController.selectedIndex
let storyboard = UIStoryboard(name: "Main", bundle: nil)
var viewControllers: [UIViewController] = []
let orderedItems = Storage.shared.orderedTabBarItems()
for (index, item) in orderedItems.prefix(4).enumerated() {
let position = TabPosition.customizablePositions[index]
if let vc = createViewControllerStatic(for: item, position: position, storyboard: storyboard) {
viewControllers.append(vc)
}
}
// Preserve existing Menu nav controller to keep its push stack intact
let existingMenuNav = (tabBarController.viewControllers ?? []).first(where: {
$0.tabBarItem.title == "Menu"
})
if let menuNav = existingMenuNav {
menuNav.tabBarItem = UITabBarItem(title: "Menu", image: UIImage(systemName: "line.3.horizontal"), tag: 4)
viewControllers.append(menuNav)
} else {
viewControllers.append(Self.makeMenuViewController(tag: 4))
}
if let presented = tabBarController.presentedViewController {
presented.dismiss(animated: false) {
tabBarController.setViewControllers(viewControllers, animated: false)
guard !viewControllers.isEmpty else { return }
let targetIndex = min(previousSelectedIndex, viewControllers.count - 1)
tabBarController.selectedIndex = targetIndex
}
} else {
tabBarController.setViewControllers(viewControllers, animated: false)
guard !viewControllers.isEmpty else { return }
let targetIndex = min(previousSelectedIndex, viewControllers.count - 1)
tabBarController.selectedIndex = targetIndex
}
}
/// Static helper to create view controllers
private static func createViewControllerStatic(for item: TabItem, position: TabPosition, storyboard: UIStoryboard) -> UIViewController? {
let tag = position.tabIndex ?? 0
switch item {
case .home:
guard let mainVC = storyboard.instantiateViewController(withIdentifier: "MainViewController") as? MainViewController else {
return nil
}
mainVC.tabBarItem = UITabBarItem(title: "Home", image: UIImage(systemName: item.icon), tag: tag)
return mainVC
case .alarms:
let vc = storyboard.instantiateViewController(withIdentifier: "AlarmViewController")
vc.tabBarItem = UITabBarItem(title: item.displayName, image: UIImage(systemName: item.icon), tag: tag)
return vc
case .remote:
let vc = storyboard.instantiateViewController(withIdentifier: "RemoteViewController")
vc.tabBarItem = UITabBarItem(title: item.displayName, image: UIImage(systemName: item.icon), tag: tag)
return vc
case .nightscout:
let vc = storyboard.instantiateViewController(withIdentifier: "NightscoutViewController")
vc.tabBarItem = UITabBarItem(title: item.displayName, image: UIImage(systemName: item.icon), tag: tag)
return vc
case .snoozer:
let vc = storyboard.instantiateViewController(withIdentifier: "SnoozerViewController")
vc.tabBarItem = UITabBarItem(title: item.displayName, image: UIImage(systemName: item.icon), tag: tag)
return vc
case .treatments:
let treatmentsVC = UIHostingController(rootView: TreatmentsView())
treatmentsVC.tabBarItem = UITabBarItem(title: item.displayName, image: UIImage(systemName: item.icon), tag: tag)
return treatmentsVC
case .stats:
let statsVC = UIHostingController(rootView: AggregatedStatsView(viewModel: AggregatedStatsViewModel(mainViewController: nil)))
let navController = UINavigationController(rootViewController: statsVC)
navController.tabBarItem = UITabBarItem(title: item.displayName, image: UIImage(systemName: item.icon), tag: tag)
return navController
}
}
private func rebuildTabs(tabBarController: UITabBarController) {
let previousSelectedIndex = tabBarController.selectedIndex
let storyboard = UIStoryboard(name: "Main", bundle: nil)
var viewControllers: [UIViewController] = []
let orderedItems = Storage.shared.orderedTabBarItems()
for (index, item) in orderedItems.prefix(4).enumerated() {
let position = TabPosition.customizablePositions[index]
if let vc = createViewController(for: item, position: position, storyboard: storyboard) {
viewControllers.append(vc)
}
}
// Preserve existing Menu nav controller to keep its push stack intact
let existingMenuNav = (tabBarController.viewControllers ?? []).first(where: {
$0.tabBarItem.title == "Menu"
})
if let menuNav = existingMenuNav {
menuNav.tabBarItem = UITabBarItem(title: "Menu", image: UIImage(systemName: "line.3.horizontal"), tag: 4)
viewControllers.append(menuNav)
} else {
viewControllers.append(Self.makeMenuViewController(tag: 4))
}
tabBarController.setViewControllers(viewControllers, animated: false)
guard !viewControllers.isEmpty else { return }
let targetIndex = min(previousSelectedIndex, viewControllers.count - 1)
tabBarController.selectedIndex = targetIndex
updateNightscoutTabState()
}
private func getSnoozerTabIndex() -> Int? {
guard let tabBarController = tabBarController,
let viewControllers = tabBarController.viewControllers else { return nil }
for (index, vc) in viewControllers.enumerated() {
if let _ = vc as? SnoozerViewController {
return index
}
}
return nil
}
private func createViewController(for item: TabItem, position: TabPosition, storyboard: UIStoryboard) -> UIViewController? {
let tag = position.tabIndex ?? 0
switch item {
case .home:
tabBarItem = UITabBarItem(title: "Home", image: UIImage(systemName: item.icon), tag: tag)
return self
case .alarms:
let vc = storyboard.instantiateViewController(withIdentifier: "AlarmViewController")
vc.tabBarItem = UITabBarItem(title: item.displayName, image: UIImage(systemName: item.icon), tag: tag)
return vc
case .remote:
let vc = storyboard.instantiateViewController(withIdentifier: "RemoteViewController")
vc.tabBarItem = UITabBarItem(title: item.displayName, image: UIImage(systemName: item.icon), tag: tag)
return vc
case .nightscout:
let vc = storyboard.instantiateViewController(withIdentifier: "NightscoutViewController")
vc.tabBarItem = UITabBarItem(title: item.displayName, image: UIImage(systemName: item.icon), tag: tag)
return vc
case .snoozer:
let vc = storyboard.instantiateViewController(withIdentifier: "SnoozerViewController")
vc.tabBarItem = UITabBarItem(title: item.displayName, image: UIImage(systemName: item.icon), tag: tag)
return vc
case .treatments:
let treatmentsVC = UIHostingController(rootView: TreatmentsView())
treatmentsVC.tabBarItem = UITabBarItem(title: item.displayName, image: UIImage(systemName: item.icon), tag: tag)
return treatmentsVC
case .stats:
let statsVC = UIHostingController(rootView: AggregatedStatsView(viewModel: AggregatedStatsViewModel(mainViewController: self)))
let navController = UINavigationController(rootViewController: statsVC)
navController.tabBarItem = UITabBarItem(title: item.displayName, image: UIImage(systemName: item.icon), tag: tag)
return navController
}
}
private static func makeMenuViewController(tag: Int) -> UIViewController {
let menuVC = MoreMenuViewController()
let navController = UINavigationController(rootViewController: menuVC)
navController.navigationBar.prefersLargeTitles = true
navController.tabBarItem = UITabBarItem(title: "Menu", image: UIImage(systemName: "line.3.horizontal"), tag: tag)
navController.overrideUserInterfaceStyle = Storage.shared.appearanceMode.value.userInterfaceStyle
return navController
}
private func createComingSoonViewController(title: String, icon: String) -> UIViewController {
let vc = UIViewController()
vc.view.backgroundColor = .systemBackground
let stackView = UIStackView()
stackView.axis = .vertical
stackView.alignment = .center
stackView.spacing = 16
stackView.translatesAutoresizingMaskIntoConstraints = false
let imageView = UIImageView(image: UIImage(systemName: icon))
imageView.tintColor = .secondaryLabel
imageView.contentMode = .scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
imageView.widthAnchor.constraint(equalToConstant: 60),
imageView.heightAnchor.constraint(equalToConstant: 60),
])
let titleLabel = UILabel()
titleLabel.text = title
titleLabel.font = .preferredFont(forTextStyle: .title1)
titleLabel.textColor = .label
stackView.addArrangedSubview(imageView)
stackView.addArrangedSubview(titleLabel)
vc.view.addSubview(stackView)
NSLayoutConstraint.activate([
stackView.centerXAnchor.constraint(equalTo: vc.view.centerXAnchor),
stackView.centerYAnchor.constraint(equalTo: vc.view.centerYAnchor),
])
vc.overrideUserInterfaceStyle = Storage.shared.appearanceMode.value.userInterfaceStyle
return vc
}
// Update the Home Screen Quick Action for toggling the "Speak BG" feature based on the current speakBG setting.
func updateQuickActions() {
let iconName = Storage.shared.speakBG.value ? "pause.circle.fill" : "play.circle.fill"
let iconTemplate = UIApplicationShortcutIcon(systemImageName: iconName)
let shortcut = UIApplicationShortcutItem(type: Bundle.main.bundleIdentifier! + ".toggleSpeakBG",
localizedTitle: "Speak BG",
localizedSubtitle: nil,
icon: iconTemplate,
userInfo: nil)
UIApplication.shared.shortcutItems = [shortcut]
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name("refresh"), object: nil)
}
// Clean all timers and start new ones when refreshing
@objc func refresh() {
LogManager.shared.log(category: .general, message: "Refreshing")
// Clear prediction for both Loop or OpenAPS
// Check if Loop prediction data exists and clear it if necessary
if !predictionData.isEmpty {
predictionData.removeAll()
updatePredictionGraph()
}
// Check if OpenAPS prediction data exists and clear it if necessary
let openAPSDataIndices = [12, 13, 14, 15]
for dataIndex in openAPSDataIndices {
let mainChart = BGChart.lineData!.dataSets[dataIndex] as! LineChartDataSet
let smallChart = BGChartFull.lineData!.dataSets[dataIndex] as! LineChartDataSet
if !mainChart.entries.isEmpty || !smallChart.entries.isEmpty {
updatePredictionGraphGeneric(
dataIndex: dataIndex,
predictionData: [],
chartLabel: "",
color: UIColor.systemGray
)
}
}
MinAgoText.text = "Refreshing"
Observable.shared.minAgoText.value = "Refreshing"
scheduleAllTasks()
currentCage = nil
currentSage = nil
currentIage = nil
refreshControl.endRefreshing()
}
// Scroll down BGText when refreshing
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == refreshScrollView {
let yOffset = scrollView.contentOffset.y
if yOffset < 0 {
BGText.transform = CGAffineTransform(translationX: 0, y: -yOffset)
} else {
BGText.transform = CGAffineTransform.identity
}
}
}
override func viewWillAppear(_: Bool) {
UIApplication.shared.isIdleTimerDisabled = Storage.shared.screenlockSwitchState.value
infoTable.reloadData()
if Observable.shared.chartSettingsChanged.value {
updateBGGraphSettings()
smallGraphHeightConstraint.constant = CGFloat(Storage.shared.smallGraphHeight.value)
view.layoutIfNeeded()
Observable.shared.chartSettingsChanged.value = false
}
}
private var timeZoneOverrideInfoValue: String? {
guard Storage.shared.graphTimeZoneEnabled.value,
let overrideTimeZone = TimeZone(identifier: Storage.shared.graphTimeZoneIdentifier.value)
else {
return nil
}
return overrideTimeZone.identifier
}
// Info Table Functions
func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
guard let infoManager = infoManager else {
return 0
}
let overrideRowCount = timeZoneOverrideInfoValue == nil ? 0 : 1
return infoManager.numberOfRows() + overrideRowCount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)
if indexPath.row == 0, let timeZoneOverrideInfoValue {
cell.textLabel?.text = "Time Zone"
cell.detailTextLabel?.text = timeZoneOverrideInfoValue
return cell
}
let adjustedIndexPath: IndexPath
if timeZoneOverrideInfoValue != nil {
adjustedIndexPath = IndexPath(row: indexPath.row - 1, section: indexPath.section)
} else {
adjustedIndexPath = indexPath
}
if let values = infoManager.dataForIndexPath(adjustedIndexPath) {
cell.textLabel?.text = values.name
cell.detailTextLabel?.text = values.value
} else {
cell.textLabel?.text = ""
cell.detailTextLabel?.text = ""
}
return cell
}
@objc func appMovedToBackground() {
// Allow screen to turn off
UIApplication.shared.isIdleTimerDisabled = false
// We want to always come back to the home screen
if let tabBarController = tabBarController,
let vcs = tabBarController.viewControllers, !vcs.isEmpty
{
tabBarController.selectedIndex = 0
}
if Storage.shared.backgroundRefreshType.value == .silentTune {
backgroundTask.startBackgroundTask()
}
if Storage.shared.backgroundRefreshType.value != .none {
BackgroundAlertManager.shared.startBackgroundAlert()
}
}
@objc func appCameToForeground() {
// reset screenlock state if needed
UIApplication.shared.isIdleTimerDisabled = Storage.shared.screenlockSwitchState.value
if Storage.shared.backgroundRefreshType.value == .silentTune {
backgroundTask.stopBackgroundTask()
}
if Storage.shared.backgroundRefreshType.value != .none {
BackgroundAlertManager.shared.stopBackgroundAlert()
}
TaskScheduler.shared.checkTasksNow()
checkAndNotifyVersionStatus()
checkAppExpirationStatus()
}
func checkAndNotifyVersionStatus() {
let versionManager = AppVersionManager()
versionManager.checkForNewVersion { latestVersion, isNewer, isBlacklisted in
let now = Date()
// Check if the current version is blacklisted, or if there is a newer version available
if isBlacklisted {
let lastBlacklistShown = Storage.shared.lastBlacklistNotificationShown.value ?? Date.distantPast
if now.timeIntervalSince(lastBlacklistShown) > 86400 { // 24 hours
self.versionAlert(message: "The current version has a critical issue and should be updated as soon as possible.")
Storage.shared.lastBlacklistNotificationShown.value = now
Storage.shared.lastVersionUpdateNotificationShown.value = now
}
} else if isNewer {
let lastVersionUpdateShown = Storage.shared.lastVersionUpdateNotificationShown.value ?? Date.distantPast
if now.timeIntervalSince(lastVersionUpdateShown) > 1_209_600 { // 2 weeks
self.versionAlert(message: "A new version is available: \(latestVersion ?? "Unknown"). It is recommended to update.")
Storage.shared.lastVersionUpdateNotificationShown.value = now
}
}
}
}
func versionAlert(title: String = "Update Available", message: String) {