iOS: Polish keyboard, diacritic autocorrect, and a bilingual partner fix (#2143)

* iOS: Polish keyboard layout

A TestFlight tester on build 56 asked for Polish. Adds KeyboardLanguage.polish
("pl", Polski). It matches the standard Polish layout and the system
keyboard's observed long-press options: QWERTY on the English letters, with
every letter, 123 and #+= key of the iOS 27.2 simulator's own Polish keyboard
held for about 3 s with a real touch and its callout read from the
accessibility tree (the keyboard-provenance survey and converter, as for the
other languages since #2140), and the letters checked again on screenshots.

letterHolds, base first: a ą à á â ä æ ã å ā; c ć ç č; e ę è é ê ë ė ē; l ł;
n ń ñ; o ó ô ö ò õ œ ø ō; s ś ß š; z ż ź ž; every other letter, U, I and Y
included, holds nothing. symbolHolds: the system keyboard's 123 currency key
is € (no zł anywhere), held for € $ £ ¥ ₩ ₽, so Hex's #+= € holds that; Hex's
123 page keeps $ and every other symbol key holds as English's does (& was
read too: & §).

Autocorrect uses iOS's pl dictionary through the dictionary engine, as Russian
and Ukrainian do: no typing model, since no commercially safe Polish word and
word-pair frequencies were found (Google Books Ngram v3 has no Polish; the
usual frequency lists are share-alike). Never-suggest's shared entries still
apply. Polish has Latin letters, so it pairs with English for bilingual
autocorrect. pl/pl-PL picks the layout automatically (dictation language,
then the iPhone's keyboards and languages), the space bar says "Polski" while
switching, and Switch dictation too dictates pl-PL. Hex's short next-word lists
get Polish entries (ja, to, nie; a, ale, że; nie, i, w, się, na, to).
Snapshot scenes take --keyboard-layout pl. Other layouts are unchanged.

Verified: KeyboardLayoutTests and FullKeyboardEngineTests pass on an iPhone
17 Pro simulator (iOS 27.2), including new Polish cases (rows, held keys and
their menus at every width, automatic pick, switching, typing zażółćęśąńź
through the holds, U/I/Y opening nothing), and the full HEXMobile suite
passes.

* iOS: Polish autocorrect restores missing diacritics

Typing Polish without its diacritics is common ("zolw" for "żółw"), but a
word lacking two or three of them was more than the one edit autocorrect
accepts, and l -> ł (ł has no Unicode decomposition) cost a far-away key, so
"maly" lost to any one-key guess listed before "mały". On the Polish layout,
a guess that differs from what you typed only by diacritics (ą ć ę ł ń ó ś ź
ż) now costs what one missing Spanish accent does (0.15), plus 0.05 for each
further one. Other layouts keep the one-edit rule.

Verified: AutocorrectEngineTests pass on an iPhone 17 Pro simulator (iOS
27.2), including the new costs and fixes for zolw, Zolw, maly (over "mamy",
listed first) and dzien, with words left alone and no three-edit fix on
Spanish. The simulator lists pl_PL but its checker treats every word as
valid and offers no Polish guess, so the engine fixes run against a stub
dictionary answering as an iPhone's would; unverified on a physical iPhone.

* iOS: cover Polish dictation and its cleanup

Polish dictation already works through Apple Speech: macOS 27.2.1 lists
pl-PL for DictationTranscriber only (not SpeechTranscriber), and say -v Zosia
clips came back with every diacritic (ą ć ę ł ń ó ś ź ż), numbers as digits
("10 min", "19:30") and no punctuation. Parakeet is English-only, so pl-PL
always goes to Apple Speech. No code change was needed; this records it.

Tests: SpeechLanguagePickerTests picks pl-PL from DictationTranscriber,
chosen by hand and by a Polish iPhone's Automatic. TranscriptCleanupTests
check Polished (capital, final stop, Polish "i" left alone by English's "i"
rule), Casual, Verbatim, and Lowercase lowering Ą Ć Ę Ł Ń Ó Ś Ź Ż. README
notes the macOS run under Dictation languages.

Verified: SpeechLanguagePickerTests and SpokenCleanupRulesTests pass on an
iPhone 17 Pro simulator (iOS 27.2). In the simulator, a Polish iPhone's
Settings › Dictation language shows Automatic as "Polish (Poland)", lists
Polish (Poland) to pick, and the Hex key's menu shows Language: Polski; the
simulator has no speech models, so dictating itself is unverified there.

* iOS: bilingual autocorrect skips a partner dictionary that takes every word

With English and Polish chosen, "teh " stayed "teh" in the iOS 27.2
simulator. iOS lists pl_PL there but has no Polish word data, so
UITextChecker takes any letters for a Polish word, and bilingual autocorrect
keeps a word the partner language knows as typed: every English typo became
"a Polish word". Polish is the first Latin-script layout whose dictionary can
be listed without data (Ukrainian's uk_UA does the same, but Cyrillic never
gets a partner), so the Polish layout is what exposed it. The same would
happen on an iPhone that lists a language before its data is in place.

The partner is now used only if its dictionary rejects a non-word
("qzxjvkq"), checked once per language on first use (so keyboard open does
no extra work). Otherwise English types alone, as before Polish was chosen.
A partner whose dictionary works is unchanged.

Verified on a fresh iPhone 17 Pro simulator (iOS 27.2), typing "teh " in
Messages: origin/dev with English + Spanish -> "The ", English + Ukrainian ->
"The "; this branch before the fix with English + Polish -> "Teh ", English
alone -> "The "; after the fix English + Polish -> "The ", English alone ->
"The ". AutocorrectEngineTests covers a partner that accepts everything
("teh" and "tge" fixed, "jest" -> "just") and a working one ("jest" kept).
The full HEXMobile suite passes (435 tests).
This commit is contained in:
Ryan Vogel
2026-11-21 04:43:47 +00:00
committed by GitHub
parent cc3074bd5c
commit d65f5f76f0
9 changed files with 288 additions and 16 deletions
+14 -2
View File
@@ -5,7 +5,7 @@ import UIKit
/// `--snap-state full-keyboard-<state>[-dark|-dark-field]` is passed on Simulator.
/// `-dark` is a dark app; `-dark-field` is a light app whose field asks for a dark keyboard.
/// The layout follows `--dictation-language` (Automatic, English, without it), or
/// `--keyboard-layout nb|es|de|it|fr|fr-CA|fr-CH|pt|ru|uk|sr-Latn|en` pins it; drafts are in the layout's language.
/// `--keyboard-layout nb|es|de|it|fr|fr-CA|fr-CH|pt|pl|ru|uk|sr-Latn|en` pins it; drafts are in the layout's language.
/// `--accent-key ø` (or Cyrillic `е`, `ь`, `ʼ`) picks the key the `accents` state holds; `--emoji-query kiss` what `emoji-search` types.
/// Emoji states (`emoji`, `emoji-search`, `emoji-tones`, `emoji-food`, `emoji-strip`) turn
/// Settings › Keyboard › Emoji on with a seeded history; `emoji-probe` prints the panel's
@@ -118,6 +118,15 @@ struct FullKeyboardSnapshotStage: View {
case "accents": "Caf"
default: "Vou chegar dez minutos atrasado, "
}
case .polish:
return switch state {
case "inserted": "Spóźnię się dziesięć minut, będę w domu o 19:30. Zacznijcie beze mnie."
case "numbers": "Spóźnię się dziesięć minut, będę w domu o 19:3"
case "shift": "Spóźnię się dziesięć minut. "
case "typing": "Spóźnię się dziesięć min"
case "accents": Self.accentKey == "e" ? "Prosz" : "Za"
default: "Spóźnię się dziesięć minut, "
}
case .russian:
return switch state {
case "inserted": "Опаздываю на десять минут, буду дома в 19:30. Начинайте без меня."
@@ -281,7 +290,10 @@ private struct FullKeyboardFixture: UIViewRepresentable {
case "accents":
let key = FullKeyboardSnapshotStage.accentKey
let serbian = FullKeyboardSnapshotStage.layout == .serbianLatin
let pick = [
let polish: [String: String] = FullKeyboardSnapshotStage.layout == .polish
? ["e": "ę", "a": "ą", "c": "ć", "l": "ł", "n": "ń", "o": "ó", "s": "ś", "z": "ż"]
: [:]
let pick = polish[key] ?? [
"e": "é", "s": serbian ? "š" : "ß", "ø": "ö", "æ": "ä", "a": "á", "o": "ó", "n": "ñ", "u": "ú",
"i": "ì", "е": "ё", "ь": "ъ", "c": "ć", "ʼ": "’",
][key]
@@ -281,6 +281,37 @@ final class AutocorrectEngineTests: XCTestCase {
XCTAssertEqual(target.text, "Привіт як справи мʼясо їжак єнот ґанок дякую сімʼя на і ")
}
/// Polish types with iOS's pl dictionary, and missing diacritics are the cheapest fix there
/// is, however many a word lacks ("zolw" -> "żółw", "maly" -> "mały": ł has no
/// decomposition), as a missing Spanish accent is; other languages keep one edit. The
/// iOS 27.2 simulator lists pl_PL but its checker flags no word and offers no Polish
/// guess, so the fixes run against a stub dictionary answering as an iPhone's would.
func testPolishRestoresMissingDiacritics() {
XCTAssertEqual(AutocorrectEngine.singleEditKeyboardCost(from: "maly", to: "mały", language: .polish)!, 0.15, accuracy: 0.001)
XCTAssertEqual(AutocorrectEngine.singleEditKeyboardCost(from: "zolw", to: "żółw", language: .polish)!, 0.25, accuracy: 0.001)
XCTAssertEqual(AutocorrectEngine.singleEditKeyboardCost(from: "dzien", to: "dzień", language: .polish)!, 0.15, accuracy: 0.001)
XCTAssertNil(AutocorrectEngine.singleEditKeyboardCost(from: "zolw", to: "żółw", language: .english), "three edits elsewhere")
XCTAssertNil(AutocorrectEngine.singleEditKeyboardCost(from: "zolw", to: "żółt", language: .polish), "w and t aren't one letter")
engine.language = .polish
XCTAssertEqual(engine.autocorrect.language, .polish)
XCTAssertTrue(engine.autocorrect.hasDictionary)
XCTAssertNil(engine.autocorrect.decoder, "no Polish typing model")
let polish = stubbed {
$0.valid = ["żółw", "mały", "mamy", "dzień", "jest", "dobry"]
// "mamy" is one far key from "maly" and listed first; "mały" only lacks its ł.
$0.guessTable = ["zolw": ["żółw"], "maly": ["mamy", "mały"], "dzien": ["dzień"]]
}
polish.setLanguage(.polish, available: ["pl_PL", "en_US"])
XCTAssertEqual(fix(polish, "zolw"), "żółw")
XCTAssertEqual(fix(polish, "Zolw"), "Żółw")
XCTAssertEqual(fix(polish, "maly"), "mały")
XCTAssertEqual(fix(polish, "dzien"), "dzień")
XCTAssertNil(fix(polish, "jest"), "a word stays")
polish.setLanguage(.spanish, available: ["pl_PL", "es_ES"])
XCTAssertNil(fix(polish, "zolw"), "three diacritics are three edits on another layout")
}
/// Serbian (Latin) has no dictionary on iOS: nothing is "corrected", into English or anything else.
func testSerbianLatinWithoutADictionaryCorrectsNothing() {
engine.language = .serbianLatin
@@ -313,9 +344,10 @@ final class AutocorrectEngineTests: XCTestCase {
/// A deterministic dictionary: `UITextChecker`'s answers vary between iOS versions.
private final class StubChecker: TextChecking {
var valid: Set<String> = []
var acceptsEverything = false
var guessTable: [String: [String]] = [:]
var completionTable: [String: [String]] = [:]
func isWordValid(_ word: String) -> Bool { valid.contains(word.lowercased()) }
func isWordValid(_ word: String) -> Bool { acceptsEverything || valid.contains(word.lowercased()) }
func guesses(for word: String) -> [String] { guessTable[word.lowercased()] ?? [] }
func completions(for prefix: String) -> [String] { completionTable[prefix.lowercased()] ?? [] }
}
@@ -427,6 +459,33 @@ final class AutocorrectEngineTests: XCTestCase {
XCTAssertNil(french.partner)
}
/// A partner whose dictionary takes any letters for a word (the iOS 27.2 simulator's pl_PL
/// has no word data) is left out: English beside it still fixes "teh", where it kept every
/// typo as "a Polish word"; a partner whose dictionary works still keeps its words.
func testAPartnerDictionaryThatTakesEveryWordIsIgnored() {
let available = ["en_US", "pl_PL"]
let english = stubbed {
$0.valid = ["the", "and", "just"]
$0.guessTable = ["tge": ["the"], "jest": ["just"]]
}
english.setLanguage(.english, available: available)
let empty = StubChecker()
empty.acceptsEverything = true
english.setPartner(.polish, available: available, checker: empty)
XCTAssertEqual(english.partner?.language, .polish)
XCTAssertEqual(fix(english, before: "teh"), "the")
XCTAssertEqual(fix(english, before: "tge"), "the")
XCTAssertTrue(strip(english, "tge").contains("the"))
XCTAssertEqual(fix(english, before: "jest"), "just", "no working Polish dictionary to keep it")
english.setPartner(nil, available: available)
let polish = StubChecker()
polish.valid = ["jest", "tak"]
english.setPartner(.polish, available: available, checker: polish)
XCTAssertNil(fix(english, before: "jest"), "a Polish word stays beside a working Polish dictionary")
XCTAssertEqual(fix(english, before: "teh"), "the")
}
/// How often one language's keyboard changes the other's words, against iOS's own
/// dictionaries and English's Spatial autocorrect model: common French words typed on the
/// English keyboard and common English words on the French one (taps where the layout has
@@ -1437,6 +1437,28 @@ final class SpeechLanguagePickerTests: XCTestCase {
XCTAssertEqual(SpeechLanguagePicker.shortNames(for: ["uk-UA"], in: Locale(identifier: "en-US"))["uk-UA"], "Ukrainian")
}
/// Polish is `DictationTranscriber`'s only (macOS 27.2 lists pl-PL there and not in
/// `SpeechTranscriber`): picked by hand or by a Polish iPhone, it dictates in Polish.
func testPolishComesFromDictationTranscriber() async {
let speech = lookup(speechLocales)
let dictation = lookup(dictationLocales + ["pl-PL"])
let chosen = await SpeechLanguagePicker.pick(
explicit: "pl-PL", candidates: ["en-US"], speech: speech, dictation: dictation
)
XCTAssertEqual(chosen?.identifier, "pl-PL")
XCTAssertEqual(chosen?.module, .dictation)
let automatic = await SpeechLanguagePicker.pick(
explicit: nil,
candidates: SpeechLanguagePicker.automaticCandidates(preferred: ["pl-PL", "en-US"], current: "pl_PL"),
speech: speech,
dictation: dictation
)
XCTAssertEqual(automatic?.identifier, "pl-PL")
XCTAssertEqual(automatic?.module, .dictation)
XCTAssertFalse(SpeechLanguagePicker.isEnglish("pl-PL"), "Apple Speech, never English-only Parakeet")
XCTAssertEqual(SpeechLanguagePicker.shortNames(for: ["pl-PL"], in: Locale(identifier: "en-US"))["pl-PL"], "Polish")
}
func testThePreferredOrderWinsOverTheModule() async {
// Hebrew first: DictationTranscriber's Hebrew beats SpeechTranscriber's English.
let picked = await pick(preferred: ["he-IL", "en-US"])
@@ -364,6 +364,66 @@ final class FullKeyboardEngineTests: XCTestCase {
XCTAssertEqual(steps, [1, -1, 1])
}
/// Settings › Keyboard › Languages with English and Polish: the space bar says "Polski",
/// the keys are QWERTY, every Polish letter is on a held key (ą ć ę ł ń ó ś ź ż), and
/// Switch dictation too dictates pl-PL.
func testPolishTypesAndSwitches() {
let settings = LanguageSettings(defaults: defaults)
settings.keyboardLanguages = [.english, .polish]
settings.dictationFollowsKeyboard = true
settings.supportedDictationLanguages = ["en-US", "pl-PL"]
let model = KeyboardViewModel()
var picked: [String?] = []
model.onLanguageSelected = { picked.append($0) }
let field = FixtureTextTarget()
field.autocapitalizationType = UITextAutocapitalizationType.none
let view = FullKeyboardView(model: model, target: field)
view.languageSettings = settings
view.frame = CGRect(x: 0, y: 0, width: 402, height: 262)
view.layoutIfNeeded()
view.switchLanguage(by: 1)
XCTAssertEqual(view.engine.language, .polish)
XCTAssertEqual(view.plane.spaceLabel, "Polski")
XCTAssertNil(view.engine.autocorrect.decoder, "no Polish typing model: the dictionary engine")
XCTAssertEqual(picked, ["pl-PL"])
var id = 400
func press(_ character: String) {
let key = view.engine.layout.key(.character(character))!
let centre = CGPoint(x: key.frame.midX, y: key.frame.midY)
id += 1
view.engine.touchBegan(id: id, at: centre)
view.engine.touchEnded(id: id, at: centre)
}
func hold(_ character: String, pick: String) {
let key = view.engine.layout.key(.character(character))!
id += 1
view.engine.touchBegan(id: id, at: CGPoint(x: key.frame.midX, y: key.frame.midY))
XCTAssertTrue(view.engine.openAccentMenuIfEligible(forTouch: id), character)
guard let menu = view.engine.activeAccentMenu, let index = menu.options.firstIndex(of: pick) else {
return XCTFail("\(character): no \(pick)")
}
let cell = menu.cellFrames[index]
view.engine.touchMoved(id: id, to: CGPoint(x: cell.midX, y: cell.midY))
view.engine.touchEnded(id: id, at: CGPoint(x: cell.midX, y: cell.midY))
}
press("z")
press("a")
for (key, letter) in [("z", "ż"), ("o", "ó"), ("l", "ł"), ("c", "ć"), ("e", "ę"), ("s", "ś"), ("a", "ą"), ("n", "ń"), ("z", "ź")] {
hold(key, pick: letter)
}
XCTAssertEqual(field.text, "zażółćęśąńź")
for letter in ["u", "i", "y"] {
let key = view.engine.layout.key(.character(letter))!
id += 1
view.engine.touchBegan(id: id, at: CGPoint(x: key.frame.midX, y: key.frame.midY))
XCTAssertFalse(view.engine.openAccentMenuIfEligible(forTouch: id), "\(letter) has no long-press options")
view.engine.touchEnded(id: id, at: CGPoint(x: key.frame.midX, y: key.frame.midY))
}
view.switchLanguage(by: 1)
XCTAssertEqual(view.engine.language, .english)
XCTAssertEqual(view.plane.spaceLabel, "English")
}
/// Settings › Keyboard › Languages with English and Ukrainian: the space bar says
/// "Українська", the keys are the twelve-key ЙЦУКЕН, ʼ types the apostrophe Ukrainian
/// spells with and a held ʼ the other apostrophes, ґ and ї have keys of their own, and
@@ -630,7 +690,7 @@ final class FullKeyboardEngineTests: XCTestCase {
XCTAssertNil(view.engine.autocorrect.decoder)
// Nor do Russian, Serbian (Latin) and French; nor do English's or Spanish's
// next-letter odds move French targets (AZERTY's letters aren't theirs).
for language in [KeyboardLanguage.russian, .ukrainian, .serbianLatin, .french, .frenchCanadian, .frenchSwiss] {
for language in [KeyboardLanguage.russian, .ukrainian, .polish, .serbianLatin, .french, .frenchCanadian, .frenchSwiss] {
view.languageOverride = language
XCTAssertEqual(view.engine.autocorrect.language, language)
XCTAssertNil(view.engine.autocorrect.decoder, "\(language)")
+36 -2
View File
@@ -436,6 +436,7 @@ final class KeyboardLayoutTests: XCTestCase {
.frenchCanadian: ["qwertyuiop", "asdfghjkl", "zxcvbnm"],
.frenchSwiss: ["qwertzuiop", "asdfghjkl", "yxcvbnm"],
.portuguese: ["qwertyuiop", "asdfghjkl", "zxcvbnm"],
.polish: ["qwertyuiop", "asdfghjkl", "zxcvbnm"],
.russian: ["йцукенгшщзх", "фывапролджэ", "ячсмитьбю"],
.ukrainian: ["йцукенгшщзхї", "фівапролджєʼ", "ячсмитьбюґ"],
.serbianLatin: ["qwertzuiop", "asdfghjkl", "yxcvbnm"],
@@ -710,6 +711,21 @@ final class KeyboardLayoutTests: XCTestCase {
XCTAssertNil(AccentCatalog.options(for: "1", uppercase: false))
XCTAssertEqual(AccentCatalog.options(for: "\"", uppercase: false, language: .german)?.dropFirst().first, "„")
XCTAssertEqual(AccentCatalog.options(for: ".", uppercase: false, language: .french), [".", "…", "·"])
// Polish: its own letter right after the base, nothing on U, I or Y; its currency key
// is € (no zł), held on Hex's #+= €, while Hex's 123 page keeps English's $.
let polish = ["a": "ą", "c": "ć", "e": "ę", "l": "ł", "n": "ń", "o": "ó", "s": "ś", "z": "ż"]
for (letter, own) in polish {
XCTAssertEqual(AccentCatalog.options(for: letter, uppercase: false, language: .polish)?.prefix(2), [letter, own][...], letter)
}
XCTAssertEqual(AccentCatalog.options(for: "z", uppercase: true, language: .polish), ["Z", "Ż", "Ź", "Ž"])
XCTAssertEqual(AccentCatalog.options(for: "l", uppercase: true, language: .polish), ["L", "Ł"])
XCTAssertEqual(shownHolds("o", .polish), ["ō", "ø", "œ", "õ", "ò", "ö", "ô", "ó"])
for letter in KeyboardLanguage.polish.letterRows.joined() where polish[letter] == nil {
XCTAssertNil(AccentCatalog.options(for: letter, uppercase: false, language: .polish), letter)
}
XCTAssertEqual(AccentCatalog.options(for: "€", uppercase: false, language: .polish), ["€", "$", "£", "¥", "₩", "₽"])
XCTAssertEqual(AccentCatalog.options(for: "$", uppercase: false, language: .polish), AccentCatalog.options(for: "$", uppercase: false))
XCTAssertEqual(AccentCatalog.options(for: "\"", uppercase: false, language: .polish), AccentCatalog.options(for: "\"", uppercase: false))
}
func testAccentMenusOnTheNewKeysStayInside() {
@@ -720,6 +736,7 @@ final class KeyboardLayoutTests: XCTestCase {
.russian: ["й", "е", "х", "ж", "э", "ь", "ю", "я"],
.ukrainian: ["й", "ї", "є", "ʼ", "ґ"],
.serbianLatin: ["c", "d", "s", "z"],
.polish: ["a", "c", "e", "l", "n", "o", "s", "z"],
]
for width in portraitWidths {
for (language, characters) in keys {
@@ -771,6 +788,10 @@ final class KeyboardLayoutTests: XCTestCase {
XCTAssertEqual(automatic("uk_UA"), .ukrainian)
XCTAssertEqual(automatic(nil, modes: ["emoji", "uk-UA", "en-US"], preferred: ["ru-RU"]), .ukrainian)
XCTAssertEqual(automatic(nil, preferred: ["uk-UA", "en-US"]), .ukrainian)
XCTAssertEqual(automatic("pl-PL", modes: ["en-US"]), .polish)
XCTAssertEqual(automatic("pl_PL"), .polish)
XCTAssertEqual(automatic(nil, modes: ["emoji", "pl_PL", "en-US"]), .polish)
XCTAssertEqual(automatic(nil, preferred: ["pl-PL", "en-US"]), .polish)
// Before Hex knows the dictation language: the first keyboard, then language, with a layout.
XCTAssertEqual(automatic(nil, modes: ["emoji", "nb-NO", "en-US"]), .norwegian)
XCTAssertEqual(automatic(nil, preferred: ["nn-NO"]), .norwegian)
@@ -814,8 +835,8 @@ final class KeyboardLayoutTests: XCTestCase {
/// between two French layouts (one dictionary).
func testBilingualAutocorrectPairsTwoLatinLanguagesWithDictionaries() {
let available = ["en_US", "fr_FR", "fr_CA", "ru_RU", "de_DE"]
func partner(_ chosen: [KeyboardLanguage], _ current: KeyboardLanguage) -> KeyboardLanguage? {
KeyboardLanguageList.resolve(chosen: chosen, stored: current, automatic: .english).partner(available: available)
func partner(_ chosen: [KeyboardLanguage], _ current: KeyboardLanguage, _ dictionaries: [String]? = nil) -> KeyboardLanguage? {
KeyboardLanguageList.resolve(chosen: chosen, stored: current, automatic: .english).partner(available: dictionaries ?? available)
}
XCTAssertEqual(partner([.english, .french, .russian], .french), .english)
XCTAssertEqual(partner([.english, .french, .russian], .english), .french)
@@ -826,6 +847,9 @@ final class KeyboardLayoutTests: XCTestCase {
XCTAssertNil(partner([.english, .serbianLatin], .english))
XCTAssertNil(partner([.ukrainian, .english], .ukrainian), "Cyrillic has no bilingual partner")
XCTAssertNil(partner([.english, .ukrainian], .english))
XCTAssertEqual(partner([.polish, .english], .polish, ["en_US", "pl"]), .english, "Polish has Latin letters")
XCTAssertEqual(partner([.english, .polish], .english, ["en_US", "pl"]), .polish)
XCTAssertNil(partner([.polish, .english], .polish), "no Polish dictionary on this iPhone")
XCTAssertNil(partner([.english], .english))
}
@@ -853,6 +877,13 @@ final class KeyboardLayoutTests: XCTestCase {
XCTAssertEqual(KeyboardLanguage.ukrainian.dictationLanguage(supported: supported + ["uk-UA"], preferred: ["uk-UA"]), "uk-UA")
XCTAssertNil(KeyboardLanguage.ukrainian.dictationLanguage(supported: supported, preferred: []), "not Russian instead")
XCTAssertEqual(KeyboardLanguage.ukrainian.dictationLanguage(supported: [], preferred: []), "uk-UA", "not listed yet")
XCTAssertEqual(
KeyboardLanguage.suggested(inputModes: ["pl_PL", "emoji"], preferred: ["pl-PL", "en-US"]),
[.polish, .english]
)
XCTAssertEqual(KeyboardLanguage.polish.dictationLanguage(supported: supported + ["pl-PL"], preferred: ["pl-PL"]), "pl-PL")
XCTAssertEqual(KeyboardLanguage.polish.dictationLanguage(supported: [], preferred: []), "pl-PL", "not listed yet")
XCTAssertEqual(KeyboardLanguage.polish.displayName, "Polski")
}
/// The languages read the one layout chosen before them, and write their first for an
@@ -888,6 +919,9 @@ final class KeyboardLayoutTests: XCTestCase {
XCTAssertEqual(KeyboardLanguage.russian.spellCheckLanguage(available: ["en_US", "ru_RU"]), "ru_RU")
XCTAssertNil(KeyboardLanguage.russian.spellCheckLanguage(available: ["en_US", "uk_UA"]), "never English")
XCTAssertEqual(KeyboardLanguage.ukrainian.spellCheckLanguage(available: ["en_US", "ru_RU", "uk_UA"]), "uk_UA")
XCTAssertEqual(KeyboardLanguage.polish.spellCheckLanguage(available: ["en_US", "pl"]), "pl")
XCTAssertNil(KeyboardLanguage.polish.spellCheckLanguage(available: ["en_US", "cs"]), "never English or Czech")
XCTAssertEqual(KeyboardLanguage.spellCheckLanguage(forDictation: "pl-PL", available: ["en_US", "pl"]), "pl")
XCTAssertNil(KeyboardLanguage.ukrainian.spellCheckLanguage(available: ["en_US", "ru_RU"]), "never Russian or English")
XCTAssertEqual(KeyboardLanguage.spellCheckLanguage(forDictation: "uk-UA", available: ["en_US", "uk_UA"]), "uk_UA")
XCTAssertEqual(KeyboardLanguage.serbianLatin.spellCheckLanguage(available: ["en_US", "sr_Latn"]), "sr_Latn")
@@ -463,6 +463,27 @@ final class SpokenCleanupRulesTests: XCTestCase {
XCTAssertEqual(pipeline.format("Єнот, Ґанок і Їжак", language: "uk-UA"), "єнот, ґанок і їжак.")
}
/// Polish as `DictationTranscriber` writes it (macOS 27.2, Zosia voice: diacritics kept, no
/// punctuation, numbers as digits): Polished capitalizes and ends it, Casual starts each
/// sentence lowercase, Lowercase lowers Ą Ć Ę Ł Ń Ó Ś Ź Ż, and English's "i" rules never
/// touch Polish "i" ("and").
func testPolishStylesAndLowercase() {
let heard = "dzień dobry spóźnię się 10 min będę w domu o 19:30 zacznijcie beze mnie"
XCTAssertEqual(
TranscriptFormatter.format(heard, style: .polished, language: "pl-PL"),
"Dzień dobry spóźnię się 10 min będę w domu o 19:30 zacznijcie beze mnie."
)
XCTAssertEqual(TranscriptFormatter.format("żółw i jeż. i gęś", style: .polished, language: "pl-PL"), "Żółw i jeż. I gęś.")
XCTAssertEqual(TranscriptFormatter.format("Łabędź i jeż. Ósma.", style: .casual, language: "pl-PL"), "łabędź i jeż. ósma")
XCTAssertEqual(TranscriptFormatter.format("Żółw i jeż.", style: .verbatim, language: "pl-PL"), "Żółw i jeż.")
var pipeline = DictationPipeline(style: .polished, language: "pl-PL", vocabulary: [])
pipeline.lowercase = true
XCTAssertEqual(
pipeline.format("WĄŻ, ĆMA, GĘŚ, ŁÓDŹ, KOŃ, ÓSMY ŚLAD, ŹLE, ŻÓŁW", language: "pl-PL"),
"wąż, ćma, gęś, łódź, koń, ósmy ślad, źle, żółw."
)
}
/// Lowercase comes after the style and the vocabulary's spellings, as desktop's Lowercase
/// step lowercases the final text, custom vocabulary included.
func testLowercaseRunsAfterTheStyleAndVocabulary() {
@@ -213,6 +213,18 @@ final class AutocorrectEngine {
/// typos are fixed in either language and a word of either is never "corrected" into the
/// other, as Apple's "Français et English" keyboard does. Nil with one language.
private(set) var partner: AutocorrectEngine?
/// The partner, unless its dictionary takes any letters for a word: iOS can list a
/// language whose word data isn't there (the iOS 27.2 simulator's `pl_PL`), and such a
/// partner would keep every typo as "a word in the other language". Checked once per
/// language, on first use.
private var workingPartner: AutocorrectEngine? {
guard let partner else { return nil }
if partner.acceptsAnyLetters == nil {
partner.acceptsAnyLetters = partner.checker.isWordValid("qzxjvkq")
}
return partner.acceptsAnyLetters == true ? nil : partner
}
private var acceptsAnyLetters: Bool?
/// The keys you type on, whose neighbours price a slip: `language`'s layout, or a
/// partner's primary's.
private(set) var layoutLanguage: KeyboardLanguage = .english
@@ -327,6 +339,7 @@ final class AutocorrectEngine {
func setLanguage(_ language: KeyboardLanguage, available: [String] = UITextChecker.availableLanguages) {
self.language = language
layoutLanguage = language
acceptsAnyLetters = nil
if partner?.language == language {
partner = nil
} else {
@@ -445,6 +458,7 @@ final class AutocorrectEngine {
case .french, .frenchCanadian, .frenchSwiss: ["je", "le", "la"]
case .italian: ["io", "il", "la"]
case .portuguese: ["eu", "o", "a"]
case .polish: ["ja", "to", "nie"]
case .norwegian: ["jeg", "det", "vi"]
case .russian: ["я", "это", "мы"]
case .ukrainian: ["я", "це", "ми"]
@@ -464,6 +478,7 @@ final class AutocorrectEngine {
case .french, .frenchCanadian, .frenchSwiss: ["et", "mais", "je"]
case .italian: ["e", "ma", "che"]
case .portuguese: ["e", "mas", "que"]
case .polish: ["a", "ale", "że"]
case .norwegian: ["og", "men", "jeg"]
case .russian: ["и", "но", "что"]
case .ukrainian: ["і", "але", "що"]
@@ -480,6 +495,7 @@ final class AutocorrectEngine {
case .french, .frenchCanadian, .frenchSwiss: ["de", "la", "et", "le", "je", "à"]
case .italian: ["di", "e", "che", "la", "il", "a"]
case .portuguese: ["de", "que", "e", "o", "a", "do"]
case .polish: ["nie", "i", "w", "się", "na", "to"]
case .norwegian: ["og", "i", "det", "er", "på", "som"]
case .russian: ["и", "в", "не", "на", "я", "что"]
case .ukrainian: ["і", "в", "не", "на", "що", "я"]
@@ -548,7 +564,7 @@ final class AutocorrectEngine {
let autoFix = allowAuto ? cautiousReplacement(for: token) : nil
var pool: [String] = autoFix.map { [$0] } ?? []
if let partner {
if let partner = workingPartner {
// Both languages' candidates, those of the language the words before are in
// first; spelling guesses only for a word neither knows.
let mine = candidates(for: token, autoFix: autoFix, guesses: !partner.knowsAsTyped(token), limit: 2, model: predictionModel)
@@ -702,7 +718,7 @@ final class AutocorrectEngine {
/// fix in the language of the words before it, else the cheaper slip on these keys, else
/// the keyboard's own language's.
private func cautiousReplacement(for token: String) -> String? {
guard let partner else { return ownReplacement(for: token) }
guard let partner = workingPartner else { return ownReplacement(for: token) }
if let shortcut = lexiconShortcuts[token.lowercased()] {
return shortcut
}
@@ -1016,6 +1032,14 @@ final class AutocorrectEngine {
if source == target { return 0 }
let s = Array(source)
let t = Array(target)
// Polish: diacritics you didn't add, however many ("zolw" -> "żółw", "maly" -> "mały"),
// are as cheap as one missing Spanish accent, a little more for each further one.
if language == .polish, s.count == t.count {
let missed = zip(s, t).filter { $0 != $1 }
if !missed.isEmpty, missed.allSatisfy({ samePolishLetterIgnoringDiacritics($0, $1) }) {
return 0.15 + 0.05 * Double(missed.count - 1)
}
}
let ds = s.count - t.count
guard abs(ds) <= 1 else { return nil }
@@ -1069,6 +1093,12 @@ final class AutocorrectEngine {
return base(a) == base(b)
}
/// Whether two lowercase letters are one Polish letter with or without its diacritic (a/ą,
/// z/ż, l/ł: ł has no decomposition, so it is named).
static func samePolishLetterIgnoringDiacritics(_ a: Character, _ b: Character) -> Bool {
sameLetterIgnoringAccents(a, b) || Set([a, b]) == ["l", "ł"]
}
private static let keyCoordinates: [KeyboardLanguage: [Character: (Double, Double)]] = Dictionary(
uniqueKeysWithValues: KeyboardLanguage.allCases.map { ($0, $0.keyCoordinates) }
)
@@ -10,7 +10,8 @@ import Foundation
/// held ь); Ukrainian is the standard Ukrainian ЙЦУКЕН (ДСТУ 4862:2007) in the twelve-key
/// rows the iPhone's own Ukrainian keyboard shows (ї, є, ʼ and ґ on keys of their own, the
/// other apostrophes on a held ʼ, and no ы, э, ъ or ё); Serbian (Latin) is Apple's QWERTZ option for it, which on iPhone has no keys of
/// its own for č ć đ š ž: they are held on c, d, s and z, as on Apple's.
/// its own for č ć đ š ž: they are held on c, d, s and z, as on Apple's. Polish types on the
/// English letters (the standard Polish layout is QWERTY) with ą ć ę ł ń ó ś ź ż on held keys.
nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable {
case english = "en"
case norwegian = "nb"
@@ -21,6 +22,7 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable {
case frenchCanadian = "fr-CA"
case frenchSwiss = "fr-CH"
case portuguese = "pt"
case polish = "pl"
case russian = "ru"
case ukrainian = "uk"
case serbianLatin = "sr-Latn"
@@ -37,6 +39,7 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable {
case .frenchCanadian: "Français (Canada)"
case .frenchSwiss: "Français (Suisse)"
case .portuguese: "Português"
case .polish: "Polski"
case .russian: "Русский"
case .ukrainian: "Українська"
case .serbianLatin: "Srpski"
@@ -80,6 +83,7 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable {
case .frenchCanadian: "fr-CA"
case .frenchSwiss: "fr-CH"
case .portuguese: "pt-BR"
case .polish: "pl-PL"
case .russian: "ru-RU"
case .ukrainian: "uk-UA"
case .serbianLatin: "sr-Latn-RS"
@@ -103,7 +107,7 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable {
/// German and Russian layouts) or 12 (Ukrainian); row 3 sits between shift and delete.
var letterRows: [[String]] {
let rows = switch self {
case .english, .italian, .frenchCanadian, .portuguese: ["qwertyuiop", "asdfghjkl", "zxcvbnm"]
case .english, .italian, .frenchCanadian, .portuguese, .polish: ["qwertyuiop", "asdfghjkl", "zxcvbnm"]
// Apple's French keyboards also hold a ´ dead key (AZERTY's row 3, the end of the
// others' row 2), which its French and English keyboard leaves out (a TestFlight
// tester's screenshot). Hex leaves it out too: accents are on a held letter.
@@ -229,6 +233,19 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable {
"c": ["c", "ç"],
"n": ["n", "ñ"],
]
case .polish:
// Polish's own letter right after the base (ą ć ę ł ń ó ś ż, then ź on Z); U, I and
// Y hold nothing.
[
"e": ["e", "ę", "è", "é", "ê", "ë", "ė", "ē"],
"o": ["o", "ó", "ô", "ö", "ò", "õ", "œ", "ø", "ō"],
"a": ["a", "ą", "à", "á", "â", "ä", "æ", "ã", "å", "ā"],
"s": ["s", "ś", "ß", "š"],
"l": ["l", "ł"],
"z": ["z", "ż", "ź", "ž"],
"c": ["c", "ć", "ç", "č"],
"n": ["n", "ń", "ñ"],
]
case .russian:
[
"й": ["й", "ї", "ј", "ѵ"],
@@ -319,6 +336,11 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable {
"8": ["8", "8ª", "8º"],
"9": ["9", "9º", "9ª"],
]
case .polish:
// Its currency key is € (no zł), held for € $ £ ¥ ₩ ₽; Hex's 123 page keeps $.
[
"€": ["€", "$", "£", "¥", "₩", "₽"],
]
case .russian:
[
"#": ["#", "№"],
@@ -344,6 +366,7 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable {
case .frenchSwiss: ["fr_CH", "fr", "fr_FR"]
// Brazil's spelling first, Portugal's where only it is installed.
case .portuguese: ["pt_BR", "pt", "pt_PT"]
case .polish: ["pl", "pl_PL"]
case .russian: ["ru", "ru_RU"]
case .ukrainian: ["uk", "uk_UA"]
// Latin only: a Cyrillic `sr` dictionary would reject every Latin word.
@@ -386,8 +409,8 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable {
case .italian:
["di", "il", "la", "in", "un", "si", "le", "lo", "ha", "ho", "ma", "da", "mi", "ci",
"ti", "se", "ne", "no", "io", "tu", "su", "al"]
case .norwegian, .german, .french, .frenchCanadian, .frenchSwiss, .portuguese, .russian,
.ukrainian, .serbianLatin:
case .norwegian, .german, .french, .frenchCanadian, .frenchSwiss, .portuguese, .polish,
.russian, .ukrainian, .serbianLatin:
[]
}
}
@@ -432,6 +455,7 @@ nonisolated enum KeyboardLanguage: String, CaseIterable, Sendable {
if region.contains("ch") { return .frenchSwiss }
return .french
case "pt": return .portuguese
case "pl": return .polish
case "ru": return .russian
case "uk": return .ukrainian
case "sr": return parts.contains("latn") ? .serbianLatin : nil
+14 -4
View File
@@ -304,7 +304,7 @@ doesn't use, and `SpeechAnalyzer` runs without it in the app and the keyboard al
including a name, day or place typed in lowercase that the dictionary knows only
capitalised, which is capitalised as the dictionary path does: "mary" -> "Mary").
Shortcuts, learned fixes, contractions, and words you kept still come first. Other
layouts (Norsk, Deutsch, Italiano, Français, Português, Русский, Українська) keep the dictionary
layouts (Norsk, Deutsch, Italiano, Français, Português, Polski, Русский, Українська) keep the dictionary
engine in their own language, and Srpski (no iOS dictionary) none, never the English
model, except as bilingual autocorrect's second language (below). The
models (`HEXKeyboard/TypingModel/en.hextm` and `es.hextm`, about 3.6 MB each) are
@@ -550,7 +550,11 @@ doesn't use, and `SpeechAnalyzer` runs without it in the app and the keyboard al
`йцукенгшщзхї`, `фівапролджєʼ`, `ячсмитьбюґ`, with ʼ the U+02BC apostrophe Ukrainian
spells with; as the system keyboard's long-press options were observed, only ʼ offers
anything, the other apostrophes (' ’ ‘ and the backtick), and ₴, which the system keyboard
offers on its held currency key, is held on $; no ы, э, ъ or ё) and Srpski (Latin: Apple's QWERTZ option for it; Apple's iPhone
offers on its held currency key, is held on $; no ы, э, ъ or ё), Polski (QWERTY, as the
standard Polish layout is, on the English letters; it matches the system keyboard's
observed long-press options: Polish's own letter right after the base on A, C, E, L, N, O,
S and Z, so ą ć ę ł ń ó ś ż, with ź after ż, and nothing on U, I or Y; its currency key
is €, held for € $ £ ¥ ₩ ₽ and no zł, which Hex holds on the #+= page's €) and Srpski (Latin: Apple's QWERTZ option for it; Apple's iPhone
Serbian Latin keyboard has no keys of its own for č ć đ š ž, they are held on c, d, s
and z), as Apple's iOS keyboards
lay them out (`KeyboardLanguage`: letter rows, long-press accents, spelling dictionary).
@@ -573,13 +577,16 @@ doesn't use, and `SpeechAnalyzer` runs without it in the app and the keyboard al
letter at the end under the thumb, in one row where the system wraps a long list
(English A) into two. Autocorrect and suggestions use the layout's
`UITextChecker` dictionary (`nb`, `es`, `de`, `it`, `fr`, `pt_BR` then
`pt_PT`, `ru`, `uk`; Serbian would use `sr_Latn`, which iOS 27.2 doesn't have, nor a
`pt_PT`, `pl`, `ru`, `uk`; Serbian would use `sr_Latn`, which iOS 27.2 doesn't have, nor a
Croatian one); where the iPhone has none
they stay off except your own text replacements, and the English contractions
and typo list (`i` → `I`) apply only to English. Neighbouring-key costs follow
the layout (on QWERTZ, Z sits beside T), and an accent or tilde you left out
is the cheapest fix of all ("aqui" → "aquí", "manana" → "mañana"; a word the
dictionary knows, such as "esta", is never changed). A two-letter non-word one
dictionary knows, such as "esta", is never changed); in Polish every missing
diacritic in a word counts as one such fix ("zolw" → "żółw", "maly" → "mały"). The
iOS 27.2 simulator lists `pl_PL` but its checker flags no word, so Polish fixes are
checked against a stub dictionary there. A two-letter non-word one
neighbouring key (or one swap) from a very common two-letter word is fixed too
("tk" → "to", Spanish "nl" → "no"; `KeyboardLanguage.commonTwoLetterWords`, English,
Spanish and Italian only). Auto-capitalization is unchanged.
@@ -800,6 +807,9 @@ from `ci_scripts/ci_post_clone.sh`. A new model gets a new release tag and hash.
Ukrainian is `DictationTranscriber`'s only (macOS 27.2 lists `uk-UA` there and
not for `SpeechTranscriber`): a `say -v Lesya` clip came back word for word in
Cyrillic, without punctuation, after an 18 s model download.
Polish is too (macOS 27.2.1 lists `pl-PL` for `DictationTranscriber` only):
`say -v Zosia` clips came back with every diacritic (ą ć ę ł ń ó ś ź ż), numbers as
digits ("10 min", "19:30"), and no punctuation.
Unverified on a physical iPhone.
- **Speech model fallback:** `SpeechModelInstallTests` and `StallWatchTests` run
the fallback, set-aside, offline, stall and keyboard-handoff rules against fakes