hex/ios/HEXShared/TypingLog/TypingLogger.swift
Ryan Vogel 08cd058df8
iOS: swipe typing for English and Spanish (Experiment, off by default) (#2106)
* iOS keyboard: a swipe-typing decoder for English and Spanish

SwipeDecoder reads a finger's path across the letter keys as a word, for
the Swipe typing experiment (wired into the keys in the next commit). It
is a shape-matching decoder after SHARK2, written for Hex, on the existing
Google Books typing models (en.hextm, es.hextm) and nothing else:

- the path is resampled to 32 points in key pitches;
- words come straight from the memory-mapped model: its sorted word list
  gives each start letter as one range (TypingDecoderModel.withCodes reads
  codes in place), kept when their last key is near the lift, every key is
  near the path and their ideal path is about as long. No index is built
  or kept between swipes, so the decoder adds no memory at rest;
- each is scored on location (point by point, then DTW for the best 80,
  after a cheap prefilter caps loose swipes at 1,500 words), shape, and a
  heavy-tailed start and end key cost, and weighed with the model's
  word-pair frequency after the word before (stupid backoff, as Spatial
  autocorrect's).

English contractions are read as extra words in three frequency tiers:
Google Books splits "don't" into "do n't", so the model ranks it like
"tom" and lacks "I'm" entirely. Slurs are never read and swear words only
when allowed (TypingDecoder.NeverSuggest from OffensiveWords).

Weights were tuned on synthetic swipes (clean, neat, typical, sloppy
fingers) of the autocorrect benchmark's held-out dev sentences, through
Hex's real 390 pt key geometry; the test sentences were used once, at
the end. Held-out test, typical fingers: English top-1 94.9% / top-3
99.1% (top-5k words 95.9%), Spanish 91.1% / 98.4% (93.7%); decode median
0.78 ms, p99 2.6-2.8 ms, max 4.2 ms on an M5 Max.

Verified: SwipeDecoderTests (new file: the decoder's own fixtures are
paths) pass on an iPhone 13 simulator, iOS 27.2: clean and offset swipes,
Spanish accents and ñ, contractions, context, slurs and swear words.

* iOS keyboard: Swipe typing, an experiment off by default (English and Spanish)

Two TestFlight testers asked for glide typing. Settings › Experiments ›
Swipe typing (off by default, App Group experiments.swipeTyping, launch
argument --experiment-swipe) lets a finger slide from a letter through a
word's letters, as Apple's QuickPath and Gboard do, on the English and
Spanish layouts only; every other layout keeps a drag as a slide to
another key, and VoiceOver keeps its own typing.

- SwipeTyping (new file) owns the gesture: a touch that goes down on a
  letter and travels more than a key's pitch (width plus gap) becomes a
  swipe; its key no longer types (FullKeyboardEngine.beginSwipe), a light
  trail (a CAShapeLayer with the last 0.45 s of the path, no bitmap)
  follows the finger, and the strip shows the word the path reads as so
  far, decoded off the main thread at most every 70 ms. Lifting decodes
  on the main thread and types the word.
- FullKeyboardEngine's swipe section types it after a space unless the
  text before ends in a space, a line break or opening punctuation;
  shift capitalises its first letter (caps lock all of it), the added
  space can start a sentence, and a name the dictionary only knows
  capitalised is capitalised. The strip then offers the next three
  readings (KeyboardSuggestion.Kind.swiped, likeliest in the centre);
  tapping one replaces the word. Until anything else edits the text,
  delete takes the whole word back with its space and space never
  autocorrects it (small guards in deleteBackward and typeSpace; insert,
  textDidChange, the trackpad and a new field clear it). A second finger
  ends a swipe first, so its word goes before that key's letter.
- Readings pass AutocorrectEngine.mayOffer: no slurs, swear words only
  with Suggest swear words on. The decoder also reads Hex's English
  contractions and your own words (AutocorrectEngine.ownWords: Contacts
  names and other UILexicon terms, one-word text replacements, kept
  words), rebuilt when ownWordsRevision changes.
- Typing logs record swipe_start and swipe_end (points, decode ms,
  readings) beside the touch moves, to fit the decoder to real fingers.
- Taps, accents, delete repeat and delete's word slide, the space bar's
  trackpad, 123 and the Hex key are unchanged: no swipe starts on them,
  and none while an accent menu is open.

The Experiments row's two new strings have zh-Hans translations
(滑行键入, Apple's name for QuickPath). README documents the experiment.

Verified on an iPhone 13 simulator (iOS 27.2): the full HEXMobileTests
suite, 322 tests, 0 failures (1 skipped, as before), including 12 new
FullKeyboardEngineTests cases for spacing, capitals, caps lock, delete,
the readings, space, taps/slides/accents, delete and the space bar,
layout gating, Spanish, a second finger, cancel, and offensive words.

* iOS keyboard: swipe_end logs decode time to the microsecond; the trail stops off screen

- Record typing logs' swipe_end line wrote the decode time rounded to whole
  milliseconds, which reads 0 or 1 for nearly every swipe (decode is about
  a millisecond); it now uses TypingLogValue.ms (three decimals), as the
  logs' other timings do.
- SwipeTrailView's display link holds the view: if the keyboard's view left
  its window mid-swipe, the link would keep redrawing an unseen trail. It
  now stops (and the trail clears) when the view leaves its window, and
  never starts without one (tests drive the plane off screen).

Verified: built for the iPhone 13 simulator (iOS 27.2); in a live keyboard
in Messages, swipe_end lines carry fractional ms and the trail fades on
lift as before.

* iOS keyboard: Swipe typing after the multilingual keyboard and #2100

Rebased onto the multilingual keyboard (#2104), dictation styles (#2103)
and #2100's strip and space changes:

- A swipe's lift now counts as a key coming up for #2100's strip guard
  (FullKeyboardEngine.lastKeyTouchAt): a quick tap on the strip's lower
  half right after a swipe types the row-1 key below it, as after any key,
  instead of picking one of the swipe's readings. The swipe never reached
  touchEnded, so the guard only saw its touch-down.
- The trackpad's start (now startTrackpad, for both a slide and #2100's
  hold) clears the swiped word, as the slide did before.
- Swipe typing follows the language the space bar switches to: syncLanguage
  (which #2104 calls on every switch) also syncs it, so it is on only while
  the current language is English or Spanish, with that language's model.
  A quick slide along the space bar stays a language swipe: swipes start
  only on letter keys.

Spacing composes with #2100: a swiped word is typed with didEdit, which
clears the swallowed-suggestion-space state, and adds no trailing space,
so a space typed after it is always one space.

Verified: the full HEXMobileTests suite on an iPhone 13 simulator (iOS
27.2), 348 tests, 0 failures (1 skipped, as on dev), including the new
testSwipeTypingFollowsALiveLanguageSwitch (English, German, Spanish) and
a space-bar language swipe with Swipe typing on.

* iOS keyboard: Swipe typing reads across the iPhone Duo's split keyboard

#2105 splits the keyboard on the Duo unfolded upright: two halves, G and V
on both, and nothing in the middle. TypingDecoder.Keys already places every
key as on the unsplit keyboard (KeyboardLayout.unsplitX), so the decoder's
letter centres were right, but a swipe's points were read where they were
drawn, so the right half's strokes landed a gap away from their keys.

Swipe points are now read where KeyboardLayout.joinedForSwipe puts them:
the right half pushed against the left, as unsplitX does, and the middle
between the halves squeezed to one key's gap, so a stroke across it stays
one continuous stroke (unsplitX alone would jump it back by the gap), as
Gboard joins the halves. Either half's G and V is the one letter. On the
split, a touch becomes a swipe after the split's own key pitch, 57 pt
(KeyboardLayout.swipePitch); the trail still follows the finger where it is.

Benchmark (synthetic swipes of the held-out dev sentences on Apple's split
geometry at 801 pt, G and V taken on the side nearer the neighbouring
letter): English top-1 95.4% / top-3 99.3% with typical fingers (97.9%
clean), Spanish 90.0% / 97.9% (93.9% clean), as on the phone layout.

Verified: the full HEXMobileTests suite on an iPhone 13 simulator (iOS
27.2), 356 tests, 0 failures (1 skipped, as on dev), including the new
testASwipeReadsAcrossTheSplitKeyboardsMiddle ("hello", "the", "keyboard"
across the middle; "give" from the right half's G). AXe can't touch the
Duo's inner screen (#2105), so the split was not swiped live.
2026-11-20 22:30:53 +00:00

552 lines
22 KiB
Swift

import CoreGraphics
import QuartzCore
import UIKit
/// Record typing logs, on the main thread: turns what the keyboard does into events, keeps
/// them in memory, and hands them to `TypingLogStore` every 2 s, when the keyboard goes
/// away, and on a memory warning. Exists only while the experiment is on.
@MainActor
final class TypingLogger {
static let flushInterval: TimeInterval = 2
static let maxBuffered = 1500
static let contextLimit = 200
/// A moving finger is written once it has gone this far and this long since its last line.
static let moveMinInterval: TimeInterval = 0.008
static let moveMinDistance: CGFloat = 2
private static var shared: TypingLogger?
/// The one logger this process writes while the experiment is on; nil while it is off.
static func sharedIfEnabled(settings: TypingLogSettings = TypingLogSettings()) -> TypingLogger? {
guard settings.isEnabled else {
shared?.endSession(reason: "disabled")
shared = nil
return nil
}
if let shared { return shared }
let logger = TypingLogger(store: TypingLogStore())
logger.store.prune()
shared = logger
return logger
}
let store: TypingLogStore
var wallClock: () -> TimeInterval = { Date().timeIntervalSince1970 }
var monoClock: () -> TimeInterval = { CACurrentMediaTime() }
/// The host's text around the cursor (`documentContextBeforeInput`/`AfterInput`).
var contextSource: (() -> TypingLogContext)?
private struct LayoutInputs: Equatable {
var width: CGFloat
var orientation: KeyboardOrientation
var layer: KeyboardLayer
var field: KeyboardFieldKind
var showsGlobe: Bool
var horizontalInset: CGFloat
var placement: HexKeyPlacement
init(_ layout: KeyboardLayout) {
width = layout.width
orientation = layout.orientation
layer = layout.layer
field = layout.field
showsGlobe = layout.showsGlobe
horizontalInset = layout.horizontalInset
placement = HexKeyPlacement.current
}
}
private struct Move {
var time: TimeInterval
var point: CGPoint
var key: String?
}
private struct Session {
let id: String
let startedAt: TimeInterval
let skipped: Bool
var seq = 0
var touches = 0
var edits = 0
var layoutInputs: LayoutInputs?
var layout: KeyboardLayout?
var layoutHash: String?
var shift: ShiftState?
var shiftHeld = false
var viewSize: CGSize = .zero
var safeArea: UIEdgeInsets = .zero
/// The view's size or safe area changed since the last `layout` line.
var geometryChanged = false
var context: TypingLogContext?
var shownCandidates: [KeyboardSuggestion]?
var candidates: [KeyboardSuggestion] = []
var moves: [Int: Move] = [:]
var dictations = 0
}
private var session: Session?
private var buffer: [TypingLogEvent] = []
private var timer: Timer?
/// The last dictation logged, which an outcome refers to.
private var lastDictation: (session: String, seq: Int)?
init(store: TypingLogStore) {
self.store = store
}
/// A session is open and its field may be logged.
var isRecording: Bool { session?.skipped == false }
var sessionID: String? { session?.id }
// MARK: - Sessions
/// The keyboard appeared, or moved to another field. Logs `session_start`, or one
/// `skipped` line and nothing else until the session ends when the field must not be logged.
func beginSession(_ info: TypingLogSessionInfo) {
if session != nil { endSession(reason: "replaced") }
let id = String(UUID().uuidString.replacingOccurrences(of: "-", with: "").prefix(12)).lowercased()
if let reason = info.traits.skipReason {
session = Session(id: id, startedAt: monoClock(), skipped: true)
emit("skipped", [
TypingLogField("reason", .string(reason)),
TypingLogField("trigger", .string(info.trigger)),
TypingLogField("surface", .string(info.surface)),
TypingLogField("keyboardType", .string(info.traits.keyboardType)),
TypingLogField("textContentType", .text(info.traits.textContentType)),
TypingLogField("secure", .bool(info.traits.isSecure)),
], force: true)
flush()
return
}
session = Session(id: id, startedAt: monoClock(), skipped: false)
emit("session_start", info.fields)
context("session_start", force: true)
startTimer()
}
func endSession(reason: String) {
guard let current = session else { return }
if !current.skipped {
emitPendingCandidates()
context("session_end")
emit("session_end", [
TypingLogField("reason", .string(reason)),
TypingLogField("durationMS", .ms((monoClock() - current.startedAt) * 1000)),
TypingLogField("touches", .int(current.touches)),
TypingLogField("edits", .int(current.edits)),
TypingLogField("dictations", .int(current.dictations)),
])
}
session = nil
timer?.invalidate()
timer = nil
flush()
store.close()
}
/// Hands buffered events to the writer.
func flush() {
guard !buffer.isEmpty else { return }
store.append(buffer)
buffer.removeAll(keepingCapacity: true)
}
private func startTimer() {
timer?.invalidate()
let timer = Timer(timeInterval: Self.flushInterval, repeats: true) { [weak self] _ in
MainActor.assumeIsolated { self?.flush() }
}
timer.tolerance = 0.5
RunLoop.main.add(timer, forMode: .common)
self.timer = timer
}
// MARK: - Keys
/// The layout or shift changed (or may have): writes a `layout` line when either did.
/// The key list goes in full the first time a layout appears in a day's file.
func keyboardState(layout: KeyboardLayout, shift: ShiftStateMachine, cause: String) {
guard var current = session, !current.skipped else { return }
let inputs = LayoutInputs(layout)
let layoutChanged = inputs != current.layoutInputs
guard layoutChanged || shift.state != current.shift || shift.isHeld != current.shiftHeld else { return }
if layoutChanged {
current.layoutInputs = inputs
current.layout = layout
current.layoutHash = Self.hash(layout)
}
current.shift = shift.state
current.shiftHeld = shift.isHeld
session = current
emitLayout(cause: cause)
}
/// The keyboard view's size or safe area, before the layout follows it. The next
/// `layout` line carries it; `commitGeometry` writes one if the layout didn't change.
func viewGeometry(size: CGSize, safeArea: UIEdgeInsets) {
guard var current = session, !current.skipped,
size != current.viewSize || safeArea != current.safeArea else { return }
current.viewSize = size
current.safeArea = safeArea
current.geometryChanged = true
session = current
}
func commitGeometry() {
guard let current = session, !current.skipped, current.geometryChanged, current.layout != nil else { return }
emitLayout(cause: "geometry")
}
private func emitLayout(cause: String) {
session?.geometryChanged = false
guard let current = session, let layout = current.layout, let hash = current.layoutHash else { return }
var fields = [
TypingLogField("hash", .string(hash)),
TypingLogField("cause", .string(cause)),
TypingLogField("layer", .string(Self.name(layout.layer))),
TypingLogField("shift", .string(Self.name(current.shift ?? .off))),
TypingLogField("field", .string(Self.name(layout.field))),
TypingLogField("orientation", .string(layout.orientation == .portrait ? "portrait" : "landscape")),
TypingLogField("width", .pt(layout.width)),
TypingLogField("height", .pt(layout.totalHeight)),
TypingLogField("view", .array([.pt(current.viewSize.width), .pt(current.viewSize.height)])),
TypingLogField("safeArea", TypingLogSessionInfo.insets(current.safeArea)),
TypingLogField("horizontalInset", .pt(layout.horizontalInset)),
TypingLogField("globe", .bool(layout.showsGlobe)),
TypingLogField("hexPlacement", .string(HexKeyPlacement.current.rawValue)),
TypingLogField("language", .string(layout.language.rawValue)),
]
if current.shiftHeld {
fields.insert(TypingLogField("shiftHeld", .bool(true)), at: 4)
}
emit("layout", fields, detail: TypingLogEvent.Detail(key: hash) { Self.layoutDetail(layout) })
}
nonisolated private static func layoutDetail(_ layout: KeyboardLayout) -> [TypingLogField] {
let m = layout.metrics
let strip = layout.stripFrame
let slotWidth = strip.width / 3
let slots = (0..<3).map { index in
TypingLogValue.rect(CGRect(x: strip.minX + CGFloat(index) * slotWidth, y: strip.minY, width: slotWidth, height: strip.height))
}
let keys = layout.keys.map { key in
TypingLogValue.object([
TypingLogField("id", .string(keyID(key.kind))),
TypingLogField("label", .string(key.label)),
TypingLogField("row", .int(key.row)),
TypingLogField("frame", .rect(key.frame)),
TypingLogField("hitFrame", .rect(key.hitFrame)),
])
}
return [
TypingLogField("letterWidth", .pt(layout.letterWidth)),
TypingLogField("metrics", .object([
TypingLogField("side", .pt(m.side)),
TypingLogField("gap", .pt(m.gap)),
TypingLogField("rowGap", .pt(m.rowGap)),
TypingLogField("keyHeight", .pt(m.keyHeight)),
TypingLogField("stripHeight", .pt(m.stripHeight)),
TypingLogField("keysBottom", .pt(m.keysBottom)),
TypingLogField("cornerRadius", .pt(m.cornerRadius)),
])),
TypingLogField("strip", .rect(strip)),
TypingLogField("slots", .array(slots)),
TypingLogField("keys", .array(keys)),
]
}
/// A finger on the keys. `key` is the key the engine holds it on (for `began`, the
/// key it is about to press); `under` is written when the key under the raw point differs.
func touch(_ phase: TypingLogTouchPhase, id: Int, sample: TypingLogTouchSample, key: KeyboardKey?, under: KeyboardKey? = nil) {
guard var current = session, !current.skipped else { return }
let keyName = key.map { Self.keyID($0.kind) }
switch phase {
case .began:
emitPendingCandidates()
current = session ?? current
current.touches += 1
current.moves[id] = Move(time: sample.timestamp, point: sample.point, key: keyName)
case .moved:
if let last = current.moves[id] {
let distance = hypot(sample.point.x - last.point.x, sample.point.y - last.point.y)
let slid = keyName != last.key
guard slid || (distance >= Self.moveMinDistance && sample.timestamp - last.time >= Self.moveMinInterval) else {
return
}
}
current.moves[id] = Move(time: sample.timestamp, point: sample.point, key: keyName)
case .ended, .cancelled:
current.moves.removeValue(forKey: id)
}
session = current
var fields = [
TypingLogField("phase", .string(phase.rawValue)),
TypingLogField("id", .int(id)),
TypingLogField("x", .pt(sample.point.x)),
TypingLogField("y", .pt(sample.point.y)),
TypingLogField("r", .pt(sample.majorRadius)),
TypingLogField("rt", .pt(sample.majorRadiusTolerance)),
TypingLogField("ts", .ms(sample.timestamp * 1000)),
TypingLogField("layout", .text(current.layoutHash)),
TypingLogField("key", .text(keyName)),
]
if sample.maximumPossibleForce > 0 {
fields.insert(TypingLogField("force", .number(Double(sample.force), places: 3)), at: 6)
fields.insert(TypingLogField("maxForce", .number(Double(sample.maximumPossibleForce), places: 3)), at: 7)
}
if let under, under.kind != key?.kind {
fields.append(TypingLogField("under", .string(Self.keyID(under.kind))))
} else if under == nil, phase != .moved, key != nil {
fields.append(TypingLogField("under", .null))
}
emit("touch", fields)
}
/// Something the keys did to the text.
func edit(_ op: String, _ fields: [TypingLogField] = []) {
guard session?.skipped == false else { return }
session?.edits += 1
emit("edit", [TypingLogField("op", .string(op))] + fields)
}
/// A tap on the strip, the Hex key or its menu, an accent picker, or the trackpad.
func ui(_ action: String, _ fields: [TypingLogField] = []) {
emit("ui", [TypingLogField("action", .string(action))] + fields)
}
/// The suggestions the strip shows. Written lazily: before the next touch goes down,
/// with a pick, or when the session ends, so a line is what was on screen.
func suggestionsChanged(_ suggestions: [KeyboardSuggestion]) {
guard session?.skipped == false else { return }
session?.candidates = suggestions
}
var shownSuggestions: [KeyboardSuggestion] { session?.candidates ?? [] }
private func emitPendingCandidates() {
guard let current = session, !current.skipped, current.candidates != current.shownCandidates else { return }
session?.shownCandidates = current.candidates
emit("candidates", [TypingLogField("items", Self.candidates(current.candidates))])
}
static func candidates(_ suggestions: [KeyboardSuggestion]) -> TypingLogValue {
.array(suggestions.enumerated().map { index, suggestion in
var fields = [
TypingLogField("slot", .int(index)),
TypingLogField("text", .string(suggestion.displayText)),
]
if suggestion.replacement != suggestion.displayText {
fields.append(TypingLogField("replacement", .string(suggestion.replacement)))
}
switch suggestion.kind {
case .keepLiteral:
fields.append(TypingLogField("kind", .string("literal")))
case .primary(let auto):
fields.append(TypingLogField("kind", .string("primary")))
fields.append(TypingLogField("auto", .bool(auto)))
case .secondary:
fields.append(TypingLogField("kind", .string("secondary")))
case .emoji:
fields.append(TypingLogField("kind", .string("emoji")))
case .swiped:
fields.append(TypingLogField("kind", .string("swiped")))
}
return .object(fields)
})
}
// MARK: - Text
/// The host's text around the cursor, after a word, a return, a dictation, or a change
/// from outside the keys. Identical context is written once. `cleared` marks the host
/// emptying a field that had text (most apps do that when they send).
func context(_ why: String, force: Bool = false) {
guard var current = session, !current.skipped, let read = contextSource?() else { return }
guard force || read != current.context else { return }
let previous = current.context
current.context = read
session = current
var fields = [
TypingLogField("why", .string(why)),
TypingLogField("before", .text(read.before.map { String($0.suffix(Self.contextLimit)) })),
TypingLogField("after", .text(read.after.map { String($0.prefix(Self.contextLimit)) })),
TypingLogField("beforeLength", read.before.map { .int($0.count) } ?? .null),
TypingLogField("afterLength", read.after.map { .int($0.count) } ?? .null),
TypingLogField("hasText", .bool(read.hasText)),
]
if let previous, !read.hasText,
previous.hasText || !(previous.before ?? "").isEmpty || !(previous.after ?? "").isEmpty {
fields.append(TypingLogField("cleared", .bool(true)))
}
emit("context", fields)
}
// MARK: - Dictation
/// Hex inserted a dictation's text.
func dictation(source: String, resultID: String?, style: String, stages: DictationStages?, delivered: String, inserted: String) {
guard var current = session, !current.skipped else { return }
current.dictations += 1
session = current
var fields = [
TypingLogField("source", .string(source)),
TypingLogField("resultID", .text(resultID)),
TypingLogField("style", .string(stages?.style ?? style)),
]
if let stages { fields += stages.fields }
fields += [
TypingLogField("text", .string(delivered)),
TypingLogField("inserted", .string(inserted)),
]
let seq = emit("dictation", fields)
lastDictation = seq.map { (current.id, $0) }
context("dictation")
}
/// What became of a dictation (`DictationEditTracker`): it always concerns the latest
/// `dictation` line written before it, which `dictation`/`dictationSession` name.
func dictationOutcome(_ result: DictationEditResult) {
var fields = [
TypingLogField("outcome", .string(result.outcome.rawValue)),
TypingLogField("words", .int(result.wordCount)),
TypingLogField("changed", .int(result.changedWordCount)),
]
if let lastDictation {
fields.insert(TypingLogField("dictationSession", .string(lastDictation.session)), at: 0)
fields.insert(TypingLogField("dictation", .int(lastDictation.seq)), at: 1)
}
fields.append(TypingLogField("pairs", .array(result.pairs.map { pair in
.object([
TypingLogField("kind", .string(pair.kind.rawValue)),
TypingLogField("heard", .string(pair.heard)),
TypingLogField("inserted", .string(pair.inserted)),
TypingLogField("meant", .string(pair.meant)),
TypingLogField("before", .text(pair.before)),
TypingLogField("after", .text(pair.after)),
])
})))
emit("dictation_outcome", fields)
}
// MARK: - Lines
@discardableResult
private func emit(_ type: String, _ fields: [TypingLogField], detail: TypingLogEvent.Detail? = nil, force: Bool = false) -> Int? {
guard var current = session, force || !current.skipped else { return nil }
current.seq += 1
let seq = current.seq
session = current
buffer.append(TypingLogEvent(
type: type,
wallMS: Int64((wallClock() * 1000).rounded()),
monoMS: monoClock() * 1000,
session: current.id,
seq: seq,
fields: fields,
detail: detail
))
if buffer.count >= Self.maxBuffered { flush() }
return seq
}
// MARK: - Names
/// A key's id in logs: the character itself for character keys (always one character),
/// otherwise a word: `shift`, `delete`, `space`, `return`, `hex`, `globe`, `layer:numbers`.
nonisolated static func keyID(_ kind: KeyKind) -> String {
switch kind {
case .character(let text): text
case .shift: "shift"
case .layerSwitch(let layer): "layer:\(name(layer))"
case .delete: "delete"
case .space: "space"
case .returnKey: "return"
case .hex: "hex"
case .globe: "globe"
case .emoji: "emoji"
}
}
nonisolated static func name(_ layer: KeyboardLayer) -> String {
switch layer {
case .letters: "letters"
case .numbers: "numbers"
case .symbols: "symbols"
}
}
nonisolated static func name(_ field: KeyboardFieldKind) -> String {
switch field {
case .text: "text"
case .url: "url"
case .email: "email"
}
}
nonisolated static func name(_ shift: ShiftState) -> String {
switch shift {
case .off: "off"
case .on: "on"
case .locked: "locked"
}
}
/// 64-bit FNV-1a over every key's kind and frames and the strip, as 16 hex digits.
nonisolated static func hash(_ layout: KeyboardLayout) -> String {
var hash: UInt64 = 0xcbf2_9ce4_8422_2325
func mix(_ text: String) {
for byte in text.utf8 {
hash ^= UInt64(byte)
hash = hash &* 0x0000_0100_0000_01b3
}
}
func mix(_ value: CGFloat) {
// Rounded to 1/100 pt so the hash is the same wherever the same frames come from.
var bits = UInt64(bitPattern: Int64((Double(value) * 100).rounded()))
for _ in 0..<8 {
hash ^= bits & 0xff
hash = hash &* 0x0000_0100_0000_01b3
bits >>= 8
}
}
func mix(_ rect: CGRect) {
mix(rect.minX)
mix(rect.minY)
mix(rect.width)
mix(rect.height)
}
mix(name(layout.layer))
mix(name(layout.field))
mix(layout.orientation == .portrait ? "p" : "l")
mix(layout.stripFrame)
for key in layout.keys {
mix(keyID(key.kind))
mix(key.frame)
mix(key.hitFrame)
}
return String(format: "%016llx", hash)
}
}
extension DictationStages {
var fields: [TypingLogField] {
var fields: [TypingLogField] = []
func add(_ key: String, _ value: String?) {
if let value { fields.append(TypingLogField(key, .string(value))) }
}
add("engine", engine)
add("locale", locale)
add("language", language)
if let recordedMS { fields.append(TypingLogField("recordedMS", .int(recordedMS))) }
if let transcribeMS { fields.append(TypingLogField("transcribeMS", .int(transcribeMS))) }
add("raw", raw)
add("fixed", fixed)
add("spelled", spelled)
add("tagged", tagged)
add("cleaned", cleaned)
add("translated", translated)
add("formatted", formatted)
return fields
}
}