hex/ios/HEXShared/FullKeyboard/TypingConfig/TypingConfigStore.swift
Ryan Vogel dfb877d1e4 ios: typing config review: the person's keyboards, each part's evidence and place, cleaned text
The phone lane's three requests for TypingConfigReview (#2529 renders it):
- Keyboards, not one guessed context:
  - The keyboard records each letters keyboard it runs on, with the experiment on and Full
    Access, in typingConfig.keyboards (TypingConfigKeyboard: context plus KeyboardZoneGeometry),
    most recent first, at most 8, written only when the list changes.
  - TypingConfigReview(data:keyboards:) checks each key block against all of them: a block
    applies on the first keyboard it matches, a second block for that keyboard is a duplicate,
    and one that matches none is forAnotherKeyboard, with its differences from the nearest.
  - ContextCheck gains keyboardIndex, and keyboard is the matched or nearest one. Applied.blocks
    holds every applying block; Applied.aim and .zones are keyboard 0's.
  - compiled(switchedOn:) keeps every applying block, and the keyboard picks the one for its
    layout.
  - The zone compiler moved onto KeyboardZoneGeometry so recorded keyboards can be checked.
    KeyboardLayout.zoneMap wraps it, with the same results.
- Evidence and place on every Item: list (file, keep, neverCorrectTo, fixes, dictation,
  keyBlocks, aim, zones), position in it, block, the file's evidence, and the cleaned text, so
  "Words to keep, number 6" comes from the result alone.
- Cleaned text (TypingConfigText) for the note and every word, fix and dictation fix, so the
  sheet and the keyboard use the same strings.
  - Removed: controls (Cc), bidi embeddings, overrides, isolates and marks (U+202A-202E,
    U+2066-2069, U+200E, U+200F, U+061C), and invisible format characters (Cf: U+200B, U+2060,
    U+FEFF, U+00AD, ...).
  - ZWNJ and ZWJ are kept only between letters or marks of Arabic and Persian, Syriac, the Indic
    scripts, Sinhala, Myanmar and Khmer, and ZWJ between emoji. Tag characters are kept after a
    black flag.
  - Words are NFC-normalised and trimmed. A word that loses anything from inside it is skipped
    with the new Reason hiddenCharacters (after invalidValue in the order); one empty after
    cleaning is invalidValue. The note is cleaned, then cut at 280.
- The reference's "Reading" and "On the phone" sections and docs/typing-configs.md say so.

Verified on the Studio (iPhone 17 Pro, iOS 27.2):
- FullKeyboardEngineTests: 163 of 163 pass, including two new cases in
  FullKeyboardEngineTests+AdaptiveTouch.swift.
  - Four blocks on upright and sideways keyboards: English upright and sideways apply, French is
    forAnotherKeyboard with differences [language, letters], a second upright block is a
    duplicate, compiled keeps both applying blocks, the keyboard picks each on its own layout,
    and recording dedupes most-recent-first.
  - Cleaning: an override, a zero-width space, a Latin ZWJ and a fix with an isolate are
    hiddenCharacters. A Persian word keeps its ZWNJ, a Devanagari conjunct its ZWJ, and a
    decomposed café becomes NFC. The note loses its newline and override and is cut at 280.
  - The first review case also checks list, position and evidence.
- TypingLogTests: 12 of 12 pass.
2026-11-23 12:47:08 -05:00

67 lines
2.9 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters

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

import Foundation
/// Settings › Experiments › Typing › Typing configs (off by default) and the App Group keys
/// the app and the keyboard share for it (`reference/typing-config.md`, "On the phone").
nonisolated struct TypingConfigSettings {
enum Keys {
static let enabled = "experiments.typingConfigs"
/// Bumped whenever `TypingConfigs/active.json` is written or removed.
static let generation = "typingConfig.generation"
/// The keyboards the keys have run on (`TypingConfigKeyboard`), JSON.
static let keyboards = "typingConfig.keyboards"
}
var defaults: UserDefaults? = UserDefaults(suiteName: KeyboardBridge.appGroup)
var isEnabled: Bool {
get { defaults?.bool(forKey: Keys.enabled) ?? false }
nonmutating set { defaults?.set(newValue, forKey: Keys.enabled) }
}
var generation: Int { defaults?.integer(forKey: Keys.generation) ?? 0 }
func bumpGeneration() {
defaults?.set(generation + 1, forKey: Keys.generation)
}
}
/// `TypingConfigs/active.json` in the App Group: the compiled config the keyboard reads. The
/// app writes and removes it (`TypingConfigReview.compiled`); the keyboard only reads it, with
/// Full Access, and a missing or unreadable file is no config.
nonisolated struct TypingConfigStore {
static let folder = "TypingConfigs"
static let activeFile = "active.json"
var settings = TypingConfigSettings()
var directory: URL? = FileManager.default
.containerURL(forSecurityApplicationGroupIdentifier: KeyboardBridge.appGroup)?
.appendingPathComponent(folder, isDirectory: true)
var activeURL: URL? { directory?.appendingPathComponent(Self.activeFile) }
/// Writes `config` as the active one, atomically (a temporary file, then a rename), and
/// bumps the generation so a running keyboard reloads it.
func writeActive(_ config: TypingConfigFile) throws {
guard let directory, let url = activeURL else { throw CocoaError(.fileNoSuchFile) }
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
let encoder = JSONEncoder()
encoder.outputFormatting = [.sortedKeys]
try encoder.encode(config).write(to: url, options: [.atomic])
settings.bumpGeneration()
}
/// Hex defaults: no active config.
func removeActive() {
if let url = activeURL { try? FileManager.default.removeItem(at: url) }
settings.bumpGeneration()
}
/// The active file's bytes, or nil when the experiment is off, without Full Access, or
/// when there is none or it is larger than a config may be.
func activeData(fullAccess: Bool) -> Data? {
guard fullAccess, settings.isEnabled, let url = activeURL,
let size = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize,
size <= TypingConfigLimits.maxBytes else { return nil }
return try? Data(contentsOf: url)
}
}