mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
* 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.
337 lines
13 KiB
Swift
337 lines
13 KiB
Swift
import QuartzCore
|
||
import UIKit
|
||
|
||
/// Experiments › Swipe typing: slide from a letter through the letters of a word and lift,
|
||
/// and the word goes in, as with Apple's QuickPath and Gboard's glide typing. English and
|
||
/// Spanish layouts only (the languages with a typing model); every other layout keeps a drag
|
||
/// as a slide to another key.
|
||
///
|
||
/// A touch on a letter key becomes a swipe once it travels more than a key's pitch from
|
||
/// where it went down: the key no longer types, a light trail follows the finger, and the
|
||
/// strip shows what the path reads as so far. Lifting the finger types the best reading
|
||
/// (`FullKeyboardEngine.typeSwipedWord`, which spaces and capitalises it) and offers the
|
||
/// next three in the strip. Taps, holds for accents, and slides of a key or less keep
|
||
/// working as before, and so do delete, the space bar's trackpad, 123 and the Hex key, which
|
||
/// no swipe starts on.
|
||
@MainActor
|
||
final class SwipeTyping {
|
||
private(set) var decoder: SwipeDecoder
|
||
private unowned let engine: FullKeyboardEngine
|
||
/// The light trail behind the finger; the key plane holds it above its keys.
|
||
let trail = SwipeTrailView()
|
||
|
||
/// Letter touches that may still become swipes: their points so far.
|
||
private var pending: [Int: [CGPoint]] = [:]
|
||
/// The swipe under way.
|
||
private var active: (id: Int, points: [CGPoint])?
|
||
/// Bumped by every swipe's start and end, so a reading of an older one is dropped.
|
||
private var generation = 0
|
||
private var previewInFlight = false
|
||
private var lastPreviewAt: TimeInterval = 0
|
||
/// Decodes while the finger moves, for the strip, off the main thread.
|
||
private static let previewQueue = DispatchQueue(label: "anomaly.hex.swipe-preview", qos: .userInitiated)
|
||
static let previewInterval: TimeInterval = 0.07
|
||
/// Your own words (`AutocorrectEngine.ownWords`) as the decoder has them.
|
||
private var ownWordsRevision: Int?
|
||
|
||
/// How long the last swipe's decode took, for Record typing logs and probes.
|
||
private(set) var lastDecodeTime: TimeInterval?
|
||
|
||
var clock: () -> TimeInterval = { CACurrentMediaTime() }
|
||
|
||
init(engine: FullKeyboardEngine, model: TypingDecoderModel) {
|
||
self.engine = engine
|
||
decoder = SwipeDecoder(model: model)
|
||
syncWords()
|
||
}
|
||
|
||
var model: TypingDecoderModel { decoder.model }
|
||
|
||
/// How far a letter touch travels before it is a swipe: a key's width and gap.
|
||
var threshold: CGFloat { engine.layout.swipePitch }
|
||
|
||
var isSwiping: Bool { active != nil }
|
||
|
||
/// Words never offered (slurs, and swear words unless Suggest swear words is on), the
|
||
/// language's contractions, and your own words; rebuilt only when one of them changed.
|
||
func syncWords() {
|
||
let autocorrect = engine.autocorrect
|
||
let revision = autocorrect.ownWordsRevision
|
||
guard revision != ownWordsRevision else { return }
|
||
ownWordsRevision = revision
|
||
let model = decoder.model
|
||
decoder.neverSuggest = TypingDecoder.NeverSuggest(
|
||
autocorrect.offensiveWords.blocked(allowSwearing: autocorrect.allowsSwearing), model: model
|
||
)
|
||
var extra = SwipeDecoder.ExtraWords()
|
||
if model.language == KeyboardLanguage.english.rawValue {
|
||
extra.add(AutocorrectEngine.englishContractions, cost: { SwipeDecoder.costOfContraction($0) }, model: model)
|
||
}
|
||
extra.add(autocorrect.ownWords, cost: SwipeDecoder.ownWordCost, model: model)
|
||
decoder.extraWords = extra
|
||
}
|
||
|
||
// MARK: - Touches (from `KeyboardKeyPlaneView`)
|
||
|
||
/// Before a touch goes down: a swipe still under way ends first, so its word goes in
|
||
/// before the new key's letter.
|
||
func touchWillBegin() {
|
||
if let swipe = active { finish(swipe.id, points: swipe.points) }
|
||
}
|
||
|
||
/// After the engine took a touch: a letter key's may become a swipe.
|
||
func began(id: Int, at point: CGPoint) {
|
||
guard engine.allowsSwipes, let touch = engine.touches[id], !touch.committed,
|
||
touch.key.character?.first?.isLetter == true else { return }
|
||
pending[id] = [point]
|
||
}
|
||
|
||
/// True when the touch is a swipe (now or already): the plane leaves it to this.
|
||
func moved(id: Int, to point: CGPoint) -> Bool {
|
||
if var swipe = active, swipe.id == id {
|
||
swipe.points.append(point)
|
||
active = swipe
|
||
trail.add(point)
|
||
schedulePreview()
|
||
return true
|
||
}
|
||
guard var points = pending[id] else { return false }
|
||
points.append(point)
|
||
pending[id] = points
|
||
guard let first = points.first, hypot(point.x - first.x, point.y - first.y) > threshold,
|
||
let touch = engine.touches[id], !touch.committed, engine.activeAccentMenu == nil,
|
||
engine.allowsSwipes else { return false }
|
||
pending[id] = nil
|
||
syncWords()
|
||
engine.beginSwipe(touchID: id)
|
||
active = (id, points)
|
||
generation += 1
|
||
lastPreviewAt = 0
|
||
trail.begin(points)
|
||
schedulePreview()
|
||
return true
|
||
}
|
||
|
||
/// Whether the touch is the swipe under way.
|
||
func owns(_ id: Int) -> Bool { active?.id == id }
|
||
|
||
/// A touch that never became a swipe ended.
|
||
func forget(_ id: Int) {
|
||
pending[id] = nil
|
||
}
|
||
|
||
/// The swipe's finger lifted: its word goes in.
|
||
func ended(id: Int, at point: CGPoint) {
|
||
guard let swipe = active, swipe.id == id else { return }
|
||
finish(id, points: swipe.points + [point])
|
||
}
|
||
|
||
/// The system cancelled the swipe's touch: nothing goes in.
|
||
func cancelled(id: Int) {
|
||
pending[id] = nil
|
||
guard let swipe = active, swipe.id == id else { return }
|
||
active = nil
|
||
generation += 1
|
||
trail.fade()
|
||
engine.endSwipe(typing: [], points: swipe.points.count, decodeTime: nil)
|
||
}
|
||
|
||
func cancelAll() {
|
||
pending.removeAll()
|
||
guard active != nil else { return }
|
||
active = nil
|
||
generation += 1
|
||
trail.clear()
|
||
engine.endSwipe(typing: [], points: 0, decodeTime: nil)
|
||
}
|
||
|
||
private func finish(_ id: Int, points: [CGPoint]) {
|
||
active = nil
|
||
pending[id] = nil
|
||
generation += 1
|
||
trail.fade()
|
||
let started = clock()
|
||
let layout = engine.layout
|
||
let candidates = decoder.decode(
|
||
points.map(layout.joinedForSwipe), keys: engine.swipeKeys, previous: engine.swipePreviousWord, limit: 8
|
||
)
|
||
let elapsed = clock() - started
|
||
lastDecodeTime = elapsed
|
||
engine.endSwipe(typing: candidates.map(\.text), points: points.count, decodeTime: elapsed)
|
||
}
|
||
|
||
// MARK: - The word so far
|
||
|
||
/// Reads the path so far off the main thread, at most every `previewInterval`, and shows
|
||
/// its best word in the strip while the swipe is still the same one.
|
||
private func schedulePreview() {
|
||
guard let swipe = active, !previewInFlight, swipe.points.count >= 3 else { return }
|
||
let now = clock()
|
||
guard now - lastPreviewAt >= Self.previewInterval else { return }
|
||
previewInFlight = true
|
||
lastPreviewAt = now
|
||
let decoder = decoder, keys = engine.swipeKeys, previous = engine.swipePreviousWord
|
||
let points = swipe.points.map(engine.layout.joinedForSwipe), generation = generation
|
||
Self.previewQueue.async { [weak self] in
|
||
let words = decoder.decode(points, keys: keys, previous: previous, limit: 3).map(\.text)
|
||
DispatchQueue.main.async {
|
||
MainActor.assumeIsolated {
|
||
guard let self else { return }
|
||
self.previewInFlight = false
|
||
guard self.generation == generation, self.active != nil else { return }
|
||
self.engine.showSwipePreview(words)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// MARK: - Spacing
|
||
|
||
/// Whether a swiped word needs a space before it, as Apple's keyboard adds one: unless
|
||
/// the text before the cursor is empty or ends in a space, a line break or opening
|
||
/// punctuation (a bracket, an opening quote, ¿ or ¡, or a mark that starts a word such
|
||
/// as @ # /). A straight quote opens when nothing or a space comes before it.
|
||
static func needsSpace(before: String?) -> Bool {
|
||
guard let before, let last = before.last else { return false }
|
||
if last.isWhitespace || last.isNewline || opening.contains(last) { return false }
|
||
if last == "\"" || last == "'" {
|
||
let previous = before.dropLast().last
|
||
return !(previous == nil || previous!.isWhitespace || previous!.isNewline || opening.contains(previous!))
|
||
}
|
||
return true
|
||
}
|
||
|
||
private static let opening: Set<Character> = ["(", "[", "{", "<", "«", "‹", "“", "‘", "„", "¿", "¡", "@", "#", "/"]
|
||
}
|
||
|
||
extension KeyboardLanguage {
|
||
/// Swipe typing reads only the layouts with a typing model; elsewhere a drag stays a
|
||
/// slide to another key.
|
||
var supportsSwipeTyping: Bool { self == .english || self == .spanish }
|
||
}
|
||
|
||
/// The light trail behind a swiping finger: the last `tail` seconds of its path, which
|
||
/// shortens behind the finger and fades when it lifts. A shape layer, so the keyboard draws
|
||
/// no bitmap of its own for it.
|
||
@MainActor
|
||
final class SwipeTrailView: UIView {
|
||
static let tail: TimeInterval = 0.45
|
||
static let width: CGFloat = 6
|
||
|
||
var palette = FullKeyboardPalette(isDark: false) {
|
||
didSet { if palette != oldValue { shape.strokeColor = Self.color(palette).cgColor } }
|
||
}
|
||
var clock: () -> TimeInterval = { CACurrentMediaTime() }
|
||
|
||
private let shape = CAShapeLayer()
|
||
private var points: [(point: CGPoint, at: TimeInterval)] = []
|
||
private var link: CADisplayLink?
|
||
|
||
override init(frame: CGRect) {
|
||
super.init(frame: frame)
|
||
isUserInteractionEnabled = false
|
||
isOpaque = false
|
||
backgroundColor = .clear
|
||
isAccessibilityElement = false
|
||
shape.fillColor = nil
|
||
shape.lineCap = .round
|
||
shape.lineJoin = .round
|
||
shape.lineWidth = Self.width
|
||
shape.strokeColor = Self.color(palette).cgColor
|
||
layer.addSublayer(shape)
|
||
}
|
||
|
||
@available(*, unavailable)
|
||
required init?(coder: NSCoder) { fatalError() }
|
||
|
||
static func color(_ palette: FullKeyboardPalette) -> UIColor {
|
||
palette.isDark ? UIColor(white: 1, alpha: 0.5) : palette.actionFill.withAlphaComponent(0.42)
|
||
}
|
||
|
||
override func layoutSubviews() {
|
||
super.layoutSubviews()
|
||
shape.frame = bounds
|
||
}
|
||
|
||
/// Off screen, the display link (which holds this view) stops.
|
||
override func didMoveToWindow() {
|
||
super.didMoveToWindow()
|
||
if window == nil { clear() }
|
||
}
|
||
|
||
var isShowing: Bool { shape.path != nil }
|
||
|
||
func begin(_ start: [CGPoint]) {
|
||
shape.removeAllAnimations()
|
||
shape.opacity = 1
|
||
let now = clock()
|
||
points = start.map { ($0, now) }
|
||
if link == nil, window != nil {
|
||
let link = CADisplayLink(target: self, selector: #selector(tick))
|
||
link.add(to: .main, forMode: .common)
|
||
self.link = link
|
||
}
|
||
redraw()
|
||
}
|
||
|
||
func add(_ point: CGPoint) {
|
||
points.append((point, clock()))
|
||
redraw()
|
||
}
|
||
|
||
/// The finger lifted: the trail fades out.
|
||
func fade() {
|
||
stopTicking()
|
||
guard shape.path != nil else { return }
|
||
CATransaction.begin()
|
||
CATransaction.setCompletionBlock { [weak self] in
|
||
MainActor.assumeIsolated {
|
||
guard let self, self.link == nil else { return }
|
||
self.clear()
|
||
}
|
||
}
|
||
let fade = CABasicAnimation(keyPath: "opacity")
|
||
fade.fromValue = 1
|
||
fade.toValue = 0
|
||
fade.duration = 0.2
|
||
shape.opacity = 0
|
||
shape.add(fade, forKey: "fade")
|
||
CATransaction.commit()
|
||
}
|
||
|
||
func clear() {
|
||
stopTicking()
|
||
points.removeAll()
|
||
CATransaction.begin()
|
||
CATransaction.setDisableActions(true)
|
||
shape.removeAllAnimations()
|
||
shape.path = nil
|
||
CATransaction.commit()
|
||
}
|
||
|
||
private func stopTicking() {
|
||
link?.invalidate()
|
||
link = nil
|
||
}
|
||
|
||
@objc private func tick() {
|
||
redraw()
|
||
}
|
||
|
||
private func redraw() {
|
||
// Points older than the tail drop off behind the finger, down to its last stretch.
|
||
if let old = points.lastIndex(where: { $0.at < clock() - Self.tail }) {
|
||
let drop = min(old, points.count - 2)
|
||
if drop > 0 { points.removeFirst(drop) }
|
||
}
|
||
let path = CGMutablePath()
|
||
if let first = points.first {
|
||
path.move(to: first.point)
|
||
for p in points.dropFirst() { path.addLine(to: p.point) }
|
||
}
|
||
CATransaction.begin()
|
||
CATransaction.setDisableActions(true)
|
||
shape.path = points.count >= 2 ? path : nil
|
||
CATransaction.commit()
|
||
}
|
||
}
|