mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
* iOS keyboard: choose several languages and switch them on the space bar
A TestFlight tester asked for more than one keyboard language. Settings ›
Keyboard › Keyboard layout (one menu: Automatic or one layout) becomes
Languages, a page where you tick one or more languages and drag them into
order. Automatic stays, and stays the default: unset, it still follows the
dictation language. The iPhone's own keyboards' and preferred languages'
layouts are offered first ("On this iPhone"), then the rest. Ticking a
language from Automatic keeps Automatic's language beside it; unticking the
last goes back to Automatic.
With two or more languages the space bar names the current one, and a
quick swipe along it switches (left the next, right the one before),
changing the letters (QWERTY, AZERTY, ЙЦУКЕН), accents and autocorrect
language. Apple and Gboard switch with a long press on the globe, but
Face ID iPhones have no globe in a third-party keyboard and Hex's space-bar
slide is already its cursor trackpad, so this follows SwiftKey: with two or
more languages the cursor slides once the space bar was held
(trackpadHoldDelay, 0.4 s, the hold #2100 added, as Apple's), a slide
before that is a language swipe, and one shorter than 24 pt still types a
space. The hold timer firing during a slow swipe leaves it a swipe. With
one language nothing changes. The globe key is untouched
(handleInputModeList: next keyboard, list on hold).
The current language persists (settings.keyboardLanguages.current), so the
keyboard comes back in it. Optional Switch dictation too (off by default)
sets the dictation language to the keyboard's on each switch, in the
iPhone's region where Apple Speech has it (en-GB on a British iPhone).
Storage: settings.keyboardLanguages (array). It reads the old
settings.keyboardLayout until first written and writes its first language
there for an older build. "Keyboard layout" string removed; new strings
have zh-Hans entries.
Verified: xcodebuild test FullKeyboardEngineTests + KeyboardLayoutTests on
an iOS 27.2 simulator (54 tests, 0 failures), with new cases for the swipe
vs hold, switching in a FullKeyboardView, resolution, migration and the
dictation language pick.
* iOS keyboard: bilingual autocorrect for two Latin-script languages
With two or more keyboard languages, autocorrect and the strip also check
the first other chosen language with Latin letters and an iOS dictionary,
on the current keys, as Apple's "Français et English" keyboard does:
French with English beside it, English with French; Russian alone (Cyrillic)
and no partner for Serbian (no iOS dictionary) or between two French
layouts (one dictionary).
AutocorrectEngine gets a partner engine with its own UITextChecker language
and, where one is bundled (en, es), Spatial autocorrect's model reading the
same taps on the current layout. It shares your words (learned words, text
replacements, Learn how I type). Rules:
- a word either language knows as typed is never changed (only your text
replacements still apply), so French "dont" never becomes "don't" and
English "the" never becomes "thé";
- a typo only one language can fix gets that fix ("teh" -> "the" while
French types);
- when both can, the language of the last few words only one dictionary
knows wins, else the clearly cheaper slip on these keys, else the
keyboard's own language;
- the strip interleaves both languages' fixes and completions, the leaning
language first; spelling guesses only for a word neither knows;
- one-letter words stay with the keyboard's own language (UITextChecker
takes every letter as a word, so English "i" still becomes "I").
Slip costs now use the layout you type on (layoutLanguage), so the partner
prices AZERTY neighbours on the French keys.
Measured in the iOS 27.2 simulator (testABilingualKeyboardKeepsBothLanguagesWords,
iOS dictionaries plus the English Spatial model, each word in an empty field):
the English keyboard alone changed 34 of 77 common French words (demain ->
remain, dont -> don't, que -> we, cette -> centre...) and the French keyboard
alone 28 of 80 common English words (was -> sas, then -> the, people ->
peuple...); with English and French chosen, 0 of either, typing in either
layout, and neither language's own words changed.
Verified: xcodebuild test FullKeyboardEngineTests, AutocorrectEngineTests
and KeyboardLayoutTests (91 tests, 0 failures), with new cases for the
rules on stub dictionaries, the real-dictionary sentence "Bonjour merci the
meeting est dont teh tomorow demian" -> "... the tomorrow demain" on the
French keyboard, and the pairing rule.
* iOS settings: drag handles for newly ticked languages, French's region
Keyboard › Languages: a language ticked while the page was open showed no
drag handle (SwiftUI gives a row added in edit mode no reorder control), so
it couldn't be reordered until the page was opened again. The chosen
section's rows are now rebuilt whenever the list changes (.id of the
list). Français (France)'s line in the iPhone's language now reads its
region too ("French (France)", "法语(法国)"), like the other two French
layouts.
Verified in the iOS 27.2 simulator: unticking and re-ticking Français
shows its handle; dragging it above Русский reorders the list and the App
Group (settings.keyboardLanguages en, fr, ru); screenshots in English and
Chinese.
* iOS docs: keyboard languages, the space-bar swipe and bilingual autocorrect
README: Settings › Keyboard › Languages (Automatic or chosen languages in
order), the space-bar swipe and why it beats a long press on the globe here,
the hold-then-slide trackpad with two or more languages, the persisted
current language, Switch dictation too, bilingual autocorrect's rules and
measured break counts, the space bar naming the keyboard's language while
it switches, the tests that cover them, and the simulator memory figures
(the second language costs about 1 MB after a sentence: Français 28.7-28.8
alone vs 29.7-29.9 MB with English; English 28.9-29.9 vs 29.5-29.9 MB with
Français). typing-logs.md: the language_swipe and keyboard_language ui
lines.
Docs only; the figures come from the iOS 27.2 simulator runs on this branch.
* iOS docs: bilingual break count on the rebased keyboard
After rebasing onto #2100/#2101 (tap targets near the strip, learned-word
erasing), testABilingualKeyboardKeepsBothLanguagesWords reports the French
keyboard alone changing 27 of 80 common English words, not 28 (one word
fewer); the English keyboard alone still changes 34 of 77 French words and
English + French none of either. README updated to the current figure.
Verified: full xcodebuild test on the rebased branch, iOS 27.2 simulator,
327 tests, 0 failures, 1 skipped (AppleSpeechClipTests, no clips).
305 lines
15 KiB
Swift
305 lines
15 KiB
Swift
import Foundation
|
||
|
||
/// Settings › Dictation language and Settings › Keyboard › Languages, in the App Group so the
|
||
/// keyboard reads them and can switch the language.
|
||
nonisolated struct LanguageSettings {
|
||
private enum Key {
|
||
static let dictation = "settings.dictationLanguage"
|
||
static let resolvedDictation = "settings.dictationLanguage.resolved"
|
||
static let automaticDictation = "settings.dictationLanguage.automatic"
|
||
static let recent = "settings.dictationLanguage.recent"
|
||
static let supported = "settings.dictationLanguage.supported"
|
||
/// One layout, or none for Automatic: the setting before Languages, still written
|
||
/// with the first language for an older build.
|
||
static let keyboardLayout = "settings.keyboardLayout"
|
||
static let keyboardLanguages = "settings.keyboardLanguages"
|
||
static let currentKeyboardLanguage = "settings.keyboardLanguages.current"
|
||
static let dictationFollowsKeyboard = "settings.keyboardLanguages.switchDictation"
|
||
static let speechModuleFailed = "settings.dictationLanguage.speechModuleFailed"
|
||
static let unavailable = "settings.dictationLanguage.unavailable"
|
||
static let keyboardNeedsHex = "settings.dictationLanguage.keyboardNeedsHex"
|
||
}
|
||
|
||
static let maxRecent = 5
|
||
/// How long a language whose speech model wouldn't install stays set aside before Hex
|
||
/// tries it again: Apple's downloads that fail tend to keep failing for days.
|
||
static let setAsideDuration: TimeInterval = 3 * 24 * 60 * 60
|
||
|
||
private let defaults: UserDefaults?
|
||
|
||
init(defaults: UserDefaults? = UserDefaults(suiteName: KeyboardBridge.appGroup)) {
|
||
self.defaults = defaults
|
||
}
|
||
|
||
/// A BCP 47 identifier such as `nb-NO`, or nil for Automatic.
|
||
var dictationLanguage: String? {
|
||
get { defaults?.string(forKey: Key.dictation) }
|
||
nonmutating set { defaults?.set(newValue, forKey: Key.dictation) }
|
||
}
|
||
|
||
/// The language Apple Speech last resolved for dictation (the app or the keyboard), so
|
||
/// translation can follow it without asking Speech again.
|
||
var resolvedDictationLanguage: String? {
|
||
get { defaults?.string(forKey: Key.resolvedDictation) }
|
||
nonmutating set { defaults?.set(newValue, forKey: Key.resolvedDictation) }
|
||
}
|
||
|
||
/// What Automatic picks on this iPhone, when the app or keyboard last worked it out.
|
||
var automaticDictationLanguage: String? {
|
||
get { defaults?.string(forKey: Key.automaticDictation) }
|
||
nonmutating set { defaults?.set(newValue, forKey: Key.automaticDictation) }
|
||
}
|
||
|
||
/// Languages picked lately, newest first, for the keyboard's quick switch.
|
||
var recentDictationLanguages: [String] {
|
||
get { defaults?.stringArray(forKey: Key.recent) ?? [] }
|
||
nonmutating set { defaults?.set(Array(newValue.prefix(Self.maxRecent)), forKey: Key.recent) }
|
||
}
|
||
|
||
/// Every language Apple Speech transcribes here (BCP 47), as last listed, so the
|
||
/// keyboard can offer only those without asking Speech.
|
||
var supportedDictationLanguages: [String] {
|
||
get { defaults?.stringArray(forKey: Key.supported) ?? [] }
|
||
nonmutating set { defaults?.set(newValue, forKey: Key.supported) }
|
||
}
|
||
|
||
/// Settings › Keyboard › Languages: the full keyboard's languages in order, the space bar
|
||
/// switching between them; empty is Automatic (the dictation language's layout). Until
|
||
/// it is first written, the one layout chosen before (`settings.keyboardLayout`).
|
||
var keyboardLanguages: [KeyboardLanguage] {
|
||
get {
|
||
let stored = defaults?.stringArray(forKey: Key.keyboardLanguages)
|
||
?? defaults?.string(forKey: Key.keyboardLayout).map { [$0] }
|
||
?? []
|
||
var seen = Set<KeyboardLanguage>()
|
||
return stored.compactMap(KeyboardLanguage.init(rawValue:)).filter { seen.insert($0).inserted }
|
||
}
|
||
nonmutating set {
|
||
var seen = Set<KeyboardLanguage>()
|
||
let languages = newValue.filter { seen.insert($0).inserted }
|
||
defaults?.set(languages.map(\.rawValue), forKey: Key.keyboardLanguages)
|
||
defaults?.set(languages.first?.rawValue, forKey: Key.keyboardLayout)
|
||
}
|
||
}
|
||
|
||
/// The language the space bar last switched to, so the keyboard comes back in it.
|
||
var currentKeyboardLanguage: KeyboardLanguage? {
|
||
get { defaults?.string(forKey: Key.currentKeyboardLanguage).flatMap(KeyboardLanguage.init(rawValue:)) }
|
||
nonmutating set { defaults?.set(newValue?.rawValue, forKey: Key.currentKeyboardLanguage) }
|
||
}
|
||
|
||
/// Settings › Keyboard › Languages › Switch dictation too: switching the keyboard's language
|
||
/// on the space bar switches the dictation language to it. Off by default.
|
||
var dictationFollowsKeyboard: Bool {
|
||
get { defaults?.bool(forKey: Key.dictationFollowsKeyboard) ?? false }
|
||
nonmutating set { defaults?.set(newValue, forKey: Key.dictationFollowsKeyboard) }
|
||
}
|
||
|
||
/// The language dictation uses, when known: the one set, else what Automatic picks,
|
||
/// else the last one it ran in.
|
||
var effectiveDictationLanguage: String? {
|
||
dictationLanguage ?? automaticDictationLanguage ?? resolvedDictationLanguage
|
||
}
|
||
|
||
/// `SpeechTranscriber`'s model for this language (BCP 47) wouldn't install, so dictation
|
||
/// uses `DictationTranscriber`'s for a while.
|
||
func markSpeechModuleFailed(_ identifier: String, at now: Date = Date()) {
|
||
mark(identifier, key: Key.speechModuleFailed, at: now)
|
||
}
|
||
|
||
func speechModuleFailed(_ identifier: String, now: Date = Date()) -> Bool {
|
||
isMarked(identifier, key: Key.speechModuleFailed, now: now)
|
||
}
|
||
|
||
/// How long the keyboard hands dictation to Hex after it couldn't get a model itself.
|
||
static let keyboardNeedsHexDuration: TimeInterval = 24 * 60 * 60
|
||
|
||
/// In-keyboard dictation couldn't get its speech model ready (an asset released or
|
||
/// removed since Hex downloaded it, a download the keyboard couldn't finish), so the Hex
|
||
/// key opens Hex, which downloads it in the foreground. Until a model installs
|
||
/// (`SpeechModelInstall`), a language is chosen, or a day passes.
|
||
func markKeyboardNeedsHex(at now: Date = Date()) {
|
||
defaults?.set(now.timeIntervalSince1970, forKey: Key.keyboardNeedsHex)
|
||
}
|
||
|
||
func keyboardNeedsHex(now: Date = Date()) -> Bool {
|
||
guard let at = defaults?.object(forKey: Key.keyboardNeedsHex) as? Double else { return false }
|
||
return now.timeIntervalSince1970 - at < Self.keyboardNeedsHexDuration
|
||
}
|
||
|
||
func clearKeyboardNeedsHex() {
|
||
guard defaults?.object(forKey: Key.keyboardNeedsHex) != nil else { return }
|
||
defaults?.removeObject(forKey: Key.keyboardNeedsHex)
|
||
}
|
||
|
||
/// Neither module's model for this language (BCP 47) would install while online, so
|
||
/// Automatic passes over it for a while. An explicit choice still tries it.
|
||
func markUnavailable(_ identifier: String, at now: Date = Date()) {
|
||
mark(identifier, key: Key.unavailable, at: now)
|
||
}
|
||
|
||
func isUnavailable(_ identifier: String, now: Date = Date()) -> Bool {
|
||
isMarked(identifier, key: Key.unavailable, now: now)
|
||
}
|
||
|
||
/// A language that installed after all.
|
||
func clearUnavailable(_ identifier: String) {
|
||
let key = Locale(identifier: identifier).identifier(.bcp47)
|
||
guard var marks = defaults?.dictionary(forKey: Key.unavailable) as? [String: Double],
|
||
marks.removeValue(forKey: key) != nil else { return }
|
||
defaults?.set(marks, forKey: Key.unavailable)
|
||
}
|
||
|
||
private func mark(_ identifier: String, key: String, at now: Date) {
|
||
var marks = (defaults?.dictionary(forKey: key) as? [String: Double]) ?? [:]
|
||
marks = marks.filter { now.timeIntervalSince1970 - $0.value < Self.setAsideDuration }
|
||
marks[Locale(identifier: identifier).identifier(.bcp47)] = now.timeIntervalSince1970
|
||
defaults?.set(marks, forKey: key)
|
||
}
|
||
|
||
private func isMarked(_ identifier: String, key: String, now: Date) -> Bool {
|
||
guard let marks = defaults?.dictionary(forKey: key) as? [String: Double],
|
||
let at = marks[Locale(identifier: identifier).identifier(.bcp47)] else { return false }
|
||
return now.timeIntervalSince1970 - at < Self.setAsideDuration
|
||
}
|
||
|
||
/// A choice made in Hex or the keyboard: the setting, and the front of the recents.
|
||
func chooseDictationLanguage(_ identifier: String?) {
|
||
dictationLanguage = identifier
|
||
clearKeyboardNeedsHex()
|
||
if let identifier {
|
||
recentDictationLanguages = [identifier] + recentDictationLanguages.filter { $0 != identifier }
|
||
}
|
||
}
|
||
}
|
||
|
||
/// The Apple Speech module that transcribes a language. `SpeechTranscriber` is Apple's newer
|
||
/// model and Hex's default; `DictationTranscriber` (the model behind the iOS keyboard's
|
||
/// dictation) covers languages it lacks, such as Norwegian, Danish, and Swedish.
|
||
nonisolated enum SpeechModuleKind: String, Codable, Sendable {
|
||
case speech
|
||
case dictation
|
||
}
|
||
|
||
nonisolated struct SpeechLanguage: Equatable, Sendable {
|
||
let locale: Locale
|
||
let module: SpeechModuleKind
|
||
|
||
var identifier: String { locale.identifier(.bcp47) }
|
||
var languageCode: String? { locale.language.languageCode?.identifier }
|
||
}
|
||
|
||
/// One entry in Settings › Dictation language.
|
||
nonisolated struct SpeechLanguageOption: Equatable, Identifiable, Sendable {
|
||
/// BCP 47, such as `nb-NO`.
|
||
let id: String
|
||
let name: String
|
||
}
|
||
|
||
/// Which language and Apple Speech module a dictation uses.
|
||
nonisolated enum SpeechLanguagePicker {
|
||
/// What Automatic tries, in order: the iPhone's preferred languages, its own locale, then
|
||
/// US English. Norwegian Nynorsk also tries Bokmål, the only Norwegian Apple transcribes.
|
||
static func automaticCandidates(preferred: [String], current: String) -> [String] {
|
||
var result: [String] = []
|
||
var seen = Set<String>()
|
||
func add(_ identifier: String) {
|
||
let key = Locale(identifier: identifier).identifier(.bcp47)
|
||
if seen.insert(key).inserted {
|
||
result.append(identifier)
|
||
}
|
||
}
|
||
for identifier in preferred + [current, "en-US"] {
|
||
add(identifier)
|
||
if Locale(identifier: identifier).language.languageCode?.identifier == "nn" {
|
||
add("nb-NO")
|
||
}
|
||
}
|
||
return result
|
||
}
|
||
|
||
/// An explicit choice wins: `SpeechTranscriber` when it has that language, else
|
||
/// `DictationTranscriber`. Automatic takes the first candidate either module has,
|
||
/// preferring `SpeechTranscriber` for the same language, so a Norwegian iPhone gets
|
||
/// Norwegian from `DictationTranscriber` rather than English from `SpeechTranscriber`.
|
||
/// `speech` and `dictation` return each module's equivalent locale, or nil. Automatic
|
||
/// passes over a language `skip` names (one whose model wouldn't install here), so it
|
||
/// lands on the next working one; an explicit choice is tried as it is. When every
|
||
/// language either module has was set aside (an English-only iPhone whose English model
|
||
/// failed once), Automatic tries the first of them again: nil means neither module has
|
||
/// any of them, never that Hex gave up on the only one there is.
|
||
static func pick(
|
||
explicit: String?,
|
||
candidates: [String],
|
||
speech: (Locale) async -> Locale?,
|
||
dictation: (Locale) async -> Locale?,
|
||
skip: (Locale) -> Bool = { _ in false }
|
||
) async -> SpeechLanguage? {
|
||
if let explicit, !explicit.isEmpty {
|
||
let wanted = Locale(identifier: explicit)
|
||
if let found = await speech(wanted), sameLanguage(found, wanted) {
|
||
return SpeechLanguage(locale: found, module: .speech)
|
||
}
|
||
if let found = await dictation(wanted) {
|
||
return SpeechLanguage(locale: found, module: .dictation)
|
||
}
|
||
}
|
||
var setAside: SpeechLanguage?
|
||
for identifier in candidates {
|
||
let candidate = Locale(identifier: identifier)
|
||
if let found = await speech(candidate) {
|
||
let language = SpeechLanguage(locale: found, module: .speech)
|
||
guard skip(found) else { return language }
|
||
setAside = setAside ?? language
|
||
continue
|
||
}
|
||
if let found = await dictation(candidate) {
|
||
let language = SpeechLanguage(locale: found, module: .dictation)
|
||
guard skip(found) else { return language }
|
||
setAside = setAside ?? language
|
||
}
|
||
}
|
||
return setAside
|
||
}
|
||
|
||
/// The same language and, when both name one, the same region.
|
||
private static func sameLanguage(_ a: Locale, _ b: Locale) -> Bool {
|
||
guard a.language.languageCode == b.language.languageCode else { return false }
|
||
guard let ra = a.region, let rb = b.region else { return true }
|
||
return ra == rb
|
||
}
|
||
|
||
/// "Norwegian Bokmål (Norway)" in the iPhone's own language.
|
||
static func displayName(for identifier: String, in display: Locale = .current) -> String {
|
||
display.localizedString(forIdentifier: identifier)
|
||
?? Locale(identifier: identifier).localizedString(forIdentifier: identifier)
|
||
?? identifier
|
||
}
|
||
|
||
/// Short names for a list of locales: the language alone where it has one region in the
|
||
/// list ("Norwegian Bokmål"), the full name where it has several ("English (Canada)").
|
||
static func shortNames(for identifiers: [String], in display: Locale = .current) -> [String: String] {
|
||
var regionsPerLanguage: [String: Int] = [:]
|
||
for identifier in identifiers {
|
||
let code = Locale(identifier: identifier).language.languageCode?.identifier ?? identifier
|
||
regionsPerLanguage[code, default: 0] += 1
|
||
}
|
||
var names: [String: String] = [:]
|
||
for identifier in identifiers {
|
||
let code = Locale(identifier: identifier).language.languageCode?.identifier ?? identifier
|
||
if regionsPerLanguage[code] == 1, let language = display.localizedString(forLanguageCode: code) {
|
||
names[identifier] = language.prefix(1).uppercased() + language.dropFirst()
|
||
} else {
|
||
names[identifier] = displayName(for: identifier, in: display)
|
||
}
|
||
}
|
||
return names
|
||
}
|
||
|
||
/// Whether a language identifier is English, for the English-only steps (the cleanup
|
||
/// tagger). nil (unknown) counts as English, as before languages existed.
|
||
static func isEnglish(_ identifier: String?) -> Bool {
|
||
guard let identifier else { return true }
|
||
return Locale(identifier: identifier).language.languageCode?.identifier == "en"
|
||
}
|
||
}
|