mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
* iOS keyboard: live words over the keys while dictating (stage 1, two looks)
What: while the keyboard records (in-keyboard dictation, iOS 26+), the capture's
16-bit chunks also feed Apple's SpeechAnalyzer (SpeechTranscriber with volatile and
fast results, DictationTranscriber's progressive preset for its languages), and the
words so far show over the keys: settled words in the keys' ink, the tentative tail
muted, newest line in view, whole lines at the top. Two looks behind a temporary App
Group key (debug.liveDictationLook): dim (keys at 10%) and hide. The preview takes every
touch on the keys, so nothing types while it shows; the recording bar, its cancel and
done, and the globe (drawn over the words where the keyboard has its own) work as before.
The final text still comes from the recording exactly as today; the live recogniser is
stopped when the capture stops (model lingering for the final pass).
Why: Ryan asked for the dictation to show in real time over a hidden or dimmed keyboard.
LiveTranscriptSource is one small protocol so the source can be swapped:
ParakeetLiveTranscriber (the audio so far again about once a second, a 20 s window) is
written but not wired. Never worse than today: no preview when neither switch wants it,
when less than 24 MB is left, when the language's model isn't on the iPhone (no
download), on an error, or before iOS 26. Hooks in KeyboardLocalDictation stay in the
capture's events and phase, away from the transcription call.
Verified: Studio simulator (iPhone 17 Pro iOS 27.2, SE iOS 26.5), real keyboard in a
host app with results recorded from Apple's recogniser on macOS 27.2.1 replayed (the
simulator has no speech models; LiveTranscriptReplay is simulator-only): both looks,
light and dark, upright and turned, a 60 s dictation scrolling, taps on Q and space
while recording type nothing with the preview (and "Q " without it), the globe switches
keyboards on the SE, no model -> no preview and the keys as today. Measured on macOS
with the same source: first words 0.5-1.0 s after the first word ends, word lag median
0.56-0.76 s, 2.1% of shown words rewritten, +0.4-2.6 MB in the feeding process.
code-shape.py passes. No settings UI yet (stage 2).
* iOS keyboard: Show what I say (hide look) and Type as I speak
What: look (b) only. While the keyboard records by itself the keys go and the words
so far take their place under the recording bar; the dim look and its temporary
debug.liveDictationLook key are gone. Two switches in Settings › Dictation on their
own card under the style card, iOS 26 and later only, Simplified Chinese:
- Show what I say (on by default): the preview.
- Type as I speak (off by default, "Words can change until you stop"):
LiveFieldTyping types the live words through the text document proxy, retyping only
the changed tail, and keeps exactly what it typed. It edits only while the text
before the cursor still ends with that (smart quotes allowed for; a host showing only
the end must show the part that changes); otherwise it stops and leaves the field,
and the dictation goes in at the cursor as today. When the dictation's text goes in,
KeyboardLiveTyping.handOver takes the words out first and returns the field as it was,
so spacing, Undo dictation (the whole dictation), Learn how I type and typing logs see
exactly what they did before. Cancel, a failure, nothing heard and the keyboard hiding
take the words out (a held dictation goes in at the next keyboard as before). Never
in secure, password, one-time code or card number fields, over a selection or a
two-thumb Dictate's range, or with Translate what I say on (Ryan's call).
- Never worse than today: live words only with 32 MB left once the capture runs (the
speech model's 24 MB transcription headroom plus the recogniser's share), stopped under
24 MB or on a memory warning; the preview never shows before a recogniser is running,
so a dictation without one never flashes it.
- The hand-over: the preview fades with the words it had while the keys and the
dictation's own text come in; with Parakeet now English's default the field's words
can differ slightly from the preview's (Apple's), and never flash in the preview.
Why: Ryan picked look (b) and the two switch names at the checkpoint.
Verified: Studio simulator (iPhone 17 Pro, iOS 27.2) with the replayed recogniser
results: the field typed and revised as the words came ("Quick note: Hey, I am running
about 10 minutes late. Can you grab us a table by...") and back to "Quick note:" after
Cancel; Settings › Dictation in English, dark with both on, and Simplified Chinese.
New tests in DictationLearningTests (LiveDictationTests: accumulator, joining, switch
defaults, typing and revising, stopping when the field changes or reports nothing,
private fields). README describes what the keyboard shows while recording.
code-shape.py passes.
* iOS keyboard: the preview draws only the end of a long dictation
What: LiveDictationPreviewView draws its words with one label in a clipping box, moved up by
whole lines once they overflow it, and only about the box's worth of text and three lines more
(from a word's start). It replaces the scrolling UITextView, so the words can no longer be
dragged back.
Why: on the iPhone 17 Pro a 60 s dictation with the preview held up to 27 MB more in the
keyboard (peak 103 MB, against 60 MB with the recogniser on and the preview off); the Studio
simulator showed the same, +24.5 MB.
Verified: Studio simulator, the 60 s replay: +24.5 MB (text view) -> +17.3 (capped text view)
-> +5.7 MB with the label, against +7.0 MB for the same recording without the preview. Test
for the tail in LiveDictationTests.
* iOS keyboard: the preview's tail keeps a word that starts right at the cut
Verified: LiveDictationTests on the Studio simulator.
* iOS keyboard: Type as I speak's words are replaced by the held text after the keyboard hides
What: when the keyboard hides mid-dictation, KeyboardLiveTyping notes the words it typed
(LiveDictationSettings.leftover, in the App Group) as well as taking them out. When the held
dictation goes in (inserted by itself or by Paste dictation), it replaces those words if the
text before the cursor still ends with them (LiveFieldTyping(resuming:in:)); otherwise it goes in
at the cursor as before. A new dictation clears the note.
Why: on the iPhone 17 Pro, pressing Home mid-dictation left the typed words in the field (an
app gone to the background takes no edits) and, back in the app (a new document identifier),
the strip offered Paste dictation, which would have put the dictation after them.
Verified: LiveDictationTests on the Studio simulator (9 tests).
* iOS README: what the keyboard shows while recording, measured on the iPhone 17 Pro
Adds the phone's numbers (first words about 1.2-1.3 s after speech starts; 60 s dictation 60.1 MB
with the preview against 58.1 MB without, peaks 66.5 against 60.1), the hidden-keyboard case for
Type as I speak, and what is verified where and what isn't (VoiceOver on a device, lagging hosts).
255 lines
11 KiB
Swift
255 lines
11 KiB
Swift
import Combine
|
||
import UIKit
|
||
|
||
/// The words so far in place of the full keyboard's keys while it records (Settings ›
|
||
/// Dictation › Show what I say): the keys go and the words have their space, the settled
|
||
/// words in the keys' ink and the tentative tail muted, the newest line always in view with
|
||
/// whole lines above it. It takes every touch where the keys were, so nothing types while it
|
||
/// shows; the recording bar above and the globe stay as they are.
|
||
@MainActor
|
||
final class LiveDictationPreviewView: UIView {
|
||
var palette = FullKeyboardPalette(isDark: false) { didSet { if palette != oldValue { render() } } }
|
||
var orientation: KeyboardOrientation = .portrait { didSet { if orientation != oldValue { render() } } }
|
||
/// Where the words sit inside this view: the keys' own edges.
|
||
var textInsets: UIEdgeInsets = .zero { didSet { if textInsets != oldValue { setNeedsLayout() } } }
|
||
/// Where the keyboard has its own globe key (an iPhone with a Home button), its keycap in
|
||
/// this view: drawn whole over the words, since it still switches keyboards.
|
||
var globeFrame: CGRect? {
|
||
didSet {
|
||
guard globeFrame != oldValue else { return }
|
||
globe.isHidden = globeFrame == nil
|
||
globe.frame = globeFrame ?? .zero
|
||
globe.setNeedsDisplay()
|
||
}
|
||
}
|
||
var globeRadius: CGFloat = FullKeyboardPalette.cornerRadius { didSet { globe.cornerRadius = globeRadius } }
|
||
private(set) var transcript = LiveTranscript()
|
||
/// The words' box, and the words in it: one label, as tall as the text it shows, moved up
|
||
/// by whole lines once that's taller than the box.
|
||
private let box = UIView()
|
||
private let label = UILabel()
|
||
private let globe = GlobeKeycapView()
|
||
|
||
static let placeholder = String(localized: "Listening…")
|
||
|
||
override init(frame: CGRect) {
|
||
super.init(frame: frame)
|
||
backgroundColor = .clear
|
||
isOpaque = false
|
||
box.clipsToBounds = true
|
||
box.isUserInteractionEnabled = false
|
||
label.numberOfLines = 0
|
||
label.isAccessibilityElement = false
|
||
box.addSubview(label)
|
||
addSubview(box)
|
||
globe.isHidden = true
|
||
globe.isUserInteractionEnabled = false
|
||
addSubview(globe)
|
||
// One element for VoiceOver, read when it's focused, never announced as words change.
|
||
isAccessibilityElement = true
|
||
accessibilityTraits = .staticText
|
||
render()
|
||
}
|
||
|
||
@available(*, unavailable)
|
||
required init?(coder: NSCoder) { fatalError() }
|
||
|
||
func show(_ next: LiveTranscript) {
|
||
guard next != transcript else { return }
|
||
transcript = next
|
||
render()
|
||
}
|
||
|
||
override func layoutSubviews() {
|
||
super.layoutSubviews()
|
||
let frame = bounds.inset(by: textInsets)
|
||
if box.frame != frame {
|
||
box.frame = frame
|
||
placeWords()
|
||
}
|
||
}
|
||
|
||
/// A touch anywhere on it stays with it.
|
||
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
|
||
bounds.contains(point)
|
||
}
|
||
|
||
private var font: UIFont {
|
||
.systemFont(ofSize: orientation == .landscape ? 19 : 23, weight: .regular)
|
||
}
|
||
|
||
private func render() {
|
||
globe.palette = palette
|
||
globe.isLandscape = orientation == .landscape
|
||
let paragraph = NSMutableParagraphStyle()
|
||
paragraph.minimumLineHeight = lineHeight
|
||
paragraph.maximumLineHeight = lineHeight
|
||
paragraph.lineBreakMode = .byWordWrapping
|
||
let base: [NSAttributedString.Key: Any] = [.font: font, .paragraphStyle: paragraph]
|
||
let text = NSMutableAttributedString()
|
||
if transcript.isEmpty {
|
||
text.append(NSAttributedString(string: Self.placeholder, attributes: base.merging([.foregroundColor: palette.textMuted]) { $1 }))
|
||
accessibilityLabel = Self.placeholder
|
||
} else {
|
||
let shown = Self.tail(of: transcript, characters: shownCharacters)
|
||
text.append(NSAttributedString(string: shown.settled, attributes: base.merging([.foregroundColor: palette.textBase]) { $1 }))
|
||
text.append(NSAttributedString(string: shown.tentative, attributes: base.merging([.foregroundColor: palette.textMuted]) { $1 }))
|
||
accessibilityLabel = transcript.text
|
||
}
|
||
label.attributedText = text
|
||
placeWords()
|
||
}
|
||
|
||
/// About as many characters as fill the box and three lines more: a minute's text laid out
|
||
/// whole in a scrolling text view held 27 MB more in the keyboard (iPhone 17 Pro).
|
||
private var shownCharacters: Int {
|
||
let lines = max(1, box.bounds.height / lineHeight) + 3
|
||
let perLine = max(10, box.bounds.width / (font.pointSize * 0.42))
|
||
return max(200, Int(lines * perLine))
|
||
}
|
||
|
||
/// The end of `transcript` in at most `characters`, from a word's start: its settled part,
|
||
/// then its tentative tail as it follows them.
|
||
static func tail(of transcript: LiveTranscript, characters: Int) -> (settled: String, tentative: String) {
|
||
let settled = transcript.settled
|
||
let tentative = transcript.tentativeJoined
|
||
let total = settled.count + tentative.count
|
||
guard total > characters else { return (settled, tentative) }
|
||
let full = settled + tentative
|
||
var start = full.index(full.startIndex, offsetBy: total - characters)
|
||
// From a word's start, so no word shows cut.
|
||
if !full[full.index(before: start)].isWhitespace, let space = full[start...].firstIndex(where: \.isWhitespace) {
|
||
start = full[space...].firstIndex(where: { !$0.isWhitespace }) ?? start
|
||
}
|
||
let dropped = full.distance(from: full.startIndex, to: start)
|
||
if dropped >= settled.count {
|
||
return ("", String(full[start...]))
|
||
}
|
||
return (String(settled.dropFirst(dropped)), tentative)
|
||
}
|
||
|
||
private var lineHeight: CGFloat { (font.lineHeight * 1.08).rounded(.up) }
|
||
|
||
/// The newest line at the box's foot once the words overflow it, with whole lines above.
|
||
private func placeWords() {
|
||
let width = box.bounds.width
|
||
guard width > 0 else { return }
|
||
let height = label.sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude)).height.rounded(.up)
|
||
let overflow = height - box.bounds.height
|
||
let y = overflow > 0 ? -(overflow / lineHeight).rounded(.up) * lineHeight : 0
|
||
label.frame = CGRect(x: 0, y: y, width: width, height: height)
|
||
}
|
||
}
|
||
|
||
/// The globe key as the key plane draws it, for the preview to keep where it was.
|
||
@MainActor
|
||
private final class GlobeKeycapView: UIView {
|
||
var palette = FullKeyboardPalette(isDark: false) { didSet { if palette != oldValue { setNeedsDisplay() } } }
|
||
var isLandscape = false { didSet { if isLandscape != oldValue { setNeedsDisplay() } } }
|
||
var cornerRadius = FullKeyboardPalette.cornerRadius { didSet { if cornerRadius != oldValue { setNeedsDisplay() } } }
|
||
|
||
override init(frame: CGRect) {
|
||
super.init(frame: frame)
|
||
backgroundColor = .clear
|
||
isOpaque = false
|
||
contentMode = .redraw
|
||
}
|
||
|
||
@available(*, unavailable)
|
||
required init?(coder: NSCoder) { fatalError() }
|
||
|
||
override func draw(_ rect: CGRect) {
|
||
guard let context = UIGraphicsGetCurrentContext() else { return }
|
||
context.fillKeycap(bounds, fill: palette.keyFill, shadow: palette.keyShadow, radius: cornerRadius)
|
||
let config = UIImage.SymbolConfiguration(pointSize: isLandscape ? 16 : 19, weight: .regular)
|
||
guard let image = UIImage(systemName: "globe", withConfiguration: config)?
|
||
.withTintColor(palette.textBase, renderingMode: .alwaysOriginal) else { return }
|
||
image.draw(at: CGPoint(x: bounds.midX - image.size.width / 2, y: bounds.midY - image.size.height / 2 + (isLandscape ? 0 : -1)))
|
||
}
|
||
}
|
||
|
||
/// Puts `LiveDictationPreviewView` in place of a full keyboard's keys while it records with
|
||
/// live words (`KeyboardViewModel.liveText`), and takes it away, with the keys back, once
|
||
/// the dictation is in: the preview fades with the words it had while the keys and the
|
||
/// dictation's own text come in, so different words never flash in it.
|
||
@MainActor
|
||
final class LiveDictationPreviewHost {
|
||
private weak var keyboard: FullKeyboardView?
|
||
private var preview: LiveDictationPreviewView?
|
||
private var subscription: AnyCancellable?
|
||
static let fade: TimeInterval = 0.18
|
||
|
||
func attach(to keyboard: FullKeyboardView) {
|
||
self.keyboard = keyboard
|
||
subscription = keyboard.model.liveText.$transcript.sink { [weak self] transcript in
|
||
self?.sync(transcript)
|
||
}
|
||
}
|
||
|
||
var palette = FullKeyboardPalette(isDark: false) {
|
||
didSet { preview?.palette = palette }
|
||
}
|
||
|
||
/// The recording state changed.
|
||
func sync() {
|
||
sync(keyboard?.model.liveText.transcript)
|
||
}
|
||
|
||
private func sync(_ transcript: LiveTranscript?) {
|
||
guard let keyboard else { return }
|
||
let live = keyboard.model.liveText
|
||
guard keyboard.showsRecording, live.showsPreview, let transcript else {
|
||
hide()
|
||
return
|
||
}
|
||
let preview = self.preview ?? show(in: keyboard)
|
||
preview.show(transcript)
|
||
}
|
||
|
||
private func show(in keyboard: FullKeyboardView) -> LiveDictationPreviewView {
|
||
let preview = LiveDictationPreviewView()
|
||
preview.palette = keyboard.palette
|
||
preview.alpha = 0
|
||
keyboard.insertSubview(preview, aboveSubview: keyboard.plane)
|
||
self.preview = preview
|
||
layout()
|
||
let duration = keyboard.window == nil ? 0 : Self.fade
|
||
UIView.animate(withDuration: duration, delay: 0, options: [.beginFromCurrentState, .allowUserInteraction]) {
|
||
preview.alpha = 1
|
||
keyboard.plane.alpha = 0
|
||
}
|
||
return preview
|
||
}
|
||
|
||
private func hide() {
|
||
guard let preview, let keyboard else { return }
|
||
self.preview = nil
|
||
let duration = keyboard.window == nil ? 0 : Self.fade
|
||
UIView.animate(withDuration: duration, delay: 0, options: [.beginFromCurrentState, .allowUserInteraction]) {
|
||
preview.alpha = 0
|
||
keyboard.plane.alpha = 1
|
||
} completion: { _ in
|
||
preview.removeFromSuperview()
|
||
}
|
||
}
|
||
|
||
/// Where the keys were, under the recording bar to the keyboard's bottom.
|
||
func layout() {
|
||
guard let preview, let keyboard else { return }
|
||
let layout = keyboard.engine.layout
|
||
preview.frame = layout.keysAreaFrame.offsetBy(dx: keyboard.plane.frame.minX, dy: keyboard.plane.frame.minY)
|
||
let side = layout.horizontalInset + layout.metrics.side + 4
|
||
var bottom: CGFloat = 10
|
||
// The globe keeps working where the keyboard has one: its button is above the words.
|
||
if let globe = layout.key(.globe), !keyboard.globeButton.isHidden {
|
||
let frame = globe.frame.offsetBy(dx: keyboard.plane.frame.minX - preview.frame.minX, dy: keyboard.plane.frame.minY - preview.frame.minY)
|
||
preview.globeFrame = frame
|
||
bottom = max(bottom, preview.bounds.height - frame.minY + 4)
|
||
preview.globeRadius = layout.metrics.cornerRadius
|
||
} else {
|
||
preview.globeFrame = nil
|
||
}
|
||
preview.textInsets = UIEdgeInsets(top: layout.metrics.rowGap + 4, left: side, bottom: bottom, right: side)
|
||
preview.orientation = keyboard.orientation
|
||
}
|
||
}
|