mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
* iOS keyboard: a failure from Hex shows for seconds, not forever, and the Hex key retries it X testers on build 56 and earlier: "The keyboard keeps either bringing me back to the app or telling me another app is using the microphone" (@itsjling) and "The another app is using audio message seems inaccurate cause it's showing for me all the time although it's working fine" (@RedaSjakur). Cause, reproduced on build 56 (2ef08aa4) in an iOS 27.2 simulator on the Mac Studio (no microphone input): Hex's dictation failed ("Hex couldn't start the microphone. Try again."), Hex was then closed, and a minute later the Hex keyboard's strip in Settings' search field still said so. Hex writes its snapshot only while it runs, so a failed snapshot (heartbeat 0, no time) stayed in the App Group, and KeyboardViewModel read any .failed snapshot as failed whatever its age. The code path is unchanged on origin/dev. With a warm session up it was worse: Hex stayed in .failed, consumeKeyboardCommand ignored every start unless the phase was .ready, and the full keyboard's Hex key (isWarm = Full Access && warm available) kept sending starts to it, so nothing recorded until Hex was opened. The keyboard's own failure snapshot also reads as available for its 6 s, so a Hex key tap right after an in-keyboard failure went to a warm session that doesn't exist. Now: - KeyboardSnapshot.messageAt: when Hex wrote the message (DictationController stamps a failure when its phase becomes failed, and keyboardMessage when set; the keyboard's own failure stamps its snapshot). The keyboard drops a message, and reads a failure as offline, 8 s after it (messageShownFor), and at once for a snapshot with no time (an earlier build's). Whether a warm session is up and any result stay as they were. - KeyboardViewModel.dictatesThroughHex (Full Access, warm available, not failed), used by the full keyboard's Hex key and its touch-down capture: after a failure both keyboards dictate in the keyboard, as the Dictation bar already did. - Hex takes a keyboard start while failed when the failure was the microphone for a keyboard dictation with the model loaded (captureFailed): the next Hex key is its Try again. Model failures still wait for Hex to get ready again. Not changed: the 32 MB memory threshold and keyboardNeedsHex, the two ways the Hex key opens Hex. In the simulator the handoffs logged "speech model missing here" after the keyboard's own asset check failed ("anomaly.hex.mobile.keyboard is not subscribed to assistant.en_US") on a sim whose Hex had never installed a model, which is the intended path; a device's reason needs its probe log. Verified: new KeyboardBridgeTests.testAFailureHexWroteAWhileAgoIsOver and DictationControllerTests.testAWarmSessionsMicrophoneFailureIsRetriedFromTheKeyboard; KeyboardBridgeTests and DictationControllerTests pass (79 tests, 0 failures, iPhone 17 Pro iOS 27.2 simulator). In the simulator with this build, the same failure no longer shows in the keyboard a minute later. * iOS keyboard: the Hex key's audio session calls leave the main thread X tester @leeladhar (iPhone 16 Pro Max, build 56 or earlier): "the keyboard freezes while using apps sometimes ... the only way to close the keyboard is to close the app completely". Not reproduced in the iOS 27.2 simulator on build 56 (2ef08aa4) or origin/dev: 24 host visits (Messages, Contacts, Settings search) with typing, the Hex key and globe switches kept one keyboard process, no crash or hang report, footprint 29-40 MB with no growth. The device cause isn't confirmed. The likeliest one left on origin/dev is the last synchronous audio server round trips on the keyboard's main thread: every Hex key touch-down set the session's category, read and preferred its inputs (KeyboardLocalDictation.microphone(for:)), asked isOtherAudioPlaying, and read the Speech Recognition status for the probe log, all before the page could start. These wait on the audio server (and TCC) with no timeout; a build 56 crash report from TestFlight shows Hex's own main thread parked in such a call (setPreferredSampleRate waiting on SetBatchProperties). #2185 moved the one on the launch path for the same reason. While blocked, no key, Done or globe responds, and the keyboard can't dismiss. Now begin() runs those on the keyboard's audio session queue (after any earlier capture's release there) and starts the page when they return, unless the job was dropped, stopped or replaced meanwhile. Done before the page was asked to start ends quietly at once instead of leaving the page to start a capture nobody wants. Verified: builds clean; in an iPhone 17 Pro iOS 27.2 simulator (WebKit's mock audio device) the Hex key's touch-down capture still starts and is kept: "first audio +124 ms after touch-down (... getUserMedia +83 ...)", 13.5 s recorded as 643,072 frames at 48 kHz (no gap), then transcription as before. * iOS keyboard: the capture page resumes an audio context iOS suspended mid-dictation TestFlight tester on X (iPhone 13 Pro Max, iOS 27, build 56 or earlier): "in progress recording dropped when I took a screenshot". What a screenshot does to an in-keyboard dictation, in an iPhone 17 Pro iOS 27.2 simulator on the Mac Studio (WebKit's mock audio device records there): - The host only going inactive doesn't stop it: with Control Center pulled down for 4 s mid-dictation the page kept sending audio (700,416 frames at 48 kHz over a 14.8 s recording, no gap). - A screenshot taken with Cmd-Shift-3 hid the keyboard and the probe log said "keyboard hidden while recording: finishing with what was said" at the shutter. The simulator can only take one through its hardware keyboard, which also turns on keyboard minimization, so it doesn't show which of the two hid it. On an iPhone, iOS 26 and 27 open the screenshot's full-screen preview over the app, and a keyboard that hides is torn down and its WebKit processes suspended, so a dictation can't keep recording through that. - On build 56 a keyboard hidden mid-recording lost the dictation: viewWillDisappear only dropped a touch-down capture, and the recording went with the view controller (reproduced in #2163). Since #2163 on origin/dev it stops, keeps what was said, and the text goes into the same field when the keyboard comes back within 30 s, else is offered as Paste dictation. The one way left for a capture to end early with the keyboard still up is the page's audio context: iOS may suspend or interrupt it for other audio and the page never resumed it, so no more audio came and the 6 s watchdog ended the dictation. The page now resumes a context that isn't running every 250 ms while it records, and stops trying when the capture stops. Not changed: a keyboard hidden by a screenshot's preview still ends the recording (with its text kept, as above). Verified: builds clean; in the simulator the touch-down capture still starts and records through Control Center with no gap (numbers above). * iOS: a spoken count reads "Test 1, 2, 3." on every speech model TestFlight (@kevin_miller, Nov 20, build 56 =2ef08aa4): "Test 1, 2, 3" came out "Test three." / "Test 3" from the keyboard's in-keyboard dictation and "test 123" in the app's Dictate box. What each speech model writes (macOS 27.2.1 on the Mac Studio, `say` clips, 4 voices): Apple's SpeechTranscriber (in-keyboard dictation) writes "Test one, 2, 3.", "Test, one, two, three.", "Testing 123.", "Counting one, two, three, four."; DictationTranscriber writes "Test 123", "Counting 1234"; Parakeet v2 through FluidAudio 0.15.5 (the app) writes "Test 1, 2, 3", "Testing 123" (no pauses), "1, 2, 3, testing". Responsible steps: - "Test three." / "Test 3": at build 56 Clean up what I say deleted every word over P(DELETE) 0.98 with no guard. The real Core ML model gives the count words but the last 0.97-0.999 ("Test one two three." -> "Test three.", "Test 1, 2, 3." -> "Test 1, 3."): it reads a count as a self-correction. CleanupGuard (#2132, after build 56) already keeps every count on origin/dev; this commit adds tests that pin it. - "test 123": Parakeet and DictationTranscriber write "123" themselves; no Hex step merges digits. Apple Intelligence's cleanup (same prompt, macOS 27.2 model) kept "Test 1, 2, 3." in 3 of 3 runs per input. - The paths still disagreed on origin/dev: the keyboard inserted "Test one, 2, 3." where the app inserted "Test 1, 2, 3.". Change: SpokenCleanupRules.spokenCounts, run by CleanupTagger.cleanIfEnabled right after spoken symbols (every style but Verbatim, English, Clean up what I say on or off, before the tagger, in the app and in-keyboard dictation), writes a count in digits: three numbers or more counting up from one, in words or digits, with only a comma or a space between them ("one, 2, 3", "one two three" -> "1, 2, 3"), and "123"... right after "test"/"testing" when it ends its clause ("Test 123" -> "Test 1, 2, 3"; "test 123 passed", "room 123", "Counting 1234" stay). Decision: the "123" split is limited to test/testing because a bare "123" is usually a real number. Format lists already never makes a list of a count (each item would be empty); tests prove it. README gains the Spoken counts paragraph. Verified on the iOS 27.2 simulator (Mac Studio), real Core ML tagger: TranscriptCleanupGuardTests 9, CleanupGuardTests 6, SpokenCleanupRulesTests 19, HinglishRomanizerTests 7, SpokenListsTests 10, InformalContractionTests 4, FrenchSpacingTests 3, CleanupTaggerTests 15, DictationControllerTests 50: 123 tests, 0 failures. New: testSpokenCountsBecomeDigits, testOtherNumbersStayAsSaid, testCountsAreNoList, testCountsKeepEveryNumberFromEverySpeechModel (also shows the guardless tagger's "Test three."), testACountReadsTheSameFromTheAppAndTheKeyboard (app with Parakeet's text vs keyboard with both Apple modules' text, every style, Lowercase).
1252 lines
53 KiB
Swift
1252 lines
53 KiB
Swift
import Combine
|
||
import UIKit
|
||
|
||
/// The experimental full keyboard: a 3-slot suggestion strip, QWERTY keys with the Hex key
|
||
/// right of space, long-press accents, and the recording panel that replaces both while Hex records.
|
||
/// Dictation state comes from the same `KeyboardViewModel` the dictation bar uses.
|
||
@MainActor
|
||
final class FullKeyboardView: UIView {
|
||
let model: KeyboardViewModel
|
||
let engine: FullKeyboardEngine
|
||
weak var hostController: UIInputViewController? {
|
||
didSet { configureGlobe() }
|
||
}
|
||
|
||
/// Fixtures force light or dark and portrait or landscape; the keyboard follows its field.
|
||
var appearanceOverride: Bool? { didSet { applyAppearance() } }
|
||
var orientationOverride: KeyboardOrientation? { didSet { setNeedsLayout() } }
|
||
/// Haptics need Full Access.
|
||
var allowsHaptics: () -> Bool = { false }
|
||
/// Draws a stand-in backdrop where there is no system keyboard behind the view.
|
||
var drawsBackdrop = false { didSet { applyAppearance() } }
|
||
/// The keys typed, deleted, or pasted something (Learn how I type follows dictations).
|
||
var onTextEdit: (() -> Void)?
|
||
/// Undo dictation took the last dictation back.
|
||
var onUndoDictation: (() -> Void)?
|
||
/// The return key is about to type its line break.
|
||
var onReturnKey: (() -> Void)?
|
||
|
||
let stripView = KeyboardStripView()
|
||
/// The keys' touch surface; tests feed it touch samples.
|
||
let plane: KeyboardKeyPlaneView
|
||
let callout = KeyCalloutView()
|
||
let accentCallout = AccentCalloutView()
|
||
let hexKey = HexKeyControl()
|
||
let globeButton = UIButton(type: .custom)
|
||
/// The capsule that grows from the Hex mark across the strip into the recording bar.
|
||
private let morph = UIView()
|
||
private var recordingPanel: HexKeyRecordingPanel?
|
||
private var styleMenu: HexStyleMenuView?
|
||
private(set) var palette = FullKeyboardPalette(isDark: false)
|
||
private var didApplyPalette = false
|
||
private var subscriptions: Set<AnyCancellable> = []
|
||
private(set) var showsRecording = false
|
||
/// The Hex key's last tap or hold started a dictation here (not by opening Hex).
|
||
private var dictatingFromHexKey = false
|
||
private var lastDictation: String?
|
||
private var undoHideWork: DispatchWorkItem?
|
||
/// The Hex key was tapped without Full Access: the strip says what dictation needs.
|
||
private(set) var showsFullAccessHint = false
|
||
private var fullAccessHintHideWork: DispatchWorkItem?
|
||
/// How long the Full Access hint stays unless a key or the strip is used first.
|
||
static let fullAccessHintDuration: TimeInterval = 8
|
||
private let haptics = UIImpactFeedbackGenerator(style: .light)
|
||
/// Every key's touch-down tick (letters, space, delete and its repeats, shift, 123,
|
||
/// return, suggestions), as hard as Settings › Keyboard › Strength asks. The Hex key's hold
|
||
/// and its menu keep `haptics`' fuller thud.
|
||
var hapticStrength: KeyHapticStrength = .medium {
|
||
didSet {
|
||
guard hapticStrength != oldValue else { return }
|
||
keyTicks = UIImpactFeedbackGenerator(style: Self.keyTickStyle(hapticStrength))
|
||
if allowsHaptics() { keyTicks.prepare() }
|
||
}
|
||
}
|
||
private var keyTicks = UIImpactFeedbackGenerator(style: FullKeyboardView.keyTickStyle(.medium))
|
||
|
||
/// Apple's key haptic is a crisp tick, so every strength is a rigid impact (the sharpest
|
||
/// style) but Strong, a fuller medium one. Medium, the default, is 0.8 of a rigid tap;
|
||
/// Hex's was a 0.65 light impact, which testers found much weaker than Apple's.
|
||
static func keyTickStyle(_ strength: KeyHapticStrength) -> UIImpactFeedbackGenerator.FeedbackStyle {
|
||
strength == .strong ? .medium : .rigid
|
||
}
|
||
|
||
static func keyTickIntensity(_ strength: KeyHapticStrength) -> CGFloat {
|
||
switch strength {
|
||
case .light: 0.5
|
||
case .medium: 0.8
|
||
case .strong: 1
|
||
}
|
||
}
|
||
private let selectionHaptics = UISelectionFeedbackGenerator()
|
||
private let clipboard = KeyboardClipboardTracker()
|
||
/// What the strip's Paste chip offers now.
|
||
private var stripOffer: KeyboardClipboardOffer?
|
||
/// A paste iOS asked about or refused: the strip points to the setting that stops it.
|
||
private var showsAllowPasteHint = false
|
||
private var allowPasteHintHideWork: DispatchWorkItem?
|
||
static let allowPasteHintDuration: TimeInterval = 8
|
||
|
||
// MARK: Emoji (Settings › Keyboard › Emoji; FullKeyboardView+Emoji.swift)
|
||
|
||
/// The keys' target: the field, or the emoji search while you search.
|
||
let routedTarget: EmojiRoutedTarget
|
||
/// Fixtures turn the emoji experiment on or off; otherwise the App Group's switch.
|
||
var emojiOverride: Bool? { didSet { refreshEmojiKey() } }
|
||
/// Where emoji use is kept; fixtures give a seeded store.
|
||
var makeEmojiUsage: () -> EmojiUsageStore = { EmojiUsageStore() }
|
||
var emojiLibrary: EmojiLibrary?
|
||
var emojiPanel: EmojiPanelView?
|
||
var emojiSearchField: EmojiSearchField?
|
||
var emojiResults: EmojiRowView?
|
||
var emojiResultEntries: [Int] = []
|
||
var emojiSearchLift: CGFloat = 0
|
||
/// Record typing logs, held back while you type a search.
|
||
var suspendedTypingLog: TypingLogger?
|
||
/// From the emoji key to the panel's suggestions laid out, for probes.
|
||
var lastEmojiPanelLatency: TimeInterval?
|
||
|
||
/// Exposed so unit tests can verify lazy allocation and teardown of the Metal recording panel.
|
||
var hasAllocatedRecordingPanel: Bool { recordingPanel != nil }
|
||
|
||
init(model: KeyboardViewModel, target: KeyboardTextTarget, autocorrect: AutocorrectEngine? = nil) {
|
||
self.model = model
|
||
routedTarget = EmojiRoutedTarget(document: target)
|
||
engine = FullKeyboardEngine(target: routedTarget, autocorrect: autocorrect)
|
||
plane = KeyboardKeyPlaneView(engine: engine)
|
||
super.init(frame: .zero)
|
||
backgroundColor = .clear
|
||
|
||
addSubview(stripView)
|
||
morph.isUserInteractionEnabled = false
|
||
morph.isHidden = true
|
||
addSubview(morph)
|
||
addSubview(plane)
|
||
addSubview(hexKey)
|
||
addSubview(globeButton)
|
||
addSubview(callout)
|
||
addSubview(accentCallout)
|
||
accentCallout.isHidden = true
|
||
|
||
stripView.onSelectSuggestion = { [weak self] suggestion in
|
||
guard let self else { return }
|
||
self.keyFeedback()
|
||
if suggestion.kind == .emoji {
|
||
self.recordEmojiUse(suggestion.replacement)
|
||
}
|
||
self.engine.acceptSuggestion(suggestion)
|
||
}
|
||
stripView.onUndoDictation = { [weak self] in self?.undoDictation() }
|
||
stripView.onPaste = { [weak self] in self?.pasteFromClipboard() }
|
||
stripView.onOpenHexFromHint = { [weak self] in self?.openSetupFromHint() }
|
||
stripView.onOpenNotice = { [weak self] in
|
||
self?.keyFeedback()
|
||
self?.model.onOpenURL?(KeyboardLaunchRequest.translationSettings.url)
|
||
}
|
||
stripView.onNextKeyboard = { [weak self] in
|
||
self?.typingLog?.ui("next_keyboard")
|
||
self?.hostController?.advanceToNextInputMode()
|
||
}
|
||
|
||
globeButton.accessibilityLabel = "Next keyboard"
|
||
globeButton.isAccessibilityElement = true
|
||
globeButton.addTarget(self, action: #selector(globeTapped), for: .touchUpInside)
|
||
|
||
hexKey.onPress = { [weak self] at in self?.model.onHexKeyPress?(at) }
|
||
hexKey.onPressAbandoned = { [weak self] in self?.model.onHexKeyAbandon?() }
|
||
hexKey.onHold = { [weak self] in self?.hexKeyHeld() }
|
||
hexKey.onHoldRelease = { [weak self] in self?.hexKeyReleased() }
|
||
hexKey.onMenuOpen = { [weak self] point in
|
||
guard let self else { return }
|
||
// Styles and languages are for dictation, which needs Full Access.
|
||
guard self.model.hasFullAccess else {
|
||
self.showFullAccessHint()
|
||
return
|
||
}
|
||
self.typingLog?.ui("hex_menu")
|
||
self.showStyleMenu()
|
||
self.forwardMenuPoint(point, release: false)
|
||
}
|
||
hexKey.onMenuDrag = { [weak self] point in self?.forwardMenuPoint(point, release: false) }
|
||
hexKey.onMenuRelease = { [weak self] point in self?.forwardMenuPoint(point, release: true) }
|
||
|
||
plane.onKeyDown = { [weak self] _ in self?.keyFeedback() }
|
||
plane.onAccentMenuOpened = { [weak self] in self?.selectionFeedback() }
|
||
engine.onSelectionStep = { [weak self] in self?.selectionFeedback() }
|
||
engine.onChange = { [weak self] in self?.engineChanged() }
|
||
engine.onEdit = { [weak self] in
|
||
guard let self else { return }
|
||
if self.routedTarget.isSearching {
|
||
self.refreshEmojiSearch()
|
||
return
|
||
}
|
||
self.hideUndo()
|
||
self.hideFullAccessHint()
|
||
self.hideAllowPasteHint()
|
||
self.refreshReturnKey()
|
||
self.refreshStrip()
|
||
self.onTextEdit?()
|
||
}
|
||
engine.onReturn = { [weak self] in
|
||
guard self?.routedTarget.isSearching == false else { return }
|
||
self?.onReturnKey?()
|
||
}
|
||
engine.onEmojiKey = { [weak self] in self?.emojiKeyTapped() }
|
||
engine.onLanguageSwipe = { [weak self] step in self?.switchLanguage(by: step) }
|
||
routedTarget.onSearchReturn = { [weak self] in self?.endEmojiSearch() }
|
||
|
||
model.objectWillChange
|
||
.receive(on: RunLoop.main)
|
||
.sink { [weak self] _ in self?.refreshFromModel() }
|
||
.store(in: &subscriptions)
|
||
|
||
registerForTraitChanges([UITraitUserInterfaceStyle.self, UITraitVerticalSizeClass.self]) { (view: FullKeyboardView, _) in
|
||
view.applyAppearance()
|
||
view.setNeedsLayout()
|
||
}
|
||
|
||
engine.autocorrect.isEnabled = FullKeyboardSettings().autocorrect
|
||
engine.autocorrect.allowsSwearing = FullKeyboardSettings().suggestSwearWords
|
||
engine.autoCapitalizes = FullKeyboardSettings().autoCapitalization
|
||
engine.showsKeyPopups = FullKeyboardSettings().keyPopups
|
||
syncHexPlacement()
|
||
refreshEmojiKey()
|
||
syncSpatialAutocorrect()
|
||
refreshLanguageSignals()
|
||
syncLanguage()
|
||
syncSwipeTyping()
|
||
engine.configureForField()
|
||
applyAppearance()
|
||
refreshFromModel()
|
||
}
|
||
|
||
@available(*, unavailable)
|
||
required init?(coder: NSCoder) { fatalError() }
|
||
|
||
// MARK: - Typing logs
|
||
|
||
/// Record typing logs (Experiments): set by the keyboard while a session may be logged,
|
||
/// nil otherwise. The app's fixtures never set it.
|
||
var typingLog: TypingLogger? {
|
||
get { routedTarget.isSearching ? suspendedTypingLog : engine.typingLog }
|
||
set {
|
||
if routedTarget.isSearching {
|
||
suspendedTypingLog = newValue
|
||
} else {
|
||
engine.typingLog = newValue
|
||
}
|
||
}
|
||
}
|
||
|
||
/// A typing log session began: write the layout, shift, and suggestions as they are now.
|
||
func typingLogSessionBegan() {
|
||
guard let log = engine.typingLog else { return }
|
||
log.viewGeometry(size: bounds.size, safeArea: safeAreaInsets)
|
||
engine.logState("session")
|
||
log.commitGeometry()
|
||
log.suggestionsChanged(engine.suggestions)
|
||
}
|
||
|
||
@objc private func globeTapped() {
|
||
typingLog?.ui("globe")
|
||
}
|
||
|
||
// MARK: - Size
|
||
|
||
static func orientation(for traits: UITraitCollection) -> KeyboardOrientation {
|
||
traits.verticalSizeClass == .compact ? .landscape : .portrait
|
||
}
|
||
|
||
var orientation: KeyboardOrientation {
|
||
orientationOverride ?? Self.orientation(for: traitCollection)
|
||
}
|
||
|
||
var preferredHeight: CGFloat {
|
||
KeyboardLayout.height(for: orientation, posture: engine.posture, phoneSize: engine.phoneSize) + lift
|
||
}
|
||
|
||
/// Room above the strip for the emoji search results. The strip itself keeps its height in
|
||
/// every state, the recording bar's included.
|
||
private var lift: CGFloat { emojiSearchLift }
|
||
|
||
/// Asks the host to apply `preferredHeight` now (the keyboard extension resizes itself).
|
||
var onPreferredHeightChange: (() -> Void)?
|
||
|
||
/// How much of the lift the view actually has yet, so nothing jumps before the host grows it.
|
||
private var appliedLift: CGFloat {
|
||
max(0, min(lift, bounds.height - KeyboardLayout.height(for: orientation, posture: engine.posture, phoneSize: engine.phoneSize)))
|
||
}
|
||
|
||
/// Reads which device and posture the keyboard is on, and how far iOS set it in from the
|
||
/// screen's sides, from its window. The Duo's unfolded screen has regular size classes either
|
||
/// way up, so the size classes alone can't tell its postures apart.
|
||
private func syncPosture() {
|
||
guard let screen = window?.windowScene?.screen ?? window?.screen else { return }
|
||
let size = screen.bounds.size
|
||
let posture = KeyboardPosture.current(screenSize: size, isFoldable: Self.isFoldable)
|
||
let inset = posture == .phone ? 0 : max(0, (size.width - bounds.width) / 2)
|
||
let phoneSize = KeyboardPhoneSize.current(screenSize: size)
|
||
let heightChanges = posture != engine.posture || phoneSize != engine.phoneSize
|
||
engine.posture = posture
|
||
engine.phoneSize = phoneSize
|
||
engine.windowInset = inset
|
||
if heightChanges { onPreferredHeightChange?() }
|
||
}
|
||
|
||
/// The iPhone Duo (`KeyboardPosture.foldableModels`), read once per process.
|
||
static let isFoldable: Bool = {
|
||
if let simulated = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] {
|
||
return KeyboardPosture.foldableModels.contains(simulated)
|
||
}
|
||
var system = utsname()
|
||
uname(&system)
|
||
let model = withUnsafeBytes(of: &system.machine) { raw in
|
||
String(decoding: raw.prefix { $0 != 0 }, as: UTF8.self)
|
||
}
|
||
return KeyboardPosture.foldableModels.contains(model)
|
||
}()
|
||
|
||
// MARK: - Host events
|
||
|
||
func warmUpTextCheckerAsync() {
|
||
DispatchQueue.main.async { [weak self] in
|
||
guard let self, let checker = self.engine.autocorrect.checker as? SystemTextChecker else { return }
|
||
checker.warmUp()
|
||
// German's capitalisation list reads with the dictionary, off the open path, and only
|
||
// while the German model is on: the dictionary engine never asks for it.
|
||
if self.engine.language == .german, self.engine.letterOdds != nil,
|
||
self.engine.autocorrect.germanCapitals == nil {
|
||
self.engine.autocorrect.germanCapitals = GermanCapitals.bundled()
|
||
}
|
||
self.engine.refreshSuggestions()
|
||
}
|
||
}
|
||
|
||
func loadLexicon(_ lexicon: UILexicon) {
|
||
engine.autocorrect.loadLexicon(lexicon)
|
||
engine.refreshSuggestions()
|
||
}
|
||
|
||
// MARK: - Language
|
||
|
||
/// Fixtures pin one layout; otherwise Settings › Keyboard › Languages, whose Automatic
|
||
/// follows the dictation language.
|
||
var languageOverride: KeyboardLanguage? {
|
||
didSet { syncLanguage() }
|
||
}
|
||
|
||
/// Fixtures pin how the letters are arranged; otherwise Settings › Keyboard › Languages ›
|
||
/// Layout for the keys' language. Without the App Group (an iPhone that keeps it from a
|
||
/// keyboard without Full Access) every language types on its own layout, as before.
|
||
var letterLayoutOverride: KeyboardLetterLayout? {
|
||
didSet { syncLanguage() }
|
||
}
|
||
|
||
/// Where Languages and the language last switched to are kept; tests give their own.
|
||
var languageSettings = LanguageSettings() {
|
||
didSet { syncLanguage() }
|
||
}
|
||
|
||
/// The languages the space bar switches between and the one typing now.
|
||
private(set) var languages = KeyboardLanguageList(languages: [.english], current: .english)
|
||
/// The language this keyboard last switched to, ahead of the App Group's copy, which an
|
||
/// iPhone may not let a keyboard without Full Access write.
|
||
private var switchedLanguage: KeyboardLanguage?
|
||
private static let spellCheckLanguages = UITextChecker.availableLanguages
|
||
|
||
/// The iPhone's keyboards and preferred languages, read when the keyboard appears, for
|
||
/// Automatic before any dictation language is known.
|
||
private var inputModeLanguages: [String] = []
|
||
private var preferredLanguages: [String] = []
|
||
|
||
private func refreshLanguageSignals() {
|
||
inputModeLanguages = UITextInputMode.activeInputModes.compactMap(\.primaryLanguage)
|
||
preferredLanguages = Locale.preferredLanguages
|
||
}
|
||
|
||
private func syncLanguage() {
|
||
let settings = languageSettings
|
||
let list = if let languageOverride {
|
||
KeyboardLanguageList(languages: [languageOverride], current: languageOverride)
|
||
} else {
|
||
KeyboardLanguageList.resolve(
|
||
chosen: settings.keyboardLanguages,
|
||
stored: switchedLanguage ?? settings.currentKeyboardLanguage,
|
||
automatic: KeyboardLanguage.automatic(
|
||
dictationLanguage: settings.effectiveDictationLanguage,
|
||
inputModes: inputModeLanguages,
|
||
preferredLanguages: preferredLanguages
|
||
)
|
||
)
|
||
}
|
||
// The keys' language's layout: with English and Spanish on one keyboard, the first one's.
|
||
let letters = letterLayoutOverride.map(list.layout.offered) ?? settings.letterLayout(for: list.layout)
|
||
guard list != languages || engine.language != list.current || engine.letterLayout != letters else { return }
|
||
languages = list
|
||
engine.switchesLanguage = list.switches
|
||
engine.layoutLanguage = list.layout == list.current ? nil : list.layout
|
||
engine.letterLayout = letters
|
||
engine.language = list.current
|
||
engine.partnerLanguage = list.partner(available: Self.spellCheckLanguages)
|
||
syncSpatialAutocorrect()
|
||
refreshSpaceLabel()
|
||
syncSwipeTyping()
|
||
setNeedsLayout()
|
||
}
|
||
|
||
/// A swipe along the space bar: the next or previous language (its letters, accents and
|
||
/// autocorrect), kept for next time. Dictation on Automatic follows it
|
||
/// (`LanguageSettings.keyboardDictationLanguage`); with Switch dictation too, a dictation
|
||
/// language picked by hand goes back to Automatic, so it follows too.
|
||
func switchLanguage(by step: Int) {
|
||
guard languages.switches, languageOverride == nil else { return }
|
||
let next = languages.switched(by: step)
|
||
typingLog?.ui("keyboard_language", [TypingLogField("language", .string(next.rawValue))])
|
||
switchedLanguage = next
|
||
languageSettings.currentKeyboardLanguage = next
|
||
selectionFeedback()
|
||
syncLanguage()
|
||
guard languageSettings.dictationFollowsKeyboard, model.hasFullAccess,
|
||
languageSettings.dictationLanguage != nil else { return }
|
||
model.onLanguageSelected?(nil)
|
||
}
|
||
|
||
/// With two or more languages the space bar names the keyboard's; otherwise, with Full
|
||
/// Access, the dictation language's.
|
||
private func refreshSpaceLabel() {
|
||
plane.spaceLabel = languages.spaceLabel ?? (model.hasFullAccess ? model.languageSummary : nil)
|
||
}
|
||
|
||
func syncSettings() {
|
||
syncLanguage()
|
||
// Learn each language separately: each keyboard language's own learned words, and the
|
||
// partner's own; Learn how I type's journal filters its fixes the same way.
|
||
let learnsPerLanguage = TypingJournalSettings().learnsPerLanguage
|
||
if engine.autocorrect.learnsPerLanguage != learnsPerLanguage {
|
||
engine.autocorrect.learnsPerLanguage = learnsPerLanguage
|
||
engine.refreshSuggestions()
|
||
}
|
||
let journal = TypingJournal.sharedIfEnabled()
|
||
if engine.journal !== journal {
|
||
engine.journal = journal
|
||
}
|
||
// Adaptive touch keeps its averages on disk only with Full Access; without, in memory.
|
||
let adaptive = AdaptiveTouch.sharedIfEnabled(persistent: hostController?.hasFullAccess == true)
|
||
if engine.adaptiveTouch !== adaptive {
|
||
engine.adaptiveTouch = adaptive
|
||
}
|
||
engine.showsKeyPopups = FullKeyboardSettings().keyPopups
|
||
engine.autoCapitalizes = FullKeyboardSettings().autoCapitalization
|
||
hapticStrength = FullKeyboardSettings().hapticStrength
|
||
syncHexPlacement()
|
||
refreshEmojiKey()
|
||
let wantsAutocorrect = FullKeyboardSettings().autocorrect
|
||
if engine.autocorrect.isEnabled != wantsAutocorrect {
|
||
engine.autocorrect.isEnabled = wantsAutocorrect
|
||
engine.refreshSuggestions()
|
||
}
|
||
let wantsSwearing = FullKeyboardSettings().suggestSwearWords
|
||
if engine.autocorrect.allowsSwearing != wantsSwearing {
|
||
engine.autocorrect.allowsSwearing = wantsSwearing
|
||
engine.refreshSuggestions()
|
||
}
|
||
syncSpatialAutocorrect()
|
||
syncSwipeTyping()
|
||
}
|
||
|
||
/// Fixtures pin where the Hex key sits; otherwise Settings › Keyboard › Hex key.
|
||
var hexPlacementOverride: HexKeyPlacement? { didSet { syncHexPlacement() } }
|
||
|
||
/// Settings › Keyboard › Hex key: Right (the strip's trailing end) or Left (its leading
|
||
/// end), kept in `HexKeyPlacement.current` too for typing logs.
|
||
private func syncHexPlacement() {
|
||
let placement = hexPlacementOverride ?? FullKeyboardSettings().hexKeyPlacement
|
||
HexKeyPlacement.current = placement
|
||
guard engine.hexPlacement != placement else { return }
|
||
plane.cancelAllTouches()
|
||
dismissStyleMenu()
|
||
engine.hexPlacement = placement
|
||
setNeedsLayout()
|
||
}
|
||
|
||
/// Fixtures and tests turn Swipe typing on or off; otherwise its switch in Settings › Keyboard.
|
||
var swipeOverride: Bool? { didSet { syncSwipeTyping() } }
|
||
|
||
/// Settings › Keyboard › Swipe typing (on by default): on the English and Spanish layouts, a
|
||
/// drag across the letters types a word, read with the layout language's bundled model.
|
||
/// Off under VoiceOver, which has its own way to type. German stays out of it:
|
||
/// `supportsSwipeTyping` lists English and Spanish only, and the experiment does not add it.
|
||
private func syncSwipeTyping() {
|
||
let settings = FullKeyboardSettings()
|
||
let on = (swipeOverride ?? settings.swipeTyping) && engine.language.supportsSwipeTyping
|
||
&& !UIAccessibility.isVoiceOverRunning
|
||
let model = on ? settings.typingModel(for: engine.language) : nil
|
||
if plane.swipe?.model !== model {
|
||
plane.swipe = model.map { SwipeTyping(engine: engine, model: $0) }
|
||
} else {
|
||
plane.swipe?.syncWords()
|
||
}
|
||
}
|
||
|
||
/// Settings › Keyboard › Spatial autocorrect (on by default): maps the layout language's
|
||
/// bundled model when the keyboard opens (English, Spanish, and German while its experiment
|
||
/// in Settings › Experiments is on; others keep `UITextChecker`), and moves the keys'
|
||
/// centres to where Learn how I type saw you tap. The same word list lets the likely next
|
||
/// letter claim a few points of its neighbour's touch target whether or not Spatial
|
||
/// autocorrect is on (`FullKeyboardEngine.letterOdds`; only while autocorrecting).
|
||
private func syncSpatialAutocorrect() {
|
||
let settings = FullKeyboardSettings()
|
||
let words = settings.typingModel(for: engine.language)
|
||
if engine.letterOdds !== words {
|
||
engine.letterOdds = words
|
||
}
|
||
let model = settings.spatialAutocorrect ? words : nil
|
||
if engine.autocorrect.decoder?.model !== model {
|
||
engine.autocorrect.decoder = model.map { TypingDecoder(model: $0) }
|
||
engine.refreshSuggestions()
|
||
}
|
||
// Bilingual autocorrect reads the same taps with the other language's model, where it has one.
|
||
if let partner = engine.autocorrect.partner {
|
||
let theirs = settings.spatialAutocorrect ? settings.typingModel(for: partner.language) : nil
|
||
if partner.decoder?.model !== theirs {
|
||
partner.decoder = theirs.map { TypingDecoder(model: $0) }
|
||
engine.refreshSuggestions()
|
||
}
|
||
}
|
||
let keys = model == nil ? [:] : (engine.journal?.current.keys ?? [:])
|
||
engine.tapOffsets = TypingDecoder.offsets(from: keys, layout: engine.layout)
|
||
}
|
||
|
||
/// The field or its contents changed outside these keys.
|
||
func textDidChange() {
|
||
applyAppearance()
|
||
let field = engine.field
|
||
let route = KeyboardFieldRouting.route(for: engine.target.keyboardType)
|
||
let routeField: KeyboardFieldKind = if case .keys(let kind, _) = route { kind } else { .text }
|
||
// While you search emoji the keys still type the query, whatever the host changed.
|
||
if routedTarget.isSearching {
|
||
refreshReturnKey()
|
||
return
|
||
}
|
||
if routeField != field {
|
||
plane.cancelAllTouches()
|
||
engine.configureForField()
|
||
refreshEmojiKey()
|
||
} else {
|
||
engine.textDidChange()
|
||
}
|
||
refreshReturnKey()
|
||
refreshStrip()
|
||
}
|
||
|
||
/// The keyboard came on screen for a (possibly new) field.
|
||
func prepareForField() {
|
||
closeEmojiPanel()
|
||
refreshLanguageSignals()
|
||
syncSettings()
|
||
plane.cancelAllTouches()
|
||
engine.configureForField()
|
||
refreshReturnKey()
|
||
applyAppearance()
|
||
refreshStrip()
|
||
dismissStyleMenu()
|
||
if allowsHaptics() {
|
||
keyTicks.prepare()
|
||
selectionHaptics.prepare()
|
||
}
|
||
}
|
||
|
||
/// Frees non-essential UI and Metal drawables when the extension approaches its memory ceiling.
|
||
func handleMemoryWarning() {
|
||
dismissStyleMenu()
|
||
if emojiPanel == nil {
|
||
emojiLibrary = nil
|
||
}
|
||
emojiPanel?.glyphs.purge()
|
||
if !showsRecording, let panel = recordingPanel {
|
||
panel.tearDown()
|
||
panel.removeFromSuperview()
|
||
recordingPanel = nil
|
||
}
|
||
}
|
||
|
||
/// Hex inserted a dictation; offer to take it back until the next edit.
|
||
func didInsertDictation(_ text: String) {
|
||
lastDictation = text
|
||
refreshStrip()
|
||
undoHideWork?.cancel()
|
||
let work = DispatchWorkItem { [weak self] in self?.hideUndo() }
|
||
undoHideWork = work
|
||
DispatchQueue.main.asyncAfter(deadline: .now() + 12, execute: work)
|
||
engine.textDidChange()
|
||
refreshReturnKey()
|
||
}
|
||
|
||
/// Fixtures: show a key held down.
|
||
func debugPress(_ character: String) {
|
||
guard let key = engine.layout.key(.character(character)) else { return }
|
||
engine.touchBegan(id: -1, at: CGPoint(x: key.frame.midX, y: key.frame.midY))
|
||
}
|
||
|
||
/// Fixtures: show a key's accent callout with `option` selected.
|
||
func debugHoldAccent(_ character: String, selecting option: String) {
|
||
debugHoldAccent(character)
|
||
guard let index = engine.activeAccentMenu?.options.firstIndex(of: option) else { return }
|
||
engine.debugSelectAccent(index)
|
||
}
|
||
|
||
/// Fixtures: show a key's long-press accent callout.
|
||
func debugHoldAccent(_ character: String, selectIndex: Int? = nil) {
|
||
guard let key = engine.layout.key(.character(character)) else { return }
|
||
let center = CGPoint(x: key.frame.midX, y: key.frame.midY)
|
||
engine.touchBegan(id: -2, at: center)
|
||
_ = engine.openAccentMenuIfEligible(forTouch: -2)
|
||
if let selectIndex { engine.debugSelectAccent(selectIndex) }
|
||
}
|
||
|
||
// MARK: - Layout
|
||
|
||
override func layoutSubviews() {
|
||
super.layoutSubviews()
|
||
let isLandscape = orientation == .landscape
|
||
engine.typingLog?.viewGeometry(size: bounds.size, safeArea: safeAreaInsets)
|
||
engine.orientation = orientation
|
||
engine.horizontalInset = isLandscape ? max(safeAreaInsets.left, safeAreaInsets.right) : 0
|
||
engine.width = bounds.width
|
||
syncPosture()
|
||
engine.typingLog?.commitGeometry()
|
||
let layout = engine.layout
|
||
|
||
let lift = appliedLift
|
||
let content = CGRect(x: 0, y: lift, width: bounds.width, height: bounds.height - lift)
|
||
plane.frame = content
|
||
callout.frame = content
|
||
accentCallout.frame = content
|
||
stripView.frame = layout.stripFrame.offsetBy(dx: 0, dy: lift)
|
||
stripView.slotFrames = layout.stripSlotFrames.map { $0.offsetBy(dx: -layout.stripFrame.minX, dy: -layout.stripFrame.minY) }
|
||
stripView.pillInset = layout.metrics.stripInset
|
||
stripView.textCenterY = layout.metrics.stripTextCenter
|
||
stripView.hexOnLeading = layout.hexOnLeading
|
||
|
||
hexKey.cornerRadius = layout.metrics.cornerRadius
|
||
if let hex = layout.key(.hex) {
|
||
hexKey.inStrip = hex.row < 0
|
||
hexKey.frame = hex.hitFrame.offsetBy(dx: 0, dy: lift)
|
||
hexKey.keycapFrame = hex.frame.offsetBy(dx: -hex.hitFrame.minX, dy: -hex.hitFrame.minY)
|
||
hexKey.markCenterY = layout.metrics.stripTop + layout.metrics.stripTextCenter - hex.hitFrame.minY
|
||
}
|
||
if let globe = layout.key(.globe), emojiPanel == nil || routedTarget.isSearching {
|
||
globeButton.isHidden = false
|
||
globeButton.frame = globe.hitFrame.offsetBy(dx: 0, dy: lift)
|
||
} else {
|
||
globeButton.isHidden = true
|
||
}
|
||
layoutEmoji(content: content, lift: lift)
|
||
|
||
if let panel = recordingPanel {
|
||
panel.frame = recordingPanelFrame
|
||
panel.horizontalInset = layout.horizontalInset
|
||
panel.metrics = layout.metrics
|
||
panel.sideKeyWidth = layout.modifierWidth
|
||
panel.hexOnLeading = layout.hexOnLeading
|
||
}
|
||
if let menu = styleMenu, let hex = layout.key(.hex) {
|
||
menu.frame = bounds
|
||
menu.anchor = hex.frame
|
||
}
|
||
plane.setNeedsDisplay()
|
||
updateCallout()
|
||
}
|
||
|
||
// MARK: - State
|
||
|
||
private func applyAppearance() {
|
||
let isDark = appearanceOverride
|
||
?? FullKeyboardPalette.isDark(traits: traitCollection)
|
||
let next = FullKeyboardPalette(isDark: isDark)
|
||
backgroundColor = drawsBackdrop ? next.backdrop : .clear
|
||
stripView.inSystemPlatter = !drawsBackdrop
|
||
guard next != palette || !didApplyPalette else { return }
|
||
didApplyPalette = true
|
||
palette = next
|
||
stripView.palette = next
|
||
plane.palette = next
|
||
callout.palette = next
|
||
callout.setNeedsDisplay()
|
||
accentCallout.palette = next
|
||
hexKey.palette = next
|
||
recordingPanel?.palette = next
|
||
styleMenu?.palette = next
|
||
emojiPanel?.palette = next
|
||
emojiSearchField?.palette = next
|
||
emojiResults?.palette = next
|
||
}
|
||
|
||
func refreshReturnKey() {
|
||
plane.returnStyle = ReturnKeyStyle(engine.target.returnKeyType)
|
||
plane.returnIsEnabled = ReturnKeyStyle.isEnabled(
|
||
automatically: engine.target.enablesReturnKeyAutomatically,
|
||
hasText: engine.target.hasText
|
||
)
|
||
}
|
||
|
||
private func refreshFromModel() {
|
||
hexKey.isWarm = model.dictatesThroughHex
|
||
hexKey.translatingTo = model.translatingTo
|
||
if engine.showsGlobe != model.needsGlobeKey {
|
||
engine.showsGlobe = model.needsGlobeKey
|
||
setNeedsLayout()
|
||
}
|
||
let recording = model.stagePhase == .recording || model.stagePhase == .transcribing
|
||
if recording != showsRecording {
|
||
setRecording(recording)
|
||
}
|
||
refreshRecordingPanel()
|
||
stripView.showsLoggingMark = model.isLoggingTyping
|
||
recordingPanel?.showsLoggingMark = model.isLoggingTyping
|
||
// A language picked in the switch changes the layout at once when it follows dictation.
|
||
syncLanguage()
|
||
refreshSpaceLabel()
|
||
if let menu = styleMenu {
|
||
menu.style = model.style
|
||
applyLanguages(to: menu)
|
||
}
|
||
refreshStrip()
|
||
}
|
||
|
||
private func applyLanguages(to menu: HexStyleMenuView) {
|
||
menu.dictationLanguage = model.dictationLanguage
|
||
menu.automaticLanguage = model.automaticLanguage
|
||
menu.languageChoices = model.showsLanguageSwitch ? model.languageChoices : []
|
||
menu.moreLanguages = model.showsLanguageSwitch ? model.moreLanguages : []
|
||
menu.translationTarget = model.showsTranslationSwitch ? model.translationLanguage : nil
|
||
menu.isTranslating = model.isTranslating
|
||
menu.translationTargets = model.translationTargetChoices
|
||
}
|
||
|
||
func refreshStrip() {
|
||
// Without Full Access the strip suggests and corrects like any keyboard's; what
|
||
// dictation needs shows only once the Hex key is tapped (`showFullAccessHint`).
|
||
let status: String? = if model.hasFullAccess, model.stagePhase == .failed {
|
||
model.statusMessage
|
||
} else if showsAllowPasteHint {
|
||
KeyboardClipboardTracker.allowPasteHint
|
||
} else {
|
||
nil
|
||
}
|
||
var clipboardOffer = clipboard.offer(
|
||
textContentType: engine.target.textContentType,
|
||
hasFullAccess: model.hasFullAccess
|
||
)
|
||
// A dictation that didn't go in by itself comes before a copy, but not in a code field.
|
||
if model.hasFullAccess, model.offeredDictation != nil {
|
||
if case .code = clipboardOffer {} else { clipboardOffer = .dictation }
|
||
}
|
||
stripOffer = clipboardOffer
|
||
var suggestions = engine.suggestions
|
||
if showsAllowPasteHint, status != nil {
|
||
// The pasted text's last word would otherwise hide where to stop Allow Paste.
|
||
suggestions = []
|
||
} else if suggestions.isEmpty || suggestions.first?.kind == .nextWord {
|
||
if lastDictation != nil || status != nil || clipboardOffer != nil {
|
||
suggestions = []
|
||
} else {
|
||
let emoji = emojiForFinishedWord()
|
||
if !emoji.isEmpty {
|
||
// The finished word's emoji, with next words beside it so every slot fills:
|
||
// one emoji takes the centre.
|
||
let words = Array(suggestions.prefix(max(0, 3 - emoji.count)))
|
||
suggestions = emoji.count == 1 && words.count == 2 ? [words[0], emoji[0], words[1]] : emoji + words
|
||
}
|
||
}
|
||
}
|
||
stripView.update(
|
||
suggestions: suggestions,
|
||
showsUndo: lastDictation != nil,
|
||
statusText: status,
|
||
clipboard: clipboardOffer,
|
||
fullAccessHint: showsFullAccessHint && !model.hasFullAccess,
|
||
notice: translationNotice
|
||
)
|
||
}
|
||
|
||
/// The last dictation went in as spoken while Translate what I say was on: what happened,
|
||
/// the fix, and Open Hex, which opens Settings › Dictation.
|
||
private var translationNotice: KeyboardStripNotice? {
|
||
guard model.hasFullAccess, let note = model.translationNote else { return nil }
|
||
return KeyboardStripNotice(title: TranslationFailure.note, detail: note.fix, button: String(localized: "Open Hex"))
|
||
}
|
||
|
||
// MARK: - Without Full Access
|
||
|
||
/// The Hex key without Full Access: the keys keep typing, and the strip says, for a few
|
||
/// seconds, that dictation needs Allow Full Access and where to turn it on. Only its
|
||
/// Open Hex chip opens Hex; nothing opens it by itself.
|
||
func showFullAccessHint() {
|
||
dismissStyleMenu()
|
||
showsFullAccessHint = true
|
||
refreshStrip()
|
||
UIAccessibility.post(
|
||
notification: .announcement,
|
||
argument: "\(FullAccessHintView.title). Settings, Apps, Hex, Keyboards."
|
||
)
|
||
fullAccessHintHideWork?.cancel()
|
||
let work = DispatchWorkItem { [weak self] in self?.hideFullAccessHint() }
|
||
fullAccessHintHideWork = work
|
||
DispatchQueue.main.asyncAfter(deadline: .now() + Self.fullAccessHintDuration, execute: work)
|
||
}
|
||
|
||
private func hideFullAccessHint() {
|
||
fullAccessHintHideWork?.cancel()
|
||
fullAccessHintHideWork = nil
|
||
guard showsFullAccessHint else { return }
|
||
showsFullAccessHint = false
|
||
refreshStrip()
|
||
}
|
||
|
||
private func openSetupFromHint() {
|
||
keyFeedback()
|
||
hideFullAccessHint()
|
||
model.onOpenURL?(KeyboardLaunchRequest.setup.url)
|
||
}
|
||
|
||
private func pasteFromClipboard() {
|
||
if stripOffer == .dictation {
|
||
keyFeedback()
|
||
typingLog?.ui("paste_dictation")
|
||
model.onPasteDictation?()
|
||
refreshStrip()
|
||
return
|
||
}
|
||
let pasteboard = UIPasteboard.general
|
||
// The read blocks while iOS asks Allow Paste, so its length tells whether it asked.
|
||
let start = ProcessInfo.processInfo.systemUptime
|
||
let read = KeyboardClipboardTracker.read(pasteboard)
|
||
let readDuration = ProcessInfo.processInfo.systemUptime - start
|
||
let text = read.flatMap { $0.isEmpty ? nil : $0 }
|
||
let refused = text == nil && (pasteboard.hasStrings || pasteboard.hasURLs)
|
||
let pointsToSetting = clipboard.shouldPointToAllowPaste(readDuration: readDuration, refused: refused)
|
||
guard let text else {
|
||
if pointsToSetting { showAllowPasteHint() }
|
||
return
|
||
}
|
||
keyFeedback()
|
||
clipboard.markPasted()
|
||
typingLog?.edit("paste", [TypingLogField("inserted", .string(text))])
|
||
engine.target.insertText(text)
|
||
engine.textDidChange()
|
||
typingLog?.context("paste")
|
||
if pointsToSetting { showAllowPasteHint() }
|
||
refreshStrip()
|
||
onTextEdit?()
|
||
}
|
||
|
||
/// For a few seconds after a paste iOS asked about (or refused), the strip says where
|
||
/// to stop it asking: Settings › Apps › Hex › Paste from Other Apps › Allow.
|
||
private func showAllowPasteHint() {
|
||
showsAllowPasteHint = true
|
||
refreshStrip()
|
||
UIAccessibility.post(notification: .announcement, argument: KeyboardClipboardTracker.allowPasteHintAnnouncement)
|
||
allowPasteHintHideWork?.cancel()
|
||
let work = DispatchWorkItem { [weak self] in self?.hideAllowPasteHint() }
|
||
allowPasteHintHideWork = work
|
||
DispatchQueue.main.asyncAfter(deadline: .now() + Self.allowPasteHintDuration, execute: work)
|
||
}
|
||
|
||
/// Typing takes the strip back before the hint's time is up.
|
||
private func hideAllowPasteHint() {
|
||
allowPasteHintHideWork?.cancel()
|
||
allowPasteHintHideWork = nil
|
||
guard showsAllowPasteHint else { return }
|
||
showsAllowPasteHint = false
|
||
refreshStrip()
|
||
}
|
||
|
||
private func refreshRecordingPanel() {
|
||
guard let panel = recordingPanel, showsRecording else { return }
|
||
panel.update(
|
||
phase: model.stagePhase == .transcribing ? .processing : .recording,
|
||
style: model.style
|
||
)
|
||
}
|
||
|
||
private func setRecording(_ recording: Bool) {
|
||
showsRecording = recording
|
||
dismissStyleMenu()
|
||
if recording { closeEmojiPanel() }
|
||
let closingFrames = recording ? nil : morphFrames()
|
||
if recording {
|
||
plane.cancelAllTouches()
|
||
hideUndo()
|
||
let panel = recordingPanel ?? makeRecordingPanel()
|
||
panel.palette = palette
|
||
panel.frame = recordingPanelFrame
|
||
refreshRecordingPanel()
|
||
panel.isHidden = false
|
||
if let (mark, bar) = morphFrames(), window != nil {
|
||
// The mark grows into a capsule and runs across the strip, then the panel takes over.
|
||
runMorph(from: mark, to: bar, appearing: true)
|
||
fade(in: [], out: [stripView, hexKey])
|
||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.16) { [weak self, weak panel] in
|
||
guard let self, self.showsRecording, let panel else { return }
|
||
self.fade(in: [panel], out: [self.morph])
|
||
}
|
||
} else {
|
||
fade(in: [panel], out: [stripView, hexKey])
|
||
}
|
||
} else if let panel = recordingPanel {
|
||
panel.scope.phase = .hidden
|
||
if let (_, bar) = closingFrames, let (mark, _) = morphFrames(), window != nil {
|
||
runMorph(from: bar, to: mark, appearing: false)
|
||
}
|
||
fade(in: [stripView, hexKey], out: [panel]) { [weak self, weak panel] in
|
||
guard let self, !self.showsRecording, let panel, panel === self.recordingPanel else { return }
|
||
panel.tearDown()
|
||
panel.removeFromSuperview()
|
||
self.recordingPanel = nil
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Where the recording panel sits: the suggestion strip, full width and its height, so
|
||
/// neither the keyboard nor the keys move.
|
||
private var recordingPanelFrame: CGRect {
|
||
let m = engine.layout.metrics
|
||
return CGRect(x: 0, y: m.stripTop + appliedLift, width: bounds.width, height: m.stripHeight)
|
||
}
|
||
|
||
/// The Hex mark's frame in the strip and the full-width bar it grows into, or nil when
|
||
/// the Hex key sits in the bottom row.
|
||
private func morphFrames() -> (CGRect, CGRect)? {
|
||
let layout = engine.layout
|
||
guard let hex = layout.key(.hex), hex.row < 0 else { return nil }
|
||
let m = layout.metrics
|
||
let lift = appliedLift
|
||
let mark = hex.frame.offsetBy(dx: 0, dy: lift)
|
||
let bar = CGRect(
|
||
x: layout.horizontalInset + m.side,
|
||
y: m.stripTop + lift + m.stripInset,
|
||
width: bounds.width - 2 * (layout.horizontalInset + m.side),
|
||
height: m.stripPillHeight
|
||
)
|
||
return (mark, bar)
|
||
}
|
||
|
||
private func runMorph(from start: CGRect, to end: CGRect, appearing: Bool) {
|
||
morph.layer.removeAllAnimations()
|
||
// Under the recording panel on the way in (the panel fades in over it), above it on the
|
||
// way out so the bar is seen shrinking back into the mark.
|
||
if appearing {
|
||
insertSubview(morph, aboveSubview: stripView)
|
||
} else {
|
||
bringSubviewToFront(morph)
|
||
}
|
||
morph.backgroundColor = palette.chipFill
|
||
morph.frame = start
|
||
morph.layer.cornerRadius = start.height / 2
|
||
morph.alpha = appearing ? 0.6 : 1
|
||
morph.isHidden = false
|
||
UIView.animate(
|
||
withDuration: 0.34,
|
||
delay: 0,
|
||
usingSpringWithDamping: 0.82,
|
||
initialSpringVelocity: 0,
|
||
options: [.beginFromCurrentState, .allowUserInteraction]
|
||
) {
|
||
self.morph.frame = end
|
||
self.morph.layer.cornerRadius = end.height / 2
|
||
if appearing { self.morph.alpha = 1 }
|
||
}
|
||
guard !appearing else { return }
|
||
UIView.animate(withDuration: 0.12, delay: 0.24, options: [.allowUserInteraction]) {
|
||
self.morph.alpha = 0
|
||
} completion: { _ in
|
||
if !self.showsRecording {
|
||
self.morph.isHidden = true
|
||
}
|
||
}
|
||
}
|
||
|
||
private func fade(in shown: [UIView], out hidden: [UIView], after: (() -> Void)? = nil) {
|
||
shown.forEach { $0.isHidden = false }
|
||
let globeHidden = engine.layout.key(.globe) == nil
|
||
let accentHidden = engine.activeAccentMenu == nil
|
||
let duration = window == nil ? 0 : 0.18
|
||
if duration == 0 {
|
||
shown.forEach { $0.alpha = 1 }
|
||
hidden.forEach {
|
||
$0.alpha = 0
|
||
$0.isHidden = true
|
||
}
|
||
if globeHidden { globeButton.isHidden = true }
|
||
if accentHidden { accentCallout.isHidden = true }
|
||
after?()
|
||
return
|
||
}
|
||
UIView.animate(withDuration: duration, delay: 0, options: [.beginFromCurrentState, .allowUserInteraction]) {
|
||
shown.forEach { $0.alpha = 1 }
|
||
hidden.forEach { $0.alpha = 0 }
|
||
} completion: { _ in
|
||
// A Hex key still held for push to talk stays in the window (at alpha 0), so its
|
||
// touch keeps arriving and lifting the finger finishes the dictation.
|
||
for view in hidden where view.alpha == 0 && (view as? UIControl)?.isTracking != true {
|
||
view.isHidden = true
|
||
}
|
||
if globeHidden { self.globeButton.isHidden = true }
|
||
if accentHidden { self.accentCallout.isHidden = true }
|
||
after?()
|
||
}
|
||
}
|
||
|
||
private func makeRecordingPanel() -> HexKeyRecordingPanel {
|
||
let panel = HexKeyRecordingPanel(loudness: { [weak model] in model?.liveLoudnessDB ?? -62 })
|
||
panel.alpha = 0
|
||
panel.onDone = { [weak self] in
|
||
self?.typingLog?.ui("dictation_stop")
|
||
self?.model.onStopTap?()
|
||
}
|
||
panel.onCancel = { [weak self] in
|
||
self?.typingLog?.ui("dictation_cancel")
|
||
self?.model.onCancelTap?()
|
||
}
|
||
panel.onCycleStyle = { [weak self] in
|
||
guard let self else { return }
|
||
self.typingLog?.ui("style", [
|
||
TypingLogField("style", .string(self.model.style.next.rawValue)),
|
||
TypingLogField("from", .string("recording_panel")),
|
||
])
|
||
self.model.onStyleSelected?(self.model.style.next)
|
||
}
|
||
panel.showsLoggingMark = model.isLoggingTyping
|
||
panel.hexOnLeading = engine.layout.hexOnLeading
|
||
insertSubview(panel, belowSubview: callout)
|
||
recordingPanel = panel
|
||
setNeedsLayout()
|
||
return panel
|
||
}
|
||
|
||
private func engineChanged() {
|
||
plane.setNeedsDisplay()
|
||
updateCallout()
|
||
refreshStrip()
|
||
if globeButton.isHidden != (engine.layout.key(.globe) == nil) || hexKey.frame != engine.layout.key(.hex)?.hitFrame {
|
||
setNeedsLayout()
|
||
}
|
||
}
|
||
|
||
private func updateCallout() {
|
||
if let menu = engine.activeAccentMenu {
|
||
endCalloutLinger()
|
||
callout.show(nil, label: "")
|
||
accentCallout.show(menu)
|
||
return
|
||
}
|
||
accentCallout.show(nil)
|
||
let layout = engine.layout
|
||
if engine.showsKeyPopups, let key = engine.previewKey, let balloon = layout.balloon(for: key) {
|
||
endCalloutLinger()
|
||
let label = KeyboardKeyPlaneView.keycapLabel(engine.displayLabel(for: key))
|
||
callout.show(balloon, label: label, style: KeyCalloutView.style(for: label))
|
||
shownPreviewKind = key.kind
|
||
} else if let kind = shownPreviewKind, calloutLingerWork == nil, engine.touches.isEmpty {
|
||
// The finger lifted: Apple's pop-up and its grey key stay up 3 frames more (about
|
||
// 50 ms after the letter lands, iOS 27.2 at 60 fps), then go in one frame.
|
||
plane.lingeringKind = kind
|
||
let work = DispatchWorkItem { [weak self] in self?.endCalloutLinger() }
|
||
calloutLingerWork = work
|
||
DispatchQueue.main.asyncAfter(deadline: .now() + KeyCalloutView.linger, execute: work)
|
||
} else if calloutLingerWork == nil {
|
||
shownPreviewKind = nil
|
||
callout.show(nil, label: "")
|
||
}
|
||
}
|
||
|
||
/// The key whose pop-up is up, or lingering after the finger lifted.
|
||
private var shownPreviewKind: KeyKind?
|
||
private var calloutLingerWork: DispatchWorkItem?
|
||
|
||
private func endCalloutLinger() {
|
||
calloutLingerWork?.cancel()
|
||
calloutLingerWork = nil
|
||
guard plane.lingeringKind != nil || shownPreviewKind != nil else { return }
|
||
plane.lingeringKind = nil
|
||
if engine.previewKey == nil {
|
||
shownPreviewKind = nil
|
||
callout.show(nil, label: "")
|
||
}
|
||
}
|
||
|
||
// MARK: - Actions
|
||
|
||
/// The system key click (`KeyboardInputView`), one for every key, delete and shift too:
|
||
/// Apple's keyboard plays other sounds for those, but the click is the only keyboard sound
|
||
/// a keyboard may play. Tests count it.
|
||
var playInputClick: () -> Void = { UIDevice.current.playInputClick() }
|
||
|
||
/// A key went down (or delete repeated): its click, and its tick while haptics are allowed.
|
||
func keyFeedback() {
|
||
playInputClick()
|
||
if allowsHaptics() {
|
||
keyTicks.impactOccurred(intensity: Self.keyTickIntensity(hapticStrength))
|
||
keyTicks.prepare()
|
||
}
|
||
}
|
||
|
||
func selectionFeedback() {
|
||
if allowsHaptics() {
|
||
selectionHaptics.selectionChanged()
|
||
selectionHaptics.prepare()
|
||
}
|
||
}
|
||
|
||
/// A tap or still hold on the Hex key.
|
||
private func hexKeyHeld() {
|
||
if allowsHaptics() { haptics.impactOccurred() }
|
||
dismissStyleMenu()
|
||
guard model.hasFullAccess else {
|
||
// Dictation needs Full Access (the microphone and Hex's App Group): say so,
|
||
// instead of a dictation that can't start.
|
||
dictatingFromHexKey = false
|
||
showFullAccessHint()
|
||
return
|
||
}
|
||
if hexKey.isWarm {
|
||
typingLog?.ui("hex_key", [TypingLogField("dictation", .string("warm"))])
|
||
dictatingFromHexKey = true
|
||
model.onDictateTap?()
|
||
} else if let local = model.onLocalDictateTap {
|
||
typingLog?.ui("hex_key", [TypingLogField("dictation", .string("keyboard"))])
|
||
dictatingFromHexKey = true
|
||
local()
|
||
} else {
|
||
typingLog?.ui("hex_key", [TypingLogField("dictation", .string("open_hex"))])
|
||
dictatingFromHexKey = false
|
||
model.onOpenURL?(model.coldStartURL)
|
||
}
|
||
}
|
||
|
||
/// Push to talk: lifting the finger after a hold finishes the dictation the hold started,
|
||
/// as Done does. A hold that opened Hex has nothing to finish here.
|
||
private func hexKeyReleased() {
|
||
guard dictatingFromHexKey else { return }
|
||
dictatingFromHexKey = false
|
||
typingLog?.ui("dictation_stop", [TypingLogField("from", .string("hex_key_release"))])
|
||
model.onStopTap?()
|
||
}
|
||
|
||
/// Hold and slide: light the row under the finger, and pick it on release.
|
||
private func forwardMenuPoint(_ point: CGPoint, release: Bool) {
|
||
guard let menu = styleMenu else { return }
|
||
let local = hexKey.convert(point, to: menu)
|
||
if release {
|
||
menu.finishDrag(at: local)
|
||
} else {
|
||
menu.updateDrag(at: local)
|
||
}
|
||
}
|
||
|
||
private func showStyleMenu() {
|
||
guard styleMenu == nil, !showsRecording else { return }
|
||
if allowsHaptics() {
|
||
haptics.impactOccurred()
|
||
haptics.prepare()
|
||
}
|
||
plane.cancelAllTouches()
|
||
let menu = HexStyleMenuView()
|
||
menu.palette = palette
|
||
menu.style = model.style
|
||
applyLanguages(to: menu)
|
||
menu.onHoverChanged = { [weak self] in self?.selectionFeedback() }
|
||
menu.onLanguage = { [weak self] language in
|
||
self?.typingLog?.ui("dictation_language", [TypingLogField("language", .string(language ?? "automatic"))])
|
||
self?.model.onLanguageSelected?(language)
|
||
self?.dismissStyleMenu()
|
||
}
|
||
// The menu stays open, so the language is seen to go.
|
||
menu.onRemoveLanguage = { [weak self] language in
|
||
self?.typingLog?.ui("dictation_language_removed", [TypingLogField("language", .string(language))])
|
||
self?.model.onLanguageRemoved?(language)
|
||
}
|
||
menu.onTranslationToggle = { [weak self] on in
|
||
self?.typingLog?.ui("translate", [TypingLogField("on", .bool(on))])
|
||
self?.model.onTranslationToggled?(on)
|
||
self?.dismissStyleMenu()
|
||
}
|
||
menu.onTranslationTarget = { [weak self] target in
|
||
self?.typingLog?.ui("translate", [TypingLogField("target", .string(target))])
|
||
self?.model.onTranslationTargetSelected?(target)
|
||
self?.dismissStyleMenu()
|
||
}
|
||
menu.onStyle = { [weak self] style in
|
||
self?.typingLog?.ui("style", [
|
||
TypingLogField("style", .string(style.rawValue)),
|
||
TypingLogField("from", .string("hex_menu")),
|
||
])
|
||
self?.model.onStyleSelected?(style)
|
||
self?.dismissStyleMenu()
|
||
}
|
||
menu.onDismiss = { [weak self] in self?.dismissStyleMenu() }
|
||
addSubview(menu)
|
||
styleMenu = menu
|
||
setNeedsLayout()
|
||
layoutIfNeeded()
|
||
}
|
||
|
||
func dismissStyleMenu() {
|
||
styleMenu?.removeFromSuperview()
|
||
styleMenu = nil
|
||
}
|
||
|
||
/// Fixtures: open the menu without a long press, optionally on another page.
|
||
func debugShowStyleMenu(page: HexStyleMenuView.Page = .styles) {
|
||
showStyleMenu()
|
||
styleMenu?.show(page: page)
|
||
}
|
||
|
||
/// Fixtures: the language page with Remove on a language's row.
|
||
func debugOfferRemove(_ language: String) {
|
||
showStyleMenu()
|
||
styleMenu?.debugOfferRemove(language)
|
||
}
|
||
|
||
private func undoDictation() {
|
||
guard let text = lastDictation else { return }
|
||
let before = engine.target.documentContextBeforeInput ?? ""
|
||
// Only take back text that is still right before the cursor.
|
||
if before.hasSuffix(text) || (!before.isEmpty && before.count < text.count && text.hasSuffix(before)) {
|
||
// The host may show only the end of it; replay removes what the keys remove.
|
||
typingLog?.edit("undo_dictation", before.hasSuffix(text)
|
||
? [TypingLogField("deleted", .string(text))]
|
||
: [TypingLogField("deletedCount", .int(text.count))])
|
||
for _ in 0..<text.count {
|
||
engine.target.deleteBackward()
|
||
}
|
||
onUndoDictation?()
|
||
} else {
|
||
typingLog?.ui("undo_dictation", [TypingLogField("applied", .bool(false))])
|
||
}
|
||
hideUndo()
|
||
engine.textDidChange()
|
||
typingLog?.context("undo_dictation")
|
||
refreshReturnKey()
|
||
}
|
||
|
||
private func hideUndo() {
|
||
undoHideWork?.cancel()
|
||
undoHideWork = nil
|
||
if lastDictation != nil {
|
||
lastDictation = nil
|
||
refreshStrip()
|
||
}
|
||
}
|
||
|
||
private func configureGlobe() {
|
||
globeButton.removeTarget(nil, action: nil, for: .allEvents)
|
||
if let controller = hostController {
|
||
globeButton.addTarget(
|
||
controller,
|
||
action: #selector(UIInputViewController.handleInputModeList(from:with:)),
|
||
for: .allTouchEvents
|
||
)
|
||
}
|
||
}
|
||
}
|