mirror of
https://github.com/anomalyco/hex.git
synced 2026-12-06 12:16:12 +08:00
android: swipe typing (#2599)
* android: swipe typing (Keyboard › Swipe typing, on) Slide from a letter through a word's letters and lift: the word goes in. People asked for it at launch (four replies, "a must"); iPhone Hex has it. What changed - typing/SwipeDecoder.kt: iPhone Hex's SwipeDecoder (SHARK2-style shape matching with DTW, turn and pause evidence, the word-pair model) ported to Kotlin with the same parameters, reading the mapped HXTM model in place, so it may run off the main thread. Letters without a key read through the keys people swipe (ß on s, French œ/æ on o-e/a-e); iPhone drops those words. SwipeReader adds English's contractions and your personal-dictionary words and ranks rare names lower (not German, whose capitals list marks nouns). - keyboard/KeyPlaneView.kt, SwipeTyping.kt: a letter touch that travels a key's pitch becomes a swipe; its key no longer types, a trail in the keys' ink follows the finger and the strip shows the word so far (read off the main thread every 70 ms). Lifting reads it on the main thread. A drag back to its own key is a tap that slid; another key going down finishes the swipe first. Shift/?123 slides, accents, the space bar's cursor and Delete's slide are unchanged. - keyboard/KeyboardEngine.kt: the word goes in after a space unless the text ends in one or in opening punctuation, with a capital from shift or the sentence; the strip offers the next three readings. A tapped letter goes in after a pending space, closing marks against the word; space never autocorrects or text-replaces it. Delete right after takes the whole word back as Gboard's does (black box, API 36 emulator): the space before it stays, the strip offers the word again, and the next swipe there types its next reading. iPhone also takes the space; Gboard wins where they differ. - Settings › Keyboard › Swipe typing (TypingPreferences.swipe, default on, as on iPhone and Gboard), English and Chinese strings. - benchmark/typing: swipe_paths.py (the iPhone benchmark's path generator, ported; matches the Swift one to 5e-6 pitch), SwipeReplay.java and swipe-bench.py (host JVM or --device), README section with results. Verified - Same held-out paths as the iPhone replay: Android's decoder gives the identical top four for all 12,514 English and 12,346 Spanish swipes. First word right / typed or in the strip: en 96.9/99.6, es 94.3/99.4, de 95.9/99.4, nb 96.4/99.3, fr 95.2/99.3, it 96.0/99.3. - API 36 emulator (app_process against the APK): 1.0-1.4 ms median and 3.5-5.2 ms p99 per swipe. - quality-gate.py all: report identical field for field to origin/dev's. - testDebugUnitTest green; cases added to NeverSuggestTest and InsertionTest only. - In Messages on the emulator, injected swipes: spacing, capitals, punctuation, Delete and swipe-again behave as above. * android: swipe typing notes: iPhone's German pitch, ß words, the tap check The iPhone replay disagreed with Android on German because iPhone's TypingDecoder.Keys gives German's eleven-key rows a ten-column pitch (38.3 pt for 34.8 pt keys); with it corrected the first readings agree on all 13,206 swipes. Android's ß-through-s reading costs 0.1 point on the held-out set, which has no ß, and reads 71.4% of ß words first (98.3% in the strip) on accent-de.tsv, where iPhone reads none. The on/off tap check in Messages: 29 of 30 sentences identical, the one difference a tap lost right after the keyboard restarted, not reproduced on retyping. Docs only.
This commit is contained in:
+6
-2
@@ -35,13 +35,17 @@ spelling; its literal chip accepts what you typed. The filter never changes the
|
||||
|
||||
On space, the Kotlin decoder compares each tap with the measured key centres and combines those distances with the previous word’s probability. It can recover a missing space. A known spelling requires a higher confidence margin than a nonword. Immediately press **Delete** to restore exactly what you typed, without the space. Undo the same replacement twice and Hex keeps that spelling in later sessions. Only rejection counts keyed by hashes are saved locally; there is no typing journal.
|
||||
|
||||
**Keyboard › Swipe typing** is on by default, as on iPhone Hex and Gboard (Gboard calls it glide typing). Slide from a letter through a word's letters and lift: a trail follows the finger and the strip shows the word so far. Lifting types the best reading, after a space unless the text before ends in one, a line break or opening punctuation, with a capital from shift or a sentence's start; names and German nouns take theirs from the capitals list. The strip then offers the next three readings; tapping one puts it in the word's place. A letter, digit or opening mark tapped next goes in after a space; a comma, period or other closing mark goes against the word. Delete right after takes the whole word back as Gboard's does: the space before it stays, the strip offers the word again, and the same swipe there types its next reading instead. Space never autocorrects a swiped word. A drag that comes back to the key it started on types that key; a hold for accents, a slide from shift or ?123, the space bar's cursor and Delete's slide work as before, and a second finger going down finishes the swipe first. Swipes work in all six layouts, in fields where Hex reads words (not passwords, addresses or URLs). ß is read through s, and French œ and æ through o and e and through a and e.
|
||||
|
||||
[SwipeDecoder](app/src/main/java/ly/anoma/hex/typing/SwipeDecoder.kt) is iPhone Hex's decoder in Kotlin with the same parameters. A path is resampled in key pitches, and the words starting and ending near its ends are read in place from the same HXTM model. Each is scored on location, shape, where the finger turned and paused, and the word before. On the iPhone benchmark's method and the held-out sentences ([swipe-bench.py](benchmark/typing/swipe-bench.py)), the Android and iPhone decoders give the same four readings for every one of 12,514 English swipes. The first word is right for 96.9% of English swipes and 94.3% of Spanish, 95.9% German, 96.4% Bokmål, 95.2% French and 96.0% Italian; the word is typed or in the strip 99.2–99.6% of the time. A swipe takes 1.0–1.4 ms at the median and under 5 ms at p99 on the API 36 emulator. [Swipe results and how to run them](benchmark/typing/README.md#swipe-typing)
|
||||
|
||||
**Keyboard settings and Hex menu → Typing feedback** control key pop-ups and key haptics independently. Both default on; Hex follows system keyboard vibration. Hold a letter, slide to an accent, and release. Turning off pop-ups leaves the deliberate accent picker available.
|
||||
|
||||
[English/Spanish typing benchmark, model sources and licences](benchmark/typing/README.md)
|
||||
|
||||
## Settings
|
||||
|
||||
After setup, Home shows **Ready** or **Finish setup**, a **Dictate** bar and four destinations, following the iOS navigation in #2054. Tap Dictate, speak, then Finish dictation: Hex displays the local result on Home. **Dictation** controls style, language, translation, cleanup and the offline speech model. **Keyboard** has layout, autocorrect, key pop-ups, haptics and a practice field. **Privacy** explains storage and links the model credits. **Labs** has an **Output** group with **Signature** (off): each keyboard dictation ends with “Sent from Hex” on its own line. The line is editable, one line of up to 200 characters, and an empty line adds nothing. The next dictation starts on a new line below the signature, and a signed dictation never continues the signature line. Home’s preview and Copy stay unsigned, and Hex’s own fields are never signed. Labs also has a **Keyboard** group with **Symbols on letter keys** (off): hold a letter from QWERTY’s home or bottom row, such as **m**, to type **/** first, with the letter’s accents after it. Symbols follow the letter, so AZERTY **q**/**w** and QWERTZ **y** get none, row 1 (including AZERTY **a**/**z**) keeps its digits, and off, the keyboard is unchanged. With Number row on, AZERTY **a**/**z** and QWERTZ **z** show their symbols (**@**, **_**) as hint and hold instead of digits. The same group has **Number row** (off): while it is on, every letter layout draws 1 2 3 4 5 6 7 8 9 0 in a row above the letters, so a digit types without switching to ?123. The digits type like normal keys, with key pop-ups, haptics and their held symbols, and shift leaves them alone. With the number row on, the letter keys’ corner digits and digit-first holds are gone, and the Symbols on letter keys hints and holds still work, with row 1 letters that have a symbol (AZERTY **a**/**z**, QWERTZ **z**) showing it instead of the digit. The keyboard is one row taller and the Hex menu keeps its keys but matches that height; switching between the letters and ?123, the symbols pages or a number pad changes the height by a row while it is on. With the toggles off the keys are exactly as before. That group also has **Emoji suggestions** (off): on the English keyboard, while an English word that names an emoji is being typed, the strip’s last slot offers it beside the word suggestions — “smile” gives 😊, “joy” or “haha” gives 😂, “heart” gives ❤️. It always takes that last slot, even when it is the only suggestion. Matching is case-insensitive and whole-word; continuing to type keeps the word, and nothing matching leaves the strip unchanged. Tapping the emoji replaces the word and commits it with the same space rules as a word suggestion. The word list uses the same 0.85 strong cut-off as iPhone Hex, plus a reviewed “joy” → 😂 and a reviewed exclusion list (number words that name clock faces, and ordinary words that name an emoji’s object in another sense), generated from the [iOS keyboard’s emoji index](../ios/HEXShared/FullKeyboard/Emoji/emoji-index-en.txt) (Unicode emoji-test 18.0 and CLDR 49, plus Hex’s chat words) by [build-emoji-suggestions.py](scripts/build-emoji-suggestions.py). It is a 10 KB asset (828 words), read lazily only while the toggle is on; the loader keeps only emoji the device’s `Paint.hasGlyph` can draw (minSdk 31 draws up to Emoji 13.1), so the strip never shows tofu. **Keyboard › Spatial autocorrect** controls tap-based correction; it starts on to preserve existing Android behavior. Turning it off keeps dictionary completions and the fixed English typo/contraction rules; turning off Keyboard › Autocorrect disables all automatic replacements.
|
||||
After setup, Home shows **Ready** or **Finish setup**, a **Dictate** bar and four destinations, following the iOS navigation in #2054. Tap Dictate, speak, then Finish dictation: Hex displays the local result on Home. **Dictation** controls style, language, translation, cleanup and the offline speech model. **Keyboard** has layout, autocorrect, swipe typing, key pop-ups, haptics and a practice field. **Privacy** explains storage and links the model credits. **Labs** has an **Output** group with **Signature** (off): each keyboard dictation ends with “Sent from Hex” on its own line. The line is editable, one line of up to 200 characters, and an empty line adds nothing. The next dictation starts on a new line below the signature, and a signed dictation never continues the signature line. Home’s preview and Copy stay unsigned, and Hex’s own fields are never signed. Labs also has a **Keyboard** group with **Symbols on letter keys** (off): hold a letter from QWERTY’s home or bottom row, such as **m**, to type **/** first, with the letter’s accents after it. Symbols follow the letter, so AZERTY **q**/**w** and QWERTZ **y** get none, row 1 (including AZERTY **a**/**z**) keeps its digits, and off, the keyboard is unchanged. With Number row on, AZERTY **a**/**z** and QWERTZ **z** show their symbols (**@**, **_**) as hint and hold instead of digits. The same group has **Number row** (off): while it is on, every letter layout draws 1 2 3 4 5 6 7 8 9 0 in a row above the letters, so a digit types without switching to ?123. The digits type like normal keys, with key pop-ups, haptics and their held symbols, and shift leaves them alone. With the number row on, the letter keys’ corner digits and digit-first holds are gone, and the Symbols on letter keys hints and holds still work, with row 1 letters that have a symbol (AZERTY **a**/**z**, QWERTZ **z**) showing it instead of the digit. The keyboard is one row taller and the Hex menu keeps its keys but matches that height; switching between the letters and ?123, the symbols pages or a number pad changes the height by a row while it is on. With the toggles off the keys are exactly as before. That group also has **Emoji suggestions** (off): on the English keyboard, while an English word that names an emoji is being typed, the strip’s last slot offers it beside the word suggestions — “smile” gives 😊, “joy” or “haha” gives 😂, “heart” gives ❤️. It always takes that last slot, even when it is the only suggestion. Matching is case-insensitive and whole-word; continuing to type keeps the word, and nothing matching leaves the strip unchanged. Tapping the emoji replaces the word and commits it with the same space rules as a word suggestion. The word list uses the same 0.85 strong cut-off as iPhone Hex, plus a reviewed “joy” → 😂 and a reviewed exclusion list (number words that name clock faces, and ordinary words that name an emoji’s object in another sense), generated from the [iOS keyboard’s emoji index](../ios/HEXShared/FullKeyboard/Emoji/emoji-index-en.txt) (Unicode emoji-test 18.0 and CLDR 49, plus Hex’s chat words) by [build-emoji-suggestions.py](scripts/build-emoji-suggestions.py). It is a 10 KB asset (828 words), read lazily only while the toggle is on; the loader keeps only emoji the device’s `Paint.hasGlyph` can draw (minSdk 31 draws up to Emoji 13.1), so the strip never shows tofu. **Keyboard › Spatial autocorrect** controls tap-based correction; it starts on to preserve existing Android behavior. Turning it off keeps dictionary completions and the fixed English typo/contraction rules; turning off Keyboard › Autocorrect disables all automatic replacements.
|
||||
|
||||
**Privacy › Privacy policy** opens the [Android policy text](play/policy/privacy-policy.txt) even in airplane mode.
|
||||
|
||||
@@ -66,7 +70,7 @@ Five unit tests passed in each of the debug and release variants. Home, the four
|
||||
## How it works
|
||||
|
||||
- **App:** Kotlin and Jetpack Compose. Welcome → microphone permission and Android’s keyboard settings/picker → a real practice field. Setup reads live system state; it remembers the page, not the words.
|
||||
- **Keyboard:** [HexKeyboard](app/src/main/java/ly/anoma/hex/keyboard/HexKeyboard.kt) is an `InputMethodService` with native key views. Letters, shift/caps lock, symbols, delete, editor actions and next keyboard use Android input APIs. It commits through the active `InputConnection`; changing editors or hiding the keyboard discards pending results. Password fields allow typing only. Typing lives in [KeyboardEngine](app/src/main/java/ly/anoma/hex/keyboard/KeyboardEngine.kt), which reaches the editor only through `KeyboardTextTarget`; the views are `KeyboardView` (strip, keys or Hex menu), `StripView` and `KeyPlaneView`; each layout's letters are data in `KeyboardLetters`.
|
||||
- **Keyboard:** [HexKeyboard](app/src/main/java/ly/anoma/hex/keyboard/HexKeyboard.kt) is an `InputMethodService` with native key views. Letters, shift/caps lock, symbols, delete, editor actions and next keyboard use Android input APIs. It commits through the active `InputConnection`; changing editors or hiding the keyboard discards pending results. Password fields allow typing only. Typing lives in [KeyboardEngine](app/src/main/java/ly/anoma/hex/keyboard/KeyboardEngine.kt), which reaches the editor only through `KeyboardTextTarget`; the views are `KeyboardView` (strip, keys or Hex menu), `StripView` and `KeyPlaneView`; each layout's letters are data in `KeyboardLetters`. `KeyPlaneView` turns a letter touch that travels a key's pitch into a swipe and draws its trail ([SwipeTyping](app/src/main/java/ly/anoma/hex/keyboard/SwipeTyping.kt)). While the finger moves, the path is read off the main thread every 70 ms; on lifting it is read on the main thread.
|
||||
- **Audio:** [MicCapture](app/src/main/java/ly/anoma/hex/speech/MicCapture.kt) records up to 60 s of mono 16 kHz PCM in RAM and releases the microphone before CPU inference. The [recognizer interface](app/src/main/java/ly/anoma/hex/speech/Whisper.kt) operates on that capture and its language/task. Hex requests no audio focus and does not change playback routing.
|
||||
- **Speed:** the model loads when the Hex key goes down, while the person speaks, and stays loaded between dictations; it is freed 2 minutes after the last one or when Android runs short of memory, and nothing runs while it waits. The encoder's window is sized to the speech for dictations up to 8 s (speech plus 3.84 s, at most the earlier 512 frames); longer ones, and the bundled tiny model, keep Whisper's full 30 s window, since every shorter one tried cost accuracy. Inference uses one thread per fast core (at least half the strongest core's `cpu_capacity`), at most four. On the 40-clip benchmark this cut the emulator's median from 0.76 s to 0.56 s with the same word errors (5.26%).
|
||||
- **Type:** unmodified [InterVariable.ttf](app/src/main/res/font/inter_variable.ttf) from [Rasmus Andersson and the Inter Project, v4.1](https://github.com/rsms/inter/releases/tag/v4.1), licensed under [SIL OFL 1.1](app/src/main/assets/licenses/inter-ofl.txt). One [Compose font family and native TextView helper](app/src/main/java/ly/anoma/hex/HexType.kt) cover Hex’s text, including keys, menus, strip labels and tabular digits (`tnum`). Android supplies missing glyphs; permission dialogs and the system keyboard picker use the OS font. Gradle verifies the bundled TTF’s SHA-256.
|
||||
|
||||
@@ -112,6 +112,7 @@ internal fun HexSettings(setup: Setup, speech: SpeechPreferences, typing: Typing
|
||||
val autocorrect = remember(revision) { typing.autocorrect }
|
||||
val swearWords = remember(revision) { typing.suggestSwearWords }
|
||||
val spatial = remember(revision) { typing.spatial }
|
||||
val swipe = remember(revision) { typing.swipe }
|
||||
val popups = remember(revision) { typing.popups }
|
||||
val haptics = remember(revision) { typing.haptics }
|
||||
val letterSymbols = remember(revision) { typing.letterSymbols }
|
||||
@@ -268,6 +269,7 @@ internal fun HexSettings(setup: Setup, speech: SpeechPreferences, typing: Typing
|
||||
Rule(); Toggle(stringResource(R.string.settings_autocorrect), stringResource(R.string.settings_autocorrect_detail), autocorrect) { typing.autocorrect = it }
|
||||
// Shown under Autocorrect while it is on, as on iPhone (it was alone on an Experiments page, on by default).
|
||||
if (autocorrect) { Rule(); Toggle(stringResource(R.string.settings_spatial), stringResource(R.string.settings_spatial_detail), spatial) { typing.spatial = it } }
|
||||
Rule(); Toggle(stringResource(R.string.settings_swipe), stringResource(R.string.settings_swipe_detail), swipe) { typing.swipe = it }
|
||||
Rule(); Toggle(stringResource(R.string.settings_swear_words), stringResource(R.string.settings_swear_words_detail), swearWords) { typing.suggestSwearWords = it }
|
||||
// The words the keyboard keeps and suggests are Android's own personal dictionary.
|
||||
Rule(); Entry(stringResource(R.string.settings_personal_dictionary), stringResource(R.string.settings_personal_dictionary_detail), "↗",
|
||||
|
||||
@@ -3,6 +3,7 @@ package ly.anoma.hex.keyboard
|
||||
import android.content.Context
|
||||
import android.content.res.ColorStateList
|
||||
import android.content.res.Configuration
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.drawable.GradientDrawable
|
||||
import android.media.AudioManager
|
||||
@@ -40,6 +41,11 @@ import kotlin.math.roundToInt
|
||||
* Keys that type as they lift do so in the order the fingers went down ([Rollover]). */
|
||||
internal class KeyPlaneView(context: Context, private val ime: HexKeyboard, private val host: KeyboardView,
|
||||
private val feedback: LetterFeedback) : LinearLayout(context) {
|
||||
private companion object {
|
||||
/** How far (key pitches) a swipe may go from where it went down and still be a tap that slid (iPhone Hex). */
|
||||
const val SLID_TAP_REACH = 1.6
|
||||
fun Int.isLight() = (Color.red(this) * 299 + Color.green(this) * 587 + Color.blue(this) * 114) / 1000 > 128
|
||||
}
|
||||
private val density = resources.displayMetrics.density
|
||||
private fun dp(value: Int) = (value * density).roundToInt()
|
||||
private fun px(value: Float) = (value * density).roundToInt()
|
||||
@@ -105,6 +111,13 @@ internal class KeyPlaneView(context: Context, private val ime: HexKeyboard, priv
|
||||
private val deleteGesture = DeleteGesture(KeyboardMetrics.DELETE_START * density, KeyboardMetrics.DELETE_STEP * density,
|
||||
KeyboardMetrics.DELETE_CANCEL * density, slop.toFloat())
|
||||
private var deleteSlide: DeleteSlide? = null
|
||||
// Keyboard › Swipe typing: the letter touch that may become a swipe (the latest finger down on a letter), the
|
||||
// swipe it became, and its trail over the keys.
|
||||
private var stroke: SwipeStroke? = null
|
||||
private var strokeKey: KeyCap? = null
|
||||
private var swipe: KeyboardEngine.SwipeContext? = null
|
||||
private val trail = SwipeTrail(this, (ink and 0xFFFFFF) or ((if (ink.isLight()) 0x80 else 0x66) shl 24), 6 * density)
|
||||
private val preview = SwipePreview { post(it) }
|
||||
private val repeatDelete = object : Runnable {
|
||||
override fun run() {
|
||||
if (deleting) { repeated = true; ime.engine.delete(); postDelayed(this, KeyboardMetrics.DELETE_REPEAT_EVERY) }
|
||||
@@ -231,7 +244,7 @@ internal class KeyPlaneView(context: Context, private val ime: HexKeyboard, priv
|
||||
// Another kind of field in the same box (the app changed its type): the keys, not the emoji panel over them.
|
||||
if (emojiOpen) host.closeEmoji()
|
||||
current = page; letterSymbolsDrawn = letterSymbols
|
||||
clearCallout(); endSlide(); grid = null; letters.clear(); caseKeys.clear(); slides.clear(); shiftIcon = null
|
||||
clearCallout(); endSlide(); cancelSwipe(); grid = null; letters.clear(); caseKeys.clear(); slides.clear(); shiftIcon = null
|
||||
rows.removeAllViews()
|
||||
page.pad?.let { showPad(page, it); return }
|
||||
bottom.visibility = VISIBLE
|
||||
@@ -298,7 +311,7 @@ internal class KeyPlaneView(context: Context, private val ime: HexKeyboard, priv
|
||||
val g = if (symbols) null else geometry()
|
||||
if (g != null) ime.engine.letter(cased(c), p.x, p.y, g) else ime.engine.type(cased(c))
|
||||
}
|
||||
typesOnLift(k, preview = { cased(c) }, holds = { listOf(holds()) },
|
||||
typesOnLift(k, preview = { cased(c) }, holds = { listOf(holds()) }, swipes = !symbols,
|
||||
down = { e ->
|
||||
downText = cased(c)
|
||||
touch = KeyPoint((k.left + e.getX(e.actionIndex)).toDouble(), (row.top + e.getY(e.actionIndex)).toDouble())
|
||||
@@ -557,8 +570,10 @@ internal class KeyPlaneView(context: Context, private val ime: HexKeyboard, priv
|
||||
* options to slide over, and on lifting (or when another key goes down first) [type] with the option
|
||||
* chosen, or null for the key's own. */
|
||||
private fun typesOnLift(k: KeyCap, preview: () -> String?, holds: () -> List<List<String>>, default: () -> Int = { 0 },
|
||||
down: (MotionEvent) -> Unit = {}, type: (String?) -> Unit, done: () -> Unit = {}) {
|
||||
swipes: Boolean = false, down: (MotionEvent) -> Unit = {}, type: (String?) -> Unit, done: () -> Unit = {}) {
|
||||
fun finish(): Boolean {
|
||||
// The key types: its touch is no swipe any more.
|
||||
if (strokeKey === k && swipe == null) forgetStroke()
|
||||
val option = if (feedback.choosing) feedback.selected() else null
|
||||
val pressed = k.isPressed; k.isPressed = false; clearCallout()
|
||||
if (pressed) type(option)
|
||||
@@ -569,8 +584,11 @@ internal class KeyPlaneView(context: Context, private val ime: HexKeyboard, priv
|
||||
when (e.actionMasked) {
|
||||
// A second finger on the same key is a second press: the first types now.
|
||||
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
|
||||
// A second finger on a swiping key: the swipe's word goes in first.
|
||||
if (e.actionMasked == MotionEvent.ACTION_POINTER_DOWN && strokeKey === k && swipe != null) { roll.up(k); finishSwipe() }
|
||||
if (e.actionMasked == MotionEvent.ACTION_POINTER_DOWN && roll.up(k)) finish()
|
||||
roll.down(k) { finish() }
|
||||
if (swipes && e.actionMasked == MotionEvent.ACTION_DOWN) strokeBegan(k, e)
|
||||
clearCallout(); v.isPressed = true
|
||||
down(e)
|
||||
val shown = preview()
|
||||
@@ -582,6 +600,7 @@ internal class KeyPlaneView(context: Context, private val ime: HexKeyboard, priv
|
||||
}
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
if (swipes && strokeMoved(k, e)) return@setOnTouchListener true
|
||||
if (feedback.choosing && v.isPressed) { val (x, y) = inHost(v, e); feedback.move(x, y) }
|
||||
else if (e.x < -slop || e.x > v.width + slop || e.y < -slop || e.y > v.height + slop) {
|
||||
if (v.isPressed) clearCallout()
|
||||
@@ -589,8 +608,14 @@ internal class KeyPlaneView(context: Context, private val ime: HexKeyboard, priv
|
||||
}
|
||||
}
|
||||
// Gboard's lighter second tick when a key types as it lifts, but not for a held option.
|
||||
MotionEvent.ACTION_UP -> if (roll.up(k) && finish()) k.typedOnLift()
|
||||
MotionEvent.ACTION_CANCEL -> if (roll.up(k)) { v.isPressed = false; clearCallout(); done() }
|
||||
MotionEvent.ACTION_UP -> when {
|
||||
swipes && strokeKey === k && swipe != null -> { roll.up(k); strokeMoved(k, e); finishSwipe(); done() }
|
||||
else -> { if (strokeKey === k) forgetStroke(); if (roll.up(k) && finish()) k.typedOnLift() }
|
||||
}
|
||||
MotionEvent.ACTION_CANCEL -> {
|
||||
if (strokeKey === k) cancelSwipe()
|
||||
if (roll.up(k)) { v.isPressed = false; clearCallout(); done() }
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
@@ -628,6 +653,95 @@ internal class KeyPlaneView(context: Context, private val ime: HexKeyboard, priv
|
||||
return (onScreen[0] - hostAt[0] + e.x) to (onScreen[1] - hostAt[1] + e.y)
|
||||
}
|
||||
|
||||
// MARK: Swipe typing
|
||||
|
||||
/** A finger went down on a letter key: it may become a swipe. */
|
||||
private fun strokeBegan(k: KeyCap, e: MotionEvent) {
|
||||
if (swipe != null) finishSwipe()
|
||||
if (!ime.engine.swipes || geometry() == null) { forgetStroke(); return }
|
||||
val row = k.parent as View
|
||||
stroke = SwipeStroke(e.getPointerId(e.actionIndex)).also { it.add(k.left + e.getX(e.actionIndex).toDouble(), row.top + e.getY(e.actionIndex).toDouble(), e.eventTime / 1000.0) }
|
||||
strokeKey = k
|
||||
}
|
||||
|
||||
/** The finger moved: true when the touch is a swipe (now or already), which the key leaves to it. A touch becomes
|
||||
* one once it travels a key's pitch from where it went down, unless its accents already show. */
|
||||
private fun strokeMoved(k: KeyCap, e: MotionEvent): Boolean {
|
||||
val st = stroke ?: return false
|
||||
if (strokeKey !== k) return false
|
||||
val index = e.findPointerIndex(st.pointer).takeIf { it >= 0 } ?: return false
|
||||
val row = k.parent as View
|
||||
val dx = k.left.toDouble(); val dy = row.top.toDouble()
|
||||
val active = swipe != null
|
||||
for (h in 0 until e.historySize) {
|
||||
val x = dx + e.getHistoricalX(index, h); val y = dy + e.getHistoricalY(index, h)
|
||||
st.add(x, y, e.getHistoricalEventTime(h) / 1000.0)
|
||||
if (active) trail.add(x.toFloat(), (y + rows.top).toFloat())
|
||||
}
|
||||
val x = dx + e.getX(index); val y = dy + e.getY(index)
|
||||
if (e.actionMasked != MotionEvent.ACTION_UP || st.xs[st.count - 1] != x || st.ys[st.count - 1] != y) {
|
||||
st.add(x, y, e.eventTime / 1000.0)
|
||||
if (active) trail.add(x.toFloat(), (y + rows.top).toFloat())
|
||||
}
|
||||
val grid = geometry() ?: return active
|
||||
if (!active) {
|
||||
if (st.travelled() <= grid.pitchX || feedback.choosing) return false
|
||||
val context = ime.engine.beginSwipe() ?: run { forgetStroke(); return false }
|
||||
swipe = context
|
||||
// The key no longer types: no pop-up, no accents, and another key going down ends the swipe first.
|
||||
k.isPressed = false; clearCallout()
|
||||
roll.down(k) { finishSwipe() }
|
||||
trail.begin(List(st.count) { floatArrayOf(st.xs[it].toFloat(), (st.ys[it] + rows.top).toFloat()) })
|
||||
preview.next()
|
||||
}
|
||||
swipe?.let { s -> preview.schedule(st, s.reader, grid, s.previous) { words -> if (swipe === s) ime.engine.swipePreview(words) } }
|
||||
return true
|
||||
}
|
||||
|
||||
/** The swipe's finger lifted, or another key went down: its word goes in, or a tap that slid types its letter. */
|
||||
private fun finishSwipe() {
|
||||
val st = stroke; val s = swipe; val key = strokeKey
|
||||
forgetStroke(); preview.next(); trail.fade()
|
||||
if (st == null || s == null) return
|
||||
val grid = geometry() ?: run { ime.engine.cancelSwipe(); return }
|
||||
val readings = s.reader.ranked(s.reader.decode(st.xs, st.ys, st.ts, st.count, grid, s.previous, 8).candidates)
|
||||
val letter = key?.let { slidTap(st, it, grid) }
|
||||
if (key != null && letter != null && readings.firstOrNull()?.let { startsAndEnds(it, letter) } != true) {
|
||||
// A tap that slid ("a" dragged a little too far and back): its letter goes in as a tap's would.
|
||||
ime.engine.cancelSwipe(); key.performClick()
|
||||
return
|
||||
}
|
||||
ime.engine.endSwipe(readings)
|
||||
}
|
||||
|
||||
/** The system took the touch away: nothing goes in. */
|
||||
private fun cancelSwipe() {
|
||||
val active = swipe != null
|
||||
forgetStroke(); preview.next()
|
||||
if (active) { trail.clear(); ime.engine.cancelSwipe() }
|
||||
}
|
||||
private fun forgetStroke() { stroke = null; strokeKey = null; swipe = null }
|
||||
|
||||
/** The letter of a swipe that lifted on the key it went down on without going more than 1.6 pitches from where it
|
||||
* started (iPhone Hex's slidTapLetter), or null. */
|
||||
private fun slidTap(st: SwipeStroke, key: KeyCap, grid: KeyGrid): Char? {
|
||||
if (!st.within(SLID_TAP_REACH * grid.pitchX)) return null
|
||||
val row = key.parent as View
|
||||
val x = st.xs[st.count - 1]; val y = st.ys[st.count - 1]
|
||||
if (x < key.left || x >= key.right || y < row.top || y >= row.bottom) return null
|
||||
return letters.entries.firstOrNull { it.value === key }?.key
|
||||
}
|
||||
/** Whether [word] begins and ends on [letter]'s key ("lol" on l): a word a swipe that comes back to its key can mean. */
|
||||
private fun startsAndEnds(word: String, letter: Char): Boolean {
|
||||
fun base(c: Char) = java.text.Normalizer.normalize(c.lowercaseChar().toString(), java.text.Normalizer.Form.NFD).first()
|
||||
return word.length > 1 && base(word.first()) == letter && base(word.last()) == letter
|
||||
}
|
||||
|
||||
override fun dispatchDraw(canvas: Canvas) {
|
||||
super.dispatchDraw(canvas)
|
||||
trail.draw(canvas)
|
||||
}
|
||||
|
||||
private fun shiftIconFor(page: KeyboardPage) = when { page.locked -> R.drawable.ic_caps_lock; page.shifted -> R.drawable.ic_shift_on; else -> R.drawable.ic_shift }
|
||||
// As Gboard's: "Shift", "Shift enabled", "Caps lock enabled".
|
||||
private fun shiftDescription(page: KeyboardPage) = context.getString(when {
|
||||
@@ -711,6 +825,7 @@ internal class KeyPlaneView(context: Context, private val ime: HexKeyboard, priv
|
||||
spaceKey.label?.textSize = if (next.translate) 12f else 14f
|
||||
}
|
||||
fun cancelGestures() {
|
||||
cancelSwipe()
|
||||
clearCallout(); endSlide(); roll.clear()
|
||||
removeCallbacks(repeatDelete); removeCallbacks(switchLanguage)
|
||||
spaceKey.isPressed = false
|
||||
|
||||
@@ -14,6 +14,7 @@ import ly.anoma.hex.typing.KeyPoint
|
||||
import ly.anoma.hex.typing.PersonalWords
|
||||
import ly.anoma.hex.typing.SpatialDecoder
|
||||
import ly.anoma.hex.typing.Suggestion
|
||||
import ly.anoma.hex.typing.SwipeReader
|
||||
import ly.anoma.hex.typing.TypingModel
|
||||
import ly.anoma.hex.typing.TypingPreferences
|
||||
import ly.anoma.hex.typing.TypingWord
|
||||
@@ -110,6 +111,19 @@ internal class KeyboardEngine(
|
||||
private var dictated: Dictated? = null
|
||||
private val dropDictation = Runnable { offerUndo(null) }
|
||||
private val continuation = DictationContinuation()
|
||||
// Keyboard › Swipe typing (SwipeTyping.kt). The word a swipe just typed, until anything else changes the text:
|
||||
// the strip offers its other readings, any of which takes its place, and delete takes it back.
|
||||
private data class Swiped(val word: String, val alternatives: List<String>)
|
||||
private var swiped: Swiped? = null
|
||||
// The text before the cursor right after a swiped word: a letter, digit or opening mark tapped next goes in after
|
||||
// a space, as Gboard keeps one pending; closing marks go against the word (SpaceRules.JOINERS).
|
||||
private var swipeAnchor: String? = null
|
||||
// The word delete just took back and the text before the cursor then: the strip offers it again (Gboard).
|
||||
private var takenBack: Pair<String, String>? = null
|
||||
private val retries = SwipeRetries()
|
||||
/** A swipe is under way: from the touch becoming one until it ends. */
|
||||
var swiping = false
|
||||
private set
|
||||
|
||||
fun startInput(attribute: EditorInfo) {
|
||||
edited()
|
||||
@@ -127,7 +141,7 @@ internal class KeyboardEngine(
|
||||
variation !in setOf(InputType.TYPE_TEXT_VARIATION_URI, InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS,
|
||||
InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS, InputType.TYPE_TEXT_VARIATION_FILTER) &&
|
||||
attribute.inputType and (InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE) == 0
|
||||
resetTyping(); word = null; clearSpaces()
|
||||
resetTyping(); word = null; clearSpaces(); forgetSwipe()
|
||||
pad = Pad.of(attribute.inputType)
|
||||
symbols = pad != null
|
||||
more = false; shift.reset()
|
||||
@@ -146,6 +160,12 @@ internal class KeyboardEngine(
|
||||
if (newSelStart != newSelEnd || suffix == null || !endsWith(suffix) ||
|
||||
oldSelStart == expectedCaret) { resetTyping(); surface?.suggestions(emptyList()) }
|
||||
}
|
||||
// The cursor left the word a swipe typed (or the place delete took it back from): its strip goes.
|
||||
val s = swiped; val back = takenBack
|
||||
if (!swiping && ((s != null && (newSelStart != newSelEnd || !endsWith(s.word))) ||
|
||||
(back != null && (newSelStart != newSelEnd || before() != back.second)))) {
|
||||
forgetSwipe(); retries.forget(); surface?.suggestions(emptyList())
|
||||
}
|
||||
refreshCaps()
|
||||
}
|
||||
}
|
||||
@@ -215,7 +235,8 @@ internal class KeyboardEngine(
|
||||
private fun resetTyping() {
|
||||
cancelChip(); word?.reset(); undo = null; expectedCaret = -1; prefix = ""
|
||||
}
|
||||
private fun clearSpaces() { spaceAnchor = null; pickedAnchor = null; heldAnchor = null }
|
||||
private fun clearSpaces() { spaceAnchor = null; pickedAnchor = null; heldAnchor = null; swipeAnchor = null }
|
||||
private fun forgetSwipe() { swiped = null; takenBack = null }
|
||||
private fun cancelChip() { pendingChip?.let(main::removeCallbacks); pendingChip = null }
|
||||
fun configureTyping(keepWord: Boolean = false) {
|
||||
val language = layoutLanguage().layoutCode
|
||||
@@ -324,8 +345,9 @@ internal class KeyboardEngine(
|
||||
}
|
||||
// A space a pick held goes in before the next word starts; returns the text before the cursor.
|
||||
private fun takeHeldSpace(before: String): String {
|
||||
if (heldAnchor == null || heldAnchor != before) return before
|
||||
heldAnchor = null
|
||||
val held = heldAnchor != null && heldAnchor == before
|
||||
if (!held && (swipeAnchor == null || swipeAnchor != before)) return before
|
||||
heldAnchor = null; swipeAnchor = null
|
||||
if (!target.commit(" ")) return before
|
||||
if (expectedCaret >= 0) expectedCaret++
|
||||
return "$before "
|
||||
@@ -346,6 +368,7 @@ internal class KeyboardEngine(
|
||||
* double-space), and a closing mark takes its place. */
|
||||
fun pickSuggestion(text: String) {
|
||||
val w = word ?: return
|
||||
if (pickSwiped(text)) return
|
||||
edited()
|
||||
if (symbols || !canEndWord()) return
|
||||
val old = w.token
|
||||
@@ -377,9 +400,11 @@ internal class KeyboardEngine(
|
||||
if (replace(" ", ". ")) { resetTyping(); showPredictions(before()); inputDone(); return }
|
||||
}
|
||||
}
|
||||
// Space never changes a swiped word: it is a reading, not a typo (iPhone Hex).
|
||||
val afterSwipe = swipeAnchor != null && swipeAnchor == b
|
||||
clearSpaces()
|
||||
val w = word
|
||||
if (w != null && !symbols && canEndWord()) {
|
||||
if (w != null && !symbols && canEndWord() && !afterSwipe) {
|
||||
val old = w.token; val lang = w.decoder.model.language
|
||||
// Your text replacements first, whatever autocorrect is set to; they never offer an undo.
|
||||
val swap = w.textReplacement(b)
|
||||
@@ -414,10 +439,11 @@ internal class KeyboardEngine(
|
||||
if (replace(" ", value)) { resetTyping(); showPredictions(before()); inputDone(); return }
|
||||
}
|
||||
// Anything that starts another word puts a held space in first; marks go against the word.
|
||||
val afterSwipe = swipeAnchor != null && swipeAnchor == b
|
||||
val text = if (value.any { it in SpaceRules.JOINERS || it.isWhitespace() }) b else takeHeldSpace(b)
|
||||
clearSpaces()
|
||||
val w = word
|
||||
if (mark && w != null && !symbols && canEndWord()) {
|
||||
if (mark && w != null && !symbols && canEndWord() && !afterSwipe) {
|
||||
val swap = w.textReplacement(text)
|
||||
if (swap != null && replace(swap.original, swap.replacement + value)) { resetTyping(); showPredictions(before()); inputDone(); return }
|
||||
if (feedback.autocorrect && w.token.isNotEmpty() && endsWith(prefix + w.token)) {
|
||||
@@ -431,6 +457,7 @@ internal class KeyboardEngine(
|
||||
}
|
||||
fun delete() {
|
||||
if (!target.connected) return
|
||||
if (deleteSwiped()) return
|
||||
edited()
|
||||
// Right after a pick held its space, delete takes that space back and deletes nothing.
|
||||
if (heldAnchor != null && heldAnchor == before()) { clearSpaces(); surface?.suggestions(emptyList()); return }
|
||||
@@ -544,5 +571,134 @@ internal class KeyboardEngine(
|
||||
if (shown || next != null) surface?.undoDictation(next != null)
|
||||
}
|
||||
/** Any edit through the keys ends the Undo dictation offer, and a signed dictation's effect on the next. */
|
||||
private fun edited() { if (dictated != null) offerUndo(null); continuation.clear() }
|
||||
private fun edited() { if (dictated != null) offerUndo(null); continuation.clear(); forgetSwipe(); retries.forget() }
|
||||
|
||||
// MARK: Swipe typing (Keyboard › Swipe typing; SwipeTyping.kt and KeyPlaneView)
|
||||
|
||||
/** What a swipe here is read with: the layout's reader and the word before. */
|
||||
class SwipeContext(val reader: SwipeReader, val previous: String?)
|
||||
|
||||
/** Whether a letter touch may become a swipe now: the setting on, on the letters page of an ordinary text field
|
||||
* (not a password, address, URL or number, where Hex reads no words), with its typing model loaded. */
|
||||
val swipes get() = feedback.swipe && !secure && word != null && !symbols && pad == null && target.connected
|
||||
|
||||
/** A letter touch became a swipe: its key no longer types. Null when it can't be one here. */
|
||||
fun beginSwipe(): SwipeContext? {
|
||||
val w = word ?: return null
|
||||
if (!swipes) return null
|
||||
// A word delete took back stays remembered for this swipe; anything else ends the Undo dictation offer.
|
||||
if (dictated != null) offerUndo(null)
|
||||
continuation.clear(); cancelChip(); forgetSwipe()
|
||||
val reader = w.decoder.swipe.also { it.prepare(feedback.suggestSwearWords) }
|
||||
swiping = true
|
||||
surface?.suggestions(emptyList())
|
||||
val b = before()
|
||||
return SwipeContext(reader, TypingWord.previousWord(if (SwipeText.needsSpace(b)) "$b " else b).takeIf { it.isNotEmpty() })
|
||||
}
|
||||
|
||||
/** The swipe under way reads as [readings] so far, best first: the strip shows the first, as it would go in. */
|
||||
fun swipePreview(readings: List<String>) {
|
||||
if (!swiping) return
|
||||
val b = before()
|
||||
val first = retries.reordered(readings, b).firstOrNull() ?: return
|
||||
surface?.suggestions(listOf(Suggestion(swipeCased(first, swipeCapital(b, SwipeText.needsSpace(b))), Suggestion.Kind.Word)))
|
||||
}
|
||||
|
||||
/** The swipe ended: its best reading goes in (none when [readings] is empty, as for a cancelled swipe), after a
|
||||
* space unless the text before ends in one or in opening punctuation, with a capital from shift or the sentence,
|
||||
* and the strip offers the next three. The next tapped letter goes in after a space; a closing mark against it. */
|
||||
fun endSwipe(readings: List<String>) {
|
||||
if (!swiping) return
|
||||
swiping = false
|
||||
val w = word
|
||||
if (!target.connected || w == null || readings.isEmpty()) { surface?.suggestions(emptyList()); return }
|
||||
val b = before()
|
||||
val ordered = retries.typing(readings, b)
|
||||
val space = SwipeText.needsSpace(b)
|
||||
val capital = swipeCapital(b, space)
|
||||
val text = swipeCased(ordered.first(), capital)
|
||||
val alternatives = swipeAlternatives(w, ordered, capital)
|
||||
clearSpaces(); resetTyping()
|
||||
if (!target.commit(if (space) " $text" else text)) return
|
||||
swiped = Swiped(text, alternatives); takenBack = null
|
||||
swipeAnchor = before()
|
||||
surface?.suggestions(alternatives.map { Suggestion(it, Suggestion.Kind.Word) })
|
||||
inputDone()
|
||||
}
|
||||
|
||||
/** A swipe that read as nothing, was cancelled, or was a tap that slid: nothing goes in. */
|
||||
fun cancelSwipe() {
|
||||
if (!swiping) return
|
||||
swiping = false
|
||||
surface?.suggestions(emptyList())
|
||||
}
|
||||
|
||||
/** Whether a swiped word starts with a capital: shift (one-shot, held, caps lock, or the field's own capital at
|
||||
* the cursor), or the capital the space the swipe adds brings to a sentence ("Hi." then a swipe types " There"). */
|
||||
private fun swipeCapital(before: String, space: Boolean): Boolean {
|
||||
if (shift.uppercase) return true
|
||||
if (!space || !feedback.autoCapitalize) return false
|
||||
val mask = (editor?.inputType ?: 0) and
|
||||
(InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS or InputType.TYPE_TEXT_FLAG_CAP_WORDS or InputType.TYPE_TEXT_FLAG_CAP_SENTENCES)
|
||||
if (mask == 0) return false
|
||||
return mask != InputType.TYPE_TEXT_FLAG_CAP_SENTENCES || TypingWord.startsSentence("$before ")
|
||||
}
|
||||
|
||||
/** A reading as it goes in: all capitals with caps lock, a capital first letter with [capital], else as the word
|
||||
* list writes it mid-sentence (names and German nouns with their capital, "I", your own spellings). */
|
||||
private fun swipeCased(reading: String, capital: Boolean): String {
|
||||
if (shift.locked) return reading.uppercase()
|
||||
val shown = word?.swiped(reading, TypingWord.previousWord(before()).takeIf { it.isNotEmpty() }) ?: reading
|
||||
return if (capital) shown.replaceFirstChar { it.uppercase() } else shown
|
||||
}
|
||||
|
||||
/** The strip's other readings after a swipe, cased as its word is; a reading that is one of your shortcuts shows
|
||||
* as its phrase (the swiped word's first), which space never puts in. */
|
||||
private fun swipeAlternatives(w: TypingWord, readings: List<String>, capital: Boolean): List<String> {
|
||||
val out = ArrayList<String>(3)
|
||||
fun phrase(reading: String) = w.decoder.personal?.shortcut(if (capital) reading.replaceFirstChar { it.uppercase() } else reading)
|
||||
phrase(readings.first())?.let(out::add)
|
||||
for (r in readings.drop(1)) {
|
||||
val item = phrase(r) ?: swipeCased(r, capital)
|
||||
if (out.none { it == item }) out.add(item)
|
||||
if (out.size == 3) break
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** The strip tapped right after a swipe: another reading takes the swiped word's place, or a word delete took
|
||||
* back goes in again. False when [text] isn't one of them. */
|
||||
private fun pickSwiped(text: String): Boolean {
|
||||
val back = takenBack
|
||||
if (back != null && back.first == text) {
|
||||
if (before() != back.second || !target.commit(text)) { forgetSwipe(); return false }
|
||||
takenBack = null
|
||||
swiped = Swiped(text, emptyList()); swipeAnchor = before()
|
||||
surface?.suggestions(emptyList()); inputDone(); return true
|
||||
}
|
||||
val s = swiped ?: return false
|
||||
if (text !in s.alternatives) return false
|
||||
if (swipeAnchor != before() || !replace(s.word, text)) { forgetSwipe(); return false }
|
||||
val alternatives = (listOf(s.word) + s.alternatives.filter { it != text }).take(3)
|
||||
swiped = Swiped(text, alternatives); swipeAnchor = before()
|
||||
surface?.suggestions(alternatives.map { Suggestion(it, Suggestion.Kind.Word) })
|
||||
return true
|
||||
}
|
||||
|
||||
/** Right after a swipe, delete takes back its whole word, as Gboard's does: the space before it stays, the strip
|
||||
* offers the word again, and the next swipe there types its next reading. */
|
||||
private fun deleteSwiped(): Boolean {
|
||||
val s = swiped ?: return false
|
||||
val b = before()
|
||||
if (swipeAnchor != b || !b.endsWith(s.word) || !replace(s.word, "")) return false
|
||||
if (dictated != null) offerUndo(null)
|
||||
continuation.clear(); clearSpaces(); resetTyping()
|
||||
val left = before()
|
||||
swiped = null
|
||||
retries.tookBack(s.word, left)
|
||||
takenBack = s.word to left
|
||||
surface?.suggestions(listOf(Suggestion(s.word, Suggestion.Kind.Word)))
|
||||
refreshCaps()
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
package ly.anoma.hex.keyboard
|
||||
|
||||
import android.animation.ValueAnimator
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Paint
|
||||
import android.os.SystemClock
|
||||
import android.view.View
|
||||
import java.util.concurrent.Executor
|
||||
import java.util.concurrent.Executors
|
||||
import ly.anoma.hex.typing.KeyGrid
|
||||
import ly.anoma.hex.typing.SwipeReader
|
||||
import kotlin.math.hypot
|
||||
|
||||
/** Keyboard › Swipe typing's text rules, as Gboard places a glided word (black box, Pixel 8 emulator, API 36) and
|
||||
* iPhone Hex where Gboard says nothing. */
|
||||
internal object SwipeText {
|
||||
/** Whether a swiped word needs a space before it: 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. */
|
||||
fun needsSpace(before: String?): Boolean {
|
||||
val last = before?.lastOrNull() ?: return false
|
||||
if (last.isWhitespace() || last == '\uFFFC' || last in OPENING) return false
|
||||
if (last == '"' || last == '\'') {
|
||||
val previous = before.getOrNull(before.length - 2)
|
||||
return !(previous == null || previous.isWhitespace() || previous in OPENING)
|
||||
}
|
||||
return true
|
||||
}
|
||||
private const val OPENING = "([{<«‹“‘„¿¡@#/"
|
||||
}
|
||||
|
||||
/** Words Delete took back right after a swipe typed them, at one place in the text: the next swipe there types its
|
||||
* next reading instead (Gboard: "there" deleted, the same path swiped again types "they're"). One place: the text
|
||||
* before it is the same, trailing spaces aside. Any other edit forgets them. */
|
||||
internal class SwipeRetries {
|
||||
private var place: String? = null
|
||||
private val words = ArrayList<String>()
|
||||
|
||||
/** [readings] with the words taken back where [before] ends moved after the others. */
|
||||
fun reordered(readings: List<String>, before: String?): List<String> {
|
||||
if (words.isEmpty() || place(before) != place) return readings
|
||||
return readings.filter { it.lowercase() !in words } + readings.filter { it.lowercase() in words }
|
||||
}
|
||||
|
||||
/** [reordered], for a swipe going in now; one somewhere else forgets the words. */
|
||||
fun typing(readings: List<String>, before: String?): List<String> {
|
||||
if (place(before) != place) forget()
|
||||
return reordered(readings, before)
|
||||
}
|
||||
|
||||
/** Delete took back [word], which had [before] before it. */
|
||||
fun tookBack(word: String, before: String?) {
|
||||
val at = place(before)
|
||||
if (at != place) { words.clear(); place = at }
|
||||
words.add(word.lowercase())
|
||||
}
|
||||
|
||||
fun forget() { place = null; words.clear() }
|
||||
|
||||
private fun place(before: String?) = before.orEmpty().trimEnd(' ')
|
||||
}
|
||||
|
||||
/** The light trail behind a swiping finger, drawn over the keys by [KeyPlaneView]: the last [TAIL_MS] of its path,
|
||||
* shortening behind the finger (iPhone Hex's), in the keys' ink; it fades out when the finger lifts, animated as the
|
||||
* strip's recording bar is, only while Android's animations are on. */
|
||||
internal class SwipeTrail(private val view: View, color: Int, width: Float) {
|
||||
private companion object {
|
||||
const val TAIL_MS = 450L
|
||||
const val FADE_MS = 200L
|
||||
const val MAX = 512
|
||||
}
|
||||
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
style = Paint.Style.STROKE; strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND; strokeWidth = width; this.color = color
|
||||
}
|
||||
private val alpha = android.graphics.Color.alpha(color)
|
||||
private val xs = FloatArray(MAX); private val ys = FloatArray(MAX); private val at = LongArray(MAX)
|
||||
private val path = android.graphics.Path()
|
||||
private var count = 0
|
||||
private var live = false
|
||||
private var fade = 1f
|
||||
private var fading: ValueAnimator? = null
|
||||
|
||||
val showing get() = count >= 2
|
||||
|
||||
fun begin(points: List<FloatArray>) {
|
||||
fading?.cancel(); fading = null; fade = 1f
|
||||
count = 0; live = true
|
||||
val now = SystemClock.uptimeMillis()
|
||||
for (p in points) add(p[0], p[1], now)
|
||||
}
|
||||
|
||||
fun add(x: Float, y: Float, time: Long = SystemClock.uptimeMillis()) {
|
||||
if (count == MAX) { System.arraycopy(xs, 1, xs, 0, MAX - 1); System.arraycopy(ys, 1, ys, 0, MAX - 1); System.arraycopy(at, 1, at, 0, MAX - 1); count-- }
|
||||
xs[count] = x; ys[count] = y; at[count] = time; count++
|
||||
view.postInvalidateOnAnimation()
|
||||
}
|
||||
|
||||
/** The finger lifted: the trail fades out. */
|
||||
fun fade() {
|
||||
live = false
|
||||
if (!showing || !ValueAnimator.areAnimatorsEnabled()) { clear(); return }
|
||||
fading = ValueAnimator.ofFloat(1f, 0f).apply {
|
||||
duration = FADE_MS
|
||||
addUpdateListener { fade = it.animatedValue as Float; view.invalidate() }
|
||||
addListener(object : android.animation.AnimatorListenerAdapter() {
|
||||
override fun onAnimationEnd(animation: android.animation.Animator) { if (fading === animation) clear() }
|
||||
})
|
||||
start()
|
||||
}
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
fading?.cancel(); fading = null
|
||||
live = false; count = 0; fade = 1f
|
||||
view.invalidate()
|
||||
}
|
||||
|
||||
fun draw(canvas: Canvas) {
|
||||
if (count < 2) return
|
||||
val now = SystemClock.uptimeMillis()
|
||||
// Points older than the tail drop off behind the finger, down to its last stretch.
|
||||
var first = 0
|
||||
while (first < count - 2 && now - at[first] > TAIL_MS) first++
|
||||
path.rewind()
|
||||
path.moveTo(xs[first], ys[first])
|
||||
for (i in first + 1 until count) path.lineTo(xs[i], ys[i])
|
||||
paint.alpha = (alpha * fade).toInt().coerceIn(0, 255)
|
||||
canvas.drawPath(path, paint)
|
||||
if (live) view.postInvalidateOnAnimation()
|
||||
}
|
||||
}
|
||||
|
||||
/** One letter touch that may become a swipe, and the swipe it became: its points in the keys' coordinates (the
|
||||
* KeyGrid's) and their times. */
|
||||
internal class SwipeStroke(val pointer: Int) {
|
||||
var xs = DoubleArray(128); var ys = DoubleArray(128); var ts = DoubleArray(128)
|
||||
var count = 0
|
||||
fun add(x: Double, y: Double, seconds: Double) {
|
||||
if (count == xs.size) { xs = xs.copyOf(count * 2); ys = ys.copyOf(count * 2); ts = ts.copyOf(count * 2) }
|
||||
xs[count] = x; ys[count] = y; ts[count] = seconds; count++
|
||||
}
|
||||
fun travelled() = if (count < 2) 0.0 else hypot(xs[count - 1] - xs[0], ys[count - 1] - ys[0])
|
||||
/** Whether every point stayed within [reach] of the first. */
|
||||
fun within(reach: Double): Boolean { for (i in 0 until count) if (hypot(xs[i] - xs[0], ys[i] - ys[0]) > reach) return false; return true }
|
||||
}
|
||||
|
||||
/** Reads a swipe's path so far off the main thread, at most every [INTERVAL_MS], for the strip while the finger
|
||||
* moves (iPhone: 70 ms). Results for an older swipe are dropped. */
|
||||
internal class SwipePreview(private val post: (Runnable) -> Unit) {
|
||||
companion object { const val INTERVAL_MS = 70L }
|
||||
private val worker: Executor by lazy { Executors.newSingleThreadExecutor { Thread(it, "Hex swipe").apply { isDaemon = true } } }
|
||||
private var inFlight = false
|
||||
private var last = 0L
|
||||
var generation = 0
|
||||
private set
|
||||
|
||||
fun next() { generation++; last = 0L }
|
||||
|
||||
fun schedule(stroke: SwipeStroke, reader: SwipeReader, grid: KeyGrid, previous: String?, show: (List<String>) -> Unit) {
|
||||
val now = SystemClock.uptimeMillis()
|
||||
if (inFlight || stroke.count < 3 || now - last < INTERVAL_MS) return
|
||||
inFlight = true; last = now
|
||||
val n = stroke.count
|
||||
val xs = stroke.xs.copyOf(n); val ys = stroke.ys.copyOf(n); val ts = stroke.ts.copyOf(n)
|
||||
val generation = generation
|
||||
worker.execute {
|
||||
val words = reader.ranked(reader.decode(xs, ys, ts, n, grid, previous, 3).candidates)
|
||||
post(Runnable { inFlight = false; if (generation == this.generation) show(words) })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,8 @@ internal class PersonalWords(private val model: TypingModel, words: Collection<S
|
||||
}
|
||||
|
||||
val isEmpty get() = codes.isEmpty() && shortcuts.isEmpty()
|
||||
/** Your words, spelled your way. */
|
||||
val words: List<String> get() = texts.asList()
|
||||
override val size get() = codes.size
|
||||
override fun length(word: Int) = codes[word].size
|
||||
private fun byte(word: Int, depth: Int) = if (depth < codes[word].size) codes[word][depth].toInt() and 255 else -1
|
||||
|
||||
@@ -24,6 +24,8 @@ internal class KeyGrid(val centres: Map<Char, KeyPoint>, val pitchX: Double, val
|
||||
internal class SpatialDecoder(val model: TypingModel) {
|
||||
/** Your own words (`PersonalWords`), read beside the model's; null or empty without any. */
|
||||
@Volatile var personal: PersonalWords? = null
|
||||
/** Keyboard › Swipe typing's reader for this language, made at the first swipe. */
|
||||
val swipe by lazy { SwipeReader(this) }
|
||||
/** `spaceCost`: what reading this tap as a space the finger missed costs when it landed on
|
||||
* the bottom row's upper half, or infinity (`spaceTapCost`). */
|
||||
class Tap(val cost: DoubleArray, val choices: IntArray, val belowLetters: Boolean, val missedSpaceCost: Double,
|
||||
|
||||
@@ -0,0 +1,656 @@
|
||||
package ly.anoma.hex.typing
|
||||
|
||||
import java.text.Normalizer
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.atan2
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.exp
|
||||
import kotlin.math.ln
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
import kotlin.math.sqrt
|
||||
|
||||
/** Reads a finger's path across the letter keys as a word (Keyboard › Swipe typing). A port of iPhone
|
||||
* Hex's `SwipeDecoder`, a shape-matching decoder after SHARK2 (Kristensson and Zhai, 2004), with the same
|
||||
* parameters, so the two platforms read a path alike:
|
||||
* 1. The path is resampled to evenly spaced points in key pitches (the grid's [KeyGrid.pitchX] across and
|
||||
* [KeyGrid.pitchY] down), so a slip of half a key counts the same either way.
|
||||
* 2. Words come from the typing model's sorted word list: the words starting on a key near where the finger
|
||||
* went down are one range of it per letter, read in place from the mapped file. 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 (a quick point-by-point pass, then
|
||||
* dynamic time warping for the best 80), on its shape alone, and on how near the finger went down and
|
||||
* lifted to its first and last keys;
|
||||
* 4. the best 80 also on how their keys account for where the finger turned and slowed (from the touches'
|
||||
* times): a straight stroke runs over the letters between its ends, so the path alone can't tell "tired"
|
||||
* from "tied"; a pause on r can;
|
||||
* 5. and weighed with the model's frequency of the word after the word before.
|
||||
* A letter without a key reads through the keys a person swipes for it: ß through s, French œ and æ
|
||||
* through o and e, a and e (iPhone drops those words). Nothing is built ahead or kept between swipes, and a
|
||||
* read touches only the mapped model and its own arrays, so it may run off the main thread. */
|
||||
internal class SwipeDecoder(val model: TypingModel, val parameters: Parameters = Parameters()) {
|
||||
/** iPhone's, tuned on synthetic swipes of the autocorrect benchmark's held-out dev sentences (English
|
||||
* and Spanish; experiment 2026-11-20-hex-swipe-typing), never its test sentences. */
|
||||
data class Parameters(
|
||||
/** Points the gesture and each word's ideal path are resampled to. */
|
||||
val samples: Int = 32,
|
||||
/** Keys this many pitches from where the finger went down (lifted) may start (end) the word. */
|
||||
val startRadius: Double = 1.6,
|
||||
val endRadius: Double = 2.1,
|
||||
val maxStartKeys: Int = 4,
|
||||
val maxEndKeys: Int = 8,
|
||||
/** Every key of a word passes at most this far from the path (pitches). */
|
||||
val nearRadius: Double = 1.5,
|
||||
/** How much shorter or longer than the gesture a word's ideal path may be. */
|
||||
val minLengthRatio: Double = 0.4,
|
||||
val maxLengthRatio: Double = 1.8,
|
||||
/** How far from its first and last keys a finger goes down and lifts: most within the first
|
||||
* spread, the rest ([stray]) within the wider second. */
|
||||
val startSigma: Double = 0.3,
|
||||
val endSigma: Double = 0.3,
|
||||
val startStraySigma: Double = 0.8,
|
||||
val endStraySigma: Double = 0.9,
|
||||
val stray: Double = 0.25,
|
||||
/** Nats per mean squared pitch between the paths, and between their shapes (each in a unit box). */
|
||||
val locationWeight: Double = 30.0,
|
||||
val shapeWeight: Double = 60.0,
|
||||
/** Weight of the word model's cost, -ln P(word | word before). */
|
||||
val lmWeight: Double = 1.0,
|
||||
/** Words of the quick pass the aligned pass scores again. */
|
||||
val shortlist: Int = 80,
|
||||
/** Past this many words, only the likeliest by how near their keys lie to the path get the quick pass. */
|
||||
val prefilter: Int = 1500,
|
||||
/** How far (a share of the samples) the aligned pass may run ahead or behind. */
|
||||
val band: Double = 0.1,
|
||||
/** The shortest path read as a swipe (pitches). */
|
||||
val minimumLength: Double = 0.6,
|
||||
/** A contraction whose first word never follows the word before in the model's pairs costs this much more. */
|
||||
val contractionMissingPair: Double = 3.0,
|
||||
/** Turns and pauses: the path is read every [evidenceStep] pitches. */
|
||||
val evidenceStep: Double = 0.1,
|
||||
val turnWindow: Double = 0.2,
|
||||
val turnFrom: Double = 35.0,
|
||||
val turnFull: Double = 120.0,
|
||||
val dwellWindow: Double = 0.1,
|
||||
val dwellFrom: Double = 1.3,
|
||||
val dwellFull: Double = 4.0,
|
||||
val evidenceFloor: Double = 0.1,
|
||||
val evidenceSpacing: Double = 0.8,
|
||||
val evidenceGuard: Double = 0.7,
|
||||
val evidenceSigma: Double = 0.35,
|
||||
val evidenceReach: Double = 1.4,
|
||||
/** Nats for a full turn or pause no key of the word accounts for, a key the word goes straight
|
||||
* through without a pause (only with times), and a key it turns at without a turn or pause. */
|
||||
val unexplainedCost: Double = 6.0,
|
||||
val straightKeyCost: Double = 2.5,
|
||||
val cornerKeyCost: Double = 2.0,
|
||||
val straightAngle: Double = 20.0,
|
||||
) {
|
||||
/** -ln of a point landing [squared] pitches² from a key's centre under a tight and a stray spread; 0 at the centre. */
|
||||
fun cost(squared: Double, sigma: Double, straying: Double): Double {
|
||||
val near = (1 - stray) / (sigma * sigma)
|
||||
val far = stray / (straying * straying)
|
||||
val density = near * exp(-squared / (2 * sigma * sigma)) + far * exp(-squared / (2 * straying * straying))
|
||||
return ln((near + far) / max(density, java.lang.Double.MIN_NORMAL))
|
||||
}
|
||||
}
|
||||
|
||||
/** A reading: the word as the model spells it (lowercase, with its accents), or an extra word as given. */
|
||||
data class Candidate(val text: String, val cost: Double)
|
||||
data class Reading(val candidates: List<Candidate>, val scored: Int)
|
||||
|
||||
/** Words read beside the model's, each with its own cost (-ln P): English contractions, which Google
|
||||
* Books barely counts ("do n't"), and your own words. */
|
||||
class ExtraWords(model: TypingModel, entries: List<Word>) {
|
||||
/** A word as you'd see it ("I'm"), its cost, and whether it is a contraction its first word's pairs weigh. */
|
||||
data class Word(val text: String, val cost: Double, val contraction: Boolean = false)
|
||||
val codes: List<IntArray>
|
||||
val texts: List<String>
|
||||
val costs: DoubleArray
|
||||
/** The model's index of the same word, for its pairs; -1 when it lacks it. */
|
||||
val modelIndex: IntArray
|
||||
/** A contraction's first word in the model ("i" for "I'm"), whose pairs weigh it after the word before; -1 otherwise. */
|
||||
val heads: IntArray
|
||||
init {
|
||||
val seen = HashSet<String>()
|
||||
val c = ArrayList<IntArray>(); val t = ArrayList<String>(); val k = ArrayList<Double>()
|
||||
val m = ArrayList<Int>(); val h = ArrayList<Int>()
|
||||
for ((word, cost, contraction) in entries) {
|
||||
val lower = word.lowercase()
|
||||
if (lower.length < 2 || !seen.add(lower)) continue
|
||||
val encoded = IntArray(lower.length) { model.code(lower[it]) }
|
||||
if (encoded.any { it == 0 }) continue
|
||||
c.add(encoded); t.add(word); k.add(cost); m.add(model.index(lower))
|
||||
h.add(if (contraction) head(lower)?.let(model::index) ?: -1 else -1)
|
||||
}
|
||||
codes = c; texts = t; costs = k.toDoubleArray(); modelIndex = m.toIntArray(); heads = h.toIntArray()
|
||||
}
|
||||
val size get() = texts.size
|
||||
companion object {
|
||||
/** A contraction's first word: "do" for "don't", "i" for "i'm". */
|
||||
fun head(contraction: String): String? {
|
||||
if (contraction.endsWith("n't")) return contraction.dropLast(3)
|
||||
val apostrophe = contraction.indexOf('\'')
|
||||
return if (apostrophe > 0) contraction.substring(0, apostrophe) else null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Swear words may be read (Keyboard › Suggest swear words); slurs never are. */
|
||||
@Volatile var swears = false
|
||||
@Volatile var extra: ExtraWords? = null
|
||||
set(value) {
|
||||
field = value
|
||||
extraIndices = value?.modelIndex?.filter { it >= 0 }?.toHashSet() ?: emptySet()
|
||||
}
|
||||
/** The model's words that [extra] also has, read only as extra words. */
|
||||
@Volatile private var extraIndices: Set<Int> = emptySet()
|
||||
|
||||
/** The likeliest words for a swipe along the points ([xs], [ys], the first [count], in [grid]'s
|
||||
* coordinates), best first; empty when it can't be read as one. [times] (seconds, each point's) show
|
||||
* where the finger paused; without them only its turns count. [previous] is the word before, lowercase. */
|
||||
fun read(xs: DoubleArray, ys: DoubleArray, times: DoubleArray?, count: Int, grid: KeyGrid, previous: String?, limit: Int = 4): Reading {
|
||||
val p = parameters
|
||||
val none = Reading(emptyList(), 0)
|
||||
if (grid.pitchX <= 0 || grid.pitchY <= 0 || count < 2 || limit <= 0 || p.samples < 4) return none
|
||||
val keys = Keys(grid)
|
||||
if (keys.size < 2 || keys.size > 64) return none
|
||||
val gesture = Gesture.of(xs, ys, times, count, grid.pitchX, grid.pitchY, p) ?: return none
|
||||
if (gesture.length < p.minimumLength) return none
|
||||
val startX = gesture.rawX[0]; val startY = gesture.rawY[0]
|
||||
val endX = gesture.rawX[gesture.rawCount - 1]; val endY = gesture.rawY[gesture.rawCount - 1]
|
||||
|
||||
// 1. The keys the word may start and end on, and how near the path passes each key.
|
||||
val keyCount = keys.size
|
||||
val near = DoubleArray(keyCount) { distanceToPolyline(keys.x[it], keys.y[it], gesture.rawX, gesture.rawY, gesture.rawCount) }
|
||||
val startCost = DoubleArray(keyCount) { Double.POSITIVE_INFINITY }
|
||||
val endCost = DoubleArray(keyCount) { Double.POSITIVE_INFINITY }
|
||||
val starts = nearest(keys, startX, startY, p.startRadius, p.maxStartKeys)
|
||||
for ((k, squared) in starts) startCost[k] = p.cost(squared, p.startSigma, p.startStraySigma)
|
||||
var endMask = 0L
|
||||
for ((k, squared) in nearest(keys, endX, endY, p.endRadius, p.maxEndKeys)) {
|
||||
endCost[k] = p.cost(squared, p.endSigma, p.endStraySigma)
|
||||
endMask = endMask or (1L shl k)
|
||||
}
|
||||
if (starts.isEmpty() || endMask == 0L) 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.
|
||||
val words = IntList(); val offsets = IntList().also { it.add(0) }; val sequence = IntList()
|
||||
val lengths = DoubleList(); val nearness = DoubleList()
|
||||
val scratch = IntArray(64); val codes = IntArray(64)
|
||||
val gestureLength = gesture.length
|
||||
fun consider(word: IntArray, size: Int, id: Int) {
|
||||
// The last key first: most words end elsewhere.
|
||||
var j = size - 1
|
||||
while (j > 0 && keys.skips(word[j])) j--
|
||||
if (j <= 0) return
|
||||
val endKey = keys.last(word[j])
|
||||
if (endKey < 0 || endMask and (1L shl endKey) == 0L) return
|
||||
var n = 0; var last = -1; var length = 0.0; var squares = 0.0
|
||||
for (i in 0 until size) {
|
||||
val code = word[i]
|
||||
if (keys.skips(code)) continue
|
||||
val first = keys.first(code)
|
||||
if (first < 0) return
|
||||
for (pass in 0..1) {
|
||||
val k = if (pass == 0) first else keys.second(code)
|
||||
if (k < 0 || k == last) continue
|
||||
if (n >= scratch.size || near[k] > p.nearRadius) return
|
||||
if (last >= 0) length += hypot(keys.x[last] - keys.x[k], keys.y[last] - keys.y[k])
|
||||
squares += near[k] * near[k]
|
||||
scratch[n++] = k; last = k
|
||||
}
|
||||
}
|
||||
if (n < 2 || !startCost[scratch[0]].isFinite()) return
|
||||
val ratio = length / gestureLength
|
||||
if (ratio < p.minLengthRatio || ratio > p.maxLengthRatio) return
|
||||
for (i in 0 until n) sequence.add(scratch[i])
|
||||
words.add(id); lengths.add(length); offsets.add(sequence.size); nearness.add(squares / n)
|
||||
}
|
||||
val swears = swears
|
||||
val extras = extra
|
||||
val skipped = extraIndices
|
||||
for ((s, _) in starts) for (code in keys.codesOfKey[s]) {
|
||||
val lo = model.bound(0, model.words, 0, code)
|
||||
val hi = model.bound(lo, model.words, 0, code + 1)
|
||||
for (i in lo until hi) {
|
||||
if (model.neverSuggest.blocks(i, swears) || i in skipped) continue
|
||||
consider(codes, model.codes(i, codes), i)
|
||||
}
|
||||
}
|
||||
if (extras != null) for (n in 0 until extras.size) { val c = extras.codes[n]; if (c.size <= 64) consider(c, c.size, -1 - n) }
|
||||
if (words.size == 0) return none
|
||||
|
||||
// 3. A quick point-by-point pass over them all, then the aligned pass for the best.
|
||||
val samples = p.samples
|
||||
val templateX = DoubleArray(samples); val templateY = DoubleArray(samples)
|
||||
val vx = DoubleArray(64); val vy = DoubleArray(64)
|
||||
val rowA = DoubleArray(samples); val rowB = DoubleArray(samples)
|
||||
val evidenceA = DoubleArray(gesture.evidenceCount + 1); val evidenceB = DoubleArray(gesture.evidenceCount + 1)
|
||||
val band = max(1, (p.band * samples).toInt())
|
||||
fun spatial(c: Int, aligned: Boolean): Double {
|
||||
val from = offsets[c]; val to = offsets[c + 1]; val m = to - from
|
||||
for (v in from until to) { val k = sequence[v]; vx[v - from] = keys.x[k]; vy[v - from] = keys.y[k] }
|
||||
resample(vx, vy, m, lengths[c], templateX, templateY)
|
||||
val location = if (aligned) warpedDistance(gesture.pointsX, gesture.pointsY, templateX, templateY, band, rowA, rowB)
|
||||
else meanSquaredDistance(gesture.pointsX, gesture.pointsY, templateX, templateY)
|
||||
val shape = shapeDistance(gesture.shapeX, gesture.shapeY, templateX, templateY)
|
||||
val evidence = if (aligned) evidenceCost(vx, vy, m, gesture, p, evidenceA, evidenceB) else 0.0
|
||||
return startCost[sequence[from]] + endCost[sequence[to - 1]] + p.locationWeight * location + p.shapeWeight * shape + evidence
|
||||
}
|
||||
var pool = IntArray(words.size) { it }
|
||||
if (pool.size > p.prefilter) {
|
||||
val rough = DoubleArray(pool.size) { c ->
|
||||
startCost[sequence[offsets[c]]] + endCost[sequence[offsets[c + 1] - 1]] + p.locationWeight * nearness[c] +
|
||||
p.lmWeight * lmCost(words[c], -1, extras)
|
||||
}
|
||||
pool = pool.sortedWith(compareBy { rough[it] }).take(p.prefilter).toIntArray()
|
||||
}
|
||||
val quick = DoubleArray(pool.size) { spatial(pool[it], aligned = false) + p.lmWeight * lmCost(words[pool[it]], -1, extras) }
|
||||
val order = pool.indices.sortedWith(compareBy { quick[it] })
|
||||
|
||||
val previousWord = previous?.let { model.index(it.lowercase()) } ?: -1
|
||||
val scored = ArrayList<Pair<Int, Double>>()
|
||||
for (q in order.take(max(limit, p.shortlist))) {
|
||||
val c = pool[q]
|
||||
val word = words[c]
|
||||
if (word >= 0 && model.neverSuggest.blocksFollowing(word, swears, previousWord)) continue
|
||||
scored.add(word to spatial(c, aligned = true) + p.lmWeight * lmCost(word, previousWord, extras))
|
||||
}
|
||||
scored.sortBy { it.second }
|
||||
val candidates = scored.take(limit).map { (word, cost) -> Candidate(if (word >= 0) model.text(word) else extras!!.texts[-1 - word], cost) }
|
||||
return Reading(candidates, words.size)
|
||||
}
|
||||
|
||||
/** -ln P(word | previous) with the unigram backoff, as the tap decoder's; an extra word's own cost when lower. */
|
||||
private fun lmCost(id: Int, previous: Int, extras: ExtraWords?): Double {
|
||||
if (id >= 0) return model.languageCost(previous, id)
|
||||
val n = -1 - id
|
||||
var own = 0.92 + extras!!.costs[n]
|
||||
// A contraction is as much likelier after the word before as its first word is.
|
||||
val head = extras.heads[n]
|
||||
if (head >= 0 && previous >= 0) {
|
||||
val alone = 0.92 + model.unigramCost(head)
|
||||
val pair = model.pairCost(previous, head)
|
||||
own += (if (pair >= 0) pair else alone + parameters.contractionMissingPair) - alone
|
||||
}
|
||||
val index = extras.modelIndex[n]
|
||||
return if (index >= 0) min(own, model.languageCost(previous, index)) else own
|
||||
}
|
||||
|
||||
/** The grid's letter keys in pitches, and which keys each of the model's letters types through: its own,
|
||||
* else its unaccented letter's (é on e), else the keys a person swipes for it (ß on s, œ on o and e); the
|
||||
* apostrophe has none and is skipped. */
|
||||
private inner class Keys(grid: KeyGrid) {
|
||||
val x: DoubleArray; val y: DoubleArray
|
||||
private val firstKey = IntArray(model.alphabet + 1) { MISSING }
|
||||
private val secondKey = IntArray(model.alphabet + 1) { -1 }
|
||||
val codesOfKey: Array<IntArray>
|
||||
init {
|
||||
val letters = grid.centres.keys.filter { it != '\'' }.sorted()
|
||||
x = DoubleArray(letters.size) { grid.centres.getValue(letters[it]).x / grid.pitchX }
|
||||
y = DoubleArray(letters.size) { grid.centres.getValue(letters[it]).y / grid.pitchY }
|
||||
val index = HashMap<Char, Int>().apply { letters.forEachIndexed { i, c -> put(c, i) } }
|
||||
val byKey = Array(letters.size) { ArrayList<Int>() }
|
||||
for (code in 1..model.alphabet) {
|
||||
if (code == model.apostrophe) { firstKey[code] = SKIP; continue }
|
||||
val c = model.character(code)
|
||||
val own = index[c] ?: index[model.character(model.bases[code])]
|
||||
val keysOf = if (own != null) listOf(own) else spelled(c).map { index[it] ?: -1 }
|
||||
if (keysOf.isEmpty() || keysOf.any { it < 0 }) continue
|
||||
firstKey[code] = keysOf[0]
|
||||
if (keysOf.size > 1) secondKey[code] = keysOf[1]
|
||||
byKey[keysOf[0]].add(code)
|
||||
}
|
||||
codesOfKey = Array(letters.size) { byKey[it].toIntArray() }
|
||||
}
|
||||
val size get() = x.size
|
||||
fun skips(code: Int) = firstKey[code] == SKIP
|
||||
fun first(code: Int) = firstKey[code]
|
||||
fun second(code: Int) = secondKey[code]
|
||||
fun last(code: Int) = if (secondKey[code] >= 0) secondKey[code] else firstKey[code]
|
||||
}
|
||||
|
||||
/** The finger's path in pitches without repeated points, resampled, its shape, and where it turned or paused. */
|
||||
private class Gesture(val rawX: DoubleArray, val rawY: DoubleArray, val rawCount: Int, val length: Double,
|
||||
val pointsX: DoubleArray, val pointsY: DoubleArray, val shapeX: DoubleArray, val shapeY: DoubleArray,
|
||||
val evidenceX: DoubleArray, val evidenceY: DoubleArray, val strength: DoubleArray, val timed: Boolean) {
|
||||
val evidenceCount get() = strength.size
|
||||
companion object {
|
||||
fun of(xs: DoubleArray, ys: DoubleArray, times: DoubleArray?, count: Int, pitchX: Double, pitchY: Double, p: Parameters): Gesture? {
|
||||
val t = times?.takeIf { it.size >= count }
|
||||
val rawX = DoubleArray(count); val rawY = DoubleArray(count); val stamps = DoubleArray(count)
|
||||
var n = 0; var length = 0.0
|
||||
for (i in 0 until count) {
|
||||
val vx = xs[i] / pitchX; val vy = ys[i] / pitchY
|
||||
if (n > 0) {
|
||||
val step = hypot(vx - rawX[n - 1], vy - rawY[n - 1])
|
||||
if (step <= 1e-4) continue
|
||||
length += step
|
||||
}
|
||||
rawX[n] = vx; rawY[n] = vy
|
||||
// A still finger sends no points: the time it stayed goes to the next one's step.
|
||||
if (t != null) stamps[n] = if (n == 0) t[i] else max(t[i], stamps[n - 1])
|
||||
n++
|
||||
}
|
||||
if (n < 2 || length <= 0) return null
|
||||
val px = DoubleArray(p.samples); val py = DoubleArray(p.samples)
|
||||
resample(rawX, rawY, n, length, px, py)
|
||||
val (sx, sy) = normalized(px, py)
|
||||
val timed = t != null && stamps[n - 1] - stamps[0] > 0.02
|
||||
val evidence = evidence(rawX, rawY, n, if (timed) stamps else null, length, p)
|
||||
return Gesture(rawX, rawY, n, length, px, py, sx, sy, evidence[0], evidence[1], evidence[2], timed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** A common English contraction's cost (-ln P), about a word ranked 1,500th: Google Books splits them. */
|
||||
const val CONTRACTION_COST = 7.5
|
||||
/** One of your own words, as the tap decoder scores it. */
|
||||
const val OWN_WORD_COST = 11.0
|
||||
private val commonestContractions = setOf("i'm", "don't", "it's", "i'll", "can't", "that's", "didn't", "you're", "i've", "doesn't")
|
||||
private val commonContractions = setOf("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")
|
||||
/** An English contraction's cost by how often a chat uses it: the commonest like a word ranked about 300th,
|
||||
* common ones at [CONTRACTION_COST], the rest ("he'll", "ma'am") about 10,000th. */
|
||||
fun costOfContraction(word: String): Double = when (word.lowercase()) {
|
||||
in commonestContractions -> CONTRACTION_COST - 1.5
|
||||
in commonContractions -> CONTRACTION_COST
|
||||
else -> CONTRACTION_COST + 2
|
||||
}
|
||||
|
||||
private const val SKIP = -1
|
||||
private const val MISSING = -2
|
||||
|
||||
/** The letters a person swipes through for one without a key (iPhone has none for them). */
|
||||
private fun spelled(c: Char): List<Char> = when (c) {
|
||||
'ß' -> listOf('s')
|
||||
'œ' -> listOf('o', 'e')
|
||||
'æ' -> listOf('a', 'e')
|
||||
else -> Normalizer.normalize(c.toString(), Normalizer.Form.NFD).firstOrNull()?.takeIf { it != c }?.let(::listOf) ?: emptyList()
|
||||
}
|
||||
|
||||
private fun hypot(dx: Double, dy: Double) = sqrt(dx * dx + dy * dy)
|
||||
|
||||
/** The keys within [radius] of the point, nearest first, at most [limit], with their squared
|
||||
* distances; the nearest two however far. */
|
||||
private fun nearest(keys: Keys, px: Double, py: Double, radius: Double, limit: Int): List<Pair<Int, Double>> {
|
||||
val sorted = (0 until keys.size).map { it to (keys.x[it] - px).let { d -> d * d } + (keys.y[it] - py).let { d -> d * d } }
|
||||
.sortedBy { it.second }
|
||||
val found = sorted.take(limit).filter { it.second <= radius * radius }
|
||||
return if (found.size < 2) sorted.take(min(2, limit)) else found
|
||||
}
|
||||
|
||||
fun distanceToPolyline(px: Double, py: Double, lx: DoubleArray, ly: DoubleArray, count: Int): Double {
|
||||
var best = Double.POSITIVE_INFINITY
|
||||
for (i in 1 until count) {
|
||||
val ax = lx[i - 1]; val ay = ly[i - 1]
|
||||
val dx = lx[i] - ax; val dy = ly[i] - ay
|
||||
val span = dx * dx + dy * dy
|
||||
var t = if (span > 0) ((px - ax) * dx + (py - ay) * dy) / span else 0.0
|
||||
t = t.coerceIn(0.0, 1.0)
|
||||
val ex = px - (ax + t * dx); val ey = py - (ay + t * dy)
|
||||
best = min(best, ex * ex + ey * ey)
|
||||
}
|
||||
return sqrt(best)
|
||||
}
|
||||
|
||||
/** The first [count] points of a line [length] long, evenly spaced along it into the outputs, first and last included. */
|
||||
fun resample(lx: DoubleArray, ly: DoubleArray, count: Int, length: Double, outX: DoubleArray, outY: DoubleArray) {
|
||||
val samples = outX.size
|
||||
outX[0] = lx[0]; outY[0] = ly[0]
|
||||
outX[samples - 1] = lx[count - 1]; outY[samples - 1] = ly[count - 1]
|
||||
if (samples <= 2) return
|
||||
val step = length / (samples - 1)
|
||||
var segment = 0
|
||||
var walked = 0.0
|
||||
var span = hypot(lx[min(1, count - 1)] - lx[0], ly[min(1, count - 1)] - ly[0])
|
||||
for (i in 1 until samples - 1) {
|
||||
val target = step * i
|
||||
while (walked + span < target && segment < count - 2) {
|
||||
walked += span
|
||||
segment++
|
||||
span = hypot(lx[segment + 1] - lx[segment], ly[segment + 1] - ly[segment])
|
||||
}
|
||||
val b = min(segment + 1, count - 1)
|
||||
val t = if (span > 0) ((target - walked) / span).coerceIn(0.0, 1.0) else 0.0
|
||||
outX[i] = lx[segment] + t * (lx[b] - lx[segment]); outY[i] = ly[segment] + t * (ly[b] - ly[segment])
|
||||
}
|
||||
}
|
||||
|
||||
/** Centroid, and the scale that makes the bounding box's longer side 1. */
|
||||
private fun frame(xs: DoubleArray, ys: DoubleArray): DoubleArray {
|
||||
var sx = 0.0; var sy = 0.0
|
||||
var minX = Double.POSITIVE_INFINITY; var maxX = Double.NEGATIVE_INFINITY
|
||||
var minY = Double.POSITIVE_INFINITY; var maxY = Double.NEGATIVE_INFINITY
|
||||
for (i in xs.indices) {
|
||||
sx += xs[i]; sy += ys[i]
|
||||
minX = min(minX, xs[i]); maxX = max(maxX, xs[i]); minY = min(minY, ys[i]); maxY = max(maxY, ys[i])
|
||||
}
|
||||
val side = max(maxX - minX, maxY - minY)
|
||||
return doubleArrayOf(sx / xs.size, sy / xs.size, if (side > 1e-6) 1 / side else 1.0)
|
||||
}
|
||||
|
||||
private fun normalized(xs: DoubleArray, ys: DoubleArray): Pair<DoubleArray, DoubleArray> {
|
||||
val (cx, cy, scale) = frame(xs, ys).let { Triple(it[0], it[1], it[2]) }
|
||||
return DoubleArray(xs.size) { (xs[it] - cx) * scale } to DoubleArray(ys.size) { (ys[it] - cy) * scale }
|
||||
}
|
||||
|
||||
/** Mean squared distance between the gesture's normalized shape and the template's. */
|
||||
private fun shapeDistance(sx: DoubleArray, sy: DoubleArray, tx: DoubleArray, ty: DoubleArray): Double {
|
||||
val f = frame(tx, ty)
|
||||
var total = 0.0
|
||||
for (i in sx.indices) {
|
||||
val dx = sx[i] - (tx[i] - f[0]) * f[2]; val dy = sy[i] - (ty[i] - f[1]) * f[2]
|
||||
total += dx * dx + dy * dy
|
||||
}
|
||||
return total / sx.size
|
||||
}
|
||||
|
||||
private fun meanSquaredDistance(ax: DoubleArray, ay: DoubleArray, bx: DoubleArray, by: DoubleArray): Double {
|
||||
var total = 0.0
|
||||
for (i in ax.indices) { val dx = ax[i] - bx[i]; val dy = ay[i] - by[i]; total += dx * dx + dy * dy }
|
||||
return total / ax.size
|
||||
}
|
||||
|
||||
/** 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 fun warpedDistance(ax: DoubleArray, ay: DoubleArray, bx: DoubleArray, by: DoubleArray, band: Int,
|
||||
rowA: DoubleArray, rowB: DoubleArray): Double {
|
||||
val n = ax.size
|
||||
var prev = rowA; var cur = rowB
|
||||
prev.fill(Double.POSITIVE_INFINITY)
|
||||
for (i in 0 until n) {
|
||||
cur.fill(Double.POSITIVE_INFINITY)
|
||||
val lo = max(0, i - band); val hi = min(n - 1, i + band)
|
||||
for (j in lo..hi) {
|
||||
val dx = ax[i] - bx[j]; val dy = ay[i] - by[j]
|
||||
val c = dx * dx + dy * dy
|
||||
var best = if (i == 0 && j == 0) 2 * c else Double.POSITIVE_INFINITY
|
||||
if (i > 0 && j > 0) best = min(best, prev[j - 1] + 2 * c)
|
||||
if (i > 0) best = min(best, prev[j] + c)
|
||||
if (j > 0) best = min(best, cur[j - 1] + c)
|
||||
cur[j] = best
|
||||
}
|
||||
val swap = prev; prev = cur; cur = swap
|
||||
}
|
||||
return prev[n - 1] / (2 * n)
|
||||
}
|
||||
|
||||
/** The path's turns and pauses in order along it, as [x, y, strength] arrays: the path is read every
|
||||
* [Parameters.evidenceStep] pitches; a point scores by how sharply the path turns there and how long the
|
||||
* finger took over it against the rest of the swipe; the strongest at least [Parameters.evidenceSpacing]
|
||||
* apart, away from the ends, count. */
|
||||
private fun evidence(rawX: DoubleArray, rawY: DoubleArray, rawCount: Int, times: DoubleArray?, length: Double, p: Parameters): Array<DoubleArray> {
|
||||
val none = arrayOf(DoubleArray(0), DoubleArray(0), DoubleArray(0))
|
||||
val count = (length / p.evidenceStep).toInt() + 1
|
||||
if (count < 5) return none
|
||||
val px = DoubleArray(count); val py = DoubleArray(count)
|
||||
resample(rawX, rawY, rawCount, length, px, py)
|
||||
val step = length / (count - 1)
|
||||
val score = DoubleArray(count)
|
||||
val k = max(1, (p.turnWindow / step).roundToInt())
|
||||
if (count > 2 * k) for (i in k until count - k) {
|
||||
val ax = px[i] - px[i - k]; val ay = py[i] - py[i - k]
|
||||
val bx = px[i + k] - px[i]; val by = py[i + k] - py[i]
|
||||
val angle = atan2(abs(ax * by - ay * bx), ax * bx + ay * by) * 180 / Math.PI
|
||||
score[i] = ((angle - p.turnFrom) / (p.turnFull - p.turnFrom)).coerceIn(0.0, 1.0)
|
||||
}
|
||||
val guard = ceil(p.evidenceGuard / step).toInt()
|
||||
if (count <= 2 * guard + 1) return none
|
||||
if (times != null) {
|
||||
// The time at each point read, from the raw points' times along the path.
|
||||
val at = DoubleArray(count)
|
||||
var segment = 0
|
||||
var walked = 0.0
|
||||
var span = hypot(rawX[1] - rawX[0], rawY[1] - rawY[0])
|
||||
for (i in 0 until count) {
|
||||
val target = step * i
|
||||
while (walked + span < target && segment < rawCount - 2) {
|
||||
walked += span
|
||||
segment++
|
||||
span = hypot(rawX[segment + 1] - rawX[segment], rawY[segment + 1] - rawY[segment])
|
||||
}
|
||||
val t = if (span > 0) ((target - walked) / span).coerceIn(0.0, 1.0) else 0.0
|
||||
at[i] = times[segment] + t * (times[min(segment + 1, rawCount - 1)] - times[segment])
|
||||
}
|
||||
val w = max(1, (p.dwellWindow / step).roundToInt())
|
||||
val perPitch = DoubleArray(count) {
|
||||
val lo = max(0, it - w); val hi = min(count - 1, it + w)
|
||||
(at[hi] - at[lo]) / (step * (hi - lo))
|
||||
}
|
||||
val middle = perPitch.copyOfRange(guard, count - guard).also { it.sort() }
|
||||
val median = middle[middle.size / 2]
|
||||
if (median > 0) {
|
||||
val from = ln(p.dwellFrom); val full = ln(p.dwellFull)
|
||||
for (i in guard until count - guard) if (perPitch[i] > 0) {
|
||||
val dwell = ((ln(perPitch[i] / median) - from) / (full - from)).coerceIn(0.0, 1.0)
|
||||
score[i] = max(score[i], dwell)
|
||||
}
|
||||
}
|
||||
}
|
||||
// The strongest first, each keeping its neighbours within the spacing out.
|
||||
val spacing = max(1, (p.evidenceSpacing / step).roundToInt())
|
||||
val order = (guard until count - guard).filter { score[it] >= p.evidenceFloor }
|
||||
.sortedWith(compareByDescending<Int> { score[it] }.thenBy { it })
|
||||
val taken = ArrayList<Int>()
|
||||
for (i in order) if (taken.all { abs(it - i) >= spacing }) taken.add(i)
|
||||
taken.sort()
|
||||
return arrayOf(DoubleArray(taken.size) { px[taken[it]] }, DoubleArray(taken.size) { py[taken[it]] },
|
||||
DoubleArray(taken.size) { score[taken[it]] })
|
||||
}
|
||||
|
||||
/** Nats for how well a word's keys (the first [m] of [kx], [ky], in pitches) account for the path's
|
||||
* turns and pauses, in order: an edit distance where a key accounts for the ones near it, a turn or
|
||||
* pause no key accounts for costs by its strength, and a key with none costs [Parameters.cornerKeyCost]
|
||||
* where the word turns, [Parameters.straightKeyCost] where it goes straight on (when the path has
|
||||
* times). The first and last keys cost nothing without one. */
|
||||
private fun evidenceCost(kx: DoubleArray, ky: DoubleArray, m: Int, g: Gesture, p: Parameters,
|
||||
rowA: DoubleArray, rowB: DoubleArray): Double {
|
||||
val n = g.evidenceCount
|
||||
if (m < 2) return 0.0
|
||||
val reach = p.evidenceReach * p.evidenceReach
|
||||
val spread = 2 * p.evidenceSigma * p.evidenceSigma
|
||||
val straight = cos(p.straightAngle * Math.PI / 180)
|
||||
fun missing(i: Int): Double {
|
||||
if (i <= 0 || i >= m - 1) return 0.0
|
||||
val ax = kx[i] - kx[i - 1]; val ay = ky[i] - ky[i - 1]
|
||||
val bx = kx[i + 1] - kx[i]; val by = ky[i + 1] - ky[i]
|
||||
val la = hypot(ax, ay); val lb = hypot(bx, by)
|
||||
if (la <= 1e-6 || lb <= 1e-6) return 0.0
|
||||
val goesStraight = (ax * bx + ay * by) / (la * lb) >= straight
|
||||
return if (goesStraight) (if (g.timed) p.straightKeyCost else 0.0) else p.cornerKeyCost
|
||||
}
|
||||
fun accounts(i: Int, j: Int): Double {
|
||||
val dx = kx[i] - g.evidenceX[j]; val dy = ky[i] - g.evidenceY[j]
|
||||
val d = dx * dx + dy * dy
|
||||
return if (d <= reach) d / spread else Double.POSITIVE_INFINITY
|
||||
}
|
||||
fun unexplained(j: Int) = p.unexplainedCost * g.strength[j]
|
||||
// Row i: keys 0..i placed; column j: the first j turns and pauses read.
|
||||
var prev = rowA; var cur = rowB
|
||||
prev[0] = 0.0
|
||||
for (j in 0 until n) prev[j + 1] = prev[j] + min(unexplained(j), accounts(0, j))
|
||||
for (i in 1 until m) {
|
||||
val skip = missing(i)
|
||||
cur[0] = prev[0] + skip
|
||||
for (j in 0 until n) {
|
||||
val near = accounts(i, j)
|
||||
var best = prev[j + 1] + skip
|
||||
best = min(best, prev[j] + near)
|
||||
best = min(best, cur[j] + min(unexplained(j), near))
|
||||
cur[j + 1] = best
|
||||
}
|
||||
val swap = prev; prev = cur; cur = swap
|
||||
}
|
||||
return prev[n]
|
||||
}
|
||||
}
|
||||
|
||||
private class IntList {
|
||||
private var data = IntArray(256)
|
||||
var size = 0; private set
|
||||
fun add(v: Int) { if (size == data.size) data = data.copyOf(size * 2); data[size++] = v }
|
||||
operator fun get(i: Int) = data[i]
|
||||
}
|
||||
private class DoubleList {
|
||||
private var data = DoubleArray(256)
|
||||
var size = 0; private set
|
||||
fun add(v: Double) { if (size == data.size) data = data.copyOf(size * 2); data[size++] = v }
|
||||
operator fun get(i: Int) = data[i]
|
||||
}
|
||||
}
|
||||
|
||||
/** What a swipe reads as for one language, as the keyboard offers it: [SwipeDecoder]'s readings of the
|
||||
* model, English's contractions and your own words, ranked with a rare name costing more. [prepare] on the
|
||||
* main thread before a swipe; [decode] and [ranked] may then run on any thread. */
|
||||
internal class SwipeReader(private val spatial: SpatialDecoder) {
|
||||
val model get() = spatial.model
|
||||
private val decoder = SwipeDecoder(spatial.model)
|
||||
private var builtFrom: PersonalWords? = null
|
||||
private var built = false
|
||||
|
||||
/** Swear words as Suggest swear words says, and the extra words again when your own words changed. */
|
||||
fun prepare(swears: Boolean) {
|
||||
decoder.swears = swears
|
||||
val personal = spatial.personal
|
||||
if (built && personal === builtFrom) return
|
||||
built = true; builtFrom = personal
|
||||
val words = (if (model.language == "en") contractions.map { SwipeDecoder.ExtraWords.Word(it, SwipeDecoder.costOfContraction(it), true) }
|
||||
else emptyList()) + personal?.words.orEmpty().map { SwipeDecoder.ExtraWords.Word(it, SwipeDecoder.OWN_WORD_COST) }
|
||||
decoder.extra = if (words.isEmpty()) null else SwipeDecoder.ExtraWords(model, words)
|
||||
}
|
||||
|
||||
fun decode(xs: DoubleArray, ys: DoubleArray, times: DoubleArray?, count: Int, grid: KeyGrid, previous: String?, limit: Int) =
|
||||
decoder.read(xs, ys, times, count, grid, previous, limit)
|
||||
|
||||
/** The readings best first once a rare name or abbreviation costs [NAME_COST] more (iPhone's `SwipeTyping.ranked`):
|
||||
* the model's lowercase list holds names ("kent", "ut") a loose swipe of a common word could read as, and they
|
||||
* would go in capitalised mid-sentence. Common ones ("john", "york") and your own words cost nothing more. */
|
||||
fun ranked(candidates: List<SwipeDecoder.Candidate>): List<String> {
|
||||
fun rareName(text: String): Boolean {
|
||||
// German's capitals list marks its nouns, not names: they cost nothing more.
|
||||
if (model.language == "de" || text != text.lowercase() || text.length < 2 || (model.capitals?.percent(text) ?: -1) < 95) return false
|
||||
if (spatial.personal?.owns(text) == true) return false
|
||||
val i = model.index(text)
|
||||
return i < 0 || model.unigramCost(i) > COMMON_NAME_COST
|
||||
}
|
||||
return candidates.withIndex().sortedWith(compareBy<IndexedValue<SwipeDecoder.Candidate>> {
|
||||
it.value.cost + if (rareName(it.value.text)) NAME_COST else 0.0
|
||||
}.thenBy { it.index }).map { it.value.text }
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val NAME_COST = 4.0
|
||||
/** About the model's 2,500th word. */
|
||||
const val COMMON_NAME_COST = 10.0
|
||||
/** English contractions the tap decoder fixes or offers (iPhone's `AutocorrectEngine.englishContractions`). */
|
||||
val contractions: List<String> = (englishFixes.values.filter { '\'' in it } + TypingWord.suggestOnly.values).distinct().sorted()
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,16 @@ internal class TypingModel private constructor(private val data: ByteBuffer, val
|
||||
for (at in start(word) until start(word + 1)) append(chars[u8(blob + at)])
|
||||
}
|
||||
fun frequencyCost(word: Int) = u8(uni + word)
|
||||
/** -ln P(word), in nats. */
|
||||
fun unigramCost(word: Int) = frequencyCost(word) * 0.125
|
||||
/** -ln P(word | prev) from the stored pair, in nats, or -1 when the model has no such pair. */
|
||||
fun pairCost(prev: Int, word: Int): Double = pair(prev, word).let { if (it >= 0) u8(bi + it) * 0.125 else -1.0 }
|
||||
/** The word's letter codes into [out], at most its size; returns how many there are. Reads the mapping only. */
|
||||
fun codes(word: Int, out: IntArray): Int {
|
||||
val from = start(word); val n = minOf(start(word + 1) - from, out.size)
|
||||
for (i in 0 until n) out[i] = u8(blob + from + i)
|
||||
return n
|
||||
}
|
||||
fun languageCost(prev: Int, word: Int): Double {
|
||||
val backoff = 0.92 + frequencyCost(word) * 0.125
|
||||
val pair = pair(prev, word)
|
||||
|
||||
@@ -22,6 +22,10 @@ internal class TypingPreferences(context: Context) {
|
||||
var spatial: Boolean
|
||||
get() = prefs.getBoolean("spatial", true)
|
||||
set(value) { prefs.edit().putBoolean("spatial", value).apply() }
|
||||
/** Keyboard › Swipe typing: slide through a word's letters to type it. On by default, as on iPhone and Gboard. */
|
||||
var swipe: Boolean
|
||||
get() = prefs.getBoolean("swipe", true)
|
||||
set(value) { prefs.edit().putBoolean("swipe", value).apply() }
|
||||
var popups: Boolean
|
||||
get() = prefs.getBoolean("popups", true)
|
||||
set(value) { prefs.edit().putBoolean("popups", value).apply() }
|
||||
|
||||
@@ -279,6 +279,24 @@ internal class TypingWord(val decoder: SpatialDecoder, val spatial: Boolean) {
|
||||
return if (model.language == "de" && ' ' !in fix) capitalised(fix) ?: fix else fix
|
||||
}
|
||||
|
||||
/** A swiped reading ([SwipeReader]'s: the model's lowercase spelling, a contraction such as "I'm", or your own
|
||||
* word) as it goes in mid-sentence after [previous] (lowercase, or null), iPhone Hex's swipeCased: "i" and its
|
||||
* contractions, names the books nearly always capitalise and German nouns take their capital (as the tap decoder
|
||||
* gives them), your own words keep your spelling unless that is an ordinary word with a stray capital ("Will").
|
||||
* With Auto-capitalisation off, no capital you didn't type, your own spellings aside. */
|
||||
fun swiped(reading: String, previous: String?): String {
|
||||
val own = decoder.personal?.owns(reading) == true
|
||||
if (!addsCapitals) return if (own) reading else reading.lowercase()
|
||||
if (own) return if (reading.drop(1).none { it.isUpperCase() } && ordinary(reading)) reading.lowercase() else reading
|
||||
val lower = reading.lowercase()
|
||||
if (model.language == "en" && (lower == "i" || lower.startsWith("i'"))) return "I" + lower.drop(1)
|
||||
if (lower.length < 2) return lower
|
||||
val share = model.capitals?.percent(lower) ?: return lower
|
||||
val capital = share >= 95 || (model.language == "de" && share >= 50 && previous in germanDeterminers)
|
||||
val first = lower.first().uppercase()
|
||||
return if (capital && first.length == 1) first + lower.drop(1) else lower
|
||||
}
|
||||
|
||||
private fun capitalisedName(word: String): String? {
|
||||
if (word.length < 2 || word != word.lowercase() || (model.capitals?.percent(word) ?: -1) < 95) return null
|
||||
val first = word.first().uppercase()
|
||||
@@ -370,7 +388,7 @@ internal class TypingWord(val decoder: SpatialDecoder, val spatial: Boolean) {
|
||||
const val REACH = 5.0
|
||||
const val ODDS_PER_DP = .8
|
||||
// Words the strip offers in place of these, but space never puts in: each is a word too.
|
||||
private val suggestOnly = mapOf("ill" to "I'll", "id" to "I'd", "were" to "we're", "wed" to "we'd",
|
||||
val suggestOnly = mapOf("ill" to "I'll", "id" to "I'd", "were" to "we're", "wed" to "we'd",
|
||||
"well" to "we'll", "its" to "it's", "lets" to "let's", "hell" to "he'll", "shell" to "she'll")
|
||||
// Hex's own short lists, as iOS: a sentence's common first words, a clause's after a comma, and
|
||||
// the commonest words for next-word slots the model can't fill.
|
||||
|
||||
@@ -86,6 +86,8 @@
|
||||
<string name="settings_autocorrect_detail">按空格时修正拼写错误</string>
|
||||
<string name="settings_spatial">按触点自动改正</string>
|
||||
<string name="settings_spatial_detail">根据点按位置修正拼写错误</string>
|
||||
<string name="settings_swipe">滑行输入</string>
|
||||
<string name="settings_swipe_detail">滑过单词的字母即可输入</string>
|
||||
<string name="settings_swear_words">在建议中显示脏话</string>
|
||||
<string name="settings_swear_words_detail">绝不会建议歧视性词语</string>
|
||||
<string name="settings_personal_dictionary">个人字典</string>
|
||||
|
||||
@@ -94,6 +94,8 @@
|
||||
<string name="settings_autocorrect_detail">Fixes typos when you press space</string>
|
||||
<string name="settings_spatial">Spatial autocorrect</string>
|
||||
<string name="settings_spatial_detail">Uses where you tap to fix typos</string>
|
||||
<string name="settings_swipe">Swipe typing</string>
|
||||
<string name="settings_swipe_detail">Slide across a word’s letters to type it</string>
|
||||
<string name="settings_swear_words">Suggest swear words</string>
|
||||
<string name="settings_swear_words_detail">Slurs are never suggested</string>
|
||||
<string name="settings_personal_dictionary">Personal dictionary</string>
|
||||
|
||||
@@ -730,4 +730,33 @@ class InsertionTest {
|
||||
.send(FeedbackRequest(FeedbackDraft("Hi"), feedbackContext, installId = { "" })) { _, _ -> })
|
||||
}
|
||||
}
|
||||
|
||||
// Keyboard › Swipe typing: where a swiped word's space goes (Gboard's, and iPhone Hex's where Gboard says nothing).
|
||||
@Test fun aSwipedWordGetsASpaceBeforeItUnlessTheTextOpensOne() {
|
||||
assertFalse(SwipeText.needsSpace(null))
|
||||
assertFalse(SwipeText.needsSpace(""))
|
||||
assertTrue(SwipeText.needsSpace("Hello"))
|
||||
assertTrue(SwipeText.needsSpace("Hello,"))
|
||||
assertTrue(SwipeText.needsSpace("Hi."))
|
||||
assertFalse(SwipeText.needsSpace("Hello "))
|
||||
assertFalse(SwipeText.needsSpace("Hello\n"))
|
||||
for (opening in listOf("(", "[", "“", "¿", "¡", "@", "#", "/")) assertFalse(opening, SwipeText.needsSpace("see $opening"))
|
||||
assertFalse(SwipeText.needsSpace("he said \""))
|
||||
assertTrue(SwipeText.needsSpace("he said \"yes\""))
|
||||
}
|
||||
|
||||
@Test fun aSwipeWhereDeleteTookAWordBackTypesItsNextReading() {
|
||||
val retries = SwipeRetries()
|
||||
val readings = listOf("there", "they're", "three")
|
||||
assertEquals(readings, retries.typing(readings, "Hello world "))
|
||||
retries.tookBack("there", "Hello world ")
|
||||
assertEquals(listOf("they're", "three", "there"), retries.typing(readings, "Hello world "))
|
||||
retries.tookBack("they're", "Hello world")
|
||||
assertEquals(listOf("three", "there", "they're"), retries.typing(readings, "Hello world "))
|
||||
// Somewhere else, or after any other edit, the words are forgotten.
|
||||
assertEquals(readings, retries.typing(readings, "Goodbye "))
|
||||
retries.tookBack("there", "Hello world ")
|
||||
retries.forget()
|
||||
assertEquals(readings, retries.typing(readings, "Hello world "))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -581,4 +581,108 @@ class NeverSuggestTest {
|
||||
assertEquals(listOf("Je", "Le", "La"), word("fr").predictions(""))
|
||||
assertEquals(listOf("e", "ma", "che"), word("it").predictions("ciao, "))
|
||||
}
|
||||
|
||||
// Keyboard › Swipe typing's decoder (SwipeDecoder, iPhone Hex's port) on the bundled models, with straight strokes
|
||||
// through the centres of a word's keys as KeyPlaneView lays them out (the Pixel 8's 107 x 155 px pitch).
|
||||
private fun swipeGrid(language: String): KeyGrid {
|
||||
val rows = ly.anoma.hex.keyboard.KeyboardLetters.rows(language)
|
||||
val columns = maxOf(rows[0].length, rows[1].length)
|
||||
return KeyGrid(buildMap {
|
||||
for ((r, row) in rows.withIndex()) for ((i, c) in row.withIndex())
|
||||
if (c.isLetter()) put(c, KeyPoint(((columns - row.length) / 2.0 + i + 0.5) * 107.2, (r + 0.5) * 155.0))
|
||||
}, 107.2, 155.0)
|
||||
}
|
||||
private fun swipeReader(language: String, swears: Boolean = false) =
|
||||
SwipeReader(SpatialDecoder(TypingModel.file(File("src/main/assets/typing/$language.hextm"), language))).also { it.prepare(swears) }
|
||||
/** The word's keys' centres in order (an accented letter on its base letter's key, ß on s, œ on o and e), repeats run
|
||||
* together, a point every [step] px, moved by [dx], [dy]; with [pauses] (indexes into those keys) the finger stays
|
||||
* 0.15 s on them, at an even 750 px a second otherwise. */
|
||||
private fun swipe(word: String, grid: KeyGrid, dx: Double = 0.0, dy: Double = 0.0, step: Double = 16.0,
|
||||
pauses: Set<Int>? = null): Triple<DoubleArray, DoubleArray, DoubleArray?> {
|
||||
val keys = ArrayList<KeyPoint>()
|
||||
for (c in word.lowercase()) {
|
||||
if (c == '\'') continue
|
||||
val letters = when (c) { 'ß' -> "s"; 'œ' -> "oe"; else -> grid.centres[c]?.let { c.toString() }
|
||||
?: java.text.Normalizer.normalize(c.toString(), java.text.Normalizer.Form.NFD).take(1) }
|
||||
for (l in letters) grid.centres[l]?.let { if (keys.lastOrNull() != it) keys.add(it) }
|
||||
}
|
||||
val xs = ArrayList<Double>(); val ys = ArrayList<Double>(); val ts = ArrayList<Double>()
|
||||
xs.add(keys[0].x + dx); ys.add(keys[0].y + dy); ts.add(0.0)
|
||||
for (k in 1 until keys.size) {
|
||||
val a = keys[k - 1]; val b = keys[k]
|
||||
val n = maxOf(1, kotlin.math.ceil(Math.hypot(b.x - a.x, b.y - a.y) / step).toInt())
|
||||
for (i in 1..n) {
|
||||
xs.add(a.x + (b.x - a.x) * i / n + dx); ys.add(a.y + (b.y - a.y) * i / n + dy)
|
||||
ts.add(ts.last() + step / 750 + if (i == 1 && pauses?.contains(k - 1) == true) 0.15 else 0.0)
|
||||
}
|
||||
}
|
||||
return Triple(xs.toDoubleArray(), ys.toDoubleArray(), if (pauses == null) null else ts.toDoubleArray())
|
||||
}
|
||||
private fun SwipeReader.read(word: String, grid: KeyGrid, previous: String? = null, dx: Double = 0.0, dy: Double = 0.0,
|
||||
pauses: Set<Int>? = null): List<String> {
|
||||
val (xs, ys, ts) = swipe(word, grid, dx, dy, pauses = pauses)
|
||||
return ranked(decode(xs, ys, ts, xs.size, grid, previous, 4).candidates)
|
||||
}
|
||||
|
||||
@Test fun cleanSwipesReadAsTheirWordsInEveryLayout() {
|
||||
val en = swipeReader("en"); val g = swipeGrid("en")
|
||||
for (w in listOf("hello", "the", "keyboard", "world", "typing", "people", "because", "quick", "with", "you", "and"))
|
||||
assertEquals(w, en.read(w, g).first())
|
||||
// A finger that runs low all the way, or low and to the left, still reads.
|
||||
for ((dx, dy) in listOf(0.0 to 155 * .3, -107.2 / 4 to 155.0 / 4))
|
||||
for (w in listOf("hello", "keyboard", "people", "world", "because")) assertEquals("$dx,$dy", w, en.read(w, g, dx = dx, dy = dy).first())
|
||||
val es = swipeReader("es"); val ge = swipeGrid("es")
|
||||
for (w in listOf("año", "también", "gracias", "mañana", "teclado")) assertEquals(w, es.read(w, ge).first())
|
||||
assertEquals(setOf("esta", "está"), es.read("esta", ge).take(2).toSet())
|
||||
for ((language, w) in listOf("de" to "hallo", "nb" to "norsk", "fr" to "bonjour", "it" to "perché", "de" to "schön", "nb" to "kjøre"))
|
||||
assertTrue("$language: $w", w in swipeReader(language).read(w, swipeGrid(language)).take(2))
|
||||
// iPhone drops these: ß is swiped through s, œ through o and e.
|
||||
assertTrue(swipeReader("de").read("straße", swipeGrid("de")).take(3).contains("straße"))
|
||||
assertTrue(swipeReader("fr").read("cœur", swipeGrid("fr")).take(3).contains("cœur"))
|
||||
}
|
||||
|
||||
@Test fun swipedContractionsTheWordBeforeAndTooShortAPath() {
|
||||
val en = swipeReader("en"); val g = swipeGrid("en")
|
||||
assertEquals("don't", en.read("dont", g).first())
|
||||
assertEquals("I'm", en.read("im", g).first())
|
||||
assertEquals(listOf("to", "too"), en.read("to", g).take(2))
|
||||
assertEquals("too", en.read("too", g, previous = "far").first())
|
||||
val h = g.centres.getValue('h')
|
||||
assertTrue(en.decode(doubleArrayOf(h.x, h.x + 10), doubleArrayOf(h.y, h.y), null, 2, g, null, 4).candidates.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun aSwipeReadsSlursNeverAndSwearWordsOnlyWhenAsked() {
|
||||
for ((language, probes) in listOf("en" to listOf("fuck", "shit", "bitch", "nigger", "faggot"), "es" to listOf("mierda", "maricón"))) {
|
||||
for (swears in listOf(false, true)) {
|
||||
val reader = swipeReader(language, swears)
|
||||
for (probe in probes) for (reading in reader.read(probe, swipeGrid(language)))
|
||||
assertFalse("$probe read as $reading", reader.model.neverSuggest.blocks(reading, swears, -1))
|
||||
}
|
||||
}
|
||||
assertEquals("fuck", swipeReader("en", swears = true).read("fuck", swipeGrid("en")).first())
|
||||
}
|
||||
|
||||
/** A straight stroke runs over the letters between its ends; only where the finger slowed tells "tired" from "tied". */
|
||||
@Test fun aPauseOnALetterTheStrokeCrossesReadsIt() {
|
||||
val en = swipeReader("en"); val g = swipeGrid("en")
|
||||
assertEquals("tired", en.read("tired", g, pauses = setOf(2)).first())
|
||||
assertEquals("tied", en.read("tired", g, pauses = emptySet()).first())
|
||||
assertEquals("wire", en.read("wire", g, pauses = setOf(2)).first())
|
||||
assertEquals("write", en.read("write", g, pauses = setOf(1, 3)).first())
|
||||
assertEquals("put", en.read("put", g, pauses = setOf(1)).first())
|
||||
assertEquals("pit", en.read("pit", g, pauses = setOf(1)).first())
|
||||
}
|
||||
|
||||
@Test fun aSwipedWordTakesTheCapitalsTheWordListGivesIt() {
|
||||
val en = word("en")
|
||||
assertEquals("I'm", en.swiped("i'm", null))
|
||||
assertEquals("Monday", en.swiped("monday", null))
|
||||
assertEquals("the", en.swiped("the", null))
|
||||
en.addsCapitals = false
|
||||
assertEquals("i'm", en.swiped("I'm", null))
|
||||
val de = word("de")
|
||||
assertEquals("Haus", de.swiped("haus", "das"))
|
||||
assertEquals("leben", de.swiped("leben", "zu"))
|
||||
assertEquals("Leben", de.swiped("leben", "das"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,6 +48,37 @@ Outputs also drop the `. , ! ? ; :` and quotes the engine may add, and ’ reads
|
||||
|
||||
iOS numbers quoted elsewhere in this file (`ZZDecoderBench`, "iOS today") were made before the nearest-key rule, which moved them by 1–1.6 points of word error rate.
|
||||
|
||||
## Swipe typing
|
||||
|
||||
Keyboard › Swipe typing's decoder ([SwipeDecoder](../../app/src/main/java/ly/anoma/hex/typing/SwipeDecoder.kt)) is scored the way iPhone Hex's was (its experiment `2026-11-20-hex-swipe-typing`): synthetic swipes for every word of the held-out sentences above, with the true word before as context. Words of one key are tapped and words the model lacks are left out. [swipe_paths.py](swipe_paths.py) is a port of the iPhone benchmark's generator: the same random numbers, noise model and minimum-jerk timing, on the key grid both keyboards share. Its paths match the Swift generator's to 5e-6 pitch, word for word. The iPhone replay reads the same files, so the two platforms are scored on the very same paths. [SwipeReplay.java](SwipeReplay.java) decodes them with the keyboard's own `SwipeReader`: the decoder, English's contractions, the never-suggest list, then a rare name ranked lower.
|
||||
|
||||
```sh
|
||||
android/benchmark/typing/swipe-bench.py # every language, host JVM
|
||||
android/benchmark/typing/swipe-bench.py en --device emulator-5760 # time per swipe against the installed APK
|
||||
```
|
||||
|
||||
It writes the paths, each set's summary and each word's readings to `android/build/swipe-bench/`. Typical fingers, 120 Hz (2026-11-23):
|
||||
|
||||
| Layout | Words swiped | First word right | Typed or in the strip | iPhone, same paths | Emulator, median / p99 |
|
||||
|---|---:|---:|---:|---:|---:|
|
||||
| English | 12,514 | 96.9% | 99.6% | 96.9% / 99.6% | 1.00 / 3.82 ms |
|
||||
| Spanish | 12,346 | 94.3% | 99.4% | 94.3% / 99.4% | 1.28 / 5.16 ms |
|
||||
| German | 13,206 | 95.9% | 99.4% | 95.9% / 99.4% | 1.17 / 3.49 ms |
|
||||
| Bokmål | 11,845 | 96.4% | 99.3% | — | 1.10 / 3.79 ms |
|
||||
| French | 12,666 | 95.2% | 99.3% | 95.2% / 99.3% | 1.30 / 4.62 ms |
|
||||
| Italian | 11,002 | 96.0% | 99.3% | — | 1.43 / 4.69 ms |
|
||||
|
||||
"Typed or in the strip" is the word among the first four readings: the one typed and the three the strip offers. The emulator is the Studio's API 36 Pixel 8 (4 cores, ARM64), timing `SwipeReader` alone as the keyboard calls it when the finger lifts. iPhone Hex has no Bokmål or Italian model. English with neat and sloppy fingers: 99.0% / 99.9% and 82.0% / 92.2%, the same as iPhone; Spanish 96.1% / 99.9% and 83.3% / 93.4% (iPhone 83.2%).
|
||||
|
||||
On the same paths, the Android and iPhone decoders give the same four readings for every English and Spanish swipe. They differ in three ways:
|
||||
- **German pitch:** iPhone reads German with too wide a key pitch, a ten-column keyboard's (38.3 pt) where its eleven-key rows are 34.8 pt apart (`TypingDecoder.Keys`, `KeyboardLayout.letterWidth`). Android reads the keys as drawn. With that pitch corrected, iPhone gives Android's first reading on all 13,206 German swipes (Android with ß read as iPhone reads it, below): 96.0% first word right against 95.9% as iPhone ships.
|
||||
- **ß:** Android swipes a word with ß through s ("straße", "groß"); iPhone can't read one. The test set above has no ß, so there it only adds candidates: German 95.9% against 96.0% without it. On the 500 [accent-de.tsv](held-out/accent-de.tsv) sentences, each with a ß, Android gets 71.4% of the 518 ß words first and 98.3% typed or in the strip; iPhone can't read any of them. Most of the misses are old spellings ("daß") the model ranks below today's ("dass"). The other words there are unchanged (96.3% against 96.4%).
|
||||
- **French:** Android leaves out French swear words, which iPhone's never-suggest list lacks ("con", "salaud"). The first reading differs on 4 of 12,666.
|
||||
|
||||
The keyboard ranks a rare name ("kent", "ut") 4 nats lower, as iPhone does, except in German, whose capitals list marks nouns. That costs Italian 0.2 points of first word right against the decoder alone; the other layouts are unchanged.
|
||||
|
||||
Taps are unaffected: `quality-gate.py all` gives the same report, field for field, with swipe typing as without it. Separately, 30 English held-out sentences were tapped into Messages on the emulator with Swipe typing off and then on. Each run started from fresh typing preferences, and the taps were real touches that drift up to 8 px while down, moved onto Hex's keys. 29 came out the same. The first sentence after the keyboard restarted lost a tap in the run with swipe typing on ("Mnnae" for "Men as"). Typed twice more with it on, that sentence came out as it did with it off.
|
||||
|
||||
## Against today's iOS engine
|
||||
|
||||
The same 2,000 held-out English and Spanish sentences, typed by today's iOS engine (`origin/dev` 96b4f365, Spatial autocorrect on, iPhone 17 simulator, its taps moved onto today's layout key by key) and by the Android replay, which finishes each word with `TypingWord.finish` and moves each letter tap to the likelier next letter (`likelierKey`, touch areas tiling the rows) as the keyboard does. German and Bokmål have their own 2,000-sentence sets ([synthetic_sets.py](synthetic_sets.py)): held-out Tatoeba sentences typed with the same touch model on Android's eleven-key rows at a 36 pt pitch. iOS ships no Bokmål model and keeps German's behind an experiment, so those two have no iOS column.
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
package local.hex.bench;
|
||||
|
||||
import ly.anoma.hex.keyboard.KeyboardLetters;
|
||||
import ly.anoma.hex.typing.*;
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
/** Replays swipe_paths.py's paths through the keyboard's swipe reader (SwipeReader: SwipeDecoder with English's
|
||||
* contractions, never-suggest, then the rare-name ranking) on the host JVM or, with app_process, against the
|
||||
* installed APK. Never built into Hex.
|
||||
* SwipeReplay MODEL.hextm LANG PATHS.tsv.gz [WORDS.tsv]
|
||||
* Prints top-1/3/4 of the decoder's readings and of the keyboard's ranking, by frequency and length as the iPhone
|
||||
* replay does, and the time per swipe. WORDS.tsv gets each word's first four readings, the keyboard's then the decoder's. */
|
||||
public final class SwipeReplay {
|
||||
public static void main(String[] args) throws Exception {
|
||||
String lang = args[1];
|
||||
TypingModel model = TypingModel.Companion.file(new File(args[0]), lang);
|
||||
SwipeReader reader = new SwipeReader(new SpatialDecoder(model));
|
||||
reader.prepare(false);
|
||||
KeyGrid grid = canonical(lang);
|
||||
// Frequency ranks by unigram cost, as the iPhone bench buckets them.
|
||||
Integer[] order = new Integer[model.getWords()];
|
||||
for (int i = 0; i < order.length; i++) order[i] = i;
|
||||
Arrays.sort(order, Comparator.comparingInt((Integer i) -> model.frequencyCost(i)).thenComparingInt(i -> i));
|
||||
int[] rank = new int[order.length];
|
||||
for (int r = 0; r < order.length; r++) rank[order[r]] = r;
|
||||
Set<String> extra = new HashSet<>();
|
||||
if (lang.equals("en")) for (String c : SwipeReader.Companion.getContractions()) extra.add(c.toLowerCase(Locale.ROOT));
|
||||
|
||||
PrintWriter words = args.length > 3 ? new PrintWriter(new OutputStreamWriter(new FileOutputStream(args[3]), "UTF-8")) : null;
|
||||
List<long[]> rows = new ArrayList<>(); // swiped words: rank, length, decoder hit (1/3/4), keyboard hit (1/3/4)
|
||||
List<Long> nanos = new ArrayList<>();
|
||||
int total = 0, outside = 0;
|
||||
double[] xs = new double[4096], ys = new double[4096], ts = new double[4096];
|
||||
try (BufferedReader in = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(args[2])), "UTF-8"))) {
|
||||
String line;
|
||||
// Warm up the JIT on the first 200 swipes, then start over and time everything.
|
||||
List<String> lines = new ArrayList<>();
|
||||
while ((line = in.readLine()) != null) if (!line.startsWith("#")) lines.add(line);
|
||||
for (int pass = 0; pass < 2; pass++) {
|
||||
for (int li = 0; li < (pass == 0 ? Math.min(200, lines.size()) : lines.size()); li++) {
|
||||
String[] f = lines.get(li).split("\t", -1);
|
||||
String word = f[2], previous = f[3].isEmpty() ? null : f[3];
|
||||
if (pass == 1) total++;
|
||||
int index = model.index(word);
|
||||
if (index < 0 && !extra.contains(word)) { if (pass == 1) outside++; continue; }
|
||||
String[] pts = f[4].split(" ");
|
||||
int n = Math.min(pts.length, xs.length);
|
||||
for (int i = 0; i < n; i++) {
|
||||
String[] p = pts[i].split(",");
|
||||
xs[i] = Double.parseDouble(p[0]); ys[i] = Double.parseDouble(p[1]); ts[i] = Double.parseDouble(p[2]);
|
||||
}
|
||||
long start = System.nanoTime();
|
||||
SwipeDecoder.Reading reading = reader.decode(xs, ys, ts, n, grid, previous, 8);
|
||||
List<String> ranked = reader.ranked(reading.getCandidates());
|
||||
long spent = System.nanoTime() - start;
|
||||
if (pass == 0) continue;
|
||||
nanos.add(spent);
|
||||
List<String> decoded = new ArrayList<>();
|
||||
for (SwipeDecoder.Candidate c : reading.getCandidates()) decoded.add(c.getText().toLowerCase(Locale.ROOT));
|
||||
List<String> keyboard = new ArrayList<>();
|
||||
for (String r : ranked) keyboard.add(r.toLowerCase(Locale.ROOT));
|
||||
int length = word.replace("'", "").length();
|
||||
rows.add(new long[]{index >= 0 ? rank[index] : 999, length, hit(decoded, word), hit(keyboard, word)});
|
||||
if (words != null) words.println(f[0] + "\t" + f[1] + "\t" + word + "\t" + String.join(" ", keyboard.subList(0, Math.min(4, keyboard.size())))
|
||||
+ "\t" + String.join(" ", decoded.subList(0, Math.min(4, decoded.size()))));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (words != null) words.close();
|
||||
System.out.printf(Locale.ROOT, "lang %s paths %s: words %d, swiped %d, not in the model %d%n", lang, new File(args[2]).getName(), total, rows.size(), outside);
|
||||
for (int which = 2; which <= 3; which++) {
|
||||
String name = which == 2 ? "decoder" : "keyboard";
|
||||
summary(name + " ALL ", rows, which, r -> true);
|
||||
summary(name + " top1k ", rows, which, r -> r[0] < 1000);
|
||||
summary(name + " top5k ", rows, which, r -> r[0] < 5000);
|
||||
summary(name + " top20k", rows, which, r -> r[0] < 20000);
|
||||
summary(name + " rare ", rows, which, r -> r[0] >= 20000);
|
||||
}
|
||||
long[][] lengths = {{2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}, {7, 8}, {9, 99}};
|
||||
for (long[] l : lengths) summary("keyboard len " + (l[0] == l[1] ? l[0] + " " : l[1] == 99 ? l[0] + "+ " : l[0] + "-" + l[1]), rows, 3, r -> r[1] >= l[0] && r[1] <= l[1]);
|
||||
Collections.sort(nanos);
|
||||
System.out.printf(Locale.ROOT, "time per swipe ms: median %.2f p90 %.2f p99 %.2f max %.2f%n", ms(nanos, .5), ms(nanos, .9), ms(nanos, .99), nanos.get(nanos.size() - 1) / 1e6);
|
||||
}
|
||||
|
||||
/** 1 when the word is first, 3 when it is 2nd or 3rd, 4 when 4th, 0 otherwise. */
|
||||
static long hit(List<String> readings, String word) {
|
||||
int i = readings.indexOf(word);
|
||||
return i == 0 ? 1 : i == 1 || i == 2 ? 3 : i == 3 ? 4 : 0;
|
||||
}
|
||||
interface Filter { boolean test(long[] r); }
|
||||
static void summary(String name, List<long[]> rows, int column, Filter filter) {
|
||||
int n = 0, t1 = 0, t3 = 0, t4 = 0;
|
||||
for (long[] r : rows) {
|
||||
if (!filter.test(r)) continue;
|
||||
n++;
|
||||
long h = r[column];
|
||||
if (h == 1) t1++;
|
||||
if (h == 1 || h == 3) t3++;
|
||||
if (h != 0) t4++;
|
||||
}
|
||||
System.out.printf(Locale.ROOT, "%s n=%6d top1 %5.1f%% top3 %5.1f%% top4 %5.1f%%%n", name, n, pct(t1, n), pct(t3, n), pct(t4, n));
|
||||
}
|
||||
static double pct(int a, int b) { return b == 0 ? 0 : 100.0 * a / b; }
|
||||
static double ms(List<Long> sorted, double q) { return sorted.get(Math.min(sorted.size() - 1, (int) (sorted.size() * q))) / 1e6; }
|
||||
|
||||
/** The keyboard's letters on the canonical grid in key pitches (swipe_paths.py's): KeyPlaneView centres rows 1
|
||||
* and 2 in the wider row's columns and row 3 between shift and delete; the apostrophe is no letter. */
|
||||
static KeyGrid canonical(String lang) {
|
||||
List<String> rows = KeyboardLetters.INSTANCE.rows(lang);
|
||||
int columns = Math.max(rows.get(0).length(), rows.get(1).length());
|
||||
Map<Character, KeyPoint> centres = new LinkedHashMap<>();
|
||||
for (int r = 0; r < 3; r++) {
|
||||
String row = rows.get(r);
|
||||
double offset = (columns - row.length()) / 2.0;
|
||||
for (int i = 0; i < row.length(); i++)
|
||||
if (Character.isLetter(row.charAt(i))) centres.put(row.charAt(i), new KeyPoint(offset + i + 0.5, r + 0.5));
|
||||
}
|
||||
return new KeyGrid(centres, 1.0, 1.0, null);
|
||||
}
|
||||
}
|
||||
Executable
+81
@@ -0,0 +1,81 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Score swipe typing on synthetic paths: how often the first word is right, how often the word is typed or in
|
||||
the strip (top 4), and the time per swipe. The paths are swipe_paths.py's, the same ones the iPhone replay reads,
|
||||
from the held-out sentences; each is decoded by the keyboard's own SwipeReader (SwipeReplay.java) on the host
|
||||
JVM, or with --device on an emulator or phone against the installed APK, as replay.sh runs the tap replay.
|
||||
|
||||
android/benchmark/typing/swipe-bench.py [LANG ...] [--noise typical] [--device SERIAL] [--out DIR]
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
ANDROID = HERE.parents[1]
|
||||
MODELS = ANDROID / 'app/src/main/assets/typing'
|
||||
LANGUAGES = ['en', 'es', 'de', 'nb', 'fr', 'it']
|
||||
|
||||
|
||||
def paths(lang, noise, out):
|
||||
"""The path set, made once per language and noise."""
|
||||
target = out / f'{lang}-{noise}.tsv.gz'
|
||||
if not target.is_file():
|
||||
subprocess.run(['python3', HERE / 'swipe_paths.py', lang, target, '--noise', noise], check=True)
|
||||
return target
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument('languages', nargs='*', help=' '.join(LANGUAGES) + ' (default: all)')
|
||||
parser.add_argument('--noise', default='typical', choices=['typical', 'neat', 'sloppy', 'none'])
|
||||
parser.add_argument('--device', help='adb serial: run on the device against the installed APK')
|
||||
parser.add_argument('--out', type=Path, default=ANDROID / 'build/swipe-bench')
|
||||
args = parser.parse_args()
|
||||
if not set(args.languages) <= set(LANGUAGES):
|
||||
parser.error('languages: ' + ' '.join(LANGUAGES))
|
||||
args.languages = args.languages or LANGUAGES
|
||||
args.out.mkdir(parents=True, exist_ok=True)
|
||||
jdk = Path(os.environ['JAVA_HOME']) / 'bin' if 'JAVA_HOME' in os.environ else Path('')
|
||||
with tempfile.TemporaryDirectory() as scratch:
|
||||
tmp = Path(scratch)
|
||||
cp = tmp / 'classpath'
|
||||
subprocess.run([ANDROID / 'gradlew', '-q', '-I', HERE / 'gate-classpath.gradle', ':app:typingGateClasspath',
|
||||
'-x', 'prepareSpeechModel', '-PgateClasspath=' + str(cp)], cwd=ANDROID, check=True)
|
||||
classes = tmp / 'classes'
|
||||
subprocess.run([jdk / 'javac', '-encoding', 'UTF-8', '--release', '8', '-Xlint:-options', '-cp', cp.read_text(), '-d', classes,
|
||||
HERE / 'SwipeReplay.java'], check=True)
|
||||
if args.device:
|
||||
adb = ['adb', '-s', args.device]
|
||||
sdk = Path(os.environ['ANDROID_HOME'])
|
||||
lib = sdk / 'platforms/android-36/android.jar'
|
||||
tools = max((sdk / 'build-tools').iterdir())
|
||||
subprocess.run([jdk / 'jar', 'cf', tmp / 'replay.jar', '-C', classes, '.'], check=True)
|
||||
subprocess.run([tools / 'd8', '--min-api', '31', '--lib', lib, '--output', tmp / 'replay-dex.jar', tmp / 'replay.jar'], check=True)
|
||||
dev = '/data/local/tmp/hex-swipe'
|
||||
subprocess.run(adb + ['shell', 'mkdir', '-p', dev], check=True)
|
||||
subprocess.run(adb + ['push', tmp / 'replay-dex.jar', dev + '/replay.jar'], check=True, capture_output=True)
|
||||
subprocess.run(adb + ['push', MODELS / 'never-suggest.tsv', dev], check=True, capture_output=True)
|
||||
apk = subprocess.check_output(adb + ['shell', 'pm', 'path', 'ly.anoma.hex'], text=True).strip().removeprefix('package:')
|
||||
for lang in args.languages:
|
||||
source = paths(lang, args.noise, args.out)
|
||||
words = args.out / f'{lang}-{args.noise}-words.tsv'
|
||||
if args.device:
|
||||
for side in ['hextm', 'capitals', 'valid']:
|
||||
subprocess.run(adb + ['shell', 'rm', '-f', f'{dev}/{lang}.{side}'], check=True)
|
||||
if (MODELS / f'{lang}.{side}').is_file():
|
||||
subprocess.run(adb + ['push', MODELS / f'{lang}.{side}', dev], check=True, capture_output=True)
|
||||
subprocess.run(adb + ['push', source, f'{dev}/{source.name}'], check=True, capture_output=True)
|
||||
report = subprocess.check_output(adb + ['shell', f'CLASSPATH={dev}/replay.jar:{apk} app_process /system/bin '
|
||||
f'local.hex.bench.SwipeReplay {dev}/{lang}.hextm {lang} {dev}/{source.name} {dev}/words.tsv'], text=True)
|
||||
subprocess.run(adb + ['shell', 'rm', f'{dev}/{source.name}'], check=True)
|
||||
subprocess.run(adb + ['pull', dev + '/words.tsv', words], check=True, capture_output=True)
|
||||
else:
|
||||
report = subprocess.check_output([jdk / 'java', '-Xmx1g', '-Dfile.encoding=UTF-8', '-cp', str(classes) + os.pathsep + cp.read_text(),
|
||||
'local.hex.bench.SwipeReplay', MODELS / f'{lang}.hextm', lang, source, words], text=True)
|
||||
(args.out / f'{lang}-{args.noise}{"-device" if args.device else ""}.txt').write_text(report)
|
||||
print(report, flush=True)
|
||||
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,342 @@
|
||||
"""Synthetic swipe paths for the held-out sentences, shared by the Android and iPhone replays so
|
||||
both keyboards are scored on the very same paths. A faithful port of the iPhone swipe benchmark's
|
||||
generator (2026-11-20-hex-swipe-typing/bench/main.swift: SplitMix64, Noise, swipeTimed,
|
||||
keySequence and its sentence loop); with the same seed a word's path matches the Swift one to
|
||||
floating-point rounding, up to a translation (see the geometry below).
|
||||
|
||||
Geometry: key pitches on the canonical grid both Hex keyboards share. Row r's centres sit at
|
||||
y = r + 0.5; rows 0 and 1 are centred in columns = the wider of them, row 2 (between shift and
|
||||
delete) likewise, so q (a on AZERTY) is at (0.5, 0.5). A replay maps a point onto its own
|
||||
layout as q's centre + (point - 0.5) * pitch.
|
||||
|
||||
Every swipable word is written, in the model or not (the replays skip and count the words their
|
||||
model lacks). The Swift bench skips those before drawing a path, so after a sentence set's first
|
||||
such word its random numbers, and paths, differ from the bench's.
|
||||
|
||||
Writes gzip TSV: "#" header lines (lang, noise, rate, seed, rows), then one line per swiped word:
|
||||
sentence, position (0-based), word, previous (the true word before; empty at a sentence's start)
|
||||
and the points as space-separated x,y,t (pitches, seconds). With --words, sentence is the word's
|
||||
index in the list and position the repeat.
|
||||
Usage: python3 swipe_paths.py LANG OUT.tsv.gz [--noise typical|neat|sloppy|none] [--rate 120]
|
||||
[--flow F] [--hesitate H] [--limit N] [--seed S] [--words a,b,c --repeats N]"""
|
||||
import argparse, gzip, math, os, sys, unicodedata
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
MASK = (1 << 64) - 1
|
||||
GOLDEN = 0x9E3779B97F4A7C15
|
||||
|
||||
# Letter rows, as android/app/src/main/java/ly/anoma/hex/keyboard/KeyboardLetters.kt draws them.
|
||||
# French's apostrophe key ends row 2: a key, but not a letter.
|
||||
ROWS = {"en": ["qwertyuiop", "asdfghjkl", "zxcvbnm"], "it": ["qwertyuiop", "asdfghjkl", "zxcvbnm"],
|
||||
"es": ["qwertyuiop", "asdfghjklñ", "zxcvbnm"], "nb": ["qwertyuiopå", "asdfghjkløæ", "zxcvbnm"],
|
||||
"de": ["qwertzuiopü", "asdfghjklöä", "yxcvbnm"], "fr": ["azertyuiop", "qsdfghjklm", "wxcvbn'"]}
|
||||
# Added to seed * 7919 for the sentence loop (en and es as the Swift bench has them).
|
||||
SEED_OFFSET = {"en": 0, "es": 17, "de": 29, "nb": 31, "fr": 37, "it": 41}
|
||||
# Letters with neither a key nor a base letter's key, swiped as these keys.
|
||||
SPELLED = {"ß": "s", "œ": "oe", "æ": "ae"}
|
||||
|
||||
|
||||
class SplitMix64:
|
||||
"""Swift's SplitMix64, with its 64-bit wrapping arithmetic."""
|
||||
|
||||
def __init__(self, seed):
|
||||
self.state = (seed + GOLDEN) & MASK
|
||||
|
||||
def next(self):
|
||||
self.state = (self.state + GOLDEN) & MASK
|
||||
z = self.state
|
||||
z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & MASK
|
||||
z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & MASK
|
||||
return z ^ (z >> 31)
|
||||
|
||||
def unit(self):
|
||||
return (self.next() >> 11) / float(1 << 53)
|
||||
|
||||
def uniform(self, a, b):
|
||||
return a + (b - a) * self.unit()
|
||||
|
||||
def gaussian(self):
|
||||
u1 = max(self.unit(), 1e-12)
|
||||
u2 = self.unit()
|
||||
return math.sqrt(-2 * math.log(u1)) * math.cos(2 * math.pi * u2)
|
||||
|
||||
|
||||
# Noise presets in key pitches, as Swift's Noise (see its comments for each field).
|
||||
TYPICAL = dict(sloppiness=0.25, offset=0.08, via=0.22, start=0.18, end=0.22, cut=0.5, overshoot=(-0.1, 0.35),
|
||||
tremor=0.025, rate=120.0, speed=(0.6, 1.5), flow=0.0, hesitate=0.0)
|
||||
NOISE = {
|
||||
"typical": TYPICAL,
|
||||
"sloppy": {**TYPICAL, "offset": 0.15, "via": 0.36, "start": 0.3, "end": 0.42, "cut": 0.8,
|
||||
"overshoot": (-0.25, 0.7), "tremor": 0.055, "speed": (0.45, 1.2)},
|
||||
"none": {**TYPICAL, "sloppiness": 0.0, "offset": 0.0, "via": 0.0, "start": 0.0, "end": 0.0, "cut": 0.0,
|
||||
"overshoot": (0.0, 0.0), "tremor": 0.0, "speed": (1.0, 1.0)},
|
||||
"neat": {**TYPICAL, "offset": 0.04, "via": 0.12, "start": 0.1, "end": 0.12, "cut": 0.3,
|
||||
"overshoot": (-0.05, 0.15), "tremor": 0.01},
|
||||
}
|
||||
|
||||
|
||||
class Layout:
|
||||
"""A layout's letter centres and its "starts on a letter" test, in pitches."""
|
||||
|
||||
def __init__(self, lang):
|
||||
self.rows = ROWS[lang]
|
||||
self.columns = max(len(self.rows[0]), len(self.rows[1]))
|
||||
self.side = (self.columns - len(self.rows[2])) / 2
|
||||
self.centres = {}
|
||||
for r, row in enumerate(self.rows):
|
||||
left = (self.columns - len(row)) / 2
|
||||
for i, c in enumerate(row):
|
||||
if c != "'":
|
||||
self.centres[c] = (left + i + 0.5, r + 0.5)
|
||||
|
||||
def on_letter(self, x, y):
|
||||
# Rows 0 and 1 are letters edge to edge (edge keys reach the row ends); row 2 between
|
||||
# shift and delete, less the apostrophe key's cell.
|
||||
if not 0 <= y < 3:
|
||||
return False
|
||||
if y < 2:
|
||||
return 0 <= x < self.columns
|
||||
if not self.side <= x < self.columns - self.side:
|
||||
return False
|
||||
return self.rows[2][min(len(self.rows[2]) - 1, int(x - self.side))] != "'"
|
||||
|
||||
def key_sequence(self, word):
|
||||
"""The keys a word's swipe goes through (an accented letter on its base letter's key
|
||||
unless it has its own), repeats run together; None for a letter with no key."""
|
||||
out = []
|
||||
for ch in word:
|
||||
if ch == "'" or unicodedata.combining(ch):
|
||||
continue
|
||||
base = unicodedata.normalize("NFD", ch)[0]
|
||||
keys = ch if ch in self.centres else base if base in self.centres else SPELLED.get(ch)
|
||||
if keys is None or any(k not in self.centres for k in keys):
|
||||
return None
|
||||
for k in keys:
|
||||
if not out or out[-1] != k:
|
||||
out.append(k)
|
||||
return out
|
||||
|
||||
|
||||
def length(x, y):
|
||||
return math.sqrt(x * x + y * y) # not hypot: Swift's (x*x + y*y).squareRoot(), bit for bit
|
||||
|
||||
|
||||
def swipe_timed(centres, noise, s, rng, on_letter):
|
||||
"""Swift's swipeTimed: via points around each key, corners rounded with quadratic Béziers,
|
||||
an overshoot or a trim at the end, a slow wobble, then sampled in time on a quintic
|
||||
(minimum-jerk) profile between keys, with an optional hesitation. Returns ([(x, y)], [t]).
|
||||
Random numbers are drawn in Swift's order, and float operations kept in its order."""
|
||||
m = len(centres)
|
||||
ox = rng.gaussian() * noise["offset"] * s
|
||||
oy = rng.gaussian() * noise["offset"] * s
|
||||
via = []
|
||||
for j, (cx, cy) in enumerate(centres):
|
||||
sd = (noise["start"] if j == 0 else noise["end"] if j == m - 1 else noise["via"]) * s
|
||||
gx = rng.gaussian() * sd
|
||||
vx, vy = (cx + ox) + gx, (cy + oy) + rng.gaussian() * sd
|
||||
# A swipe starts on a letter key.
|
||||
tries = 0
|
||||
while j == 0 and not on_letter(vx, vy) and tries < 50:
|
||||
gx = rng.gaussian() * sd
|
||||
vx, vy = (cx + ox * 0.5) + gx, (cy + oy * 0.5) + rng.gaussian() * sd
|
||||
tries += 1
|
||||
if j == 0 and not on_letter(vx, vy):
|
||||
vx, vy = cx, cy
|
||||
via.append((vx, vy))
|
||||
|
||||
# Dense path with rounded corners; anchors are the path indices of each key's moment.
|
||||
path, anchors = [via[0]], [0]
|
||||
|
||||
def line_to(p):
|
||||
ax, ay = path[-1]
|
||||
steps = max(1, int(length(p[0] - ax, p[1] - ay) / 0.05))
|
||||
for k in range(1, steps + 1):
|
||||
path.append((ax + (p[0] - ax) * (k / steps), ay + (p[1] - ay) * (k / steps)))
|
||||
|
||||
for j in range(1, m - 1):
|
||||
(ax, ay), (bx, by), (cx, cy) = via[j - 1], via[j], via[j + 1]
|
||||
lin, lout = length(bx - ax, by - ay), length(cx - bx, cy - by)
|
||||
if not (lin > 1e-6 and lout > 1e-6):
|
||||
line_to((bx, by))
|
||||
anchors.append(len(path) - 1)
|
||||
continue
|
||||
# Fingers round a corner by a few tenths of a key, however long the strokes around it.
|
||||
d = min(0.45 * min(lin, lout), noise["cut"] * min(s, 1.8) * rng.uniform(0.4, 1.4) * 0.6)
|
||||
pin = (bx - (bx - ax) * (d / lin), by - (by - ay) * (d / lin))
|
||||
pout = (bx + (cx - bx) * (d / lout), by + (cy - by) * (d / lout))
|
||||
line_to(pin)
|
||||
for k in range(1, 13):
|
||||
t = k / 12
|
||||
a, b, c = (1 - t) * (1 - t), 2 * (1 - t) * t, t * t
|
||||
path.append((pin[0] * a + bx * b + pout[0] * c, pin[1] * a + by * b + pout[1] * c))
|
||||
if k == 6:
|
||||
anchors.append(len(path) - 1)
|
||||
line_to(via[m - 1])
|
||||
|
||||
# Overshoot along the last direction, or stop short (keeping half the last stretch).
|
||||
e = rng.uniform(*noise["overshoot"]) * s
|
||||
if len(path) >= 2:
|
||||
tx, ty = path[max(0, len(path) - 6)]
|
||||
dx, dy = path[-1][0] - tx, path[-1][1] - ty
|
||||
dl = length(dx, dy)
|
||||
if dl > 1e-6:
|
||||
if e > 0:
|
||||
line_to((path[-1][0] + dx * (e / dl), path[-1][1] + dy * (e / dl)))
|
||||
else:
|
||||
trimmed, last = 0.0, anchors[-1]
|
||||
keep = last + (len(path) - 1 - last) // 2
|
||||
while len(path) - 1 > keep and trimmed < -e:
|
||||
trimmed += length(path[-1][0] - path[-2][0], path[-1][1] - path[-2][1])
|
||||
path.pop()
|
||||
anchors.append(len(path) - 1)
|
||||
|
||||
# Arc lengths, and a slow wobble across the path fading in and out at its ends.
|
||||
arc = [0.0]
|
||||
for i in range(1, len(path)):
|
||||
arc.append(arc[i - 1] + length(path[i][0] - path[i - 1][0], path[i][1] - path[i - 1][1]))
|
||||
total = arc[-1]
|
||||
if noise["tremor"] > 0 and total > 0:
|
||||
amp = noise["tremor"] * s
|
||||
l1 = rng.uniform(1.2, 3.0)
|
||||
l2 = rng.uniform(0.5, 1.2)
|
||||
p1 = rng.uniform(0, 2 * math.pi)
|
||||
p2 = rng.uniform(0, 2 * math.pi)
|
||||
wobbled = list(path)
|
||||
for i in range(1, len(path) - 1):
|
||||
dx, dy = path[i + 1][0] - path[i - 1][0], path[i + 1][1] - path[i - 1][1]
|
||||
dl = length(dx, dy)
|
||||
if not dl > 1e-9:
|
||||
continue
|
||||
fade = min(1, arc[i] / 0.3, (total - arc[i]) / 0.3)
|
||||
w = amp * fade * (math.sin(2 * math.pi * arc[i] / l1 + p1) + 0.5 * math.sin(2 * math.pi * arc[i] / l2 + p2))
|
||||
wobbled[i] = (path[i][0] + (-dy / dl) * w, path[i][1] + (dx / dl) * w)
|
||||
path = wobbled
|
||||
|
||||
# Time: each stretch between key moments takes (0.08 + 0.05 * its length) * speed.
|
||||
speed = rng.uniform(*noise["speed"])
|
||||
times = [0.0]
|
||||
for k in range(1, len(anchors)):
|
||||
times.append(times[k - 1] + (0.08 + 0.05 * (arc[anchors[k]] - arc[anchors[k - 1]])) * speed)
|
||||
|
||||
def position(u):
|
||||
lo, hi = 0, len(arc) - 1
|
||||
while lo < hi - 1:
|
||||
mid = (lo + hi) // 2
|
||||
if arc[mid] <= u:
|
||||
lo = mid
|
||||
else:
|
||||
hi = mid
|
||||
span = arc[hi] - arc[lo]
|
||||
t = min(1, max(0, (u - arc[lo]) / span)) if span > 0 else 0
|
||||
return (path[lo][0] + (path[hi][0] - path[lo][0]) * t, path[lo][1] + (path[hi][1] - path[lo][1]) * t)
|
||||
|
||||
# Speed kept through each key: flow of the slower neighbouring stretch's peak, by cos²(turn/2).
|
||||
through = [0.0] * len(anchors)
|
||||
if noise["flow"] > 0 and len(anchors) == m:
|
||||
for j in range(1, m - 1):
|
||||
ax, ay = via[j][0] - via[j - 1][0], via[j][1] - via[j - 1][1]
|
||||
bx, by = via[j + 1][0] - via[j][0], via[j + 1][1] - via[j][1]
|
||||
la, lb = length(ax, ay), length(bx, by)
|
||||
if not (la > 1e-6 and lb > 1e-6):
|
||||
continue
|
||||
cos_turn = max(-1, min(1, (ax * bx + ay * by) / (la * lb)))
|
||||
keep = noise["flow"] * (1 + cos_turn) / 2
|
||||
before = (arc[anchors[j]] - arc[anchors[j - 1]]) / max(1e-9, times[j] - times[j - 1])
|
||||
after = (arc[anchors[j + 1]] - arc[anchors[j]]) / max(1e-9, times[j + 1] - times[j])
|
||||
through[j] = keep * 1.5 * min(before, after)
|
||||
|
||||
# A sample every 1/rate s, each stretch walked on a quintic Hermite (minimum jerk from rest).
|
||||
out, stamps = [], []
|
||||
end, t, k = times[-1], 0.0, 1
|
||||
while t < end:
|
||||
while k < len(times) - 1 and t > times[k]:
|
||||
k += 1
|
||||
span = max(1e-9, times[k] - times[k - 1])
|
||||
tau = (t - times[k - 1]) / span
|
||||
stretch = arc[anchors[k]] - arc[anchors[k - 1]]
|
||||
t2 = tau * tau
|
||||
t3 = t2 * tau
|
||||
t4 = t3 * tau
|
||||
t5 = t4 * tau
|
||||
h5 = 10 * t3 - 15 * t4 + 6 * t5
|
||||
h1 = tau - 6 * t3 + 8 * t4 - 3 * t5
|
||||
h4 = -4 * t3 + 7 * t4 - 3 * t5
|
||||
walked = stretch * h5 + through[k - 1] * span * h1 + through[k] * span * h4
|
||||
out.append(position(arc[anchors[k - 1]] + max(0, min(stretch, walked))))
|
||||
stamps.append(t)
|
||||
t += 1 / noise["rate"]
|
||||
out.append(path[-1])
|
||||
stamps.append(end)
|
||||
# Sometimes the finger stops once along the way, for 0.08 to 0.25 s.
|
||||
if noise["hesitate"] > 0 and rng.unit() < noise["hesitate"] and len(out) > 8:
|
||||
at = int(len(out) * rng.uniform(0.15, 0.85))
|
||||
wait = rng.uniform(0.08, 0.25)
|
||||
for i in range(at, len(stamps)):
|
||||
stamps[i] += wait
|
||||
return out, stamps
|
||||
|
||||
|
||||
def points_text(layout, points, stamps):
|
||||
# x is clamped to the layout's width, as the Swift bench clamps to its layout's.
|
||||
return " ".join(f"{min(max(x, 0), layout.columns):.5f},{y:.5f},{t:.5f}" for (x, y), t in zip(points, stamps))
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Synthetic swipe paths for the held-out sentences.")
|
||||
ap.add_argument("lang", choices=sorted(ROWS))
|
||||
ap.add_argument("out")
|
||||
ap.add_argument("--noise", choices=sorted(NOISE), default="typical")
|
||||
ap.add_argument("--rate", type=float, default=120.0)
|
||||
ap.add_argument("--flow", type=float, default=0.0)
|
||||
ap.add_argument("--hesitate", type=float, default=0.0)
|
||||
ap.add_argument("--limit", type=int)
|
||||
ap.add_argument("--seed", type=int, default=1)
|
||||
ap.add_argument("--words", help="comma-separated words, each swiped --repeats times (for checks)")
|
||||
ap.add_argument("--repeats", type=int, default=8)
|
||||
a = ap.parse_args()
|
||||
noise = {**NOISE[a.noise], "rate": a.rate, "flow": a.flow, "hesitate": a.hesitate}
|
||||
layout = Layout(a.lang)
|
||||
counts = {"words": 0, "swiped": 0, "one-key": 0, "no key": 0}
|
||||
|
||||
def swipe(seq, s, rng):
|
||||
return swipe_timed([layout.centres[c] for c in seq], noise, s, rng, layout.on_letter)
|
||||
|
||||
with gzip.open(a.out, "wt", encoding="utf-8", newline="\n") as f:
|
||||
f.write(f"# lang {a.lang}\n# noise {a.noise} "
|
||||
+ " ".join(f"{k}={v}" for k, v in noise.items() if k != "rate") + "\n")
|
||||
f.write(f"# rate {a.rate:g}\n# seed {a.seed}\n# rows {'/'.join(layout.rows)}\n")
|
||||
f.write("# sentence\tposition\tword\tprevious\tpoints (x,y,t: key pitches from the layout's top left, seconds)\n")
|
||||
if a.words:
|
||||
# As Swift's --words: one generator from the seed, a sloppiness drawn for every swipe.
|
||||
rng = SplitMix64(a.seed & MASK)
|
||||
for i, w in enumerate(a.words.split(",")):
|
||||
seq = layout.key_sequence(w)
|
||||
if seq is None or len(seq) < 2:
|
||||
print(w, "one key", file=sys.stderr)
|
||||
continue
|
||||
for r in range(a.repeats):
|
||||
pts, ts = swipe(seq, math.exp(rng.gaussian() * noise["sloppiness"]), rng)
|
||||
f.write(f"{i}\t{r}\t{w}\t\t{points_text(layout, pts, ts)}\n")
|
||||
return
|
||||
with gzip.open(os.path.join(HERE, "held-out", f"{a.lang}.tsv.gz"), "rt", encoding="utf-8") as src:
|
||||
sentences = [line.rstrip("\n").split("\t")[2].lower() for line in src]
|
||||
rng = SplitMix64((a.seed * 7919 + SEED_OFFSET[a.lang]) & MASK)
|
||||
for n, sentence in enumerate(sentences[:a.limit]):
|
||||
words = [w for w in sentence.split(" ") if w] # as Swift's split: no empty words
|
||||
sloppiness = math.exp(rng.gaussian() * noise["sloppiness"])
|
||||
previous = ""
|
||||
for position, w in enumerate(words):
|
||||
counts["words"] += 1
|
||||
seq = layout.key_sequence(w)
|
||||
if seq is None or len(seq) < 2:
|
||||
counts["no key" if seq is None else "one-key"] += 1
|
||||
else:
|
||||
counts["swiped"] += 1
|
||||
pts, ts = swipe(seq, sloppiness, rng)
|
||||
f.write(f"{n}\t{position}\t{w}\t{previous}\t{points_text(layout, pts, ts)}\n")
|
||||
previous = w
|
||||
print(" ".join(f"{k} {v}" for k, v in counts.items()), file=sys.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user