SPB Git

Repository Public BSD-3-Clause

ThemeStore.swift 7.1 KB 168 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Apps/ORIXMaps/Sources/Map/ThemeStore.swift10// Module           : Map11// Repository       : https://git.spboucher.ai/orix-maps12// Created          : 2026-11-2513// Last Modified    : 2026-11-2514//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import Observation90import ORIXMapStyle9192/// Built-in themes plus the user's own, saved as `.orixtheme` files in Application Support/Themes.93@Observable94final class ThemeStore {95    private(set) var customThemes: [MapTheme] = []96    @ObservationIgnored private let directory: URL9798    init(directory: URL) {99        self.directory = directory100        try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)101        load()102    }103104    var all: [MapTheme] { BuiltInThemes.all + customThemes }105106    func theme(id: String) -> MapTheme? { all.first { $0.id == id } }107108    func isBuiltIn(_ id: String) -> Bool { BuiltInThemes.theme(id: id) != nil }109110    private func url(for id: String) -> URL { directory.appending(path: id + ".orixtheme") }111112    private func load() {113        let files = (try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)) ?? []114        var loaded: [MapTheme] = []115        for f in files where f.pathExtension == "orixtheme" {116            let id = f.deletingPathExtension().lastPathComponent117            guard id.hasPrefix("user."), let data = try? Data(contentsOf: f), let t = try? ThemeDocument.importing(data, newID: id) else { continue }118            loaded.append(t)119        }120        customThemes = loaded.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }121    }122123    /// Saves a user theme (creating or replacing it). Built-in themes cannot be overwritten: editing one creates a copy.124    @discardableResult125    func save(_ theme: MapTheme) throws -> MapTheme {126        var t = theme.sanitized127        if !t.id.hasPrefix("user.") { t.id = "user." + UUID().uuidString.lowercased() }128        try ThemeDocument(theme: t).exported().write(to: url(for: t.id), options: .atomic)129        load()130        return t131    }132133    func delete(id: String) {134        guard id.hasPrefix("user.") else { return }135        try? FileManager.default.removeItem(at: url(for: id))136        load()137    }138139    /// A new editable copy of any theme.140    func duplicate(_ theme: MapTheme, name: String) throws -> MapTheme {141        var copy = theme142        copy.id = "user." + UUID().uuidString.lowercased()143        copy.name = name144        return try save(copy)145    }146147    /// Imports a theme file picked by the user. The file is validated and sanitized; it never replaces an existing theme.148    func importTheme(from fileURL: URL) throws -> MapTheme {149        let scoped = fileURL.startAccessingSecurityScopedResource()150        defer { if scoped { fileURL.stopAccessingSecurityScopedResource() } }151        let size = (try? fileURL.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0152        guard size <= ThemeDocument.maxSize else { throw ThemeDocument.ImportError.tooLarge(size) }153        let theme = try ThemeDocument.importing(try Data(contentsOf: fileURL))154        return try save(theme)155    }156157    /// Writes a theme to a temporary file for the share sheet.158    func exportFile(for theme: MapTheme) throws -> URL {159        let safe = theme.name.components(separatedBy: CharacterSet.alphanumerics.union(CharacterSet(charactersIn: " -_")).inverted).joined()160        let dir = FileManager.default.temporaryDirectory.appending(path: "theme-export", directoryHint: .isDirectory)161        try? FileManager.default.removeItem(at: dir)162        try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)163        let out = dir.appending(path: (safe.isEmpty ? "theme" : safe) + ".orixtheme")164        try ThemeDocument(theme: theme).exported().write(to: out, options: .atomic)165        return out166    }167}168
Files main
Menu

Theme