Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Keyboard9// File : Shared/Sources/KeyboardCore/Settings.swift10// Description : Versioned, non-sensitive preferences shared by the app and11// the extension: typing options, languages, the user12// dictionary (words, opt-in learned words) and snippets /13// message templates.14// Module : KeyboardCore15// 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 enum OneHandedMode: String, Codable, Sendable, CaseIterable {95 case off, left, right96}9798public enum HapticPreference: String, Codable, Sendable, CaseIterable {99 /// Use what the active theme asks for.100 case theme, off, light, medium101}102103public struct KeyboardSettings: VersionedSettings, Hashable {104 public static let currentSchemaVersion = 2105 public static let storageKey = "keyboard.settings"106 public static var fallback: KeyboardSettings { KeyboardSettings() }107108 public static let heightScaleRange = 0.85...1.25109110 public var schemaVersion = KeyboardSettings.currentSchemaVersion111 public var enabledLanguages: [KeyboardLanguage] = [.frenchCanada, .english, .spanish]112 public var currentLanguage: KeyboardLanguage = .frenchCanada113 public var autocorrection = true114 public var predictions = true115 public var autoCapitalization = true116 public var doubleSpacePeriod = true117 public var smartQuotes = false118 public var smartApostrophe = false119 public var keyPreview = true120 public var haptics: HapticPreference = .theme121 public var keySound = false122 public var oneHanded: OneHandedMode = .off123 public var heightScale = 1.0124 public var spaceCursor = true125 /// Opt-in: remember new words typed several times. Off by default.126 public var learnWords = false127 public var developerPage = true128 public var financePage = true129 /// Glide typing (2.0): trace a word across the letters without lifting the finger.130 public var glideTyping = true131 /// A dedicated row of digits above the letters.132 public var numberRow = false133 /// Digits on a long press of the top letter row, shown as a small hint on each key (ignored with `numberRow`).134 public var numberHints = true135 /// Resolve touches that land between two keys with what the word being typed makes likely.136 public var adaptiveTouch = true137 public var emojiFavorites: [String] = ["👍", "😂", "❤️", "🙏", "😊", "🎉", "🔥", "✅"]138 public var activeThemeID = "atelier-clair"139140 public init() {}141142 private enum CodingKeys: String, CodingKey {143 case schemaVersion, enabledLanguages, currentLanguage, autocorrection, predictions, autoCapitalization, doubleSpacePeriod144 case smartQuotes, smartApostrophe, keyPreview, haptics, keySound, oneHanded, heightScale, spaceCursor, learnWords145 case developerPage, financePage, glideTyping, numberRow, numberHints, adaptiveTouch, emojiFavorites, activeThemeID146 }147148 /// Tolerant decoding: a missing or unreadable field keeps its default, so an older or hand-edited blob149 /// never costs the user the rest of their preferences.150 public init(from decoder: Decoder) throws {151 let c = try decoder.container(keyedBy: CodingKeys.self)152 func value<T: Decodable>(_ key: CodingKeys, _ fallback: T) -> T { (try? c.decodeIfPresent(T.self, forKey: key)) ?? fallback }153 let d = KeyboardSettings()154 schemaVersion = value(.schemaVersion, 1)155 enabledLanguages = value(.enabledLanguages, d.enabledLanguages)156 currentLanguage = value(.currentLanguage, d.currentLanguage)157 autocorrection = value(.autocorrection, d.autocorrection)158 predictions = value(.predictions, d.predictions)159 autoCapitalization = value(.autoCapitalization, d.autoCapitalization)160 doubleSpacePeriod = value(.doubleSpacePeriod, d.doubleSpacePeriod)161 smartQuotes = value(.smartQuotes, d.smartQuotes)162 smartApostrophe = value(.smartApostrophe, d.smartApostrophe)163 keyPreview = value(.keyPreview, d.keyPreview)164 haptics = value(.haptics, d.haptics)165 keySound = value(.keySound, d.keySound)166 oneHanded = value(.oneHanded, d.oneHanded)167 heightScale = value(.heightScale, d.heightScale)168 spaceCursor = value(.spaceCursor, d.spaceCursor)169 learnWords = value(.learnWords, d.learnWords)170 developerPage = value(.developerPage, d.developerPage)171 financePage = value(.financePage, d.financePage)172 glideTyping = value(.glideTyping, d.glideTyping)173 numberRow = value(.numberRow, d.numberRow)174 numberHints = value(.numberHints, d.numberHints)175 adaptiveTouch = value(.adaptiveTouch, d.adaptiveTouch)176 emojiFavorites = value(.emojiFavorites, d.emojiFavorites)177 activeThemeID = value(.activeThemeID, d.activeThemeID)178 }179180 public func migrated() -> KeyboardSettings {181 var copy = self182 // Schema 1 forced glide typing off (it did not exist yet): 2.0 turns it on once, then respects the choice.183 if copy.schemaVersion < 2 {184 copy.glideTyping = true185 if copy.activeThemeID == "aurora-sp" { copy.activeThemeID = "atelier-clair" }186 }187 var seen = Set<KeyboardLanguage>()188 copy.enabledLanguages = copy.enabledLanguages.filter { seen.insert($0).inserted }189 if copy.enabledLanguages.isEmpty { copy.enabledLanguages = [.frenchCanada] }190 if !copy.enabledLanguages.contains(copy.currentLanguage) { copy.currentLanguage = copy.enabledLanguages[0] }191 copy.heightScale = copy.heightScale.isFinite192 ? min(max(copy.heightScale, Self.heightScaleRange.lowerBound), Self.heightScaleRange.upperBound) : 1193 copy.emojiFavorites = Array(copy.emojiFavorites.filter { !$0.isEmpty && $0.count <= 2 }.prefix(32))194 if copy.activeThemeID.isEmpty || copy.activeThemeID.count > 80 { copy.activeThemeID = "atelier-clair" }195 return copy196 }197198 public func nextLanguage(after language: KeyboardLanguage) -> KeyboardLanguage {199 guard let index = enabledLanguages.firstIndex(of: language) else { return enabledLanguages.first ?? .frenchCanada }200 return enabledLanguages[(index + 1) % enabledLanguages.count]201 }202}203204public struct Snippet: Codable, Hashable, Sendable, Identifiable {205 public enum Category: String, Codable, Sendable, CaseIterable {206 case personal, message, developer207 }208209 public var id: String210 public var title: String211 /// Optional short trigger: typing it shows the snippet as a suggestion (never inserted automatically).212 public var trigger: String213 public var text: String214 public var category: Category215216 public init(id: String = UUID().uuidString, title: String, trigger: String = "", text: String, category: Category = .personal) {217 self.id = id218 self.title = title219 self.trigger = trigger220 self.text = text221 self.category = category222 }223}224225public struct UserDictionary: VersionedSettings, Hashable {226 public static let currentSchemaVersion = 1227 public static let storageKey = "keyboard.dictionary"228 public static var fallback: UserDictionary { UserDictionary() }229230 public static let maxWords = 2000231 public static let maxLearned = 500232 public static let maxSnippets = 200233 public static let maxSnippetLength = 2000234 /// A new word is offered only after it has been typed this many times (when learning is enabled).235 public static let learnThreshold = 2236237 public var schemaVersion = UserDictionary.currentSchemaVersion238 public var words: [String] = []239 public var learned: [String: Int] = [:]240 public var snippets: [Snippet] = UserDictionary.defaultSnippets241242 public init() {}243244 public func migrated() -> UserDictionary {245 var copy = self246 var seen = Set<String>()247 copy.words = copy.words.map(Self.cleanWord).filter { !$0.isEmpty && seen.insert($0.lowercased()).inserted }248 copy.words = Array(copy.words.prefix(Self.maxWords))249 if copy.learned.count > Self.maxLearned {250 copy.learned = Dictionary(uniqueKeysWithValues: copy.learned.sorted { $0.value > $1.value }.prefix(Self.maxLearned).map { ($0.key, $0.value) })251 }252 copy.snippets = copy.snippets.prefix(Self.maxSnippets).compactMap { snippet in253 var clean = snippet254 clean.title = String(clean.title.trimmingCharacters(in: .whitespacesAndNewlines).prefix(60))255 clean.trigger = String(clean.trigger.trimmingCharacters(in: .whitespacesAndNewlines).prefix(24)).filter { !$0.isWhitespace }256 clean.text = String(clean.text.prefix(Self.maxSnippetLength))257 return clean.text.isEmpty ? nil : clean258 }259 return copy260 }261262 public static func cleanWord(_ raw: String) -> String {263 let word = raw.trimmingCharacters(in: .whitespacesAndNewlines)264 guard word.count <= 48, !word.contains(where: \.isWhitespace) else { return "" }265 return word266 }267268 public mutating func addWord(_ raw: String) -> Bool {269 let word = Self.cleanWord(raw)270 guard !word.isEmpty, !words.contains(where: { $0.caseInsensitiveCompare(word) == .orderedSame }), words.count < Self.maxWords else { return false }271 words.append(word)272 return true273 }274275 /// Counts one use of an unknown word. Returns true when it just crossed the learning threshold.276 public mutating func recordLearned(_ word: String) -> Bool {277 let clean = Self.cleanWord(word)278 guard clean.count >= 2 else { return false }279 if learned[clean] == nil, learned.count >= Self.maxLearned,280 let weakest = learned.min(by: { $0.value < $1.value })?.key {281 learned[weakest] = nil282 }283 learned[clean, default: 0] += 1284 return learned[clean] == Self.learnThreshold285 }286287 /// Learned words that reached the threshold, with their counts.288 public var activeLearned: [String: Int] { learned.filter { $0.value >= Self.learnThreshold } }289290 /// Trigger → snippet text, for the suggestion bar.291 public var triggers: [String: String] {292 var map: [String: String] = [:]293 for snippet in snippets where !snippet.trigger.isEmpty { map[snippet.trigger.lowercased()] = snippet.text }294 return map295 }296297 public static let defaultSnippets: [Snippet] = [298 Snippet(id: "snip-omw", title: "En route", trigger: "omw", text: "Je suis en route, j'arrive dans quelques minutes.", category: .message),299 Snippet(id: "snip-merci", title: "Merci", trigger: "mrc", text: "Merci beaucoup, bonne journée!", category: .message),300 Snippet(id: "snip-rappel", title: "Je te rappelle", text: "Je ne peux pas répondre pour l'instant, je te rappelle dès que possible.", category: .message),301 Snippet(id: "snip-courriel", title: "Accusé de réception", text: "Bonjour,\n\nJ'ai bien reçu votre message et je vous reviens sous peu.\n\nCordialement,", category: .message),302 Snippet(id: "snip-guard", title: "guard let", trigger: "gl", text: "guard let value = value else { return }", category: .developer),303 Snippet(id: "snip-func", title: "func Swift", text: "func name() async throws {\n \n}", category: .developer),304 Snippet(id: "snip-arrow", title: "Fonction fléchée", text: "const name = async () => {\n \n};", category: .developer),305 Snippet(id: "snip-pydef", title: "def Python", text: "def name():\n pass", category: .developer),306 Snippet(id: "snip-todo", title: "Bloc de code", text: "```\n\n```", category: .developer),307 ]308}309310/// Whole configuration exchanged by the app's export/import (never contains the key or learned words).311public struct SettingsExport: Codable, Sendable {312 public static let format = "sp-keyboard-settings"313 public var format = SettingsExport.format314 public var schemaVersion = 1315 public var settings: KeyboardSettings316 public var words: [String]317 public var snippets: [Snippet]318319 public init(settings: KeyboardSettings, dictionary: UserDictionary) {320 self.settings = settings321 self.words = dictionary.words322 self.snippets = dictionary.snippets323 }324325 public static let maxImportBytes = 512 * 1024326327 public enum ImportError: Error, Equatable { case tooLarge, notRecognized, unsupportedVersion }328329 public static func decode(_ data: Data) throws -> SettingsExport {330 guard data.count <= maxImportBytes else { throw ImportError.tooLarge }331 guard let decoded = try? JSONDecoder().decode(SettingsExport.self, from: data), decoded.format == format else {332 throw ImportError.notRecognized333 }334 guard decoded.schemaVersion == 1 else { throw ImportError.unsupportedVersion }335 var export = decoded336 export.settings = export.settings.migrated()337 var dictionary = UserDictionary()338 dictionary.words = export.words339 dictionary.snippets = export.snippets340 dictionary = dictionary.migrated()341 export.words = dictionary.words342 export.snippets = dictionary.snippets343 return export344 }345346 public func encoded() throws -> Data {347 let encoder = JSONEncoder()348 encoder.outputFormatting = [.prettyPrinted, .sortedKeys]349 return try encoder.encode(self)350 }351}352