SPB Git

Repository Public

KeyboardEngine.swift 26.0 KB 630 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Keyboard9// File             : Shared/Sources/KeyboardCore/KeyboardEngine.swift10// Description      : Deterministic typing engine: shift and caps lock,11//                    automatic capitalisation, grapheme-safe deletion,12//                    double-space period, smart punctuation, suggestion13//                    insertion, autocorrection and its undo, cursor movement,14//                    language and page switching. Every edit goes through the15//                    text proxy.16// Module           : KeyboardCore17// Repository       : https://git.spboucher.ai/sp-keyboard18// Created          : 2026-12-0119// Last Modified    : 2026-12-0120//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author           : Simon-Pierre Boucher26// Position         : Professor of Finance27// Institution      : Université du Québec en Outaouais (UQO)28// Department       : Département des sciences administratives29// Organization     : SP Boucher30//31// Website          : https://spboucher.ai32// Git              : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General          : info@spboucher.ai39// Professional     : contact@spboucher.ai40// Direct           : simon@spboucher.ai41// Research         : research@spboucher.ai42// Development      : dev@spboucher.ai43// Support          : support@spboucher.ai44// Security/Admin   : admin@spboucher.ai45// Notifications    : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification   : Public72// Distribution     : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License          : None specified (no license file in this repository)86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import Foundation94import PredictionCore9596public enum ShiftState: String, Sendable {97    case off, once, locked9899    public var isUppercase: Bool { self != .off }100}101102/// What the caller must do after the engine handled an input.103public struct EngineOutcome: Equatable, Sendable {104    public enum Request: Equatable, Sendable {105        case advanceToNextInputMode106        case openPanel(KeyboardPanel)107    }108109    /// Shift, page or language changed: the key caps must be redrawn.110    public var layoutChanged = false111    public var textChanged = false112    public var request: Request?113    /// A word the user finished typing verbatim that no lexicon knows (for opt-in learning).114    public var unknownWordCommitted: String?115    public var autocorrected = false116    public var restoredOriginal = false117118    public init() {}119}120121@MainActor122public final class KeyboardEngine {123    public private(set) var shift: ShiftState = .off124    public private(set) var page: KeyboardPage = .letters125    public var settings: KeyboardSettings {126        didSet { if !settings.enabledLanguages.contains(language) { language = settings.currentLanguage } }127    }128    public private(set) var language: KeyboardLanguage129    public var traits = InputTraits()130131    /// Latest prediction and the word it was computed for; ignored when the word has changed since.132    private var pending: (word: String, result: PredictionResult)?133    private var undo: AutocorrectionUndo?134    private var autoSpace = false135    private var userLockedShift = false136    private var lastShiftTap = -10.0137    private var lastSpaceTap = -10.0138    /// Words the user restored after an autocorrection: never corrected again in this session.139    private var rejected = Set<String>()140    /// Last text this engine inserted and that has not been deleted or moved away from since. Some hosts141    /// report no context at all in certain states (for instance once the text contains an emoji): when the142    /// field is known to hold text, this keeps the engine from mistaking that silence for a sentence start.143    private var lastInserted: String?144145    /// Text before the cursor right after this engine's last edit. The host reports every change, including146    /// the ones the keyboard just made: when the report matches this, nothing external happened and the147    /// pending undo and automatic space are kept.148    private var ownContext: String?149    /// The word inserted by the last glide, while it is still the last thing in the field.150    private var glide: GlideInsertion?151152    private struct GlideInsertion {153        var lead: String154        var word: String155        var inserted: String { lead + word + " " }156    }157158    private struct AutocorrectionUndo {159        var original: String160        var replacement: String161        var separator: String162    }163164    public static let doubleTapInterval = 0.35165    public static let doubleSpaceInterval = 0.8166167    public init(settings: KeyboardSettings = KeyboardSettings()) {168        self.settings = settings169        self.language = settings.currentLanguage170    }171172    // MARK: Layout173174    public func layoutRequest(showsGlobe: Bool, hasText: Bool = true) -> LayoutRequest {175        LayoutRequest(language: language, page: page, variant: traits.variant, uppercase: shift.isUppercase, showsGlobe: showsGlobe,176                      showsLanguageKey: settings.enabledLanguages.count > 1, returnKey: traits.returnKey,177                      numberRow: settings.numberRow, numberHints: settings.numberHints,178                      returnEnabled: hasText || !traits.enablesReturnKeyAutomatically)179    }180181    // MARK: Prediction hand-off182183    public func setPrediction(_ result: PredictionResult, forWord word: String) {184        pending = (word, result)185    }186187    public func clearPrediction() { pending = nil }188189    /// The autocorrection that a separator would apply right now, if any (shown highlighted in the bar).190    public func pendingAutocorrection(proxy: TextDocumentProxying) -> Suggestion? {191        let word = TextAnalysis.currentWord(in: proxy.contextBefore)192        return eligibleAutocorrection(for: word)193    }194195    private func eligibleAutocorrection(for word: String) -> Suggestion? {196        guard settings.autocorrection, traits.allowsAutocorrection, traits.isProse, page == .letters, !word.isEmpty,197              let pending, pending.word == word, let correction = pending.result.autocorrection,198              !rejected.contains(word), !TextAnalysis.looksLikeMachineToken(word), correction.text != word else { return nil }199        return correction200    }201202    // MARK: Input203204    public func handle(_ action: KeyAction, proxy: TextDocumentProxying, time: TimeInterval) -> EngineOutcome {205        let outcome = handleInput(action, proxy: proxy, time: time)206        if outcome.textChanged { noteOwnEdit(proxy) }207        return outcome208    }209210    private static let ownContextLength = 48211212    private func noteOwnEdit(_ proxy: TextDocumentProxying) {213        ownContext = proxy.contextBefore.map { String($0.suffix(Self.ownContextLength)) }214    }215216    private func handleInput(_ action: KeyAction, proxy: TextDocumentProxying, time: TimeInterval) -> EngineOutcome {217        var outcome = EngineOutcome()218        if action != .backspace, action != .shift { glide = nil }219        switch action {220        case .character(let text):221            guard !text.isEmpty else { return outcome }222            insertCharacter(text, proxy: proxy, outcome: &outcome)223        case .space:224            insertSpace(proxy: proxy, time: time, outcome: &outcome)225        case .returnKey:226            commitWord(separator: "\n", proxy: proxy, outcome: &outcome)227            proxy.insertText("\n")228            lastInserted = "\n"229            autoSpace = false230            outcome.textChanged = true231        case .backspace:232            backspace(proxy: proxy, outcome: &outcome)233        case .shift:234            tapShift(time: time)235            outcome.layoutChanged = true236            return outcome237        case .page(let target):238            page = target239            outcome.layoutChanged = true240            return outcome241        case .nextLanguage:242            switchLanguage(to: settings.nextLanguage(after: language))243            outcome.layoutChanged = true244            return outcome245        case .globe:246            outcome.request = .advanceToNextInputMode247            return outcome248        case .panel(let panel):249            outcome.request = .openPanel(panel)250            return outcome251        }252        if refreshShift(proxy: proxy) { outcome.layoutChanged = true }253        return outcome254    }255256    public func switchLanguage(to target: KeyboardLanguage) {257        guard settings.enabledLanguages.contains(target) else { return }258        language = target259        settings.currentLanguage = target260        pending = nil261        undo = nil262    }263264    public func showPage(_ target: KeyboardPage) { page = target }265266    private func insertCharacter(_ raw: String, proxy: TextDocumentProxying, outcome: inout EngineOutcome) {267        var text = raw268        let isSingle = raw.count == 1269        let first = raw.first!270        let isWordPart = isSingle && TextAnalysis.isWordCharacter(first)271        if isSingle, !isWordPart {272            // Punctuation right after an auto-inserted space takes the place of that space.273            if autoSpace, ".,;:!?)".contains(first), proxy.contextBefore?.hasSuffix(" ") == true {274                deleteCharacters(1, proxy: proxy)275            } else {276                commitWord(separator: raw, proxy: proxy, outcome: &outcome)277            }278            text = smartPunctuation(first, before: proxy.contextBefore)279        } else if isSingle, first == "'", settings.smartApostrophe, traits.allowsSmartPunctuation, traits.isProse, page == .letters,280                  proxy.contextBefore?.last?.isLetter == true {281            text = "’"282        }283        proxy.insertText(text)284        lastInserted = text285        autoSpace = false286        undo = nil287        outcome.textChanged = true288        if shift == .once, page == .letters {289            shift = .off290            outcome.layoutChanged = true291        }292        // Like the system keyboard: an apostrophe typed from the numbers page returns to letters.293        if page == .numbers, raw == "'" {294            page = .letters295            outcome.layoutChanged = true296        }297    }298299    private func smartPunctuation(_ character: Character, before: String?) -> String {300        guard settings.smartQuotes, traits.allowsSmartPunctuation, traits.isProse, character == "\"" else { return String(character) }301        let opening = before?.last.map { $0.isWhitespace || "([{«“".contains($0) } ?? true302        if language.lexicon == .french { return opening ? "«\u{00A0}" : "\u{00A0}»" }303        return opening ? "“" : "”"304    }305306    private func insertSpace(proxy: TextDocumentProxying, time: TimeInterval, outcome: inout EngineOutcome) {307        let before = proxy.contextBefore ?? ""308        let isDoubleTap = time - lastSpaceTap <= Self.doubleSpaceInterval309        lastSpaceTap = time310        if settings.doubleSpacePeriod, traits.isProse, isDoubleTap, before.hasSuffix(" "), !before.hasSuffix("  "),311           let previous = before.dropLast().last, previous.isLetter || previous.isNumber || ")\"”»’".contains(previous) {312            deleteCharacters(1, proxy: proxy)313            proxy.insertText(". ")314            lastInserted = ". "315            lastSpaceTap = -10316            autoSpace = false317            undo = nil318            outcome.textChanged = true319            return320        }321        commitWord(separator: " ", proxy: proxy, outcome: &outcome)322        proxy.insertText(" ")323        lastInserted = " "324        autoSpace = false325        outcome.textChanged = true326        if page == .numbers || page == .symbols {327            page = .letters328            outcome.layoutChanged = true329        }330    }331332    /// Called just before a separator is inserted: applies the pending autocorrection or reports an unknown word.333    private func commitWord(separator: String, proxy: TextDocumentProxying, outcome: inout EngineOutcome) {334        undo = nil335        let word = TextAnalysis.currentWord(in: proxy.contextBefore)336        guard !word.isEmpty else { return }337        if let correction = eligibleAutocorrection(for: word) {338            deleteCharacters(word.count, proxy: proxy)339            proxy.insertText(correction.text)340            undo = AutocorrectionUndo(original: word, replacement: correction.text, separator: separator)341            outcome.autocorrected = true342        } else if let pending, pending.word == word, page == .letters, !TextAnalysis.looksLikeMachineToken(word),343                  pending.result.suggestions.contains(where: { $0.kind == .verbatim && $0.text == word }) {344            outcome.unknownWordCommitted = word345        }346        pending = nil347    }348349    private func backspace(proxy: TextDocumentProxying, outcome: inout EngineOutcome) {350        autoSpace = false351        if let glide, proxy.contextBefore?.hasSuffix(glide.inserted) == true, (proxy.selectedText ?? "").isEmpty {352            // First backspace after a glide takes the whole word back.353            deleteCharacters(glide.inserted.count, proxy: proxy)354            self.glide = nil355            undo = nil356            outcome.textChanged = true357            return358        }359        glide = nil360        if let undo, let before = proxy.contextBefore, before.hasSuffix(undo.replacement + undo.separator), proxy.selectedText == nil {361            // First backspace after an autocorrection gives the typed word back.362            deleteCharacters((undo.replacement + undo.separator).count, proxy: proxy)363            proxy.insertText(undo.original)364            rejected.insert(undo.original)365            self.undo = nil366            outcome.textChanged = true367            outcome.restoredOriginal = true368            return369        }370        undo = nil371        deleteCharacters(1, proxy: proxy)372        outcome.textChanged = true373    }374375    /// Continuous delete, one step. `.word` removes the previous word and its trailing spaces.376    public func deleteStep(_ granularity: DeleteAcceleration.Granularity, proxy: TextDocumentProxying) -> EngineOutcome {377        var outcome = EngineOutcome()378        undo = nil379        autoSpace = false380        glide = nil381        defer { noteOwnEdit(proxy) }382        let count = granularity == .word ? max(1, TextAnalysis.wordDeletionCount(in: proxy.contextBefore)) : 1383        deleteCharacters(count, proxy: proxy)384        outcome.textChanged = true385        if refreshShift(proxy: proxy) { outcome.layoutChanged = true }386        return outcome387    }388389    /// Deletes `count` user-perceived characters. Hosts normally remove a whole grapheme per `deleteBackward`;390    /// when one removes only part of it (the character count did not drop), the call is repeated, bounded.391    private func deleteCharacters(_ count: Int, proxy: TextDocumentProxying) {392        guard count > 0 else { return }393        lastInserted = nil394        if proxy.selectedText?.isEmpty == false {395            proxy.deleteBackward()396            return397        }398        for _ in 0..<count {399            guard let before = proxy.contextBefore, let last = before.last else {400                proxy.deleteBackward()401                continue402            }403            let target = before.count - 1404            var guardCount = last.unicodeScalars.count405            repeat {406                proxy.deleteBackward()407                guardCount -= 1408            } while guardCount > 0 && (proxy.contextBefore?.count ?? 0) > target409        }410    }411412    // MARK: Suggestions413414    /// Replaces the word being typed with `suggestion` (or appends a next-word prediction).415    public func apply(_ suggestion: Suggestion, proxy: TextDocumentProxying) -> EngineOutcome {416        var outcome = EngineOutcome()417        glide = nil418        defer { noteOwnEdit(proxy) }419        let word = TextAnalysis.currentWord(in: proxy.contextBefore)420        if suggestion.kind == .verbatim {421            // Tapping the quoted word keeps it as typed and stops correcting it.422            rejected.insert(word)423            proxy.insertText(" ")424        } else {425            if !word.isEmpty { deleteCharacters(word.count, proxy: proxy) }426            let needsSpace = suggestion.kind != .shortcut || !suggestion.text.contains("\n")427            proxy.insertText(suggestion.text + (needsSpace ? " " : ""))428        }429        lastInserted = needsTrailingContext(suggestion)430        autoSpace = true431        undo = nil432        pending = nil433        outcome.textChanged = true434        if refreshShift(proxy: proxy) { outcome.layoutChanged = true }435        return outcome436    }437438    private func needsTrailingContext(_ suggestion: Suggestion) -> String {439        suggestion.kind == .verbatim ? " " : suggestion.text + " "440    }441442    /// Inserts free text chosen by an explicit action (emoji, snippet, AI result).443    public func insertVerbatim(_ text: String, proxy: TextDocumentProxying) -> EngineOutcome {444        var outcome = EngineOutcome()445        guard !text.isEmpty else { return outcome }446        glide = nil447        defer { noteOwnEdit(proxy) }448        proxy.insertText(text)449        lastInserted = text450        autoSpace = false451        undo = nil452        pending = nil453        outcome.textChanged = true454        if refreshShift(proxy: proxy) { outcome.layoutChanged = true }455        return outcome456    }457458    /// Replaces the `count` characters immediately before the cursor with `text` (SP AI "Replace").459    /// The caller has already verified that those characters are the expected source; this re-checks the460    /// length that actually disappeared and refuses to insert if the deletion did not go as planned.461    public func replaceBeforeCursor(count: Int, with text: String, proxy: TextDocumentProxying) -> Bool {462        guard count > 0, let before = proxy.contextBefore, before.count >= count, proxy.selectedText == nil else { return false }463        let expected = before.count - count464        deleteCharacters(count, proxy: proxy)465        guard (proxy.contextBefore?.count ?? 0) == expected else { return false }466        proxy.insertText(text)467        undo = nil468        autoSpace = false469        pending = nil470        glide = nil471        refreshShift(proxy: proxy)472        noteOwnEdit(proxy)473        return true474    }475476    // MARK: Glide typing477478    /// Inserts a word traced on the keys: spaced from what precedes it, capitalised like a typed word, followed479    /// by an automatic space that the next punctuation mark takes back.480    public func insertGlide(_ word: String, proxy: TextDocumentProxying) -> EngineOutcome {481        var outcome = EngineOutcome()482        guard !word.isEmpty else { return outcome }483        undo = nil484        pending = nil485        let before = proxy.contextBefore ?? ""486        var lead = ""487        if let last = before.last, !last.isWhitespace, !"([{«“\"'’‘-/@#".contains(last) { lead = " " }488        var text = word489        let startsSentence = !lead.isEmpty && automaticShift(for: before + lead) == .once490        if shift == .locked {491            text = word.uppercased(with: language.locale)492        } else if shift == .once || startsSentence {493            text = word.prefix(1).uppercased(with: language.locale) + word.dropFirst()494        }495        let insertion = GlideInsertion(lead: lead, word: text)496        proxy.insertText(insertion.inserted)497        glide = insertion498        lastInserted = insertion.inserted499        autoSpace = true500        outcome.textChanged = true501        if refreshShift(proxy: proxy) { outcome.layoutChanged = true }502        noteOwnEdit(proxy)503        return outcome504    }505506    /// True while the last glided word can still be swapped for another candidate.507    public func canReplaceGlide(proxy: TextDocumentProxying) -> Bool {508        guard let glide else { return false }509        return proxy.contextBefore?.hasSuffix(glide.inserted) == true && (proxy.selectedText ?? "").isEmpty510    }511512    /// Swaps the last glided word for `word` (an alternative picked in the suggestion bar).513    public func replaceGlide(with word: String, proxy: TextDocumentProxying) -> EngineOutcome {514        var outcome = EngineOutcome()515        guard let current = glide, canReplaceGlide(proxy: proxy), !word.isEmpty else { return outcome }516        var text = word517        let wasUpper = current.word.count > 1 && current.word == current.word.uppercased(with: language.locale)518            && current.word != current.word.lowercased(with: language.locale)519        if wasUpper {520            text = word.uppercased(with: language.locale)521        } else if let first = current.word.first, first.isUppercase {522            text = word.prefix(1).uppercased(with: language.locale) + word.dropFirst()523        }524        deleteCharacters((current.word + " ").count, proxy: proxy)525        proxy.insertText(text + " ")526        let insertion = GlideInsertion(lead: current.lead, word: text)527        glide = insertion528        lastInserted = insertion.inserted529        autoSpace = true530        outcome.textChanged = true531        if refreshShift(proxy: proxy) { outcome.layoutChanged = true }532        noteOwnEdit(proxy)533        return outcome534    }535536    // MARK: Cursor537538    /// Moves the cursor by `steps` user-perceived characters (negative = left), using what the proxy exposes.539    public func moveCursor(by steps: Int, proxy: TextDocumentProxying) {540        guard steps != 0 else { return }541        undo = nil542        autoSpace = false543        glide = nil544        ownContext = nil545        lastInserted = nil546        var offset = 0547        if steps < 0 {548            guard let before = proxy.contextBefore else { return }549            offset = -before.suffix(-steps).utf16.count550        } else {551            guard let after = proxy.contextAfter else { return }552            offset = after.prefix(steps).utf16.count553        }554        if offset != 0 { proxy.adjustTextPosition(byCharacterOffset: offset) }555    }556557    // MARK: Shift558559    private func tapShift(time: TimeInterval) {560        let isDoubleTap = time - lastShiftTap <= Self.doubleTapInterval561        lastShiftTap = time562        switch shift {563        case .locked:564            shift = .off565            userLockedShift = false566            lastShiftTap = -10567        case .once where isDoubleTap, .off where isDoubleTap:568            shift = .locked569            userLockedShift = true570        case .once:571            shift = .off572        case .off:573            shift = .once574        }575    }576577    public func automaticShift(for before: String?, hasText: Bool = false) -> ShiftState {578        guard settings.autoCapitalization, traits.isProse else { return .off }579        var before = before580        if (before ?? "").isEmpty, hasText, let lastInserted { before = lastInserted }581        switch traits.autocapitalization {582        case .none: return .off583        case .allCharacters: return .locked584        case .words: return TextAnalysis.isWordStart(before) ? .once : .off585        case .sentences: return TextAnalysis.isSentenceStart(before) ? .once : .off586        }587    }588589    /// Recomputes the automatic shift from the context. Returns true when the shift state changed.590    @discardableResult591    public func refreshShift(proxy: TextDocumentProxying) -> Bool {592        guard !userLockedShift else { return false }593        let target = automaticShift(for: proxy.contextBefore, hasText: proxy.hasText)594        guard target != shift else { return false }595        shift = target596        return true597    }598599    /// The host field or its content changed under us (focus change, paste, cursor moved by the user).600    @discardableResult601    public func contextDidChange(proxy: TextDocumentProxying) -> Bool {602        if let ownContext, (proxy.selectedText ?? "").isEmpty,603           proxy.contextBefore.map({ String($0.suffix(Self.ownContextLength)) }) == ownContext {604            // The host is echoing this engine's own edit.605            return refreshShift(proxy: proxy)606        }607        ownContext = nil608        glide = nil609        undo = nil610        autoSpace = false611        if !proxy.hasText { lastInserted = nil }612        return refreshShift(proxy: proxy)613    }614615    /// A new field got focus.616    public func resetForNewField() {617        page = .letters618        userLockedShift = false619        shift = .off620        lastInserted = nil621        undo = nil622        pending = nil623        autoSpace = false624        glide = nil625        ownContext = nil626        lastShiftTap = -10627        lastSpaceTap = -10628    }629}630
Files main
Menu

Theme