mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
* 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.
1040 lines
49 KiB
Swift
1040 lines
49 KiB
Swift
import CoreGraphics
|
||
|
||
nonisolated enum KeyboardLayer: Equatable, Hashable, Sendable {
|
||
case letters
|
||
case numbers
|
||
case symbols
|
||
}
|
||
|
||
/// The kind of text field, as far as the key rows care.
|
||
nonisolated enum KeyboardFieldKind: Equatable, Sendable {
|
||
case text
|
||
/// Adds `.` and `/` right of space.
|
||
case url
|
||
/// Adds `@` and `.` right of space, matching Apple's iOS 26 email layout.
|
||
case email
|
||
}
|
||
|
||
nonisolated enum KeyboardOrientation: Equatable, Sendable {
|
||
case portrait
|
||
case landscape
|
||
}
|
||
|
||
nonisolated enum KeyKind: Equatable, Hashable, Sendable {
|
||
/// Inserts its text (letters are stored lowercase; shift decides the case).
|
||
case character(String)
|
||
case shift
|
||
case layerSwitch(KeyboardLayer)
|
||
case delete
|
||
case space
|
||
case returnKey
|
||
case hex
|
||
case globe
|
||
/// Opens the emoji panel (Settings › Keyboard › Emoji).
|
||
case emoji
|
||
}
|
||
|
||
nonisolated struct KeyboardKey: Equatable, Sendable {
|
||
let kind: KeyKind
|
||
let row: Int
|
||
/// The drawn keycap.
|
||
let frame: CGRect
|
||
/// The touch target. Hit frames tile the whole key area with no gaps.
|
||
var hitFrame: CGRect
|
||
let label: String
|
||
|
||
var character: String? {
|
||
if case .character(let text) = kind { return text }
|
||
return nil
|
||
}
|
||
}
|
||
|
||
/// The pop-up balloon over a pressed key: a wider bubble joined to the key by a neck.
|
||
nonisolated struct KeyBalloon: Equatable, Sendable {
|
||
/// iOS 27's key pop-up is a bubble floating over the key, not joined to it: 23.3 pt wider
|
||
/// than the key, 65 pt tall, its bottom 3.5 pt above the key's top (iPhone 17e and 17 Pro
|
||
/// simulators). Hex drew iOS 26's balloon, a 46 pt bubble on a stem that hid the key.
|
||
static let bubbleHeight: CGFloat = 65
|
||
/// The gap between the bubble and the key below it.
|
||
static let neck: CGFloat = 3.5
|
||
static let extraWidth: CGFloat = 23.33
|
||
/// Apple's bubble over row 1 rises above the keyboard; a keyboard extension can't draw
|
||
/// outside its view, so there Hex's shrinks to the room it has, down to this, and overlaps
|
||
/// the key below that.
|
||
static let minimumBubbleHeight: CGFloat = 50
|
||
|
||
let keyFrame: CGRect
|
||
let bubble: CGRect
|
||
|
||
/// Bubble centre minus key centre; nonzero when an edge key's bubble is pushed inward.
|
||
var offsetX: CGFloat { bubble.midX - keyFrame.midX }
|
||
/// The balloon's whole outline, bubble through key.
|
||
var bounds: CGRect { bubble.union(keyFrame) }
|
||
}
|
||
|
||
/// Which of Apple's iPhone key planes a screen gets (`KeyboardMetrics.phonePortrait`), by its
|
||
/// height in points: Apple's keycaps and rows differ with it (iOS 27.2).
|
||
nonisolated enum KeyboardPhoneSize: Equatable, Sendable {
|
||
/// A Home-button iPhone (the SE, 667 pt).
|
||
case homeButton
|
||
/// 844 to 874 pt (the 17e, 16, 17 and 17 Pro), and anything else under 900 pt.
|
||
case regular
|
||
/// 900 pt and taller (the Air, the Plus and Pro Max sizes).
|
||
case large
|
||
|
||
static func current(screenSize: CGSize) -> KeyboardPhoneSize {
|
||
let tall = max(screenSize.width, screenSize.height)
|
||
if tall < 700 { return .homeButton }
|
||
return tall < 900 ? .regular : .large
|
||
}
|
||
}
|
||
|
||
/// Where the keyboard is shown. Every iPhone is `.phone`; the iPhone Duo (a foldable) sets
|
||
/// third-party keyboards in an inset platter, with iOS's own band above them, and Apple sizes
|
||
/// its keys there for each screen.
|
||
nonisolated enum KeyboardPosture: Equatable, Sendable {
|
||
case phone
|
||
/// The Duo folded: its 466 × 678 pt cover screen, either way up.
|
||
case cover
|
||
/// The Duo unfolded and held upright: the inner screen is wider than tall (951 × 669 pt).
|
||
case unfoldedWide
|
||
/// The Duo unfolded and turned: the inner screen is taller than wide (669 × 951 pt).
|
||
case unfoldedTall
|
||
|
||
/// The Duo's model identifier (the simulator's too).
|
||
static let foldableModels: Set<String> = ["iPhone19,4"]
|
||
|
||
/// The posture for a screen of `screenSize` points (as it is turned now), on a foldable or not.
|
||
static func current(screenSize: CGSize, isFoldable: Bool) -> KeyboardPosture {
|
||
guard isFoldable else { return .phone }
|
||
guard min(screenSize.width, screenSize.height) >= 600 else { return .cover }
|
||
return screenSize.width > screenSize.height ? .unfoldedWide : .unfoldedTall
|
||
}
|
||
|
||
/// Apple splits its keyboard on the Duo unfolded and held upright (the inner screen wider
|
||
/// than tall); Hex does too, automatically, as there's no setting a keyboard can read.
|
||
var splitsKeyboard: Bool { self == .unfoldedWide }
|
||
|
||
/// iOS draws a band of its own above a third-party keyboard here, so the strip needs no gap
|
||
/// under it to sit as far above the keys as Apple's predictive bar does.
|
||
var hasSystemBand: Bool { self != .phone }
|
||
|
||
/// How far in from the screen's side Apple's keycaps start on the Duo; nil on an iPhone,
|
||
/// where the keyboard has the whole width. Measured in the iOS 27.2 simulator.
|
||
var appleKeyInset: CGFloat? {
|
||
switch self {
|
||
case .phone: nil
|
||
// Folded: 6.67 pt in, a third of a point outside the 452 pt view iOS gives a third-party
|
||
// keyboard, so Hex's keys run to the view's edges (`KeyboardMetrics.for`).
|
||
case .cover: 6.67
|
||
case .unfoldedWide: 86
|
||
case .unfoldedTall: 19
|
||
}
|
||
}
|
||
}
|
||
|
||
nonisolated struct KeyboardMetrics: Equatable, Sendable {
|
||
let side: CGFloat
|
||
let gap: CGFloat
|
||
let rowGap: CGFloat
|
||
let keyHeight: CGFloat
|
||
let stripTop: CGFloat
|
||
let stripHeight: CGFloat
|
||
let stripBottom: CGFloat
|
||
let keysTop: CGFloat
|
||
let keysBottom: CGFloat
|
||
let cornerRadius: CGFloat
|
||
/// How much shorter row 4's keycaps are than the others: where Apple's row 4 reaches
|
||
/// below the bottom of a third-party keyboard's view, Hex's keeps Apple's top edge.
|
||
var bottomRowTrim: CGFloat = 0
|
||
/// Row 4 on the letter columns, as Apple's is turned and on the Duo folded: 123, the globe
|
||
/// and emoji one key wide on row 1's columns from q, space after them, and return from this
|
||
/// many letter pitches in (8, o's column, turned; 8.5, row 2's l column, on the Duo, where
|
||
/// Apple's dictation key sits on m before it). nil: the iPhone's portrait row.
|
||
var bottomRowReturnColumn: CGFloat?
|
||
/// Shift and delete (and #+=, 123 on row 3) as a share of a letter's width, where it isn't
|
||
/// the portrait rule (`KeyboardLayout.modifierWidth`): 1.33 turned, as Apple's on every iPhone.
|
||
var modifierLetterRatio: CGFloat?
|
||
|
||
/// The suggestion strip is the part of Apple's predictive bar below the band iOS 26 draws
|
||
/// over every third-party keyboard (16.3 pt on the iPhone 17 Pro, 12.5 pt on the SE, 13.3 pt
|
||
/// on the 17 Pro Max, iOS 27.2; nothing can draw there). Apple's bar is 44 pt from the
|
||
/// panel's edge, then about 8 pt to row 1's keycaps, which start 51.7, 48 and 48.3 pt down:
|
||
/// 35.3, 35.5 and 35 pt below this view's top on those iPhones. So the strip is 27 pt, then
|
||
/// the same 8 pt gap, and row 1 starts 35 pt down. Everything the strip shows (suggestions,
|
||
/// Undo dictation, the Full Access hint, the recording bar, the emoji panel's top row, the
|
||
/// Logging mark) lives in those 27 pt.
|
||
static let stripBarHeight: CGFloat = 27
|
||
static let stripGap: CGFloat = 8
|
||
/// On the iPhone Duo iOS sets the keyboard in a platter with its own band above, and the
|
||
/// strip is Apple's whole 44 pt bar, right on the keys.
|
||
static let insetStripHeight: CGFloat = 44
|
||
/// The Duo folded and upright: iOS's band there is 8.7 pt and Apple's keycaps start 48.7 pt
|
||
/// below the panel's edge (iOS 27.2), so the strip is 32 pt with the iPhone's 8 pt gap.
|
||
static let coverStripHeight: CGFloat = 32
|
||
|
||
/// How far the strip's pills (an autocorrection, a pressed suggestion, the Hex key, the
|
||
/// recording bar) sit in from its top and bottom: Apple's pill fills its bar but the
|
||
/// edge band iOS draws, so in the 27 pt strip half a point, in the Duo's 44 pt bar 4 pt.
|
||
var stripInset: CGFloat { (stripHeight - stripPillHeight) / 2 }
|
||
/// The pills' height: the strip less half a point above and below, at most 36 pt (26 pt in
|
||
/// the phone's portrait strip, 36 pt in landscape and in the Duo's 44 pt bar).
|
||
var stripPillHeight: CGFloat { min(stripHeight - 1, 36) }
|
||
|
||
/// Apple's keycap corners (iOS 27.2: the same on every iPhone, measured from screenshots
|
||
/// against keys Hex drew at known radii).
|
||
static let keyCornerRadius: CGFloat = 7.9
|
||
|
||
/// iPhone portrait key geometry, as Apple's keyboard draws it beside Hex in the same field
|
||
/// (iOS 27.2) on an 844 to 874 pt iPhone (17e, 17, 17 Pro): 43 pt keycaps on a 54 pt row
|
||
/// pitch, row 1 on the same line on screen. Apple's row 4 ends 4 pt below where a
|
||
/// third-party keyboard's view ends, so Hex's row 4 keeps Apple's top edge and is 4 pt
|
||
/// shorter: 35 pt + 201 pt of keys (4 × 43 pt + 3 × 11 pt − 4 pt) = 236 pt. Hex drew iOS 26's
|
||
/// 45 pt keys on a 56 pt pitch with 5 pt under them, 11 to 17 pt above Apple's rows, so
|
||
/// fingers used to Apple's keyboard landed low on Hex's keys.
|
||
static let portrait = KeyboardMetrics(
|
||
side: 6.5, gap: 6, rowGap: 11, keyHeight: 43,
|
||
stripTop: 0, stripHeight: stripBarHeight, stripBottom: stripGap,
|
||
keysTop: 0, keysBottom: 0, cornerRadius: keyCornerRadius, bottomRowTrim: 4
|
||
)
|
||
|
||
/// Turned, iOS draws no band above the keyboard (iPhone 17 Pro Max, iOS 27.2): Apple's keycaps
|
||
/// start 50 pt below the panel's edge, so the strip is 42 pt and the same gap.
|
||
static let landscapeStripHeight: CGFloat = 42
|
||
|
||
/// The other iPhones' key planes (`KeyboardPhoneSize`), measured the same way: a Home-button
|
||
/// iPhone (SE) has 42 pt keycaps on a 54 pt pitch and 4 pt under row 4; one 900 pt or taller
|
||
/// (Air, Pro Max) 45 pt keycaps on a 56 pt pitch and 7 pt under row 4.
|
||
static func phonePortrait(_ size: KeyboardPhoneSize) -> KeyboardMetrics {
|
||
switch size {
|
||
case .regular:
|
||
return .portrait
|
||
case .homeButton:
|
||
return KeyboardMetrics(
|
||
side: 6.5, gap: 6, rowGap: 12, keyHeight: 42,
|
||
stripTop: 0, stripHeight: stripBarHeight, stripBottom: stripGap,
|
||
keysTop: 0, keysBottom: 4, cornerRadius: keyCornerRadius
|
||
)
|
||
case .large:
|
||
return KeyboardMetrics(
|
||
side: 6.5, gap: 6, rowGap: 11, keyHeight: 45,
|
||
stripTop: 0, stripHeight: stripBarHeight, stripBottom: stripGap,
|
||
keysTop: 0, keysBottom: 7, cornerRadius: keyCornerRadius
|
||
)
|
||
}
|
||
}
|
||
|
||
/// Turned, Apple's keys are the same on every iPhone (17e, 17 Pro, Air, 17 Pro Max and SE,
|
||
/// iOS 27.2, beside Hex in the same field): 32 pt keycaps on a 40 pt pitch, row 4 ending
|
||
/// 2 pt above the bottom of a third-party keyboard's view, 7.9 pt corners, and row 4 on the
|
||
/// letter columns. Under the strip: 50 pt + 154 pt of keys (4 × 32 pt + 3 × 8 pt + 2 pt) =
|
||
/// 204 pt. Hex drew iOS 26's 27.5 pt keys on a 35.5 pt pitch, 187 pt in all, every row
|
||
/// 2 to 17 pt below Apple's.
|
||
static let landscape = KeyboardMetrics(
|
||
side: 4, gap: 6, rowGap: 8, keyHeight: 32,
|
||
stripTop: 0, stripHeight: landscapeStripHeight, stripBottom: stripGap,
|
||
keysTop: 0, keysBottom: 2, cornerRadius: keyCornerRadius, bottomRowReturnColumn: 8,
|
||
modifierLetterRatio: 1.33
|
||
)
|
||
|
||
/// Turned, a Home-button iPhone (the SE) sets Apple's keys 72 pt in from each side, 47 pt
|
||
/// wide, with 4 pt under row 4; Hex's ran to 4 pt from the edges, 60.5 pt wide.
|
||
static let homeButtonLandscape: KeyboardMetrics = {
|
||
var m = landscape.with(side: 72)
|
||
m = KeyboardMetrics(
|
||
side: m.side, gap: m.gap, rowGap: m.rowGap, keyHeight: m.keyHeight,
|
||
stripTop: m.stripTop, stripHeight: m.stripHeight, stripBottom: m.stripBottom,
|
||
keysTop: m.keysTop, keysBottom: 4, cornerRadius: m.cornerRadius,
|
||
bottomRowReturnColumn: m.bottomRowReturnColumn, modifierLetterRatio: m.modifierLetterRatio
|
||
)
|
||
return m
|
||
}()
|
||
|
||
/// `windowInset` is how far iOS set the keyboard in from each side of the screen (the Duo).
|
||
static func `for`(
|
||
_ orientation: KeyboardOrientation,
|
||
innerWidth: CGFloat? = nil,
|
||
posture: KeyboardPosture = .phone,
|
||
windowInset: CGFloat = 0,
|
||
phoneSize: KeyboardPhoneSize = .regular
|
||
) -> KeyboardMetrics {
|
||
let base: KeyboardMetrics
|
||
if orientation == .landscape {
|
||
base = posture == .phone && phoneSize == .homeButton ? .homeButtonLandscape : .landscape
|
||
} else if posture == .phone {
|
||
let phone = phonePortrait(phoneSize)
|
||
// Apple's keys start 6.5 pt in on every iPhone from the SE's 375 pt up.
|
||
let side: CGFloat = (innerWidth ?? 402) >= 370 ? 6.5 : 3.0
|
||
base = side == phone.side ? phone : phone.with(side: side)
|
||
} else {
|
||
base = .portrait
|
||
}
|
||
guard posture != .phone else { return base }
|
||
|
||
// The Duo: Apple's row pitch for each screen (56 pt folded, 59.7 pt unfolded and turned,
|
||
// 51.7 pt unfolded upright), keycaps starting where Apple's do, and no gap under the strip.
|
||
var keyHeight = base.keyHeight
|
||
var rowGap = base.rowGap
|
||
if orientation == .portrait {
|
||
switch posture {
|
||
case .unfoldedTall:
|
||
keyHeight = 46
|
||
rowGap = 13.7
|
||
case .unfoldedWide:
|
||
keyHeight = 39
|
||
rowGap = 12.7
|
||
case .cover:
|
||
keyHeight = 45
|
||
rowGap = 11
|
||
case .phone:
|
||
break
|
||
}
|
||
}
|
||
let side = orientation == .portrait
|
||
? max(0, (posture.appleKeyInset ?? base.side) - windowInset)
|
||
: base.side
|
||
// Measured folded and upright only; unfolded, and folded in landscape, the strip is still
|
||
// Apple's whole bar right on the keys. Folded and upright (iOS 27.2 simulator, beside
|
||
// Apple's keyboard) Apple's row 4 ends 7 pt above the keyboard's bottom and its keycaps
|
||
// round 9.8 pt; Hex drew 5 pt and 7.9 pt, its rows 2 pt low. Unfolded keeps the 5 pt
|
||
// under row 4 it was measured with.
|
||
let coverPortrait = posture == .cover && orientation == .portrait
|
||
return KeyboardMetrics(
|
||
side: side, gap: base.gap, rowGap: rowGap, keyHeight: keyHeight,
|
||
stripTop: base.stripTop,
|
||
stripHeight: coverPortrait ? coverStripHeight : insetStripHeight,
|
||
stripBottom: coverPortrait ? stripGap : 0,
|
||
keysTop: base.keysTop,
|
||
keysBottom: coverPortrait ? 7 : orientation == .portrait ? 5 : base.keysBottom,
|
||
cornerRadius: coverPortrait ? 9.8 : base.cornerRadius,
|
||
bottomRowReturnColumn: coverPortrait ? 8.5 : base.bottomRowReturnColumn,
|
||
modifierLetterRatio: base.modifierLetterRatio
|
||
)
|
||
}
|
||
|
||
private func with(side: CGFloat) -> KeyboardMetrics {
|
||
KeyboardMetrics(
|
||
side: side, gap: gap, rowGap: rowGap, keyHeight: keyHeight,
|
||
stripTop: stripTop, stripHeight: stripHeight, stripBottom: stripBottom,
|
||
keysTop: keysTop, keysBottom: keysBottom, cornerRadius: cornerRadius,
|
||
bottomRowTrim: bottomRowTrim, bottomRowReturnColumn: bottomRowReturnColumn,
|
||
modifierLetterRatio: modifierLetterRatio
|
||
)
|
||
}
|
||
|
||
var stripArea: CGFloat { stripTop + stripHeight + stripBottom }
|
||
/// Row 4's keycap height.
|
||
var bottomRowHeight: CGFloat { keyHeight - bottomRowTrim }
|
||
var keysArea: CGFloat { keysTop + 4 * keyHeight + 3 * rowGap + keysBottom - bottomRowTrim }
|
||
var totalHeight: CGFloat { stripArea + keysArea }
|
||
}
|
||
|
||
/// Pure geometry of the full keyboard: every key's frame and touch target for one width,
|
||
/// layer and field kind. Coordinates are in the keyboard view, strip included.
|
||
/// Where the full keyboard's Hex key sits. The strip's trailing edge keeps a full-width
|
||
/// space bar and gives the recording animation a starting point.
|
||
nonisolated enum HexKeyPlacement: String, CaseIterable, Sendable {
|
||
case rightOfSpace
|
||
case leftOfSpace
|
||
case stripLeading
|
||
case stripTrailing
|
||
|
||
/// The keyboard's, for typing logs: `FullKeyboardView` keeps Settings › Keyboard › Hex key
|
||
/// (`FullKeyboardSettings.hexKeyPlacement`) here; layouts take theirs as a parameter. The
|
||
/// snapshot stage's `--hex-placement` can render the others for comparison.
|
||
nonisolated(unsafe) static var current: HexKeyPlacement = .stripTrailing
|
||
|
||
var isInStrip: Bool { self == .stripLeading || self == .stripTrailing }
|
||
}
|
||
|
||
nonisolated struct KeyboardLayout: Equatable, Sendable {
|
||
/// Shift, delete, #+= and 123 on row 3 (and the Duo's globe and emoji keys) from the letter
|
||
/// pitch: Apple's are 1.227 pitches less 3 pt on every iPhone (45.5 pt on the 17 Pro's
|
||
/// 39.5 pt pitch, 50.2 on the Pro Max's 43.3, 42 on the SE's 36.8; iOS 27.2). A fixed
|
||
/// 1.34 letters was half a point narrow on the 17 Pro.
|
||
static func modifierWidth(letterWidth: CGFloat, gap: CGFloat, metrics: KeyboardMetrics? = nil) -> CGFloat {
|
||
if let ratio = metrics?.modifierLetterRatio { return ratio * letterWidth }
|
||
return 1.227 * (letterWidth + gap) - 3
|
||
}
|
||
|
||
/// Row 3's modifier width in this layout (`modifierWidth(letterWidth:gap:)`).
|
||
var modifierWidth: CGFloat { Self.modifierWidth(letterWidth: letterWidth, gap: metrics.gap, metrics: metrics) }
|
||
static let bottomSwitchWidthRatio: CGFloat = 1.56
|
||
static let returnWidthRatio: CGFloat = 2.40
|
||
static let compactReturnWidthRatio: CGFloat = 2.18
|
||
|
||
let width: CGFloat
|
||
let orientation: KeyboardOrientation
|
||
let layer: KeyboardLayer
|
||
let field: KeyboardFieldKind
|
||
let showsGlobe: Bool
|
||
let showsEmoji: Bool
|
||
let horizontalInset: CGFloat
|
||
let language: KeyboardLanguage
|
||
/// The letters' arrangement (Settings › Keyboard › Languages › Layout): `language`'s own
|
||
/// unless it offers the one asked for.
|
||
let letters: KeyboardLetterLayout
|
||
let posture: KeyboardPosture
|
||
/// Where the Hex key sits: Settings › Keyboard › Hex key picks the strip's trailing
|
||
/// (Right) or leading (Left) end.
|
||
let hexPlacement: HexKeyPlacement
|
||
let metrics: KeyboardMetrics
|
||
let keys: [KeyboardKey]
|
||
/// The two halves' inner edges while the keyboard is split (the Duo unfolded upright, as
|
||
/// Apple's is there); nil otherwise.
|
||
let split: SplitGeometry?
|
||
|
||
init(
|
||
width: CGFloat,
|
||
orientation: KeyboardOrientation = .portrait,
|
||
layer: KeyboardLayer = .letters,
|
||
field: KeyboardFieldKind = .text,
|
||
showsGlobe: Bool = false,
|
||
showsEmoji: Bool = false,
|
||
horizontalInset: CGFloat = 0,
|
||
language: KeyboardLanguage = .english,
|
||
letters: KeyboardLetterLayout? = nil,
|
||
posture: KeyboardPosture = .phone,
|
||
windowInset: CGFloat = 0,
|
||
hexPlacement: HexKeyPlacement = .stripTrailing,
|
||
phoneSize: KeyboardPhoneSize = .regular
|
||
) {
|
||
self.width = width
|
||
let letters = language.offered(letters)
|
||
self.letters = letters
|
||
self.hexPlacement = hexPlacement
|
||
self.orientation = orientation
|
||
self.layer = layer
|
||
self.field = field
|
||
self.showsGlobe = showsGlobe
|
||
self.showsEmoji = showsEmoji
|
||
self.horizontalInset = max(0, horizontalInset)
|
||
self.language = language
|
||
self.posture = posture
|
||
let innerWidth = width - 2 * self.horizontalInset
|
||
let metrics = KeyboardMetrics.for(
|
||
orientation, innerWidth: innerWidth, posture: posture, windowInset: windowInset, phoneSize: phoneSize
|
||
)
|
||
self.metrics = metrics
|
||
if posture.splitsKeyboard, orientation == .portrait {
|
||
let built = Self.buildSplitKeys(
|
||
width: width,
|
||
metrics: metrics,
|
||
layer: layer,
|
||
field: field,
|
||
showsGlobe: showsGlobe,
|
||
showsEmoji: showsEmoji,
|
||
inset: self.horizontalInset,
|
||
language: language,
|
||
letters: letters,
|
||
hexPlacement: hexPlacement
|
||
)
|
||
self.keys = built.keys
|
||
self.split = built.split
|
||
} else {
|
||
self.keys = Self.buildKeys(
|
||
width: width,
|
||
metrics: metrics,
|
||
layer: layer,
|
||
field: field,
|
||
showsGlobe: showsGlobe,
|
||
showsEmoji: showsEmoji,
|
||
inset: self.horizontalInset,
|
||
language: language,
|
||
letters: letters,
|
||
hexPlacement: hexPlacement
|
||
)
|
||
self.split = nil
|
||
}
|
||
}
|
||
|
||
var isSplit: Bool { split != nil }
|
||
|
||
/// The Hex key sits at the strip's leading (left) end, so what grows from it or points at
|
||
/// it (the recording bar's ✕ and ✓, its menu, the Full Access hint's Open Hex) mirrors.
|
||
var hexOnLeading: Bool { hexPlacement == .stripLeading }
|
||
|
||
static func height(
|
||
for orientation: KeyboardOrientation,
|
||
posture: KeyboardPosture = .phone,
|
||
phoneSize: KeyboardPhoneSize = .regular
|
||
) -> CGFloat {
|
||
KeyboardMetrics.for(orientation, posture: posture, phoneSize: phoneSize).totalHeight
|
||
}
|
||
|
||
var totalHeight: CGFloat { metrics.totalHeight }
|
||
|
||
/// Apple's predictive bar here: the strip with the Hex key's room (`stripFrame` leaves it out).
|
||
var stripBarFrame: CGRect {
|
||
var full = CGRect(x: horizontalInset, y: metrics.stripTop, width: width - 2 * horizontalInset, height: metrics.stripHeight)
|
||
if let split {
|
||
if hexOnLeading {
|
||
// Over the left half with the Hex key, for the left thumb, mirroring the right.
|
||
let maxX = split.leftEdge + SplitGeometry.stripLead
|
||
full = CGRect(x: full.minX, y: full.minY, width: maxX - full.minX, height: full.height)
|
||
} else {
|
||
// Over the right half, where Apple's split keyboard puts its predictions.
|
||
let minX = split.rightEdge - SplitGeometry.stripLead
|
||
full = CGRect(x: minX, y: full.minY, width: full.maxX - minX, height: full.height)
|
||
}
|
||
}
|
||
return full
|
||
}
|
||
|
||
/// Where the suggestion / undo strip sits.
|
||
var stripFrame: CGRect {
|
||
let full = stripBarFrame
|
||
guard let hex = key(.hex), hex.row < 0 else { return full }
|
||
let reserved = hex.frame.width + metrics.side + metrics.gap
|
||
return hexOnLeading
|
||
? CGRect(x: full.minX + reserved, y: full.minY, width: full.width - reserved, height: full.height)
|
||
: CGRect(x: full.minX, y: full.minY, width: full.width - reserved, height: full.height)
|
||
}
|
||
|
||
/// The three suggestion slots, in keyboard coordinates: thirds of the bar, as Apple's are
|
||
/// (its dividers sit at a third and two thirds of the keyboard), with the Hex key's room
|
||
/// taken from the slot beside it.
|
||
var stripSlotFrames: [CGRect] {
|
||
let bar = stripBarFrame
|
||
let strip = stripFrame
|
||
let third = bar.width / 3
|
||
return (0..<3).map { index in
|
||
let minX = max(strip.minX, bar.minX + CGFloat(index) * third)
|
||
let maxX = min(strip.maxX, bar.minX + CGFloat(index + 1) * third)
|
||
return CGRect(x: minX, y: strip.minY, width: max(0, maxX - minX), height: strip.height)
|
||
}
|
||
}
|
||
|
||
var keysAreaFrame: CGRect {
|
||
CGRect(x: 0, y: metrics.stripArea, width: width, height: metrics.keysArea)
|
||
}
|
||
|
||
/// Where the strip sits right on the keys (the Duo), its bottom points, below its pills and
|
||
/// chips, belong to row 1's keys: a tap just above a keycap types it rather than picking a
|
||
/// suggestion.
|
||
static let stripTouchBand: CGFloat = 4
|
||
|
||
/// How far above its keycaps row 1 takes touches: the gap under the strip, as Apple's keys
|
||
/// reach about 8 pt above their keycaps to the predictive bar, or `stripTouchBand`.
|
||
var rowOneReach: CGFloat { max(metrics.stripBottom, Self.stripTouchBand) }
|
||
|
||
/// Where touches go to the keys: the key area plus `rowOneReach`. Hit frames tile it.
|
||
var touchAreaFrame: CGRect {
|
||
CGRect(x: 0, y: metrics.stripArea - rowOneReach, width: width, height: metrics.keysArea + rowOneReach)
|
||
}
|
||
|
||
/// A letter key's width on a 10-key row. Shift, delete and the bottom row are sized
|
||
/// from it in every language, as Apple's are.
|
||
var letterWidth: CGFloat {
|
||
if isSplit { return SplitGeometry.keyWidth }
|
||
return Self.letterWidth(innerWidth: width - 2 * horizontalInset, metrics: metrics)
|
||
}
|
||
|
||
/// `x` as it would be with the halves pushed together, so a tap on the right half's G and
|
||
/// one on the left half's land on the same key for Spatial autocorrect.
|
||
func unsplitX(_ x: CGFloat) -> CGFloat {
|
||
guard let split, x >= split.middle else { return x }
|
||
return x - split.shift
|
||
}
|
||
|
||
/// The width of this page's character keys: `letterWidth`, or narrower where a row
|
||
/// holds 11 keys (Norwegian letters).
|
||
var characterWidth: CGFloat {
|
||
if isSplit { return SplitGeometry.keyWidth }
|
||
if layer == .letters, letters == .dvorak {
|
||
return Self.dvorakLetterWidth(innerWidth: width - 2 * horizontalInset, metrics: metrics)
|
||
}
|
||
return Self.letterWidth(
|
||
innerWidth: width - 2 * horizontalInset,
|
||
metrics: metrics,
|
||
columns: Self.columns(Self.characterRows(for: layer, language: language, letters: letters))
|
||
)
|
||
}
|
||
|
||
var showsBalloons: Bool { orientation == .portrait }
|
||
|
||
func key(_ kind: KeyKind) -> KeyboardKey? {
|
||
keys.first { $0.kind == kind }
|
||
}
|
||
|
||
func hitTest(_ point: CGPoint) -> KeyboardKey? {
|
||
keys.first { $0.hitFrame.contains(point) }
|
||
}
|
||
|
||
/// The balloon for a character key, kept inside the keyboard's bounds. `nil` for keys
|
||
/// without one (space, modifiers) and in landscape, where there is no room above row 1.
|
||
func balloon(for key: KeyboardKey) -> KeyBalloon? {
|
||
guard showsBalloons, key.character != nil else { return nil }
|
||
let bubbleWidth = key.frame.width + KeyBalloon.extraWidth
|
||
let room = key.frame.minY - KeyBalloon.neck
|
||
let bubbleHeight = room >= KeyBalloon.bubbleHeight ? KeyBalloon.bubbleHeight : max(KeyBalloon.minimumBubbleHeight, room)
|
||
let bubbleY = max(0, key.frame.minY - KeyBalloon.neck - bubbleHeight)
|
||
// An edge key's bubble is pushed in just far enough to stay on screen, as Apple's is.
|
||
let minX = max(0, horizontalInset)
|
||
let maxX = max(minX, width - horizontalInset - bubbleWidth)
|
||
var x = key.frame.midX - bubbleWidth / 2
|
||
x = max(minX, min(maxX, x))
|
||
let bubble = CGRect(
|
||
x: x,
|
||
y: bubbleY,
|
||
width: bubbleWidth,
|
||
height: bubbleHeight
|
||
)
|
||
return KeyBalloon(keyFrame: key.frame, bubble: bubble)
|
||
}
|
||
|
||
// MARK: - Building
|
||
|
||
static func letterWidth(innerWidth: CGFloat, metrics: KeyboardMetrics, columns: Int = 10) -> CGFloat {
|
||
(innerWidth - 2 * metrics.side - CGFloat(columns - 1) * metrics.gap) / CGFloat(columns)
|
||
}
|
||
|
||
/// Dvorak's letter keys: narrower than a 10-key row's, so shift and nine letters fill row 3
|
||
/// edge to edge, as on Apple's (iOS 27.0 simulator: a 38.3 pt pitch where QWERTY's is 39.5 pt
|
||
/// on a 402 pt iPhone).
|
||
static func dvorakLetterWidth(innerWidth: CGFloat, metrics: KeyboardMetrics) -> CGFloat {
|
||
let modifier = modifierWidth(letterWidth: letterWidth(innerWidth: innerWidth, metrics: metrics), gap: metrics.gap, metrics: metrics)
|
||
return (innerWidth - 2 * metrics.side - modifier) / 9 - metrics.gap
|
||
}
|
||
|
||
/// Keys across the widest of rows 1 and 2, never fewer than 10.
|
||
static func columns(_ rows: [[String]]) -> Int {
|
||
max(10, rows.prefix(2).map(\.count).max() ?? 10)
|
||
}
|
||
|
||
static func characterRows(
|
||
for layer: KeyboardLayer,
|
||
language: KeyboardLanguage = .english,
|
||
letters: KeyboardLetterLayout? = nil
|
||
) -> [[String]] {
|
||
let punctuation = [".", ",", "?", "!", "'"]
|
||
switch layer {
|
||
case .letters:
|
||
return language.letterRows(language.offered(letters))
|
||
case .numbers:
|
||
return [
|
||
"1234567890".map(String.init),
|
||
["-", "/", ":", ";", "(", ")", "$", "&", "@", "\""],
|
||
punctuation,
|
||
]
|
||
case .symbols:
|
||
return [
|
||
["[", "]", "{", "}", "#", "%", "^", "*", "+", "="],
|
||
["_", "\\", "|", "~", "<", ">", "€", "£", "¥", "•"],
|
||
punctuation,
|
||
]
|
||
}
|
||
}
|
||
|
||
private static func buildKeys(
|
||
width: CGFloat,
|
||
metrics m: KeyboardMetrics,
|
||
layer: KeyboardLayer,
|
||
field: KeyboardFieldKind,
|
||
showsGlobe: Bool,
|
||
showsEmoji: Bool,
|
||
inset: CGFloat,
|
||
language: KeyboardLanguage,
|
||
letters: KeyboardLetterLayout,
|
||
hexPlacement placement: HexKeyPlacement
|
||
) -> [KeyboardKey] {
|
||
let innerWidth = width - 2 * inset
|
||
let rows = characterRows(for: layer, language: language, letters: letters)
|
||
let dvorak = layer == .letters && letters == .dvorak
|
||
// Modifiers and the bottom row keep the 10-key sizes; an 11-key layout narrows only
|
||
// its character keys, and row 3's letters sit centred between shift and delete.
|
||
let referenceW = letterWidth(innerWidth: innerWidth, metrics: m)
|
||
let lw = dvorak
|
||
? dvorakLetterWidth(innerWidth: innerWidth, metrics: m)
|
||
: letterWidth(innerWidth: innerWidth, metrics: m, columns: columns(rows))
|
||
let modW = modifierWidth(letterWidth: referenceW, gap: m.gap, metrics: m)
|
||
let left = inset + m.side
|
||
let right = width - inset - m.side
|
||
|
||
func rowY(_ row: Int) -> CGFloat {
|
||
m.stripArea + m.keysTop + CGFloat(row) * (m.keyHeight + m.rowGap)
|
||
}
|
||
|
||
var drawn: [(KeyKind, Int, CGRect, String)] = []
|
||
|
||
func add(_ kind: KeyKind, row: Int, x: CGFloat, w: CGFloat, label: String) {
|
||
let h = row == 3 ? m.bottomRowHeight : m.keyHeight
|
||
drawn.append((kind, row, CGRect(x: x, y: rowY(row), width: w, height: h), label))
|
||
}
|
||
|
||
func addCharacters(_ chars: [String], row: Int, startX: CGFloat, keyWidth: CGFloat) {
|
||
var x = startX
|
||
for ch in chars {
|
||
add(.character(ch), row: row, x: x, w: keyWidth, label: ch)
|
||
x += keyWidth + m.gap
|
||
}
|
||
}
|
||
|
||
func centredStart(count: Int, keyWidth: CGFloat) -> CGFloat {
|
||
let total = CGFloat(count) * keyWidth + CGFloat(count - 1) * m.gap
|
||
return inset + (innerWidth - total) / 2
|
||
}
|
||
|
||
if dvorak {
|
||
// Apple's Dvorak: row 1's seven letters end at a delete key a pitch and a half wide,
|
||
// row 2's ten start at the edge, and row 3 is shift and nine letters, edge to edge.
|
||
let pitch = lw + m.gap
|
||
let deleteW = 1.5 * pitch - m.gap
|
||
add(.delete, row: 0, x: right - deleteW, w: deleteW, label: "delete")
|
||
addCharacters(rows[0], row: 0, startX: right - deleteW - CGFloat(rows[0].count) * pitch, keyWidth: lw)
|
||
addCharacters(rows[1], row: 1, startX: left, keyWidth: lw)
|
||
add(.shift, row: 2, x: left, w: modW, label: "shift")
|
||
addCharacters(rows[2], row: 2, startX: left + modW + m.gap, keyWidth: lw)
|
||
}
|
||
|
||
// Rows 1 and 2.
|
||
for row in 0..<2 where !dvorak {
|
||
let chars = rows[row]
|
||
addCharacters(chars, row: row, startX: centredStart(count: chars.count, keyWidth: lw), keyWidth: lw)
|
||
}
|
||
|
||
// Row 3: shift (or the symbol-page switch), the middle keys, delete. A letter row too
|
||
// long for full-size shift and delete (Russian's nine) narrows them to fit instead, as
|
||
// Apple's Russian keyboard does; every other layout keeps them at `modW`.
|
||
let middle = rows[2]
|
||
let row3ModW = layer == .letters
|
||
? min(modW, (innerWidth - 2 * m.side - CGFloat(middle.count) * lw - CGFloat(middle.count + 1) * m.gap) / 2)
|
||
: modW
|
||
if !dvorak {
|
||
switch layer {
|
||
case .letters:
|
||
add(.shift, row: 2, x: left, w: row3ModW, label: "shift")
|
||
case .numbers:
|
||
add(.layerSwitch(.symbols), row: 2, x: left, w: modW, label: "#+=")
|
||
case .symbols:
|
||
add(.layerSwitch(.numbers), row: 2, x: left, w: modW, label: "123")
|
||
}
|
||
if layer == .letters {
|
||
addCharacters(middle, row: 2, startX: centredStart(count: middle.count, keyWidth: lw), keyWidth: lw)
|
||
} else {
|
||
// Apple's punctuation row: five wide keys aligned to the s..k columns between modifiers.
|
||
let edgeGap = 1.5 * (lw + m.gap) - modW
|
||
let count = CGFloat(middle.count)
|
||
let middleW = (innerWidth - 2 * m.side - 2 * modW - 2 * edgeGap - (count - 1) * m.gap) / count
|
||
addCharacters(middle, row: 2, startX: left + modW + edgeGap, keyWidth: middleW)
|
||
}
|
||
add(.delete, row: 2, x: right - row3ModW, w: row3ModW, label: "delete")
|
||
}
|
||
|
||
// Row 4: 123/ABC, globe?, emoji?, space, field extras (@ . / . /), Hex, return.
|
||
let isCompactBottomRow = showsGlobe || showsEmoji || field != .text
|
||
let switchW = isCompactBottomRow ? modW : referenceW * bottomSwitchWidthRatio
|
||
let returnW = isCompactBottomRow ? (referenceW * compactReturnWidthRatio) : (referenceW * returnWidthRatio + m.gap)
|
||
var leading: [(KeyKind, CGFloat, String)] = [
|
||
layer == .letters
|
||
? (.layerSwitch(.numbers), switchW, "123")
|
||
: (.layerSwitch(.letters), switchW, "ABC"),
|
||
]
|
||
if showsGlobe {
|
||
leading.append((.globe, modW, "globe"))
|
||
}
|
||
if showsEmoji {
|
||
leading.append((.emoji, modW, "emoji"))
|
||
}
|
||
if placement == .leftOfSpace {
|
||
leading.append((.hex, modW, "hex"))
|
||
}
|
||
var trailing: [(KeyKind, CGFloat, String)] = []
|
||
switch field {
|
||
case .text:
|
||
break
|
||
case .url:
|
||
trailing.append((.character("."), referenceW, "."))
|
||
trailing.append((.character("/"), referenceW, "/"))
|
||
case .email:
|
||
trailing.append((.character("@"), referenceW, "@"))
|
||
trailing.append((.character("."), referenceW, "."))
|
||
}
|
||
if placement == .rightOfSpace {
|
||
trailing.append((.hex, modW, "hex"))
|
||
}
|
||
trailing.append((.returnKey, returnW, "return"))
|
||
|
||
if field == .text, let returnColumn = m.bottomRowReturnColumn {
|
||
// Turned, and on the Duo folded: each key before the space bar one letter wide on
|
||
// row 1's columns, space up to return's column (on the Duo, Apple's dictation key
|
||
// sits just before return: Hex has none, so space runs on) and a Hex key right of
|
||
// space one pitch before return.
|
||
let pitch = referenceW + m.gap
|
||
let returnStart = left + returnColumn * pitch
|
||
let kColumn = returnStart - pitch
|
||
var lead: [(KeyKind, String)] = [leading[0].0 == .layerSwitch(.numbers) ? (.layerSwitch(.numbers), "123") : (.layerSwitch(.letters), "ABC")]
|
||
if showsGlobe { lead.append((.globe, "globe")) }
|
||
if showsEmoji { lead.append((.emoji, "emoji")) }
|
||
if placement == .leftOfSpace { lead.append((.hex, "hex")) }
|
||
for (i, (kind, label)) in lead.enumerated() {
|
||
add(kind, row: 3, x: left + CGFloat(i) * pitch, w: referenceW, label: label)
|
||
}
|
||
let spaceStart = left + CGFloat(lead.count) * pitch
|
||
var spaceEnd = returnStart - m.gap
|
||
if placement == .rightOfSpace {
|
||
add(.hex, row: 3, x: kColumn, w: returnStart - m.gap - kColumn, label: "hex")
|
||
spaceEnd = kColumn - m.gap
|
||
}
|
||
add(.space, row: 3, x: spaceStart, w: max(lw, spaceEnd - spaceStart), label: "space")
|
||
add(.returnKey, row: 3, x: returnStart, w: right - returnStart, label: "return")
|
||
} else if field == .text, m.keyHeight >= 40 {
|
||
// Apple's portrait bottom row stands on row 3's letter columns: 123 (and emoji, or
|
||
// the globe on a Home-button iPhone) share the width from the edge to z's right edge,
|
||
// the space bar runs from x to n, and return from m to the edge. With no emoji key
|
||
// (Emoji not among the keyboards), Apple's 123 takes the whole first block. Hex's Hex
|
||
// key, left or right of space, comes out of the space bar.
|
||
let pitch = referenceW + m.gap
|
||
let blockEnd = left + 2.5 * pitch - m.gap
|
||
let returnStart = left + 7.5 * pitch
|
||
var block: [(KeyKind, String)] = [leading[0].0 == .layerSwitch(.numbers) ? (.layerSwitch(.numbers), "123") : (.layerSwitch(.letters), "ABC")]
|
||
if showsGlobe { block.append((.globe, "globe")) }
|
||
// Beside the globe, the emoji key takes x's column, where Apple's dictation key is.
|
||
let emojiInColumn = showsEmoji && showsGlobe
|
||
if showsEmoji, !emojiInColumn { block.append((.emoji, "emoji")) }
|
||
let blockW = (blockEnd - left - CGFloat(block.count - 1) * m.gap) / CGFloat(block.count)
|
||
var x = left
|
||
for (kind, label) in block {
|
||
add(kind, row: 3, x: x, w: blockW, label: label)
|
||
x += blockW + m.gap
|
||
}
|
||
if emojiInColumn {
|
||
add(.emoji, row: 3, x: x, w: referenceW, label: "emoji")
|
||
x += referenceW + m.gap
|
||
}
|
||
var spaceEnd = returnStart - m.gap
|
||
if placement == .leftOfSpace {
|
||
add(.hex, row: 3, x: x, w: modW, label: "hex")
|
||
x += modW + m.gap
|
||
}
|
||
if placement == .rightOfSpace {
|
||
add(.hex, row: 3, x: spaceEnd - modW, w: modW, label: "hex")
|
||
spaceEnd -= modW + m.gap
|
||
}
|
||
add(.space, row: 3, x: x, w: max(lw, spaceEnd - x), label: "space")
|
||
add(.returnKey, row: 3, x: returnStart, w: right - returnStart, label: "return")
|
||
} else {
|
||
let fixed = (leading + trailing).reduce(0) { $0 + $1.1 }
|
||
let itemCount = CGFloat(leading.count + trailing.count + 1)
|
||
let spaceW = max(lw, (right - left) - fixed - (itemCount - 1) * m.gap)
|
||
var x = left
|
||
for (kind, w, label) in leading {
|
||
add(kind, row: 3, x: x, w: w, label: label)
|
||
x += w + m.gap
|
||
}
|
||
add(.space, row: 3, x: x, w: spaceW, label: "space")
|
||
x += spaceW + m.gap
|
||
for (kind, w, label) in trailing {
|
||
add(kind, row: 3, x: x, w: w, label: label)
|
||
x += w + m.gap
|
||
}
|
||
}
|
||
|
||
// Touch targets: split every gap down the middle; outer keys reach the edges, and row 1
|
||
// the gap under the strip (or the strip's bottom band).
|
||
let top = m.stripArea - max(m.stripBottom, stripTouchBand)
|
||
let bottom = m.totalHeight
|
||
var keys: [KeyboardKey] = []
|
||
for row in 0..<4 {
|
||
let rowKeys = drawn.filter { $0.1 == row }.sorted { $0.2.minX < $1.2.minX }
|
||
let y0 = row == 0 ? top : rowY(row) - m.rowGap / 2
|
||
let y1 = row == 3 ? bottom : rowY(row + 1) - m.rowGap / 2
|
||
for (i, item) in rowKeys.enumerated() {
|
||
let x0 = i == 0 ? 0 : (rowKeys[i - 1].2.maxX + item.2.minX) / 2
|
||
let x1 = i == rowKeys.count - 1 ? width : (item.2.maxX + rowKeys[i + 1].2.minX) / 2
|
||
var hit = CGRect(x: x0, y: y0, width: x1 - x0, height: y1 - y0)
|
||
if item.0 == .emoji, row == 3, m.keyHeight >= 40 {
|
||
// Apple's emoji key takes taps only well inside its keycap, 6 pt in from each
|
||
// side and 7.5 pt below its top, and the margins around it type nothing:
|
||
// a finger aimed at 123 or space that lands near it doesn't switch keyboards.
|
||
hit = CGRect(x: item.2.minX + 6, y: item.2.minY + 7.5, width: item.2.width - 12, height: y1 - item.2.minY - 7.5)
|
||
}
|
||
keys.append(KeyboardKey(
|
||
kind: item.0,
|
||
row: row,
|
||
frame: item.2,
|
||
hitFrame: hit,
|
||
label: item.3
|
||
))
|
||
}
|
||
}
|
||
if placement.isInStrip {
|
||
// A bare mark in a target wider than tall, inset like the suggestion pills.
|
||
let height = m.stripPillHeight
|
||
let width: CGFloat = 44
|
||
let x = placement == .stripLeading ? left : right - width
|
||
let frame = CGRect(x: x, y: m.stripTop + m.stripInset, width: width, height: height)
|
||
let target = frame.insetBy(dx: -4, dy: -4)
|
||
let hitFrame = CGRect(x: target.minX, y: target.minY, width: target.width, height: top - target.minY)
|
||
keys.append(KeyboardKey(kind: .hex, row: -1, frame: frame, hitFrame: hitFrame, label: "hex"))
|
||
}
|
||
return keys
|
||
}
|
||
}
|
||
|
||
/// Where a split keyboard's halves end. Apple's split keyboard on the Duo unfolded upright
|
||
/// (iOS 27.2 simulator, 801 pt keyboard): 46.3 pt keycaps on a 57 pt pitch, shift and delete
|
||
/// 63.3 pt, 123 66.7 pt, globe and emoji 40.7 pt, return 66 pt; each half starts at the
|
||
/// keyboard's side, the middle (about 220 pt) holds no key, and its predictions sit over the
|
||
/// right half.
|
||
nonisolated struct SplitGeometry: Equatable, Sendable {
|
||
static let keyWidth: CGFloat = 46.3
|
||
static let gap: CGFloat = 10.7
|
||
static var pitch: CGFloat { keyWidth + gap }
|
||
static let modifierWidth: CGFloat = 63.3
|
||
static let layerSwitchWidth: CGFloat = 66.7
|
||
static let smallKeyWidth: CGFloat = 40.7
|
||
static let returnWidth: CGFloat = 66
|
||
/// How far left of the right half's first key the strip starts (Apple's first prediction).
|
||
static let stripLead: CGFloat = 38.3
|
||
|
||
/// The left half's right edge (row 1's last keycap) and the right half's left edge.
|
||
let leftEdge: CGFloat
|
||
let rightEdge: CGFloat
|
||
|
||
/// Touches right of this belong to the right half.
|
||
var middle: CGFloat { (leftEdge + rightEdge) / 2 }
|
||
/// How far the right half would move left to sit one gap after the left half.
|
||
var shift: CGFloat { rightEdge - leftEdge - Self.gap }
|
||
|
||
/// One row's keys for each half: an even row splits down the middle, an odd one gives its
|
||
/// middle key to both halves, as Apple's English split keeps G and V on both sides.
|
||
static func halves(_ row: [String]) -> (left: [String], right: [String]) {
|
||
let n = row.count
|
||
guard n > 1 else { return (row, row) }
|
||
if n % 2 == 1 {
|
||
return (Array(row[...(n / 2)]), Array(row[(n / 2)...]))
|
||
}
|
||
return (Array(row[..<(n / 2)]), Array(row[(n / 2)...]))
|
||
}
|
||
}
|
||
|
||
extension KeyboardLayout {
|
||
/// The split keyboard: each row's halves at the keyboard's sides with Apple's key sizes,
|
||
/// row 2 in half a key from the side and row 3's letters a key and a half, two space bars,
|
||
/// and touch targets that tile each half but leave the middle to no key.
|
||
static func buildSplitKeys(
|
||
width: CGFloat,
|
||
metrics m: KeyboardMetrics,
|
||
layer: KeyboardLayer,
|
||
field: KeyboardFieldKind,
|
||
showsGlobe: Bool,
|
||
showsEmoji: Bool,
|
||
inset: CGFloat,
|
||
language: KeyboardLanguage,
|
||
letters: KeyboardLetterLayout = .own,
|
||
hexPlacement placement: HexKeyPlacement
|
||
) -> (keys: [KeyboardKey], split: SplitGeometry) {
|
||
typealias G = SplitGeometry
|
||
// Dvorak splits like the other layouts, delete ending row 3 (Apple's split Dvorak unobserved).
|
||
let rows = characterRows(for: layer, language: language, letters: letters)
|
||
let left = inset + m.side
|
||
let right = width - inset - m.side
|
||
let p = G.pitch
|
||
|
||
func rowY(_ row: Int) -> CGFloat {
|
||
m.stripArea + m.keysTop + CGFloat(row) * (m.keyHeight + m.rowGap)
|
||
}
|
||
var drawn: [(KeyKind, Int, CGRect, String, Bool)] = [] // kind, row, frame, label, right half
|
||
func add(_ kind: KeyKind, row: Int, x: CGFloat, w: CGFloat, label: String, rightHalf: Bool) {
|
||
drawn.append((kind, row, CGRect(x: x, y: rowY(row), width: w, height: m.keyHeight), label, rightHalf))
|
||
}
|
||
func addRow(_ chars: [String], row: Int, leftStart: CGFloat, rightEnd: CGFloat) -> (CGFloat, CGFloat) {
|
||
let (l, r) = G.halves(chars)
|
||
for (i, ch) in l.enumerated() {
|
||
add(.character(ch), row: row, x: leftStart + CGFloat(i) * p, w: G.keyWidth, label: ch, rightHalf: false)
|
||
}
|
||
let rStart = rightEnd - CGFloat(r.count) * p + G.gap
|
||
for (i, ch) in r.enumerated() {
|
||
add(.character(ch), row: row, x: rStart + CGFloat(i) * p, w: G.keyWidth, label: ch, rightHalf: true)
|
||
}
|
||
return (leftStart + CGFloat(l.count) * p - G.gap, rStart)
|
||
}
|
||
|
||
// Rows 1 and 2: row 2 sits half a key in from each side.
|
||
let (leftEdge, rightEdge) = addRow(rows[0], row: 0, leftStart: left, rightEnd: right)
|
||
_ = addRow(rows[1], row: 1, leftStart: left + p / 2, rightEnd: right - p / 2)
|
||
|
||
// Row 3: shift (or the page switch) and delete at the sides, the middle keys a key and a
|
||
// half in from each side.
|
||
switch layer {
|
||
case .letters: add(.shift, row: 2, x: left, w: G.modifierWidth, label: "shift", rightHalf: false)
|
||
case .numbers: add(.layerSwitch(.symbols), row: 2, x: left, w: G.modifierWidth, label: "#+=", rightHalf: false)
|
||
case .symbols: add(.layerSwitch(.numbers), row: 2, x: left, w: G.modifierWidth, label: "123", rightHalf: false)
|
||
}
|
||
_ = addRow(rows[2], row: 2, leftStart: left + 1.5 * p, rightEnd: right - 1.5 * p)
|
||
add(.delete, row: 2, x: right - G.modifierWidth, w: G.modifierWidth, label: "delete", rightHalf: true)
|
||
|
||
// Row 4: 123/ABC, globe?, emoji? and a space bar on the left; a space bar, the field's
|
||
// extras, Hex (when it sits in the row) and return on the right.
|
||
var x = left
|
||
let switchKind: KeyKind = layer == .letters ? .layerSwitch(.numbers) : .layerSwitch(.letters)
|
||
add(switchKind, row: 3, x: x, w: G.layerSwitchWidth, label: layer == .letters ? "123" : "ABC", rightHalf: false)
|
||
x += G.layerSwitchWidth + G.gap
|
||
if showsGlobe {
|
||
add(.globe, row: 3, x: x, w: G.smallKeyWidth, label: "globe", rightHalf: false)
|
||
x += G.smallKeyWidth + G.gap
|
||
}
|
||
if showsEmoji {
|
||
add(.emoji, row: 3, x: x, w: G.smallKeyWidth, label: "emoji", rightHalf: false)
|
||
x += G.smallKeyWidth + G.gap
|
||
}
|
||
add(.space, row: 3, x: x, w: max(G.keyWidth, leftEdge - x), label: "space", rightHalf: false)
|
||
|
||
var trailing: [(KeyKind, CGFloat, String)] = []
|
||
switch field {
|
||
case .text: break
|
||
case .url:
|
||
trailing.append((.character("."), G.smallKeyWidth, "."))
|
||
trailing.append((.character("/"), G.smallKeyWidth, "/"))
|
||
case .email:
|
||
trailing.append((.character("@"), G.smallKeyWidth, "@"))
|
||
trailing.append((.character("."), G.smallKeyWidth, "."))
|
||
}
|
||
if !placement.isInStrip {
|
||
trailing.append((.hex, G.smallKeyWidth, "hex"))
|
||
}
|
||
trailing.append((.returnKey, G.returnWidth, "return"))
|
||
let trailingWidth = trailing.reduce(0) { $0 + $1.1 + G.gap }
|
||
let spaceRightWidth = max(G.keyWidth, right - rightEdge - trailingWidth)
|
||
add(.space, row: 3, x: rightEdge, w: spaceRightWidth, label: "space", rightHalf: true)
|
||
x = rightEdge + spaceRightWidth + G.gap
|
||
for (kind, w, label) in trailing {
|
||
add(kind, row: 3, x: x, w: w, label: label, rightHalf: true)
|
||
x += w + G.gap
|
||
}
|
||
|
||
// Touch targets: each half tiles from its side to half a gap past its inner key; the
|
||
// middle between the halves is no key's.
|
||
let top = m.stripArea - max(m.stripBottom, stripTouchBand)
|
||
var keys: [KeyboardKey] = []
|
||
for row in 0..<4 {
|
||
let y0 = row == 0 ? top : rowY(row) - m.rowGap / 2
|
||
let y1 = row == 3 ? m.totalHeight : rowY(row + 1) - m.rowGap / 2
|
||
for half in [false, true] {
|
||
let items = drawn.filter { $0.1 == row && $0.4 == half }.sorted { $0.2.minX < $1.2.minX }
|
||
for (i, item) in items.enumerated() {
|
||
let x0 = i == 0 ? (half ? item.2.minX - G.gap / 2 : 0) : (items[i - 1].2.maxX + item.2.minX) / 2
|
||
let x1 = i == items.count - 1 ? (half ? width : item.2.maxX + G.gap / 2) : (item.2.maxX + items[i + 1].2.minX) / 2
|
||
keys.append(KeyboardKey(
|
||
kind: item.0,
|
||
row: row,
|
||
frame: item.2,
|
||
hitFrame: CGRect(x: x0, y: y0, width: x1 - x0, height: y1 - y0),
|
||
label: item.3
|
||
))
|
||
}
|
||
}
|
||
}
|
||
if placement.isInStrip {
|
||
let height = m.stripPillHeight
|
||
let hexWidth: CGFloat = 44
|
||
let hx = placement == .stripLeading ? left : right - hexWidth
|
||
let frame = CGRect(x: hx, y: m.stripTop + m.stripInset, width: hexWidth, height: height)
|
||
let target = frame.insetBy(dx: -4, dy: -4)
|
||
let hitFrame = CGRect(x: target.minX, y: target.minY, width: target.width, height: top - target.minY)
|
||
keys.append(KeyboardKey(kind: .hex, row: -1, frame: frame, hitFrame: hitFrame, label: "hex"))
|
||
}
|
||
return (keys, SplitGeometry(leftEdge: leftEdge, rightEdge: rightEdge))
|
||
}
|
||
}
|