SPB Git

Repository Public

Theme.swift 14.9 KB 342 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Keyboard9// File             : Shared/Sources/ThemeEngine/Theme.swift10// Description      : Versioned theme model (backdrop, key styles, per-row and11//                    per-key tints, metrics, motion), its normalisation rules12//                    and the legibility guarantees applied before a theme13//                    reaches the keyboard.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 Foundation9293/// Animated treatment of the keyboard backdrop. Each one is a cheap Core Animation recipe in the renderer.94public enum BackdropEffect: String, Codable, Sendable, CaseIterable {95    case none, aurora, neon, plasma, waves, stars, iridescence, glass, energy, crystal, luxe, heat96}9798public enum MotionLevel: String, Codable, Sendable, CaseIterable {99    case off, subtle, full100}101102public enum HapticLevel: String, Codable, Sendable, CaseIterable {103    case off, light, medium104}105106/// Typeface of the key caps.107public enum KeyTypeface: String, Codable, Sendable, CaseIterable {108    case system, rounded, serif, mono109}110111/// Look of one family of keys.112public struct KeyStyle: Hashable, Sendable, Codable {113    public var fill: GradientSpec114    public var text: RGBA115    public var border: RGBA116    public var glow: RGBA117118    public init(fill: GradientSpec, text: RGBA, border: RGBA, glow: RGBA) {119        self.fill = fill120        self.text = text121        self.border = border122        self.glow = glow123    }124}125126/// Numeric knobs of the theme editor. Every value is clamped by `Theme.normalized()`.127public struct ThemeMetrics: Hashable, Sendable, Codable {128    public var cornerRadius: Double129    public var heightScale: Double130    public var spacing: Double131    public var keyOpacity: Double132    public var glowIntensity: Double133    public var contrastBoost: Double134    public var borderWidth: Double135    /// Strength of the hard edge drawn under each key cap (0 = flat, 1 = pronounced). Optional so that themes136    /// stored by 1.x still decode; see `edgeDepth`.137    public var depth: Double?138139    public init(cornerRadius: Double = 9, heightScale: Double = 1, spacing: Double = 6, keyOpacity: Double = 1,140                glowIntensity: Double = 0.6, contrastBoost: Double = 0, borderWidth: Double = 1, depth: Double? = nil) {141        self.cornerRadius = cornerRadius142        self.heightScale = heightScale143        self.spacing = spacing144        self.keyOpacity = keyOpacity145        self.glowIntensity = glowIntensity146        self.contrastBoost = contrastBoost147        self.borderWidth = borderWidth148        self.depth = depth149    }150151    /// Edge depth actually drawn: translucent keys of 1.x themes get a light edge, opaque ones a fuller one.152    public var edgeDepth: Double { depth ?? (keyOpacity < 0.9 ? 0.3 : 0.5) }153154    public static let cornerRadiusRange = 0.0...18.0155    public static let heightScaleRange = 0.85...1.25156    public static let spacingRange = 3.0...10.0157    public static let keyOpacityRange = 0.35...1.0158    public static let borderWidthRange = 0.0...2.5159}160161public struct Theme: Hashable, Sendable, Codable, Identifiable {162    public static let currentSchemaVersion = 1163164    public var schemaVersion: Int165    public var id: String166    public var name: String167    public var isDark: Bool168    public var background: GradientSpec169    public var effect: BackdropEffect170    /// Colours the effect animates through (aurora ribbons, plasma blobs, star tint…).171    public var effectColors: [RGBA]172    public var letterKey: KeyStyle173    public var functionKey: KeyStyle174    public var accentKey: KeyStyle175    public var pressedTint: RGBA176    public var suggestionText: RGBA177    /// Optional border/glow tint per letter row (top to bottom).178    public var rowTints: [RGBA]179    /// Optional tint per key, by key identifier (`"a"`, `"space"`, `"return"`…).180    public var keyTints: [String: RGBA]181    public var metrics: ThemeMetrics182    public var motion: MotionLevel183    public var haptic: HapticLevel184    /// File name of a locally resized photo in the shared container. Never a URL, never sent anywhere.185    public var backgroundImage: String?186    public var imageDim: Double187    /// Typeface of the key caps; `nil` (themes stored by 1.x) means the system face.188    public var typeface: KeyTypeface?189190    public init(id: String, name: String, isDark: Bool, background: GradientSpec, effect: BackdropEffect,191                effectColors: [RGBA], letterKey: KeyStyle, functionKey: KeyStyle, accentKey: KeyStyle,192                pressedTint: RGBA, suggestionText: RGBA, rowTints: [RGBA] = [], keyTints: [String: RGBA] = [:],193                metrics: ThemeMetrics = ThemeMetrics(), motion: MotionLevel = .subtle, haptic: HapticLevel = .light,194                backgroundImage: String? = nil, imageDim: Double = 0.35, typeface: KeyTypeface? = nil) {195        self.schemaVersion = Self.currentSchemaVersion196        self.id = id197        self.name = name198        self.isDark = isDark199        self.background = background200        self.effect = effect201        self.effectColors = effectColors202        self.letterKey = letterKey203        self.functionKey = functionKey204        self.accentKey = accentKey205        self.pressedTint = pressedTint206        self.suggestionText = suggestionText207        self.rowTints = rowTints208        self.keyTints = keyTints209        self.metrics = metrics210        self.motion = motion211        self.haptic = haptic212        self.backgroundImage = backgroundImage213        self.imageDim = imageDim214        self.typeface = typeface215    }216217    public var isBuiltIn: Bool { BuiltInThemes.all.contains { $0.id == id } }218}219220public extension Theme {221    static let maxGradientColors = 6222    static let maxKeyTints = 80223    static let maxNameLength = 40224225    /// Clamps every numeric value and trims every list, so a hand-edited or imported theme can never226    /// produce an unusable keyboard.227    func normalized() -> Theme {228        var theme = self229        theme.schemaVersion = Self.currentSchemaVersion230        theme.name = String(theme.name.trimmingCharacters(in: .whitespacesAndNewlines).prefix(Self.maxNameLength))231        if theme.name.isEmpty { theme.name = "Thème" }232        theme.background = theme.background.normalized()233        theme.effectColors = Array(theme.effectColors.prefix(Self.maxGradientColors))234        theme.letterKey.fill = theme.letterKey.fill.normalized()235        theme.functionKey.fill = theme.functionKey.fill.normalized()236        theme.accentKey.fill = theme.accentKey.fill.normalized()237        theme.rowTints = Array(theme.rowTints.prefix(5))238        if theme.keyTints.count > Self.maxKeyTints {239            theme.keyTints = Dictionary(uniqueKeysWithValues: theme.keyTints.sorted { $0.key < $1.key }.prefix(Self.maxKeyTints).map { ($0.key, $0.value) })240        }241        theme.metrics.cornerRadius = theme.metrics.cornerRadius.clamped(ThemeMetrics.cornerRadiusRange)242        theme.metrics.heightScale = theme.metrics.heightScale.clamped(ThemeMetrics.heightScaleRange)243        theme.metrics.spacing = theme.metrics.spacing.clamped(ThemeMetrics.spacingRange)244        theme.metrics.keyOpacity = theme.metrics.keyOpacity.clamped(ThemeMetrics.keyOpacityRange)245        theme.metrics.borderWidth = theme.metrics.borderWidth.clamped(ThemeMetrics.borderWidthRange)246        theme.metrics.glowIntensity = theme.metrics.glowIntensity.clamped01247        theme.metrics.contrastBoost = theme.metrics.contrastBoost.clamped01248        if let depth = theme.metrics.depth { theme.metrics.depth = depth.clamped01 }249        theme.imageDim = theme.imageDim.clamped(0...0.85)250        if let image = theme.backgroundImage, !Self.isSafeImageName(image) { theme.backgroundImage = nil }251        return theme252    }253254    /// Only a bare file name with a known image extension is accepted: no path, no URL.255    static func isSafeImageName(_ name: String) -> Bool {256        guard !name.isEmpty, name.count <= 80, !name.contains("/"), !name.contains(".."), !name.contains(":") else { return false }257        return ["jpg", "jpeg", "png", "heic"].contains((name as NSString).pathExtension.lowercased())258    }259260    /// Backdrop colour a key sits on, for contrast estimates.261    func surface(under style: KeyStyle) -> RGBA {262        var fill = style.fill.average263        fill.a *= metrics.keyOpacity264        return fill.composited(over: background.average)265    }266267    func contrast(of style: KeyStyle) -> Double {268        style.text.opacity(1).contrast(with: surface(under: style))269    }270271    /// Lowest text contrast across the three key families.272    var minimumContrast: Double {273        [letterKey, functionKey, accentKey].map(contrast(of:)).min() ?? 1274    }275276    /// Returns a copy whose key labels reach `ratio` against their surface. Labels are pushed towards white277    /// or black, and when that is not enough the key fill is made opaque: letters stay readable first.278    func legible(minimumRatio ratio: Double = 4.5) -> Theme {279        var theme = self280        let reference = self281        func fixed(_ original: KeyStyle) -> KeyStyle {282            var style = original283            guard reference.contrast(of: style) < ratio else { return style }284            let surface = reference.surface(under: style)285            let target: RGBA = surface.contrast(with: .white) >= surface.contrast(with: .black) ? .white : .black286            for step in stride(from: 0.25, through: 1.0, by: 0.25) {287                let candidate = style.text.opacity(1).mixed(with: target, step)288                if candidate.contrast(with: surface) >= ratio {289                    style.text = candidate290                    return style291                }292            }293            style.text = target294            guard target.contrast(with: surface) < ratio else { return style }295            // Even pure white or black is not enough on this surface: make the key itself opaque.296            style.fill = .solid(target == .white ? RGBA("#111418") : RGBA("#F4F6F8"))297            style.border = target.opacity(0.6)298            return style299        }300        theme.letterKey = fixed(theme.letterKey)301        theme.functionKey = fixed(theme.functionKey)302        theme.accentKey = fixed(theme.accentKey)303        if theme.suggestionText.opacity(1).contrast(with: theme.background.average) < ratio {304            let surface = theme.background.average305            theme.suggestionText = surface.contrast(with: .white) >= surface.contrast(with: .black) ? .white : .black306        }307        return theme308    }309310    /// What the keyboard actually draws, given the system accessibility settings.311    func resolved(increaseContrast: Bool, reduceMotion: Bool, reduceTransparency: Bool = false) -> Theme {312        var theme = normalized()313        if reduceMotion { theme.motion = .off }314        if reduceTransparency { theme.metrics.keyOpacity = 1 }315        let boost = theme.metrics.contrastBoost316        if increaseContrast {317            theme.metrics.keyOpacity = 1318            theme.metrics.borderWidth = max(theme.metrics.borderWidth, 1.5)319            theme.metrics.glowIntensity = min(theme.metrics.glowIntensity, 0.3)320            return theme.legible(minimumRatio: 7)321        }322        return theme.legible(minimumRatio: 4.5 + boost * 2.5)323    }324325    /// Border/glow tint for a key, honouring per-key then per-row overrides.326    func tint(forKey identifier: String, row: Int, fallback: RGBA) -> RGBA {327        if let tint = keyTints[identifier] { return tint }328        if rowTints.indices.contains(row) { return rowTints[row] }329        return fallback330    }331}332333extension GradientSpec {334    func normalized() -> GradientSpec {335        var gradient = self336        if gradient.colors.isEmpty { gradient.colors = [.black] }337        gradient.colors = Array(gradient.colors.prefix(Theme.maxGradientColors))338        gradient.angle = gradient.angle.isFinite ? gradient.angle.truncatingRemainder(dividingBy: 360) : 90339        return gradient340    }341}342
Files main
Menu

Theme