hex/ios/HEXShared/FullKeyboard/SwipeDecoder.swift
Ryan Vogel 759149fa54 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 17:27:07 -05:00

506 lines
24 KiB
Swift

import CoreGraphics
import Foundation
/// Experiment (Swipe typing): reads a finger's path across the letter keys as a word.
///
/// A shape-matching decoder after SHARK2 (Kristensson and Zhai, 2004) and the template
/// matching of Gboard's published gesture decoders, written for Hex:
/// 1. The path is resampled to evenly spaced points in key pitches (a key's width plus a
/// gap across, a row's height plus a gap down), so a slip of half a key counts the same
/// either way.
/// 2. Words come from the typing model's word list, which is sorted letter by letter: the
/// words starting on a key near where the finger went down are one range of it per
/// letter. Of those, only words ending on a key near where it lifted, with every key near
/// the path and an ideal path (the polyline through their keys' centres) about as long,
/// are scored.
/// 3. Each is scored on where its ideal path runs against the gesture (location: a quick
/// point-by-point pass, then dynamic time warping for the best few, which follows a
/// finger that hurries and slows), on its shape alone (both paths moved to one centre
/// and size), and on how near the finger went down and lifted to its first and last keys,
/// 4. and weighed with the model's frequency of the word after the word before.
///
/// Nothing is built ahead or kept: each swipe reads the memory-mapped model in place
/// (`TypingDecoderModel.withCodes`), so the decoder holds no memory between swipes.
nonisolated struct SwipeDecoder: Sendable {
/// Tuned on synthetic swipes of the autocorrect benchmark's held-out dev sentences
/// (English and Spanish; clean, neat, typical and sloppy fingers; experiment folder
/// 2026-11-20-hex-swipe-typing), never on its test sentences.
struct Parameters: Equatable, Sendable {
/// Points the gesture and each word's ideal path are resampled to.
var samples = 32
/// Keys this many pitches from where the finger went down (lifted) may start (end)
/// the word: the nearest few.
var startRadius = 1.6
var endRadius = 2.1
var maxStartKeys = 4
var maxEndKeys = 8
/// Every key of a word passes at most this far from the path (pitches).
var nearRadius = 1.5
/// How much shorter or longer than the gesture a word's ideal path may be.
var minLengthRatio = 0.4
var maxLengthRatio = 1.8
/// How far from its first and last keys' centres a finger goes down and lifts: most
/// within the first spread, the rest (`stray`) within the wider second, so a near
/// miss costs much and a far one no more than the path's shape can make up.
var startSigma = 0.3
var endSigma = 0.3
var startStraySigma = 0.8
var endStraySigma = 0.9
var stray = 0.25
/// Nats per mean squared pitch between the paths, and per mean squared distance
/// between their shapes (each scaled to a unit box).
var locationWeight = 40.0
var shapeWeight = 60.0
/// Weight of the word model's cost, -ln P(word | word before).
var lmWeight = 1.1
/// Words of the quick pass the aligned pass scores again.
var shortlist = 80
/// Past this many words, only the likeliest by how near their keys lie to the path
/// (and their frequency) get the quick pass, which keeps a long, loose swipe fast.
var prefilter = 1500
/// How far (a share of the samples) the aligned pass may run ahead or behind.
var band = 0.1
/// The shortest path read as a swipe (pitches).
var minimumLength = 0.6
/// -ln of a point landing `squared` (pitches²) from a key's centre, under the mixture
/// of a tight spread and a stray one; 0 at the centre.
func cost(_ squared: Double, sigma: Double, stray strayingSigma: Double) -> Double {
let near = (1 - stray) / (sigma * sigma)
let far = stray / (strayingSigma * strayingSigma)
let density = near * exp(-squared / (2 * sigma * sigma)) + far * exp(-squared / (2 * strayingSigma * strayingSigma))
return log((near + far) / max(density, .leastNormalMagnitude))
}
}
/// The cost (-ln P) of a common English contraction ("isn't", "we're"), about a word ranked
/// 1,500th: Google Books splits contractions ("do n't"), so the model's counts for them
/// are far too low.
static let contractionCost = 7.5
/// The cost of English contraction `word` by how often a chat uses it: the commonest ("I'm",
/// "don't", "it's") like a word ranked about 300th, common ones at `base`, the rest ("he'll",
/// "ma'am") about 10,000th.
static func costOfContraction(_ word: String, base: Double = contractionCost) -> Double {
let lower = word.lowercased()
if commonestContractions.contains(lower) { return base - 1.5 }
if commonContractions.contains(lower) { return base }
return base + 2
}
private static let commonestContractions: Set<String> = [
"i'm", "don't", "it's", "i'll", "can't", "that's", "didn't", "you're", "i've", "doesn't",
]
private static let commonContractions: Set<String> = [
"isn't", "there's", "let's", "won't", "what's", "he's", "she's", "wasn't", "i'd", "we're",
"they're", "haven't", "couldn't", "wouldn't", "aren't", "you'll", "we'll", "shouldn't", "you've",
]
/// The cost of one of your own words (as Spatial autocorrect's `userWordCost`).
static let ownWordCost = 11.0
struct Candidate: Equatable, Sendable {
/// The word as the model spells it: lowercase, with its accents and apostrophes.
var text: String
var cost: Double
}
struct Reading: Equatable, Sendable {
/// Best first.
var candidates: [Candidate]
/// Words that passed the key filters and were scored.
var scored: Int
}
/// Words read beside the model's, each with its own cost (-ln P(word)): words the model
/// lacks or barely counts, such as English contractions (Google Books splits "don't" into
/// "do n't", so its "don't" is as rare as "tom"), and your own words.
struct ExtraWords: Sendable {
private(set) var codes: [[UInt8]] = []
private(set) var texts: [String] = []
private(set) var costs: [Double] = []
/// The model's index of the same word, for its pairs; nil when it lacks it.
private(set) var modelIndex: [Int?] = []
init() {}
/// `words` as you'd see them ("I'm", "don't"), each with `cost` unless the model's
/// own is lower; a word with a letter the model lacks is left out, and a repeat once.
init(_ words: [String], cost: Double, model: TypingDecoderModel) {
add(words, cost: cost, model: model)
}
init(_ words: [String], cost: (String) -> Double, model: TypingDecoderModel) {
add(words, cost: cost, model: model)
}
var isEmpty: Bool { texts.isEmpty }
var count: Int { texts.count }
mutating func add(_ words: [String], cost: Double, model: TypingDecoderModel) {
add(words, cost: { _ in cost }, model: model)
}
mutating func add(_ words: [String], cost: (String) -> Double, model: TypingDecoderModel) {
var seen = Set(codes)
for word in words {
guard word.count >= 2, let encoded = model.encode(word.lowercased()), seen.insert(encoded).inserted else { continue }
codes.append(encoded)
texts.append(word)
costs.append(cost(word))
modelIndex.append(model.index(ofCodes: encoded))
}
}
}
let model: TypingDecoderModel
var parameters: Parameters
/// Words and two-word expressions never offered (`OffensiveWords`), as for Spatial
/// autocorrect: never read from a swipe.
var neverSuggest = TypingDecoder.NeverSuggest()
var extraWords = ExtraWords() {
didSet { extraIndices = Set(extraWords.modelIndex.compactMap { $0 }) }
}
/// The model's words that `extraWords` also has, read only as extra words.
private var extraIndices: Set<Int> = []
init(model: TypingDecoderModel, parameters: Parameters = Parameters()) {
self.model = model
self.parameters = parameters
}
/// The likeliest words for a swipe along `path` (the touch's points, first to last, in
/// the keys' coordinates), best first; empty when it can't be read as one.
func decode(_ path: [CGPoint], keys: TypingDecoder.Keys, previous: String? = nil, limit: Int = 4) -> [Candidate] {
read(path, keys: keys, previous: previous, limit: limit).candidates
}
func read(_ path: [CGPoint], keys: TypingDecoder.Keys, previous: String? = nil, limit: Int = 4) -> Reading {
let p = parameters
let none = Reading(candidates: [], scored: 0)
let pitch = Vec(x: Double(keys.pitch.width), y: Double(keys.pitch.height))
guard pitch.x > 0, pitch.y > 0, path.count >= 2, limit > 0, p.samples >= 4 else { return none }
let grid = KeyGrid(keys, model: model, pitch: pitch)
guard grid.centres.count >= 2, grid.centres.count <= 64 else { return none }
guard let gesture = Gesture(path, pitch: pitch, samples: p.samples), gesture.length >= p.minimumLength,
let start = gesture.raw.first, let end = gesture.raw.last else { return none }
// 1. The keys the word may start and end on, and how near the path passes each key.
let keyCount = grid.centres.count
let near = grid.centres.map { Self.distance(from: $0, toPolyline: gesture.raw) }
var startCost = [Double](repeating: .infinity, count: keyCount)
var endCost = [Double](repeating: .infinity, count: keyCount)
let starts = Self.nearest(grid.centres, to: start, radius: p.startRadius, limit: p.maxStartKeys)
for (k, squared) in starts { startCost[k] = p.cost(squared, sigma: p.startSigma, stray: p.startStraySigma) }
var endMask: UInt64 = 0
for (k, squared) in Self.nearest(grid.centres, to: end, radius: p.endRadius, limit: p.maxEndKeys) {
endCost[k] = p.cost(squared, sigma: p.endSigma, stray: p.endStraySigma)
endMask |= 1 << UInt64(k)
}
guard !starts.isEmpty, endMask != 0 else { return none }
// 2. Words that start on a start key, end on an end key, keep near the path and are
// about as long: their keys (repeats run together, apostrophes left out). An id is
// a model word's index, or -1 - n for extra word n.
var words: [Int32] = []
var offsets: [Int32] = [0]
var lengths: [Double] = []
var sequence: [UInt8] = []
/// Mean squared distance of each word's keys from the path, for the prefilter.
var nearness: [Double] = []
var scratch = [UInt8](repeating: 0, count: 64)
func consider<Codes: RandomAccessCollection>(_ codes: Codes, id: Int) where Codes.Element == UInt8, Codes.Index == Int {
var j = codes.endIndex - 1
while j > codes.startIndex, grid.keyOfCode[Int(codes[j])] == KeyGrid.skip { j -= 1 }
guard j > codes.startIndex else { return }
let endKey = grid.keyOfCode[Int(codes[j])]
guard endKey >= 0, endMask & (1 << UInt64(endKey)) != 0 else { return }
var count = 0
var last = -1
var length = 0.0
var squares = 0.0
for c in codes {
let k = Int(grid.keyOfCode[Int(c)])
if k == Int(KeyGrid.skip) || k == last { continue }
guard k >= 0, count < scratch.count, near[k] <= p.nearRadius else { return }
if last >= 0 { length += Self.distance(grid.centres[last], grid.centres[k]) }
squares += near[k] * near[k]
scratch[count] = UInt8(k)
count += 1
last = k
}
guard count >= 2, startCost[Int(scratch[0])].isFinite else { return }
let ratio = length / gesture.length
guard ratio >= p.minLengthRatio, ratio <= p.maxLengthRatio else { return }
sequence.append(contentsOf: scratch[0..<count])
words.append(Int32(id))
lengths.append(length)
offsets.append(Int32(sequence.count))
nearness.append(squares / Double(count))
}
for (s, _) in starts {
for code in grid.codesOfKey[s] {
let (lo, hi) = model.narrow(0, model.wordCount, depth: 0, byte: Int(code))
guard lo < hi else { continue }
for i in lo..<hi where !neverSuggest.words.contains(i) && !extraIndices.contains(i) {
model.withCodes(i) { consider($0, id: i) }
}
}
}
for n in 0..<extraWords.count {
consider(extraWords.codes[n], id: -1 - n)
}
guard !words.isEmpty else { return none }
// 3. A quick point-by-point pass over them all, then the aligned pass for the best.
let n = p.samples
var template = [Vec](repeating: Vec(x: 0, y: 0), count: n)
var vertices = [Vec](repeating: Vec(x: 0, y: 0), count: 64)
var rows = ([Double](repeating: 0, count: n), [Double](repeating: 0, count: n))
func spatial(_ c: Int, aligned: Bool) -> Double {
let from = Int(offsets[c]), to = Int(offsets[c + 1])
for v in from..<to { vertices[v - from] = grid.centres[Int(sequence[v])] }
Self.resample(vertices, count: to - from, length: lengths[c], into: &template)
let location = aligned
? Self.warpedDistance(gesture.points, template, band: max(1, Int(p.band * Double(n))), rows: &rows)
: Self.meanSquaredDistance(gesture.points, template)
let shape = Self.shapeDistance(gesture.shape, template)
return startCost[Int(sequence[from])] + endCost[Int(sequence[to - 1])]
+ p.locationWeight * location + p.shapeWeight * shape
}
var pool = Array(words.indices)
if pool.count > p.prefilter {
let rough = pool.map { c -> Double in
let from = Int(offsets[c]), to = Int(offsets[c + 1])
return startCost[Int(sequence[from])] + endCost[Int(sequence[to - 1])]
+ p.locationWeight * nearness[c] + p.lmWeight * lmCost(Int(words[c]), after: nil)
}
pool.sort { rough[$0] < rough[$1] }
pool.removeLast(pool.count - p.prefilter)
}
var quick: [(candidate: Int, cost: Double)] = []
quick.reserveCapacity(pool.count)
for c in pool {
quick.append((c, spatial(c, aligned: false) + p.lmWeight * lmCost(Int(words[c]), after: nil)))
}
quick.sort { $0.cost < $1.cost }
let previousWord = previous.flatMap { model.index(of: $0.lowercased()) }
var scored: [(word: Int, cost: Double)] = []
for (c, _) in quick.prefix(max(limit, p.shortlist)) {
let word = Int(words[c])
if word >= 0, neverSuggest.follows(word, after: previousWord) { continue }
scored.append((word, spatial(c, aligned: true) + p.lmWeight * lmCost(word, after: previousWord)))
}
scored.sort { $0.cost < $1.cost }
var candidates: [Candidate] = []
for (word, cost) in scored.prefix(limit) {
candidates.append(Candidate(text: word >= 0 ? model.word(word) : extraWords.texts[-1 - word], cost: cost))
}
return Reading(candidates: candidates, scored: words.count)
}
/// -ln P(word | previous) with stupid backoff (0.4) to the unigram, as Spatial autocorrect's;
/// an extra word's own cost when lower.
private func lmCost(_ id: Int, after previous: Int?) -> Double {
func model(_ word: Int) -> Double {
let backoff = 0.92 + self.model.unigramCost(word)
guard let previous, let bigram = self.model.bigramCost(previous, word) else { return backoff }
return min(bigram, backoff)
}
guard id < 0 else { return model(id) }
let own = 0.92 + extraWords.costs[-1 - id]
return extraWords.modelIndex[-1 - id].map { min(own, model($0)) } ?? own
}
// MARK: - Geometry, in key pitches
struct Vec: Equatable, Sendable {
var x: Double
var y: Double
}
/// The layout's letter keys in pitches, and which key types each of the model's letters:
/// its own, else its unaccented letter's (é on e); the apostrophe has none and is skipped.
private struct KeyGrid {
static let skip: Int8 = -1
static let missing: Int8 = -2
var centres: [Vec] = []
var keyOfCode: [Int8]
var codesOfKey: [[UInt8]]
init(_ keys: TypingDecoder.Keys, model: TypingDecoderModel, pitch: Vec) {
var index: [Character: Int] = [:]
for (character, point) in keys.centres.sorted(by: { $0.key < $1.key }) {
index[character] = centres.count
centres.append(Vec(x: Double(point.x) / pitch.x, y: Double(point.y) / pitch.y))
}
keyOfCode = [Int8](repeating: Self.missing, count: model.characters.count)
codesOfKey = [[UInt8]](repeating: [], count: centres.count)
for code in 1..<model.characters.count {
if UInt8(code) == model.apostropheCode {
keyOfCode[code] = Self.skip
continue
}
let own = index[model.characters[code]]
guard let key = own ?? index[model.characters[Int(model.baseCodes[code])]], key < 64 else { continue }
keyOfCode[code] = Int8(key)
codesOfKey[key].append(UInt8(code))
}
}
}
/// The finger's path in pitches without repeated points, resampled, and its shape.
private struct Gesture {
var raw: [Vec] = []
var length = 0.0
var points: [Vec]
var shape: [Vec]
init?(_ path: [CGPoint], pitch: Vec, samples: Int) {
for point in path {
let v = Vec(x: Double(point.x) / pitch.x, y: Double(point.y) / pitch.y)
if let last = raw.last {
let step = SwipeDecoder.distance(last, v)
guard step > 1e-4 else { continue }
length += step
}
raw.append(v)
}
guard raw.count >= 2, length > 0 else { return nil }
points = [Vec](repeating: Vec(x: 0, y: 0), count: samples)
SwipeDecoder.resample(raw, count: raw.count, length: length, into: &points)
shape = SwipeDecoder.normalized(points)
}
}
@inline(__always) static func distance(_ a: Vec, _ b: Vec) -> Double {
((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)).squareRoot()
}
@inline(__always) private static func squared(_ a: Vec, _ b: Vec) -> Double {
(a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)
}
/// The keys within `radius` of `point`, nearest first, at most `limit`, with their
/// squared distances; the nearest two however far.
private static func nearest(_ centres: [Vec], to point: Vec, radius: Double, limit: Int) -> [(Int, Double)] {
let sorted = centres.indices.map { ($0, squared(centres[$0], point)) }.sorted { $0.1 < $1.1 }
var found = Array(sorted.prefix(limit).filter { $0.1 <= radius * radius })
if found.count < 2 { found = Array(sorted.prefix(min(2, limit))) }
return found
}
static func distance(from point: Vec, toPolyline line: [Vec]) -> Double {
var best = Double.infinity
for i in 1..<line.count {
let a = line[i - 1], b = line[i]
let dx = b.x - a.x, dy = b.y - a.y
let span = dx * dx + dy * dy
var t = span > 0 ? ((point.x - a.x) * dx + (point.y - a.y) * dy) / span : 0
t = min(1, max(0, t))
best = min(best, squared(point, Vec(x: a.x + t * dx, y: a.y + t * dy)))
}
return best.squareRoot()
}
/// `count` points of `line` (`length` long) evenly spaced along it into `out`,
/// first and last included.
static func resample(_ line: [Vec], count: Int, length: Double, into out: inout [Vec]) {
let samples = out.count
out[0] = line[0]
out[samples - 1] = line[count - 1]
guard samples > 2 else { return }
let step = length / Double(samples - 1)
var segment = 0
var walked = 0.0
var span = distance(line[0], line[min(1, count - 1)])
for i in 1..<(samples - 1) {
let target = step * Double(i)
while walked + span < target, segment < count - 2 {
walked += span
segment += 1
span = distance(line[segment], line[segment + 1])
}
let a = line[segment], b = line[min(segment + 1, count - 1)]
let t = span > 0 ? min(1, max(0, (target - walked) / span)) : 0
out[i] = Vec(x: a.x + t * (b.x - a.x), y: a.y + t * (b.y - a.y))
}
}
/// The points moved to their centroid and scaled so their bounding box's longer side is 1.
static func normalized(_ points: [Vec]) -> [Vec] {
let (centre, scale) = frame(points)
return points.map { Vec(x: ($0.x - centre.x) * scale, y: ($0.y - centre.y) * scale) }
}
@inline(__always) private static func frame(_ points: [Vec]) -> (Vec, Double) {
var sx = 0.0, sy = 0.0
var minX = Double.infinity, maxX = -Double.infinity, minY = Double.infinity, maxY = -Double.infinity
for v in points {
sx += v.x
sy += v.y
minX = min(minX, v.x)
maxX = max(maxX, v.x)
minY = min(minY, v.y)
maxY = max(maxY, v.y)
}
let side = max(maxX - minX, maxY - minY)
let n = Double(points.count)
return (Vec(x: sx / n, y: sy / n), side > 1e-6 ? 1 / side : 1)
}
/// Mean squared distance between the gesture's normalized shape and the template's.
private static func shapeDistance(_ shape: [Vec], _ template: [Vec]) -> Double {
let (centre, scale) = frame(template)
var total = 0.0
for i in shape.indices {
let t = Vec(x: (template[i].x - centre.x) * scale, y: (template[i].y - centre.y) * scale)
total += squared(shape[i], t)
}
return total / Double(shape.count)
}
private static func meanSquaredDistance(_ a: [Vec], _ b: [Vec]) -> Double {
var total = 0.0
for i in a.indices { total += squared(a[i], b[i]) }
return total / Double(a.count)
}
/// Dynamic time warping of two equally long point lists within a band, symmetric steps
/// (a diagonal step counts twice), as a mean squared distance.
private static func warpedDistance(_ a: [Vec], _ b: [Vec], band: Int, rows: inout ([Double], [Double])) -> Double {
let n = a.count
for j in 0..<n { rows.0[j] = .infinity }
for i in 0..<n {
for j in 0..<n { rows.1[j] = .infinity }
let lo = max(0, i - band), hi = min(n - 1, i + band)
for j in lo...hi {
let c = squared(a[i], b[j])
var best = i == 0 && j == 0 ? 2 * c : Double.infinity
if i > 0, j > 0 { best = min(best, rows.0[j - 1] + 2 * c) }
if i > 0 { best = min(best, rows.0[j] + c) }
if j > 0 { best = min(best, rows.1[j - 1] + c) }
rows.1[j] = best
}
swap(&rows.0, &rows.1)
}
return rows.0[n - 1] / Double(2 * n)
}
}
extension KeyboardLayout {
/// A swipe's point where the decoder's keys are (`TypingDecoder.Keys`): on the split
/// keyboard the right half moves left against the left one (as `unsplitX`) and the middle
/// between the halves shrinks to one key's gap, so a stroke across it stays one unbroken
/// stroke, as Gboard joins the halves; elsewhere the point itself.
func joinedForSwipe(_ point: CGPoint) -> CGPoint {
guard let split else { return point }
if point.x <= split.leftEdge { return point }
if point.x >= split.rightEdge { return CGPoint(x: point.x - split.shift, y: point.y) }
let across = (point.x - split.leftEdge) / max(1, split.rightEdge - split.leftEdge)
return CGPoint(x: split.leftEdge + across * SplitGeometry.gap, y: point.y)
}
/// The distance between neighbouring letter keys' centres across: a split half's own pitch.
var swipePitch: CGFloat { isSplit ? SplitGeometry.pitch : letterWidth + metrics.gap }
}