hex/ios/HEXShared/FullKeyboard/TypingConfig/KeyboardZoneMap.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

221 lines
11 KiB
Swift

import CoreGraphics
/// A typing config's zones compiled against one layout: the touch area of every key they
/// change, as disjoint rectangles, and what became of each zone. Every point of the keys'
/// area still belongs to exactly one key, and every key keeps its keycap's centre plus
/// `TypingConfigLimits.zoneKeepFromCentre` of its keycap each way.
nonisolated struct KeyboardZoneMap: Equatable, Sendable {
/// Touch areas by index into `KeyboardLayout.keys`, only for keys whose area changed.
var regions: [Int: [CGRect]] = [:]
/// One per zone, in the order given: nil when it applied, else why it didn't.
var skipped: [TypingConfigReview.Reason?] = []
var isEmpty: Bool { regions.isEmpty }
}
/// What zones are compiled against: every key's id, row, keycap and touch area, the letter
/// keycap's size and the touch area, from a live layout or as the keyboard recorded it
/// (`TypingConfigKeyboard`), so the app can check a config against keyboards it can't draw.
nonisolated struct KeyboardZoneGeometry: Codable, Equatable, Sendable {
struct Key: Codable, Equatable, Sendable {
var id: String
var row: Int
var frame: CGRect
var hitFrame: CGRect
var gapHitFrame: CGRect?
}
var keys: [Key]
var keyHeight: CGFloat
var letterWidth: CGFloat
var touchArea: CGRect
init(layout: KeyboardLayout) {
keys = layout.keys.map { Key(id: TypingLogger.keyID($0.kind), row: $0.row, frame: $0.frame, hitFrame: $0.hitFrame, gapHitFrame: $0.gapHitFrame) }
keyHeight = layout.metrics.keyHeight
letterWidth = layout.letterWidth
touchArea = layout.touchAreaFrame
}
}
nonisolated extension KeyboardLayout {
/// `zones` against these keys (`KeyboardZoneGeometry.zoneMap`).
func zoneMap(_ zones: [KeyboardZone]) -> KeyboardZoneMap {
KeyboardZoneGeometry(layout: self).zoneMap(zones)
}
}
nonisolated extension KeyboardZoneGeometry {
/// `zones` against these keys (letter keycaps: `letterWidth` across, `keyHeight` down).
/// Zones on an edge they may not move, or on a key this keyboard lacks, are skipped; so are
/// both of two zones whose strips meet, and every zone whose strip reaches into a key that
/// would keep too little. Regions are by index into `keys`, the layout's own order.
func zoneMap(_ zones: [KeyboardZone]) -> KeyboardZoneMap {
var skipped = [TypingConfigReview.Reason?](repeating: nil, count: zones.count)
let base = keys.map { [$0.hitFrame] + ($0.gapHitFrame.map { [$0] } ?? []) }
var strips: [[(rect: CGRect, owner: Int)]] = Array(repeating: [], count: zones.count)
for (n, zone) in zones.enumerated() {
let found = zoneStrips(for: zone, base: base)
strips[n] = found.strips
skipped[n] = found.reason
}
// Two zones claiming the same point: neither applies.
for a in zones.indices where skipped[a] == nil {
for b in zones.indices where b > a && skipped[b] == nil {
let meet = strips[a].contains { s in strips[b].contains { Self.overlaps(s.rect, $0.rect) } }
if meet {
skipped[a] = .twoZonesClaimPoint
skipped[b] = .twoZonesClaimPoint
}
}
}
// Apply, then drop the zones that leave a key too little of its keycap, until none does.
while true {
var regions = base
for n in zones.indices where skipped[n] == nil {
for strip in strips[n] {
for k in regions.indices where k != strip.owner {
regions[k] = regions[k].flatMap { Self.subtract(strip.rect, from: $0) }
}
regions[strip.owner] += regions[strip.owner].reduce([strip.rect]) { pieces, own in
pieces.flatMap { Self.subtract(own, from: $0) }
}
}
}
let small = keys.indices.filter { k in
keys[k].row >= 0 && keys[k].frame.width > 0 && !Self.covers(regions[k], keepRect(keys[k]))
}
let culprits = zones.indices.filter { n in
skipped[n] == nil && small.contains { k in strips[n].contains { Self.overlaps($0.rect, keepRect(keys[k])) } }
}
if small.isEmpty || culprits.isEmpty {
var map = KeyboardZoneMap(skipped: skipped)
for k in regions.indices where regions[k] != base[k] { map.regions[k] = regions[k] }
return map
}
for n in culprits { skipped[n] = .keyTooSmall }
}
}
/// The rectangle around a keycap's centre its key must keep.
private func keepRect(_ key: Key) -> CGRect {
let keep = TypingConfigLimits.zoneKeepFromCentre
return CGRect(x: key.frame.midX - keep * key.frame.width, y: key.frame.midY - keep * key.frame.height,
width: 2 * keep * key.frame.width, height: 2 * keep * key.frame.height)
}
/// The strips one zone moves, each with the key that gets it.
private func zoneStrips(for zone: KeyboardZone, base: [[CGRect]]) -> (strips: [(rect: CGRect, owner: Int)], reason: TypingConfigReview.Reason?) {
let letter = zone.key.count == 1 && zone.key.first?.isLetter == true
guard let edges = TypingConfigLimits.zoneEdges[letter ? "letter" : zone.key], edges.contains(zone.edge) else {
return ([], .edgeNotAllowed)
}
let targets = keys.indices.filter { keys[$0].row >= 0 && keys[$0].id == zone.key }
guard !targets.isEmpty else { return ([], .keyNotOnKeyboard) }
let move = max(-TypingConfigLimits.zoneMaxMove, min(TypingConfigLimits.zoneMaxMove, zone.move))
let vertical = zone.edge == .top || zone.edge == .bottom
let d = abs(move) * (vertical ? keyHeight : letterWidth)
guard d > 0.01 else { return ([], nil) }
let area = touchArea
var out: [(rect: CGRect, owner: Int)] = []
for i in targets {
let rects = base[i]
let bounds = rects.dropFirst().reduce(rects[0]) { $0.union($1) }
let line: CGFloat = switch zone.edge {
case .top: bounds.minY
case .bottom: bounds.maxY
case .left: bounds.minX
case .right: bounds.maxX
}
let outer = switch zone.edge {
case .top: line <= area.minY + 0.01
case .bottom: line >= area.maxY - 0.01
case .left: line <= area.minX + 0.01
case .right: line >= area.maxX - 0.01
}
if outer { return ([], .edgeNotAllowed) }
// The key's own stretches of that edge.
let segments = rects.filter { r in
switch zone.edge {
case .top: abs(r.minY - line) < 0.01
case .bottom: abs(r.maxY - line) < 0.01
case .left: abs(r.minX - line) < 0.01
case .right: abs(r.maxX - line) < 0.01
}
}
for s in segments {
if move > 0 {
let grown: CGRect = switch zone.edge {
case .top: CGRect(x: s.minX, y: line - d, width: s.width, height: d)
case .bottom: CGRect(x: s.minX, y: line, width: s.width, height: d)
case .left: CGRect(x: line - d, y: s.minY, width: d, height: s.height)
case .right: CGRect(x: line, y: s.minY, width: d, height: s.height)
}
let clipped = grown.intersection(area)
if !clipped.isNull, clipped.width > 0.01, clipped.height > 0.01 { out.append((clipped, i)) }
} else {
// A strip inside the key goes to the key across the edge at each point.
let strip: CGRect = switch zone.edge {
case .top: CGRect(x: s.minX, y: line, width: s.width, height: d)
case .bottom: CGRect(x: s.minX, y: line - d, width: s.width, height: d)
case .left: CGRect(x: line, y: s.minY, width: d, height: s.height)
case .right: CGRect(x: line - d, y: s.minY, width: d, height: s.height)
}
for j in base.indices where j != i && keys[j].row >= 0 {
for r in base[j] {
let touching = switch zone.edge {
case .top: abs(r.maxY - line) < 0.01
case .bottom: abs(r.minY - line) < 0.01
case .left: abs(r.maxX - line) < 0.01
case .right: abs(r.minX - line) < 0.01
}
guard touching else { continue }
let piece = vertical
? CGRect(x: max(strip.minX, r.minX), y: strip.minY, width: min(strip.maxX, r.maxX) - max(strip.minX, r.minX), height: strip.height)
: CGRect(x: strip.minX, y: max(strip.minY, r.minY), width: strip.width, height: min(strip.maxY, r.maxY) - max(strip.minY, r.minY))
if piece.width > 0.01, piece.height > 0.01 { out.append((piece, j)) }
}
}
}
}
}
return (out, nil)
}
static func overlaps(_ a: CGRect, _ b: CGRect) -> Bool {
let i = a.intersection(b)
return !i.isNull && i.width > 0.01 && i.height > 0.01
}
/// `rect` minus `hole`: up to four rectangles.
static func subtract(_ hole: CGRect, from rect: CGRect) -> [CGRect] {
let i = rect.intersection(hole)
guard !i.isNull, i.width > 0.01, i.height > 0.01 else { return [rect] }
let pieces = [
CGRect(x: rect.minX, y: rect.minY, width: rect.width, height: i.minY - rect.minY),
CGRect(x: rect.minX, y: i.maxY, width: rect.width, height: rect.maxY - i.maxY),
CGRect(x: rect.minX, y: i.minY, width: i.minX - rect.minX, height: i.height),
CGRect(x: i.maxX, y: i.minY, width: rect.maxX - i.maxX, height: i.height),
]
return pieces.filter { $0.width > 0.01 && $0.height > 0.01 }
}
/// Whether disjoint `rects` cover `target`.
static func covers(_ rects: [CGRect], _ target: CGRect) -> Bool {
let area = rects.reduce(0) { sum, r in
let i = r.intersection(target)
return i.isNull ? sum : sum + i.width * i.height
}
return area >= target.width * target.height - 0.5
}
}
nonisolated extension KeyboardLayout {
/// These keys with `map`'s touch areas.
func applying(_ map: KeyboardZoneMap) -> KeyboardLayout {
guard !map.isEmpty else { return self }
var out = self
for (k, rects) in map.regions where k < out.keys.count { out.keys[k].zoneRects = rects }
return out
}
}