SPB Git

Repository Public

Layout.swift 24.1 KB 539 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Keyboard9// File             : Shared/Sources/KeyboardCore/Layout.swift10// Description      : Languages, keys and the deterministic layout builder:11//                    letters (QWERTY fr-CA / en / es, AZERTY), numbers,12//                    symbols, developer and finance pages, pads, and the URL /13//                    e-mail bottom rows.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 PredictionCore9394public enum KeyboardLanguage: String, Codable, Sendable, CaseIterable, Identifiable {95    case frenchCanada = "fr-CA"96    case english = "en"97    case spanish = "es"98    case frenchAZERTY = "fr-AZERTY"99100    public var id: String { rawValue }101102    public var lexicon: LexiconLanguage {103        switch self {104        case .frenchCanada, .frenchAZERTY: .french105        case .english: .english106        case .spanish: .spanish107        }108    }109110    public var geometry: KeyGeometry { self == .frenchAZERTY ? .azerty : .qwerty }111112    public var locale: Locale {113        switch self {114        case .frenchCanada, .frenchAZERTY: Locale(identifier: "fr_CA")115        case .english: Locale(identifier: "en_CA")116        case .spanish: Locale(identifier: "es")117        }118    }119120    public var displayName: String {121        switch self {122        case .frenchCanada: "Français (Canada) — QWERTY"123        case .english: "English — QWERTY"124        case .spanish: "Español — QWERTY"125        case .frenchAZERTY: "Français — AZERTY"126        }127    }128129    public var shortLabel: String {130        switch self {131        case .frenchCanada: "FR"132        case .english: "EN"133        case .spanish: "ES"134        case .frenchAZERTY: "AZ"135        }136    }137138    public var spaceLabel: String {139        switch self {140        case .frenchCanada, .frenchAZERTY: "Français"141        case .english: "English"142        case .spanish: "Español"143        }144    }145}146147public enum KeyboardPage: String, Hashable, Sendable, Codable {148    case letters, numbers, symbols, developer, finance149}150151public enum KeyboardPanel: String, Hashable, Sendable {152    case emoji, ai, snippets153}154155public enum KeyAction: Hashable, Sendable {156    case character(String)157    case shift158    case backspace159    case space160    case returnKey161    case globe162    case nextLanguage163    case page(KeyboardPage)164    case panel(KeyboardPanel)165}166167public enum KeyRole: String, Hashable, Sendable {168    case letter, function, accent169}170171public struct Key: Hashable, Sendable, Identifiable {172    public var id: String173    public var label: String174    public var action: KeyAction175    /// Relative width; 1 is one letter key.176    public var width: Double177    public var role: KeyRole178    /// Long-press alternates, first is the default pick.179    public var alternates: [String]180    /// SF Symbol drawn instead of the label, when set.181    public var symbol: String?182    public var accessibilityLabel: String?183    /// Small secondary legend in the corner of the cap (the digit a long press gives).184    public var hint: String?185    /// False for a key that is shown but does nothing right now (return key of an empty search field).186    public var isEnabled = true187188    public init(id: String, label: String, action: KeyAction, width: Double = 1, role: KeyRole = .letter,189                alternates: [String] = [], symbol: String? = nil, accessibilityLabel: String? = nil, hint: String? = nil) {190        self.id = id191        self.label = label192        self.action = action193        self.width = width194        self.role = role195        self.alternates = alternates196        self.symbol = symbol197        self.accessibilityLabel = accessibilityLabel198        self.hint = hint199    }200}201202public struct KeyboardLayout: Hashable, Sendable {203    public var rows: [[Key]]204    /// Widest row in letter units: every row is centred against it.205    public var columns: Double206207    public init(rows: [[Key]]) {208        self.rows = rows209        self.columns = rows.map { $0.reduce(0) { $0 + $1.width } }.max() ?? 10210    }211212    public var keys: [Key] { rows.flatMap { $0 } }213}214215public struct LayoutRequest: Hashable, Sendable {216    public var language: KeyboardLanguage217    public var page: KeyboardPage218    public var variant: LayoutVariant219    public var uppercase: Bool220    public var showsGlobe: Bool221    public var showsLanguageKey: Bool222    public var returnKey: ReturnKeyKind223    /// A row of digits above the letters.224    public var numberRow: Bool225    /// Digits as long-press alternates (and hints) of the top letter row.226    public var numberHints: Bool227    /// False when the field has nothing to send yet and asked for the return key to wait.228    public var returnEnabled: Bool229230    public init(language: KeyboardLanguage, page: KeyboardPage = .letters, variant: LayoutVariant = .standard, uppercase: Bool = false,231                showsGlobe: Bool = true, showsLanguageKey: Bool = false, returnKey: ReturnKeyKind = .default,232                numberRow: Bool = false, numberHints: Bool = false, returnEnabled: Bool = true) {233        self.numberRow = numberRow234        self.numberHints = numberHints235        self.returnEnabled = returnEnabled236        self.language = language237        self.page = page238        self.variant = variant239        self.uppercase = uppercase240        self.showsGlobe = showsGlobe241        self.showsLanguageKey = showsLanguageKey242        self.returnKey = returnKey243    }244}245246public enum LayoutBuilder {247    public static func layout(for request: LayoutRequest) -> KeyboardLayout {248        if request.variant.isPad { return pad(request) }249        var page = request.page250        if request.variant == .numbersAndPunctuation, page == .letters { page = .numbers }251        switch page {252        case .letters: return letters(request)253        case .numbers: return numbers(request)254        case .symbols: return symbols(request)255        case .developer: return developer(request)256        case .finance: return finance(request)257        }258    }259260    // MARK: Letter rows261262    static func letterRows(_ language: KeyboardLanguage) -> [[String]] {263        switch language {264        case .frenchCanada:265            [["q", "w", "e", "r", "t", "y", "u", "i", "o", "p"], ["a", "s", "d", "f", "g", "h", "j", "k", "l", "é"], ["z", "x", "c", "v", "b", "n", "m", "'"]]266        case .english:267            [["q", "w", "e", "r", "t", "y", "u", "i", "o", "p"], ["a", "s", "d", "f", "g", "h", "j", "k", "l"], ["z", "x", "c", "v", "b", "n", "m"]]268        case .spanish:269            [["q", "w", "e", "r", "t", "y", "u", "i", "o", "p"], ["a", "s", "d", "f", "g", "h", "j", "k", "l", "ñ"], ["z", "x", "c", "v", "b", "n", "m"]]270        case .frenchAZERTY:271            [["a", "z", "e", "r", "t", "y", "u", "i", "o", "p"], ["q", "s", "d", "f", "g", "h", "j", "k", "l", "m"], ["w", "x", "c", "v", "b", "n", "'"]]272        }273    }274275    static func letterKey(_ letter: String, request: LayoutRequest, hint: String? = nil) -> Key {276        let locale = request.language.locale277        let shown = request.uppercase ? letter.uppercased(with: locale) : letter278        var alternates = Accents.alternates(for: letter, language: request.language)279        if request.uppercase { alternates = alternates.map { $0.uppercased(with: locale) } }280        if let hint {281            // A letter without accents gives its digit straight away; an accented one keeps its first accent as282            // the default pick (à, é, ù are typed far more often than a digit) and offers the digit next to it.283            alternates.insert(hint, at: alternates.isEmpty ? 0 : 1)284        }285        return Key(id: letter, label: shown, action: .character(shown), alternates: alternates, hint: hint)286    }287288    static let topRowDigits = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]289290    static func letters(_ request: LayoutRequest) -> KeyboardLayout {291        let rows = letterRows(request.language)292        let hinted = request.numberHints && !request.numberRow293        let first = rows[0].enumerated().map { index, letter in294            letterKey(letter, request: request, hint: hinted && index < topRowDigits.count ? topRowDigits[index] : nil)295        }296        // Shift and backspace share what the letters leave of the ten-unit row.297        let side = max(1.0, (10 - Double(rows[2].count)) / 2)298        var third: [Key] = [Key(id: "shift", label: "⇧", action: .shift, width: side, role: .function, symbol: "shift", accessibilityLabel: "Majuscule")]299        third += rows[2].map { letterKey($0, request: request) }300        third.append(backspace(width: side))301        var all: [[Key]] = [302            first,303            rows[1].map { letterKey($0, request: request) },304            third,305            bottomRow(request, pageKey: Key(id: "page.numbers", label: "123", action: .page(.numbers), width: 1.4, role: .function, accessibilityLabel: "Chiffres")),306        ]307        if request.numberRow { all.insert(digits(), at: 0) }308        return KeyboardLayout(rows: all)309    }310311    // MARK: Shared pieces312313    static func backspace(width: Double = 1.4) -> Key {314        Key(id: "backspace", label: "⌫", action: .backspace, width: width, role: .function, symbol: "delete.left", accessibilityLabel: "Effacer")315    }316317    static func chars(_ list: [String], alternates: [String: [String]] = [:]) -> [Key] {318        list.map { Key(id: $0, label: $0, action: .character($0), alternates: alternates[$0] ?? []) }319    }320321    public static func returnLabel(_ kind: ReturnKeyKind, language: KeyboardLanguage) -> String {322        let french = language.lexicon == .french, spanish = language.lexicon == .spanish323        switch kind {324        case .default: return french ? "retour" : spanish ? "intro" : "return"325        case .go: return french ? "aller" : spanish ? "ir" : "go"326        case .search: return french ? "chercher" : spanish ? "buscar" : "search"327        case .send: return french ? "envoyer" : spanish ? "enviar" : "send"328        case .done: return french ? "OK" : spanish ? "OK" : "done"329        case .next: return french ? "suivant" : spanish ? "siguiente" : "next"330        case .join: return french ? "joindre" : spanish ? "unirse" : "join"331        case .route: return french ? "itinéraire" : spanish ? "ruta" : "route"332        case .continue: return french ? "continuer" : spanish ? "continuar" : "continue"333        case .emergencyCall: return "SOS"334        }335    }336337    static func returnKey(_ request: LayoutRequest, width: Double) -> Key {338        let label = returnLabel(request.returnKey, language: request.language)339        var key = Key(id: "return", label: label, action: .returnKey, width: width, role: .accent,340                      symbol: request.returnKey == .default ? "return" : nil, accessibilityLabel: label)341        key.isEnabled = request.returnEnabled342        return key343    }344345    /// Bottom row of every non-pad page: page switch, globe, language, space, context keys, return.346    static func bottomRow(_ request: LayoutRequest, pageKey: Key) -> [Key] {347        var row = [pageKey]348        if request.showsGlobe {349            row.append(Key(id: "globe", label: "🌐", action: .globe, width: 1.1, role: .function, symbol: "globe", accessibilityLabel: "Clavier suivant"))350        }351        if request.showsLanguageKey {352            row.append(Key(id: "language", label: request.language.shortLabel, action: .nextLanguage, width: 1.1, role: .function,353                           accessibilityLabel: "Changer de langue, \(request.language.displayName)"))354        }355        var trailing: [Key] = []356        switch request.variant {357        case .url:358            trailing = chars(["/", "."], alternates: [".": [".com", ".ca", ".org", ".net", ".ai", ".qc.ca", ".fr"]])359        case .email:360            trailing = chars(["@", "."], alternates: [".": [".com", ".ca", ".org", ".net", ".ai", ".qc.ca"]])361        default:362            if request.page == .letters {363                trailing = chars(["."], alternates: [".": [",", "?", "!", ";", ":", "…", "-"]])364            }365        }366        let returnWidth = 2.0367        var used = row.reduce(0) { $0 + $1.width } + trailing.reduce(0) { $0 + $1.width } + returnWidth368        // The emoji key joins the row whenever the space bar keeps a comfortable width.369        if request.page == .letters, 10 - used - 1.1 >= 3.3 {370            row.append(Key(id: "emoji", label: "☺", action: .panel(.emoji), width: 1.1, role: .function, symbol: "face.smiling",371                           accessibilityLabel: "Emoji"))372            used += 1.1373        }374        let spaceWidth = max(2.6, 10 - used)375        row.append(Key(id: "space", label: request.language.spaceLabel, action: .space, width: spaceWidth, role: .letter,376                       accessibilityLabel: "Espace"))377        row += trailing378        row.append(returnKey(request, width: returnWidth))379        return row380    }381382    // MARK: Numbers and symbols383384    static let digitAlternates: [String: [String]] = [385        "0": ["°", "⁰", "∅"], "1": ["¹", "½", "⅓", "¼"], "2": ["²", "⅔"], "3": ["³", "¾"], "4": ["⁴"], "5": ["⁵"],386        "6": ["⁶"], "7": ["⁷"], "8": ["⁸"], "9": ["⁹"],387    ]388389    static func digits() -> [Key] {390        chars(["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"], alternates: digitAlternates)391    }392393    static func numbers(_ request: LayoutRequest) -> KeyboardLayout {394        let french = request.language.lexicon == .french395        let second = chars(["-", "/", ":", ";", "(", ")", "$", "&", "@", "\""], alternates: [396            "-": ["–", "—", "•"], "$": ["€", "£", "¥", "¢", "₿"], "&": ["§"],397            "\"": french ? ["«", "»", "“", "”"] : ["“", "”", "«", "»"], "/": ["\\"],398        ])399        var third: [Key] = [Key(id: "page.symbols", label: "#+=", action: .page(.symbols), width: 1.4, role: .function, accessibilityLabel: "Symboles")]400        third += chars([".", ",", "?", "!", "'"], alternates: ["?": ["¿"], "!": ["¡"], "'": ["’", "‘", "`"], ".": ["…"]]).map { key in401            var wide = key402            wide.width = 1.44403            return wide404        }405        third.append(backspace())406        return KeyboardLayout(rows: [digits(), second, third, bottomRow(request, pageKey: lettersKey())])407    }408409    static func symbols(_ request: LayoutRequest) -> KeyboardLayout {410        let first = chars(["[", "]", "{", "}", "#", "%", "^", "*", "+", "="], alternates: ["%": ["‰"], "=": ["≠", "≈"], "+": ["±"]])411        let second = chars(["_", "\\", "|", "~", "<", ">", "€", "£", "¥", "•"], alternates: ["<": ["≤", "«"], ">": ["≥", "»"], "•": ["·", "°"]])412        var third: [Key] = [Key(id: "page.numbers", label: "123", action: .page(.numbers), width: 1.4, role: .function, accessibilityLabel: "Chiffres")]413        third += chars([".", ",", "?", "!", "'"]).map { key in414            var wide = key415            wide.width = 1.44416            return wide417        }418        third.append(backspace())419        return KeyboardLayout(rows: [first, second, third, bottomRow(request, pageKey: lettersKey())])420    }421422    static func lettersKey(width: Double = 1.4) -> Key {423        Key(id: "page.letters", label: "ABC", action: .page(.letters), width: width, role: .function, accessibilityLabel: "Lettres")424    }425426    // MARK: Developer and finance427428    static func developer(_ request: LayoutRequest) -> KeyboardLayout {429        let second = chars(["{", "}", "[", "]", "(", ")", "<", ">", "/", "\\"], alternates: ["<": ["<=", "<<", "</"], ">": [">=", ">>", "/>"], "/": ["//", "/*", "*/"]])430        let third = chars(["=", "+", "-", "*", "%", "&", "|", "!", "?", ":"], alternates: [431            "=": ["==", "===", "=>", "!=", "+=", "-="], "-": ["->", "--", "-="], "+": ["++", "+="], "&": ["&&"], "|": ["||"],432            "!": ["!=", "!=="], "?": ["??", "?."], ":": ["::", ":="],433        ])434        var fourth: [Key] = [lettersKey(width: 1.2)]435        fourth += chars(["`", "'", "\"", "_", "#", "$", "@", ";"], alternates: ["`": ["```"], "$": ["${}"], "\"": ["\"\""], "'": ["''"]]).map { key in436            var narrow = key437            narrow.width = 0.95438            return narrow439        }440        fourth.append(backspace(width: 1.2))441        var bottom = [Key(id: "page.numbers", label: "123", action: .page(.numbers), width: 1.4, role: .function, accessibilityLabel: "Chiffres")]442        if request.showsGlobe {443            bottom.append(Key(id: "globe", label: "🌐", action: .globe, width: 1.1, role: .function, symbol: "globe", accessibilityLabel: "Clavier suivant"))444        }445        bottom.append(Key(id: "tab", label: "⇥", action: .character("\t"), width: 1.1, role: .function, accessibilityLabel: "Tabulation"))446        let used = bottom.reduce(0) { $0 + $1.width } + 2 + 2447        bottom.append(Key(id: "space", label: "espace", action: .space, width: max(2.4, 10 - used), accessibilityLabel: "Espace"))448        bottom += chars([".", ","])449        bottom.append(returnKey(request, width: 2))450        return KeyboardLayout(rows: [digits(), second, third, fourth, bottom])451    }452453    static func finance(_ request: LayoutRequest) -> KeyboardLayout {454        let second = chars(["%", "$", "€", "£", "¥", "Δ", "σ", "β", "Σ", "√"], alternates: [455            "%": ["‰", "bps"], "$": ["CAD", "USD", "¢"], "€": ["EUR"], "Δ": ["δ", "∂", "∇"], "σ": ["σ²", "μ", "ρ"], "β": ["α", "γ", "θ", "λ"],456            "Σ": ["∑", "∏", "∫"], "√": ["∛"],457        ])458        let third = chars(["+", "−", "×", "÷", "=", "≈", "≠", "≤", "≥", "±"], alternates: ["−": ["-", "–"], "×": ["*", "·"], "÷": ["/"]])459        var fourth: [Key] = [lettersKey(width: 1.2)]460        fourth += chars(["(", ")", "²", "³", "ⁿ", "µ", "π", "∞"], alternates: [461            "²": ["⁰", "¹", "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹"], "ⁿ": ["⁻¹", "⁺", "⁻", "ᵗ", "ⁱ"], "³": ["₀", "₁", "₂", "₃", "ₜ"],462        ]).map { key in463            var narrow = key464            narrow.width = 0.95465            return narrow466        }467        fourth.append(backspace(width: 1.2))468        var bottom = [Key(id: "page.numbers", label: "123", action: .page(.numbers), width: 1.4, role: .function, accessibilityLabel: "Chiffres")]469        if request.showsGlobe {470            bottom.append(Key(id: "globe", label: "🌐", action: .globe, width: 1.1, role: .function, symbol: "globe", accessibilityLabel: "Clavier suivant"))471        }472        let used = bottom.reduce(0) { $0 + $1.width } + 2 + 2473        bottom.append(Key(id: "space", label: "espace", action: .space, width: max(2.4, 10 - used), accessibilityLabel: "Espace"))474        bottom += chars([".", ","])475        bottom.append(returnKey(request, width: 2))476        return KeyboardLayout(rows: [digits(), second, third, fourth, bottom])477    }478479    // MARK: Pads480481    static func pad(_ request: LayoutRequest) -> KeyboardLayout {482        func wide(_ value: String, id: String? = nil) -> Key {483            Key(id: id ?? value, label: value, action: .character(value), width: 3.3)484        }485        let decimal = Locale.current.decimalSeparator ?? "."486        var lastRow: [Key]487        switch request.variant {488        case .decimalPad:489            lastRow = [wide(decimal, id: "decimal"), wide("0"), backspace(width: 3.3)]490        case .phonePad:491            var plus = wide("+")492            plus.alternates = ["*", "#", ",", ";"]493            lastRow = [plus, wide("0"), backspace(width: 3.3)]494        default:495            if request.showsGlobe {496                lastRow = [Key(id: "globe", label: "🌐", action: .globe, width: 3.3, role: .function, symbol: "globe", accessibilityLabel: "Clavier suivant"),497                           wide("0"), backspace(width: 3.3)]498            } else {499                lastRow = [Key(id: "pad.blank", label: "", action: .character(""), width: 3.3, role: .function), wide("0"), backspace(width: 3.3)]500            }501        }502        return KeyboardLayout(rows: [503            [wide("1"), wide("2"), wide("3")], [wide("4"), wide("5"), wide("6")], [wide("7"), wide("8"), wide("9")], lastRow,504        ])505    }506}507508/// Long-press alternates of letters, ordered for the active language.509public enum Accents {510    static let base: [String: [String]] = [511        "a": ["à", "â", "æ", "á", "ä", "ã", "å", "ā"],512        "c": ["ç", "ć", "č"],513        "e": ["é", "è", "ê", "ë", "ē", "ė", "ę"],514        "i": ["î", "ï", "í", "ì", "ī"],515        "n": ["ñ", "ń"],516        "o": ["ô", "œ", "ó", "ö", "ò", "õ", "ø", "ō", "º"],517        "u": ["û", "ù", "ü", "ú", "ū"],518        "y": ["ÿ", "ý"],519        "s": ["ß", "ś", "š"],520        "l": ["ł"],521        "z": ["ž", "ź", "ż"],522        "é": ["è", "ê", "ë", "e"],523        "ñ": ["n"],524        "'": ["’", "‘", "\"", "«", "»"],525    ]526527    static let spanishFirst: [String: [String]] = [528        "a": ["á"], "e": ["é"], "i": ["í"], "o": ["ó"], "u": ["ú", "ü"], "n": ["ñ"],529    ]530531    public static func alternates(for letter: String, language: KeyboardLanguage) -> [String] {532        guard var list = base[letter] else { return [] }533        if language == .spanish, let preferred = spanishFirst[letter] {534            list = preferred + list.filter { !preferred.contains($0) }535        }536        return list537    }538}539
Files main
Menu

Theme