hex/ios/HEXShared/TypingLog/TypingLogger.swift
Ryan Vogel cc75290551
iOS: emoji panel with on-device suggestions (Experiments › Emoji) (#2051)
* iOS: emoji index built from Unicode's emoji list and CLDR

What changed
- scripts/build-emoji-data.py builds HEXShared/FullKeyboard/Emoji/emoji-index-<lang>.txt
  for the four keyboard layouts (en, nb, es, de) from Unicode emoji-test.txt 18.0
  (pinned by SHA-256) and CLDR 49 annotations and annotationsDerived (release-49 tag),
  plus Hex's own chat words in scripts/emoji-aliases-en.txt ("congrats", "bday",
  "lol", "new year"; 336 words, written for Hex).
- Each file holds the catalog in panel order (8 categories, 1,923 emoji, 332 with five
  uniform skin tones), each emoji's English name, its folded search words, and the
  word and phrase postings already weighted (one-word name 1.0, name word 0.75,
  keyword 0.6, keyword-phrase word 0.3, chat word 1.2 down to 0.9, an IDF factor for
  words many emoji share), sorted by key so the keyboard can binary-search the file
  in place. Non-English layouts carry English's words at 0.85.
- LICENSE-Unicode.txt (Unicode License v3) ships beside the data, as the licence
  asks: both emoji-test.txt and CLDR's data are under it, which allows commercial
  use with the notice.

Why
- The emoji panel (next commits) suggests emoji for what you type and searches them
  on the iPhone. Precomputing the index keeps the keyboard extension's heap small:
  the first version built Swift dictionaries at runtime and held 5.7 MB, which
  malloc kept after release; the mapped file plus offsets measures 0.7 MB.

Verified
- The generator runs from a sources folder or downloads the pinned files; output is
  deterministic. Files: en 351 KB, nb 560 KB, es 549 KB, de 610 KB.

* iOS: rank emoji for the text before the cursor, on device

What changed
- EmojiLibrary maps an emoji-index file (Data .alwaysMapped) and keeps only the emoji,
  their skin tones and byte offsets: word and phrase lookups binary-search the file's
  sorted keys and parse postings in place; search scans each emoji's folded name and
  keyword words for prefixes (name words first, a short name the query fills before a
  long one it touches, then your use and everyday emoji). Emoji newer than 15.1 are
  listed only if the emoji font itself draws them as one glyph.
- EmojiSuggester reads the last eight content words (the newest counts 1, then 0.85
  each word back), their forms (plurals, -ing, -ed, held-down letters: "lmaooo"),
  two- to four-word phrases ("new year", "good luck") and the word still being typed;
  an emoji several words point at gains a third of the rest. One emoji per family
  ("man running", "woman running"); your use breaks ties and fills the row, then
  everyday defaults. forFinishedWord gives the strip at most three strong matches for
  the word just finished ("pizza " -> 🍕).
- EmojiUsageStore keeps, in the App Group, a use count per emoji that halves every 10
  days (frequency and recency in one score, at most 120 emoji) and the skin tone last
  picked for each; no words. clear() empties both.
- EmojiRoutedTarget lets the keys type into the emoji search's query instead of the
  field while you search.
- EmojiSemanticIndex (app target only, for the comparison test): Apple's on-device
  NLEmbedding word vectors over the index's 3,257 words, standing in for a context word
  with no emoji of its own. Not used by the keyboard (see Measured).
- EmojiSuggesterTests: index, folding, context, families, endings, other layouts,
  strip, search, history decay and tones, the search's routing, and quality on 60
  hand-written sentences (Fixtures/emoji-context-sentences.json, 30 to tune, 30 held
  out) with and without the embedding.

Measured (sensible emoji in the top 5, context only; top-1 in brackets)
- Simulator, iPhone 17, iOS 27.2: keywords dev 30/30 (27), held-out 30/30 (27), 0.04 ms
  a sentence; with the embedding the same counts at 0.14 ms, its index built in 120 ms.
- Mac harness, same code: CLDR keywords alone dev 26/30 (13), held-out 22/30 (14);
  with Hex's chat words 30/30 (27) and 30/30 (27). A blind set of 40 messages and
  sensible emoji written by a separate agent that saw no code or word lists: CLDR
  alone 30/40 (13), with chat words 37/40 (28), adding the embedding 37/40 (28); 38/40
  after the held-down-letter rule, which those failures suggested. Apple's sentence
  embedding scored 18/40 (7) and took 7.5 s to embed the 1,923 descriptions.
- Memory on the Mac: the mapped index adds 0.72 MB; the embedding adds 5.3 MB (1 MB
  NLEmbedding, 3.9 MB vectors) and none of it came back after release. No measurable
  gain for that, so the keyboard uses keywords and your history only.

Verified: xcodebuild test on an iPhone 17 simulator (iOS 27.2): 245 tests, 1 skipped,
0 failures.

* iOS: emoji panel for the full keyboard (Experiments › Emoji)

What changed
- Experiments › Full keyboard › Emoji (experiments.emoji, off by default; shown with the
  full keyboard): an emoji key (face.smiling) right of 123, after the globe, in plain
  text fields (not URL, email or ASCII-only ones). The bottom row takes the compact
  sizes it uses beside the globe. "Clear emoji history" empties EmojiUsageStore.
- EmojiPanelView replaces the strip and the keys: a row of up to ten suggestions for
  the text before the cursor and your history (one emoji per family, your skin tone),
  a search button; a grid that scrolls sideways through Frequently used (your history,
  then everyday emoji, 16 at least) and the eight categories in four rows of 42 pt
  (three of 38 in landscape), each section's name kept at the left edge while it
  scrolls; a bar with ABC, the categories and a repeating delete, drawn like the
  letter keys' 123 and delete. Holding an emoji with skin tones opens the accent
  picker with its five tones; the pick is typed and remembered for that emoji. Key
  pop-ups and haptics follow their switches.
- Search: the letter keys type into a search field in the strip (EmojiRoutedTarget),
  results above it in a row the keyboard grows 44 pt for, your suggestions while it's
  empty; return, the field's close button or the emoji key go back to the panel.
  Typing logs and Learn how I type see the emoji typed into the field, never the query.
- The strip, when it would be empty after a space, offers the finished word's strong
  emoji ("pizza " -> 🍕, "birthday " -> 🎂 🎉 🥳), a lone one in the centre slot; never
  over word suggestions, Undo dictation, a status or the clipboard chips.
- Grid cells drop their text (and bitmap) when they scroll off and prefetching is off:
  scrolling every section had kept 353 cell bitmaps, 35 MB.
- FullKeyboardView+Emoji.swift holds the wiring; the engine's target is now the routed
  target, which forwards everything to the field unless a search is open.
- Scenes: full-keyboard-emoji, -emoji-search (--emoji-query), -emoji-tones,
  -emoji-food, -emoji-strip (each -dark and -dark-field), and -emoji-probe, which prints
  the panel's footprint and open latency.

Measured in the keyboard extension (Release, iPhone 17 simulator, iOS 27.2, a field
focused with the real HEXKeyboard.appex and a temporary, uncommitted probe; the
simulator counts no GPU memory and reports no headroom), footprint:
  keyboard with the emoji key, nothing loaded   19.0 MB
  after "pizza " (the strip loads the index)    19.0 MB
  panel open                                     28.7 MB
  picked three suggestions, closed               22.7 MB
  every section scrolled                         41.6 MB (peak 48.4; 71.1 before the cell fix)
  closed after that                              36.5 MB
The 17.5 MB left after browsing everything is about 351 emoji glyph images the system's
text rendering caches process-wide (18.7 MB in the heap, 351 CGImages); drawing with a
font instance the panel owns or at 21 pt left it the same, and no public API frees it.
Whether iOS purges it under memory pressure is unverified on an iPhone.
Opening: 22-26 ms from the emoji key to the panel laid out the first time, 12-14 ms
after (median of 10), about 21 ms until committed.

Verified: xcodebuild test (245 tests, 1 skipped, 0 failures); every scene above in
light, dark and dark field looked at on the simulator.

* iOS: document the emoji experiment and keep its blind sentences as a check

What changed
- README: the emoji experiment under Capabilities (what the panel, search, skin tones
  and strip do, what the history keeps, where the index comes from and its licence),
  how to rebuild the index, and its proof limits with the quality, memory and latency
  measurements and what is unverified on an iPhone (whether iOS purges the cached
  emoji glyph images that browsing every section leaves, about 18 MB).
- emoji-context-sentences.json gains the 40-message blind set a separate agent wrote
  without seeing code or word lists; EmojiSuggesterTests scores it beside the other
  60 and fails below 35/40.

Why: the blind set is the least biased quality number; keeping it catches a ranking
change that helps the hand-written sentences at its expense.

Verified: xcodebuild test on an iPhone 17 simulator (iOS 27.2): 245 tests, 1 skipped,
0 failures; EMOJI_QUALITY: dev 30/30 (top-1 27), held-out 30/30 (27), blind 38/40 (29),
the same with the embedding, which built in 101 ms.
2026-11-20 15:53:24 +00:00

550 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 == .ended || phase == .cancelled, 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")))
}
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
}
}