hex/ios/HEXKeyboard/KeyboardViewController.swift
Ryan Vogel 3302fb4c0b
iOS: Adaptive touch, personal key centres learned on device (Experiment, off by default) (#2146)
* iOS keyboard: Adaptive touch learns personal key centres for the decoder (Experiments, off)

Adds Adaptive touch, stages 1 and 2 of the adaptive-touch design: the keyboard learns
where you land on each physical letter key, on this device, and Spatial autocorrect's
decoder (TypingDecoder.Keys) and the suggestion strip read your taps with those
personal centres. Hit rectangles, keycaps, key(at:) and Swipe typing are unchanged.

- AdaptiveTouch.swift: fixed-size sums (4 rotating bins of 200 labelled taps) per
  physical key and context (letters, posture, orientation, split, Hex key side,
  width bin, plus one of two grip regimes); offsets in keycaps, hierarchically
  shrunk (key 20, row 50, keyboard 40), bounded to 0.3 keycap, 0.05 per promotion,
  fixed sigma. The decoder reads a context only after 400 labelled taps over 3
  sessions, while the profile fits recent taps better than the stock centres; once it
  fits worse it falls back to stock at once and labels go to the other regime (a
  returning grip is taken back). The model serializes to 23,588 bytes: a protected
  file in the keyboard's own container, excluded from backup, never in the App
  Group, written off the main thread; without Full Access, memory only. Reset
  generation in the App Group drops RAM and file, and stale writes can't resurrect.
- AdaptiveTouchLabels.swift: RAM-only spans. A tap teaches only with evidence of
  intent, and only once the next word shows its word stood: a word left as typed
  (only letters the key under the finger typed), a same-length picked suggestion,
  a word kept over an autocorrection (undo or tapping it), and an erased letter
  retyped as a neighbour. Never autocorrections left in place, swipes, slides,
  strip touches, accent picks, or secure, code, email, URL or no-autocorrect fields.
- No new automatic rewrites: AutocorrectEngine.decoderStockKeys; space applies a
  personal reading only if the stock centres also clear it by the margin
  (TypingDecoder.replaces), else the stock decision. Experiment on replaces Learn how
  I type's per-letter offsets for decoding (its word-level learning stays). Off, the
  engine has no AdaptiveTouch and behaves exactly as before.
- Hooks: FullKeyboardEngine (touch-down point, letter commit, delete, undo, word
  ends, picks, swipes, cursor, field), FullKeyboardView.syncSettings, the keyboard
  saving on hide. KeyboardTextTarget gains isSecureTextEntry.

Verified: xcodebuild test on an iPhone 17 simulator (iOS 27.2), 440 tests, 0
failures (1 skipped, existing); new cases in FullKeyboardEngineTests and
AutocorrectEngineTests cover label admission, excluded fields and swipes, no
hit-rectangle change, contexts, grip fallback, evidence floor, untrained equals off,
the file cap, backup exclusion, damage and reset, and the no-new-rewrite guard.

* iOS: Settings › Experiments › Adaptive touch, with its status and Reset touch learning

The switch (off by default, App Group key experiments.adaptiveTouch) reads "Learns
where you land on the keys on this device. Stores averages, not what you type." While
on, a status line says Session only (Full Access not confirmed: the keyboard keeps its
averages in memory until it closes), Learning: n of 400 taps, or Active, from the
counts the keyboard reports (adaptiveTouch.summary.*); and Reset touch learning,
after a confirmation, bumps the reset generation every keyboard honours. Delete what
Hex learned (Typing insights) resets it too. Strings have zh-Hans. The
settings-experiments-on fixture shows it on, partway through learning.

Verified: built and tested with the previous commit (440 tests, 0 failures).

* iOS keyboard: Adaptive touch's guard follows the Experiment-off decoder, and its grip check reads each axis

Three refinements found while replaying the public benchmark:

- No new automatic rewrites now means none the keyboard wouldn't make with the
  Experiment off: AutocorrectEngine.decoderStockKeys becomes decoderBaselineKeys,
  the centres Spatial autocorrect reads without Adaptive touch (stock, or moved by
  Learn how I type's per-letter offsets). Those offsets still never move the
  centres the decoder reads while the Experiment is on (no stacking), so journal
  users keep its correction authority as the ceiling. Before, the baseline was
  always the stock centres, which let a journal user's rewrites change on enabling.
- The fit monitor keeps separate x and y log-likelihood gains. A grip that shifts
  taps sideways while the learned up/down offsets still fit used to average out:
  in the right-to-left grip replay the profile flapped in and out ~80 times and kept
  breaking words. Now a profile falls back once either axis fits worse than the
  stock centres (-0.06 nats per tap over 32 labels) and is only taken back when
  neither axis misfits.
- TypingDecoder.replaces first scores the reading letter for letter (or with one
  untyped letter), an alignment the search also tries, and skips the one-word
  search when that already clears the margin: the guard runs on most letters.

Verified: xcodebuild test on the iPhone 17 simulator (iOS 27.2), 446 tests, 0
failures (1 skipped, existing), including a new case for the journal baseline.

* iOS keyboard: Adaptive touch switches grip profiles only once one had the evidence to be used

The public replay showed a false switch while learning the steady base typist: the
early, thin profile (368 taps) misfit one axis by noise and labels moved to a fresh
second profile, throwing that evidence away. Before the activation floor nothing
is in use, so a new grip now just mixes into what is learned; the per-axis
fallback and switching apply once the profile is eligible (400 taps, 3 sessions).

Also skips the accent comparison in TypingDecoder.replaces when it can't lower the
margin (it allocates), the guard's remaining per-letter cost on the simulator.

Adds AutocorrectEngineTests.testPersonalCentresKeepNamesYourWordsAndWordsTypedRight:
with every centre pushed to the bound, words typed right, lowercase names and days,
Contacts-style terms and shorthand come out exactly as with the Experiment off.

Verified: xcodebuild test on the iPhone 17 simulator (iOS 27.2), rebased on
d65f5f76: 452 tests, 0 failures (1 skipped, existing).

* iOS keyboard: test that Adaptive touch never joins words its own way

Rebased onto the autocorrect fixes (#2144). Their new automatic rewrites go
through finishWord, so Adaptive touch hooks in there: a word space or a closing
mark autocorrects teaches nothing, a revised word before it ("well" to "we'll")
teaches nothing either, and two words joined at the space bar's edge drop
everything pending. AutocorrectEngine.merge reads the centres the keyboard reads
without Adaptive touch, so personal centres never decide a join (folded into the
first two commits while resolving the rebase).

Adds AutocorrectEngineTests.testPersonalCentresNeverJoinWordsTheirOwnWay: with a
strong personal profile in use, "the deli" + a space at the bar's edge + "ate"
still becomes "the delicate", as with the Experiment off.

Verified: xcodebuild test on the iPhone 17 simulator (iOS 27.2) on 8c93f6f5: 461
tests, 0 failures (1 skipped, existing).

* iOS keyboard: Adaptive touch's guard takes the next reading the baseline clears, not a second search

When a personal reading doesn't clear the baseline margin, the guard used to run a
whole second decode with the baseline centres to find their own decision. On the
public benchmark that happened on ~5% of checked letters and cost ~0.13 ms each,
pushing the simulator's English per-letter p95 up to +0.1-0.16 ms. Now it takes the
next of the personal readings that the baseline centres also clear by the margin
(TypingDecoder.replaces, mostly without a search), or none: still never a rewrite
the keyboard wouldn't make with the Experiment off. Only a two-word reading, which
replaces can't score, still asks the baseline decode.

Verified: xcodebuild test on the iPhone 17 simulator (iOS 27.2) on 8c93f6f5: 461
tests, 0 failures (1 skipped, existing). Held-out benchmark on the same simulator,
profile learned on the 300 dev sentences: WER unchanged by this (EN 5.24% -> 5.16%,
ES 8.34% -> 8.26%); per-letter engine p95 against Experiment off, two runs each:
EN -0.09 / +0.02 ms, ES -0.01 / +0.04 ms; peak footprint -0.11 / +0.00 MB.

* iOS: README documents Adaptive touch and what verified it

Adds Settings › Experiments › Adaptive touch to the capabilities (what it learns
from, what it keeps and where, when the decoder uses it, the no-new-rewrite guard)
and to the Experiments page list, and a verification entry: the unit tests, the
held-out benchmark on the simulator (Experiment off and on without evidence match the
keyboard without it on all 2,000 items in English and Spanish; with a learned profile
EN 5.24% -> 5.16%, ES 8.34% -> 8.26% WER, none typed right broken), the grip-change
replay (38 broken words without the fallback, none with it), latency and footprint, and
what remains unverified without a physical iPhone.

Verified: the numbers are from this branch at 17af3357 on 8c93f6f5 (replay tables in
the experiment folder, not committed).
2026-11-21 06:13:04 +00:00

899 lines
40 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import AVFoundation
import SwiftUI
import UIKit
@MainActor
final class KeyboardViewController: UIInputViewController {
private let bridge = KeyboardBridge()
private let viewModel = KeyboardViewModel()
private let localDictation = KeyboardLocalDictation()
private var pollTimer: Timer?
private var coldStartJobID = UUID().uuidString
private var lastURLRefreshBucket: Int = 0
private var lastFullAccessNote: TimeInterval = 0
private var surface: UIView?
private var fullKeyboard: FullKeyboardView?
private var heightConstraint: NSLayoutConstraint?
/// Opaque, under the surface: nothing iOS leaves behind the keyboard shows through it.
private let backdrop = KeyboardBackdropView()
private var pollInterval: TimeInterval = 0
private var didHandOffCurrentField = false
private var didWarmLexicon = false
/// Learn how I type: what becomes of each dictation Hex inserts.
private let dictationEdits = DictationEditTracker()
private lazy var documentTarget = DocumentProxyTextTarget { [weak self] in self?.textDocumentProxy }
/// Record typing logs: the process's logger while the experiment is on.
private var typingLog: TypingLogger?
/// The field the current typing log session is for.
private var typingLogTraits: TypingLogTraits?
/// Follows dictations for typing logs' outcomes, apart from Learn how I type's tracker.
private let logDictationEdits = DictationEditTracker()
private var pendingHostContext: DispatchWorkItem?
private var isShown = false
/// The dictation bar's key haptic; the full keyboard has its own generator.
private lazy var barHaptics = UIImpactFeedbackGenerator(style: .light)
/// The Hex key's last touch-down (wall clock), where a start's probe timeline begins.
private var hexKeyPressedAt: TimeInterval?
private var warmStartTimeline: WarmStartTimeline?
/// Haptics need Full Access, and Settings › Keyboard › Haptics covers both keyboards.
private var allowsKeyHaptics: Bool {
hasFullAccess && FullKeyboardSettings().haptics
}
override func viewDidLoad() {
super.viewDidLoad()
// Keyboard dictation sets this process's audio session to record (WebKit captures for
// it), and iOS mutes a recording session's haptics by default: keep key haptics on.
try? AVAudioSession.sharedInstance().setAllowHapticsAndSystemSoundsDuringRecording(true)
configureView()
syncFromBridge(animated: false)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
coldStartJobID = UUID().uuidString
didHandOffCurrentField = false
// The keyboard may come back for another field: settle on where the dictation was last seen.
dictationEdits.finish(nil)
mountSurface()
fullKeyboard?.prepareForField()
isShown = true
beginTypingLogSession(trigger: "appear")
handOffNumericPadIfNeeded()
syncFromBridge(animated: false)
schedulePoll(force: true)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// iOS holds back touches near the screen's side edges in a keyboard's window while it
// waits to see whether they start a system gesture: on an iPhone they reached the keys
// about 80 ms late (Record typing logs), so q, a, p, l, shift and delete lagged and
// could land after the next key. Apple's own keyboard has no such delay.
view.window?.gestureRecognizers?.forEach { $0.delaysTouchesBegan = false }
warmFullKeyboardLexiconIfNeeded()
listDictationLanguagesIfNeeded()
prepareLocalDictationIfNeeded()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if dictationEdits.isTracking { dictationEdits.finish(editContext) }
TypingJournal.sharedIfEnabled()?.save()
AdaptiveTouch.current?.save()
isShown = false
localDictation.discard(reason: "keyboard hidden")
endTypingLogSession(reason: "disappear", settleDictation: editContext)
pollTimer?.invalidate()
pollTimer = nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
fullKeyboard?.handleMemoryWarning()
typingLog?.flush()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if let fullKeyboard { applyHeight(fullKeyboard.preferredHeight) }
}
/// The keyboard's height. Set once before the first layout (the surface's own height), then
/// only when the surface asks for another (the emoji search's row), and never animated:
/// iOS sizes the panel from it while it swaps keyboards.
private func applyHeight(_ height: CGFloat) {
guard let heightConstraint else {
let constraint = view.heightAnchor.constraint(equalToConstant: height)
constraint.priority = UILayoutPriority(999)
constraint.isActive = true
heightConstraint = constraint
preferredContentSize.height = height
return
}
guard heightConstraint.constant != height else { return }
UIView.performWithoutAnimation {
heightConstraint.constant = height
preferredContentSize.height = height
}
}
override func textWillChange(_ textInput: UITextInput?) {
super.textWillChange(textInput)
if KeyboardFieldRouting.route(for: textDocumentProxy.keyboardType) != .handOff {
didHandOffCurrentField = false
}
}
override func textDidChange(_ textInput: UITextInput?) {
super.textDidChange(textInput)
updateKeyboardTraits()
followTypingLogField()
fullKeyboard?.textDidChange()
observeDictationEdits(fromKeys: false)
noteHostTextChange()
handOffNumericPadIfNeeded()
}
// MARK: - Record typing logs
/// Starts a session for the field the keyboard is in, while the experiment is on. A
/// field that must not be logged gets a `skipped` line and nothing else.
private func beginTypingLogSession(trigger: String) {
guard let log = TypingLogger.sharedIfEnabled() else {
typingLog = nil
return
}
typingLog = log
log.contextSource = { [weak self] in
self?.typingLogContext ?? TypingLogContext(before: nil, after: nil, hasText: false)
}
let traits = TypingLogTraits(textDocumentProxy, document: TypingLogTraits.documentIdentifier(of: textDocumentProxy))
typingLogTraits = traits
log.beginSession(typingLogSessionInfo(trigger: trigger, traits: traits))
attachTypingLog()
syncLoggingMark()
}
/// `settleDictation` is the text the last dictation's outcome is judged on (nil: where
/// it was last seen, for a field the keyboard already left).
private func endTypingLogSession(reason: String, settleDictation context: DictationEditTracker.Context?) {
pendingHostContext?.cancel()
pendingHostContext = nil
guard let log = typingLog else { return }
if logDictationEdits.isTracking { logDictationEdits.finish(context) }
fullKeyboard?.typingLog = nil
log.endSession(reason: reason)
typingLogTraits = nil
syncLoggingMark()
}
/// Both keyboards show a small mark the whole time typing logs record this field.
private func syncLoggingMark() {
let logging = typingLog?.isRecording == true
if viewModel.isLoggingTyping != logging {
viewModel.isLoggingTyping = logging
}
}
private func attachTypingLog() {
guard let fullKeyboard else { return }
let log = typingLog?.isRecording == true ? typingLog : nil
guard fullKeyboard.typingLog !== log || log != nil else { return }
fullKeyboard.typingLog = log
fullKeyboard.typingLogSessionBegan()
}
/// Turned on or off while the keyboard is shown.
private func syncTypingLogEnabled() {
let enabled = TypingLogSettings().isEnabled
if enabled, typingLog == nil, isShown {
beginTypingLogSession(trigger: "enabled")
} else if !enabled, typingLog != nil {
endTypingLogSession(reason: "disabled", settleDictation: nil)
typingLog = nil
_ = TypingLogger.sharedIfEnabled()
}
}
/// Another field, or the same field with new traits: a new session (which may be skipped).
private func followTypingLogField() {
guard typingLog != nil, isShown else { return }
let traits = TypingLogTraits(textDocumentProxy, document: TypingLogTraits.documentIdentifier(of: textDocumentProxy))
if let current = typingLogTraits, !current.isOtherField(than: traits) {
// The same field: keep its document once UIKit names it.
if current.document == nil { typingLogTraits?.document = traits.document }
return
}
endTypingLogSession(reason: "field_changed", settleDictation: nil)
beginTypingLogSession(trigger: "field")
}
/// The host changed the text or moved the cursor. Hosts call this in bursts (and some
/// after Hex's own edits), so the context is written once things settle, at once when
/// the field was emptied.
private func noteHostTextChange() {
guard let log = typingLog, log.isRecording else { return }
pendingHostContext?.cancel()
guard textDocumentProxy.hasText else {
pendingHostContext = nil
log.context("text_did_change")
return
}
let work = DispatchWorkItem { [weak self] in
MainActor.assumeIsolated {
self?.pendingHostContext = nil
self?.typingLog?.context("text_did_change")
}
}
pendingHostContext = work
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: work)
}
private var typingLogContext: TypingLogContext {
TypingLogContext(
before: textDocumentProxy.documentContextBeforeInput,
after: textDocumentProxy.documentContextAfterInput,
hasText: textDocumentProxy.hasText
)
}
private func typingLogSessionInfo(trigger: String, traits: TypingLogTraits) -> TypingLogSessionInfo {
let bundle = Bundle.main.infoDictionary
let orientation = fullKeyboard?.orientation ?? FullKeyboardView.orientation(for: traitCollection)
let dark = textDocumentProxy.keyboardAppearance == .dark || traitCollection.userInterfaceStyle == .dark
return TypingLogSessionInfo(
trigger: trigger,
surface: fullKeyboard == nil ? "bar" : "full",
traits: traits,
bounds: view.bounds.size,
safeArea: view.safeAreaInsets,
orientation: orientation == .landscape ? "landscape" : "portrait",
appearance: dark ? "dark" : "light",
device: TypingLogSessionInfo.deviceModel,
system: "\(UIDevice.current.systemName) \(UIDevice.current.systemVersion)",
version: bundle?["CFBundleShortVersionString"] as? String ?? "",
build: bundle?["CFBundleVersion"] as? String ?? "",
locale: Locale.current.identifier,
languages: Array(Locale.preferredLanguages.prefix(4)),
keyboardLanguage: primaryLanguage,
inputMode: textDocumentProxy.documentInputMode?.primaryLanguage,
fullAccess: hasFullAccess,
settings: [
TypingLogField("autocorrect", .bool(FullKeyboardSettings().autocorrect)),
TypingLogField("spatialAutocorrect", .bool(FullKeyboardSettings().spatialAutocorrect)),
TypingLogField("swipeTyping", .bool(FullKeyboardSettings().swipeTyping)),
TypingLogField("emoji", .bool(FullKeyboardSettings().emoji)),
TypingLogField("key_popups", .bool(FullKeyboardSettings().keyPopups)),
TypingLogField("haptics", .bool(FullKeyboardSettings().haptics)),
TypingLogField("learnHowIType", .bool(TypingJournalSettings().isEnabled)),
TypingLogField("cleanupTagger", .bool(CleanupTaggerSettings().isEnabled)),
TypingLogField("hexKeyPlacement", .string(HexKeyPlacement.current.rawValue)),
TypingLogField("keyboardLayout", .string(fullKeyboard?.engine.language.rawValue ?? "")),
TypingLogField("dictationLanguage", .string(LanguageSettings().dictationLanguage ?? "automatic")),
TypingLogField("style", .string(bridge.style.rawValue)),
]
)
}
// MARK: - Learn how I type
/// Dictations are followed only while Learn how I type is on, in plain text fields
/// that allow autocorrect.
private var learnsFromDictation: Bool {
guard TypingJournalSettings().isEnabled,
case .keys(let kind, _) = KeyboardFieldRouting.route(for: textDocumentProxy.keyboardType)
else { return false }
return TypingJournal.allows(field: kind, target: documentTarget)
}
private var editContext: DictationEditTracker.Context {
DictationEditTracker.Context(
before: textDocumentProxy.documentContextBeforeInput,
after: textDocumentProxy.documentContextAfterInput,
hasText: textDocumentProxy.hasText
)
}
private func observeDictationEdits(fromKeys: Bool) {
guard dictationEdits.isTracking || logDictationEdits.isTracking else { return }
let context = editContext
if logDictationEdits.isTracking { logDictationEdits.observe(context, fromKeys: fromKeys) }
if dictationEdits.isTracking { dictationEdits.observe(context, fromKeys: fromKeys) }
}
/// A return key labelled Send ends the dictation's edit window: what is there is sent.
private func returnKeyWillInsert() {
guard textDocumentProxy.returnKeyType == .send else { return }
if logDictationEdits.isTracking { logDictationEdits.finish(editContext) }
guard dictationEdits.isTracking else { return }
dictationEdits.finish(editContext)
}
private func handOffNumericPadIfNeeded() {
guard fullKeyboard != nil else { return }
if KeyboardFieldRouting.route(for: textDocumentProxy.keyboardType) == .handOff {
guard !didHandOffCurrentField else { return }
didHandOffCurrentField = true
if needsInputModeSwitchKey {
advanceToNextInputMode()
}
} else {
didHandOffCurrentField = false
}
}
private func warmFullKeyboardLexiconIfNeeded() {
guard let fullKeyboard else { return }
fullKeyboard.warmUpTextCheckerAsync()
guard !didWarmLexicon else { return }
didWarmLexicon = true
// UIKit calls back on its lexicon-request queue. A main-actor closure here trips
// Swift's runtime isolation check (EXC_BREAKPOINT, TestFlight build 3), so the
// callback is nonisolated and hops to the main actor itself.
requestSupplementaryLexicon { @Sendable [weak self] lexicon in
Task { @MainActor in
self?.fullKeyboard?.loadLexicon(lexicon)
}
}
}
private func configureView() {
guard backdrop.superview == nil else { return }
view.backgroundColor = .clear
backdrop.translatesAutoresizingMaskIntoConstraints = false
view.insertSubview(backdrop, at: 0)
NSLayoutConstraint.activate([
backdrop.leadingAnchor.constraint(equalTo: view.leadingAnchor),
backdrop.trailingAnchor.constraint(equalTo: view.trailingAnchor),
backdrop.topAnchor.constraint(equalTo: view.topAnchor),
backdrop.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
viewModel.inputViewController = self
dictationEdits.onResult = { result in
TypingJournal.sharedIfEnabled()?.recordDictation(result)
}
logDictationEdits.onResult = { [weak self] result in
self?.typingLog?.dictationOutcome(result)
}
localDictation.corrections = {
TypingJournal.sharedIfEnabled()?.dictationCorrections() ?? []
}
viewModel.onDictateTap = { [weak self] in self?.startWarmDictation() }
viewModel.onHexKeyPress = { [weak self] at in self?.hexKeyPressed(at: at) }
viewModel.onHexKeyAbandon = { [weak self] in self?.localDictation.discard() }
viewModel.onKeyFeedback = { [weak self] in
guard let self, self.allowsKeyHaptics else { return }
self.barHaptics.impactOccurred(intensity: 0.65)
self.barHaptics.prepare()
}
viewModel.onStopTap = { [weak self] in
guard let self else { return }
if self.localDictation.isActive {
self.localDictation.stop()
// Loading the cleanup model while recording starts ran older iPhones out of
// keyboard memory, so it loads after the microphone closes.
CleanupTagger.prepareIfEnabled(
style: self.bridge.style,
language: LanguageSettings().effectiveDictationLanguage
)
} else {
self.stopWarmDictation()
}
}
viewModel.onCancelTap = { [weak self] in
guard let self else { return }
if self.localDictation.isActive { self.localDictation.cancel() } else { self.cancelWarmDictation() }
}
syncLocalDictationAvailability(access: dictationAccess(now: Date().timeIntervalSince1970))
viewModel.onStyleSelected = { [weak self] style in
guard let self else { return }
self.bridge.style = style
if self.viewModel.style != style {
self.viewModel.style = style
}
self.refreshColdStartURL(now: Date().timeIntervalSince1970, force: true)
}
viewModel.onLanguageSelected = { [weak self] language in
LanguageSettings().chooseDictationLanguage(language)
self?.languageSignature = nil
self?.syncLanguageState()
}
viewModel.onTranslationToggled = { [weak self] on in
DictationTranslationSettings().isTranslating = on
self?.languageSignature = nil
self?.syncLanguageState()
}
viewModel.onTranslationTargetSelected = { [weak self] target in
let settings = DictationTranslationSettings()
settings.targetLanguage = target
settings.isTranslating = true
self?.languageSignature = nil
self?.syncLanguageState()
}
viewModel.onSpace = { [weak self] in
self?.typingLog?.edit("insert", [
TypingLogField("inserted", .string(" ")),
TypingLogField("src", .string("bar")),
])
self?.textDocumentProxy.insertText(" ")
self?.observeDictationEdits(fromKeys: true)
self?.typingLog?.context("space")
}
viewModel.onDelete = { [weak self] in
if let self, let log = self.typingLog {
let deleted = self.textDocumentProxy.documentContextBeforeInput?.last.map { String($0) }
log.edit("delete", [
deleted.map { TypingLogField("deleted", .string($0)) } ?? TypingLogField("deletedCount", .int(1)),
TypingLogField("src", .string("bar")),
])
}
self?.textDocumentProxy.deleteBackward()
self?.observeDictationEdits(fromKeys: true)
}
viewModel.onReturn = { [weak self] in
if let self {
self.typingLog?.edit("return", [
TypingLogField("inserted", .string("\n")),
TypingLogField("returnKeyType", .string(TypingLogTraits.name(self.textDocumentProxy.returnKeyType ?? .default))),
TypingLogField("send", .bool(self.textDocumentProxy.returnKeyType == .send)),
TypingLogField("src", .string("bar")),
])
}
self?.returnKeyWillInsert()
self?.textDocumentProxy.insertText("\n")
self?.observeDictationEdits(fromKeys: true)
self?.typingLog?.context("return")
}
viewModel.onOpenURL = { [weak self] url in
guard let self else { return }
ContainingAppOpener.open(url, from: self)
}
mountSurface()
}
/// The full keyboard (iPhone only), or the dictation bar once it was chosen. Without Full
/// Access always the full keyboard: the bar types nothing but spaces and line breaks,
/// and its Dictate needs Full Access. Only switches while idle.
private func mountSurface() {
let wantsFull = (FullKeyboardSettings().isEnabled || !hasFullAccess)
&& UIDevice.current.userInterfaceIdiom == .phone
guard surface == nil || wantsFull != (fullKeyboard != nil) else { return }
guard surface == nil || viewModel.stagePhase == .idle || viewModel.stagePhase == .failed else { return }
// Hex's own views only (UIKit may keep views of its own here): the surface, and any
// keyboard or bar an earlier mount left behind.
children.forEach { child in
child.willMove(toParent: nil)
child.viewIfLoaded?.removeFromSuperview()
child.removeFromParent()
}
surface?.removeFromSuperview()
view.subviews.filter { $0 is FullKeyboardView }.forEach { $0.removeFromSuperview() }
fullKeyboard = nil
didWarmLexicon = false
let mounted: UIView
if wantsFull {
let keyboard = FullKeyboardView(
model: viewModel,
target: DocumentProxyTextTarget { [weak self] in self?.textDocumentProxy }
)
keyboard.hostController = self
keyboard.onPreferredHeightChange = { [weak self] in
self?.view.setNeedsLayout()
self?.view.layoutIfNeeded()
}
keyboard.allowsHaptics = { [weak self] in
self?.allowsKeyHaptics ?? false
}
keyboard.onTextEdit = { [weak self] in self?.observeDictationEdits(fromKeys: true) }
keyboard.onUndoDictation = { [weak self] in
self?.dictationEdits.didUndo()
self?.logDictationEdits.didUndo()
}
keyboard.onReturnKey = { [weak self] in self?.returnKeyWillInsert() }
fullKeyboard = keyboard
mounted = keyboard
applyHeight(keyboard.preferredHeight)
} else {
let hosting = UIHostingController(
rootView: KeyboardSurfaceView(model: viewModel, defersDotScopeUntilActive: true)
)
hosting.view.backgroundColor = .clear
addChild(hosting)
hosting.didMove(toParent: self)
mounted = hosting.view
applyHeight(140)
}
mounted.translatesAutoresizingMaskIntoConstraints = false
view.insertSubview(mounted, aboveSubview: backdrop)
NSLayoutConstraint.activate([
mounted.leadingAnchor.constraint(equalTo: view.leadingAnchor),
mounted.trailingAnchor.constraint(equalTo: view.trailingAnchor),
mounted.topAnchor.constraint(equalTo: view.topAnchor),
mounted.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
surface = mounted
attachTypingLog()
schedulePoll(force: false)
}
/// The dictation bar polls at 25 Hz; the full keyboard at 4 Hz, and 30 Hz while recording.
private func schedulePoll(force: Bool) {
let busy = viewModel.stagePhase == .recording || viewModel.stagePhase == .transcribing
|| viewModel.pendingCommand != nil
let interval: TimeInterval = fullKeyboard == nil ? 0.04 : (busy ? 1.0 / 30 : 0.25)
guard force || (pollTimer != nil && interval != pollInterval) else { return }
pollInterval = interval
pollTimer?.invalidate()
pollTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in
MainActor.assumeIsolated {
self?.syncFromBridge(animated: true)
}
}
}
/// Full Access, which dictation needs (Hex's App Group, the microphone). In the simulator
/// a live Hex session stands in for it.
private func dictationAccess(now: TimeInterval) -> Bool {
#if targetEnvironment(simulator)
return hasFullAccess || bridge.snapshot().isAvailable(at: now)
#else
return hasFullAccess
#endif
}
private func syncFromBridge(animated: Bool) {
let now = Date().timeIntervalSince1970
updateKeyboardTraits()
fullKeyboard?.syncSettings()
syncTypingLogEnabled()
syncLoggingMark()
let effectiveFullAccess = dictationAccess(now: now)
syncLocalDictationAvailability(access: effectiveFullAccess)
guard effectiveFullAccess else {
viewModel.applyBridgeState(
hasFullAccess: false,
snapshot: .offline,
isModelInstalled: false,
style: viewModel.style,
now: now,
clearPending: true,
animated: animated
)
return
}
if now - lastFullAccessNote >= 5 {
lastFullAccessNote = now
bridge.fullAccessSeenAt = now
}
if dictationEdits.isTracking {
dictationEdits.tick { editContext }
}
if logDictationEdits.isTracking {
logDictationEdits.tick { editContext }
}
let localSnapshot = localDictation.snapshot(now: now)
let snap = localSnapshot ?? bridge.snapshot()
if let timeline = warmStartTimeline, timeline.observe(snap, now: now) { warmStartTimeline = nil }
var insertedResult = false
if snap.hasDeliverableResult(at: now),
let resultID = snap.resultID,
let rawTranscript = snap.transcript,
bridge.lastInsertedResultID != resultID {
let context = editContext
let insertion = TranscriptFormatter.insertionText(
for: rawTranscript,
beforeContext: context.before,
afterContext: context.after,
isWord: dictationWordCheck()
)
if learnsFromDictation {
dictationEdits.willInsert(heard: snap.heard, inserted: insertion, context: context)
} else {
dictationEdits.finish(context)
}
if let log = typingLog, log.isRecording {
// A translation can't be compared with what was heard.
let heard = snap.stages?.translated == nil ? (snap.heard ?? snap.stages?.raw) : nil
logDictationEdits.willInsert(heard: heard, inserted: insertion, context: context)
} else if logDictationEdits.isTracking {
logDictationEdits.finish(context)
}
textDocumentProxy.insertText(insertion)
fullKeyboard?.didInsertDictation(insertion)
typingLog?.dictation(
source: localSnapshot == nil ? "app" : "keyboard",
resultID: resultID,
style: bridge.style.rawValue,
stages: snap.stages,
delivered: rawTranscript,
inserted: insertion
)
observeDictationEdits(fromKeys: true)
bridge.lastInsertedResultID = resultID
localDictation.markDelivered(resultID: resultID)
insertedResult = true
coldStartJobID = UUID().uuidString
}
syncLanguageState()
viewModel.applyBridgeState(
hasFullAccess: true,
snapshot: snap,
isModelInstalled: bridge.isModelInstalled,
style: bridge.style,
now: now,
clearPending: insertedResult,
animated: animated
)
refreshColdStartURL(now: now, force: false)
schedulePoll(force: false)
}
// MARK: - In-keyboard dictation
/// Whether the Dictate and Hex keys dictate in the keyboard; nil until first decided.
private var localDictationAvailable: Bool?
private var lastAvailabilityNote: TimeInterval = 0
/// In-keyboard dictation (iOS 26) needs memory for its capture web view and recording
/// screen, and iOS ends a keyboard that passes its limit (older iPhones, many apps open).
/// While the keyboard is short of it, `onLocalDictateTap` is nil, so Dictate and the Hex
/// key take the cold start that opens Hex, as before iOS 26 (a hold stays a tap there).
/// The same while the keyboard couldn't get its speech model ("Open Hex to download
/// English."): Hex downloads it, and the keyboard dictates again once it installs.
/// Without Full Access it is nil too, and the Hex key says dictation needs Full Access.
private func syncLocalDictationAvailability(access: Bool) {
guard KeyboardLocalDictation.isSupported else { return }
guard access || localDictation.isActive else {
if viewModel.onLocalDictateTap != nil { viewModel.onLocalDictateTap = nil }
localDictationAvailable = nil
return
}
let needsHex = !localDictation.isActive && LanguageSettings().keyboardNeedsHex()
let available = localDictation.isActive || (!needsHex && localDictation.hasMemoryToStart)
guard available != localDictationAvailable else { return }
// Noted at most every 5 s, as the footprint can hover at the line.
let now = Date().timeIntervalSince1970
if localDictationAvailable != nil || !available, now - lastAvailabilityNote >= 5 {
lastAvailabilityNote = now
let change = available
? "dictating in the keyboard"
: needsHex ? "speech model missing here, Dictate opens Hex" : "short of memory, Dictate opens Hex"
KeyboardProbeLog.shared.write("\(change) \(KeyboardProbeLog.memory())")
}
localDictationAvailable = available
viewModel.onLocalDictateTap = available ? { [weak self] in
guard let self else { return }
self.localDictation.start(
in: self.view,
allowBluetoothMic: self.bridge.allowBluetoothMic,
pressedAt: self.takeHexKeyPress()
)
} : nil
}
/// Loads in-keyboard dictation's capture page once the keyboard has shown, so the Hex key
/// only waits for the microphone. Only with Full Access, which dictation needs, and not
/// while a warm Hex session takes the Hex key instead; `prepare` checks memory.
private func prepareLocalDictationIfNeeded() {
guard hasFullAccess, viewModel.onLocalDictateTap != nil, !viewModel.isWarmAvailable else { return }
// A turn after the keyboard's first frame, so making the web view never delays it.
DispatchQueue.main.async { [weak self] in
guard let self, self.isShown, !self.viewModel.isWarmAvailable else { return }
self.localDictation.prepare(in: self.view)
}
}
// MARK: - Dictation language
/// The dictation language's dictionary, for lowercasing a dictation that continues a
/// sentence; nil (case kept) when the iPhone has no dictionary for it.
private func dictationWordCheck() -> ((String) -> Bool)? {
let settings = LanguageSettings()
let language = settings.resolvedDictationLanguage
?? settings.effectiveDictationLanguage
?? Locale.preferredLanguages.first
?? "en-US"
guard TranscriptFormatter.lowercasesContinuations(in: language),
let code = KeyboardLanguage.spellCheckLanguage(
forDictation: language,
available: UITextChecker.availableLanguages
) else { return nil }
let checker = SystemTextChecker(language: code)
return { checker.isWordValid($0) }
}
/// What `syncLanguageState` last read, so the 25 Hz poll only works out the choices on a change.
private var languageSignature: String?
/// Apple Speech's languages are listed once per keyboard process.
private static var didListDictationLanguages = false
/// Settings › Dictation language, what Automatic picks, and the switch's choices, plus
/// Translate what I say's target and paste switch, from the App Group (iOS 26, where
/// dictation is Apple Speech).
private func syncLanguageState() {
guard KeyboardLocalDictation.isSupported else { return }
let settings = LanguageSettings()
let explicit = settings.dictationLanguage
let automatic = settings.automaticDictationLanguage
let recent = settings.recentDictationLanguages
let supported = settings.supportedDictationLanguages
let translation = DictationTranslationSettings()
let target = translation.isEnabled ? translation.targetLanguage : nil
let pastesTranslation = translation.pastesTranslation
// Apple's translation (iOS 26+) backs the keyboards' Translate to <language> switch.
let translationLanguage: String? = if #available(iOS 26.0, *) { translation.targetLanguage } else { nil }
let translationLanguages = Self.translationLanguages
let hinglish = HinglishSettings().isEnabled
let signature = [
explicit ?? "", automatic ?? "", recent.joined(separator: ","), "\(supported.count)",
target ?? "", "\(pastesTranslation)", "\(hinglish)",
translationLanguage ?? "", "\(translationLanguages?.count ?? -1)",
].joined(separator: "|")
guard signature != languageSignature else { return }
languageSignature = signature
let choices = DictationLanguageSwitch.choices(
current: explicit,
recent: recent,
preferred: Locale.preferredLanguages,
supported: supported,
hinglish: hinglish
)
if viewModel.dictationLanguage != explicit { viewModel.dictationLanguage = explicit }
if viewModel.automaticLanguage != automatic { viewModel.automaticLanguage = automatic }
if viewModel.languageChoices != choices { viewModel.languageChoices = choices }
if viewModel.translationTarget != target { viewModel.translationTarget = target }
if viewModel.pastesTranslation != pastesTranslation { viewModel.pastesTranslation = pastesTranslation }
if viewModel.translationLanguage != translationLanguage { viewModel.translationLanguage = translationLanguage }
let targets = translationLanguage.map {
DictationTranslationSettings.targetChoices(
current: $0,
dictation: choices,
preferred: Locale.preferredLanguages,
supported: translationLanguages
)
} ?? []
if viewModel.translationTargetChoices != targets { viewModel.translationTargetChoices = targets }
listTranslationLanguagesIfNeeded()
}
/// Apple's translation languages (minimal identifiers), listed once per keyboard process
/// so the Hex key menu offers only targets Apple can translate into.
private static var translationLanguages: [String]?
private static var didListTranslationLanguages = false
private func listTranslationLanguagesIfNeeded() {
guard #available(iOS 26.0, *), hasFullAccess, !Self.didListTranslationLanguages else { return }
Self.didListTranslationLanguages = true
Task { [weak self] in
Self.translationLanguages = await DictationTranslator.supportedTargets()
self?.languageSignature = nil
self?.syncLanguageState()
}
}
/// Asks Apple Speech which languages it has and what Automatic picks, so the switch can
/// offer them before Hex has listed them.
private func listDictationLanguagesIfNeeded() {
guard #available(iOS 26.0, *), hasFullAccess, !Self.didListDictationLanguages else { return }
Self.didListDictationLanguages = true
Task { [weak self] in
_ = await AppleSpeechLanguages.options()
_ = await AppleSpeechLanguages.automatic()
self?.languageSignature = nil
self?.syncLanguageState()
}
}
private func refreshColdStartURL(now: TimeInterval, force: Bool) {
let bucket = Int(now / 2.0)
guard force || bucket != lastURLRefreshBucket else { return }
lastURLRefreshBucket = bucket
mountSurface()
let request: KeyboardLaunchRequest
if bridge.isModelInstalled {
request = .startRecording(
jobID: coldStartJobID,
requestedAt: now,
style: bridge.style
)
} else {
request = .startSession(requestedAt: now)
}
viewModel.coldStartURL = request.url
}
private func updateKeyboardTraits() {
let globe = needsInputModeSwitchKey
if viewModel.needsGlobeKey != globe {
viewModel.needsGlobeKey = globe
}
// No interface style override: iOS already gives the keyboard the field's appearance
// (a field that asks for a dark keyboard gets dark traits in light mode, like the system
// keyboard), while the document proxy's `keyboardAppearance` can go stale.
let nextReturn: String = switch textDocumentProxy.returnKeyType {
case .send: "Send"
case .google, .yahoo, .search: "Search"
case .go: "Go"
case .done: "Done"
case .join: "Join"
case .next: "Next"
case .route: "Route"
case .continue: "Continue"
case .emergencyCall: "SOS"
default: "Return"
}
if viewModel.returnKeyLabel != nextReturn {
viewModel.returnKeyLabel = nextReturn
}
}
/// In-keyboard dictation starts listening as the finger lands on the Hex key, not when the
/// touch has become a tap (on lifting) or a hold (0.35 s): both keep that capture, and a
/// slide to the menu or a cancelled touch drops it (`onHexKeyAbandon`). The same checks as
/// the Hex key's own choice of in-keyboard dictation; a warm Hex session records instead.
private func hexKeyPressed(at time: TimeInterval) {
hexKeyPressedAt = time
guard viewModel.hasFullAccess, !viewModel.isWarmAvailable, viewModel.onLocalDictateTap != nil,
viewModel.stagePhase == .idle || viewModel.stagePhase == .failed else { return }
localDictation.arm(in: view, allowBluetoothMic: bridge.allowBluetoothMic, pressedAt: time)
}
/// The touch-down that led to this start, if it was the Hex key's in the last 2 s.
private func takeHexKeyPress() -> TimeInterval? {
defer { hexKeyPressedAt = nil }
guard let at = hexKeyPressedAt, Date().timeIntervalSince1970 - at < 2 else { return nil }
return at
}
private func startWarmDictation() {
let now = Date().timeIntervalSince1970
guard viewModel.hasFullAccess, viewModel.currentSnapshot.isAvailable(at: now) else { return }
// A warm session that came up since touch-down records instead.
localDictation.discard(reason: "warm session")
let jobID = UUID().uuidString
warmStartTimeline = WarmStartTimeline(jobID: jobID, pressedAt: takeHexKeyPress() ?? now, sentAt: now)
viewModel.setPendingCommand(
KeyboardViewModel.PendingCommand(kind: .start, jobID: jobID, sentAt: now),
now: now,
animated: true
)
bridge.send(.start, jobID: jobID, style: viewModel.style, sentAt: now)
}
private func stopWarmDictation() {
let now = Date().timeIntervalSince1970
guard let jobID = viewModel.currentSnapshot.jobID ?? viewModel.pendingCommand?.jobID else { return }
viewModel.setPendingCommand(
KeyboardViewModel.PendingCommand(kind: .stop, jobID: jobID, sentAt: now),
now: now,
animated: true
)
bridge.send(.stop, jobID: jobID, style: viewModel.style, sentAt: now)
}
private func cancelWarmDictation() {
let now = Date().timeIntervalSince1970
guard let jobID = viewModel.currentSnapshot.jobID ?? viewModel.pendingCommand?.jobID else { return }
viewModel.setPendingCommand(
KeyboardViewModel.PendingCommand(kind: .cancel, jobID: jobID, sentAt: now),
now: now,
animated: true
)
bridge.send(.cancel, jobID: jobID, style: viewModel.style, sentAt: now)
}
}