SPB Git

Repository Public

ThemeLibrary.swift 7.7 KB 190 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Keyboard9// File             : Shared/Sources/ThemeEngine/ThemeLibrary.swift10// Description      : The user's theme state shared with the extension: active11//                    theme (stored whole, so the keyboard never has to look12//                    anything up), custom themes and favourites. Photos live13//                    beside it as files.14// Module           : ThemeEngine15// Repository       : https://git.spboucher.ai/sp-keyboard16// Created          : 2026-12-0117// Last Modified    : 2026-12-0118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : None specified (no license file in this repository)84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation92import SecureStorage9394public struct ThemeLibrary: VersionedSettings, Hashable {95    public static let currentSchemaVersion = 296    public static let storageKey = "themes.library"97    public static var fallback: ThemeLibrary { ThemeLibrary() }98    public static let maxCustomThemes = 4099100    /// Folder of the shared container holding locally resized background photos.101    public static let backgroundsFolder = "Backgrounds"102    public static let maxBackgroundPixels = 1290103    public static let maxBackgroundBytes = 700 * 1024104105    public var schemaVersion = ThemeLibrary.currentSchemaVersion106    public var active: Theme = BuiltInThemes.default107    /// When set, `active` is drawn in light appearance and this one in dark appearance.108    public var darkVariant: Theme? = BuiltInThemes.defaultDark109    public var custom: [Theme] = []110    public var favorites: [String] = []111112    public init() {}113114    public func migrated() -> ThemeLibrary {115        var copy = self116        if copy.schemaVersion < 2 {117            // 1.x had no light/dark pairing, and decoding leaves the new field empty. Someone who never left the118            // 1.0 default gets the 2.0 default pair; any other choice is kept as it was.119            copy.darkVariant = nil120            if copy.active == BuiltInThemes.aurora {121                copy.active = BuiltInThemes.default122                copy.darkVariant = BuiltInThemes.defaultDark123            }124        }125        copy.active = copy.active.normalized()126        copy.darkVariant = copy.darkVariant?.normalized()127        var seen = Set(BuiltInThemes.all.map(\.id))128        copy.custom = copy.custom.prefix(Self.maxCustomThemes).map { $0.normalized() }.filter { seen.insert($0.id).inserted }129        let known = Set(BuiltInThemes.all.map(\.id) + copy.custom.map(\.id))130        copy.favorites = copy.favorites.filter(known.contains)131        return copy132    }133134    public var all: [Theme] { BuiltInThemes.all + custom }135136    /// The theme to draw for the given appearance.137    public func theme(dark: Bool) -> Theme {138        if dark, let darkVariant { return darkVariant }139        return active140    }141142    /// Activates one theme for both appearances.143    public mutating func activate(_ theme: Theme) {144        active = theme145        darkVariant = nil146    }147148    /// Activates a light/dark pair that follows the system appearance.149    public mutating func activatePair(light: Theme, dark: Theme) {150        active = light151        darkVariant = dark152    }153154    public var followsAppearance: Bool { darkVariant != nil }155156    public func theme(id: String) -> Theme? { all.first { $0.id == id } }157158    public mutating func upsert(_ theme: Theme) {159        guard !theme.isBuiltIn else { return }160        let clean = theme.normalized()161        if let index = custom.firstIndex(where: { $0.id == clean.id }) {162            custom[index] = clean163        } else if custom.count < Self.maxCustomThemes {164            custom.append(clean)165        }166        if active.id == clean.id { active = clean }167        if darkVariant?.id == clean.id { darkVariant = clean }168    }169170    public mutating func delete(id: String) {171        custom.removeAll { $0.id == id }172        favorites.removeAll { $0 == id }173        if darkVariant?.id == id { darkVariant = nil }174        if active.id == id {175            active = BuiltInThemes.default176            darkVariant = BuiltInThemes.defaultDark177        }178    }179180    public mutating func toggleFavorite(_ id: String) {181        if let index = favorites.firstIndex(of: id) { favorites.remove(at: index) } else { favorites.append(id) }182    }183184    /// Location of a background photo, `nil` when the shared container is unreachable or the name is unsafe.185    public static func backgroundURL(named name: String, container: URL? = SharedContainer.directory) -> URL? {186        guard Theme.isSafeImageName(name), let container else { return nil }187        return container.appendingPathComponent(backgroundsFolder, isDirectory: true).appendingPathComponent(name)188    }189}190
Files main
Menu

Theme