SPB Git

Repository Public

KeyboardViewController.swift 11.9 KB 288 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Keyboard9// File             : KeyboardExtension/KeyboardViewController.swift10// Description      : The keyboard extension's principal class. Adapts11//                    UITextDocumentProxy and the host field's traits to the12//                    shared controller, sizes the input view, and measures its13//                    own appearance time.14// Module           : KeyboardExtension15// 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 UIKit92import KeyboardCore9394/// Adapter over the system text proxy. Resolved on every access: the proxy object can change between fields.95@MainActor96final class SystemTextProxy: TextDocumentProxying {97    private weak var controller: UIInputViewController?9899    init(controller: UIInputViewController) { self.controller = controller }100101    private var proxy: UITextDocumentProxy? { controller?.textDocumentProxy }102    var contextBefore: String? { proxy?.documentContextBeforeInput }103    var contextAfter: String? { proxy?.documentContextAfterInput }104    var selectedText: String? { proxy?.selectedText }105    var hasText: Bool { proxy?.hasText ?? false }106    func insertText(_ text: String) { proxy?.insertText(text) }107    func deleteBackward() { proxy?.deleteBackward() }108    func adjustTextPosition(byCharacterOffset offset: Int) { proxy?.adjustTextPosition(byCharacterOffset: offset) }109}110111/// Process-wide flag: the first appearance of a freshly launched extension process is the cold one.112@MainActor113private enum ProcessState {114    static var hasAppeared = false115}116117final class KeyboardViewController: UIInputViewController, KeyboardHost {118    private var controller: KeyboardController?119    private lazy var proxyAdapter = SystemTextProxy(controller: self)120    private var heightConstraint: NSLayoutConstraint?121    private var appearanceStart: CFTimeInterval = 0122    private var coldMs: Double?123    private var warmMs: Double?124    private var keysSinceReport = 0125126    // MARK: KeyboardHost127128    var textProxy: TextDocumentProxying { proxyAdapter }129    var needsGlobeKey: Bool { needsInputModeSwitchKey }130    var documentIdentifier: String { textDocumentProxy.documentIdentifier.uuidString }131132    var inputTraits: InputTraits {133        let proxy = textDocumentProxy134        var traits = InputTraits()135        switch proxy.keyboardType ?? .default {136        case .URL: traits.variant = .url137        case .emailAddress: traits.variant = .email138        case .webSearch: traits.variant = .webSearch139        case .numberPad, .asciiCapableNumberPad: traits.variant = .numberPad140        case .decimalPad: traits.variant = .decimalPad141        case .phonePad, .namePhonePad: traits.variant = .phonePad142        case .numbersAndPunctuation: traits.variant = .numbersAndPunctuation143        default: traits.variant = .standard144        }145        switch proxy.returnKeyType ?? .default {146        case .go: traits.returnKey = .go147        case .search, .google, .yahoo: traits.returnKey = .search148        case .send: traits.returnKey = .send149        case .done: traits.returnKey = .done150        case .next: traits.returnKey = .next151        case .join: traits.returnKey = .join152        case .route: traits.returnKey = .route153        case .continue: traits.returnKey = .continue154        case .emergencyCall: traits.returnKey = .emergencyCall155        default: traits.returnKey = .default156        }157        switch proxy.autocapitalizationType ?? .sentences {158        case .none: traits.autocapitalization = .none159        case .words: traits.autocapitalization = .words160        case .allCharacters: traits.autocapitalization = .allCharacters161        default: traits.autocapitalization = .sentences162        }163        traits.allowsAutocorrection = proxy.autocorrectionType != .no164        traits.allowsSmartPunctuation = proxy.smartQuotesType != .no165        traits.enablesReturnKeyAutomatically = proxy.enablesReturnKeyAutomatically ?? false166        return traits167    }168169    func keyboardHeightDidChange(_ height: CGFloat) {170        guard isViewLoaded else { return }171        if let heightConstraint {172            heightConstraint.constant = height173        } else {174            let constraint = view.heightAnchor.constraint(equalToConstant: height)175            constraint.priority = UILayoutPriority(999)176            constraint.isActive = true177            heightConstraint = constraint178        }179    }180181    // MARK: Lifecycle182183    override func viewDidLoad() {184        super.viewDidLoad()185        appearanceStart = CACurrentMediaTime()186        let controller = KeyboardController(host: self, environment: .live(bundle: .main))187        self.controller = controller188        let root = controller.rootView189        root.translatesAutoresizingMaskIntoConstraints = false190        view.addSubview(root)191        NSLayoutConstraint.activate([192            root.leadingAnchor.constraint(equalTo: view.leadingAnchor),193            root.trailingAnchor.constraint(equalTo: view.trailingAnchor),194            root.topAnchor.constraint(equalTo: view.topAnchor),195            root.bottomAnchor.constraint(equalTo: view.bottomAnchor),196        ])197        controller.reloadConfigurationIfNeeded(force: true)198        // Key latency is reported every few dozen keys, after the key has been handled.199        controller.onKeyHandled = { [weak self] _ in200            guard let self else { return }201            self.keysSinceReport += 1202            guard self.keysSinceReport >= 30 else { return }203            self.keysSinceReport = 0204            DispatchQueue.main.async { [weak self] in205                guard let self else { return }206                self.controller?.saveMetrics(coldMs: self.coldMs, warmMs: self.warmMs)207            }208        }209        keyboardHeightDidChange(controller.preferredHeight)210        requestSystemLexicon()211    }212213    /// Text replacements defined in Settings. Loaded once, off the typing path.214    private func requestSystemLexicon() {215        Task { [weak self] in216            guard let lexicon = await self?.requestSupplementaryLexicon() else { return }217            var pairs: [String: String] = [:]218            for entry in lexicon.entries.prefix(500) where entry.userInput != entry.documentText {219                pairs[entry.userInput.lowercased()] = entry.documentText220            }221            self?.controller?.setSystemLexicon(pairs)222        }223    }224225    override func viewWillAppear(_ animated: Bool) {226        super.viewWillAppear(animated)227        if appearanceStart == 0 { appearanceStart = CACurrentMediaTime() }228        controller?.viewWillAppear()229    }230231    override func viewDidAppear(_ animated: Bool) {232        super.viewDidAppear(animated)233        let elapsed = (CACurrentMediaTime() - appearanceStart) * 1000234        if ProcessState.hasAppeared { warmMs = elapsed } else { coldMs = elapsed }235        ProcessState.hasAppeared = true236        appearanceStart = 0237        // Reported right away, off the appearance path: the process can be killed without ever being told238        // that its view disappeared (seen in the simulator when the host app quits).239        DispatchQueue.main.async { [weak self] in240            guard let self else { return }241            self.controller?.saveMetrics(coldMs: self.coldMs, warmMs: self.warmMs)242        }243    }244245    override func viewWillDisappear(_ animated: Bool) {246        super.viewWillDisappear(animated)247        controller?.saveMetrics(coldMs: coldMs, warmMs: warmMs)248    }249250    override func viewDidDisappear(_ animated: Bool) {251        super.viewDidDisappear(animated)252        controller?.viewDidDisappear()253    }254255    override func viewDidLayoutSubviews() {256        super.viewDidLayoutSubviews()257        let size = view.bounds.size258        // The keyboard is always wider than tall, so its own bounds say nothing about orientation: use the259        // screen when the scene exposes it, otherwise the size class (compact height = iPhone in landscape).260        let isLandscape: Bool261        if let screen = view.window?.windowScene?.screen.bounds.size {262            isLandscape = screen.width > screen.height263        } else {264            isLandscape = traitCollection.verticalSizeClass == .compact265        }266        controller?.viewDidLayout(size: size, isLandscape: isLandscape)267    }268269    override func textWillChange(_ textInput: UITextInput?) {270        super.textWillChange(textInput)271    }272273    override func textDidChange(_ textInput: UITextInput?) {274        super.textDidChange(textInput)275        controller?.textDidChange()276    }277278    override func selectionDidChange(_ textInput: UITextInput?) {279        super.selectionDidChange(textInput)280        controller?.textDidChange()281    }282283    override func didReceiveMemoryWarning() {284        super.didReceiveMemoryWarning()285        controller?.didReceiveMemoryWarning()286    }287}288
Files main
Menu

Theme