Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Keyboard9// File : KeyboardUI/KeyboardSurfaceView.swift10// Description : The typing surface. Lays keys out from a KeyboardLayout11// and owns every touch: rollover typing, key preview,12// long-press alternates, continuous delete with a guaranteed13// stop, and the space-bar cursor gesture. Touch zones extend14// to the neighbouring keys, so no tap falls in a gap.15// Module : KeyboardUI16// Repository : https://git.spboucher.ai/sp-keyboard17// Created : 2026-12-0118// Last Modified : 2026-12-0119//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author : Simon-Pierre Boucher25// Position : Professor of Finance26// Institution : Université du Québec en Outaouais (UQO)27// Department : Département des sciences administratives28// Organization : SP Boucher29//30// Website : https://spboucher.ai31// Git : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General : info@spboucher.ai38// Professional : contact@spboucher.ai39// Direct : simon@spboucher.ai40// Research : research@spboucher.ai41// Development : dev@spboucher.ai42// Support : support@spboucher.ai43// Security/Admin : admin@spboucher.ai44// Notifications : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification : Public71// Distribution : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License : None specified (no license file in this repository)85// Maintainer : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import UIKit93import KeyboardCore94import PredictionCore95import ThemeEngine9697@MainActor98protocol KeyboardSurfaceDelegate: AnyObject {99 /// A key was committed. `text` overrides the key's own character (long-press alternate).100 func surface(_ surface: KeyboardSurfaceView, didCommit key: Key, alternate text: String?)101 /// Continuous delete, step `repeatIndex` (0-based, after the first delete).102 func surface(_ surface: KeyboardSurfaceView, deleteRepeat repeatIndex: Int)103 /// The finger swept left from the backspace key: one more word goes.104 func surfaceDidSwipeDeleteWord(_ surface: KeyboardSurfaceView)105 func surface(_ surface: KeyboardSurfaceView, moveCursorBy steps: Int)106 /// A key went down (for haptics and sound).107 func surface(_ surface: KeyboardSurfaceView, didPress key: Key)108 /// The language key was long-pressed.109 func surfaceDidRequestLanguageMenu(_ surface: KeyboardSurfaceView)110 /// A word was traced across the letters. `path` is in the coordinates `layout` describes.111 func surface(_ surface: KeyboardSurfaceView, didGlide path: [SIMD2<Double>], layout: GlideLayout)112}113114/// Pure geometry of the touch model, kept apart from the view so it can be tested without one.115enum TouchModel {116 /// Half-size of the part of a key that always belongs to it, as a share of the key's cell.117 /// Only the gap between two caps and their very rim are open to interpretation.118 static let coreX: CGFloat = 0.40119 static let coreY: CGFloat = 0.38120 /// Spread of a touch around its target, as a share of the cell.121 static let sigmaX: CGFloat = 0.27122 static let sigmaY: CGFloat = 0.30123 /// Weight every key keeps whatever the word suggests: likelihoods tilt a decision, they never forbid a key.124 static let floorWeight = 0.16125126 struct Candidate {127 var id: String128 var center: CGPoint129 }130131 /// The key a touch at `point` most plausibly aimed for. `base` is the key whose cell holds the point,132 /// `candidates` are it and its neighbours, `weights` the share of likely next letters by key identifier.133 /// A touch well inside a key is never reassigned.134 static func resolve(point: CGPoint, base: Candidate, cell: CGSize, candidates: [Candidate], weights: [String: Double]) -> String {135 guard cell.width > 0, cell.height > 0, !weights.isEmpty else { return base.id }136 let dx = abs(point.x - base.center.x) / cell.width, dy = abs(point.y - base.center.y) / cell.height137 if dx < coreX, dy < coreY { return base.id }138 var best = base.id139 var bestScore = -Double.infinity140 for candidate in candidates {141 let nx = Double((point.x - candidate.center.x) / cell.width), ny = Double((point.y - candidate.center.y) / cell.height)142 guard abs(nx) < 1.1, abs(ny) < 1.1 else { continue }143 let likelihood = exp(-(nx * nx) / (2 * Double(sigmaX * sigmaX)) - (ny * ny) / (2 * Double(sigmaY * sigmaY)))144 let score = likelihood * (floorWeight + (weights[candidate.id] ?? 0))145 // The key under the finger wins ties.146 if score > bestScore || (score == bestScore && candidate.id == base.id) {147 bestScore = score148 best = candidate.id149 }150 }151 return best152 }153}154155final class KeyboardSurfaceView: UIView {156 weak var delegate: KeyboardSurfaceDelegate?157 var showsKeyPreview = true158 var spaceCursorEnabled = true159 /// Tracing a word across the letter keys.160 var glideEnabled = false { didSet { if !glideEnabled { endGlideTrail(animated: false) } } }161 /// Likely next letters (key identifier → share), used to settle touches between two keys. Empty = off.162 var keyWeights: [String: Double] = [:]163164 private(set) var layout = KeyboardLayout(rows: [])165 private var theme: Theme = BuiltInThemes.default166 private var keyViews: [String: KeyView] = [:]167 /// Touch targets, one per key, tiling the whole surface.168 private var hitZones: [(frame: CGRect, id: String)] = []169 private var rowOfKey: [String: Int] = [:]170 private let popup = KeyPopupView()171 private let trail = CAShapeLayer()172 private var shiftState: ShiftState = .off173 private var unitWidth: CGFloat = 32174 private var rowHeight: CGFloat = 54175 private(set) var glideLayout = GlideLayout(centers: [:], keyWidth: 32)176177 private struct Tracking {178 var key: Key179 var start: CGPoint180 var committedOnDown = false181 var showingAlternates = false182 var cursorMode = false183 var cursorAnchor: CGFloat = 0184 /// Raw points since the touch began on a letter, while a glide is still possible or under way.185 var path: [CGPoint] = []186 var travel: CGFloat = 0187 var gliding = false188 /// Leftward sweep from backspace: x of the last word boundary crossed, once the sweep has started.189 var sweepAnchor: CGFloat?190 }191192 private var tracking: [ObjectIdentifier: Tracking] = [:]193 private var longPressTimer: Timer?194 private var longPressTouch: ObjectIdentifier?195 private var deleteTimer: Timer?196 private var deleteRepeats = 0197198 static let longPressDelay = 0.38199 static let cursorStep: CGFloat = 9200 static let sweepStart: CGFloat = 18201 static let sweepStep: CGFloat = 24202 static let maxPathPoints = 600203204 override init(frame: CGRect) {205 super.init(frame: frame)206 isMultipleTouchEnabled = true207 isExclusiveTouch = false208 backgroundColor = .clear209 trail.fillColor = nil210 trail.lineCap = .round211 trail.lineJoin = .round212 trail.lineWidth = 5213 trail.opacity = 0214 layer.addSublayer(trail)215 addSubview(popup)216 }217218 @available(*, unavailable)219 required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }220221 // MARK: Configuration222223 func apply(theme: Theme) {224 self.theme = theme225 popup.apply(theme: theme)226 // The trail takes the accent of the theme, unless that would vanish on the backdrop.227 var stroke = theme.accentKey.fill.average.opacity(1)228 if stroke.contrast(with: theme.background.average.opacity(1)) < 1.6 { stroke = theme.suggestionText.opacity(1) }229 trail.strokeColor = stroke.opacity(0.7).cgColor230 for (id, view) in keyViews { view.apply(theme: theme, row: rowOfKey[id] ?? 0) }231 setNeedsLayout()232 }233234 /// Installs a layout, reusing key views whose identifiers did not change (a shift only swaps labels).235 func setLayout(_ newLayout: KeyboardLayout, shift: ShiftState) {236 shiftState = shift237 let oldIDs = Set(keyViews.keys)238 var rows: [String: Int] = [:]239 for (rowIndex, row) in newLayout.rows.enumerated() {240 for key in row { rows[key.id] = rowIndex }241 }242 let newIDs = Set(rows.keys)243 let structureChanged = oldIDs != newIDs || rows != rowOfKey || newLayout.rows.map({ $0.map(\.width) }) != layout.rows.map({ $0.map(\.width) })244 layout = newLayout245 rowOfKey = rows246 for id in oldIDs.subtracting(newIDs) {247 keyViews[id]?.removeFromSuperview()248 keyViews[id] = nil249 }250 for key in newLayout.keys {251 if let view = keyViews[key.id] {252 view.update(key: key)253 } else {254 let view = KeyView(key: key)255 view.apply(theme: theme, row: rows[key.id] ?? 0)256 let id = key.id257 view.onActivate = { [weak self] in self?.accessibilityActivate(keyID: id) }258 insertSubview(view, belowSubview: popup)259 keyViews[key.id] = view260 }261 keyViews[key.id]?.shiftState = shift262 }263 if structureChanged {264 cancelAllTouches()265 setNeedsLayout()266 }267 }268269 // MARK: Layout270271 override func layoutSubviews() {272 super.layoutSubviews()273 guard !layout.rows.isEmpty, bounds.width > 0, bounds.height > 0 else { return }274 let spacing = CGFloat(theme.metrics.spacing)275 let edge = spacing / 2276 let rowCount = CGFloat(layout.rows.count)277 rowHeight = bounds.height / rowCount278 unitWidth = (bounds.width - edge * 2) / CGFloat(layout.columns)279 // Rows sit further apart than keys do, as on the system keyboard: it is what makes a row readable.280 let rowGap = min(spacing * 1.75, rowHeight * 0.22)281 hitZones.removeAll(keepingCapacity: true)282 var centers: [Character: SIMD2<Double>] = [:]283 for (rowIndex, row) in layout.rows.enumerated() {284 let rowWidth = row.reduce(0) { $0 + CGFloat($1.width) } * unitWidth285 var x = edge + (bounds.width - edge * 2 - rowWidth) / 2286 let y = CGFloat(rowIndex) * rowHeight287 for (index, key) in row.enumerated() {288 let width = CGFloat(key.width) * unitWidth289 let cell = CGRect(x: x, y: y, width: width, height: rowHeight)290 keyViews[key.id]?.frame = cell.insetBy(dx: spacing / 2, dy: rowGap / 2)291 // The first and last keys of a row own the margin beside them.292 var zone = cell293 if index == 0 { zone = CGRect(x: 0, y: y, width: cell.maxX, height: rowHeight) }294 if index == row.count - 1 { zone = CGRect(x: zone.minX, y: y, width: bounds.width - zone.minX, height: rowHeight) }295 hitZones.append((zone, key.id))296 if isGlidable(key), let character = key.id.first {297 centers[character] = SIMD2(Double(cell.midX), Double(cell.midY))298 }299 x += width300 }301 }302 let newGlideLayout = GlideLayout(centers: centers, keyWidth: Double(unitWidth))303 // Kept identical while the geometry is: the decoder caches its index by layout.304 if newGlideLayout != glideLayout { glideLayout = newGlideLayout }305 trail.frame = bounds306 bringSubviewToFront(popup)307 }308309 private func zoneKey(at point: CGPoint) -> (key: Key, zone: CGRect)? {310 let clamped = CGPoint(x: min(max(point.x, 0), bounds.width - 0.5), y: min(max(point.y, 0), bounds.height - 0.5))311 guard let hit = hitZones.first(where: { $0.frame.contains(clamped) }), let key = keyViews[hit.id]?.key else { return nil }312 return (key, hit.frame)313 }314315 /// The key at `point`. With `adaptive`, a touch near the border of two letters goes to the likelier one.316 private func key(at point: CGPoint, adaptive: Bool = false) -> Key? {317 guard let (base, _) = zoneKey(at: point) else { return nil }318 guard adaptive, !keyWeights.isEmpty, isGlidable(base), let baseFrame = keyViews[base.id]?.frame else { return base }319 let cell = CGSize(width: unitWidth * CGFloat(base.width), height: rowHeight)320 var candidates: [TouchModel.Candidate] = []321 for key in layout.keys where isGlidable(key) {322 guard let frame = keyViews[key.id]?.frame, abs(frame.midX - point.x) < cell.width * 1.2, abs(frame.midY - point.y) < cell.height * 1.2 else { continue }323 candidates.append(TouchModel.Candidate(id: key.id, center: CGPoint(x: frame.midX, y: frame.midY)))324 }325 let chosen = TouchModel.resolve(point: point, base: TouchModel.Candidate(id: base.id, center: CGPoint(x: baseFrame.midX, y: baseFrame.midY)),326 cell: cell, candidates: candidates, weights: keyWeights)327 return keyViews[chosen]?.key ?? base328 }329330 func frameOfKey(id: String) -> CGRect? { keyViews[id]?.frame }331332 /// A letter key a word can be traced through.333 private func isGlidable(_ key: Key) -> Bool {334 guard case .character = key.action, key.role == .letter, key.id.count == 1, let character = key.id.first else { return false }335 return character.isLetter || character == "'"336 }337338 private func isSlidable(_ key: Key) -> Bool {339 if case .character = key.action { return true }340 return false341 }342343 private var isGliding: Bool { tracking.values.contains { $0.gliding } }344345 // MARK: Touches346347 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {348 for touch in touches {349 // A trace owns the surface until the finger lifts.350 guard !isGliding else { continue }351 let point = touch.location(in: self)352 guard let key = key(at: point, adaptive: true), !key.label.isEmpty || key.symbol != nil, key.isEnabled else { continue }353 // Rollover: a second finger commits what the first one is still holding.354 for (id, other) in tracking where !other.committedOnDown && !other.cursorMode {355 commit(other, touchID: id)356 tracking[id]?.committedOnDown = true357 tracking[id]?.path = []358 }359 var state = Tracking(key: key, start: point)360 keyViews[key.id]?.isPressed = true361 delegate?.surface(self, didPress: key)362 switch key.action {363 case .backspace:364 delegate?.surface(self, didCommit: key, alternate: nil)365 state.committedOnDown = true366 startDeleteRepeat()367 case .shift:368 delegate?.surface(self, didCommit: key, alternate: nil)369 state.committedOnDown = true370 default:371 if glideEnabled, isGlidable(key), tracking.isEmpty { state.path = [point] }372 showPreview(for: key)373 scheduleLongPress(for: touch, key: key)374 }375 tracking[ObjectIdentifier(touch)] = state376 }377 }378379 override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {380 for touch in touches {381 let id = ObjectIdentifier(touch)382 guard var state = tracking[id] else { continue }383 let point = touch.location(in: self)384 if state.gliding {385 extendPath(&state, with: touch, event: event)386 drawTrail(state.path)387 } else if state.showingAlternates {388 popup.select(popup.index(at: point.x))389 } else if state.cursorMode {390 let delta = point.x - state.cursorAnchor391 let steps = Int(delta / Self.cursorStep)392 if steps != 0 {393 delegate?.surface(self, moveCursorBy: steps)394 state.cursorAnchor += CGFloat(steps) * Self.cursorStep395 }396 } else if state.key.action == .backspace {397 sweep(&state, to: point)398 } else if state.key.action == .space, spaceCursorEnabled, !state.committedOnDown, abs(point.x - state.start.x) > 14 {399 beginCursorMode(&state, at: point)400 } else if !state.path.isEmpty, !state.committedOnDown {401 extendPath(&state, with: touch, event: event)402 // A trace starts once the finger has really left its key for another letter.403 if state.travel > unitWidth * 0.7, let moved = zoneKey(at: point)?.key, moved.id != state.key.id, isGlidable(moved), tracking.count == 1 {404 state.gliding = true405 keyViews[state.key.id]?.isPressed = false406 cancelLongPress()407 popup.hide()408 drawTrail(state.path)409 }410 } else if !state.committedOnDown, let moved = key(at: point), moved.id != state.key.id, isSlidable(state.key), isSlidable(moved) {411 // The finger slid to a neighbour before lifting: that neighbour is the intended key.412 keyViews[state.key.id]?.isPressed = false413 state.key = moved414 state.start = point415 keyViews[moved.id]?.isPressed = true416 showPreview(for: moved)417 scheduleLongPress(for: touch, key: moved)418 }419 tracking[id] = state420 }421 }422423 private func extendPath(_ state: inout Tracking, with touch: UITouch, event: UIEvent?) {424 // Coalesced touches give the full 120 Hz trace: corners are what the decoder reads.425 let touches = event?.coalescedTouches(for: touch) ?? [touch]426 for sample in touches {427 let point = sample.location(in: self)428 guard let last = state.path.last else { continue }429 let step = hypot(point.x - last.x, point.y - last.y)430 guard step >= 1.5, state.path.count < Self.maxPathPoints else { continue }431 state.path.append(point)432 state.travel += step433 }434 }435436 private func beginCursorMode(_ state: inout Tracking, at point: CGPoint) {437 state.cursorMode = true438 state.cursorAnchor = point.x439 keyViews[state.key.id]?.isPressed = false440 cancelLongPress()441 popup.hide()442 setLegendsDimmed(true)443 }444445 /// Sweeping left from backspace deletes whole words, one per step, instead of repeating.446 private func sweep(_ state: inout Tracking, to point: CGPoint) {447 if var anchor = state.sweepAnchor {448 while anchor - point.x >= Self.sweepStep {449 anchor -= Self.sweepStep450 delegate?.surfaceDidSwipeDeleteWord(self)451 }452 // Coming back to the right never restores text; it only moves the reference.453 if point.x > anchor { anchor = point.x }454 state.sweepAnchor = anchor455 } else if state.start.x - point.x >= Self.sweepStart {456 stopDeleteRepeat()457 state.sweepAnchor = point.x458 delegate?.surfaceDidSwipeDeleteWord(self)459 }460 }461462 override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {463 for touch in touches {464 let id = ObjectIdentifier(touch)465 guard let state = tracking[id] else { continue }466 finish(state, touchID: id, commitKey: true)467 }468 }469470 override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {471 for touch in touches {472 let id = ObjectIdentifier(touch)473 guard let state = tracking[id] else { continue }474 finish(state, touchID: id, commitKey: false)475 }476 }477478 private func finish(_ state: Tracking, touchID: ObjectIdentifier, commitKey: Bool) {479 if state.gliding {480 if commitKey, state.travel < unitWidth * 1.25, let last = state.path.last, let slipped = zoneKey(at: last)?.key, isGlidable(slipped) {481 // Too short to be a word: the finger slipped onto a neighbour, and that neighbour is the key meant.482 delegate?.surface(self, didCommit: slipped, alternate: nil)483 } else if commitKey {484 delegate?.surface(self, didGlide: state.path.map { SIMD2(Double($0.x), Double($0.y)) }, layout: glideLayout)485 }486 endGlideTrail(animated: commitKey)487 } else if commitKey, !state.committedOnDown, !state.cursorMode {488 commit(state, touchID: touchID)489 }490 tracking[touchID] = nil491 keyViews[state.key.id]?.isPressed = false492 if state.key.action == .backspace { stopDeleteRepeat() }493 if state.cursorMode { setLegendsDimmed(false) }494 if longPressTouch == touchID { cancelLongPress() }495 if tracking.values.allSatisfy({ !$0.showingAlternates }) { popup.hide() }496 if let remaining = tracking.values.first(where: { !$0.committedOnDown && !$0.cursorMode }) { showPreview(for: remaining.key) }497 }498499 private func commit(_ state: Tracking, touchID: ObjectIdentifier) {500 if state.showingAlternates {501 delegate?.surface(self, didCommit: state.key, alternate: popup.selectedOption)502 tracking[touchID]?.showingAlternates = false503 popup.hide()504 } else {505 delegate?.surface(self, didCommit: state.key, alternate: nil)506 }507 if longPressTouch == touchID { cancelLongPress() }508 }509510 // MARK: Glide trail511512 /// Draws the last stretch of the trace, comet-like: enough to see the gesture, never a scribble over the keys.513 private func drawTrail(_ points: [CGPoint]) {514 let tail = points.suffix(42)515 guard let first = tail.first else { return }516 let path = UIBezierPath()517 path.move(to: first)518 var previous = first519 for point in tail.dropFirst() {520 path.addQuadCurve(to: CGPoint(x: (previous.x + point.x) / 2, y: (previous.y + point.y) / 2), controlPoint: previous)521 previous = point522 }523 path.addLine(to: previous)524 CATransaction.begin()525 CATransaction.setDisableActions(true)526 trail.removeAllAnimations()527 trail.path = path.cgPath528 trail.opacity = 1529 CATransaction.commit()530 }531532 private func endGlideTrail(animated: Bool) {533 guard trail.opacity > 0 else { return }534 CATransaction.begin()535 CATransaction.setDisableActions(true)536 trail.opacity = 0537 CATransaction.commit()538 if animated, window != nil {539 let fade = CABasicAnimation(keyPath: "opacity")540 fade.fromValue = 1541 fade.toValue = 0542 fade.duration = 0.22543 trail.add(fade, forKey: "fade")544 }545 }546547 private func setLegendsDimmed(_ dimmed: Bool) {548 for view in keyViews.values { view.legendsDimmed = dimmed }549 }550551 // MARK: Preview and alternates552553 private func showPreview(for key: Key) {554 guard showsKeyPreview, case .character = key.action, key.role == .letter, key.label.count <= 2,555 let frame = keyViews[key.id]?.frame else {556 if tracking.values.allSatisfy({ !$0.showingAlternates }) { popup.hide() }557 return558 }559 popup.show(options: [key.label], above: frame, in: bounds.insetBy(dx: 0, dy: -44))560 }561562 private func scheduleLongPress(for touch: UITouch, key: Key) {563 cancelLongPress()564 guard !key.alternates.isEmpty || key.action == .nextLanguage || (key.action == .space && spaceCursorEnabled) else { return }565 let id = ObjectIdentifier(touch)566 longPressTouch = id567 let timer = Timer(timeInterval: Self.longPressDelay, repeats: false) { [weak self] _ in568 MainActor.assumeIsolated { self?.longPressFired(touchID: id) }569 }570 RunLoop.main.add(timer, forMode: .common)571 longPressTimer = timer572 }573574 private func longPressFired(touchID: ObjectIdentifier) {575 longPressTimer = nil576 guard var state = tracking[touchID], !state.committedOnDown, !state.cursorMode, !state.gliding else { return }577 if state.key.action == .nextLanguage {578 state.committedOnDown = true579 tracking[touchID] = state580 keyViews[state.key.id]?.isPressed = false581 delegate?.surfaceDidRequestLanguageMenu(self)582 return583 }584 if state.key.action == .space {585 // Holding the space bar turns the keyboard into a trackpad, without having to slide first.586 beginCursorMode(&state, at: state.path.last ?? state.start)587 tracking[touchID] = state588 delegate?.surface(self, didPress: state.key)589 return590 }591 guard let frame = keyViews[state.key.id]?.frame else { return }592 state.showingAlternates = true593 state.path = []594 tracking[touchID] = state595 popup.show(options: state.key.alternates, above: frame, in: bounds.insetBy(dx: 0, dy: -44))596 delegate?.surface(self, didPress: state.key)597 }598599 private func cancelLongPress() {600 longPressTimer?.invalidate()601 longPressTimer = nil602 longPressTouch = nil603 }604605 // MARK: Continuous delete606607 private func startDeleteRepeat() {608 stopDeleteRepeat()609 deleteRepeats = 0610 scheduleDelete(after: DeleteAcceleration.initialDelay)611 }612613 private func scheduleDelete(after delay: TimeInterval) {614 let timer = Timer(timeInterval: delay, repeats: false) { [weak self] _ in615 MainActor.assumeIsolated { self?.deleteTick() }616 }617 RunLoop.main.add(timer, forMode: .common)618 deleteTimer = timer619 }620621 private func deleteTick() {622 deleteTimer = nil623 // The timer only lives while a finger is on backspace and the surface is on screen.624 guard window != nil, tracking.values.contains(where: { $0.key.action == .backspace && $0.sweepAnchor == nil }) else { return }625 delegate?.surface(self, deleteRepeat: deleteRepeats)626 deleteRepeats += 1627 scheduleDelete(after: DeleteAcceleration.interval(forRepeat: deleteRepeats))628 }629630 func stopDeleteRepeat() {631 deleteTimer?.invalidate()632 deleteTimer = nil633 deleteRepeats = 0634 }635636 /// Drops every pending touch and timer: rotation, layout swap, keyboard dismissal, interruption.637 func cancelAllTouches() {638 stopDeleteRepeat()639 cancelLongPress()640 for state in tracking.values { keyViews[state.key.id]?.isPressed = false }641 tracking.removeAll()642 popup.hide()643 endGlideTrail(animated: false)644 setLegendsDimmed(false)645 }646647 override func willMove(toWindow newWindow: UIWindow?) {648 super.willMove(toWindow: newWindow)649 if newWindow == nil { cancelAllTouches() }650 }651652 // MARK: Accessibility653654 override var accessibilityElements: [Any]? {655 get { layout.keys.compactMap { keyViews[$0.id] } }656 set {}657 }658659 /// VoiceOver activates a key by double tap: route it like a commit.660 func accessibilityActivate(keyID: String) {661 guard let key = keyViews[keyID]?.key, key.isEnabled else { return }662 delegate?.surface(self, didCommit: key, alternate: nil)663 }664665 #if DEBUG666 /// Test hook: commits the key with this identifier as a tap would.667 func simulateTap(keyID: String) {668 guard let key = keyViews[keyID]?.key, key.isEnabled else { return }669 delegate?.surface(self, didPress: key)670 delegate?.surface(self, didCommit: key, alternate: nil)671 }672673 /// Test hook: the trace a finger would leave going through the centres of `word`'s letters.674 func simulateGlide(word: String) {675 layoutIfNeeded()676 var path: [SIMD2<Double>] = []677 for character in word.lowercased() {678 guard let center = glideLayout.centers[character] else { continue }679 if let last = path.last {680 for step in 1...8 { path.append(last + (center - last) * (Double(step) / 8)) }681 } else {682 path.append(center)683 }684 }685 guard path.count > 1 else { return }686 delegate?.surface(self, didGlide: path, layout: glideLayout)687 }688689 /// Screenshot hook: freezes the surface in a state that otherwise only exists under a finger.690 func debugShow(_ demo: String) {691 layoutIfNeeded()692 switch demo {693 case "popup":694 guard let view = keyViews["t"] else { return }695 view.isPressed = true696 popup.show(options: [view.key.label], above: view.frame, in: bounds.insetBy(dx: 0, dy: -44))697 case "alternates":698 guard let view = keyViews["e"] else { return }699 view.isPressed = true700 popup.show(options: view.key.alternates, above: view.frame, in: bounds.insetBy(dx: 0, dy: -44), selected: 2)701 case "glide":702 var points: [CGPoint] = []703 for character in "merci" {704 guard let center = glideLayout.centers[character] else { continue }705 let target = CGPoint(x: center.x, y: center.y)706 if let last = points.last {707 for step in 1...10 { points.append(CGPoint(x: last.x + (target.x - last.x) * CGFloat(step) / 10, y: last.y + (target.y - last.y) * CGFloat(step) / 10)) }708 } else {709 points.append(target)710 }711 }712 drawTrail(points)713 case "trackpad":714 setLegendsDimmed(true)715 default: break716 }717 }718719 /// Test hook: the key a touch at `point` resolves to.720 func debugKeyID(at point: CGPoint, adaptive: Bool) -> String? { key(at: point, adaptive: adaptive)?.id }721 #endif722}723