hex/android/README.md
Ryan Vogel d65b02d36e
Android keyboard batch 1: space-bar cursor, chip after a pause, delete slide (#2257)
* Android keyboard: Gboard's key geometry, the Hex mark in the strip, and the recording bar growing out of it

What changed, and why: thumbs trained on Gboard should land right on Hex, and the strip should look
and act like the iPhone keyboard's.
- Geometry (KeyboardMetrics, new KeyRowLayout): measured from Gboard on a Pixel 8 emulator (API 36)
  in the same field: row 1's keycaps 52.2 dp below the top, 47 dp keycaps on a 58.9 dp pitch with
  5.33 dp gaps, row 4 ending 12 dp above the system's bar, 7 dp corners, 26 sp letters. Hex's keys
  now sit within a pixel of Gboard's on API 36 and API 31. Every point of the key area types a key:
  gaps split down the middle, row 2's outer keys and the bottom row reach the edges, row 1 reaches
  2 dp into the strip, as Gboard's do (black-box taps). Landscape uses Gboard's 43 dp rows.
- Bottom row: ?123, comma, space, period, enter (Gboard's without its emoji key). The Hex key moved
  to the strip's trailing end, where Gboard has its mic and the iPhone keyboard has the Hex mark.
- The globe key is removed: Android draws its own keyboard switcher in the navigation bar whenever two
  keyboards are on (checked with 3-button navigation on API 31 and gesture navigation on API 36);
  Hex menu gets a Next keyboard row for devices that hide it.
- Edge to edge: keys stay above systemBars() (Android 14+ reports the IME's 48 dp back/switcher bar
  as the caption bar; navigationBars alone is the 24 dp handle, which let row 4 run 16 dp into it).
- Strip: the likeliest word in the middle slot (Gboard and iPhone); when space would autocorrect,
  what you typed in quotes on the left and the fix in a word-width chip in the middle
  (KeyboardEngine passes TypingWord.replacement() through the surface; the fix itself is unchanged).
- Recording: the Hex mark turns into ✓ in place (same view, so a hold's finger-up still finishes),
  the waveform's well grows leftwards out of it and ✕ fades in beside it; ✓ becomes the spinner.
- Shift shows outline, filled, and filled-with-bar for off, on and caps lock on a grey key.
- The decoder now gets the space bar's keycap (KeyGrid space, from #2241), so a tap just above space
  can read as a missed space.
Replaced: the bottom-row Hex key and globe key; swipe-up-only on the Hex key (any 10 dp slide opens
the menu now, as on iPhone); the black shift key when shifted; best suggestion on the left.

Verified (emulator only, Mac Studio; Ryan has no Android phone): assembleDebug, testDebugUnitTest
(16 tests) and lintDebug (warnings only, same kinds as before) pass. Pixel 8 AVDs at API 36 and 31,
probe app's text field next to Gboard: key rectangles measured from screenshots match Gboard's
within a pixel; edge, gap and above-row taps type the same keys as Gboard's (one difference: Gboard
types q 18 px above row 1's keycap, Hex 21); typing "teh" shows “Teh” | The (chip) | They, space
types "The ", delete restores "Teh"; a WAV through the emulator microphone dictated the full
sentence into the field with the new recording bar, light and dark; Hex menu opens on a slide.

* Android keyboard: slide on the space bar to move the cursor, as on Gboard

What changed: a slide on space now moves the cursor along the text at once. Measured from Gboard on
a Pixel 8 emulator (API 36, black box): the first character after about 45 px (17 dp) of travel and
one more every 33 px (12.6 dp), linear, both ways; Hex uses those numbers. It moves whole characters
(an emoji with a skin tone is one) by setting the selection from where the slide began; without a
known cursor position, or in a password field whose text it shouldn't read, it steps with arrow keys.
Why: Android users slide on space to place the cursor; Hex had no cursor control at all.

Spaces are never lost: a press that lifts within 180 ms types its space however far it drifted, and
so does any press that never started moving the cursor, even one that slid off the key. Replaced:
before, a press that left the space key's bounds typed nothing. Long press, held still, still opens
Hex's dictation-language menu (Gboard types a space there); once the finger moves it doesn't.

Verified (emulator only, Pixel 8 AVDs, probe app field "The quick brown fox jumps over the lazy dog",
cursor at the end, 'input swipe' gestures):
- quick taps of 60, 100 and 150 ms drifting 8, 21, 31, 42 and 63 px (up to 24 dp) typed a space
  15 of 15 times on API 36 and on API 31; Gboard: 15 of 15;
- slides over 300 ms of 21/42/63/126/252/525 px: Hex space, space, 1, 3, 7, 15 characters left;
  Gboard exactly the same; right at the end of the text moves nothing; up types a space;
- differences: Gboard types a space for some 200 ms flicks (63 and 252 px) where Hex moves the
  cursor; a still hold opens Hex's menu where Gboard types a space (decided);
- "ab👍🏽cd": 3 characters left lands before the emoji's start (offset 2), 5 at 0; password field:
  160 px moved 4 characters with arrow keys;
- testDebugUnitTest: three new cases in InsertionTest (drifting taps, slide steps, emoji steps),
  19 tests pass.

* Android keyboard: work out the autocorrection chip after a 100 ms pause, not inside the keystroke

What changed: the strip's correction chip (#2249) asked the decoder for what space would do on every
letter, inside the key's own handling. Measured on the API 31 emulator (temporary timing around
KeyboardEngine.letter, 108 letters of a typed sentence with typos): that search took 1.97 ms median,
16.1 ms p95 and 21 ms at worst, 77% of each keystroke (letter() 3.1 ms median, 19.0 ms p95).
Now the letter commits and the suggestions show at once, and the chip is worked out 100 ms later
unless another letter came first (then it waits again). Space still decides its correction itself,
exactly as before, so what gets typed doesn't change.

After (same run): letter() 1.36 ms median, 4.3 ms p95; the deferred chip 1.5 ms median, 5.3 ms p95,
between keys. The typed sentence came out identical before and after ("The quick brown fox jumps
over the lady dog ... because people like to write long sentnces"). Emulator only; a phone's CPU is
slower, so the gap there is larger. Replaced: the inline chip computation.

* Android keyboard: slide left from delete to delete words, and delete repeats at Gboard's pace

What changed (measured from Gboard on a Pixel 8 emulator, API 36, black box, and matched):
- Slide left from delete: past about 140 px (53 dp) the word before the cursor is selected in the
  field, one more word every 95 px (36 dp); sliding back selects fewer; lifting deletes what is
  selected, and nothing if the finger came back. Words are what Option-Delete takes: "far away
  from home" selects "home", then "from home". Not in password fields, with a selection, or when
  the cursor position is unknown (then delete works as before).
- A press that drifts up to about 32 dp is still one delete; one that went further and selected
  nothing deletes nothing, as Gboard's does.
- Held still, delete repeats after 400 ms every 50 ms, and stops repeating once the finger moves.
Replaced: 380 ms then every 65 ms, and a repeat that kept going while the finger slid. Why: Gboard
users delete words with this slide; iPhone Hex has its own live version (DeleteWordSwipe), but on
Android the platform convention is select, then delete on lift.

Verified (emulator only, Pixel 8, probe field "The quick brown fox jumps over the lazy dog and runs
far away from home", cursor at the end):
- slides over 500 ms of 60/107/130/160/190/214/250/300/350 px: Hex 1 character, nothing, nothing,
  1, 1, 1, 2, 2, 3 words, the same as Gboard on every one (API 36; 60/107/214 also on API 31);
  428 px gave 3 or 4 words between runs (Gboard 4, it sits on the boundary);
- 330 px out in 30 px steps and back to 120 px: selection 1, 2, 3, 2, 1, 0 words, nothing deleted,
  as Gboard;
- holds of 400/800/1200/2000/3000 ms deleted 1/8/16/31/51 characters (Gboard 1/8/16/31/50);
- testDebugUnitTest: 20 tests pass (word lengths and the gesture added to InsertionTest).
2026-11-21 16:10:02 -05:00

84 lines
12 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Hex for Android
Hold the Hex key, speak and release to insert text in the current app. A tap starts hands-free dictation; ✓ finishes and ✕ discards. The Hex key sits at the strip’s trailing end, where Gboard has its mic; while dictating it becomes ✓ and the live dot waveform grows out of it, above the keys. While Hex transcribes, a spinner takes the checkmark’s place and ✕ still cancels. The keys are Gboard’s size and place on a Pixel (measured on an emulator), with ?123, comma, space, period and enter in the bottom row; the system’s own switcher in the navigation bar, or Hex menu › Next keyboard, changes keyboards.
## Speech model and privacy
**[Whisper small Q5_1](https://huggingface.co/ggerganov/whisper.cpp/resolve/5359861c739e955e79d9a303bcbc70fb988958b1/ggml-small-q5_1.bin) is the default; multilingual tiny Q5_1 is bundled and works from first launch in airplane mode.** The [Android benchmark](benchmark/README.md) compares tiny, base, small, Parakeet and Android’s strictly on-device provider on the same 40 clips. Hex’s small configuration reduced WER from 17.54% to 5.26% and used 344 MiB peak native RSS on short clips. Norwegian remains the weakest language.
Welcome explains that the internet is used only to fetch the 190 MB speech model. Get started begins a fixed HTTPS download; setup shows progress and lets you continue with tiny or retry. [ModelStore](app/src/main/java/ly/anoma/hex/speech/ModelStore.kt) verifies the exact byte count and SHA-256 before atomically installing it in private, non-backed-up storage. The keyboard never makes a network request. Missing or unusable small weights fall back to tiny. Voice, words and translations stay on the device; Hex has no telemetry, transcript history or network speech service.
## Keyboard and styles
**Automatic** uses the first supported Android system language, or English if none is supported. Hold the language-labelled space bar to switch immediately between Automatic, English, Español, Deutsch and Norsk (Bokmål). Slide on the Hex key or tap **Hex menu** to change the spoken language or style:
- **Polished** (default): trims standalone hesitation sounds, fixes spacing/capitals and closes sentences.
- **Casual:** lowercase texting, without the period at the end of a single statement.
- **Notes:** “bullet point,” “next bullet,” “new line” and “new paragraph” become list items and breaks.
- **Verbatim:** keeps the recognizer’s words and punctuation; no cleanup is applied.
**Clean up what I say** is off by default. The [deterministic rules](app/src/main/java/ly/anoma/hex/speech/SpokenCleanup.kt) remove hesitations and resolve explicit self-corrections against nearby words of the same kind. Spanish, German and Norwegian use the iOS word lists and pause boundaries; English uses explicit markers, not iOS’s learned tagger or an LLM. Ambiguous repairs stay as spoken. Ordinary negation and language-specific words such as German “eh” and Norwegian “er” stay intact.
**Translate what I say** is also off by default. With Español and translation enabled, **Next dictation** offers **Paste in English** or **Paste as spoken**. The choice is captured when recording begins; after a one-off spoken-language insertion, the next dictation returns to English. Translation is multilingual Whisper’s native speech-to-English task, not a second text model or online SDK. The tested Spanish WAV inserted both “El café todavía está caliente.” and “The coffee is still hot.” offline.
## Typing assistance
All four layouts have a bundled, memory-mapped **HXTM v3** word and word-pair model. English and Spanish keep the original iOS Google Books files. German uses Google Books; Bokmål uses the National Library of Norway’s book counts filtered by Norsk ordbank. Start typing to see ranked suggestions; tap one to insert it. A space brings up next-word predictions. Passwords, addresses and editors that disable suggestions use literal typing.
**Keyboard › Keyboard layout** follows dictation by default; an explicit layout can differ from the space bar’s spoken language. Spanish has a dedicated ñ and ¿/¡ on the second symbols page. German is QWERTZ with ü, ö and ä; hold s for ß. Bokmål has å, ø and æ.
**Keyboard › Suggest swear words** is off by default on every layout. Slurs on the
[curated list](app/src/main/assets/typing/never-suggest.tsv) are never offered, even when
swear words are enabled. The filter applies to completions, next words, autocorrect and
both halves of a missed-space correction. Typing a listed word in full keeps your exact
spelling; its literal chip accepts what you typed. The filter never changes the HXTM models.
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 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. **Experiments › 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.
## Phase 4 verification
On identical held-out synthetic taps and **unchanged English and Spanish iOS models**, Android’s English word error rate fell from 10.53% to **7.40%**, against **8.39%** for iOS R1 without offsets. Spanish was **10.33%** against **10.43%** for iOS (phase 3 Android: 10.06%). The [step-by-step benchmark](benchmark/typing/README.md#where-the-298-english-errors-came-from) explains the original 298 extra English errors; [the replay table](benchmark/typing/phase4.tsv) gives raw counts, exact sentences and timing.
The Studio verified Spanish, German and Bokmål suggestions and space-triggered corrections in a separate Android app, including **¿¡**, **ß** and **æøå**. The German and Bokmål assets were also copied, byte-for-byte, into the iOS typing-model folder in local commit `230a437e`. The production Swift reader checked all 95,000 words per language and every stored pair score; no iOS source or existing English/Spanish model changed.
With airplane mode on and Wi-Fi off, fixed audio went through the emulator microphone and Whisper small into that editor. Spanish **“Nos vemos mañana en la estación”** and German **“Wir treffen uns morgen am Bahnhof”** matched. Bokmål **“Tusen takk for hjelpen”** also matched; on corpus clip 40 Hex inserted **“Biblioteket stenger tydelig på lørdag”** instead of **“Biblioteket stenger tidlig på lørdag.”** The same Spanish clip also produced a transcript from Home’s Dictate bar.
Five unit tests passed in each of the debug and release variants. Home, the four settings pages and all four detail pages were captured in light and dark. Deselecting Hex as the current keyboard changed **Ready** to **Finish setup · 1 step**; selecting it again through setup restored **Ready**. The local APK, full-size screenshots, replay results and Studio log are under `build/phase4-proof/`.
## 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`.
- **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.
- **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.
- **Licences:** OpenAI Whisper weights and whisper.cpp/ggml are MIT. Kotlin/AndroidX are Apache 2.0; libc++ is Apache 2.0 with LLVM exceptions. [Bundled credits and licence texts](app/src/main/assets/licenses/). No ML Kit, Parakeet or third-party language packs are shipped.
## Build and run
Use the Studio’s JDK 21, SDK platform 36, NDK 27.2.12479018 and CMake 3.22.1. The Play packaging checks use Build Tools 36.0.0 and bundletool 1.18.3. From the synced `android/` directory, with an ARM64 emulator or phone running:
```sh
export JAVA_HOME="/opt/homebrew/opt/openjdk@21/libexec/openjdk.jdk/Contents/Home"
export ANDROID_HOME="$HOME/Library/Android/sdk"
export PATH="$ANDROID_HOME/platform-tools:$JAVA_HOME/bin:$PATH"
./gradlew assembleDebug
./gradlew test
adb install -r app/build/outputs/apk/debug/app-debug.apk
adb shell am start -n ly.anoma.hex/.MainActivity
```
On the headless Studio, start an ARM64 AVD with `-audio none -grpc 8566 -grpc-use-token`. [inject.py](benchmark/inject.py) uses the matching emulator discovery record and streams paced mono PCM16 into the guest microphone. Generate the bindings from the SDK emulator’s `lib/emulator_controller.proto` with `grpcio-tools`, then put them on `PYTHONPATH`. No recording or transcript is injected directly into the application.
For the upload bundle, run `./gradlew :app:bundleRelease`. Release packaging requires a private properties file at `~/.config/hex-android/keystore.properties` or the path in `HEX_ANDROID_KEYSTORE_PROPERTIES`. It must contain `storeFile` (relative to that file, or absolute), `keyAlias`, `storePassword` and `keyPassword`. Release uses R8 and resource shrinking and never falls back to the debug key. Gradle writes `app/build/outputs/bundle/release/app-release.aab`.
**Scope:** Android 12+ (min API 31), target 36, ARM64, four typing models and four dictation languages. See the [Play release evidence, listing drafts, phone screenshots and real-device checklist](play/README.md). The Studio also exercised offline fallback, all four styles, per-dictation translation, both appearances and insertion into a separate app with music playing in earlier phases.