MainViewController.swift 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  1. // LoopFollow
  2. // MainViewController.swift
  3. import AVFAudio
  4. import Combine
  5. import CoreBluetooth
  6. import EventKit
  7. import ShareClient
  8. import SwiftUI
  9. import UIKit
  10. import UserNotifications
  11. func IsNightscoutEnabled() -> Bool {
  12. return !Storage.shared.url.value.isEmpty
  13. }
  14. private struct APNSCredentialSnapshot: Equatable {
  15. let remoteApnsKey: String
  16. let teamId: String?
  17. let remoteKeyId: String
  18. let lfApnsKey: String
  19. let lfKeyId: String
  20. }
  21. class MainViewController: UIViewController, UNUserNotificationCenterDelegate {
  22. /// The single, long-lived MainViewController that owns the app's data
  23. /// pipeline (scheduleAllTasks). Held strongly so it stays alive — and the
  24. /// engine keeps running — regardless of which tabs are visible or whether
  25. /// Home has been opened. Created once via bootstrap() on first foreground.
  26. private(set) static var shared: MainViewController?
  27. /// Creates and force-loads the shared instance if it does not yet exist.
  28. /// loadViewIfNeeded() triggers viewDidLoad, which starts scheduleAllTasks.
  29. /// Idempotent and main-thread only. Called from MainTabView on appear so
  30. /// the engine runs even when Home lives in the Menu rather than a tab.
  31. static func bootstrap() {
  32. guard shared == nil else { return }
  33. let vc = MainViewController()
  34. shared = vc
  35. vc.loadViewIfNeeded()
  36. }
  37. var statsDisplayModel = StatsDisplayModel()
  38. /// The hosting controller's view — hidden during loading / first-time setup.
  39. private var mainContentView: UIView!
  40. // Setup buttons for first-time configuration
  41. private var setupNightscoutButton: UIButton!
  42. private var setupDexcomButton: UIButton!
  43. let speechSynthesizer = AVSpeechSynthesizer()
  44. // Variables for BG Charts
  45. var firstGraphLoad: Bool = true
  46. var currentOverride = 1.0
  47. var currentSage: sageData?
  48. var currentCage: cageData?
  49. var currentIage: iageData?
  50. var backgroundTask = BackgroundTask()
  51. var graphNowTimer = Timer()
  52. var lastCalendarWriteAttemptTime: TimeInterval = 0
  53. // Info Table Setup
  54. var infoManager: InfoManager!
  55. var profileManager = ProfileManager.shared
  56. var bgData: [ShareGlucoseData] = []
  57. var yesterdayBGData: [ShareGlucoseData] = [] // readings already shifted +24h for the comparison overlay
  58. var basalProfile: [basalProfileStruct] = []
  59. var basalData: [basalGraphStruct] = []
  60. var basalScheduleData: [basalGraphStruct] = []
  61. var bolusData: [bolusGraphStruct] = []
  62. var smbData: [bolusGraphStruct] = []
  63. var carbData: [carbGraphStruct] = []
  64. // Stats-specific data storage (can hold up to 30 days)
  65. var statsBGData: [ShareGlucoseData] = []
  66. var statsBolusData: [bolusGraphStruct] = []
  67. var statsSMBData: [bolusGraphStruct] = []
  68. var statsCarbData: [carbGraphStruct] = []
  69. var statsBasalData: [basalGraphStruct] = []
  70. var overrideGraphData: [DataStructs.overrideStruct] = []
  71. var tempTargetGraphData: [DataStructs.tempTargetStruct] = []
  72. var predictionData: [ShareGlucoseData] = []
  73. var ztPredictionData: [ShareGlucoseData] = []
  74. var iobPredictionData: [ShareGlucoseData] = []
  75. var cobPredictionData: [ShareGlucoseData] = []
  76. var uamPredictionData: [ShareGlucoseData] = []
  77. var openAPSPredBGs: [String: [Double]]?
  78. var openAPSPredUpdatedTime: TimeInterval?
  79. var bgCheckData: [ShareGlucoseData] = []
  80. var suspendGraphData: [DataStructs.timestampOnlyStruct] = []
  81. var resumeGraphData: [DataStructs.timestampOnlyStruct] = []
  82. var sensorStartGraphData: [DataStructs.timestampOnlyStruct] = []
  83. var noteGraphData: [DataStructs.noteStruct] = []
  84. var deviceBatteryData: [DataStructs.batteryStruct] = []
  85. var lastCalDate: Double = 0
  86. var latestLoopStatusString = ""
  87. var latestCOB: CarbMetric?
  88. var latestBasal = ""
  89. var latestPumpVolume: Double = 50.0
  90. var latestIOB: InsulinMetric?
  91. var lastOverrideStartTime: TimeInterval = 0
  92. var lastOverrideEndTime: TimeInterval = 0
  93. var topBG: Double = Storage.shared.minBGScale.value
  94. var topPredictionBG: Double = Storage.shared.minBGScale.value
  95. var lastOverrideAlarm: TimeInterval = 0
  96. var lastTempTargetAlarm: TimeInterval = 0
  97. var lastTempTargetStartTime: TimeInterval = 0
  98. var lastTempTargetEndTime: TimeInterval = 0
  99. // share
  100. var bgDataShare: [ShareGlucoseData] = []
  101. var dexShare: ShareClient?
  102. // calendar setup
  103. let store = EKEventStore()
  104. // Stores the timestamp of the last BG value that was spoken.
  105. var lastSpokenBGDate: TimeInterval = 0
  106. var IsNotLooping = false
  107. let contactImageUpdater = ContactImageUpdater()
  108. let chartModel = BGChartModel()
  109. private var cancellables = Set<AnyCancellable>()
  110. // Loading state management
  111. private var loadingOverlay: UIView?
  112. private var isInitialLoad = true
  113. private var loadingStates: [String: Bool] = [
  114. "bg": false,
  115. "profile": false,
  116. "deviceStatus": false,
  117. ]
  118. private var loadingTimeoutTimer: Timer?
  119. // MARK: - Programmatic UI Setup
  120. private func setupUI() {
  121. view.backgroundColor = .systemBackground
  122. infoManager = InfoManager()
  123. let mainView = MainHomeView(
  124. chartModel: chartModel,
  125. infoManager: infoManager,
  126. statsModel: statsDisplayModel,
  127. onRefresh: { [weak self] in self?.refresh() },
  128. onStatsTap: { [weak self] in self?.statsViewTapped() }
  129. )
  130. let hosting = UIHostingController(rootView: mainView)
  131. // Exclude the keyboard from the hosting controller's safe area. Home has
  132. // no text input, but a stale keyboard frame replayed on foregrounding can
  133. // otherwise compress the layout until a rotation recomputes the safe area.
  134. hosting.safeAreaRegions = .container
  135. hosting.view.translatesAutoresizingMaskIntoConstraints = false
  136. hosting.view.backgroundColor = .clear
  137. addChild(hosting)
  138. view.addSubview(hosting.view)
  139. let safeArea = view.safeAreaLayoutGuide
  140. NSLayoutConstraint.activate([
  141. hosting.view.topAnchor.constraint(equalTo: safeArea.topAnchor),
  142. hosting.view.bottomAnchor.constraint(equalTo: safeArea.bottomAnchor),
  143. hosting.view.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor),
  144. hosting.view.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor),
  145. ])
  146. hosting.didMove(toParent: self)
  147. mainContentView = hosting.view
  148. }
  149. override func viewDidLoad() {
  150. super.viewDidLoad()
  151. // Adopt the singleton only if it is not already set (normally bootstrap()
  152. // has set it to this same instance). Guarding prevents a stray instance
  153. // from displacing the long-lived engine and spawning a second pipeline.
  154. if MainViewController.shared == nil {
  155. MainViewController.shared = self
  156. }
  157. setupUI()
  158. loadDebugData()
  159. // Migrations run in foreground only — see runMigrationsIfNeeded() for details.
  160. runMigrationsIfNeeded()
  161. // Synchronize info types to ensure arrays are the correct size
  162. synchronizeInfoTypes()
  163. let shareUserName = Storage.shared.shareUserName.value
  164. let sharePassword = Storage.shared.sharePassword.value
  165. let shareServer = Storage.shared.shareServer.value == "US" ?KnownShareServers.US.rawValue : KnownShareServers.NON_US.rawValue
  166. dexShare = ShareClient(username: shareUserName, password: sharePassword, shareServer: shareServer)
  167. // setup show/hide graphs (first-time setup check)
  168. updateGraphVisibility()
  169. // Apply initial appearance mode
  170. updateAppearance(Storage.shared.appearanceMode.value)
  171. // Trigger foreground and background functions
  172. let notificationCenter = NotificationCenter.default
  173. notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
  174. notificationCenter.addObserver(self, selector: #selector(appCameToForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
  175. // didBecomeActive is used (not willEnterForeground) to ensure applicationState == .active
  176. // when runMigrationsIfNeeded() is called. This catches migrations deferred by a
  177. // background BGAppRefreshTask launch in Before-First-Unlock state.
  178. notificationCenter.addObserver(self, selector: #selector(appDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
  179. // Posted by AppDelegate after BFU recovery. Vestigial with the readiness gate
  180. // (this controller is built only after storage is ready, so it never fires
  181. // while we're alive); retained one release as a safety net.
  182. notificationCenter.addObserver(self, selector: #selector(handleBFUReloadCompleted), name: .bfuReloadCompleted, object: nil)
  183. #if !targetEnvironment(macCatalyst)
  184. notificationCenter.addObserver(self, selector: #selector(navigateOnLAForeground), name: .liveActivityDidForeground, object: nil)
  185. #endif
  186. // Setup the Graph
  187. if firstGraphLoad {
  188. createGraph()
  189. createSmallBGGraph()
  190. }
  191. // setup display for NS vs Dex
  192. showHideNSDetails()
  193. scheduleAllTasks()
  194. setupNightscoutSocket()
  195. NotificationCenter.default.addObserver(self, selector: #selector(refresh), name: NSNotification.Name("refresh"), object: nil)
  196. /// When an alarm is triggered, go to the snoozer tab
  197. Observable.shared.currentAlarm.$value
  198. .receive(on: DispatchQueue.main)
  199. .compactMap { $0 }
  200. .sink { _ in
  201. let orderedItems = Storage.shared.orderedTabBarItems()
  202. if let index = orderedItems.firstIndex(of: .snoozer) {
  203. Observable.shared.selectedTabIndex.value = index
  204. }
  205. }
  206. .store(in: &cancellables)
  207. Storage.shared.colorBGText.$value
  208. .receive(on: DispatchQueue.main)
  209. .sink { [weak self] _ in
  210. self?.updateBGTextAppearance()
  211. }
  212. .store(in: &cancellables)
  213. // Update appearance when setting changes
  214. Storage.shared.appearanceMode.$value
  215. .receive(on: DispatchQueue.main)
  216. .sink { [weak self] mode in
  217. self?.updateAppearance(mode)
  218. }
  219. .store(in: &cancellables)
  220. Publishers.MergeMany(
  221. Storage.shared.units.$value.map { _ in () }.eraseToAnyPublisher(),
  222. Storage.shared.useIFCC.$value.map { _ in () }.eraseToAnyPublisher(),
  223. Storage.shared.showGMI.$value.map { _ in () }.eraseToAnyPublisher(),
  224. Storage.shared.showStdDev.$value.map { _ in () }.eraseToAnyPublisher()
  225. )
  226. .receive(on: DispatchQueue.main)
  227. .sink { [weak self] _ in
  228. self?.updateStats()
  229. }
  230. .store(in: &cancellables)
  231. Storage.shared.timeInRangeModeRaw.$value
  232. .receive(on: DispatchQueue.main)
  233. .sink { [weak self] _ in
  234. self?.updateBGGraphSettings()
  235. self?.updateBGGraph()
  236. }
  237. .store(in: &cancellables)
  238. Storage.shared.screenlockSwitchState.$value
  239. .receive(on: DispatchQueue.main)
  240. .sink { newValue in
  241. UIApplication.shared.isIdleTimerDisabled = newValue
  242. }
  243. .store(in: &cancellables)
  244. Storage.shared.showDisplayName.$value
  245. .receive(on: DispatchQueue.main)
  246. .sink { [weak self] _ in
  247. self?.updateServerText()
  248. }
  249. .store(in: &cancellables)
  250. Storage.shared.speakBG.$value
  251. .receive(on: DispatchQueue.main)
  252. .sink { [weak self] _ in
  253. self?.updateQuickActions()
  254. }
  255. .store(in: &cancellables)
  256. Storage.shared.url.$value
  257. .receive(on: DispatchQueue.main)
  258. .sink { [weak self] _ in
  259. self?.checkAndShowImportButtonIfNeeded()
  260. }
  261. .store(in: &cancellables)
  262. Storage.shared.token.$value
  263. .receive(on: DispatchQueue.main)
  264. .sink { [weak self] _ in
  265. self?.checkAndShowImportButtonIfNeeded()
  266. }
  267. .store(in: &cancellables)
  268. Storage.shared.shareUserName.$value
  269. .receive(on: DispatchQueue.main)
  270. .sink { [weak self] _ in
  271. self?.checkAndShowImportButtonIfNeeded()
  272. }
  273. .store(in: &cancellables)
  274. Storage.shared.sharePassword.$value
  275. .receive(on: DispatchQueue.main)
  276. .sink { [weak self] _ in
  277. self?.checkAndShowImportButtonIfNeeded()
  278. }
  279. .store(in: &cancellables)
  280. Publishers.CombineLatest4(
  281. Storage.shared.remoteApnsKey.$value,
  282. Storage.shared.teamId.$value,
  283. Storage.shared.remoteKeyId.$value,
  284. Storage.shared.lfApnsKey.$value
  285. )
  286. .combineLatest(Storage.shared.lfKeyId.$value)
  287. .map { values, lfKeyId in
  288. APNSCredentialSnapshot(
  289. remoteApnsKey: values.0,
  290. teamId: values.1,
  291. remoteKeyId: values.2,
  292. lfApnsKey: values.3,
  293. lfKeyId: lfKeyId
  294. )
  295. }
  296. .removeDuplicates()
  297. .dropFirst()
  298. .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main)
  299. .sink { _ in JWTManager.shared.invalidateCache() }
  300. .store(in: &cancellables)
  301. Storage.shared.device.$value
  302. .receive(on: DispatchQueue.main)
  303. .removeDuplicates()
  304. .sink { [weak self] _ in
  305. guard let self = self else { return }
  306. let isTrioDevice = (Storage.shared.device.value == "Trio")
  307. let isLoopDevice = (Storage.shared.device.value == "Loop")
  308. let currentRemoteType = Storage.shared.remoteType.value
  309. // Check if current remote type is invalid for the device
  310. let shouldReset = (currentRemoteType == .loopAPNS && !isLoopDevice) ||
  311. (currentRemoteType == .trc && !isTrioDevice)
  312. if shouldReset {
  313. Storage.shared.remoteType.value = .none
  314. }
  315. }
  316. .store(in: &cancellables)
  317. Storage.shared.device.$value
  318. .receive(on: DispatchQueue.main)
  319. .map { device -> Bool? in
  320. device.isEmpty ? nil : (device == "Loop")
  321. }
  322. .removeDuplicates()
  323. .dropFirst()
  324. .sink { [weak self] isLoop in
  325. guard let isLoop = isLoop else { return }
  326. Storage.shared.predictionDisplayType.value = isLoop ? .lines : .cone
  327. self?.updateOpenAPSPredictionDisplay()
  328. }
  329. .store(in: &cancellables)
  330. updateQuickActions()
  331. speechSynthesizer.delegate = self
  332. // Check configuration and show appropriate UI
  333. if isDataSourceConfigured() {
  334. // Data source configured - show loading overlay
  335. setupLoadingState()
  336. showLoadingOverlay()
  337. } else {
  338. // No data source - hide all data UI and show setup buttons
  339. hideAllDataUI()
  340. isInitialLoad = false
  341. }
  342. checkAndShowImportButtonIfNeeded()
  343. }
  344. // MARK: - Loading Overlay
  345. private func isDataSourceConfigured() -> Bool {
  346. let isNightscoutConfigured = !Storage.shared.url.value.isEmpty
  347. let isDexcomConfigured = !Storage.shared.shareUserName.value.isEmpty && !Storage.shared.sharePassword.value.isEmpty
  348. return isNightscoutConfigured || isDexcomConfigured
  349. }
  350. private func setupLoadingState() {
  351. // If Nightscout is not enabled, mark profile and deviceStatus as loaded
  352. // since we only need BG data from Dexcom Share
  353. if !IsNightscoutEnabled() {
  354. loadingStates["profile"] = true
  355. loadingStates["deviceStatus"] = true
  356. }
  357. }
  358. private func showLoadingOverlay() {
  359. guard loadingOverlay == nil else { return }
  360. // Hide all data UI while loading
  361. hideAllDataUI()
  362. let overlay = UIView(frame: view.bounds)
  363. overlay.backgroundColor = UIColor.systemBackground
  364. overlay.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  365. let activityIndicator = UIActivityIndicatorView(style: .large)
  366. activityIndicator.translatesAutoresizingMaskIntoConstraints = false
  367. activityIndicator.startAnimating()
  368. let loadingLabel = UILabel()
  369. loadingLabel.translatesAutoresizingMaskIntoConstraints = false
  370. loadingLabel.text = "Loading..."
  371. loadingLabel.textAlignment = .center
  372. loadingLabel.font = UIFont.systemFont(ofSize: 17, weight: .medium)
  373. loadingLabel.textColor = UIColor.secondaryLabel
  374. overlay.addSubview(activityIndicator)
  375. overlay.addSubview(loadingLabel)
  376. NSLayoutConstraint.activate([
  377. activityIndicator.centerXAnchor.constraint(equalTo: overlay.centerXAnchor),
  378. activityIndicator.centerYAnchor.constraint(equalTo: overlay.centerYAnchor, constant: -20),
  379. loadingLabel.centerXAnchor.constraint(equalTo: overlay.centerXAnchor),
  380. loadingLabel.topAnchor.constraint(equalTo: activityIndicator.bottomAnchor, constant: 16),
  381. ])
  382. view.addSubview(overlay)
  383. loadingOverlay = overlay
  384. // Set a timeout to hide the loading overlay if data takes too long
  385. loadingTimeoutTimer = Timer.scheduledTimer(withTimeInterval: 15.0, repeats: false) { [weak self] _ in
  386. guard let self = self else { return }
  387. if self.isInitialLoad {
  388. LogManager.shared.log(category: .general, message: "Loading timeout reached, hiding overlay")
  389. self.isInitialLoad = false
  390. self.hideLoadingOverlay()
  391. }
  392. }
  393. }
  394. private func hideLoadingOverlay() {
  395. guard let overlay = loadingOverlay else { return }
  396. // Cancel the timeout timer
  397. loadingTimeoutTimer?.invalidate()
  398. loadingTimeoutTimer = nil
  399. // Show all data UI now that loading is complete
  400. showAllDataUI()
  401. UIView.animate(withDuration: 0.3, animations: {
  402. overlay.alpha = 0
  403. }, completion: { _ in
  404. overlay.removeFromSuperview()
  405. self.loadingOverlay = nil
  406. })
  407. }
  408. func markDataLoaded(_ key: String) {
  409. guard isInitialLoad else { return }
  410. loadingStates[key] = true
  411. // Check if all critical data is loaded
  412. let allLoaded = loadingStates.values.allSatisfy { $0 }
  413. if allLoaded {
  414. isInitialLoad = false
  415. DispatchQueue.main.async {
  416. self.hideLoadingOverlay()
  417. }
  418. }
  419. }
  420. @objc private func navigateOnLAForeground() {
  421. let orderedItems = Storage.shared.orderedTabBarItems()
  422. if Observable.shared.currentAlarm.value != nil,
  423. let snoozerIndex = orderedItems.firstIndex(of: .snoozer)
  424. {
  425. Observable.shared.selectedTabIndex.value = snoozerIndex
  426. } else {
  427. Observable.shared.selectedTabIndex.value = 0
  428. }
  429. }
  430. @objc private func statsViewTapped() {
  431. #if !targetEnvironment(macCatalyst)
  432. let orderedItems = Storage.shared.orderedTabBarItems()
  433. if let statsIndex = orderedItems.firstIndex(of: .stats) {
  434. Observable.shared.selectedTabIndex.value = statsIndex
  435. return
  436. }
  437. #endif
  438. let statsModalView = AggregatedStatsModalView(mainViewController: self)
  439. let hostingController = UIHostingController(rootView: statsModalView)
  440. hostingController.overrideUserInterfaceStyle = Storage.shared.appearanceMode.value.userInterfaceStyle
  441. hostingController.modalPresentationStyle = .fullScreen
  442. present(hostingController, animated: true)
  443. }
  444. // Update the Home Screen Quick Action for toggling the "Speak BG" feature based on the current speakBG setting.
  445. func updateQuickActions() {
  446. let iconName = Storage.shared.speakBG.value ? "pause.circle.fill" : "play.circle.fill"
  447. let iconTemplate = UIApplicationShortcutIcon(systemImageName: iconName)
  448. let shortcut = UIApplicationShortcutItem(type: Bundle.main.bundleIdentifier! + ".toggleSpeakBG",
  449. localizedTitle: "Speak BG",
  450. localizedSubtitle: nil,
  451. icon: iconTemplate,
  452. userInfo: nil)
  453. UIApplication.shared.shortcutItems = [shortcut]
  454. }
  455. deinit {
  456. NotificationCenter.default.removeObserver(self)
  457. }
  458. // Clean all timers and start new ones when refreshing
  459. @objc func refresh() {
  460. LogManager.shared.log(category: .general, message: "Refreshing")
  461. Observable.shared.minAgoText.value = "Refreshing"
  462. scheduleAllTasks()
  463. NightscoutSocketManager.shared.connectIfNeeded()
  464. currentCage = nil
  465. currentSage = nil
  466. currentIage = nil
  467. }
  468. override func viewWillAppear(_ animated: Bool) {
  469. super.viewWillAppear(animated)
  470. UIApplication.shared.isIdleTimerDisabled = Storage.shared.screenlockSwitchState.value
  471. if Observable.shared.chartSettingsChanged.value {
  472. updateBGGraphSettings()
  473. Observable.shared.chartSettingsChanged.value = false
  474. }
  475. }
  476. @objc func appMovedToBackground() {
  477. // Allow screen to turn off
  478. UIApplication.shared.isIdleTimerDisabled = false
  479. // We want to always come back to the home screen
  480. Observable.shared.selectedTabIndex.value = 0
  481. if Storage.shared.backgroundRefreshType.value == .silentTune {
  482. backgroundTask.startBackgroundTask()
  483. BackgroundRefreshManager.shared.scheduleRefresh()
  484. }
  485. if Storage.shared.backgroundRefreshType.value != .none {
  486. BackgroundAlertManager.shared.startBackgroundAlert()
  487. }
  488. NightscoutSocketManager.shared.disconnect()
  489. }
  490. // Migrations must only run when UserDefaults is accessible (i.e. after first unlock).
  491. // When the app is launched in the background by BGAppRefreshTask immediately after a
  492. // reboot, the device may be in Before-First-Unlock (BFU) state: UserDefaults files are
  493. // still encrypted, so every read returns the default value (0 / ""). Running migrations
  494. // in that state would overwrite real settings with empty strings.
  495. //
  496. // Strategy: skip migrations if applicationState == .background; call this method again
  497. // from appCameToForeground() so they run on the first foreground after a BFU launch.
  498. func runMigrationsIfNeeded() {
  499. guard UIApplication.shared.applicationState != .background else { return }
  500. // Capture before migrations run: true for existing users, false for fresh installs.
  501. let isExistingUser = Storage.shared.migrationStep.exists
  502. // When adding a new migration step below:
  503. // 1. Bump the `migrationStep` defaultValue in Storage.swift to the new latest step
  504. // number so fresh installs skip every migration.
  505. // 2. Update any other StorageValue defaults in Storage.swift that this new step
  506. // mutates, so a fresh install ends up in the same state as a migrated user.
  507. // Step 2: Released in v3.1.0 (2025-07-21). Can be removed after 2026-07-21.
  508. if Storage.shared.migrationStep.value < 2 {
  509. Storage.shared.migrateStep2()
  510. Storage.shared.migrationStep.value = 2
  511. }
  512. // Step 3: Released in v4.5.0 (2026-02-01). Can be removed after 2027-02-01.
  513. if Storage.shared.migrationStep.value < 3 {
  514. Storage.shared.migrateStep3()
  515. Storage.shared.migrationStep.value = 3
  516. }
  517. // Step 4: Released in v5.0.0 (2026-03-20). Can be removed after 2027-03-20.
  518. if Storage.shared.migrationStep.value < 4 {
  519. // Existing users need to see the fat/protein order change banner.
  520. // New users never saw the old order, so mark it as already seen.
  521. Storage.shared.hasSeenFatProteinOrderChange.value = !isExistingUser
  522. Storage.shared.migrationStep.value = 4
  523. }
  524. // Step 5: Released in v5.0.0 (2026-03-20). Can be removed after 2027-03-20.
  525. if Storage.shared.migrationStep.value < 5 {
  526. Storage.shared.migrateStep5()
  527. Storage.shared.migrationStep.value = 5
  528. }
  529. if Storage.shared.migrationStep.value < 6 {
  530. Storage.shared.migrateStep6()
  531. Storage.shared.migrationStep.value = 6
  532. }
  533. if Storage.shared.migrationStep.value < 7 {
  534. Storage.shared.migrateStep7()
  535. Storage.shared.migrationStep.value = 7
  536. }
  537. if Storage.shared.migrationStep.value < 8 {
  538. Storage.shared.migrateStep8()
  539. Storage.shared.migrationStep.value = 8
  540. }
  541. if Storage.shared.migrationStep.value < 9 {
  542. Storage.shared.migrateStep9()
  543. Storage.shared.migrationStep.value = 9
  544. }
  545. if Storage.shared.migrationStep.value < 10 {
  546. Storage.shared.migrateStep10()
  547. Storage.shared.migrationStep.value = 10
  548. }
  549. }
  550. @objc func appDidBecomeActive() {
  551. // applicationState == .active is guaranteed here, so the BFU guard in
  552. // runMigrationsIfNeeded() will always pass. Catches the case where viewDidLoad
  553. // ran during a BGAppRefreshTask background launch and deferred migrations.
  554. runMigrationsIfNeeded()
  555. }
  556. @objc func handleBFUReloadCompleted() {
  557. // Show the loading overlay so the user sees feedback during the 2-5s
  558. // while tasks re-run with the now-correct credentials. Tasks scheduled
  559. // before reload used url='' and rescheduled themselves 60s out — reset
  560. // them so they run within their normal 2-5s initial delay.
  561. loadingStates = ["bg": false, "profile": false, "deviceStatus": false]
  562. isInitialLoad = true
  563. setupLoadingState()
  564. showLoadingOverlay()
  565. scheduleAllTasks()
  566. }
  567. @objc func appCameToForeground() {
  568. // BFU recovery (StorageReadiness.recover) is driven by AppDelegate before this
  569. // controller exists (the readiness gate), so handleBFUReloadCompleted() above
  570. // is a vestigial no-op in the gated flow.
  571. // reset screenlock state if needed
  572. UIApplication.shared.isIdleTimerDisabled = Storage.shared.screenlockSwitchState.value
  573. if Storage.shared.backgroundRefreshType.value == .silentTune {
  574. backgroundTask.stopBackgroundTask()
  575. }
  576. if Storage.shared.backgroundRefreshType.value != .none {
  577. BackgroundAlertManager.shared.stopBackgroundAlert()
  578. }
  579. TaskScheduler.shared.checkTasksNow()
  580. NightscoutSocketManager.shared.connectIfNeeded()
  581. checkAndNotifyVersionStatus()
  582. checkAppExpirationStatus()
  583. }
  584. func checkAndNotifyVersionStatus() {
  585. let versionManager = AppVersionManager()
  586. versionManager.checkForNewVersion { latestVersion, isNewer, isBlacklisted in
  587. let now = Date()
  588. // Check if the current version is blacklisted, or if there is a newer version available
  589. if isBlacklisted {
  590. let lastBlacklistShown = Storage.shared.lastBlacklistNotificationShown.value ?? Date.distantPast
  591. if now.timeIntervalSince(lastBlacklistShown) > 86400 { // 24 hours
  592. self.versionAlert(message: "The current version has a critical issue and should be updated as soon as possible.")
  593. Storage.shared.lastBlacklistNotificationShown.value = now
  594. Storage.shared.lastVersionUpdateNotificationShown.value = now
  595. }
  596. } else if isNewer {
  597. let lastVersionUpdateShown = Storage.shared.lastVersionUpdateNotificationShown.value ?? Date.distantPast
  598. if now.timeIntervalSince(lastVersionUpdateShown) > 1_209_600 { // 2 weeks
  599. self.versionAlert(message: "A new version is available: \(latestVersion ?? "Unknown"). It is recommended to update.")
  600. Storage.shared.lastVersionUpdateNotificationShown.value = now
  601. }
  602. }
  603. }
  604. }
  605. func versionAlert(title: String = "Update Available", message: String) {
  606. DispatchQueue.main.async {
  607. let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
  608. alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
  609. self.present(alert, animated: true)
  610. }
  611. }
  612. func checkAppExpirationStatus() {
  613. let now = Date()
  614. let expirationDate = BuildDetails.default.calculateExpirationDate()
  615. let weekBeforeExpiration = Calendar.current.date(byAdding: .day, value: -7, to: expirationDate)!
  616. if now >= weekBeforeExpiration {
  617. let lastExpirationShown = Storage.shared.lastExpirationNotificationShown.value ?? Date.distantPast
  618. if now.timeIntervalSince(lastExpirationShown) > 86400 { // 24 hours
  619. expirationAlert()
  620. Storage.shared.lastExpirationNotificationShown.value = now
  621. }
  622. }
  623. }
  624. func expirationAlert() {
  625. DispatchQueue.main.async {
  626. let alert = UIAlertController(title: "App Expiration Warning", message: "This app will expire in less than a week. Please rebuild to continue using it.", preferredStyle: .alert)
  627. alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
  628. self.present(alert, animated: true)
  629. }
  630. }
  631. override func viewDidAppear(_ animated: Bool) {
  632. super.viewDidAppear(animated)
  633. showHideNSDetails()
  634. // Re-render the graph every time Home appears. The single MainViewController
  635. // is reused across tab/Menu hosts, so its chart view gets re-parented when
  636. // the user switches to Home or moves it between the tab bar and the Menu —
  637. // and Charts does not redraw itself after a re-parent. Rebuilding here keeps
  638. // the curve visible regardless of how Home was reached. It also recovers the
  639. // one-shot firstGraphLoad zoom that is skipped while the view is off-screen
  640. // (force-loaded headless when Home lives in the Menu). Deferred one runloop
  641. // so the nested SwiftUI chart has its final frame; updateBGGraph's own
  642. // width>0 guard skips the initial zoom until it does.
  643. if !bgData.isEmpty {
  644. DispatchQueue.main.async { [weak self] in
  645. self?.updateBGGraph()
  646. }
  647. }
  648. #if !targetEnvironment(macCatalyst)
  649. LiveActivityManager.shared.startFromCurrentState()
  650. #endif
  651. }
  652. func stringFromTimeInterval(interval: TimeInterval) -> String {
  653. let interval = Int(interval)
  654. let minutes = (interval / 60) % 60
  655. let hours = (interval / 3600)
  656. return String(format: "%02d:%02d", hours, minutes)
  657. }
  658. func showHideNSDetails() {
  659. // Info table visibility is handled reactively by MainHomeView.
  660. }
  661. func updateBadge(val: Int) {
  662. if Storage.shared.appBadge.value {
  663. let latestBG = String(val)
  664. UIApplication.shared.applicationIconBadgeNumber = Int(Localizer.removePeriodAndCommaForBadge(Localizer.toDisplayUnits(latestBG))) ?? val
  665. } else {
  666. UIApplication.shared.applicationIconBadgeNumber = 0
  667. }
  668. }
  669. func updateBGTextAppearance() {
  670. if bgData.count > 0 {
  671. let latestBG = bgData[bgData.count - 1].sgv
  672. if Storage.shared.colorBGText.value {
  673. let thresholds = UnitSettingsStore.shared.effectiveThresholds()
  674. if Double(latestBG) >= thresholds.high {
  675. Observable.shared.bgTextColor.value = .yellow
  676. } else if Double(latestBG) <= thresholds.low {
  677. Observable.shared.bgTextColor.value = .red
  678. } else {
  679. Observable.shared.bgTextColor.value = .green
  680. }
  681. } else {
  682. Observable.shared.bgTextColor.value = .primary
  683. }
  684. }
  685. }
  686. func updateAppearance(_ mode: AppearanceMode) {
  687. guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
  688. let window = windowScene.windows.first else { return }
  689. let style: UIUserInterfaceStyle
  690. switch mode {
  691. case .light:
  692. style = .light
  693. case .dark:
  694. style = .dark
  695. case .system:
  696. // Use .unspecified to follow system
  697. style = .unspecified
  698. }
  699. // Update this view controller
  700. overrideUserInterfaceStyle = style
  701. // Update the window (affects the entire app including modals)
  702. window.overrideUserInterfaceStyle = style
  703. }
  704. func bgDirectionGraphic(_ value: String) -> String {
  705. let // graphics:[String:String]=["Flat":"\u{2192}","DoubleUp":"\u{21C8}","SingleUp":"\u{2191}","FortyFiveUp":"\u{2197}\u{FE0E}","FortyFiveDown":"\u{2198}\u{FE0E}","SingleDown":"\u{2193}","DoubleDown":"\u{21CA}","None":"-","NOT COMPUTABLE":"-","RATE OUT OF RANGE":"-"]
  706. graphics: [String: String] = ["Flat": "→", "DoubleUp": "↑↑", "SingleUp": "↑", "FortyFiveUp": "↗", "FortyFiveDown": "↘︎", "SingleDown": "↓", "DoubleDown": "↓↓", "None": "-", "NONE": "-", "NOT COMPUTABLE": "-", "RATE OUT OF RANGE": "-", "": "-"]
  707. return graphics[value]!
  708. }
  709. func writeCalendar() {
  710. store.requestCalendarAccess { granted, error in
  711. if !granted {
  712. LogManager.shared.log(category: .calendar, message: "Failed to get calendar access: \(String(describing: error))")
  713. return
  714. }
  715. self.processCalendarUpdates()
  716. }
  717. }
  718. func processCalendarUpdates() {
  719. if Storage.shared.calendarIdentifier.value == "" { return }
  720. if bgData.count < 1 { return }
  721. // This lets us fire the method to write Min Ago entries only once a minute starting after 6 minutes but allows new readings through
  722. let now = dateTimeUtils.getNowTimeIntervalUTC()
  723. let newestBGDate = bgData[bgData.count - 1].date
  724. if lastCalDate == newestBGDate {
  725. if (now - lastCalendarWriteAttemptTime) < 60 || (now - newestBGDate) < 360 {
  726. return
  727. }
  728. }
  729. // Create Event info
  730. var deltaBG = 0 // protect index out of bounds
  731. if bgData.count > 1 {
  732. deltaBG = bgData[bgData.count - 1].sgv - bgData[bgData.count - 2].sgv as Int
  733. }
  734. let deltaTime = (TimeInterval(Date().timeIntervalSince1970) - bgData[bgData.count - 1].date) / 60
  735. var deltaString = ""
  736. if deltaBG < 0 {
  737. deltaString = Localizer.toDisplayUnits(String(deltaBG))
  738. } else {
  739. deltaString = "+" + Localizer.toDisplayUnits(String(deltaBG))
  740. }
  741. let direction = bgDirectionGraphic(bgData[bgData.count - 1].direction ?? "")
  742. let eventStartDate = Date(timeIntervalSince1970: bgData[bgData.count - 1].date)
  743. var eventEndDate = eventStartDate.addingTimeInterval(60 * 10)
  744. var eventTitle = Storage.shared.watchLine1.value
  745. if Storage.shared.watchLine2.value.count > 1 {
  746. eventTitle += "\n" + Storage.shared.watchLine2.value
  747. }
  748. eventTitle = eventTitle.replacingOccurrences(of: "%BG%", with: Localizer.toDisplayUnits(String(bgData[bgData.count - 1].sgv)))
  749. eventTitle = eventTitle.replacingOccurrences(of: "%DIRECTION%", with: direction)
  750. eventTitle = eventTitle.replacingOccurrences(of: "%DELTA%", with: deltaString)
  751. if currentOverride != 1.0 {
  752. let val = Int(currentOverride * 100)
  753. // let overrideText = String(format:"%f1", self.currentOverride*100)
  754. let text = String(val) + "%"
  755. eventTitle = eventTitle.replacingOccurrences(of: "%OVERRIDE%", with: text)
  756. } else {
  757. eventTitle = eventTitle.replacingOccurrences(of: "%OVERRIDE%", with: "")
  758. }
  759. eventTitle = eventTitle.replacingOccurrences(of: "%LOOP%", with: latestLoopStatusString)
  760. var minAgo = ""
  761. if deltaTime > 9 {
  762. // write old BG reading and continue pushing out end date to show last entry
  763. minAgo = String(Int(deltaTime)) + " min"
  764. eventEndDate = eventStartDate.addingTimeInterval((60 * 10) + (deltaTime * 60))
  765. }
  766. var basal = "~"
  767. if latestBasal != "" {
  768. basal = latestBasal
  769. }
  770. eventTitle = eventTitle.replacingOccurrences(of: "%MINAGO%", with: minAgo)
  771. eventTitle = eventTitle.replacingOccurrences(of: "%IOB%", with: latestIOB?.formattedValue() ?? "0")
  772. eventTitle = eventTitle.replacingOccurrences(of: "%COB%", with: latestCOB?.formattedValue() ?? "0")
  773. eventTitle = eventTitle.replacingOccurrences(of: "%BASAL%", with: basal)
  774. // Delete Events from last 2 hours and 2 hours in future
  775. let deleteStartDate = Date().addingTimeInterval(-60 * 60 * 2)
  776. let deleteEndDate = Date().addingTimeInterval(60 * 60 * 2)
  777. // guard solves for some ios upgrades removing the calendar
  778. guard let deleteCalendar = store.calendar(withIdentifier: Storage.shared.calendarIdentifier.value) as? EKCalendar else { return }
  779. let predicate2 = store.predicateForEvents(withStart: deleteStartDate, end: deleteEndDate, calendars: [deleteCalendar])
  780. let eVDelete = store.events(matching: predicate2) as [EKEvent]?
  781. if eVDelete != nil {
  782. for i in eVDelete! {
  783. do {
  784. try store.remove(i, span: EKSpan.thisEvent, commit: true)
  785. } catch {
  786. LogManager.shared.log(category: .calendar, message: "Failed to remove calendar event: \(error.localizedDescription)")
  787. }
  788. }
  789. }
  790. // Write New Event
  791. let event = EKEvent(eventStore: store)
  792. event.title = eventTitle
  793. event.startDate = eventStartDate
  794. event.endDate = eventEndDate
  795. event.calendar = store.calendar(withIdentifier: Storage.shared.calendarIdentifier.value)
  796. do {
  797. try store.save(event, span: .thisEvent, commit: true)
  798. lastCalendarWriteAttemptTime = now
  799. lastCalDate = bgData[bgData.count - 1].date
  800. } catch {
  801. let msg = "Error storing to calendar: \(error.localizedDescription) (\(error))"
  802. LogManager.shared.log(category: .calendar, message: msg)
  803. }
  804. }
  805. func userNotificationCenter(_: UNUserNotificationCenter, didReceive _: UNNotificationResponse, withCompletionHandler _: @escaping () -> Void) {}
  806. func calculateMaxBgGraphValue() -> Float {
  807. return max(Float(topBG), Float(topPredictionBG))
  808. }
  809. func loadDebugData() {
  810. struct DebugData: Codable {
  811. let debug: Bool?
  812. let url: String?
  813. let token: String?
  814. }
  815. let fileManager = FileManager.default
  816. let url = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("debugData.json")
  817. if fileManager.fileExists(atPath: url.path) {
  818. do {
  819. let data = try Data(contentsOf: url)
  820. let decoder = JSONDecoder()
  821. decoder.dateDecodingStrategy = .iso8601
  822. let debugData = try decoder.decode(DebugData.self, from: data)
  823. LogManager.shared.log(category: .alarm, message: "Loaded DebugData from \(url.path)", isDebug: true)
  824. if let debug = debugData.debug {
  825. Observable.shared.debug.value = debug
  826. }
  827. if let url = debugData.url {
  828. Storage.shared.url.value = url
  829. }
  830. if let token = debugData.token {
  831. Storage.shared.token.value = token
  832. }
  833. } catch {
  834. LogManager.shared.log(category: .alarm, message: "Failed to load DebugData: \(error)", isDebug: true)
  835. }
  836. }
  837. }
  838. private func synchronizeInfoTypes() {
  839. // Safety net: fold any leftover legacy infoSort/infoVisible into
  840. // infoDisplayItems for users whose migrationStep predates that key.
  841. Storage.shared.migrateInfoDisplayItems()
  842. var items = Storage.shared.infoDisplayItems.value
  843. // Drop items whose InfoType no longer exists.
  844. let validTypes = Set(InfoType.allCases)
  845. items.removeAll { !validTypes.contains($0.type) }
  846. // Append any newly added InfoType.
  847. let present = Set(items.map(\.type))
  848. for type in InfoType.allCases where !present.contains(type) {
  849. items.append(InfoDisplayItem(type: type, isVisible: type.defaultVisible, coloring: InfoColoring()))
  850. }
  851. Storage.shared.infoDisplayItems.value = items
  852. }
  853. // MARK: - First Time Setup
  854. private func checkAndShowImportButtonIfNeeded() {
  855. // Check if this is first-time setup (no data source configured)
  856. let isFirstTimeSetup = !isDataSourceConfigured()
  857. if isFirstTimeSetup {
  858. setupFirstTimeButtons()
  859. hideAllDataUI()
  860. // Hide loading overlay if it's showing and mark as not loading
  861. if loadingOverlay != nil {
  862. isInitialLoad = false
  863. hideLoadingOverlay()
  864. }
  865. } else {
  866. hideFirstTimeButtons()
  867. // Only show data UI if we're not in initial loading state
  868. if !isInitialLoad || loadingOverlay == nil {
  869. showAllDataUI()
  870. }
  871. }
  872. }
  873. private func setupFirstTimeButtons() {
  874. // Create Setup Nightscout button
  875. if setupNightscoutButton == nil {
  876. setupNightscoutButton = UIButton(type: .system)
  877. setupNightscoutButton.setTitle("Setup Nightscout", for: .normal)
  878. setupNightscoutButton.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .medium)
  879. setupNightscoutButton.backgroundColor = UIColor.systemBlue
  880. setupNightscoutButton.setTitleColor(.white, for: .normal)
  881. setupNightscoutButton.layer.cornerRadius = 12
  882. setupNightscoutButton.layer.shadowColor = UIColor.black.cgColor
  883. setupNightscoutButton.layer.shadowOffset = CGSize(width: 0, height: 2)
  884. setupNightscoutButton.layer.shadowOpacity = 0.3
  885. setupNightscoutButton.layer.shadowRadius = 4
  886. setupNightscoutButton.addTarget(self, action: #selector(setupNightscoutTapped), for: .touchUpInside)
  887. view.addSubview(setupNightscoutButton)
  888. setupNightscoutButton.translatesAutoresizingMaskIntoConstraints = false
  889. NSLayoutConstraint.activate([
  890. setupNightscoutButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
  891. setupNightscoutButton.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -30),
  892. setupNightscoutButton.widthAnchor.constraint(equalToConstant: 200),
  893. setupNightscoutButton.heightAnchor.constraint(equalToConstant: 50),
  894. ])
  895. }
  896. // Create Setup Dexcom Share button
  897. if setupDexcomButton == nil {
  898. setupDexcomButton = UIButton(type: .system)
  899. setupDexcomButton.setTitle("Setup Dexcom Share", for: .normal)
  900. setupDexcomButton.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .medium)
  901. setupDexcomButton.backgroundColor = UIColor.systemGreen
  902. setupDexcomButton.setTitleColor(.white, for: .normal)
  903. setupDexcomButton.layer.cornerRadius = 12
  904. setupDexcomButton.layer.shadowColor = UIColor.black.cgColor
  905. setupDexcomButton.layer.shadowOffset = CGSize(width: 0, height: 2)
  906. setupDexcomButton.layer.shadowOpacity = 0.3
  907. setupDexcomButton.layer.shadowRadius = 4
  908. setupDexcomButton.addTarget(self, action: #selector(setupDexcomTapped), for: .touchUpInside)
  909. view.addSubview(setupDexcomButton)
  910. setupDexcomButton.translatesAutoresizingMaskIntoConstraints = false
  911. NSLayoutConstraint.activate([
  912. setupDexcomButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
  913. setupDexcomButton.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 30),
  914. setupDexcomButton.widthAnchor.constraint(equalToConstant: 200),
  915. setupDexcomButton.heightAnchor.constraint(equalToConstant: 50),
  916. ])
  917. }
  918. setupNightscoutButton.isHidden = false
  919. setupDexcomButton.isHidden = false
  920. }
  921. private func hideFirstTimeButtons() {
  922. setupNightscoutButton?.isHidden = true
  923. setupDexcomButton?.isHidden = true
  924. }
  925. @objc private func setupNightscoutTapped() {
  926. let navController = UINavigationController()
  927. let nightscoutSettingsView = NightscoutSettingsView(viewModel: .init(), usesModalCloseButton: true, onContinueToUnits: { [weak navController] in
  928. let unitsView = UnitsOnboardingView {
  929. navController?.dismiss(animated: true)
  930. }
  931. let unitsController = UIHostingController(rootView: unitsView)
  932. let style = Storage.shared.appearanceMode.value.userInterfaceStyle
  933. unitsController.overrideUserInterfaceStyle = style
  934. navController?.pushViewController(unitsController, animated: true)
  935. }, onImportSettings: { [weak navController] in
  936. let importSettingsView = ImportExportSettingsView()
  937. let importSettingsController = UIHostingController(rootView: importSettingsView)
  938. let style = Storage.shared.appearanceMode.value.userInterfaceStyle
  939. importSettingsController.overrideUserInterfaceStyle = style
  940. navController?.pushViewController(importSettingsController, animated: true)
  941. })
  942. let hostingController = UIHostingController(rootView: nightscoutSettingsView)
  943. // Apply appearance mode
  944. let style = Storage.shared.appearanceMode.value.userInterfaceStyle
  945. hostingController.overrideUserInterfaceStyle = style
  946. navController.overrideUserInterfaceStyle = style
  947. navController.setViewControllers([hostingController], animated: false)
  948. hostingController.navigationItem.rightBarButtonItem = makeCloseBarButtonItem()
  949. navController.modalPresentationStyle = .pageSheet
  950. present(navController, animated: true)
  951. }
  952. @objc private func setupDexcomTapped() {
  953. let navController = UINavigationController()
  954. let dexcomSettingsView = DexcomSettingsView(viewModel: .init(), usesModalCloseButton: true, onContinueToUnits: { [weak navController] in
  955. let unitsView = UnitsOnboardingView {
  956. navController?.dismiss(animated: true)
  957. }
  958. let unitsController = UIHostingController(rootView: unitsView)
  959. let style = Storage.shared.appearanceMode.value.userInterfaceStyle
  960. unitsController.overrideUserInterfaceStyle = style
  961. navController?.pushViewController(unitsController, animated: true)
  962. })
  963. let hostingController = UIHostingController(rootView: dexcomSettingsView)
  964. // Apply appearance mode
  965. let style = Storage.shared.appearanceMode.value.userInterfaceStyle
  966. hostingController.overrideUserInterfaceStyle = style
  967. navController.overrideUserInterfaceStyle = style
  968. navController.setViewControllers([hostingController], animated: false)
  969. hostingController.navigationItem.rightBarButtonItem = makeCloseBarButtonItem()
  970. navController.modalPresentationStyle = .pageSheet
  971. present(navController, animated: true)
  972. }
  973. private func makeCloseBarButtonItem() -> UIBarButtonItem {
  974. let button = UIBarButtonItem(barButtonSystemItem: .close, target: self, action: #selector(dismissModal))
  975. button.tintColor = .systemBlue
  976. return button
  977. }
  978. private func hideAllDataUI() {
  979. mainContentView?.isHidden = true
  980. }
  981. private func showAllDataUI() {
  982. mainContentView?.isHidden = false
  983. }
  984. private func updateGraphVisibility() {
  985. // Graph and component visibility is handled reactively by MainHomeView.
  986. // This method now only manages the overall content visibility for first-time setup.
  987. if !isDataSourceConfigured() {
  988. mainContentView?.isHidden = true
  989. }
  990. }
  991. @objc private func importSettingsButtonTapped() {
  992. presentImportSettingsView()
  993. }
  994. private func presentImportSettingsView() {
  995. let importExportView = ImportExportSettingsView()
  996. let hostingController = UIHostingController(rootView: importExportView)
  997. hostingController.modalPresentationStyle = .pageSheet
  998. present(hostingController, animated: true)
  999. }
  1000. @objc private func dismissModal() {
  1001. dismiss(animated: true) { [weak self] in
  1002. guard let self = self else { return }
  1003. // Check if user just configured a data source
  1004. if self.isDataSourceConfigured(), self.loadingOverlay == nil {
  1005. // Reset loading states for fresh load
  1006. self.loadingStates = [
  1007. "bg": false,
  1008. "profile": false,
  1009. "deviceStatus": false,
  1010. ]
  1011. self.isInitialLoad = true
  1012. // Show loading overlay and trigger refresh
  1013. self.setupLoadingState()
  1014. self.showLoadingOverlay()
  1015. self.refresh()
  1016. }
  1017. }
  1018. }
  1019. }
  1020. extension MainViewController: AVSpeechSynthesizerDelegate {
  1021. func speechSynthesizer(_: AVSpeechSynthesizer, didFinish _: AVSpeechUtterance) {
  1022. let appState = UIApplication.shared.applicationState
  1023. let isSilentTuneMode = Storage.shared.backgroundRefreshType.value == .silentTune
  1024. if isSilentTuneMode, appState == .background {
  1025. LogManager.shared.log(category: .general, message: "Silent tune active in background; not deactivating session.", isDebug: true)
  1026. } else {
  1027. do {
  1028. try AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
  1029. LogManager.shared.log(category: .general, message: "Audio session deactivated after speech.", isDebug: true)
  1030. } catch {
  1031. LogManager.shared.log(category: .alarm, message: "Failed to deactivate audio session: \(error)")
  1032. }
  1033. }
  1034. }
  1035. }