Files
luxe-macos-tray-notifier/Sources/LuxeNotifier/AppState.swift

66 lines
2.2 KiB
Swift
Raw Normal View History

import AppKit
import NotifierCore
import SwiftUI
/// Bridges the socket thread to the main-thread UI.
@MainActor
final class AppState: ObservableObject {
@Published private(set) var history: [NotifyEvent] = []
@Published private(set) var unseenCount = 0
@Published var isMuted = false {
didSet { model.isMuted = isMuted }
}
@Published var launchAtLogin = LoginItem.isEnabled {
didSet { if launchAtLogin != LoginItem.isEnabled { LoginItem.set(launchAtLogin) } }
}
@Published private(set) var permission = BannerPermission.unknown
private let model = NotificationCenterModel()
/// Counts every event since launch. History length can't serve: Clear and the cap both shrink it.
private var totalReceived = 0
private var listener: NotifyListener?
func refreshPermission() {
BannerPoster.refreshStatus { [weak self] status in Task { @MainActor in self?.permission = status } }
}
func start() {
BannerClickHandler.install()
BannerPoster.requestPermission { [weak self] status in Task { @MainActor in self?.permission = status } }
let listener = NotifyListener(
path: NotifySocket.defaultPath(),
onEvent: { [weak self] event in Task { @MainActor in self?.receive(event) } },
onProblem: { NSLog("LuxeNotifier: \($0)") }
)
do { try listener.start() } catch { NSLog("LuxeNotifier: cannot listen on socket: \(error)") }
self.listener = listener
}
func markSeen() {
model.markAllSeen()
publish()
}
func clear() {
model.clear()
publish()
}
private func receive(_ event: NotifyEvent) {
totalReceived += 1
NSLog("LuxeNotifier: received \(event.kind.rawValue): \(event.message)")
StatusFile.set("last-event", "\(event.kind.rawValue) at \(event.timestamp)")
StatusFile.set("events-received", "\(totalReceived)")
let showBanner = model.receive(event)
publish()
if showBanner { BannerPoster.post(title: event.title, message: event.message, terminalBundleID: event.terminalBundleID) }
}
private func publish() {
history = model.history
unseenCount = model.unseenCount
}
}