hex/ios/HEXShared/FullKeyboard/FullKeyboardSettings.swift
Ryan Vogel 9ca17141d6
iOS: the full keyboard matches the system keyboard one to one (#2178)
* iOS keyboard: key haptic fires on touch-down before the key's work, as a crisp tick

Adam (build 56) said the haptics feel weird. In KeyboardKeyPlaneView.began the
haptic and click came after engine.touchBegan, which for a fast typist first
commits the rolled-over key (autocorrect, suggestions) or deletes, so the tick
could trail the finger by tens of ms. The plane now asks the engine which key
kind the finger lands on (new FullKeyboardEngine.keyKind(at:), a pure hit test)
and fires onKeyDown before any typing; delete's repeat still ticks per step.

The tick itself is now a rigid impact at 0.6 (FullKeyboardView.keyTickStyle /
keyTickIntensity, shared with the dictation bar) instead of light at 0.65:
Apple's key haptic is a light, crisp tick and rigid is the sharpest impact
style. The Hex key's hold and menu keep the fuller light thud. The haptic now
fires before UIDevice.playInputClick rather than after it.

KeyboardViewController reads Settings > Keyboard > Haptics on each bridge sync
(appear and poll) instead of building FullKeyboardSettings on every key press.

Verified: new FullKeyboardEngineTests.testKeyFeedbackFiresOnceOnTouchDownBeforeTheKeyTypes
(rollover ticks before either letter types; space, delete, shift, return and
123 tick once each on the way down; lifting never ticks) and the existing
testEveryLayoutAsksForTheSameKeyHaptics; full HEXMobileTests 383 run, 0 failed
(iPhone 17 sim, iOS 27.2). The simulator has no Taptic Engine: style and
intensity need a real iPhone.

* iOS keyboard: Apple's 43 pt keys on a 54 pt row pitch, so rows sit where fingers expect

Black-box measurement beside Apple's keyboard in the same Messages field
(iPhone 17 simulator, iOS 27.2): Apple's keycaps are 43.0 pt tall on a 54 pt
pitch (rows at 598/652/706/760 pt on screen); Hex drew iOS 26's 45 pt on
56 pt, rows at 581/637/693/749. Hex's hit borders therefore sat 12 to 21 pt
above Apple's on screen, so taps aimed by Apple-trained thumbs landed low on
Hex's keys and crossed into the row below ("the hit box is super weird").

iPhone portrait is now 43 pt keys, 11 pt gaps, 5 pt under row 4 (262 pt, was
270): rows sit 9 pt above Apple's everywhere and borders within 6 to 9 pt.
Row 4 can't go lower: a third-party keyboard's view ends 4 pt above Apple's
row 4 bottom, and dropping the 5 pt margin cost low space-bar taps (held-out
benchmark EN 5.94% -> 6.19% WER). The Duo's cover screen keeps its measured
45 pt on 56 pt. Hit frames still tile the key area (gaps split at their
middles, edge keys to the screen edges), which matched Apple's base borders.

Verified: held-out tap benchmark (2,000 sentences each, Spatial on) EN 824
edits before and after (5.9409%); ES 1,145 -> 1,146 (one sentence better, one
worse, both from the fixed 5 pt next-letter reach). KeyboardLayoutTests updated
for 262 pt and the 54 pt pitch; HEXMobileTests 383 run, 0 failed.

Rebased on #2146: Adaptive touch's contexts now key on the key height and row
pitch too (AdaptiveTouchGeometry), so offsets learned on Hex's 45 pt keys on a
56 pt pitch, in keycap units, aren't read on these rows. A key plane with the
same rows keeps its profile, as before.

* iOS keyboard: the key plane matches Apple's, key for key, on every iPhone

Measured from screenshots beside Apple's keyboard in the same Messages field
(iOS 27.2 simulators: iPhone 17 Pro, 17e, Air, 17 Pro Max, SE 3rd gen; light and
dark; letters, shifted, numbers and symbols pages), black box only.

Geometry (KeyboardLayout):
- Key height and row pitch follow the screen (KeyboardPhoneSize): 43 pt on 54 pt
  on 844-874 pt iPhones, 45 on 56 on the Air and Pro Max, 42 on 54 on the SE.
  Hex drew 45 on 56 everywhere, rows 11-17 pt above Apple's. Rows now sit on
  Apple's lines. On 390/402 pt iPhones Apple's row 4 ends 4 pt below where a
  third-party keyboard's view ends (touches below y 799 never reach Hex), so
  Hex's row 4 keeps Apple's top edge and is 39 pt tall (bottomRowTrim); its
  labels are centred as on Apple's 43 pt row.
- The SE's keys start 6.5 pt in, as Apple's (Hex used 4.5).
- Shift, delete, #+= and 123 are 1.227 pitches less 3 pt (fits all five
  iPhones within a pixel; a fixed 1.34 letters was 0.5 pt narrow on the 17 Pro).
- The portrait bottom row stands on row 3's columns: 123 (and emoji, or the
  globe) end at z's right edge, space runs x to n, return m to the edge. With no
  emoji key 123 fills that block, which is what Apple's own keyboard does with
  the Emoji keyboard removed; on the SE Apple's row matches with dictation off.
- Apple's emoji key takes taps only 6 pt inside its sides and 7.5 pt below its
  top, the margins typing nothing (mapped by tapping); Hex's emoji key does the
  same (Erick hit it by accident).
- Keycaps are pixel-aligned and the corner radius is 7.9 pt (same corner fit as
  Apple's, 8.1 by the measuring tool; Hex's 8.5 measured 8.7).
Labels (KeyboardKeyPlaneView), fitted against labels rendered offscreen at known
sizes: lowercase 24.5 pt (was 22.5), capitals 21 pt weight 0.12, digits and
symbols 21.5 pt weight 0.08 with case-sensitive forms, a few symbols at their
own sizes, 123/ABC 17.75 pt, #+= 12.25 pt, shift/delete/return/globe symbols
19 pt; the quote keys show " and ' curly as Apple's (they still type straight).

Result: every keycap edge on every iPhone, page and appearance within 0.00 pt
of Apple's (except row 4's bottom on 390/402 pt and the emoji-less 123);
label boxes within 1 pt (median 0.34 pt), ink within 2% (median), except ^, <
and > on the symbols page (different shapes).

Held-out tap benchmark (2,000 sentences each, taps aimed at Hex's own keys):
EN 5.94% -> 6.41% WER, ES 8.61% -> 9.32%: low space-bar taps now fall below the
view's bottom edge (19.5 pt below the space bar's centre instead of 27.5).
With taps aimed where Apple's keys are (a user used to Apple's keyboard):
EN 21.34% -> 6.97%, ES 23.45% -> 10.04%.

KeyboardLayoutTests updated to the measured numbers (heights 253/260/272,
54/56 pt pitch, shift and delete edges, SE inset, bottom-row columns, emoji
target, tiling with the emoji margins); HEXMobileTests 385 run, 0 failed.

Rebased on #2142: the emoji panel's bar sits from keysBottom, so on these
iPhones it now reaches the panel's bottom edge as row 4 does.
testTheBarsKeysTakeTheWholeBandUnderTheGrid skips its probes below the panel,
where nothing can be hit.

Rebased on #2172: Dvorak's letters size from this shift width
(dvorakLetterWidth reads modifierWidth), so its row 3 of shift and nine letters
still fills edge to edge. Its rows take these heights and pitch like every
layout's.

* iOS keyboard: Settings > Keyboard > Strength for key haptics, Medium by default

Testers on X said Hex's key haptic is too weak beside Apple's keyboard (Tareq:
"add an option to adjust the haptic feedback strength", Erick: "not nearly as
nice as apple keyboard"). The tick was a light impact at 0.65 (0d4f78e5 made it
rigid 0.6).

- KeyHapticStrength (light, medium, strong) in the App Group, read on each
  bridge sync (FullKeyboardSettings.hapticStrength, default medium).
- Light is a rigid impact at 0.5, Medium (meant to feel like Apple's crisp
  tick) rigid at 0.8, Strong a medium impact at 1.0. The full keyboard and the
  dictation bar use the same mapping (FullKeyboardView.keyTickStyle/Intensity).
- Settings > Keyboard shows Strength (Light | Medium | Strong) under Haptics
  while Haptics is on, with zh-Hans strings (强度, 轻, 中, 强).

Verified: HEXMobileTests 385 run, 0 failed; the Settings page renders the row
in English and zh-Hans (simulator scene settings-keyboard-end). The simulator
has no Taptic Engine: which intensity matches Apple's tick needs a real iPhone.

* iOS keyboard: the Duo folded matches Apple's keys, and a tester fixture follows the new rows

The Duo folded (iPhone Duo simulator, iOS 27.2 iPhone19-4 runtime, cover screen,
Hex beside Apple's keyboard in Messages; Ethan on X: "a tiny bit off"):
- Apple's row 4 ends 7 pt above the keyboard's bottom; Hex's ended 5 pt above, so
  every Hex row sat 2 pt low. keysBottom is 7 folded and upright (the strip stays
  the top bar's 32 + 8 pt).
- Apple's keys start 6.67 pt from the screen's side, a third of a point outside
  the 452 pt view a third-party keyboard gets; Hex's started 8.0 pt in (a 1 pt
  minimum inset). The inset may now be 0, so Hex's keys run to the view's edges.
- Apple's keycaps round about 9.8 pt there (Hex drew 7.9).
- Row 4 stands on the letter columns, as Apple's does folded: 123, globe and
  emoji one key wide on q, w and e, space from r, return from l's column. Apple
  puts dictation on m's column; Hex has none, so its space bar runs on (a Hex key
  right of space takes that slot).
Result: rows on the same y as Apple's, every edge within 0.67 pt (the view's
edge), corners 10.2 vs 10.1 by the same measuring tool. Not measured unfolded
(no unfold tool on the Studio); the unfolded metrics are unchanged.

testTheTestersSentenceComesOutRightWithSpatialAutocorrect (from origin/dev) placed
its taps on the old 45 pt rows on a 56 pt pitch, down to y 242 where row 4 now
ends at 236, so low space taps fell off the keys. Each tap now sits at the same
spot on today's row; the expected sentence is unchanged.
KeyboardLayoutTests: the cover's Apple edge is 6.67 pt, and the bounds checks
allow 0.001 pt of rounding now that keys can touch the view's edge.

Verified: HEXMobileTests all passing (iPhone 17 sim, iOS 27.2); Duo cover
screenshots measured as above.

* iOS keyboard: turned, the keys match Apple's on every iPhone

Measured turned beside Apple's keyboard in the same Messages field (iOS 27.2
simulators: iPhone 17e, 17 Pro, Air, 17 Pro Max, SE), black box:
- Apple's keys are 32 pt on a 40 pt pitch with 2 pt under row 4 on every iPhone
  (4 pt on the SE), corners 7.9 pt. Hex drew iOS 26's 27.5 pt on 35.5 pt with
  3 pt under, every row 2 to 17 pt below Apple's. The strip stays the top bar's
  42 + 8 pt; the keyboard is 204 pt (was 187).
- Row 4 stands on row 1's columns: 123 on q, emoji (or the globe) on w, space
  from e to i, return from o to p (KeyboardMetrics.bottomRowReturnColumn, which
  the Duo folded now shares with its own 8.5).
- Shift, delete, #+= and 123 on row 3 are 1.33 letters wide turned (the portrait
  rule left them 2.3 pt narrow).
- The SE sets its keys 72 pt in from each side, 47 pt wide; Hex's ran 4 pt from
  the edges, 60.5 pt wide.
Result: every keycap edge on the five iPhones within 0.5 pt of Apple's turned
(0.00 on all but the SE's delete, 0.5). Apple's SE reaches emoji through the globe
and shows no emoji key turned; Hex keeps its emoji key after the globe, so the
SE's space bar starts one key later. Not measured: the Duo turned (its cover
screen doesn't rotate in the simulator); it follows the iPhone.

Verified: KeyboardLayoutTests (heights 204 and 198 turned, new
testLandscapeMatchesApplesKeys); turned screenshots on all five iPhones.

* iOS keyboard: turned labels and held keys look like Apple's

Black box, beside Apple's keyboard in the same field (iOS 27.2 simulators):

Turned labels (17e, 17 Pro, SE; fitted against labels rendered offscreen at
known sizes and weights): letters, digits and symbols are about 0.875 of their
portrait sizes (lowercase 21.5 pt, capitals and symbols 18.75 pt a little
heavier), with per-symbol sizes where Apple's differ (. , : _ # * • and others);
123 15.5 pt, ABC 17.75 pt, #+= 12.25 pt; shift, delete and return symbols 18 to
18.5 pt (Hex drew 15.5 to 16), and the emoji key's face semibold, as Apple's.
Hex drew 18 and 19 pt labels, about 14% lighter than Apple's. Now each label's
box is within 1 to 1.25 pt of Apple's and its ink within 1% (median) on the 17e
and SE turned.

Held keys: Apple paints a held key one of three greys. A letter under its pop-up
222 (105 dark), which Hex already drew for every key; shift, delete, globe, emoji
and return 197, 197, 201 (131 dark); the space bar 242, 242, 247 (56 dark). 123
and ABC switch the page as they go down and aren't shaded. FullKeyboardPalette
gains keyHeldFill, functionHeldFill and spaceHeldFill; every held key now
measures within 1 grey level of Apple's in light and dark (17e).

Checked, nothing to change: keycaps have no shadow, edge highlight or inner
stroke on Apple's keys (letter or function, light or dark); the fill meets the
panel in one anti-aliased pixel, as Hex's does, and a 32 x 32 px corner differs
by at most 6/255. The keys draw over #2139's opaque backdrop.

Verified: HEXMobileTests passing; screenshots above on the simulators.

* Draw iOS 27's floating key pop-up and let it linger after lift

What: the key pop-up is now iOS 27's bubble: a rounded rectangle (radius 12)
23.33 pt wider than the key and 65 pt tall, floating 3.5 pt above it, with no
border or stem. The letter is 36.5 pt in either case; digits and symbols use the
key's own style scaled 1.5x. The dark bubble shades from 63 to 85 grey, and the
pressed key stays drawn grey under it. Over row 1 the bubble shrinks to the room
there is, down to 50 pt, because an extension can't draw above its view, which
Apple's can. After lift the pop-up and its grey key stay 45 ms, then go in one
frame.

Removed: iOS 26's balloon (a 46 pt bubble on an 8 pt stem that covered the key,
1 px border, 33 pt light label). Also removed: the pop-up disappearing before its
letter reached the field, and edge bubbles kept 2 pt in from the sides (now
pushed in only as far as the screen needs, as Apple's are).

Why: black-box comparison with the system keyboard on the iPhone 17e and 17 Pro
simulators (iOS 27.2), measured from screenshots and 60 fps recordings.

Verified: popups-17e-apple-vs-hex.png comparison, light and dark. On 60 fps
recordings of 120 ms taps, Hex's pop-up now leaves about 47 ms after the letter
lands (Apple about 50). Full HEXMobileTests pass.

* Match Apple's long-press accent callout: arrangement, layout, timing

What: the accent callout now looks and behaves like the system keyboard's
(iOS 27.2 simulators, every English letter, digit and symbol key held and
screenshotted):
- Arrangement: options sit where Apple puts them, the key's own selected over
  the key (e: ë é [e] è ê ě ẽ ē ė ę; $: ₽ ¥ € [$] ¢ £ ₩; " « » „ “ ” ["]).
  "a" gets two rows (æ ã å ā ă ą over a à á â ä ǎ). The characters stay
  #2140's observed lists (KeyboardLanguage.letterHolds, symbolHolds, the
  123/#+= list). AccentCatalog.arrangement only places them, and only while its
  table lists exactly the same options, so a list change can't drop or invent
  one. Languages without a checked arrangement open from the key toward the
  middle, as before.
- Geometry: cells are the held key's width + 4 pt (36.3 on a 390 pt iPhone's
  letters, 51.7 on the wide . , ? ! ' keys, 67 in landscape). Rows are 47 pt
  with 10.5/10.35 pt padding and 20.8 pt corners, 3 pt above the key, kept
  6.67 pt from the sides. Sliding picks by row, then by nearest cell.
- Look: the selection is a grey rounded square (227/227/230, dark 87 grey,
  6.3 pt corners) behind 21.5 pt regular options, on the pop-up's bubble with no
  border. The dark callout lightens toward its bottom.
- Letting go more than 57.5 pt below the key's middle closes the callout with
  nothing typed (Apple: 55 pt types, 60 cancels).
- Hold delay 0.36 s: the callout replaces the pop-up about 380 ms in (Apple
  382, Hex was 420).
The emoji panel's skin-tone picker passes its own cell width and keeps its
layout and drawing unchanged (AccentMenu.buildFixed, drawFixed).

Removed: the blue selected cell with white medium text, the 1 px border, the
44 pt cells and 4 pt padding, and opening every list sideways from the key with
the base at the thumb end.

Why: press-and-hold visuals should match the system keyboard one to one.

Verified: 17e simulator screenshots of Apple vs Hex holds (e with slide and
drag-off cancel, a, n, u, k, $, 0, ", ', .), light and dark, and landscape (i).
The drag-off typed nothing on both. Updated testLongPressAccentPicker... for
Apple's arrangement. Full HEXMobileTests pass apart from #2142's emoji bar band
test, fixed with the key-plane geometry it depends on.

Rebased on #2164 and #2172: the arrangement is looked up for the layout's
language and letters, as the options are (the bilingual English & Spanish
keyboard holds English's; Spanish on plain QWERTY, whose n also holds ñ, opens
its own list). testEnglishOnQWERTZTypesOnItsOwnKeys checks the selected option
is the key's own instead of the first, since Apple's y reads ÿ ŷ ý [y].

* Match Apple's key-plane micro-animations: shift press, key release, trackpad fade

What, each measured against the system keyboard from 60 fps recordings and
mid-press screenshots on the iPhone 17 Pro simulator (iOS 27.2):
- Shift: a press that turns shift on now shows nothing until lift: no shade,
  outline arrow, lowercase letters (ShiftStateMachine.pressShowsOff,
  FullKeyboardEngine.keycapLabel). Hex used to shade the key and show capitals on
  touch-down. Shift still engages on touch-down, so a chord types a capital, and
  the keycaps show capitals once a letter has been typed during the hold. Presses
  that turn shift or caps lock off still shade at once, as Apple's do.
- Delete, space, return, globe and emoji stay shaded 60 ms after a tap lifts.
  Apple shows them 265-284 ms for a 200 ms tap; Hex showed 200-210 and now
  265-277. A delete held long enough to repeat, or used for a word swipe, lets
  go at once, as Apple's does.
- Trackpad: the key labels fade out and back in, ease-out over 0.24 s (visible
  change 204/198 ms against Apple's 202/200, first step 10 ms after the change,
  Apple 13). The space bar unshades as it becomes the trackpad. Hex used to blank
  the labels in one frame and keep the space bar shaded. Reduce Motion, or no
  window, switches at once. A CADisplayLink drives the fade through a weak ticker,
  only while it runs.
- Trackpad hold delay 0.4 s -> 0.35 s: it now starts 363 ms after touch-down,
  as Apple's does (Hex was 417).

Unchanged, because Apple's are instant too: pop-up appear/disappear, page
switches (123/ABC/#+=), accent callout open, select and close, and caps lock.

Verified: recordings and screenshots of Apple vs Hex for shift (held from off,
from on and from caps lock), delete/space/return taps (50, 200 and 600 ms),
the trackpad, page switches and accent open. Full HEXMobileTests pass. Tap
latency is untouched (the linger and fade run after lift or after the trackpad
starts).

* Place portrait letter labels where Apple's sit, not centred by advance

What: letter keycaps (letters page, portrait) now draw each letter at its key's
middle plus Apple's measured offset for where that middle falls between whole
points: sixths of a point on 3x screens, quarters on 2x (KeyboardKeyPlaneView
drawLetter, letterNudge3x/letterNudge2x; lowercase and capitals separately).
Capitals move up a pixel (yOffset -1 -> -1.33).

Why: a TestFlight tester (build 56, iOS 27.2.1) said the letters look slightly
off-centre. Measured at native resolution against the system keyboard (iOS 27.2
simulators, ink centroid of each of the 26 letters relative to its keycap's
centre, lowercase and capitals, light and dark), Apple doesn't centre letters by
their advance as plain text does. Its offset depends on the key's position: on
the 17 Pro, keys centred on a whole point have letters 0.2-0.6 pt left of plain
centring, and keys centred on a half point have them 0.3-0.8 pt right. The same
fraction gives the same offset on the Pro Max. Hex's plain centring was therefore
0.27-0.32 pt off Apple's per letter (median; up to 0.82) on 3x screens, and
0.35/0.58 (up to 1.16) on the SE. Capitals also sat 0.27 pt (0.8 px) low on every
letter.

Removed: plain advance centring for portrait letters. Landscape letters, digits
and symbols keep it.

Verified (Apple minus Hex, ink centroids, median|max, pt):
- 17 Pro: lowercase 0.31|0.82 -> 0.09|0.49; capitals 0.27|0.63 -> 0.14|0.42
- Pro Max: lowercase 0.29|0.77 -> 0.10|0.44; capitals 0.28|0.75 -> 0.13|0.53
- Air (held out of the fit): lowercase 0.29|0.77 -> 0.10|0.44; capitals
  0.28|0.75 -> 0.13|0.53
- SE (2x): lowercase 0.58|1.16 -> 0.15|0.44; capitals 0.35|0.70 -> 0.12|0.37
- Vertical, capitals on 3x: 0.27 -> 0.06.
Lowercase stays 0.13 pt low and SE capitals 0.28 low: text lands on whole
pixels, so a whole pixel would overshoot. Light and dark measure the same. Full
HEXMobileTests pass.

* Draw Apple's grinning emoji-key face instead of SF Symbols' face.smiling

What: the emoji key draws the face Apple's shows (KeyboardKeyPlaneView
drawEmojiFace): a 19 pt face (18 in landscape) with an open mouth and a band of
teeth, centred 0.67 pt above the key's middle. Light mode draws a 1.58 pt ring;
dark mode draws a solid face with the eyes and mouth cut through to the keycap
(even-odd fill). The teeth are always the light colour.

Why: the key-plane overlays showed Hex's emoji key drawing a closed smile
(face.smiling), and in landscape at 16 pt instead of Apple's 18. Apple's grinning
face isn't a public SF Symbol (face.grinning and the like don't exist), so it is
drawn from primitives sized from measurements of 3x simulator screenshots on the
17 Pro, Pro Max, Air, 17e and SE (iOS 27.2): ring, eyes 2 x 2.67 pt at
(+/-2.78, -2.13), and a mouth 12.33 pt wide, its top 0.5-1.5 pt and its bottom
6.5 pt below the centre. No Apple artwork is copied.

Removed: the face.smiling symbol on the emoji key.

Verified: zoomed Apple vs Hex crops on the 17 Pro in light, dark and landscape
match by eye; within the glyph, 5.2% (light) and 2.0% (dark) of pixels differ by
more than 64/255, mostly a one-pixel horizontal phase. Full HEXMobileTests pass.

* Lay out Spanish holds as Apple's; keep the key's own until the finger moves

What:
- Spanish callouts use the system keyboard's arrangement, read off every letter,
  digit and symbol held on the iOS 27.2 Spanish keyboard
  (AccentCatalog.spanishOrder). Examples: º ō œ ø õ ô ò ó [o] ö with ö to the
  right of o; ū û ù ü ú [u]; l·l [l]; ń [n]; 9ª [9] 9º; [0] 0ª ° 0º. Symbols as
  English's. The characters stay #2140's Spanish letterHolds and symbolHolds,
  which match these on screen.
- The accent callout keeps the key's own character selected until the finger
  moves into another cell, and lifting types the current selection
  (FullKeyboardEngine.accentOpenCell, accentIndex). The debug fixtures select a
  callout option directly (debugSelectAccent), as a slide to it does.

Removed: lifting choosing the cell under the finger even if the finger never
moved. At the screen's edge the callout shifts, so 0 typed "0º" on a plain hold;
Apple's types "0". Also removed: the fixtures' synthetic move, which landed in
the cell the finger opened in when a long callout shifted (Italian e), so it
selected nothing.

Why: the Spanish system keyboard comparison (17e simulators, both set to
Spanish) showed the arrangement differing and the 0 hold typing the wrong
character.

Verified: Apple vs Hex screenshots of o s d l n z c 1 9 0 held on the Spanish
keyboard all match. A plain hold of 0 now types "0", and slide-then-drag-off
cancels. Lowercase holds confirmed đ (Spanish) vs ď ð (English). Full
HEXMobileTests pass apart from #2142's emoji bar band test, fixed with the
key-plane geometry it depends on.

* Replace the letter-position table with per-scale constants: it didn't generalize

What: portrait letters are again centred by advance, plus a constant per case
and screen scale: lowercase +0.17 pt and capitals 0 on 3x screens, +0.55 and
+0.23 on the 2x SE (KeyboardKeyPlaneView drawLetter). The capitals' one-pixel
lift from cef53885 stays.

Removed: cef53885's letterNudge3x/letterNudge2x tables, which offset each letter
by where its key's middle falls between whole points. They were fitted on the
17 Pro and Pro Max (the Air shares the Max's key phases, so it wasn't an
independent check). On the 17e, held out, they made letters worse: lowercase
0.23 -> 0.42 pt (median, Apple minus Hex), capitals 0.22 -> 0.27, worst cases up
to 1.0. The 17e's half-point keys need the opposite offset from the 17 Pro's.
No model tried (rounding to pixels or points from the screen, the keyboard or
the row; ink-weighted centring; optical sizes) predicted Apple's per-key
scatter across devices; the best managed 0.31 pt RMS against 0.385 for plain
centring.

Why: only the per-case constant holds on every device of a scale. Apple's
lowercase sits 0.13-0.22 pt right of plain centring on all four 3x iPhones
measured, its capitals within 0.13 either way, and the SE's by 0.55 and 0.23.

Verified (ink centroids, all 26 letters, light and dark; median|max, pt):
- Lowercase x: 17 Pro 0.31|0.82 -> 0.25|0.82; Air and Pro Max unchanged
  0.29|0.77 (the half-pixel nudge rounds away there); 17e 0.26|0.81; SE
  0.58|1.16 -> 0.27|0.69.
- Capitals x: unchanged on 3x (0.25-0.28); SE 0.35|0.70 -> 0.33|0.64.
- Capitals y on 3x: 0.27 -> 0.06.
- Full HEXMobileTests pass.
2026-11-21 07:20:46 -05:00

192 lines
9.9 KiB
Swift
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.

import Foundation
/// How hard the keys' haptic tap is (Settings › Keyboard › Strength). Medium is meant to match
/// Apple's keyboard (testers found Hex's, a 0.65 light impact, too weak beside it).
nonisolated enum KeyHapticStrength: String, CaseIterable, Sendable {
case light
case medium
case strong
}
/// The full keyboard's switches in the shared App Group.
///
/// Without Full Access an iPhone may not let the keyboard read the App Group (the simulator
/// does), so every switch's default must work there: the full keyboard, which types
/// without Full Access.
@MainActor
struct FullKeyboardSettings {
static let launchArgument = "--experiment-full-keyboard"
static let emojiLaunchArgument = "--experiment-emoji"
static let swipeLaunchArgument = "--experiment-swipe"
/// Simulator scenes pass `--hex-key left` (or `right`) for Settings › Keyboard › Hex key.
static let hexKeyLaunchArgument = "--hex-key"
/// Simulator scenes pass `--keyboard dictation-bar` (or `full`) to pick the keyboard.
static let keyboardLaunchArgument = "--keyboard"
private enum Key {
static let fullKeyboard = "experiments.fullKeyboard"
static let autocorrect = "settings.keyboardAutocorrect"
static let autoCapitalization = "settings.keyboardAutoCapitalization"
static let spatialAutocorrect = "experiments.spatialAutocorrect"
static let germanSpatialAutocorrect = "experiments.germanSpatialAutocorrect"
static let keyPopups = "settings.keyboardKeyPopups"
static let haptics = "settings.keyboardHaptics"
static let hapticStrength = "settings.keyboardHapticStrength"
static let suggestSwearWords = "settings.keyboardSuggestSwearWords"
static let emoji = "experiments.emoji"
static let swipeTyping = "experiments.swipeTyping"
static let hexKeyOnLeft = "settings.keyboardHexKeyLeft"
}
private let defaults: UserDefaults?
init(defaults: UserDefaults? = UserDefaults(suiteName: KeyboardBridge.appGroup)) {
self.defaults = defaults
}
/// Settings › Keyboard: Full (true) or Dictation bar (false). The full keyboard (letters,
/// numbers, symbols, autocorrect and the Hex key) by default; the dictation bar (space,
/// delete, return and Dictate) only once it was chosen. Stored as
/// `experiments.fullKeyboard`, from when the full keyboard was an experiment: unset or
/// true is the full keyboard and false the dictation bar, so testers who never touched
/// the experiment get the full keyboard and those who turned it off keep the bar.
var isEnabled: Bool {
get { defaults?.object(forKey: Key.fullKeyboard) as? Bool ?? true }
nonmutating set { defaults?.set(newValue, forKey: Key.fullKeyboard) }
}
/// Settings › Keyboard › Auto-capitalization, as Apple's switch of the same name. On by
/// default: shift turns itself on where the field asks (the start of a field or sentence,
/// after "." "!" "?"). Off, Hex never adds a capital you didn't type: shift stays off
/// whatever the field's `autocapitalizationType`, and autocorrect and swipe typing keep
/// words lowercase ("i", "i'm", "monday") unless they're your own spelling. Dictation
/// keeps its own Lowercase setting.
var autoCapitalization: Bool {
get { defaults?.object(forKey: Key.autoCapitalization) as? Bool ?? true }
nonmutating set { defaults?.set(newValue, forKey: Key.autoCapitalization) }
}
/// Cautious autocorrect on space. On by default.
var autocorrect: Bool {
get { defaults?.object(forKey: Key.autocorrect) as? Bool ?? true }
nonmutating set { defaults?.set(newValue, forKey: Key.autocorrect) }
}
/// Settings › Keyboard › Spatial autocorrect: autocorrect reads your taps with a language
/// model (`TypingDecoder`) instead of `UITextChecker`'s one-edit guesses, in English and
/// Spanish. On by default. Stored as `experiments.spatialAutocorrect`, from when it was an
/// experiment (off by default) that only its switch ever wrote: unset or true is on and
/// false off, so testers who never touched it get it and those who turned it off keep it off.
var spatialAutocorrect: Bool {
get { defaults?.object(forKey: Key.spatialAutocorrect) as? Bool ?? true }
nonmutating set { defaults?.set(newValue, forKey: Key.spatialAutocorrect) }
}
/// Settings › Experiments › German spatial autocorrect: lets the Deutsch layout read your
/// taps with the German model Android ships (`TypingDecoder`), as English and Spanish
/// already do. Off by default, like every experiment: a keyboard without it types German
/// exactly as before (the dictionary engine, and no word list for the letter odds, the
/// strip or a bilingual partner). Stored as `experiments.germanSpatialAutocorrect`.
var germanSpatialAutocorrect: Bool {
get { defaults?.object(forKey: Key.germanSpatialAutocorrect) as? Bool ?? false }
nonmutating set { defaults?.set(newValue, forKey: Key.germanSpatialAutocorrect) }
}
/// The typing model the keyboard may read `language`'s taps with: its bundled model, with
/// German's only while both Spatial autocorrect and the German experiment are on. English
/// and Spanish never wait on the experiment. The keyboard asks this for the word list, the
/// decoder and a bilingual partner, so one gate keeps a German model out of everything
/// until it is chosen; `TypingDecoderModel.bundled` still loads any bundled file for tests.
func typingModel(for language: KeyboardLanguage) -> TypingDecoderModel? {
if language == .german, !(spatialAutocorrect && germanSpatialAutocorrect) { return nil }
return TypingDecoderModel.bundled(language.rawValue)
}
/// Suggestions and autocorrect may offer swear words (`OffensiveWords`); slurs never.
/// Off by default, like Apple's keyboard.
var suggestSwearWords: Bool {
get { defaults?.bool(forKey: Key.suggestSwearWords) ?? false }
nonmutating set { defaults?.set(newValue, forKey: Key.suggestSwearWords) }
}
/// The enlarged letter that pops up over a pressed key. On by default.
var keyPopups: Bool {
get { defaults?.object(forKey: Key.keyPopups) as? Bool ?? true }
nonmutating set { defaults?.set(newValue, forKey: Key.keyPopups) }
}
/// A light tap under your finger for each key press. On by default.
var haptics: Bool {
get { defaults?.object(forKey: Key.haptics) as? Bool ?? true }
nonmutating set { defaults?.set(newValue, forKey: Key.haptics) }
}
/// Settings › Keyboard › Strength, under Haptics: how hard each key's tap is. Medium, the
/// default, is meant to feel like Apple's keyboard.
var hapticStrength: KeyHapticStrength {
get { defaults?.string(forKey: Key.hapticStrength).flatMap(KeyHapticStrength.init(rawValue:)) ?? .medium }
nonmutating set { defaults?.set(newValue.rawValue, forKey: Key.hapticStrength) }
}
/// Settings › Keyboard › Emoji: an emoji key whose panel suggests emoji for what you just
/// typed, from what the words mean and what you use. On by default. Stored as
/// `experiments.emoji`, from when it was an experiment (off by default) that only its
/// switch ever wrote: unset or true is on and false off, so testers who turned it off
/// keep it off.
var emoji: Bool {
get { defaults?.object(forKey: Key.emoji) as? Bool ?? true }
nonmutating set { defaults?.set(newValue, forKey: Key.emoji) }
}
/// Settings › Keyboard › Swipe typing: slide through a word's letters to type it, on the
/// English and Spanish layouts (`SwipeTyping`). On by default. Stored as
/// `experiments.swipeTyping`, from when it was an experiment (off by default): unset or
/// true is on and false off, so testers who turned it off keep it off.
var swipeTyping: Bool {
get { defaults?.object(forKey: Key.swipeTyping) as? Bool ?? true }
nonmutating set { defaults?.set(newValue, forKey: Key.swipeTyping) }
}
/// Settings › Keyboard › Hex key: Right (false, the default) or Left. Left puts the Hex key
/// at the strip's leading end, for people who type with their left thumb; everything
/// tied to it (the recording bar's ✕ and ✓, its menu, the Full Access hint) follows.
var hexKeyOnLeft: Bool {
get { defaults?.bool(forKey: Key.hexKeyOnLeft) ?? false }
nonmutating set { defaults?.set(newValue, forKey: Key.hexKeyOnLeft) }
}
/// Where the full keyboard's Hex key sits for `hexKeyOnLeft`.
var hexKeyPlacement: HexKeyPlacement {
hexKeyOnLeft ? .stripLeading : .stripTrailing
}
/// Simulator scenes pass `--experiment-full-keyboard` or `--keyboard full|dictation-bar`
/// to pick the keyboard, `--experiment-emoji` to turn Emoji on, `--experiment-swipe` for
/// Swipe typing (both on by default; the arguments override a stored off), and
/// `--hex-key left|right` for the Hex key's side.
func applyLaunchArguments(_ arguments: [String] = ProcessInfo.processInfo.arguments) {
if arguments.contains(Self.launchArgument) {
isEnabled = true
}
if let index = arguments.firstIndex(of: Self.keyboardLaunchArgument), index + 1 < arguments.count {
switch arguments[index + 1] {
case "full": isEnabled = true
case "dictation-bar": isEnabled = false
default: break
}
}
if arguments.contains(Self.emojiLaunchArgument) {
emoji = true
}
if arguments.contains(Self.swipeLaunchArgument) {
swipeTyping = true
}
if let index = arguments.firstIndex(of: Self.hexKeyLaunchArgument), index + 1 < arguments.count {
switch arguments[index + 1] {
case "left": hexKeyOnLeft = true
case "right": hexKeyOnLeft = false
default: break
}
}
}
}