hex/ios/HEXMobile/KeyboardSetup.swift
Ryan Vogel ee34feb49b iOS: dictate in every language Apple Speech has on device
A Norwegian TestFlight tester's iPhone silently fell back to English:
Hex picked the first preferred language SpeechTranscriber supports, and
SpeechTranscriber has no Norwegian, Danish, Swedish or Hebrew. Testers
also asked for Spanish and German.

What changed:
- SpeechLanguagePicker picks the dictation language: an explicit choice
  wins (SpeechTranscriber where it has the language, else
  DictationTranscriber); Automatic takes the first preferred iPhone
  language either module has, SpeechTranscriber first for the same
  language, then the region's locale, then en-US. Nynorsk tries Bokmal.
- AppleSpeechModule wraps SpeechTranscriber and DictationTranscriber
  (preset longDictation) for the same SpeechAnalyzer flow and asset
  download; the app's AppleSpeechTranscriber and in-keyboard dictation
  both use it and AppleSpeechLanguages, so they resolve the same language
  and share downloaded assets.
- Settings > Dictation language (iOS 26): Automatic plus every locale
  either module supports, by name, saved in the App Group
  (settings.dictationLanguage). Picking one prepares its model now, or
  after the dictation in flight. The setup card's Speech model row names
  the real language ("Norwegian Bokmal · Apple").
- English-only steps follow the language: the cleanup tagger skips other
  languages; Apple Intelligence cleanup runs only when the model supports
  the language; filler trimming is per language (English "er" was eating
  Norwegian "er" = "is"; Portuguese "um" is a word); translation's source
  is the dictation language instead of a guess.
- Replaced: AppleSpeechTranscriber.preferredLocale()/isAvailable with
  preferredLanguage()/shouldUse(_:). An iPhone without SpeechTranscriber
  still dictates English with Parakeet, as before.

Verified: xcodebuild test on the iPhone 18 Pro simulator (iOS 27.2),
189 tests, 0 failures, including new picker, language-change, filler and
tagger tests; Release generic-iOS build with CODE_SIGNING_ALLOWED=NO
succeeds. The simulator can't transcribe (SpeechTranscriber unavailable,
DictationTranscriber "Model not available"); the same Swift files built
for macOS 26 transcribed say clips word for word: de-DE and es-ES via
SpeechTranscriber, nb-NO and he-IL via DictationTranscriber (no
punctuation from DictationTranscriber under any preset). Not tried on a
physical iPhone.
2026-11-20 07:52:32 -05:00

245 lines
8.8 KiB
Swift

import AVFAudio
import Observation
import SwiftUI
import UIKit
/// Live keyboard setup state, read from the system and the App Group.
@MainActor
@Observable
final class KeyboardSetupMonitor {
static let keyboardBundleID = "anomaly.hex.mobile.keyboard"
private let bridge: KeyboardBridge
/// nil when iOS doesn't say which keyboards are enabled.
private(set) var keyboardAdded: Bool?
private(set) var fullAccessOn = false
private(set) var microphone = AVAudioApplication.shared.recordPermission
init(bridge: KeyboardBridge = KeyboardBridge()) {
self.bridge = bridge
refresh()
}
var keyboardReady: Bool {
keyboardAdded == true && fullAccessOn
}
func refresh() {
let args = ProcessInfo.processInfo.arguments
if let idx = args.firstIndex(of: "--snap-state"), idx + 1 < args.count {
switch args[idx + 1] {
case "setup", "onboarding-try", "onboarding-try-off":
keyboardAdded = true
fullAccessOn = false
microphone = .granted
case "onboarding-welcome", "onboarding-allow":
keyboardAdded = true
fullAccessOn = false
microphone = .undetermined
case "onboarding-tour":
let elapsed = OnboardingFixture.Tour.elapsed
keyboardAdded = elapsed >= OnboardingFixture.Tour.keyboardAdded
fullAccessOn = elapsed >= OnboardingFixture.Tour.fullAccess
microphone = elapsed >= OnboardingFixture.Tour.microphoneAllowed ? .granted : .undetermined
default:
keyboardAdded = true
fullAccessOn = true
microphone = .granted
}
return
}
fullAccessOn = bridge.fullAccessSeenAt != nil
if let keyboards = UserDefaults.standard.stringArray(forKey: "AppleKeyboards") {
keyboardAdded = keyboards.contains(Self.keyboardBundleID) || fullAccessOn
} else {
keyboardAdded = fullAccessOn ? true : nil
}
microphone = AVAudioApplication.shared.recordPermission
}
func requestMicrophone() {
AVAudioApplication.requestRecordPermission { _ in
Task { @MainActor [weak self] in
self?.refresh()
}
}
}
}
struct KeyboardSetupCard: View {
@Environment(\.openURL) private var openURL
@Bindable var dictation: DictationController
let monitor: KeyboardSetupMonitor
@State private var checkText = ""
@FocusState private var checkFocused: Bool
/// iOS only tells Hex about Full Access from inside its keyboard, so until the keyboard
/// has run once with it, the app can't tell "on" from "off".
private var needsKeyboardCheck: Bool {
monitor.keyboardAdded != false && !monitor.fullAccessOn
}
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Keyboard setup")
.font(.system(size: 15, weight: .medium))
.foregroundStyle(HexTheme.textBase)
VStack(spacing: 0) {
row(
title: "Hex Keyboard",
status: keyboardStatus,
done: monitor.keyboardAdded == true
)
divider
row(
title: "Allow Full Access",
status: monitor.fullAccessOn ? "On" : needsKeyboardCheck ? "Not checked" : "Off",
done: monitor.fullAccessOn
)
divider
row(
title: "Microphone",
status: microphoneStatus,
done: monitor.microphone == .granted
) {
if monitor.microphone == .undetermined {
smallButton("Allow") { monitor.requestMicrophone() }
}
}
divider
row(
title: "Speech model",
status: modelStatus,
done: dictation.isModelReady
)
}
if needsKeyboardCheck {
VStack(alignment: .leading, spacing: 8) {
Text("Already turned it on? Tap the field and switch to Hex with \(Image(systemName: "globe")). Hex can only check Full Access from its keyboard.")
.font(.system(size: 12))
.foregroundStyle(HexTheme.textMuted)
.fixedSize(horizontal: false, vertical: true)
TextField("Tap here, then switch to Hex", text: $checkText)
.font(.system(size: 15))
.foregroundStyle(HexTheme.textBase)
.focused($checkFocused)
.padding(.horizontal, 14)
.frame(minHeight: 40)
.background(Color.white.opacity(0.06), in: Capsule())
}
}
if !monitor.keyboardReady || monitor.microphone == .denied {
Button {
if let url = URL(string: UIApplication.openSettingsURLString) {
openURL(url)
}
} label: {
HStack(spacing: 7) {
Image(systemName: "gearshape.fill")
.font(.system(size: 13, weight: .medium))
Text("Open Settings")
.font(.system(size: 15, weight: .medium))
}
.foregroundStyle(HexTheme.textBase)
.frame(maxWidth: .infinity, minHeight: 40)
.background(Color.white.opacity(0.09), in: Capsule())
}
.buttonStyle(.plain)
}
}
.padding(16)
.background(HexTheme.bgBase, in: RoundedRectangle(cornerRadius: HexTheme.cardRadius, style: .continuous))
.onChange(of: monitor.fullAccessOn) { _, on in
if on { checkFocused = false }
}
}
private var keyboardStatus: String {
switch monitor.keyboardAdded {
case true?: "Added"
case false?: "Not added"
case nil: "Not verified"
}
}
private var microphoneStatus: String {
switch monitor.microphone {
case .granted: "Allowed"
case .denied: "Off"
default: "Required"
}
}
private var modelStatus: String {
if dictation.isModelReady {
// "Norwegian Bokmål · Apple": the language it really transcribes, short enough
// for the row.
let code = Locale(identifier: dictation.transcriptionLanguageID).language.languageCode?.identifier ?? "en"
let language = Locale.current.localizedString(forLanguageCode: code).map {
$0.prefix(1).uppercased() + $0.dropFirst()
} ?? dictation.transcriptionLanguage
let engine = dictation.engineName == "Apple Speech" ? "Apple" : dictation.engineName
return "\(language) · \(engine)"
}
switch dictation.phase {
case .preparingModel:
return "\(Int(dictation.modelPreparation.fractionCompleted * 100))%"
case .failed:
return "Failed"
default:
return "Preparing"
}
}
private func row(title: String, status: String, done: Bool) -> some View {
row(title: title, status: status, done: done) { EmptyView() }
}
private func row<Trailing: View>(
title: String,
status: String,
done: Bool,
@ViewBuilder trailing: () -> Trailing
) -> some View {
HStack(alignment: .center, spacing: 10) {
Image(systemName: done ? "checkmark.circle.fill" : "circle")
.font(.system(size: 16, weight: .medium))
.foregroundStyle(done ? HexTheme.success : HexTheme.textFaint)
Text(title)
.font(.system(size: 15, weight: .regular))
.foregroundStyle(HexTheme.textBase)
Spacer(minLength: 8)
Text(status)
.font(.system(size: 13))
.foregroundStyle(HexTheme.textMuted)
.lineLimit(1)
trailing()
}
.padding(.vertical, 9)
}
private func smallButton(_ title: String, action: @escaping () -> Void) -> some View {
Button(title, action: action)
.font(.system(size: 13, weight: .medium))
.foregroundStyle(HexTheme.textBase)
.padding(.horizontal, 12)
.frame(height: 28)
.background(Color.white.opacity(0.09), in: Capsule())
.buttonStyle(.plain)
}
private var divider: some View {
Rectangle()
.fill(HexTheme.borderWeak)
.frame(height: 0.5)
}
}