hex/ios/HEXShared/FullKeyboard/FullKeyboardView.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

1248 lines
52 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 Combine
import UIKit
/// The experimental full keyboard: a 3-slot suggestion strip, QWERTY keys with the Hex key
/// right of space, long-press accents, and the recording panel that replaces both while Hex records.
/// Dictation state comes from the same `KeyboardViewModel` the dictation bar uses.
@MainActor
final class FullKeyboardView: UIView, UIInputViewAudioFeedback {
let model: KeyboardViewModel
let engine: FullKeyboardEngine
weak var hostController: UIInputViewController? {
didSet { configureGlobe() }
}
/// Fixtures force light or dark and portrait or landscape; the keyboard follows its field.
var appearanceOverride: Bool? { didSet { applyAppearance() } }
var orientationOverride: KeyboardOrientation? { didSet { setNeedsLayout() } }
/// Haptics need Full Access.
var allowsHaptics: () -> Bool = { false }
/// Draws a stand-in backdrop where there is no system keyboard behind the view.
var drawsBackdrop = false { didSet { applyAppearance() } }
/// The keys typed, deleted, or pasted something (Learn how I type follows dictations).
var onTextEdit: (() -> Void)?
/// Undo dictation took the last dictation back.
var onUndoDictation: (() -> Void)?
/// The return key is about to type its line break.
var onReturnKey: (() -> Void)?
let stripView = KeyboardStripView()
/// The keys' touch surface; tests feed it touch samples.
let plane: KeyboardKeyPlaneView
let callout = KeyCalloutView()
let accentCallout = AccentCalloutView()
let hexKey = HexKeyControl()
let globeButton = UIButton(type: .custom)
/// The capsule that grows from the Hex mark across the strip into the recording bar.
private let morph = UIView()
private var recordingPanel: HexKeyRecordingPanel?
private var styleMenu: HexStyleMenuView?
private(set) var palette = FullKeyboardPalette(isDark: false)
private var didApplyPalette = false
private var subscriptions: Set<AnyCancellable> = []
private(set) var showsRecording = false
/// The Hex key's last tap or hold started a dictation here (not by opening Hex).
private var dictatingFromHexKey = false
private var lastDictation: String?
private var undoHideWork: DispatchWorkItem?
/// The Hex key was tapped without Full Access: the strip says what dictation needs.
private(set) var showsFullAccessHint = false
private var fullAccessHintHideWork: DispatchWorkItem?
/// How long the Full Access hint stays unless a key or the strip is used first.
static let fullAccessHintDuration: TimeInterval = 8
private let haptics = UIImpactFeedbackGenerator(style: .light)
/// Every key's touch-down tick (letters, space, delete and its repeats, shift, 123,
/// return, suggestions), as hard as Settings › Keyboard › Strength asks. The Hex key's hold
/// and its menu keep `haptics`' fuller thud.
var hapticStrength: KeyHapticStrength = .medium {
didSet {
guard hapticStrength != oldValue else { return }
keyTicks = UIImpactFeedbackGenerator(style: Self.keyTickStyle(hapticStrength))
if allowsHaptics() { keyTicks.prepare() }
}
}
private var keyTicks = UIImpactFeedbackGenerator(style: FullKeyboardView.keyTickStyle(.medium))
/// Apple's key haptic is a crisp tick, so every strength is a rigid impact (the sharpest
/// style) but Strong, a fuller medium one. Medium, the default, is 0.8 of a rigid tap;
/// Hex's was a 0.65 light impact, which testers found much weaker than Apple's.
static func keyTickStyle(_ strength: KeyHapticStrength) -> UIImpactFeedbackGenerator.FeedbackStyle {
strength == .strong ? .medium : .rigid
}
static func keyTickIntensity(_ strength: KeyHapticStrength) -> CGFloat {
switch strength {
case .light: 0.5
case .medium: 0.8
case .strong: 1
}
}
private let selectionHaptics = UISelectionFeedbackGenerator()
private let clipboard = KeyboardClipboardTracker()
/// What the strip's Paste chip offers now.
private var stripOffer: KeyboardClipboardOffer?
/// A paste iOS asked about or refused: the strip points to the setting that stops it.
private var showsAllowPasteHint = false
private var allowPasteHintHideWork: DispatchWorkItem?
static let allowPasteHintDuration: TimeInterval = 8
// MARK: Emoji (Settings › Keyboard › Emoji; FullKeyboardView+Emoji.swift)
/// The keys' target: the field, or the emoji search while you search.
let routedTarget: EmojiRoutedTarget
/// Fixtures turn the emoji experiment on or off; otherwise the App Group's switch.
var emojiOverride: Bool? { didSet { refreshEmojiKey() } }
/// Where emoji use is kept; fixtures give a seeded store.
var makeEmojiUsage: () -> EmojiUsageStore = { EmojiUsageStore() }
var emojiLibrary: EmojiLibrary?
var emojiPanel: EmojiPanelView?
var emojiSearchField: EmojiSearchField?
var emojiResults: EmojiRowView?
var emojiResultEntries: [Int] = []
var emojiSearchLift: CGFloat = 0
/// Record typing logs, held back while you type a search.
var suspendedTypingLog: TypingLogger?
/// From the emoji key to the panel's suggestions laid out, for probes.
var lastEmojiPanelLatency: TimeInterval?
/// Exposed so unit tests can verify lazy allocation and teardown of the Metal recording panel.
var hasAllocatedRecordingPanel: Bool { recordingPanel != nil }
init(model: KeyboardViewModel, target: KeyboardTextTarget, autocorrect: AutocorrectEngine? = nil) {
self.model = model
routedTarget = EmojiRoutedTarget(document: target)
engine = FullKeyboardEngine(target: routedTarget, autocorrect: autocorrect)
plane = KeyboardKeyPlaneView(engine: engine)
super.init(frame: .zero)
backgroundColor = .clear
addSubview(stripView)
morph.isUserInteractionEnabled = false
morph.isHidden = true
addSubview(morph)
addSubview(plane)
addSubview(hexKey)
addSubview(globeButton)
addSubview(callout)
addSubview(accentCallout)
accentCallout.isHidden = true
stripView.onSelectSuggestion = { [weak self] suggestion in
guard let self else { return }
self.keyFeedback()
if suggestion.kind == .emoji {
self.recordEmojiUse(suggestion.replacement)
}
self.engine.acceptSuggestion(suggestion)
}
stripView.onUndoDictation = { [weak self] in self?.undoDictation() }
stripView.onPaste = { [weak self] in self?.pasteFromClipboard() }
stripView.onOpenHexFromHint = { [weak self] in self?.openSetupFromHint() }
stripView.onOpenNotice = { [weak self] in
self?.keyFeedback()
self?.model.onOpenURL?(KeyboardLaunchRequest.translationSettings.url)
}
stripView.onNextKeyboard = { [weak self] in
self?.typingLog?.ui("next_keyboard")
self?.hostController?.advanceToNextInputMode()
}
globeButton.accessibilityLabel = "Next keyboard"
globeButton.isAccessibilityElement = true
globeButton.addTarget(self, action: #selector(globeTapped), for: .touchUpInside)
hexKey.onPress = { [weak self] at in self?.model.onHexKeyPress?(at) }
hexKey.onPressAbandoned = { [weak self] in self?.model.onHexKeyAbandon?() }
hexKey.onHold = { [weak self] in self?.hexKeyHeld() }
hexKey.onHoldRelease = { [weak self] in self?.hexKeyReleased() }
hexKey.onMenuOpen = { [weak self] point in
guard let self else { return }
// Styles and languages are for dictation, which needs Full Access.
guard self.model.hasFullAccess else {
self.showFullAccessHint()
return
}
self.typingLog?.ui("hex_menu")
self.showStyleMenu()
self.forwardMenuPoint(point, release: false)
}
hexKey.onMenuDrag = { [weak self] point in self?.forwardMenuPoint(point, release: false) }
hexKey.onMenuRelease = { [weak self] point in self?.forwardMenuPoint(point, release: true) }
plane.onKeyDown = { [weak self] _ in self?.keyFeedback() }
plane.onAccentMenuOpened = { [weak self] in self?.selectionFeedback() }
engine.onSelectionStep = { [weak self] in self?.selectionFeedback() }
engine.onChange = { [weak self] in self?.engineChanged() }
engine.onEdit = { [weak self] in
guard let self else { return }
if self.routedTarget.isSearching {
self.refreshEmojiSearch()
return
}
self.hideUndo()
self.hideFullAccessHint()
self.hideAllowPasteHint()
self.refreshReturnKey()
self.refreshStrip()
self.onTextEdit?()
}
engine.onReturn = { [weak self] in
guard self?.routedTarget.isSearching == false else { return }
self?.onReturnKey?()
}
engine.onEmojiKey = { [weak self] in self?.emojiKeyTapped() }
engine.onLanguageSwipe = { [weak self] step in self?.switchLanguage(by: step) }
routedTarget.onSearchReturn = { [weak self] in self?.endEmojiSearch() }
model.objectWillChange
.receive(on: RunLoop.main)
.sink { [weak self] _ in self?.refreshFromModel() }
.store(in: &subscriptions)
registerForTraitChanges([UITraitUserInterfaceStyle.self, UITraitVerticalSizeClass.self]) { (view: FullKeyboardView, _) in
view.applyAppearance()
view.setNeedsLayout()
}
engine.autocorrect.isEnabled = FullKeyboardSettings().autocorrect
engine.autocorrect.allowsSwearing = FullKeyboardSettings().suggestSwearWords
engine.autoCapitalizes = FullKeyboardSettings().autoCapitalization
engine.showsKeyPopups = FullKeyboardSettings().keyPopups
syncHexPlacement()
refreshEmojiKey()
syncSpatialAutocorrect()
refreshLanguageSignals()
syncLanguage()
syncSwipeTyping()
engine.configureForField()
applyAppearance()
refreshFromModel()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError() }
// MARK: - Typing logs
/// Record typing logs (Experiments): set by the keyboard while a session may be logged,
/// nil otherwise. The app's fixtures never set it.
var typingLog: TypingLogger? {
get { routedTarget.isSearching ? suspendedTypingLog : engine.typingLog }
set {
if routedTarget.isSearching {
suspendedTypingLog = newValue
} else {
engine.typingLog = newValue
}
}
}
/// A typing log session began: write the layout, shift, and suggestions as they are now.
func typingLogSessionBegan() {
guard let log = engine.typingLog else { return }
log.viewGeometry(size: bounds.size, safeArea: safeAreaInsets)
engine.logState("session")
log.commitGeometry()
log.suggestionsChanged(engine.suggestions)
}
@objc private func globeTapped() {
typingLog?.ui("globe")
}
// MARK: - Size
static func orientation(for traits: UITraitCollection) -> KeyboardOrientation {
traits.verticalSizeClass == .compact ? .landscape : .portrait
}
var orientation: KeyboardOrientation {
orientationOverride ?? Self.orientation(for: traitCollection)
}
var preferredHeight: CGFloat {
KeyboardLayout.height(for: orientation, posture: engine.posture, phoneSize: engine.phoneSize) + lift
}
/// Room above the strip for the emoji search results. The strip itself keeps its height in
/// every state, the recording bar's included.
private var lift: CGFloat { emojiSearchLift }
/// Asks the host to apply `preferredHeight` now (the keyboard extension resizes itself).
var onPreferredHeightChange: (() -> Void)?
/// How much of the lift the view actually has yet, so nothing jumps before the host grows it.
private var appliedLift: CGFloat {
max(0, min(lift, bounds.height - KeyboardLayout.height(for: orientation, posture: engine.posture, phoneSize: engine.phoneSize)))
}
/// Reads which device and posture the keyboard is on, and how far iOS set it in from the
/// screen's sides, from its window. The Duo's unfolded screen has regular size classes either
/// way up, so the size classes alone can't tell its postures apart.
private func syncPosture() {
guard let screen = window?.windowScene?.screen ?? window?.screen else { return }
let size = screen.bounds.size
let posture = KeyboardPosture.current(screenSize: size, isFoldable: Self.isFoldable)
let inset = posture == .phone ? 0 : max(0, (size.width - bounds.width) / 2)
let phoneSize = KeyboardPhoneSize.current(screenSize: size)
let heightChanges = posture != engine.posture || phoneSize != engine.phoneSize
engine.posture = posture
engine.phoneSize = phoneSize
engine.windowInset = inset
if heightChanges { onPreferredHeightChange?() }
}
/// The iPhone Duo (`KeyboardPosture.foldableModels`), read once per process.
static let isFoldable: Bool = {
if let simulated = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] {
return KeyboardPosture.foldableModels.contains(simulated)
}
var system = utsname()
uname(&system)
let model = withUnsafeBytes(of: &system.machine) { raw in
String(decoding: raw.prefix { $0 != 0 }, as: UTF8.self)
}
return KeyboardPosture.foldableModels.contains(model)
}()
// MARK: - Host events
var enableInputClicksWhenVisible: Bool { true }
func warmUpTextCheckerAsync() {
DispatchQueue.main.async { [weak self] in
guard let self, let checker = self.engine.autocorrect.checker as? SystemTextChecker else { return }
checker.warmUp()
// German's capitalisation list reads with the dictionary, off the open path, and only
// while the German model is on: the dictionary engine never asks for it.
if self.engine.language == .german, self.engine.letterOdds != nil,
self.engine.autocorrect.germanCapitals == nil {
self.engine.autocorrect.germanCapitals = GermanCapitals.bundled()
}
self.engine.refreshSuggestions()
}
}
func loadLexicon(_ lexicon: UILexicon) {
engine.autocorrect.loadLexicon(lexicon)
engine.refreshSuggestions()
}
// MARK: - Language
/// Fixtures pin one layout; otherwise Settings › Keyboard › Languages, whose Automatic
/// follows the dictation language.
var languageOverride: KeyboardLanguage? {
didSet { syncLanguage() }
}
/// Fixtures pin how the letters are arranged; otherwise Settings › Keyboard › Languages ›
/// Layout for the keys' language. Without the App Group (an iPhone that keeps it from a
/// keyboard without Full Access) every language types on its own layout, as before.
var letterLayoutOverride: KeyboardLetterLayout? {
didSet { syncLanguage() }
}
/// Where Languages and the language last switched to are kept; tests give their own.
var languageSettings = LanguageSettings() {
didSet { syncLanguage() }
}
/// The languages the space bar switches between and the one typing now.
private(set) var languages = KeyboardLanguageList(languages: [.english], current: .english)
/// The language this keyboard last switched to, ahead of the App Group's copy, which an
/// iPhone may not let a keyboard without Full Access write.
private var switchedLanguage: KeyboardLanguage?
private static let spellCheckLanguages = UITextChecker.availableLanguages
/// The iPhone's keyboards and preferred languages, read when the keyboard appears, for
/// Automatic before any dictation language is known.
private var inputModeLanguages: [String] = []
private var preferredLanguages: [String] = []
private func refreshLanguageSignals() {
inputModeLanguages = UITextInputMode.activeInputModes.compactMap(\.primaryLanguage)
preferredLanguages = Locale.preferredLanguages
}
private func syncLanguage() {
let settings = languageSettings
let list = if let languageOverride {
KeyboardLanguageList(languages: [languageOverride], current: languageOverride)
} else {
KeyboardLanguageList.resolve(
chosen: settings.keyboardLanguages,
stored: switchedLanguage ?? settings.currentKeyboardLanguage,
automatic: KeyboardLanguage.automatic(
dictationLanguage: settings.effectiveDictationLanguage,
inputModes: inputModeLanguages,
preferredLanguages: preferredLanguages
)
)
}
// The keys' language's layout: with English and Spanish on one keyboard, the first one's.
let letters = letterLayoutOverride.map(list.layout.offered) ?? settings.letterLayout(for: list.layout)
guard list != languages || engine.language != list.current || engine.letterLayout != letters else { return }
languages = list
engine.switchesLanguage = list.switches
engine.layoutLanguage = list.layout == list.current ? nil : list.layout
engine.letterLayout = letters
engine.language = list.current
engine.partnerLanguage = list.partner(available: Self.spellCheckLanguages)
syncSpatialAutocorrect()
refreshSpaceLabel()
syncSwipeTyping()
setNeedsLayout()
}
/// A swipe along the space bar: the next or previous language (its letters, accents and
/// autocorrect), kept for next time. Dictation on Automatic follows it
/// (`LanguageSettings.keyboardDictationLanguage`); with Switch dictation too, a dictation
/// language picked by hand goes back to Automatic, so it follows too.
func switchLanguage(by step: Int) {
guard languages.switches, languageOverride == nil else { return }
let next = languages.switched(by: step)
typingLog?.ui("keyboard_language", [TypingLogField("language", .string(next.rawValue))])
switchedLanguage = next
languageSettings.currentKeyboardLanguage = next
selectionFeedback()
syncLanguage()
guard languageSettings.dictationFollowsKeyboard, model.hasFullAccess,
languageSettings.dictationLanguage != nil else { return }
model.onLanguageSelected?(nil)
}
/// With two or more languages the space bar names the keyboard's; otherwise, with Full
/// Access, the dictation language's.
private func refreshSpaceLabel() {
plane.spaceLabel = languages.spaceLabel ?? (model.hasFullAccess ? model.languageSummary : nil)
}
func syncSettings() {
syncLanguage()
let journal = TypingJournal.sharedIfEnabled()
if engine.journal !== journal {
engine.journal = journal
}
// Adaptive touch keeps its averages on disk only with Full Access; without, in memory.
let adaptive = AdaptiveTouch.sharedIfEnabled(persistent: hostController?.hasFullAccess == true)
if engine.adaptiveTouch !== adaptive {
engine.adaptiveTouch = adaptive
}
engine.showsKeyPopups = FullKeyboardSettings().keyPopups
engine.autoCapitalizes = FullKeyboardSettings().autoCapitalization
hapticStrength = FullKeyboardSettings().hapticStrength
syncHexPlacement()
refreshEmojiKey()
let wantsAutocorrect = FullKeyboardSettings().autocorrect
if engine.autocorrect.isEnabled != wantsAutocorrect {
engine.autocorrect.isEnabled = wantsAutocorrect
engine.refreshSuggestions()
}
let wantsSwearing = FullKeyboardSettings().suggestSwearWords
if engine.autocorrect.allowsSwearing != wantsSwearing {
engine.autocorrect.allowsSwearing = wantsSwearing
engine.refreshSuggestions()
}
syncSpatialAutocorrect()
syncSwipeTyping()
}
/// Fixtures pin where the Hex key sits; otherwise Settings › Keyboard › Hex key.
var hexPlacementOverride: HexKeyPlacement? { didSet { syncHexPlacement() } }
/// Settings › Keyboard › Hex key: Right (the strip's trailing end) or Left (its leading
/// end), kept in `HexKeyPlacement.current` too for typing logs.
private func syncHexPlacement() {
let placement = hexPlacementOverride ?? FullKeyboardSettings().hexKeyPlacement
HexKeyPlacement.current = placement
guard engine.hexPlacement != placement else { return }
plane.cancelAllTouches()
dismissStyleMenu()
engine.hexPlacement = placement
setNeedsLayout()
}
/// Fixtures and tests turn Swipe typing on or off; otherwise its switch in Settings › Keyboard.
var swipeOverride: Bool? { didSet { syncSwipeTyping() } }
/// Settings › Keyboard › Swipe typing (on by default): on the English and Spanish layouts, a
/// drag across the letters types a word, read with the layout language's bundled model.
/// Off under VoiceOver, which has its own way to type. German stays out of it:
/// `supportsSwipeTyping` lists English and Spanish only, and the experiment does not add it.
private func syncSwipeTyping() {
let settings = FullKeyboardSettings()
let on = (swipeOverride ?? settings.swipeTyping) && engine.language.supportsSwipeTyping
&& !UIAccessibility.isVoiceOverRunning
let model = on ? settings.typingModel(for: engine.language) : nil
if plane.swipe?.model !== model {
plane.swipe = model.map { SwipeTyping(engine: engine, model: $0) }
} else {
plane.swipe?.syncWords()
}
}
/// Settings › Keyboard › Spatial autocorrect (on by default): maps the layout language's
/// bundled model when the keyboard opens (English, Spanish, and German while its experiment
/// in Settings › Experiments is on; others keep `UITextChecker`), and moves the keys'
/// centres to where Learn how I type saw you tap. The same word list lets the likely next
/// letter claim a few points of its neighbour's touch target whether or not Spatial
/// autocorrect is on (`FullKeyboardEngine.letterOdds`; only while autocorrecting).
private func syncSpatialAutocorrect() {
let settings = FullKeyboardSettings()
let words = settings.typingModel(for: engine.language)
if engine.letterOdds !== words {
engine.letterOdds = words
}
let model = settings.spatialAutocorrect ? words : nil
if engine.autocorrect.decoder?.model !== model {
engine.autocorrect.decoder = model.map { TypingDecoder(model: $0) }
engine.refreshSuggestions()
}
// Bilingual autocorrect reads the same taps with the other language's model, where it has one.
if let partner = engine.autocorrect.partner {
let theirs = settings.spatialAutocorrect ? settings.typingModel(for: partner.language) : nil
if partner.decoder?.model !== theirs {
partner.decoder = theirs.map { TypingDecoder(model: $0) }
engine.refreshSuggestions()
}
}
let keys = model == nil ? [:] : (engine.journal?.current.keys ?? [:])
engine.tapOffsets = TypingDecoder.offsets(from: keys, layout: engine.layout)
}
/// The field or its contents changed outside these keys.
func textDidChange() {
applyAppearance()
let field = engine.field
let route = KeyboardFieldRouting.route(for: engine.target.keyboardType)
let routeField: KeyboardFieldKind = if case .keys(let kind, _) = route { kind } else { .text }
// While you search emoji the keys still type the query, whatever the host changed.
if routedTarget.isSearching {
refreshReturnKey()
return
}
if routeField != field {
plane.cancelAllTouches()
engine.configureForField()
refreshEmojiKey()
} else {
engine.textDidChange()
}
refreshReturnKey()
refreshStrip()
}
/// The keyboard came on screen for a (possibly new) field.
func prepareForField() {
closeEmojiPanel()
refreshLanguageSignals()
syncSettings()
plane.cancelAllTouches()
engine.configureForField()
refreshReturnKey()
applyAppearance()
refreshStrip()
dismissStyleMenu()
if allowsHaptics() {
keyTicks.prepare()
selectionHaptics.prepare()
}
}
/// Frees non-essential UI and Metal drawables when the extension approaches its memory ceiling.
func handleMemoryWarning() {
dismissStyleMenu()
if emojiPanel == nil {
emojiLibrary = nil
}
emojiPanel?.glyphs.purge()
if !showsRecording, let panel = recordingPanel {
panel.tearDown()
panel.removeFromSuperview()
recordingPanel = nil
}
}
/// Hex inserted a dictation; offer to take it back until the next edit.
func didInsertDictation(_ text: String) {
lastDictation = text
refreshStrip()
undoHideWork?.cancel()
let work = DispatchWorkItem { [weak self] in self?.hideUndo() }
undoHideWork = work
DispatchQueue.main.asyncAfter(deadline: .now() + 12, execute: work)
engine.textDidChange()
refreshReturnKey()
}
/// Fixtures: show a key held down.
func debugPress(_ character: String) {
guard let key = engine.layout.key(.character(character)) else { return }
engine.touchBegan(id: -1, at: CGPoint(x: key.frame.midX, y: key.frame.midY))
}
/// Fixtures: show a key's accent callout with `option` selected.
func debugHoldAccent(_ character: String, selecting option: String) {
debugHoldAccent(character)
guard let index = engine.activeAccentMenu?.options.firstIndex(of: option) else { return }
engine.debugSelectAccent(index)
}
/// Fixtures: show a key's long-press accent callout.
func debugHoldAccent(_ character: String, selectIndex: Int? = nil) {
guard let key = engine.layout.key(.character(character)) else { return }
let center = CGPoint(x: key.frame.midX, y: key.frame.midY)
engine.touchBegan(id: -2, at: center)
_ = engine.openAccentMenuIfEligible(forTouch: -2)
if let selectIndex { engine.debugSelectAccent(selectIndex) }
}
// MARK: - Layout
override func layoutSubviews() {
super.layoutSubviews()
let isLandscape = orientation == .landscape
engine.typingLog?.viewGeometry(size: bounds.size, safeArea: safeAreaInsets)
engine.orientation = orientation
engine.horizontalInset = isLandscape ? max(safeAreaInsets.left, safeAreaInsets.right) : 0
engine.width = bounds.width
syncPosture()
engine.typingLog?.commitGeometry()
let layout = engine.layout
let lift = appliedLift
let content = CGRect(x: 0, y: lift, width: bounds.width, height: bounds.height - lift)
plane.frame = content
callout.frame = content
accentCallout.frame = content
stripView.frame = layout.stripFrame.offsetBy(dx: 0, dy: lift)
stripView.slotFrames = layout.stripSlotFrames.map { $0.offsetBy(dx: -layout.stripFrame.minX, dy: -layout.stripFrame.minY) }
stripView.pillInset = layout.metrics.stripInset
stripView.hexOnLeading = layout.hexOnLeading
hexKey.cornerRadius = layout.metrics.cornerRadius
if let hex = layout.key(.hex) {
hexKey.inStrip = hex.row < 0
hexKey.frame = hex.hitFrame.offsetBy(dx: 0, dy: lift)
hexKey.keycapFrame = hex.frame.offsetBy(dx: -hex.hitFrame.minX, dy: -hex.hitFrame.minY)
}
if let globe = layout.key(.globe), emojiPanel == nil || routedTarget.isSearching {
globeButton.isHidden = false
globeButton.frame = globe.hitFrame.offsetBy(dx: 0, dy: lift)
} else {
globeButton.isHidden = true
}
layoutEmoji(content: content, lift: lift)
if let panel = recordingPanel {
panel.frame = recordingPanelFrame
panel.horizontalInset = layout.horizontalInset
panel.metrics = layout.metrics
panel.sideKeyWidth = layout.modifierWidth
panel.hexOnLeading = layout.hexOnLeading
}
if let menu = styleMenu, let hex = layout.key(.hex) {
menu.frame = bounds
menu.anchor = hex.frame
}
plane.setNeedsDisplay()
updateCallout()
}
// MARK: - State
private func applyAppearance() {
let isDark = appearanceOverride
?? FullKeyboardPalette.isDark(traits: traitCollection)
let next = FullKeyboardPalette(isDark: isDark)
backgroundColor = drawsBackdrop ? next.backdrop : .clear
stripView.inSystemPlatter = !drawsBackdrop
guard next != palette || !didApplyPalette else { return }
didApplyPalette = true
palette = next
stripView.palette = next
plane.palette = next
callout.palette = next
callout.setNeedsDisplay()
accentCallout.palette = next
hexKey.palette = next
recordingPanel?.palette = next
styleMenu?.palette = next
emojiPanel?.palette = next
emojiSearchField?.palette = next
emojiResults?.palette = next
}
func refreshReturnKey() {
let type = engine.target.returnKeyType ?? .default
plane.returnLabel = switch type {
case .go: "go"
case .google, .yahoo, .search: "search"
case .join: "join"
case .next: "next"
case .route: "route"
case .send: "send"
case .done: "done"
case .emergencyCall: "SOS"
case .continue: "continue"
default: "return"
}
plane.returnSymbol = switch type {
case .send: "arrow.up"
case .go, .continue, .route, .join: "arrow.right"
case .google, .yahoo, .search: "magnifyingglass"
case .done: "checkmark"
case .emergencyCall: nil
default: "return"
}
plane.returnIsAction = switch type {
case .go, .google, .yahoo, .search, .join, .route, .send, .done, .continue, .emergencyCall: true
default: false
}
plane.returnIsEnabled = !(engine.target.enablesReturnKeyAutomatically == true && !engine.target.hasText)
}
private func refreshFromModel() {
hexKey.isWarm = model.hasFullAccess && model.isWarmAvailable
hexKey.translatingTo = model.translatingTo
if engine.showsGlobe != model.needsGlobeKey {
engine.showsGlobe = model.needsGlobeKey
setNeedsLayout()
}
let recording = model.stagePhase == .recording || model.stagePhase == .transcribing
if recording != showsRecording {
setRecording(recording)
}
refreshRecordingPanel()
stripView.showsLoggingMark = model.isLoggingTyping
recordingPanel?.showsLoggingMark = model.isLoggingTyping
// A language picked in the switch changes the layout at once when it follows dictation.
syncLanguage()
refreshSpaceLabel()
if let menu = styleMenu {
menu.style = model.style
applyLanguages(to: menu)
}
refreshStrip()
}
private func applyLanguages(to menu: HexStyleMenuView) {
menu.dictationLanguage = model.dictationLanguage
menu.automaticLanguage = model.automaticLanguage
menu.languageChoices = model.showsLanguageSwitch ? model.languageChoices : []
menu.translationTarget = model.showsTranslationSwitch ? model.translationLanguage : nil
menu.isTranslating = model.isTranslating
menu.translationTargets = model.translationTargetChoices
}
func refreshStrip() {
// Without Full Access the strip suggests and corrects like any keyboard's; what
// dictation needs shows only once the Hex key is tapped (`showFullAccessHint`).
let status: String? = if model.hasFullAccess, model.stagePhase == .failed {
model.statusMessage
} else if showsAllowPasteHint {
KeyboardClipboardTracker.allowPasteHint
} else {
nil
}
var clipboardOffer = clipboard.offer(
textContentType: engine.target.textContentType,
hasFullAccess: model.hasFullAccess
)
// A dictation that didn't go in by itself comes before a copy, but not in a code field.
if model.hasFullAccess, model.offeredDictation != nil {
if case .code = clipboardOffer {} else { clipboardOffer = .dictation }
}
stripOffer = clipboardOffer
var suggestions = engine.suggestions
if showsAllowPasteHint, status != nil {
// The pasted text's last word would otherwise hide where to stop Allow Paste.
suggestions = []
} else if suggestions.isEmpty || suggestions.first?.kind == .nextWord {
if lastDictation != nil || status != nil || clipboardOffer != nil {
suggestions = []
} else {
let emoji = emojiForFinishedWord()
if !emoji.isEmpty {
// The finished word's emoji, with next words beside it so every slot fills:
// one emoji takes the centre.
let words = Array(suggestions.prefix(max(0, 3 - emoji.count)))
suggestions = emoji.count == 1 && words.count == 2 ? [words[0], emoji[0], words[1]] : emoji + words
}
}
}
stripView.update(
suggestions: suggestions,
showsUndo: lastDictation != nil,
statusText: status,
clipboard: clipboardOffer,
fullAccessHint: showsFullAccessHint && !model.hasFullAccess,
notice: translationNotice
)
}
/// The last dictation went in as spoken while Translate what I say was on: what happened,
/// the fix, and Open Hex, which opens Settings › Dictation.
private var translationNotice: KeyboardStripNotice? {
guard model.hasFullAccess, let note = model.translationNote else { return nil }
return KeyboardStripNotice(title: TranslationFailure.note, detail: note.fix, button: String(localized: "Open Hex"))
}
// MARK: - Without Full Access
/// The Hex key without Full Access: the keys keep typing, and the strip says, for a few
/// seconds, that dictation needs Allow Full Access and where to turn it on. Only its
/// Open Hex chip opens Hex; nothing opens it by itself.
func showFullAccessHint() {
dismissStyleMenu()
showsFullAccessHint = true
refreshStrip()
UIAccessibility.post(
notification: .announcement,
argument: "\(FullAccessHintView.title). Settings, Apps, Hex, Keyboards."
)
fullAccessHintHideWork?.cancel()
let work = DispatchWorkItem { [weak self] in self?.hideFullAccessHint() }
fullAccessHintHideWork = work
DispatchQueue.main.asyncAfter(deadline: .now() + Self.fullAccessHintDuration, execute: work)
}
private func hideFullAccessHint() {
fullAccessHintHideWork?.cancel()
fullAccessHintHideWork = nil
guard showsFullAccessHint else { return }
showsFullAccessHint = false
refreshStrip()
}
private func openSetupFromHint() {
keyFeedback()
hideFullAccessHint()
model.onOpenURL?(KeyboardLaunchRequest.setup.url)
}
private func pasteFromClipboard() {
if stripOffer == .dictation {
keyFeedback()
typingLog?.ui("paste_dictation")
model.onPasteDictation?()
refreshStrip()
return
}
let pasteboard = UIPasteboard.general
// The read blocks while iOS asks Allow Paste, so its length tells whether it asked.
let start = ProcessInfo.processInfo.systemUptime
let read = KeyboardClipboardTracker.read(pasteboard)
let readDuration = ProcessInfo.processInfo.systemUptime - start
let text = read.flatMap { $0.isEmpty ? nil : $0 }
let refused = text == nil && (pasteboard.hasStrings || pasteboard.hasURLs)
let pointsToSetting = clipboard.shouldPointToAllowPaste(readDuration: readDuration, refused: refused)
guard let text else {
if pointsToSetting { showAllowPasteHint() }
return
}
keyFeedback()
clipboard.markPasted()
typingLog?.edit("paste", [TypingLogField("inserted", .string(text))])
engine.target.insertText(text)
engine.textDidChange()
typingLog?.context("paste")
if pointsToSetting { showAllowPasteHint() }
refreshStrip()
onTextEdit?()
}
/// For a few seconds after a paste iOS asked about (or refused), the strip says where
/// to stop it asking: Settings › Apps › Hex › Paste from Other Apps › Allow.
private func showAllowPasteHint() {
showsAllowPasteHint = true
refreshStrip()
UIAccessibility.post(notification: .announcement, argument: KeyboardClipboardTracker.allowPasteHintAnnouncement)
allowPasteHintHideWork?.cancel()
let work = DispatchWorkItem { [weak self] in self?.hideAllowPasteHint() }
allowPasteHintHideWork = work
DispatchQueue.main.asyncAfter(deadline: .now() + Self.allowPasteHintDuration, execute: work)
}
/// Typing takes the strip back before the hint's time is up.
private func hideAllowPasteHint() {
allowPasteHintHideWork?.cancel()
allowPasteHintHideWork = nil
guard showsAllowPasteHint else { return }
showsAllowPasteHint = false
refreshStrip()
}
private func refreshRecordingPanel() {
guard let panel = recordingPanel, showsRecording else { return }
panel.update(
phase: model.stagePhase == .transcribing ? .processing : .recording,
style: model.style
)
}
private func setRecording(_ recording: Bool) {
showsRecording = recording
dismissStyleMenu()
if recording { closeEmojiPanel() }
let closingFrames = recording ? nil : morphFrames()
if recording {
plane.cancelAllTouches()
hideUndo()
let panel = recordingPanel ?? makeRecordingPanel()
panel.palette = palette
panel.frame = recordingPanelFrame
refreshRecordingPanel()
panel.isHidden = false
if let (mark, bar) = morphFrames(), window != nil {
// The mark grows into a capsule and runs across the strip, then the panel takes over.
runMorph(from: mark, to: bar, appearing: true)
fade(in: [], out: [stripView, hexKey])
DispatchQueue.main.asyncAfter(deadline: .now() + 0.16) { [weak self, weak panel] in
guard let self, self.showsRecording, let panel else { return }
self.fade(in: [panel], out: [self.morph])
}
} else {
fade(in: [panel], out: [stripView, hexKey])
}
} else if let panel = recordingPanel {
panel.scope.phase = .hidden
if let (_, bar) = closingFrames, let (mark, _) = morphFrames(), window != nil {
runMorph(from: bar, to: mark, appearing: false)
}
fade(in: [stripView, hexKey], out: [panel]) { [weak self, weak panel] in
guard let self, !self.showsRecording, let panel, panel === self.recordingPanel else { return }
panel.tearDown()
panel.removeFromSuperview()
self.recordingPanel = nil
}
}
}
/// Where the recording panel sits: the suggestion strip, full width and its height, so
/// neither the keyboard nor the keys move.
private var recordingPanelFrame: CGRect {
let m = engine.layout.metrics
return CGRect(x: 0, y: m.stripTop + appliedLift, width: bounds.width, height: m.stripHeight)
}
/// The Hex mark's frame in the strip and the full-width bar it grows into, or nil when
/// the Hex key sits in the bottom row.
private func morphFrames() -> (CGRect, CGRect)? {
let layout = engine.layout
guard let hex = layout.key(.hex), hex.row < 0 else { return nil }
let m = layout.metrics
let lift = appliedLift
let mark = hex.frame.offsetBy(dx: 0, dy: lift)
let bar = CGRect(
x: layout.horizontalInset + m.side,
y: m.stripTop + lift + m.stripInset,
width: bounds.width - 2 * (layout.horizontalInset + m.side),
height: m.stripPillHeight
)
return (mark, bar)
}
private func runMorph(from start: CGRect, to end: CGRect, appearing: Bool) {
morph.layer.removeAllAnimations()
// Under the recording panel on the way in (the panel fades in over it), above it on the
// way out so the bar is seen shrinking back into the mark.
if appearing {
insertSubview(morph, aboveSubview: stripView)
} else {
bringSubviewToFront(morph)
}
morph.backgroundColor = palette.chipFill
morph.frame = start
morph.layer.cornerRadius = start.height / 2
morph.alpha = appearing ? 0.6 : 1
morph.isHidden = false
UIView.animate(
withDuration: 0.34,
delay: 0,
usingSpringWithDamping: 0.82,
initialSpringVelocity: 0,
options: [.beginFromCurrentState, .allowUserInteraction]
) {
self.morph.frame = end
self.morph.layer.cornerRadius = end.height / 2
if appearing { self.morph.alpha = 1 }
}
guard !appearing else { return }
UIView.animate(withDuration: 0.12, delay: 0.24, options: [.allowUserInteraction]) {
self.morph.alpha = 0
} completion: { _ in
if !self.showsRecording {
self.morph.isHidden = true
}
}
}
private func fade(in shown: [UIView], out hidden: [UIView], after: (() -> Void)? = nil) {
shown.forEach { $0.isHidden = false }
let globeHidden = engine.layout.key(.globe) == nil
let accentHidden = engine.activeAccentMenu == nil
let duration = window == nil ? 0 : 0.18
if duration == 0 {
shown.forEach { $0.alpha = 1 }
hidden.forEach {
$0.alpha = 0
$0.isHidden = true
}
if globeHidden { globeButton.isHidden = true }
if accentHidden { accentCallout.isHidden = true }
after?()
return
}
UIView.animate(withDuration: duration, delay: 0, options: [.beginFromCurrentState, .allowUserInteraction]) {
shown.forEach { $0.alpha = 1 }
hidden.forEach { $0.alpha = 0 }
} completion: { _ in
// A Hex key still held for push to talk stays in the window (at alpha 0), so its
// touch keeps arriving and lifting the finger finishes the dictation.
for view in hidden where view.alpha == 0 && (view as? UIControl)?.isTracking != true {
view.isHidden = true
}
if globeHidden { self.globeButton.isHidden = true }
if accentHidden { self.accentCallout.isHidden = true }
after?()
}
}
private func makeRecordingPanel() -> HexKeyRecordingPanel {
let panel = HexKeyRecordingPanel(loudness: { [weak model] in model?.liveLoudnessDB ?? -62 })
panel.alpha = 0
panel.onDone = { [weak self] in
self?.typingLog?.ui("dictation_stop")
self?.model.onStopTap?()
}
panel.onCancel = { [weak self] in
self?.typingLog?.ui("dictation_cancel")
self?.model.onCancelTap?()
}
panel.onCycleStyle = { [weak self] in
guard let self else { return }
self.typingLog?.ui("style", [
TypingLogField("style", .string(self.model.style.next.rawValue)),
TypingLogField("from", .string("recording_panel")),
])
self.model.onStyleSelected?(self.model.style.next)
}
panel.showsLoggingMark = model.isLoggingTyping
panel.hexOnLeading = engine.layout.hexOnLeading
insertSubview(panel, belowSubview: callout)
recordingPanel = panel
setNeedsLayout()
return panel
}
private func engineChanged() {
plane.setNeedsDisplay()
updateCallout()
refreshStrip()
if globeButton.isHidden != (engine.layout.key(.globe) == nil) || hexKey.frame != engine.layout.key(.hex)?.hitFrame {
setNeedsLayout()
}
}
private func updateCallout() {
if let menu = engine.activeAccentMenu {
endCalloutLinger()
callout.show(nil, label: "")
accentCallout.show(menu)
return
}
accentCallout.show(nil)
let layout = engine.layout
if engine.showsKeyPopups, let key = engine.previewKey, let balloon = layout.balloon(for: key) {
endCalloutLinger()
let label = KeyboardKeyPlaneView.keycapLabel(engine.displayLabel(for: key))
callout.show(balloon, label: label, style: KeyCalloutView.style(for: label))
shownPreviewKind = key.kind
} else if let kind = shownPreviewKind, calloutLingerWork == nil, engine.touches.isEmpty {
// The finger lifted: Apple's pop-up and its grey key stay up 3 frames more (about
// 50 ms after the letter lands, iOS 27.2 at 60 fps), then go in one frame.
plane.lingeringKind = kind
let work = DispatchWorkItem { [weak self] in self?.endCalloutLinger() }
calloutLingerWork = work
DispatchQueue.main.asyncAfter(deadline: .now() + KeyCalloutView.linger, execute: work)
} else if calloutLingerWork == nil {
shownPreviewKind = nil
callout.show(nil, label: "")
}
}
/// The key whose pop-up is up, or lingering after the finger lifted.
private var shownPreviewKind: KeyKind?
private var calloutLingerWork: DispatchWorkItem?
private func endCalloutLinger() {
calloutLingerWork?.cancel()
calloutLingerWork = nil
guard plane.lingeringKind != nil || shownPreviewKind != nil else { return }
plane.lingeringKind = nil
if engine.previewKey == nil {
shownPreviewKind = nil
callout.show(nil, label: "")
}
}
// MARK: - Actions
func keyFeedback() {
if allowsHaptics() {
keyTicks.impactOccurred(intensity: Self.keyTickIntensity(hapticStrength))
keyTicks.prepare()
}
UIDevice.current.playInputClick()
}
func selectionFeedback() {
if allowsHaptics() {
selectionHaptics.selectionChanged()
selectionHaptics.prepare()
}
}
/// A tap or still hold on the Hex key.
private func hexKeyHeld() {
if allowsHaptics() { haptics.impactOccurred() }
dismissStyleMenu()
guard model.hasFullAccess else {
// Dictation needs Full Access (the microphone and Hex's App Group): say so,
// instead of a dictation that can't start.
dictatingFromHexKey = false
showFullAccessHint()
return
}
if hexKey.isWarm {
typingLog?.ui("hex_key", [TypingLogField("dictation", .string("warm"))])
dictatingFromHexKey = true
model.onDictateTap?()
} else if let local = model.onLocalDictateTap {
typingLog?.ui("hex_key", [TypingLogField("dictation", .string("keyboard"))])
dictatingFromHexKey = true
local()
} else {
typingLog?.ui("hex_key", [TypingLogField("dictation", .string("open_hex"))])
dictatingFromHexKey = false
model.onOpenURL?(model.coldStartURL)
}
}
/// Push to talk: lifting the finger after a hold finishes the dictation the hold started,
/// as Done does. A hold that opened Hex has nothing to finish here.
private func hexKeyReleased() {
guard dictatingFromHexKey else { return }
dictatingFromHexKey = false
typingLog?.ui("dictation_stop", [TypingLogField("from", .string("hex_key_release"))])
model.onStopTap?()
}
/// Hold and slide: light the row under the finger, and pick it on release.
private func forwardMenuPoint(_ point: CGPoint, release: Bool) {
guard let menu = styleMenu else { return }
let local = hexKey.convert(point, to: menu)
if release {
menu.finishDrag(at: local)
} else {
menu.updateDrag(at: local)
}
}
private func showStyleMenu() {
guard styleMenu == nil, !showsRecording else { return }
if allowsHaptics() {
haptics.impactOccurred()
haptics.prepare()
}
plane.cancelAllTouches()
let menu = HexStyleMenuView()
menu.palette = palette
menu.style = model.style
applyLanguages(to: menu)
menu.onHoverChanged = { [weak self] in self?.selectionFeedback() }
menu.onLanguage = { [weak self] language in
self?.typingLog?.ui("dictation_language", [TypingLogField("language", .string(language ?? "automatic"))])
self?.model.onLanguageSelected?(language)
self?.dismissStyleMenu()
}
menu.onTranslationToggle = { [weak self] on in
self?.typingLog?.ui("translate", [TypingLogField("on", .bool(on))])
self?.model.onTranslationToggled?(on)
self?.dismissStyleMenu()
}
menu.onTranslationTarget = { [weak self] target in
self?.typingLog?.ui("translate", [TypingLogField("target", .string(target))])
self?.model.onTranslationTargetSelected?(target)
self?.dismissStyleMenu()
}
menu.onStyle = { [weak self] style in
self?.typingLog?.ui("style", [
TypingLogField("style", .string(style.rawValue)),
TypingLogField("from", .string("hex_menu")),
])
self?.model.onStyleSelected?(style)
self?.dismissStyleMenu()
}
menu.onDismiss = { [weak self] in self?.dismissStyleMenu() }
addSubview(menu)
styleMenu = menu
setNeedsLayout()
layoutIfNeeded()
}
func dismissStyleMenu() {
styleMenu?.removeFromSuperview()
styleMenu = nil
}
/// Fixtures: open the menu without a long press, optionally on another page.
func debugShowStyleMenu(page: HexStyleMenuView.Page = .styles) {
showStyleMenu()
styleMenu?.show(page: page)
}
private func undoDictation() {
guard let text = lastDictation else { return }
let before = engine.target.documentContextBeforeInput ?? ""
// Only take back text that is still right before the cursor.
if before.hasSuffix(text) || (!before.isEmpty && before.count < text.count && text.hasSuffix(before)) {
// The host may show only the end of it; replay removes what the keys remove.
typingLog?.edit("undo_dictation", before.hasSuffix(text)
? [TypingLogField("deleted", .string(text))]
: [TypingLogField("deletedCount", .int(text.count))])
for _ in 0..<text.count {
engine.target.deleteBackward()
}
onUndoDictation?()
} else {
typingLog?.ui("undo_dictation", [TypingLogField("applied", .bool(false))])
}
hideUndo()
engine.textDidChange()
typingLog?.context("undo_dictation")
refreshReturnKey()
}
private func hideUndo() {
undoHideWork?.cancel()
undoHideWork = nil
if lastDictation != nil {
lastDictation = nil
refreshStrip()
}
}
private func configureGlobe() {
globeButton.removeTarget(nil, action: nil, for: .allEvents)
if let controller = hostController {
globeButton.addTarget(
controller,
action: #selector(UIInputViewController.handleInputModeList(from:with:)),
for: .allTouchEvents
)
}
}
}