mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
* iOS keyboard: touches at the screen's side edges reach the keys at once
What: KeyboardViewController.viewDidAppear turns off delaysTouchesBegan on
the keyboard window's gesture recognizers, iOS's system-gesture gate.
Why: a TestFlight tester (build 25) said they miss keys more on Hex's full
keyboard than on Apple's. Record typing logs from an iPhone show touches
within 20 pt of the side edges reaching the keys 104 ms (median, n=8) after
the finger went down, against 21 ms everywhere else (n=1,258): iOS holds
them back while it checks for an edge gesture. q, a, p, l, shift and delete
lagged and could land after the next key. Apple's keyboard has no such delay.
Verified: full HEXMobileTests suite on the iPhone 18 Pro simulator (iOS 27.2):
280 tests, 0 failures, 1 skipped (as before). The simulator never delays edge
touches (the key balloon shows at x = 1 pt while held), so whether this removes
the delay on an iPhone is unverified until the next typing log.
* iOS keyboard: a tap just above row 1 types its key, not a suggestion
What: row 1's touch targets also take the strip's bottom 4 pt, below its pills
and chips (KeyboardLayout.stripTouchBand; touchAreaFrame is the key area plus
that band and is what the key plane accepts). The Hex key's target in the strip
now stops where row 1's starts. Every other target is unchanged: gaps still
split down the middle and the outer keys still reach the screen's edges, in
every layout (Russian and Serbian included).
Why: in the live keyboard (AXe taps on the iPhone 18 Pro simulator) a tap 1 to
7 pt above a row-1 keycap accepted a suggestion. Apple's keyboard on the same
simulator types the key in the ~8 pt above its keycaps (at x = 110 it types e
from y = 590; its keycap starts at 598, the predictive bar ends at 589).
Verified: KeyboardLayoutTests now check that the hit frames tile the touch area
with no gaps or overlaps and that 2 pt above every row-1 keycap types it, in
every language, width and orientation; full suite 280 tests, 0 failures.
* iOS keyboard: the likely next letter claims up to 5 pt of its neighbour's target
What: FullKeyboardEngine.key(at:) picks the key a touch presses: the one under
it, or a neighbouring letter within letterReach (5 pt) of the touch whose odds
of coming next in the word beat the touched letter's by 0.8 nats for every point
it reaches past its own target. The odds are the word list's frequency mass
after what is typed (TypingDecoderModel.continuations; accented letters without
a key of their own count toward their base). It applies only on the letters page
of a text field, with autocorrect on and allowed by the field, outside caps lock,
for English and Spanish, whose Spatial autocorrect models FullKeyboardView now
maps whether or not that experiment is on (other layouts keep fixed targets). A
touch a letter claimed keeps it while a rolling finger stays within reach, so a
point of jitter doesn't slide it back. Record typing logs' began line names the
key pressed, with `under` when the odds moved it (docs/typing-logs.md). The
ios/README.md gains a Touch targets section for this and the two previous commits.
Why: Apple's keyboard does this (AXe on the iPhone 18 Pro simulator: after "th"
a tap 10 pt inside d types e; with nothing typed its row borders sit within about
2 pt of the gaps' middles), and Hex's targets were fixed. A fixed upward offset
was measured and left out: moving each of 643 labelled logged taps up by 2 to
8 pt landed no more of them on the meant key (586 at 0, 583 to 562 shifted).
Verified with a benchmark harness (kept outside the repo) that types taps
through FullKeyboardEngine; 5 pt and 0.8 nats/pt chosen on dev sets, checked on
held-out sets:
- held-out English (2,000 Tatoeba sentences typed with a touch model fitted to
real typing logs, 13,870 words): words mistyped before autocorrect 3,814 ->
2,504 (names aside); output word error rate with default autocorrect 13.2% ->
10.4%, with Spatial 8.5% -> 7.9%. Taps the odds moved broke 98 words that were
typed right and fixed 1,561 (8 pt: 112 and 1,921).
- held-out Spanish (13,301 words): default 22.9% -> 19.1%, Spatial 10.4% ->
10.2%; broke 46, fixed 1,451.
- fat-finger sentences (180, 1,614 words): default 15.3% -> 12.9%, Spatial
6.2% -> 5.3%. Real logged words (172): default 10.5% -> 9.3%, Spatial 4.1%
both.
- the tester's sentence, 30 tap draws: 51 of 360 slipped words now typed right
before autocorrect; Spatial 6.7% -> 6.3%.
New FullKeyboardEngineTests: the e/d border after "th" and "an", past the reach,
with autocorrect off or disallowed, a rolled finger; and the tester's sentence
from "but", tapped, through Spatial autocorrect. Full suite: 280 tests, 0
failures.
* iOS keyboard: Spatial autocorrect keeps names typed in lowercase, capitalised
What: when Spatial autocorrect reads a word typed all in lowercase that the
dictionary knows only capitalised (a name, day or place: "mary", "monday",
"boston"), it counts as a word (the 7-nat margin) and, unless a reading beats it
by that, is capitalised as the dictionary path does ("Mary").
Why: the models' word lists are lowercase only (SCOWL), so a lowercase name was
an unknown word with a 2-nat margin. On the held-out English benchmark Spatial
changed 287 of 1,488 correctly typed names, against 85 for the default engine:
"mary" -> "may" 98 times, "boston" -> "boson", "monday" -> "money". This is the
main thing that stood against turning Spatial autocorrect on by default.
Verified (benchmark harness, held-out sets, Spatial autocorrect without and with
the next-letter odds): English correctly typed names changed 287 -> 82 (default
engine 85), output word error rate 8.5% -> 7.1% (6.5% with the odds); Spanish
names 182 -> 5 of 732, 10.4% -> 9.2% (8.8% with the odds); fat-finger sentences
6.2% -> 6.0%; the tester's sentence unchanged (6.8%). New
AutocorrectEngineTests case: "see mary on monday in boston" typed at the keys'
centres comes out "see Mary on Monday in Boston". Full suite: 280 tests, 0
failures.
855 lines
34 KiB
Swift
855 lines
34 KiB
Swift
import QuartzCore
|
||
import UIKit
|
||
|
||
/// The text field the keys type into. `UITextDocumentProxy` in the keyboard; a fake in tests.
|
||
@MainActor
|
||
protocol KeyboardTextTarget: AnyObject {
|
||
var documentContextBeforeInput: String? { get }
|
||
var hasText: Bool { get }
|
||
var autocapitalizationType: UITextAutocapitalizationType? { get }
|
||
var autocorrectionType: UITextAutocorrectionType? { get }
|
||
var keyboardType: UIKeyboardType? { get }
|
||
var returnKeyType: UIReturnKeyType? { get }
|
||
var enablesReturnKeyAutomatically: Bool? { get }
|
||
var keyboardAppearance: UIKeyboardAppearance? { get }
|
||
var textContentType: UITextContentType? { get }
|
||
func insertText(_ text: String)
|
||
func deleteBackward()
|
||
func adjustTextPosition(byCharacterOffset offset: Int)
|
||
}
|
||
|
||
extension KeyboardTextTarget {
|
||
var autocorrectionType: UITextAutocorrectionType? { .default }
|
||
var enablesReturnKeyAutomatically: Bool? { false }
|
||
var textContentType: UITextContentType? { nil }
|
||
func adjustTextPosition(byCharacterOffset offset: Int) {}
|
||
}
|
||
|
||
@MainActor
|
||
final class DocumentProxyTextTarget: KeyboardTextTarget {
|
||
private let proxy: () -> UITextDocumentProxy?
|
||
|
||
init(_ proxy: @escaping () -> UITextDocumentProxy?) {
|
||
self.proxy = proxy
|
||
}
|
||
|
||
var documentContextBeforeInput: String? { proxy()?.documentContextBeforeInput }
|
||
var hasText: Bool { proxy()?.hasText ?? false }
|
||
var autocapitalizationType: UITextAutocapitalizationType? { proxy()?.autocapitalizationType }
|
||
var autocorrectionType: UITextAutocorrectionType? { proxy()?.autocorrectionType }
|
||
var keyboardType: UIKeyboardType? { proxy()?.keyboardType }
|
||
var returnKeyType: UIReturnKeyType? { proxy()?.returnKeyType }
|
||
var enablesReturnKeyAutomatically: Bool? { proxy()?.enablesReturnKeyAutomatically }
|
||
var keyboardAppearance: UIKeyboardAppearance? { proxy()?.keyboardAppearance }
|
||
var textContentType: UITextContentType? { proxy()?.textContentType ?? nil }
|
||
func insertText(_ text: String) { proxy()?.insertText(text) }
|
||
func deleteBackward() { proxy()?.deleteBackward() }
|
||
func adjustTextPosition(byCharacterOffset offset: Int) { proxy()?.adjustTextPosition(byCharacterOffset: offset) }
|
||
}
|
||
|
||
/// Everything the keys do, apart from drawing: multitouch with rollover, shift, pages,
|
||
/// long-press accents, spacebar cursor trackpad, cautious autocorrect, double-space period,
|
||
/// auto-capitalization and accelerating delete. Touches are identified by any stable integer
|
||
/// so tests can drive it without `UITouch`.
|
||
@MainActor
|
||
final class FullKeyboardEngine {
|
||
struct ActiveTouch: Equatable {
|
||
var key: KeyboardKey
|
||
var startPoint: CGPoint
|
||
var point: CGPoint
|
||
/// A character that already went in because another key went down after it.
|
||
var committed: Bool
|
||
/// The page a 123/ABC press came from; releasing over a character returns there.
|
||
var returnLayer: KeyboardLayer?
|
||
/// True once a spacebar press crosses `trackpadActivationDistance`.
|
||
var isTrackpad = false
|
||
var trackpadAnchorX: CGFloat = 0
|
||
/// Characters the trackpad has moved the cursor, for Record typing logs.
|
||
var trackpadOffset = 0
|
||
/// True when the likelier next letter claimed this touch from the key under it; a
|
||
/// small move then keeps it rather than sliding back (`letterReach`).
|
||
var claimed = false
|
||
}
|
||
|
||
static let accentHoldDelay: TimeInterval = 0.40
|
||
static let accentSlop: CGFloat = 10
|
||
static let trackpadActivationDistance: CGFloat = 10
|
||
static let trackpadPointsPerCharacter: CGFloat = 7.5
|
||
|
||
private(set) var shift = ShiftStateMachine()
|
||
private(set) var layerState = KeyboardLayerState()
|
||
private(set) var field: KeyboardFieldKind = .text
|
||
private(set) var touches: [Int: ActiveTouch] = [:]
|
||
/// Touch ids in the order they went down.
|
||
private var touchOrder: [Int] = []
|
||
private var lastSpaceAt: TimeInterval?
|
||
|
||
/// Where each letter of the word being typed was tapped (nil for one that came another
|
||
/// way, such as an accent), for Spatial autocorrect.
|
||
private var tokenTaps: [CGPoint?] = []
|
||
/// Spatial autocorrect: where you tend to tap each letter, from its centre (Learn how I type).
|
||
var tapOffsets: [Character: CGVector] = [:] {
|
||
didSet { if tapOffsets != oldValue { syncDecoderKeys() } }
|
||
}
|
||
|
||
/// The layout language's word list, which lets the likelier of two neighbouring letters
|
||
/// claim a few points of the other's touch target, as Apple's keyboard does ("th" then a
|
||
/// tap on the e/d border types e). Used only while autocorrect is on in a text field
|
||
/// that allows it; nil keeps every target fixed.
|
||
var letterOdds: TypingDecoderModel? {
|
||
didSet {
|
||
if letterOdds !== oldValue {
|
||
continuationCache = nil
|
||
wordStartMass = nil
|
||
}
|
||
}
|
||
}
|
||
/// How far past its own target a likelier letter may reach, in points.
|
||
var letterReach: CGFloat = 5
|
||
/// Nats of odds (ln of how many times likelier) a letter needs for each point it claims.
|
||
var letterOddsPerPoint = 0.8
|
||
private var continuationCache: (prefix: [UInt8], mass: [Double]?)?
|
||
/// The first letters' frequencies, the costliest to add up (every word), kept apart.
|
||
private var wordStartMass: [Double]??
|
||
|
||
private(set) var activeAccentMenu: AccentMenu?
|
||
private var activeAccentTouchID: Int?
|
||
private(set) var suggestions: [KeyboardSuggestion] = []
|
||
|
||
let target: KeyboardTextTarget
|
||
let autocorrect: AutocorrectEngine
|
||
/// Learn how I type (Experiments); nil while off.
|
||
var journal: TypingJournal? {
|
||
didSet { syncLearning() }
|
||
}
|
||
|
||
private var learning: TypingJournal? {
|
||
guard let journal, TypingJournal.allows(field: field, target: target) else { return nil }
|
||
return journal
|
||
}
|
||
/// Record typing logs (Experiments); nil while it is off, in fields it skips, and in the
|
||
/// app's fixtures. Every call through it is skipped (arguments too) while nil.
|
||
var typingLog: TypingLogger?
|
||
var width: CGFloat = 375 { didSet { if width != oldValue { rebuildLayout() } } }
|
||
var orientation: KeyboardOrientation = .portrait { didSet { if orientation != oldValue { rebuildLayout() } } }
|
||
var showsGlobe = false { didSet { if showsGlobe != oldValue { rebuildLayout() } } }
|
||
/// Experiments › Emoji, in fields that take emoji.
|
||
var showsEmoji = false { didSet { if showsEmoji != oldValue { rebuildLayout() } } }
|
||
var horizontalInset: CGFloat = 0 { didSet { if horizontalInset != oldValue { rebuildLayout() } } }
|
||
/// The letters, accents and spelling dictionary (Settings › Keyboard layout).
|
||
var language: KeyboardLanguage = .english {
|
||
didSet {
|
||
guard language != oldValue else { return }
|
||
cancelAllTouches()
|
||
autocorrect.setLanguage(language)
|
||
rebuildLayout(cause: "language")
|
||
refreshSuggestions()
|
||
}
|
||
}
|
||
private(set) var layout = KeyboardLayout(width: 375)
|
||
|
||
var clock: () -> TimeInterval = { CACurrentMediaTime() }
|
||
/// Called whenever something visible changed (page, shift, pressed keys, suggestions, accents).
|
||
var onChange: (() -> Void)?
|
||
/// Called after the keys typed or deleted anything.
|
||
var onEdit: (() -> Void)?
|
||
/// Called when an accent cell or spacebar trackpad step ticks, for selection haptics.
|
||
var onSelectionStep: (() -> Void)?
|
||
/// Called just before the return key types its line break, so a send can be noticed.
|
||
var onReturn: (() -> Void)?
|
||
/// Called when the emoji key is let go.
|
||
var onEmojiKey: (() -> Void)?
|
||
|
||
init(target: KeyboardTextTarget, autocorrect: AutocorrectEngine? = nil) {
|
||
self.target = target
|
||
self.autocorrect = autocorrect ?? AutocorrectEngine()
|
||
rebuildLayout()
|
||
}
|
||
|
||
var isUppercase: Bool { layerState.layer == .letters && shift.isUppercase }
|
||
|
||
var isTrackpadActive: Bool {
|
||
touches.values.contains(where: \.isTrackpad)
|
||
}
|
||
|
||
/// Settings › Key pop-ups. Off: pressed keys only darken, as with iOS's Character Preview off.
|
||
var showsKeyPopups = true
|
||
|
||
/// The key whose balloon shows: the newest character still held (hidden while an accent menu is up).
|
||
var previewKey: KeyboardKey? {
|
||
guard activeAccentMenu == nil else { return nil }
|
||
for id in touchOrder.reversed() {
|
||
if let touch = touches[id], touch.key.character != nil, !touch.committed {
|
||
return touch.key
|
||
}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
var pressedKinds: Set<KeyKind> {
|
||
Set(touches.values.map(\.key.kind))
|
||
}
|
||
|
||
func displayLabel(for key: KeyboardKey) -> String {
|
||
guard let character = key.character else { return key.label }
|
||
return isUppercase && layerState.layer == .letters ? character.uppercased() : character
|
||
}
|
||
|
||
// MARK: - Field
|
||
|
||
/// Call when the keyboard appears or the field changes.
|
||
func configureForField() {
|
||
switch KeyboardFieldRouting.route(for: target.keyboardType) {
|
||
case .keys(let kind, let initialLayer):
|
||
field = kind
|
||
layerState.reset(to: initialLayer)
|
||
case .handOff:
|
||
field = .text
|
||
layerState.reset(to: .numbers)
|
||
}
|
||
shift.reset()
|
||
lastSpaceAt = nil
|
||
tokenTaps.removeAll()
|
||
autocorrect.clearPendingUndo()
|
||
cancelAllTouches()
|
||
rebuildLayout(cause: "field")
|
||
refreshAutoCapitalization()
|
||
refreshSuggestions()
|
||
}
|
||
|
||
/// Call after the text or the cursor changed outside these keys.
|
||
func textDidChange() {
|
||
lastSpaceAt = nil
|
||
tokenTaps.removeAll()
|
||
autocorrect.clearPendingUndo()
|
||
refreshAutoCapitalization()
|
||
refreshSuggestions()
|
||
}
|
||
|
||
func refreshAutoCapitalization() {
|
||
let before = shift
|
||
shift.refreshAutoCapitalization(
|
||
AutoCapitalization.shouldCapitalize(
|
||
mode: AutoCapitalization.Mode(target.autocapitalizationType),
|
||
before: target.documentContextBeforeInput,
|
||
hasText: target.hasText
|
||
)
|
||
)
|
||
if shift != before {
|
||
logState("auto")
|
||
onChange?()
|
||
}
|
||
}
|
||
|
||
func refreshSuggestions() {
|
||
syncLearning()
|
||
autocorrect.decoderTaps = currentTokenTaps
|
||
let next = autocorrect.suggestions(
|
||
beforeInput: target.documentContextBeforeInput,
|
||
field: field,
|
||
autocorrectionType: target.autocorrectionType
|
||
)
|
||
if next != suggestions {
|
||
suggestions = next
|
||
typingLog?.suggestionsChanged(next)
|
||
onChange?()
|
||
}
|
||
}
|
||
|
||
func acceptSuggestion(_ suggestion: KeyboardSuggestion) {
|
||
if let log = typingLog {
|
||
let token = AutocorrectEngine.currentToken(in: target.documentContextBeforeInput) ?? ""
|
||
log.edit("suggestion", [
|
||
TypingLogField("slot", suggestions.firstIndex(of: suggestion).map { .int($0) } ?? .null),
|
||
TypingLogField("text", .string(suggestion.displayText)),
|
||
TypingLogField("deleted", .string(token)),
|
||
TypingLogField("inserted", .string(suggestion.replacement + " ")),
|
||
TypingLogField("candidates", TypingLogger.candidates(suggestions)),
|
||
])
|
||
}
|
||
if let journal = learning {
|
||
let token = AutocorrectEngine.currentToken(in: target.documentContextBeforeInput)
|
||
if let token, !token.isEmpty, token != suggestion.replacement {
|
||
journal.record(.picked, typed: token, final: suggestion.replacement)
|
||
} else {
|
||
journal.didFinish(word: token)
|
||
// Tapping what you typed over the autocorrection space would apply turns it down.
|
||
if suggestion.kind == .keepLiteral, let token,
|
||
let autoFix = suggestions.first(where: \.willAutoReplace) {
|
||
journal.record(.keptTyped, typed: autoFix.replacement, final: token)
|
||
}
|
||
}
|
||
}
|
||
if let token = AutocorrectEngine.currentToken(in: target.documentContextBeforeInput) {
|
||
for _ in 0..<token.count {
|
||
target.deleteBackward()
|
||
}
|
||
if suggestion.kind == .keepLiteral {
|
||
autocorrect.suppressAndKeep(token)
|
||
}
|
||
}
|
||
autocorrect.clearPendingUndo()
|
||
insert(suggestion.replacement + " ", source: nil)
|
||
typingLog?.context("suggestion")
|
||
}
|
||
|
||
/// Types an emoji from the emoji panel: no spacing or autocorrect around it.
|
||
func insertEmoji(_ text: String, source: String) {
|
||
autocorrect.clearPendingUndo()
|
||
learning?.didFinish(word: AutocorrectEngine.currentToken(in: target.documentContextBeforeInput))
|
||
insert(text, source: source)
|
||
}
|
||
|
||
// MARK: - Touches
|
||
|
||
/// The key a touch going down at `point` presses: the one under it, or a neighbouring
|
||
/// letter within `letterReach` points that is enough likelier to come next in the word.
|
||
func key(at point: CGPoint) -> KeyboardKey? {
|
||
guard let key = layout.hitTest(point) else { return nil }
|
||
guard key.character != nil, let model = letterOdds, layerState.layer == .letters,
|
||
field == .text, autocorrect.isEnabled, target.autocorrectionType != .no,
|
||
shift.state != .locked, model.language == language.rawValue else { return key }
|
||
let reach = letterReach
|
||
let near = layout.keys.filter {
|
||
$0.character != nil && $0.kind != key.kind && Self.distance(from: point, to: $0.hitFrame) < reach
|
||
}
|
||
guard !near.isEmpty, let continuations = continuationMass(model) else { return key }
|
||
// An accented letter without a key of its own is typed from its base letter's (é from e).
|
||
var mass = [Double](repeating: 0, count: continuations.count)
|
||
let keyed = Set(layout.keys.compactMap { key in
|
||
key.character.flatMap { $0.count == 1 ? model.codes[Character($0)] : nil }
|
||
})
|
||
for (code, m) in continuations.enumerated() where m > 0 {
|
||
mass[keyed.contains(UInt8(code)) ? code : Int(model.baseCodes[code])] += m
|
||
}
|
||
let total = mass.reduce(0, +)
|
||
func odds(_ k: KeyboardKey) -> Double? {
|
||
guard let c = k.character, c.count == 1, let code = model.codes[Character(c)] else { return nil }
|
||
return log(mass[Int(code)] + total * 1e-4)
|
||
}
|
||
guard let own = odds(key) else { return key }
|
||
var best = key
|
||
var bestScore = own
|
||
for other in near {
|
||
guard let theirs = odds(other) else { continue }
|
||
let score = theirs - letterOddsPerPoint * Double(Self.distance(from: point, to: other.hitFrame))
|
||
if score > bestScore {
|
||
best = other
|
||
bestScore = score
|
||
}
|
||
}
|
||
return best
|
||
}
|
||
|
||
/// The word list's next-letter frequencies after the word being typed, or nil when they
|
||
/// can't help: inside something that isn't a word, or a word the list doesn't have.
|
||
private func continuationMass(_ model: TypingDecoderModel) -> [Double]? {
|
||
let before = target.documentContextBeforeInput ?? ""
|
||
let token = AutocorrectEngine.currentToken(in: before)
|
||
if token == nil, let last = before.last, last.isLetter || last.isNumber || last == "'" { return nil }
|
||
guard let prefix = model.encode((token ?? "").lowercased()) else { return nil }
|
||
if prefix.isEmpty {
|
||
if let cached = wordStartMass { return cached }
|
||
let mass = model.continuations(after: [])
|
||
wordStartMass = .some(mass)
|
||
return mass
|
||
}
|
||
if let cache = continuationCache, cache.prefix == prefix { return cache.mass }
|
||
let mass = model.continuations(after: prefix)
|
||
continuationCache = (prefix, mass)
|
||
return mass
|
||
}
|
||
|
||
private static func distance(from point: CGPoint, to rect: CGRect) -> CGFloat {
|
||
let dx = max(rect.minX - point.x, 0, point.x - rect.maxX)
|
||
let dy = max(rect.minY - point.y, 0, point.y - rect.maxY)
|
||
return (dx * dx + dy * dy).squareRoot()
|
||
}
|
||
|
||
func touchBegan(id: Int, at point: CGPoint) {
|
||
guard let key = key(at: point) else { return }
|
||
// Rollover: a new key going down commits any character or accent picker still held.
|
||
for other in touchOrder {
|
||
guard var touch = touches[other], touch.key.character != nil, !touch.committed else { continue }
|
||
if activeAccentTouchID == other, let menu = activeAccentMenu {
|
||
typingLog?.ui("accent_pick", [
|
||
TypingLogField("id", .int(other)),
|
||
TypingLogField("index", .int(menu.selectedIndex)),
|
||
TypingLogField("chosen", .string(menu.selectedOption)),
|
||
TypingLogField("rollover", .bool(true)),
|
||
])
|
||
commitAccentSelection(menu.selectedOption)
|
||
activeAccentMenu = nil
|
||
activeAccentTouchID = nil
|
||
} else {
|
||
commitCharacter(touch.key, at: touch.startPoint)
|
||
}
|
||
touch.committed = true
|
||
touches[other] = touch
|
||
}
|
||
|
||
var touch = ActiveTouch(
|
||
key: key,
|
||
startPoint: point,
|
||
point: point,
|
||
committed: false,
|
||
returnLayer: nil
|
||
)
|
||
touch.claimed = !key.hitFrame.contains(point)
|
||
if key.character != nil {
|
||
learning?.recordTap(on: key, at: point)
|
||
}
|
||
switch key.kind {
|
||
case .shift:
|
||
shift.shiftDown(now: clock())
|
||
logState("shift_key")
|
||
case .delete:
|
||
deleteBackward(allowAutocorrectUndo: true)
|
||
case .layerSwitch(let next):
|
||
touch.returnLayer = layerState.layer
|
||
layerState.switchTo(next)
|
||
if next == .letters { shift.reset() }
|
||
rebuildLayout(cause: "layer_key")
|
||
if next == .letters { refreshAutoCapitalization() }
|
||
case .character, .space, .returnKey, .hex, .globe, .emoji:
|
||
break
|
||
}
|
||
touches[id] = touch
|
||
touchOrder.append(id)
|
||
onChange?()
|
||
}
|
||
|
||
@discardableResult
|
||
func openAccentMenuIfEligible(forTouch id: Int) -> Bool {
|
||
guard activeAccentMenu == nil,
|
||
let touch = touches[id],
|
||
!touch.committed,
|
||
let base = touch.key.character else { return false }
|
||
let dx = touch.point.x - touch.startPoint.x
|
||
let dy = touch.point.y - touch.startPoint.y
|
||
guard (dx * dx + dy * dy).squareRoot() <= Self.accentSlop else { return false }
|
||
guard let options = AccentCatalog.options(for: base, uppercase: isUppercase, language: language),
|
||
options.count > 1 else { return false }
|
||
activeAccentMenu = AccentMenu.build(
|
||
for: touch.key.frame,
|
||
rawOptions: options,
|
||
in: layout.width,
|
||
horizontalInset: layout.horizontalInset
|
||
)
|
||
activeAccentTouchID = id
|
||
typingLog?.ui("accent_open", [
|
||
TypingLogField("id", .int(id)),
|
||
TypingLogField("key", .string(TypingLogger.keyID(touch.key.kind))),
|
||
TypingLogField("options", .strings(activeAccentMenu?.options ?? [])),
|
||
])
|
||
onChange?()
|
||
return true
|
||
}
|
||
|
||
func touchMoved(id: Int, to point: CGPoint) {
|
||
guard var touch = touches[id] else { return }
|
||
touch.point = point
|
||
|
||
// 1. Active long-press accent picker: horizontal drag selects the alternate character.
|
||
if activeAccentTouchID == id, var menu = activeAccentMenu {
|
||
let nextIndex = menu.index(for: point.x)
|
||
touches[id] = touch
|
||
if nextIndex != menu.selectedIndex {
|
||
menu.selectedIndex = nextIndex
|
||
activeAccentMenu = menu
|
||
onSelectionStep?()
|
||
onChange?()
|
||
}
|
||
return
|
||
}
|
||
|
||
// 2. Spacebar cursor trackpad: horizontal drag >= 10 pt slides the text caret.
|
||
if touch.key.kind == .space {
|
||
if !touch.isTrackpad, abs(point.x - touch.startPoint.x) >= Self.trackpadActivationDistance {
|
||
touch.isTrackpad = true
|
||
touch.trackpadAnchorX = point.x
|
||
lastSpaceAt = nil
|
||
autocorrect.clearPendingUndo()
|
||
touches[id] = touch
|
||
typingLog?.ui("trackpad_start", [TypingLogField("id", .int(id))])
|
||
onSelectionStep?()
|
||
onChange?()
|
||
return
|
||
}
|
||
if touch.isTrackpad {
|
||
let delta = point.x - touch.trackpadAnchorX
|
||
let rawSteps = Int((delta / Self.trackpadPointsPerCharacter).rounded(.towardZero))
|
||
if rawSteps != 0 {
|
||
touch.trackpadAnchorX += CGFloat(rawSteps) * Self.trackpadPointsPerCharacter
|
||
touch.trackpadOffset += rawSteps
|
||
touches[id] = touch
|
||
typingLog?.edit("cursor", [TypingLogField("offset", .int(rawSteps))])
|
||
tokenTaps.removeAll()
|
||
target.adjustTextPosition(byCharacterOffset: rawSteps)
|
||
onSelectionStep?()
|
||
refreshAutoCapitalization()
|
||
refreshSuggestions()
|
||
return
|
||
}
|
||
touches[id] = touch
|
||
return
|
||
}
|
||
}
|
||
|
||
// 3. Sliding across character keys updates the active key and re-anchors the hold timer.
|
||
// A letter the next-letter odds claimed keeps the touch while it stays within reach.
|
||
if touch.key.character != nil, !touch.committed,
|
||
let under = layout.hitTest(point), under.character != nil, under.kind != touch.key.kind,
|
||
!(touch.claimed && Self.distance(from: point, to: touch.key.hitFrame) < letterReach) {
|
||
touch.claimed = false
|
||
touch.key = under
|
||
touch.startPoint = point
|
||
touches[id] = touch
|
||
onChange?()
|
||
return
|
||
}
|
||
touches[id] = touch
|
||
}
|
||
|
||
func touchEnded(id: Int, at point: CGPoint) {
|
||
guard var touch = touches.removeValue(forKey: id) else { return }
|
||
touchOrder.removeAll { $0 == id }
|
||
touch.point = point
|
||
|
||
if activeAccentTouchID == id, let menu = activeAccentMenu {
|
||
let index = menu.index(for: point.x)
|
||
let chosen = menu.options[index]
|
||
activeAccentMenu = nil
|
||
activeAccentTouchID = nil
|
||
if !touch.committed {
|
||
typingLog?.ui("accent_pick", [
|
||
TypingLogField("id", .int(id)),
|
||
TypingLogField("index", .int(index)),
|
||
TypingLogField("chosen", .string(chosen)),
|
||
])
|
||
commitAccentSelection(chosen)
|
||
}
|
||
onChange?()
|
||
return
|
||
}
|
||
|
||
switch touch.key.kind {
|
||
case .character:
|
||
if !touch.committed {
|
||
commitCharacter(touch.key, at: touch.startPoint)
|
||
}
|
||
case .shift:
|
||
shift.shiftUp()
|
||
logState("shift_key")
|
||
case .space:
|
||
if touch.isTrackpad {
|
||
typingLog?.ui("trackpad_end", [
|
||
TypingLogField("id", .int(id)),
|
||
TypingLogField("offset", .int(touch.trackpadOffset)),
|
||
])
|
||
typingLog?.context("trackpad")
|
||
} else {
|
||
typeSpace()
|
||
}
|
||
case .returnKey:
|
||
if target.enablesReturnKeyAutomatically == true && !target.hasText {
|
||
typingLog?.edit("return", [
|
||
TypingLogField("returnKeyType", .string(TypingLogTraits.name(target.returnKeyType ?? .default))),
|
||
TypingLogField("ignored", .bool(true)),
|
||
])
|
||
break
|
||
}
|
||
learning?.didFinish(word: AutocorrectEngine.currentToken(in: target.documentContextBeforeInput))
|
||
autocorrect.clearPendingUndo()
|
||
typingLog?.edit("return", [
|
||
TypingLogField("inserted", .string("\n")),
|
||
TypingLogField("returnKeyType", .string(TypingLogTraits.name(target.returnKeyType ?? .default))),
|
||
TypingLogField("send", .bool(target.returnKeyType == .send)),
|
||
])
|
||
onReturn?()
|
||
insert("\n", source: nil)
|
||
typingLog?.context("return")
|
||
case .layerSwitch:
|
||
// Hold 123, slide to a key, let go: type it and go back.
|
||
if let returnLayer = touch.returnLayer,
|
||
let under = layout.hitTest(point),
|
||
let character = under.character,
|
||
under.kind != touch.key.kind {
|
||
autocorrect.clearPendingUndo()
|
||
insert(character, source: "slide")
|
||
layerState.switchTo(returnLayer)
|
||
rebuildLayout(cause: "layer_slide")
|
||
refreshAutoCapitalization()
|
||
}
|
||
case .emoji:
|
||
onEmojiKey?()
|
||
case .delete, .hex, .globe:
|
||
break
|
||
}
|
||
onChange?()
|
||
}
|
||
|
||
func touchCancelled(id: Int) {
|
||
if activeAccentTouchID == id {
|
||
activeAccentMenu = nil
|
||
activeAccentTouchID = nil
|
||
typingLog?.ui("accent_cancel", [TypingLogField("id", .int(id))])
|
||
}
|
||
guard touches.removeValue(forKey: id) != nil else { return }
|
||
touchOrder.removeAll { $0 == id }
|
||
onChange?()
|
||
}
|
||
|
||
func cancelAllTouches() {
|
||
let hadTouches = !touches.isEmpty || activeAccentMenu != nil
|
||
touches.removeAll()
|
||
touchOrder.removeAll()
|
||
activeAccentMenu = nil
|
||
activeAccentTouchID = nil
|
||
if shift.isHeld {
|
||
shift.shiftUp()
|
||
logState("cancel")
|
||
}
|
||
if hadTouches { onChange?() }
|
||
}
|
||
|
||
// MARK: - Delete
|
||
|
||
/// The delete key repeats after 360 ms, accelerates at 850 ms, and removes whole words after 1.4 s.
|
||
static let repeatDelay: TimeInterval = 0.36
|
||
static let repeatInterval: TimeInterval = 0.075
|
||
static let fastRepeatAfter: TimeInterval = 0.85
|
||
static let wordDeleteAfter: TimeInterval = 1.4
|
||
|
||
func repeatDelete(heldFor: TimeInterval) {
|
||
autocorrect.clearPendingUndo()
|
||
if heldFor >= Self.wordDeleteAfter {
|
||
deleteWordBackward()
|
||
} else if heldFor >= Self.fastRepeatAfter {
|
||
deleteBackward(allowAutocorrectUndo: false, source: "repeat_fast")
|
||
deleteBackward(allowAutocorrectUndo: false, source: "repeat_fast")
|
||
} else {
|
||
deleteBackward(allowAutocorrectUndo: false, source: "repeat")
|
||
}
|
||
}
|
||
|
||
func deleteBackward(allowAutocorrectUndo: Bool = true, source: String = "key") {
|
||
if allowAutocorrectUndo,
|
||
let undo = autocorrect.consumePendingUndo(),
|
||
let before = target.documentContextBeforeInput,
|
||
before.hasSuffix(undo.insertedText) {
|
||
typingLog?.edit("autocorrect_undo", [
|
||
TypingLogField("deleted", .string(undo.insertedText)),
|
||
TypingLogField("inserted", .string(undo.original)),
|
||
])
|
||
for _ in 0..<undo.insertedText.count {
|
||
target.deleteBackward()
|
||
}
|
||
tokenTaps.removeAll()
|
||
target.insertText(undo.original)
|
||
autocorrect.suppressAndKeep(undo.original)
|
||
learning?.record(
|
||
.undone,
|
||
typed: undo.insertedText.trimmingCharacters(in: .whitespaces),
|
||
final: undo.original
|
||
)
|
||
lastSpaceAt = nil
|
||
didEdit()
|
||
return
|
||
}
|
||
autocorrect.clearPendingUndo()
|
||
learning?.willErase(word: AutocorrectEngine.currentToken(in: target.documentContextBeforeInput))
|
||
if let log = typingLog {
|
||
let deleted = target.documentContextBeforeInput?.last.map { String($0) }
|
||
log.edit("delete", [
|
||
deleted.map { TypingLogField("deleted", .string($0)) } ?? TypingLogField("deletedCount", .int(1)),
|
||
TypingLogField("src", .string(source)),
|
||
])
|
||
}
|
||
if let last = target.documentContextBeforeInput?.last, last.isLetter || last == "'", !tokenTaps.isEmpty {
|
||
tokenTaps.removeLast()
|
||
} else {
|
||
tokenTaps.removeAll()
|
||
}
|
||
target.deleteBackward()
|
||
lastSpaceAt = nil
|
||
didEdit()
|
||
}
|
||
|
||
func deleteWordBackward() {
|
||
autocorrect.clearPendingUndo()
|
||
guard let before = target.documentContextBeforeInput, !before.isEmpty else {
|
||
deleteBackward(allowAutocorrectUndo: false, source: "repeat_word")
|
||
return
|
||
}
|
||
learning?.willErase(word: AutocorrectEngine.currentToken(in: before))
|
||
var count = 0
|
||
var index = before.endIndex
|
||
while index > before.startIndex, before[before.index(before: index)].isWhitespace {
|
||
index = before.index(before: index)
|
||
count += 1
|
||
}
|
||
while index > before.startIndex, !before[before.index(before: index)].isWhitespace {
|
||
index = before.index(before: index)
|
||
count += 1
|
||
}
|
||
tokenTaps.removeAll()
|
||
typingLog?.edit("delete_word", [
|
||
TypingLogField("deleted", .string(String(before.suffix(max(1, count))))),
|
||
TypingLogField("src", .string("repeat_word")),
|
||
])
|
||
for _ in 0..<max(1, count) {
|
||
target.deleteBackward()
|
||
}
|
||
lastSpaceAt = nil
|
||
didEdit()
|
||
typingLog?.context("delete_word")
|
||
}
|
||
|
||
// MARK: - Typing
|
||
|
||
private func commitCharacter(_ key: KeyboardKey, at point: CGPoint) {
|
||
guard let character = key.character else { return }
|
||
let text = layerState.layer == .letters && shift.isUppercase ? character.uppercased() : character
|
||
if layerState.layer == .letters {
|
||
shift.didType()
|
||
}
|
||
autocorrect.clearPendingUndo()
|
||
insert(text, source: "key", at: point)
|
||
logState("typed")
|
||
}
|
||
|
||
/// The taps of the word being typed when every letter came from a key, else nil.
|
||
private var currentTokenTaps: [CGPoint]? {
|
||
let taps = tokenTaps.compactMap { $0 }
|
||
return taps.count == tokenTaps.count && !taps.isEmpty ? taps : nil
|
||
}
|
||
|
||
private func commitAccentSelection(_ chosen: String) {
|
||
if layerState.layer == .letters {
|
||
shift.didType()
|
||
}
|
||
autocorrect.clearPendingUndo()
|
||
insert(chosen, source: "accent")
|
||
logState("typed")
|
||
}
|
||
|
||
private func typeSpace() {
|
||
let now = clock()
|
||
if DoubleSpacePeriod.shouldReplace(before: target.documentContextBeforeInput, lastSpaceAt: lastSpaceAt, now: now) {
|
||
autocorrect.clearPendingUndo()
|
||
typingLog?.edit("double_space_period", [
|
||
TypingLogField("deleted", .string(" ")),
|
||
TypingLogField("inserted", .string(". ")),
|
||
])
|
||
target.deleteBackward()
|
||
target.insertText(". ")
|
||
tokenTaps.removeAll()
|
||
lastSpaceAt = nil
|
||
layerState.didInsert(" ")
|
||
rebuildLayoutIfNeeded()
|
||
didEdit()
|
||
typingLog?.context("space")
|
||
return
|
||
}
|
||
learning?.didFinish(word: AutocorrectEngine.currentToken(in: target.documentContextBeforeInput))
|
||
syncLearning()
|
||
autocorrect.decoderTaps = currentTokenTaps
|
||
if let (original, replacement) = autocorrect.replacementOnSpace(
|
||
beforeInput: target.documentContextBeforeInput,
|
||
field: field,
|
||
autocorrectionType: target.autocorrectionType
|
||
) {
|
||
for _ in 0..<original.count {
|
||
target.deleteBackward()
|
||
}
|
||
let inserted = replacement + " "
|
||
tokenTaps.removeAll()
|
||
typingLog?.edit("autocorrect", [
|
||
TypingLogField("from", .string(original)),
|
||
TypingLogField("to", .string(replacement)),
|
||
TypingLogField("deleted", .string(original)),
|
||
TypingLogField("inserted", .string(inserted)),
|
||
])
|
||
target.insertText(inserted)
|
||
autocorrect.recordAppliedCorrection(original: original, insertedText: inserted)
|
||
learning?.record(.autocorrected, typed: original, final: replacement)
|
||
lastSpaceAt = now
|
||
layerState.didInsert(" ")
|
||
rebuildLayoutIfNeeded()
|
||
didEdit()
|
||
typingLog?.context("space")
|
||
return
|
||
}
|
||
autocorrect.clearPendingUndo()
|
||
insert(" ", source: "key")
|
||
lastSpaceAt = now
|
||
typingLog?.context("space")
|
||
}
|
||
|
||
/// `source` names the edit in typing logs; nil when the caller writes its own line.
|
||
private func insert(_ text: String, source: String?, at point: CGPoint? = nil) {
|
||
if text.count == 1, text.first?.isLetter == true {
|
||
tokenTaps.append(point)
|
||
} else {
|
||
tokenTaps.removeAll()
|
||
}
|
||
if let source {
|
||
typingLog?.edit("insert", [
|
||
TypingLogField("inserted", .string(text)),
|
||
TypingLogField("src", .string(source)),
|
||
])
|
||
}
|
||
target.insertText(text)
|
||
lastSpaceAt = nil
|
||
layerState.didInsert(text)
|
||
rebuildLayoutIfNeeded()
|
||
didEdit()
|
||
}
|
||
|
||
/// Hands what the journal learned (typos, rejected corrections) to autocorrect;
|
||
/// nothing while Learn how I type is off.
|
||
private func syncLearning() {
|
||
autocorrect.applyLearning(journal?.typingLearning ?? TypingLearning())
|
||
}
|
||
|
||
private func didEdit() {
|
||
refreshAutoCapitalization()
|
||
refreshSuggestions()
|
||
onEdit?()
|
||
}
|
||
|
||
// MARK: - Layout
|
||
|
||
private func rebuildLayoutIfNeeded() {
|
||
if layout.layer != layerState.layer {
|
||
rebuildLayout(cause: "layer_auto")
|
||
}
|
||
}
|
||
|
||
private func rebuildLayout(cause: String = "layout") {
|
||
layout = KeyboardLayout(
|
||
width: width,
|
||
orientation: orientation,
|
||
layer: layerState.layer,
|
||
field: field,
|
||
showsGlobe: showsGlobe,
|
||
showsEmoji: showsEmoji,
|
||
horizontalInset: horizontalInset,
|
||
language: language
|
||
)
|
||
syncDecoderKeys()
|
||
logState(cause)
|
||
}
|
||
|
||
/// The letter keys Spatial autocorrect scores taps against: this layout's, moved by
|
||
/// `tapOffsets`. None off the letters page.
|
||
private func syncDecoderKeys() {
|
||
autocorrect.decoderKeys = TypingDecoder.Keys(layout: layout, offsets: tapOffsets)
|
||
}
|
||
|
||
/// Hands the layout and shift to typing logs, which writes a line when either changed.
|
||
func logState(_ cause: String) {
|
||
typingLog?.keyboardState(layout: layout, shift: shift, cause: cause)
|
||
}
|
||
}
|