import AppKit public import Foundation public import Observation @MainActor @Observable public final class AppIconPreferences { public private(set) var selection: AppIconChoice = .classic public private(set) var failure: String? static let preferenceKey = "appearance.appIcon.v1" @ObservationIgnored private let defaults: UserDefaults @ObservationIgnored private let apply: @MainActor (AppIconChoice, AppIconAppearance) throws -> Void @ObservationIgnored private let appearance: @MainActor () -> AppIconAppearance @ObservationIgnored let images: AppIconImages public convenience init(defaults: UserDefaults = .standard) { let images = AppIconImages() self.init(defaults: defaults, images: images) { choice, appearance in if choice == .classic { NSApplication.shared.applicationIconImage = nil } else { NSApplication.shared.applicationIconImage = try images.image(for: choice, appearance: appearance) } } } init( defaults: UserDefaults, images: AppIconImages = AppIconImages(), appearance: @escaping @MainActor () -> AppIconAppearance = { .current }, apply: @escaping @MainActor (AppIconChoice, AppIconAppearance) throws -> Void ) { self.defaults = defaults self.images = images self.appearance = appearance self.apply = apply } public func restore() { do { let choice: AppIconChoice if let saved = defaults.object(forKey: Self.preferenceKey) { guard let raw = saved as? String, let decoded = AppIconChoice(rawValue: raw) else { throw AppIconFailure.invalidPreference } choice = decoded } else { choice = .classic } try apply(choice, appearance()) selection = choice failure = nil } catch { failure = error.localizedDescription } } public func select(_ choice: AppIconChoice) { do { try apply(choice, appearance()) defaults.set(choice.rawValue, forKey: Self.preferenceKey) selection = choice failure = nil } catch { failure = error.localizedDescription } } func refreshAppearance() { // Reload the saved choice so a failed launch can retry without hiding invalid preferences. restore() } }