// Launch at login. // // Windows registers `Run` key entries and, in service mode, a Windows service // (`Class/Program.cs`, `Core/Service.cs`); neither has a macOS equivalent worth // porting (README D6). `SMAppService.mainApp` is the whole macOS answer: it // registers the *bundle* with the login-items machinery, and the user can turn it // off again in System Settings > General > Login Items. // // It needs a real bundle with a bundle identifier and a code signature. Run // unbundled — `swift run`, or the binary straight out of `.build` — there is // nothing to register, so `isAvailable` is false and the UI says why rather than // throwing at the user. import Foundation import ServiceManagement /// The login-item registration for this app. public enum LaunchAtLogin { /// False when the process is not running from an app bundle, in which case /// nothing here does anything. public static var isAvailable: Bool { Bundle.main.bundleIdentifier != nil && Bundle.main.bundleURL.pathExtension == "app" } /// Whether macOS will start this app at login. public static var isEnabled: Bool { guard isAvailable else { return false } return SMAppService.mainApp.status == .enabled } /// Why the toggle is off when it is not simply "the user said no": /// `requiresApproval` means the registration exists but the user has to /// switch it on in System Settings, which is macOS's rule, not ours. public static var needsApproval: Bool { guard isAvailable else { return false } return SMAppService.mainApp.status == .requiresApproval } /// Registers or unregisters. Throws what `SMAppService` throws, which the /// caller shows verbatim: the failures are all "this copy is not where macOS /// will trust it from" and only the user can move it. public static func set(_ enabled: Bool) throws { guard isAvailable else { return } if enabled { try SMAppService.mainApp.register() } else { try SMAppService.mainApp.unregister() } } }