mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
* iOS: punctuation after a word fixes its typo, as space does
X (Erick): "If I add punctuation after a typo autocorrect does not fix the typo."
Only space ran autocorrect, so "teh," or "recieve." kept the typo. Now a mark
that closes a word (, . ! ? ; : ) and ") runs the same correction as space,
from the 123 page or a 123 slide, and goes in after the fix ("the,"), as the
system keyboard does. One backspace right after takes back the mark and the fix
("teh"), the same as after a space, and the kept word isn't corrected again.
A period never corrects a common abbreviation (approx., etc., dept.) and a
swiped word is never corrected (it is a reading, not a typo).
Verified: new FullKeyboardEngineTests (testPunctuationAfterATypoFixesItFirst,
testPunctuationNeverChangesASwipedWord) pass on an iOS 27.2 simulator. Autocorrect
benchmark (Spatial autocorrect on): a new 300-sentence punctuation set goes from
12.40% to 7.10% WER and 96 to 177 sentences exactly right; the held-out sets are
unchanged (EN 5.94%, ES 8.61% WER; 79 and 23 correct words broken).
* iOS: contractions typed without the apostrophe follow the words around them
X (Erick): "the id in this didn't autocorrect to I'd". Words that are real words
both with and without an apostrophe (id/I'd, ill/I'll, hell/he'll, shell/she'll,
wed/we'd, lets/let's, well/we'll) were only offered in the strip and never
changed. Now English picks between them with the typing model's word pairs,
scoring a contraction as the words it stands for ("I'd like" as "I would like"),
which the pairs know far better than the contraction itself:
- At the word's own space, when the word before makes it clear ("yes id" ->
"yes I'd", "id like" at a sentence start -> "I'd", "the id" stays).
- At the next word's space or closing mark, the word before is revised when the
next word decides it ("well see" -> "we'll see", "well done" stays), as the
system keyboard does. A contraction whose last word ("will", "would", "had",
"us") the next word never follows is evidence against it, so "till hell
freezes" keeps "hell".
One backspace right after a revision puts back both words as typed and keeps
them. Words you kept, learned words, Contacts names and other languages are
never changed, and nothing changes without the bundled typing model.
"were/we're" stays suggest-only: the pairs can't tell them apart. Undo now
records each changed word (AppliedCorrection.changes), so a revision's undo
keeps both words; a single correction behaves as before.
Margins, the sentence-start bonus (3 nats) and the missing-follower penalty
(5 nats) were tuned on Tatoeba sentences outside the held-out sets.
Verified: AutocorrectEngineTests (testContractionsWithoutTheApostropheFollow
TheWordsAroundThem, testOneBackspaceTakesARevisionBack) and the rest of
AutocorrectEngineTests and FullKeyboardEngineTests pass (113 tests, iOS 27.2
simulator). Benchmark: EN held-out WER 5.94% -> 5.72% with correct words broken
79 -> 79; ES unchanged (8.61%, 23); the contraction set 7.29% -> 5.61%; engine
p95 per letter tap 2.5 ms.
* iOS: its/it's, your/you're, there/their/they're and then/than follow the context
X (Justin): "It doesn't seem to understand grammar. Its vs it's for instance."
Autocorrect never chose between words that sound alike, so "its a nice day",
"your welcome", "their is", "more then that" stayed wrong. These groups now join
the contraction groups from the previous change and are chosen by the typing
model's word pairs at the word's own space or, when the word before can't tell,
revised at the next word's ("its a" -> "it's a", "i think its broken" -> "I think
it's broken", "they lost there keys" -> "they lost their keys", "and than we" ->
"and then we"), with the same undo: one backspace puts back what you typed.
"the dog wagged its tail" and "on its way" stay.
"it's", "you're" and "they're" are scored as "it is"/"it has", "you are", "they
are". The missing-follower penalty now applies only after "will", "would", "had"
and "us": the pairs rarely list the adjectives after "are" ("you're funny"), so
it broke right words there. A word you typed with your own apostrophe is never
changed or revised. The next-word margin for a change of letters (their/there,
then/than) is 3 nats, tuned with the others on Tatoeba sentences outside the
held-out sets.
Verified: AutocorrectEngineTests.testSoundAlikeWordsFollowTheWordsAroundThem and
the rest of AutocorrectEngineTests and FullKeyboardEngineTests pass (114 tests,
iOS 27.2 simulator). Benchmark: EN held-out WER 5.72% -> 5.48% with correct
words broken 79 -> 79; ES unchanged (8.61%, 23); a 200-sentence set with the
wrong homophone typed 14.08% -> 5.86% and one with the right one 6.33% -> 4.08%;
engine p95 per letter tap 2.3 ms.
* iOS: a space tapped as the letter above the space bar splits the words
X (Erick): "Auto correct does not separate two words like apple does
(consistently)." Spatial autocorrect read a letter tap as a missed space only
when it landed below the bottom row's centre line, so "ofbthe", "uscto" or
"oncthe" with the c, v, b or n hit on its upper half stayed one word. The system
keyboard turns "of" + b + "the" into "of the" wherever on the b the tap lands,
its centre included (black-box, iOS 27.2 simulator).
The decoder now knows where the space bar is (TypingDecoder.Keys.space, both
bars as on the unsplit keyboard), and a tap on the bottom row's upper half above
the bar may be a space, priced by the bar's Gaussian likelihood against the
row's (spaceTapCost 5 + spaceTapWeight 0.25 x the difference, in nats). There
both halves must be exactly the letters typed, so an unknown name's middle
letter is never a space with slips around it ("rima" stayed "rima"; without
that rule it became "to a"). Taps below the centre line keep the old reading and
cost. Spanish keeps only the old reading: its one- and two-letter words made
these splits too cheap ("vaxes" -> "va es") and they fixed nothing there. A
missed space after English "i" ("iwant") now gives "I want", as "i" alone does.
Tuned on the dev and targeted sets (held-out sets checked only after).
Verified: AutocorrectEngineTests.testASpaceTappedAsALetterAboveTheSpaceBarOr
MissedSplitsTheWords plus AutocorrectEngineTests, FullKeyboardEngineTests,
KeyboardLayoutTests and SwipeDecoderTests pass (165 tests, iOS 27.2 simulator).
Benchmark: EN held-out WER 5.48% -> 5.47% (correct words broken 79 -> 79); ES
unchanged (8.61%, 23); 300 sentences with a merged pair 9.73% -> 7.40%; engine
p95 per letter tap 1.9 ms.
* iOS: a space tapped at the space bar's edge for a letter joins the words
X (Justin): "Space bar accidental taps or lack of taps don't seem to be factored
in." A letter tap that landed on the space bar typed a space, and nothing ever
joined the two halves ("deli ate", "num er"). The system keyboard (black-box,
iOS 27.2 simulator) merges them at the next word's space when the space tap was
near the bar's top edge ("deli" + space + "ate" -> "Delicate", "a out" ->
"About", "so gs" -> "Songs"), and not when it was well inside the bar.
The engine now remembers the finished word's taps and where its space was
tapped. At the next word's space or closing mark, TypingDecoder.merge reads the
first word's taps, the space tap as a letter on the row above and the second
word's taps as one word; it replaces the two words when it beats them by the
usual margins (7 nats when both are words, 2 otherwise) and the tap was within
mergeReach (3 nats: the row at most that much less likely than the bar under
the space bar's Gaussian, about its top fifth, a little deeper than the system
keyboard). One backspace right after puts back both words and keeps the second.
A merged or split word is remembered as it reads, without taps. Words you kept,
learned words, shorthand, Contacts names and apostrophes are never joined. The
space tap's place now reaches typeSpace (as on the unsplit keyboard).
mergeReach was tuned on the dev and targeted sets (held-out checked after).
Verified: AutocorrectEngineTests.testASpaceTappedAtTheSpaceBarsEdgeForALetter
JoinsTheWords plus AutocorrectEngineTests and FullKeyboardEngineTests pass (120
tests, iOS 27.2 simulator). Benchmark: EN held-out WER 5.47% -> 5.23%, ES 8.61%
-> 8.34%, correct words broken 79 -> 79 and 23 -> 23; 200 sentences with a
letter tapped on the space bar 29.57% -> 16.04%; engine p95 1.9 ms per letter,
0.06 ms per space.
* iOS: no stray capitals from swiped words
X (Eric Jung): "the swipe keyboard has random auto capitalization of words."
Reproduced by swiping 600 held-out sentences word by word through the engine
with the swipe benchmark's finger models. Shift and auto-capitalization around a
swipe were right in every sequence tried (after a period, comma, return, delete,
a strip pick, a host text-change, one-shot shift and caps lock); the capitals
came from the readings themselves:
- The typing model's lowercase word list holds names and abbreviations ("gs",
"ut", "om", "kent"), which the dictionary knows only capitalised, so a loose
swipe of "he" or "it" went in as "Gs" or "Ut" mid-sentence. Such a reading now
costs 4 nats more unless it is common (the model's ~2,500 commonest words:
"york", "english") or one of your own words (Contacts names keep theirs).
The check is shared with the casing (FullKeyboardEngine.swipeReadsAsName) and
applied after decoding, on the main thread, for the swipe and its preview.
- "I'm", "I'd" and "I've" had one fixed cost whatever came before ("with us I'm
Boston"). A contraction is now as much likelier after the word before as its
first word is (SwipeDecoder.ExtraWords.heads, "i" for "I'm", "do" for
"don't"), 3 nats more when the model never has that pair.
Verified: FullKeyboardEngineTests.testASwipeMidSentenceGetsNoStrayCapital plus
AutocorrectEngineTests, FullKeyboardEngineTests and SwipeDecoderTests pass (128
tests, iOS 27.2 simulator). Swipe probe (600 held-out sentences, 3,986 words):
typical fingers words right 3,569 -> 3,578, stray mid-sentence capitals 1 -> 2
(one "I'd" for "if"), contractions right 171 -> 180 of 216; sloppy fingers
2,873 -> 2,888, stray capitals 18 -> 6, contractions 137 -> 145.
* iOS: a space at the bar's edge joins words only when space wouldn't fix them alone
Follow-up to "a space tapped at the space bar's edge for a letter joins the
words" (a005d926). The merge weighed one word against the two words exactly as
typed, so a second half with a slip counted as an unknown word and lost:
"i" + edge space + "dkdnt" became "Obedient", where space turns "dkdnt" into
"didn't" on its own. The two words are now scored as space would leave them:
each as typed or its likeliest reading of its own taps, the second after the
first's.
Verified: AutocorrectEngineTests (testASpaceTappedAtTheSpaceBarsEdgeForALetter
JoinsTheWords now also types "i" + edge space + "didnt" -> "I didn't") and
FullKeyboardEngineTests pass (121 tests, iOS 27.2 simulator). Benchmark: the
broken word on the homophone set is back (correct words broken 4 -> 3); EN
held-out WER 5.23% -> 5.24% (726 -> 727 edits, broken 79), ES unchanged (8.34%,
23), letter-on-space-bar set 16.04% -> 16.38%; engine p95 1.8 ms per letter.
* iOS: a closing mark from the 123 page reads the word's taps
Follow-up to "punctuation after a word fixes its typo, as space does"
(fb6200df). Found in a live check in Messages: "ofthe." became "Oft he." where
space gives "of the" (and the system keyboard "Of the."). Tapping 123 rebuilds
the layout, and off the letters page TypingDecoder.Keys(layout:) is nil, so by
the time the mark finished the word Spatial autocorrect had no keys and the
dictionary's guess was used. The letters page's keys now stay while another page
shows; they are where the word was typed.
Verified: AutocorrectEngineTests (the split test now also types "ofthe" + 123
+ "." -> "of the.") and FullKeyboardEngineTests pass (121 tests, iOS 27.2
simulator). Benchmark: the 300-sentence punctuation set 6.83% -> 3.94% WER,
sentences exactly right 179 -> 230; held-out sets unchanged (EN 5.24%, ES
8.34%; broken 79, 23).
* iOS tests: the space-bar merge test types with the next-letter odds on
testASpaceTappedAtTheSpaceBarsEdgeForALetterJoinsTheWords ran without the
typing model's next-letter odds, which the keyboard always has, and there "a" +
edge space + "out" joined into "about"; with them, as in a live check in
Messages, the two words stay (the 7-nat margin for joining two real words). The
test now sets letterOdds and types "ha" + edge space + "ded" -> "handed", which
joins both ways and on the system keyboard. No code change.
Verified: AutocorrectEngineTests and FullKeyboardEngineTests pass (121 tests,
iOS 27.2 simulator).
359 lines
14 KiB
Swift
359 lines
14 KiB
Swift
import QuartzCore
|
||
import UIKit
|
||
|
||
/// Settings › Keyboard › 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?
|
||
/// Nats more a rare reading the dictionary knows only with a capital costs, unless it is
|
||
/// one of your own words: the model's lowercase list holds names and abbreviations ("gs",
|
||
/// "ut", "kent") that a loose swipe of a common word could read as, and they would go in
|
||
/// capitalised mid-sentence. Common ones ("john", "york", "english") cost nothing more.
|
||
var nameCost = 4.0
|
||
/// The model's cost (-ln p) past which such a word counts as rare: about its 2,500th word.
|
||
static let commonNameCost = 10.0
|
||
|
||
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, contractions: true)
|
||
}
|
||
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 words = ranked(candidates)
|
||
let elapsed = clock() - started
|
||
lastDecodeTime = elapsed
|
||
engine.endSwipe(typing: words, points: points.count, decodeTime: elapsed)
|
||
}
|
||
|
||
/// The readings best first once a rare name or abbreviation costs `nameCost` more.
|
||
func ranked(_ candidates: [SwipeDecoder.Candidate]) -> [String] {
|
||
let model = decoder.model
|
||
func rareName(_ text: String) -> Bool {
|
||
guard engine.swipeReadsAsName(text) else { return false }
|
||
return model.index(of: text).map { model.unigramCost($0) > Self.commonNameCost } ?? true
|
||
}
|
||
return candidates
|
||
.map { ($0.text, $0.cost + (rareName($0.text) ? nameCost : 0)) }
|
||
.enumerated()
|
||
.sorted { $0.element.1 != $1.element.1 ? $0.element.1 < $1.element.1 : $0.offset < $1.offset }
|
||
.map(\.element.0)
|
||
}
|
||
|
||
// 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 candidates = decoder.decode(points, keys: keys, previous: previous, limit: 3)
|
||
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(self.ranked(candidates))
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// 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()
|
||
}
|
||
}
|