Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(mobile): stop dropping keyboard taps between rows (#2388)

Kristofer Jussmann63235b534c46
diff --git a/.github/workflows/mobile-ci.yml b/.github/workflows/mobile-ci.yml
index 905c26b4d..099d393b3 100644
--- a/.github/workflows/mobile-ci.yml
+++ b/.github/workflows/mobile-ci.yml
@@ -102,7 +102,7 @@ jobs:
name: Mobile native Swift tests
needs: changes
if: needs.changes.outputs.mobile == 'true'
- # Compiles the Foundation-only Swift sources and their tests, which need Xcode's toolchain.
+ # Compiles native Swift sources and their tests, which need Xcode's toolchain (the keyboard's UIKit tests build for Mac Catalyst).
runs-on: macos-latest
timeout-minutes: 15
steps:
@@ -117,6 +117,8 @@ jobs:
run: python3 openwhispr-mobile/plugins/hotkey-dictation/tests/run-hotkey-logic-tests.py
- name: Run Live Activity resolver tests
run: sh openwhispr-mobile/modules/live-activity/tests/run-resolver-tests.sh
+ - name: Run keyboard touch routing tests
+ run: python3 openwhispr-mobile/plugins/keyboard-extension/tests/run-keyboard-touch-tests.py
mobile-status:
name: Mobile CI
diff --git a/openwhispr-mobile/plugins/keyboard-extension/README.md b/openwhispr-mobile/plugins/keyboard-extension/README.md
index 5b4b043ec..00e9c13dc 100644
--- a/openwhispr-mobile/plugins/keyboard-extension/README.md
+++ b/openwhispr-mobile/plugins/keyboard-extension/README.md
@@ -45,6 +45,21 @@ npx expo prebuild --clean
npm run ios
```
+## Keyboard touch regression tests
+
+On macOS with Xcode:
+
+```bash
+python3 openwhispr-mobile/plugins/keyboard-extension/tests/run-keyboard-touch-tests.py
+```
+
+Run it from the repository root after changing the keyboard layout, its padding or key targets; mobile CI runs it too. The runner compiles the production keyboard Swift source for Mac Catalyst, so it needs no simulator, signing credentials or Expo build. It tests UIKit hit routing across row gaps, overlapping key targets, unequal key widths, nested stacks, hidden layouts, disabled keys and keyboard boundaries, then lays out the real keyboard at several widths in letters and numbers mode, with and without the globe key, and checks that no tap below the dictation strip is dropped, the keyboard's padding included.
+
+These touch tests do not measure typing latency. Before releasing,
+check fast two-thumb typing and repeated letters on an iPhone, near-edge taps,
+Shift, 123/ABC, space/return, held delete, keyboard switching, and dictation in
+portrait and landscape in Notes and another host app.
+
## Reference
- [Apple — Custom Keyboard Extensions](https://developer.apple.com/documentation/uikit/keyboards_and_input/creating_a_custom_keyboard)
diff --git a/openwhispr-mobile/plugins/keyboard-extension/ios/KeyboardViewController.swift b/openwhispr-mobile/plugins/keyboard-extension/ios/KeyboardViewController.swift
index 5eca4c82a..5edcd9708 100644
--- a/openwhispr-mobile/plugins/keyboard-extension/ios/KeyboardViewController.swift
+++ b/openwhispr-mobile/plugins/keyboard-extension/ios/KeyboardViewController.swift
@@ -99,6 +99,66 @@ private final class KeyButton: UIButton {
}
}
+/// Route through row/stack boundaries so a key's enlarged target also works in
+/// the gaps between rows. UIKit's default hit testing stops at a parent whose
+/// bounds do not contain the touch, before consulting the key's point(inside:).
+/// Touches no key claims keep UIKit's default target.
+private final class KeyboardRowsStack: UIStackView {
+ /// Padding around the rows that still routes to the nearest key, as the system
+ /// keyboard does at its edges.
+ var touchMargins = UIEdgeInsets.zero
+
+ override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
+ let expanded = bounds.inset(
+ by: UIEdgeInsets(
+ top: -touchMargins.top,
+ left: -touchMargins.left,
+ bottom: -touchMargins.bottom,
+ right: -touchMargins.right
+ )
+ )
+ return expanded.contains(point)
+ }
+
+ override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
+ guard let defaultTarget = super.hitTest(point, with: event) else { return nil }
+
+ var nearest: KeyButton?
+ var nearestDistance = CGFloat.infinity
+ var nearestCenterDistance = CGFloat.infinity
+
+ func visit(_ view: UIView) {
+ guard !view.isHidden, view.isUserInteractionEnabled, view.alpha >= 0.01 else { return }
+ if let key = view as? KeyButton {
+ guard key.isEnabled,
+ key.point(inside: key.convert(point, from: self), with: event) else { return }
+
+ // Prefer the visible key rectangle over another key's expanded area.
+ // In a gap, choose the nearer edge; center distance breaks edge ties.
+ // This avoids UIKit's reverse-subview-order bias in overlapping targets.
+ let rect = key.convert(key.bounds, to: self)
+ let dx = max(rect.minX - point.x, 0, point.x - rect.maxX)
+ let dy = max(rect.minY - point.y, 0, point.y - rect.maxY)
+ let distance = dx * dx + dy * dy
+ let centerDX = point.x - rect.midX
+ let centerDY = point.y - rect.midY
+ let centerDistance = centerDX * centerDX + centerDY * centerDY
+ if distance < nearestDistance
+ || (distance == nearestDistance && centerDistance < nearestCenterDistance) {
+ nearest = key
+ nearestDistance = distance
+ nearestCenterDistance = centerDistance
+ }
+ return
+ }
+ view.subviews.forEach(visit)
+ }
+
+ subviews.forEach(visit)
+ return nearest ?? defaultTarget
+ }
+}
+
private extension UIColor {
func brightened(by amount: CGFloat) -> UIColor {
var h: CGFloat = 0, s: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
@@ -517,7 +577,7 @@ final class KeyboardViewController: UIInputViewController, UIGestureRecognizerDe
// the in-flight transcription. Hidden in every other state.
private let processingCancelButton = UIButton(type: .system)
private let toneButton = KeyButton(type: .system)
- private let keyboardRowsStack = UIStackView()
+ private let keyboardRowsStack = KeyboardRowsStack()
private let lettersRowsStack = UIStackView()
private let numbersRowsStack = UIStackView()
@@ -590,10 +650,6 @@ final class KeyboardViewController: UIInputViewController, UIGestureRecognizerDe
private var isObservingHandoffNotifications = false
private var didBuildKeyboard = false
private var lastMetricsWidth: CGFloat = 0
- private var rootLeadingConstraint: NSLayoutConstraint?
- private var rootTrailingConstraint: NSLayoutConstraint?
- private var rootTopConstraint: NSLayoutConstraint?
- private var rootBottomConstraint: NSLayoutConstraint?
private var dictationStripHeightConstraint: NSLayoutConstraint?
private var keyboardHeightConstraint: NSLayoutConstraint?
private var rowHeightConstraints: [NSLayoutConstraint] = []
@@ -915,32 +971,20 @@ final class KeyboardViewController: UIInputViewController, UIGestureRecognizerDe
rootStack.axis = .vertical
rootStack.spacing = metrics.rootSectionSpacing
+ // The padding is a layout margin, not an offset from the edges, so the stack
+ // spans the whole keyboard and touches in the padding can reach the rows.
+ rootStack.isLayoutMarginsRelativeArrangement = true
+ rootStack.insetsLayoutMarginsFromSafeArea = false
rootStack.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(rootStack)
- rootLeadingConstraint = rootStack.leadingAnchor.constraint(
- equalTo: view.leadingAnchor,
- constant: metrics.rootHorizontalPadding
- )
- rootTrailingConstraint = rootStack.trailingAnchor.constraint(
- equalTo: view.trailingAnchor,
- constant: -metrics.rootHorizontalPadding
- )
- rootTopConstraint = rootStack.topAnchor.constraint(
- equalTo: view.topAnchor,
- constant: metrics.rootTopPadding
- )
- rootBottomConstraint = rootStack.bottomAnchor.constraint(
- equalTo: view.bottomAnchor,
- constant: -metrics.rootBottomPadding
- )
-
NSLayoutConstraint.activate([
- rootLeadingConstraint,
- rootTrailingConstraint,
- rootTopConstraint,
- rootBottomConstraint,
- ].compactMap { $0 })
+ rootStack.leadingAnchor.constraint(equalTo: view.leadingAnchor),
+ rootStack.trailingAnchor.constraint(equalTo: view.trailingAnchor),
+ rootStack.topAnchor.constraint(equalTo: view.topAnchor),
+ rootStack.bottomAnchor.constraint(equalTo: view.bottomAnchor),
+ ])
+ applyRootPadding()
setupDictationStrip()
setupKeyboardArea()
@@ -1935,6 +1979,23 @@ final class KeyboardViewController: UIInputViewController, UIGestureRecognizerDe
rowHeightConstraints.append(constraint)
}
+ private func applyRootPadding() {
+ rootStack.directionalLayoutMargins = NSDirectionalEdgeInsets(
+ top: metrics.rootTopPadding,
+ leading: metrics.rootHorizontalPadding,
+ bottom: metrics.rootBottomPadding,
+ trailing: metrics.rootHorizontalPadding
+ )
+ // The rows take the padding at the keyboard's sides and bottom, and the half
+ // of the gap below the dictation strip that is nearer to them.
+ keyboardRowsStack.touchMargins = UIEdgeInsets(
+ top: metrics.rootSectionSpacing / 2,
+ left: metrics.rootHorizontalPadding,
+ bottom: metrics.rootBottomPadding,
+ right: metrics.rootHorizontalPadding
+ )
+ }
+
private func refreshMetricsIfNeeded() {
let width = view.bounds.width
guard width.isFinite, width > 0, abs(width - lastMetricsWidth) > 1 else { return }
@@ -1944,10 +2005,7 @@ final class KeyboardViewController: UIInputViewController, UIGestureRecognizerDe
guard nextMetrics != metrics else { return }
metrics = nextMetrics
- rootLeadingConstraint?.constant = metrics.rootHorizontalPadding
- rootTrailingConstraint?.constant = -metrics.rootHorizontalPadding
- rootTopConstraint?.constant = metrics.rootTopPadding
- rootBottomConstraint?.constant = -metrics.rootBottomPadding
+ applyRootPadding()
rootStack.spacing = metrics.rootSectionSpacing
keyboardRowsStack.spacing = metrics.keyboardRowSpacing
lettersRowsStack.spacing = metrics.keyboardRowSpacing
@@ -2063,6 +2121,13 @@ final class KeyboardViewController: UIInputViewController, UIGestureRecognizerDe
rowStack.addArrangedSubview(button)
}
+ // Like the system keyboard, an inset row's end keys take taps in the inset.
+ if let first = rowStack.arrangedSubviews.first as? KeyButton,
+ let last = rowStack.arrangedSubviews.last as? KeyButton {
+ first.hitTestOutsets.left += inset
+ last.hitTestOutsets.right += inset
+ }
+
return rowContainer
}
@@ -2222,7 +2287,10 @@ final class KeyboardViewController: UIInputViewController, UIGestureRecognizerDe
nextKeyboardButton.topAnchor.constraint(equalTo: rowContainer.topAnchor),
nextKeyboardButton.bottomAnchor.constraint(equalTo: rowContainer.bottomAnchor),
- modeButton.leadingAnchor.constraint(equalTo: nextKeyboardButton.trailingAnchor, constant: metrics.keySpacing),
+ modeButton.leadingAnchor.constraint(
+ equalTo: nextKeyboardButton.trailingAnchor,
+ constant: needsInputModeSwitchKey ? metrics.keySpacing : 0
+ ),
modeButton.topAnchor.constraint(equalTo: rowContainer.topAnchor),
modeButton.bottomAnchor.constraint(equalTo: rowContainer.bottomAnchor),
@@ -2290,6 +2358,14 @@ final class KeyboardViewController: UIInputViewController, UIGestureRecognizerDe
role: KeyRole
) -> KeyButton {
let button = KeyButton(type: .custom)
+ // Each key's target reaches its neighbours and the keyboard's padding, so no
+ // gap or pixel-rounding sliver is dead; KeyboardRowsStack resolves overlaps.
+ button.hitTestOutsets = UIEdgeInsets(
+ top: metrics.keyboardRowSpacing,
+ left: metrics.keySpacing,
+ bottom: metrics.keyboardRowSpacing,
+ right: metrics.keySpacing
+ )
button.layer.cornerRadius = metrics.keyCornerRadius
button.layer.cornerCurve = .continuous
diff --git a/openwhispr-mobile/plugins/keyboard-extension/tests/KeyboardTouchTests.swift b/openwhispr-mobile/plugins/keyboard-extension/tests/KeyboardTouchTests.swift
new file mode 100644
index 000000000..3eef3d678
--- /dev/null
+++ b/openwhispr-mobile/plugins/keyboard-extension/tests/KeyboardTouchTests.swift
@@ -0,0 +1,317 @@
+// The runner appends this to KeyboardViewController.swift so private production
+// types remain private while the tests exercise the actual UIKit implementation.
+private extension KeyboardViewController {
+ static func makeTouchTestStack() -> UIStackView {
+ KeyboardViewController().keyboardRowsStack
+ }
+
+ /// The production keyboard laid out at `width` and its content height. `globe`
+ /// stands in for needsInputModeSwitchKey: true on iPhones with a Home button.
+ static func makeLaidOutKeyboard(width: CGFloat, numbers: Bool, globe: Bool) -> KeyboardViewController {
+ let getter = class_getInstanceMethod(
+ UIInputViewController.self,
+ #selector(getter: UIInputViewController.needsInputModeSwitchKey)
+ )!
+ let stub: @convention(block) (AnyObject) -> Bool = { _ in globe }
+ let original = method_setImplementation(getter, imp_implementationWithBlock(stub))
+ defer { method_setImplementation(getter, original) }
+
+ let controller = KeyboardViewController()
+ controller.loadViewIfNeeded()
+ if numbers {
+ controller.handleLayoutModeSwitchTapped()
+ }
+ // The first pass picks the metrics for `width`; the second sizes the view to its rows.
+ controller.view.frame = CGRect(x: 0, y: 0, width: width, height: 400)
+ controller.view.layoutIfNeeded()
+ let height = controller.view.systemLayoutSizeFitting(
+ CGSize(width: width, height: 0),
+ withHorizontalFittingPriority: .required,
+ verticalFittingPriority: .fittingSizeLevel
+ ).height
+ controller.view.frame = CGRect(x: 0, y: 0, width: width, height: height)
+ controller.view.layoutIfNeeded()
+ return controller
+ }
+
+ var touchTestRows: KeyboardRowsStack { keyboardRowsStack }
+ var touchTestRowHeight: CGFloat { metrics.rowHeight }
+ var touchTestPadding: (side: CGFloat, bottom: CGFloat) {
+ (metrics.rootHorizontalPadding, metrics.rootBottomPadding)
+ }
+}
+
+private struct TouchChecks {
+ private(set) var failures = [String]()
+ private(set) var count = 0
+
+ mutating func check(_ label: String, _ passed: Bool) {
+ count += 1
+ if !passed {
+ failures.append(label)
+ print("FAIL: \(label)")
+ }
+ }
+
+ mutating func expect(_ label: String, _ stack: UIView, _ point: CGPoint, _ expected: UIView?) {
+ check(label, stack.hitTest(point, with: nil) === expected)
+ }
+}
+
+@main
+private enum KeyboardTouchTests {
+ @MainActor
+ static func main() {
+ var checks = TouchChecks()
+ checkSyntheticRows(&checks)
+ checkEdgeTies(&checks)
+ checkOtherControls(&checks)
+ for width: CGFloat in [360, 393, 430, 852] {
+ checkProductionLayout(width: width, numbers: false, globe: false, &checks)
+ checkProductionLayout(width: width, numbers: true, globe: false, &checks)
+ checkProductionLayout(width: width, numbers: false, globe: true, &checks)
+ }
+
+ print("Keyboard touch routing: \(checks.count - checks.failures.count)/\(checks.count) passed")
+ if !checks.failures.isEmpty {
+ exit(1)
+ }
+ }
+
+ @MainActor
+ static func checkSyntheticRows(_ checks: inout TouchChecks) {
+ let stack = KeyboardViewController.makeTouchTestStack()
+ stack.frame = CGRect(x: 0, y: 0, width: 100, height: 95)
+
+ func addRow(y: CGFloat) -> (UIView, KeyButton, KeyButton) {
+ let container = UIView(frame: CGRect(x: 0, y: y, width: 100, height: 42))
+ let row = UIStackView(frame: container.bounds)
+ container.addSubview(row)
+ let left = KeyButton(type: .custom)
+ left.frame = CGRect(x: 0, y: 0, width: 47, height: 42)
+ let right = KeyButton(type: .custom)
+ right.frame = CGRect(x: 53, y: 0, width: 47, height: 42)
+ row.addSubview(left)
+ row.addSubview(right)
+ stack.addSubview(container)
+ return (container, left, right)
+ }
+
+ let (topRow, topLeft, topRight) = addRow(y: 0)
+ let (_, bottomLeft, _) = addRow(y: 53)
+
+ checks.expect("key center", stack, CGPoint(x: 20, y: 20), topLeft)
+ checks.expect("row gap closer to upper key", stack, CGPoint(x: 20, y: 45), topLeft)
+ checks.expect("row gap closer to lower key", stack, CGPoint(x: 20, y: 50), bottomLeft)
+ checks.expect("horizontal gap closer to left", stack, CGPoint(x: 49, y: 20), topLeft)
+ checks.expect("horizontal gap closer to right", stack, CGPoint(x: 51, y: 20), topRight)
+
+ // UIKit visits later siblings first. Expanded target overlap must not steal
+ // a tap from a visibly closer key solely because it was added last.
+ topLeft.hitTestOutsets.right = 8
+ topRight.hitTestOutsets.left = 8
+ checks.expect("visible left edge beats overlapping right target", stack, CGPoint(x: 46, y: 20), topLeft)
+ checks.expect("visible right edge beats overlapping left target", stack, CGPoint(x: 54, y: 20), topRight)
+ checks.expect("overlapping gap chooses nearer left", stack, CGPoint(x: 49, y: 20), topLeft)
+ checks.expect("overlapping gap chooses nearer right", stack, CGPoint(x: 51, y: 20), topRight)
+ checks.expect("exact tie keeps the earlier key", stack, CGPoint(x: 50, y: 20), topLeft)
+ checks.expect("exact row tie keeps the upper key", stack, CGPoint(x: 20, y: 47.5), topLeft)
+
+ // A hidden layout sits above the visible one in the production hierarchy.
+ // Its key covers the tap point, so it would win if it were considered.
+ let hiddenRow = UIView(frame: topRow.frame)
+ let hiddenKey = KeyButton(type: .custom)
+ hiddenKey.frame = topLeft.frame.offsetBy(dx: 0, dy: 4)
+ hiddenRow.addSubview(hiddenKey)
+ hiddenRow.isHidden = true
+ stack.addSubview(hiddenRow)
+ checks.expect("hidden layout never steals a gap", stack, CGPoint(x: 20, y: 45), topLeft)
+ hiddenRow.isHidden = false
+ hiddenRow.alpha = 0
+ checks.expect("transparent layout never steals a gap", stack, CGPoint(x: 20, y: 45), topLeft)
+ hiddenRow.alpha = 1
+ hiddenRow.isUserInteractionEnabled = false
+ checks.expect("noninteractive layout never steals a gap", stack, CGPoint(x: 20, y: 45), topLeft)
+ hiddenRow.removeFromSuperview()
+
+ // UIKit skips disabled controls, so a disabled key takes no taps at all.
+ topLeft.isEnabled = false
+ checks.expect("disabled key leaves its gap dead", stack, CGPoint(x: 20, y: 46), stack)
+ checks.expect("disabled key lets the lower key take its gap", stack, CGPoint(x: 20, y: 47), bottomLeft)
+ checks.expect("disabled key face falls through to its row", stack, CGPoint(x: 20, y: 20), topRow.subviews[0])
+ topLeft.isEnabled = true
+
+ checks.expect("outside rows does not capture dictation-strip taps", stack, CGPoint(x: 20, y: -1), nil)
+ checks.expect("outside right boundary", stack, CGPoint(x: 101, y: 20), nil)
+ stack.isHidden = true
+ checks.expect("hidden keyboard", stack, CGPoint(x: 20, y: 20), nil)
+ stack.isHidden = false
+ stack.alpha = 0
+ checks.expect("transparent keyboard", stack, CGPoint(x: 20, y: 20), nil)
+ stack.alpha = 1
+ stack.isUserInteractionEnabled = false
+ checks.expect("disabled keyboard interaction", stack, CGPoint(x: 20, y: 20), nil)
+ stack.isUserInteractionEnabled = true
+
+ // The third row adds another letters stack between shift and backspace.
+ let nested = UIStackView(frame: topLeft.frame)
+ topLeft.removeFromSuperview()
+ topRow.subviews[0].addSubview(nested)
+ topLeft.frame = nested.bounds
+ nested.addSubview(topLeft)
+ checks.expect("nested third-row key receives a gap tap", stack, CGPoint(x: 20, y: 45), topLeft)
+
+ // Exercise every row-gap pixel that lies in an expanded key target.
+ for y in 42...52 {
+ let expected = y <= 47 ? topLeft : bottomLeft
+ checks.expect("continuous row target at y=\(y)", stack, CGPoint(x: 20, y: CGFloat(y)), expected)
+ }
+ }
+
+ /// Keys of unequal width, like shift, backspace and space beside letters.
+ @MainActor
+ static func checkEdgeTies(_ checks: inout TouchChecks) {
+ func makeRow(_ frames: [CGRect]) -> (UIStackView, [KeyButton]) {
+ let stack = KeyboardViewController.makeTouchTestStack()
+ stack.frame = CGRect(x: 0, y: 0, width: 100, height: 42)
+ let row = UIView(frame: stack.bounds)
+ stack.addSubview(row)
+ let keys = frames.map { frame -> KeyButton in
+ let key = KeyButton(type: .custom)
+ key.frame = frame
+ row.addSubview(key)
+ return key
+ }
+ return (stack, keys)
+ }
+
+ // Equal edge distance: the key whose center is nearer wins, in either order.
+ let (wideFirst, wideFirstKeys) = makeRow([
+ CGRect(x: 0, y: 0, width: 60, height: 42),
+ CGRect(x: 64, y: 0, width: 20, height: 42),
+ ])
+ checks.expect("edge tie goes to the later key with the nearer center", wideFirst, CGPoint(x: 62, y: 20), wideFirstKeys[1])
+ let (narrowFirst, narrowFirstKeys) = makeRow([
+ CGRect(x: 0, y: 0, width: 20, height: 42),
+ CGRect(x: 24, y: 0, width: 60, height: 42),
+ ])
+ checks.expect("edge tie goes to the earlier key with the nearer center", narrowFirst, CGPoint(x: 22, y: 20), narrowFirstKeys[0])
+
+ // A wide key's visible face wins over a narrow neighbour whose center is nearer.
+ wideFirstKeys[1].hitTestOutsets.left = 8
+ checks.expect("wide key face beats a nearer narrow center", wideFirst, CGPoint(x: 59, y: 20), wideFirstKeys[0])
+ checks.expect("wide key gap edge beats a nearer narrow center", wideFirst, CGPoint(x: 61, y: 20), wideFirstKeys[0])
+ }
+
+ /// A control that is not a KeyButton keeps UIKit's default routing.
+ @MainActor
+ static func checkOtherControls(_ checks: inout TouchChecks) {
+ let stack = KeyboardViewController.makeTouchTestStack()
+ stack.frame = CGRect(x: 0, y: 0, width: 100, height: 42)
+ let row = UIView(frame: stack.bounds)
+ stack.addSubview(row)
+ let button = UIButton(type: .custom)
+ button.frame = CGRect(x: 0, y: 0, width: 40, height: 42)
+ row.addSubview(button)
+ let key = KeyButton(type: .custom)
+ key.frame = CGRect(x: 60, y: 0, width: 40, height: 42)
+ row.addSubview(key)
+
+ checks.expect("plain button stays tappable", stack, CGPoint(x: 20, y: 20), button)
+ checks.expect("dead point keeps UIKit's target", stack, CGPoint(x: 50, y: 20), row)
+ }
+
+ /// Sweeps the real keyboard below the dictation strip, padding included: no tap
+ /// is dropped, every key keeps its own face, and a tap just outside a key never
+ /// goes to a farther key.
+ @MainActor
+ static func checkProductionLayout(
+ width: CGFloat,
+ numbers: Bool,
+ globe: Bool,
+ _ checks: inout TouchChecks
+ ) {
+ let controller = KeyboardViewController.makeLaidOutKeyboard(width: width, numbers: numbers, globe: globe)
+ let rows = controller.touchTestRows
+ let layout = "\(Int(width)) pt \(numbers ? "numbers" : "letters")\(globe ? " with globe" : "")"
+
+ var keys = [KeyButton]()
+ func collect(_ view: UIView) {
+ guard !view.isHidden else { return }
+ if let key = view as? KeyButton {
+ keys.append(key)
+ return
+ }
+ view.subviews.forEach(collect)
+ }
+ collect(rows)
+ let rects = keys.map { $0.convert($0.bounds, to: rows) }
+ checks.check(
+ "\(layout): keys laid out at row height",
+ keys.count > 20 && rects.allSatisfy { abs($0.height - controller.touchTestRowHeight) < 0.5 }
+ )
+
+ func edgeDistance(_ rect: CGRect, _ point: CGPoint) -> CGFloat {
+ let dx = max(rect.minX - point.x, 0, point.x - rect.maxX)
+ let dy = max(rect.minY - point.y, 0, point.y - rect.maxY)
+ return dx * dx + dy * dy
+ }
+
+ var wrongFace = 0
+ var fartherKey = 0
+ for (key, rect) in zip(keys, rects) {
+ let faces = [
+ CGPoint(x: rect.midX, y: rect.midY),
+ CGPoint(x: rect.minX + 1, y: rect.midY), CGPoint(x: rect.maxX - 1, y: rect.midY),
+ CGPoint(x: rect.midX, y: rect.minY + 1), CGPoint(x: rect.midX, y: rect.maxY - 1),
+ ]
+ wrongFace += faces.filter { rows.hitTest($0, with: nil) !== key }.count
+
+ let outside = [
+ CGPoint(x: rect.minX - 2, y: rect.midY), CGPoint(x: rect.maxX + 2, y: rect.midY),
+ CGPoint(x: rect.midX, y: rect.minY - 2), CGPoint(x: rect.midX, y: rect.maxY + 2),
+ ]
+ for point in outside where rows.bounds.contains(point) {
+ guard let hit = rows.hitTest(point, with: nil) as? KeyButton,
+ let index = keys.firstIndex(where: { $0 === hit }) else { continue }
+ if edgeDistance(rects[index], point) > edgeDistance(rect, point) {
+ fartherKey += 1
+ }
+ }
+ }
+ checks.check("\(layout): every key keeps its own face (\(wrongFace) wrong)", wrongFace == 0)
+ checks.check("\(layout): no tap beside a key goes to a farther key (\(fartherKey))", fartherKey == 0)
+
+ // Hit-test from the root view, so a touch in the keyboard's padding has to get
+ // through every ancestor. Half-point steps across catch the pixel-rounding
+ // slivers between equal-width keys; row heights and gaps are whole points.
+ let root = controller.view!
+ let strip = (rows.superview as! UIStackView).arrangedSubviews[0]
+ let padding = controller.touchTestPadding
+ checks.check(
+ "\(layout): rows keep the keyboard's padding",
+ rows.frame.minX == padding.side && root.bounds.maxX - rows.frame.maxX == padding.side
+ && root.bounds.maxY - rows.frame.maxY == padding.bottom
+ )
+ let top = (strip.frame.maxY + rows.frame.minY) / 2
+ let visibleKeys = Set(keys.map(ObjectIdentifier.init))
+ var dropped = 0
+ var hiddenHits = 0
+ for y in stride(from: top, to: root.bounds.height, by: 1) {
+ for x in stride(from: 0, to: root.bounds.width, by: 0.5) {
+ guard let hit = root.hitTest(CGPoint(x: x, y: y), with: nil) as? KeyButton else {
+ dropped += 1
+ continue
+ }
+ if !visibleKeys.contains(ObjectIdentifier(hit)) {
+ hiddenHits += 1
+ }
+ }
+ }
+ checks.check("\(layout): no tap below the dictation strip is dropped (\(dropped))", dropped == 0)
+ checks.check("\(layout): no tap reaches a hidden key (\(hiddenHits))", hiddenHits == 0)
+
+ let stripHalf = CGPoint(x: root.bounds.midX, y: top - 0.5)
+ checks.check("\(layout): the strip's half of the gap takes no key taps", !(root.hitTest(stripHalf, with: nil) is KeyButton))
+ }
+}
diff --git a/openwhispr-mobile/plugins/keyboard-extension/tests/run-keyboard-touch-tests.py b/openwhispr-mobile/plugins/keyboard-extension/tests/run-keyboard-touch-tests.py
new file mode 100644
index 000000000..20031671b
--- /dev/null
+++ b/openwhispr-mobile/plugins/keyboard-extension/tests/run-keyboard-touch-tests.py
@@ -0,0 +1,42 @@
+"""Compile the production keyboard for Mac Catalyst and exercise its UIKit hit testing."""
+
+import json
+from pathlib import Path
+import platform
+import subprocess
+import tempfile
+
+# Matches IPHONEOS_DEPLOYMENT_TARGET in withKeyboardExtension.js.
+DEPLOYMENT_TARGET = "15.1"
+
+
+def main():
+ if platform.system() != "Darwin":
+ raise SystemExit("Keyboard UIKit tests require macOS and Xcode.")
+
+ plugin = Path(__file__).resolve().parents[1]
+ tests = plugin / "tests/KeyboardTouchTests.swift"
+ sdk = subprocess.check_output(
+ ["xcrun", "--sdk", "macosx", "--show-sdk-path"], text=True
+ ).strip()
+ with tempfile.TemporaryDirectory(prefix="keyboard-touch-") as directory:
+ source = Path(directory) / "keyboard-with-touch-tests.swift"
+ # #sourceLocation keeps compiler errors and traps pointing at the test file.
+ source.write_text(
+ (plugin / "ios/KeyboardViewController.swift").read_text()
+ + f"\n#sourceLocation(file: {json.dumps(str(tests), ensure_ascii=False)}, line: 1)\n"
+ + tests.read_text()
+ )
+ executable = str(Path(directory) / "keyboard-touch-tests")
+ subprocess.run([
+ "xcrun", "--sdk", "macosx", "swiftc", "-swift-version", "5", "-parse-as-library",
+ "-sdk", sdk,
+ "-target", f"{platform.machine()}-apple-ios{DEPLOYMENT_TARGET}-macabi",
+ "-Fsystem", f"{sdk}/System/iOSSupport/System/Library/Frameworks",
+ str(source), "-o", executable,
+ ], check=True)
+ subprocess.run([executable], check=True)
+
+
+if __name__ == "__main__":
+ main()